#   Copyright (C) 2002-2003 Yannick Gingras <ygingras@ygingras.net>
#   Copyright (C) 2002-2003 Vincent Barbin <vbarbin@openbeatbox.org>

#   This file is part of Open Beat Box.

#   Open Beat Box 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.

#   Open Beat Box 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 Open Beat Box; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


from qt import *
import os

class ImageLoader:
    """ImageLoader : Load images managing croping and cached version on
                     disk based on timestamps"""
    def __init__(self):
        pass

    def loadPixmap(self, filename):
        if not os.path.exists(filename):
            raise Exception("Image not present on disc")
        
        if self.hasCache(filename):
            return QPixmap(self.makeCacheName(filename))
        else:
            return self.makeCache(filename)

    def cropPixmap(self, pixmap):
        mask = pixmap.createHeuristicMask()
        rect = QRegion(mask).boundingRect()
        # there is a lost pixel somewhere is the createHeuristicMask() call
        if rect.width()+1 >= pixmap.width():
            if rect.height() >= pixmap.height():
                return pixmap
        newPixmap = QPixmap(rect.width(), rect.height())
        bitBlt( newPixmap,
                0,
                0,
                pixmap,
                rect.x(),
                rect.y(),
                rect.width(),
                rect.height(),
                Qt.CopyROP,
                1 )
        return newPixmap

    def makeCacheName(self, filename):
        return filename + ".croped" + os.path.splitext(filename)[1]

    def makeCache(self, filename):
        pixmap = QPixmap(filename)
        cropedPix = self.cropPixmap(pixmap)
        if not cropedPix.save(self.makeCacheName(filename), "PNG"):
            raise Exception("Pixmap cache I/O Error !")
        return cropedPix

    def hasCache(self, filename):
        cacheName = self.makeCacheName(filename)
        if os.path.exists(cacheName):
            cacheMTime = os.path.getmtime(cacheName)
            origMTime = os.path.getmtime(filename)
            if cacheMTime > origMTime:
                # cache should be croped : smaller
                cacheSize = os.path.getsize(cacheName)
                origSize = os.path.getsize(filename)
                if cacheSize < origSize:
                    return 1
                else:
                    raise Exception("Pixmap cache bigger than original !")
        return 0
