"""ExtImage product module."""
###############################################################################
#
# Copyright (c) 2001 Gregor Heine <mac.gregor@gmx.de>. All rights reserved.
# ExtFile Home: http://www.zope.org/Members/MacGregor/ExtFile/index_html
#
# 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.
# 3. The name of the author may not be used to endorse or promote products
#    derived from this software without specific prior written permission
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
#   
#  In accordance with the license provided for by the software upon
#  which some of the source code has been derived or used, the following
#  acknowledgement is hereby provided :
#
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
#
###############################################################################

__doc__ = """ExtImage product module.
    The ExtImage-Product works like the Zope Image-product, but stores the 
    uploaded image externally in a repository-direcory. It creates a preview
    of the image (requires PIL).

$Id: ExtImage.py 5740 2006-01-22 11:38:09Z roug $"""

__version__='$Release: 1.1.3 $'[10:-2]

import Globals
from __main__ import *
#import Zope
from ExtFile import *
from Globals import InitializeClass, DTMLFile
from DateTime import DateTime
from types import IntType, StringType
import urllib, os, string
from os.path import join, isfile
try: from cStringIO import StringIO
except: from StringIO import StringIO

NO_PREVIEW = 0
GENERATE = 1
UPLOAD_NORESIZE = 2
UPLOAD_RESIZE = 3

manage_addExtImageForm = DTMLFile('extImageAdd', globals()) 

def manage_addExtImage(self, id='', title='', descr='', file='', preview='', 
                       content_type='', create_prev=0, maxx='', maxy='', 
                       ratio=0, permission_check=0, REQUEST=None):
    """ Add a ExtImage to a folder """
    if not id and hasattr(file,'filename'): 
        # generate id from filename and make sure, it has no 'bad' chars
        id = file.filename
        title = title or id
        id = id[max(string.rfind(id,'/'), 
                    string.rfind(id,'\\'), 
                    string.rfind(id,':')
                   )+1:]
        id = string.translate(id, TRANSMAP)
    self = self.this()
    tempExtImage = ExtImage(id, title, descr, permission_check)
    self._setObject(id, tempExtImage)
    self._getOb(id).manage_file_upload(file, content_type, 0, create_prev, 
                                       maxx, maxy, ratio)
    if create_prev==UPLOAD_NORESIZE or create_prev==UPLOAD_RESIZE:
        self._getOb(id).manage_file_upload(preview, content_type, 1, 
                                           create_prev, maxx, maxy, ratio)
    if REQUEST is not None:
        message = 'The ExtImage %s was successfully created!' % id
        return self.manage_main(self,REQUEST,manage_tabs_message=message)

class ExtImage(ExtFile): 
    
    security = ClassSecurityInfo()
    security.declareProtected('View management screens', 'manage_tabs')
    security.declareProtected('View management screens', 'manage_main')
    security.declareProtected('View management screens', 'manage_uploadForm')
    security.declareProtected('Change permissions', 'manage_access')
    security.declareProtected('Change ExtFile/ExtImage', 'manage_editExtFile')
    security.declareProtected('FTP access', 'manage_FTPstat')
    security.declareProtected('FTP access', 'manage_FTPget')
    security.declareProtected('FTP access', 'manage_FTPlist')
    security.declareProtected('View', 'index_html')
    security.declareProtected('View', 'icon_html')
    security.declareProtected('View', 'icon_gif')
    security.declareProtected('View', 'link')
    # what permissions make sense for us? 
    
    # what do people think they're adding? 
    meta_type = 'ExtImage'
    
    # default,min,max-sizes for the preview image
    _image_size={'default':256,'min':10,'max':999} 
    
    ################################
    # Init method                  #
    ################################
    
    def __init__(self, id, title='', descr='', permission_check=0): 
        """initialize a new instance of ExtImage"""
        ExtImage.inheritedAttribute("__init__")(self, id, title, 
                                                descr, permission_check)
        # determine the int-values of the size of preview-image
        self.prev_filename = []
        self.prev_content_type = ''
        self.has_preview = 0
    
    ################################
    # Public methods               #
    ################################
    
    def __str__(self):
        return self.tag()
    
    security.declareProtected('View', 'tag')
    def tag(self, preview=0, icon=0, height=None, width=None, alt=None, 
        scale=0, xscale=0, yscale=0, border='0', REQUEST=None, **args):
        """ Generate an HTML IMG tag for this image, with customization.
            Arguments to self.tag() can be any valid attributes of an IMG tag.
            'src' will always be an absolute pathname, to prevent redundant
            downloading of images. Defaults are applied intelligently for
            'height', 'width', and 'alt'. If specified, the 'scale', 'xscale',
            and 'yscale' keyword arguments will be used to automatically adjust
            the output height and width values of the image tag.
            Adopted and adapted from OFS/image.py
        """
        if REQUEST is None and hasattr(self,'REQUEST'): 
            REQUEST = self.REQUEST
        if not self._access_permitted(REQUEST): preview = 1
        if preview or not self.is_webviewable(): 
            url = '%s?preview=1' % self.absolute_url()
            img_width, img_height = self._getImageSize(self.prev_filename)
        elif icon:
            url = '%s?icon=1' % self.absolute_url()
            img_width, img_height = (32, 32)
        else:
            url = self.absolute_url()
            img_width, img_height = self._getImageSize(self.filename)
        height = height or img_height
        width = width or img_width
        
        # Auto-scaling support
        xdelta = xscale or scale
        ydelta = yscale or scale
        if xdelta and width != None:
            width = str(int(width) * xdelta)
        if ydelta and height != None:
            height = str(int(height) * ydelta)
        
        if alt is None: alt = self.title_or_id()
        strg = '<img src="%s" border="%s" alt="%s"' % \
               (url, border, alt)
        if height: strg = '%s height="%s"' % (strg, height)
        if width: strg = '%s width="%s"' % (strg, width)
        for key in args.keys():
            value = args.get(key)
            strg = '%s %s="%s"' % (strg, key, value)
        strg="%s>" % (strg)
        return strg
    
    security.declareProtected('View', 'preview')
    def preview(self):
        """ return a preview of the image """
        raise 'Redirect', self.absolute_url()+'?preview=1'
    
    security.declareProtected('View', 'preview_html')
    def preview_html(self):
        """ The preview-image embedded in html with a link to the real file """
        return self.tag(preview=1)
    
    security.declareProtected('View', 'is_broken')
    def is_broken(self):
        """ Check if external file exists and return true (1) or false (0) """
        if self.has_preview and self.filename!=self.prev_filename:
            fn = self._get_filename(self.prev_filename)
            if not isfile(fn):
                self._undo()
                if not isfile(fn):
                    return 1
        return ExtImage.inheritedAttribute("is_broken")(self)
    
    security.declareProtected('View', 'is_webviewable')
    def is_webviewable(self):
        """ return 1 for GIF,JPEG and PNG images, otherwise return 0 """
        format = self.format()
        if format=='JPEG' or format=='GIF' or format=='PNG':
            return 1
        else:
            return 0
    
    def prev_rawsize(self):
        """ Returns the size of the preview file """
        fn = self._get_filename(self.prev_filename)
        if not isfile(fn): self._undo()
        if isfile(fn): size = os.stat(fn)[6]
        else: size = 0
        return size
    
    def prev_size(self):
        """ Returns a formatted stringified version of the preview size """
        return self._bytetostring(self.prev_rawsize())
    
    def width(self):
        """ pixel width of the image """
        return self._getImageSize(self.filename)[0]
        
    def height(self):
        """ pixel height of the image """
        return self._getImageSize(self.filename)[1]
        
    def prev_width(self):
        """ pixel width of the preview """
        return self._getImageSize(self.prev_filename)[0]
        
    def prev_height(self):
        """ pixel height of the preview """
        return self._getImageSize(self.prev_filename)[1]
        
    def format(self):
        """ Get the Fileformat of the image """
        try:
            from PIL import Image
            im = Image.open(self._get_filename(self.filename)) 
            return im.format
        except:
            return 'unknown'
    
    ################################
    # Protected management methods #
    ################################
    
    # Management Interface
    manage_main = DTMLFile('extImageEdit', globals())
    
    security.declareProtected('Change ExtFile/ExtImage', 'manage_del_prev')
    def manage_del_prev(self, REQUEST=None):
        """ Delete the Preview Image """
        if self.has_preview and self.filename!=self.prev_filename:
            prev_fn = self._get_filename(self.prev_filename)
            try: os.rename(prev_fn,prev_fn+'.undo')
            except OSError: pass
        self.prev_content_type = ''
        self.has_preview = 0
        if REQUEST is not None:
            return self.manage_main(self, REQUEST)
    
    security.declareProtected('Change ExtFile/ExtImage', 'manage_create_prev')
    def manage_create_prev(self, maxx=0, maxy=0, ratio=0, REQUEST=None):
        """ Create a preview Image """
        maxx, maxy = self._formatDimensions(maxx, maxy)
        if maxx!=0 and maxy!=0:
            prev_filename = self._get_ufn()
            self._createPreview(self.filename, prev_filename, 
                                maxx, maxy, ratio)
        if REQUEST is not None:
            if self.has_preview: 
                return self.manage_main(self, REQUEST)
            elif maxx=='0' and maxy=='0':
                message = "Attention: You must enter a value > 0",
                return self.manage_main(self,REQUEST,manage_tabs_message=message)
            else:
                message = "Warning: An error occurred while generating the preview."
                return self.manage_main(self,REQUEST,manage_tabs_message=message)
                
    # File upload Interface
    manage_uploadForm = DTMLFile('extImageUpload', globals())
    
    security.declareProtected('Change ExtFile/ExtImage', 'manage_file_upload')
    def manage_file_upload(self, file='', content_type='', is_preview=0, 
                           create_prev=NO_PREVIEW, maxx='', maxy='', ratio=0, 
                           REQUEST=None):
        """ Upload file from local directory """
        if is_preview and type(file) is not type(''):
            prev_filename = self._get_ufn()
            self._copy(file, self._get_filename(prev_filename))
            maxx, maxy = self._formatDimensions(maxx, maxy)
            if create_prev==UPLOAD_RESIZE and maxx!=0 and maxy!=0:
                self._createPreview(prev_filename, prev_filename, 
                                    maxx, maxy, ratio)
            else:
                self.prev_filename = prev_filename
                self.prev_content_type = self._get_content_type(file, 
                                              file.read(100), 
                                              self.id, content_type or 
                                              self.prev_content_type)
                self._initPreview()
        else:
            ExtImage.inheritedAttribute("manage_file_upload")(self, file, 
                                                              content_type)
            if create_prev==GENERATE:
                maxx, maxy = self._formatDimensions(maxx, maxy)
                if maxx!=0 and maxy!=0:
                    prev_filename = self._get_ufn()
                    self._createPreview(self.filename, prev_filename, 
                                        maxx, maxy, ratio)
        if REQUEST is not None:
            message = "The file was uploaded successfully!"
            return self.manage_main(self,REQUEST,manage_tabs_message=message)
    
    security.declareProtected('Change ExtFile/ExtImage', 'manage_http_upload')
    def manage_http_upload(self, url, is_preview=0, REQUEST=None):
        """ Upload file from http-server """
        if (is_preview):
            url = urllib.quote(url,'/:')
            prev_filename = self._get_ufn()
            cant_read_exc = "Can't open: "
            try: fp_in = urllib.urlopen(url)
            except: raise cant_read_exc, url
            self._copy(fp_in, self._get_filename(prev_filename))
            self.prev_filename = prev_filename
            self.prev_content_type = self._get_content_type(fp_temp, 
                                     fp_temp.read(100), self.id, 
                                     self.prev_content_type)
            self._initPreview()
        else:
            ExtImage.inheritedAttribute("manage_http_upload")(self, url)
            if self.has_preview:
                width, height = self._getImageSize(self.prev_filename)
                prev_filename = self._get_ufn()
                self._createPreview(self.filename, prev_filename, 
                                    width, height, 0)
        if REQUEST is not None:
            message = "The file was uploaded successfully!"
            return self.manage_main(self,REQUEST,manage_tabs_message=message)
    
    def PUT(self, REQUEST, RESPONSE):
        """ Handle HTTP PUT requests """
        RESPONSE = ExtImage.inheritedAttribute("PUT")(self,REQUEST, RESPONSE)
        if self.has_preview:
            width, height = self._getImageSize(self.prev_filename)
            prev_filename = self._get_ufn()
            self._createPreview(self.filename, prev_filename, 
                                width, height, 0)
        return RESPONSE
    
    ################################
    # Private methods              #
    ################################
    
    def _initPreview(self):
        prev_width, prev_height = self._getImageSize(self.prev_filename)
        if prev_width<=0 or prev_height<=0: 
            self.has_preview = 0
        else:
            self.has_preview = 1
            
    def _getImageSize(self, filename):
        try:
            from PIL import Image
            try: 
                im = Image.open(self._get_filename(filename)) 
            except:
                self._undo()
                im = Image.open(self._get_filename(filename)) 
            width = im.size[0]
            height = im.size[1]
        except:
            width = height = 0
        return width, height
    
    def _createPreview(self, from_filename, to_filename, maxx, maxy, ratio):
        """ generate a preview using PIL """
        try:
            from PIL import Image
            im = Image.open(self._get_filename(from_filename)) 
            if im.mode!='RGB' and im.mode!='CMYK': im = im.convert("RGB")
            if ratio==1:             # keep aspect-ratio
                im.thumbnail((maxx,maxy))
            else:                     # distort to fixed size
                im.draft(None,(maxx,maxy))
                im.load()
                im = im.resize((maxx,maxy), Image.BICUBIC)
            im.save(self._get_filename(to_filename),'JPEG', quality = 100)
            self.prev_content_type = 'image/jpeg'
            self.prev_filename = to_filename
        except:
            pass
        self._initPreview()
    
    def _formatDimensions(self, maxx, maxy):
        """ make sure, the dimensions are valid int's """
        if type(maxx) is StringType:
            try: maxx = string.atoi(maxx)
            except: maxx = self._image_size['default']
        if type(maxy) is StringType:
            try: maxy = string.atoi(maxy)
            except: maxy = self._image_size['default']
        if maxx!=0 and maxy!=0:
            if maxx<self._image_size['min']: maxx = self._image_size['min']
            elif maxx>self._image_size['max']: maxx = self._image_size['max']
            if maxy<self._image_size['min']: maxy = self._image_size['min']
            elif maxy>self._image_size['max']: maxy = self._image_size['max']
        return maxx, maxy
    
    def _undo (self):
        """ restore filename after undo or copy-paste """
        if self.has_preview:
            fn = self._get_filename(self.prev_filename)
            if not isfile(fn) and isfile(fn+'.undo'): 
                os.rename(fn+'.undo', fn)            # rename preview
        return ExtImage.inheritedAttribute("_undo")(self)
    
    def _get_ufn(self, filename=None):
        """ If no unique filename has been generated, generate one
            otherwise, return the existing one.
        """
        if filename is not None:
            return ExtImage.inheritedAttribute("_get_ufn") (self, filename)
        new_fn = ''
        if self.filename:
            test_fn = self._get_filename(self.filename) + '.preview'
            if not isfile(test_fn) and not isfile(test_fn+'.undo'):
                new_fn = self.filename[:]
        if not new_fn:
            new_fn = ExtImage.inheritedAttribute("_get_ufn") (self, 
                                                  self.prev_filename)
        if new_fn != self.prev_filename:
            new_fn[-1] = new_fn[-1] + '.preview'
        return new_fn
    
    ################################
    # Special management methods   #
    ################################
    
    def manage_afterClone(self, item):
        """ When a copy of the object is created (zope copy-paste-operation),
            this function is called by CopySupport.py. A copy of the external 
            file is created and self.filename is changed.
        """
        try: 
            self.absolute_url(1)    # this raises an exception, if no context
        except: 
            pass
        else:
            new_fn = self._get_new_ufn()
            new_prev_fn = new_fn[:]
            new_prev_fn[-1] = new_prev_fn[-1] + '.preview'
            # rename preview-file
            if self.has_preview and self.filename!=self.prev_filename:
                old_prev_fn = self._get_filename(self.prev_filename)
                if isfile(old_prev_fn):
                    self._copy(old_prev_fn, self._get_filename(new_prev_fn))
                    self.prev_filename = new_prev_fn
                else:
                    self.prev_filename = []
                    self.has_preview = 0
            elif self.has_preview:
                old_fn = self._get_filename(self.filename)
                if isfile(old_fn) or isfile(old_fn+'.undo'): 
                    self.prev_filename = new_fn
                else:
                    self.prev_filename = []
                    self.has_preview = 0
            else:
                self.prev_filename = []
            return ExtImage.inheritedAttribute("manage_afterClone") \
                   (self, item)
        return ExtImage.inheritedAttribute("manage_afterClone") \
               (self, item)

    def manage_afterAdd(self, item, container):
        """ When a copy of the object is created (zope copy-paste-operation),
            this function is called by CopySupport.py. A copy of the external 
            file is created and self.filename is changed.
        """
        return ExtImage.inheritedAttribute("manage_afterAdd") \
               (self, item, container)
        
    def manage_beforeDelete(self, item, container):
        """ This method is called, when the object is deleted. To support 
            undo-functionality and because this happens too, when the object 
            is moved (cut-paste) or renamed, the external file is not deleted. 
            It are just renamed to filename.undo and remains in the 
            repository, until it is deleted manually.
        """
        if self.has_preview and self.filename!=self.prev_filename:
            prev_fn = self._get_filename(self.prev_filename)
            try:                                
#                if UNDO_POLICY==NO_BACKUPS: os.remove(prev_fn)
#                else: os.rename(prev_fn,prev_fn+'.undo')
                os.rename(prev_fn,prev_fn+'.undo')
            except OSError:
                pass
        return ExtImage.inheritedAttribute("manage_beforeDelete") \
               (self, item, container)

InitializeClass(ExtImage)
