Update of /cvsroot/freevo/kaa/mevas/src/imagelib
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv6532/mevas/src/imagelib

Added Files:
        .cvsignore __init__.py base.py directfb_backend.py 
        gdkpixbuf_backend.py imlib2_backend.py pygame_backend.py 
Log Message:
move mevas to kaa.mevas

--- NEW FILE: pygame_backend.py ---
import pygame, types
import base

def get_capabilities():
        return {
                "to-raw-formats": [ "RGBA", "RGB" ],
                "from-raw-formats": [ "RGBA", "RGB" ],
                "preferred-format": "RGBA",  # Native format
                "shmem": False,
                "pickling": True,
                "unicode": True,
                "layer-alpha": True,
                "alpha-mask": False,
                "cache": False 

        }


# TODO: Finish me.


class Image(base.Image):
        def __init__(self, image_or_filename):
                if isinstance(image_or_filename, Image):
                        self._image = image_or_filename._image
                elif type(image_or_filename) == pygame.Surface:
                        self._image = image_or_filename
                elif type(image_or_filename) in types.StringTypes:
                        self._image = pygame.image.load(image_or_filename)
                else:
                        raise ValueError, "Unsupported image type: %s" % 
type(image_or_filename)


        def __getattr__(self, attr):
                if attr == "size":
                        return self._image.get_size()
                elif attr == "width":
                        return self._image.get_width()
                elif attr == "height":
                        return self._image.get_height()
                # FIXME: implement format, mode, filename

                return super(Image, self).__getattr__(attr)

        def get_capabilities(self):
                return get_capabilities()
        


def open(file):
        return Image(file)

def new(size, rawdata = None, from_format = "RGBA"):
        if from_format not in get_capabilities()["from-raw-formats"]:
                raise ValueError, "Unsupported raw format: %s" % from_format
        if rawdata:
                return Image( pygame.image.fromstring(rawdata, size, 
from_format) )
        return Image( pygame.Surface(size) )

def add_font_path(path):
        pass

def load_font(font, size):
        pass

--- NEW FILE: imlib2_backend.py ---
# -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------------
# imlib2_backend.py - Imlib2 backend for mevas imagelib
# -----------------------------------------------------------------------------
# $Id: imlib2_backend.py,v 1.1 2005/06/26 17:02:06 dischi Exp $
#
# -----------------------------------------------------------------------------
# kaa-mevas - MeBox Canvas System
# Copyright (C) 2004-2005 Jason Tackaberry <[EMAIL PROTECTED]>
#
# First Edition: Jason Tackaberry <[EMAIL PROTECTED]>
# Maintainer:    Dirk Meyer <[EMAIL PROTECTED]>
#
# 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 MER-
# CHANTABILITY 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 copy
import types
from kaa import Imlib2
import base

_capabilities =  {
    "to-raw-formats": ["BGRA", "BGR", "ABGR", "RGBA", "RGB", "ARGB", "YV12A"],
    "from-raw-formats": ["BGRA", "ABGR", "RGBA", "ARGB", "BGR", "RGB"],
    "preferred-format": "BGRA",
    "shmem": True,
    "pickling": True,
    "unicode": True,
    "layer-alpha": True,
    "alpha-mask": True,
    "cache": True
    }


class Image(base.Image):
    """
    An Imlib2 based image
    """
    def __init__(self, image_or_filename):
        if isinstance(image_or_filename, Image):
            self._image = image_or_filename._image
        elif isinstance(image_or_filename, Imlib2.Image):
            self._image = image_or_filename
        elif type(image_or_filename) in types.StringTypes:
            self._image = Imlib2.Image(image_or_filename)
        else:
            raise ValueError, "Unsupported image type: %s" % \
                  type(image_or_filename)

    def __getattr__(self, attr):
        if attr in ("width", "height", "size", "format", "mode", "filename",
                    "has_alpha", "rowstride", "get_pixel"):
            return getattr(self._image, attr)
        return super(Image, self).__getattr__(attr)


    def get_raw_data(self, format = "BGRA"):
        return self._image.get_raw_data(format)


    def rotate(self, angle):
        while angle >= 360:
            angle -= 360
        while angle < 0:
            angle += 360
        if angle == 0:
            return
        if angle % 90 == 0:
            f = { 90: 1, 180: 2, 270: 3}[ angle ]
            self._image.orientate(f)
        else:
            self._image = self._image.rotate(angle)


    def flip(self):
        self._image.flip_vertical()


    def mirror(self):
        self._image.flip_horizontal()


    def scale(self, size, src_pos = (0, 0), src_size = (-1, -1)):
        self._image =  self._image.scale(size, src_pos, src_size)


    def blend(self, srcimg, dst_pos = (0, 0), dst_size = (-1, -1),
          src_pos = (0, 0), src_size = (-1, -1),
          alpha = 255, merge_alpha = True):
        return self._image.blend(srcimg._image, src_pos, src_size, dst_pos,
                                 dst_size, alpha, merge_alpha)


    def clear(self, pos = (0, 0), size = (-1, -1)):
        self._image.clear( pos, size )


    def draw_mask(self, maskimg, pos):
        return self._image.draw_mask(maskimg._image, pos)


    def copy(self):
        return Image( self._image.copy() )


    def set_font(self, font_or_fontname):
        if isinstance(font_or_fontname, Font):
            font_or_fontname = font_or_fontname._font
        return self._image.set_font(font_or_fontname._font)


    def get_font(self):
        return Font(self._image.get_font())


    def draw_text(self, pos, text, color = None, font_or_fontname = None):
        if isinstance(font_or_fontname, Font):
            font_or_fontname = font_or_fontname._font
        return self._image.draw_text(pos, text, color, font_or_fontname)


    def draw_rectangle(self, pos, size, color, fill = True):
        return self._image.draw_rectangle(pos, size, color, fill)


    def draw_ellipse(self, center, size, amplitude, fill = True):
        return self._image.draw_ellipse(center, size, amplitude, fill)


    def move_to_shmem(self, format = "BGRA", id = None):
        return self._image.move_to_shmem(format, id)


    def save(self, filename, format = None):
        return self._image.save(filename)


    def get_capabilities(self):
        return _capabilities


    def crop(self, pos, size):
        self._image = self._image.crop(pos, size)


    def scale_preserve_aspect(self, size):
        self._image = self._image.scale_preserve_aspect(size)


    def copy_rect(self, src_pos, size, dst_pos):
        self._image.copy_rect(src_pos, size, dst_pos)




class Font(base.Font):
    def __init__(self, fontdesc, color = (255, 255, 255, 255)):
        self._font = Imlib2.Font(fontdesc, color)


    def get_text_size(self, text):
        return self._font.get_text_size(text)


    def set_color(self, color):
        return self._font.set_color(color)


    def __getattr__(self, attr):
        if attr in ("ascent", "descent", "max_ascent", "max_descent"):
            return getattr(self._font, attr)
        return super(Font, self).__getattr__(attr)



def get_capabilities():
    return _capabilities


def open(file):
    return Image(file)


def new(size, rawdata = None, from_format = "BGRA"):
    if from_format not in _capabilities["from-raw-formats"]:
        raise ValueError, "Unsupported raw format: %s" % from_format
    return Image( Imlib2.new(size, rawdata, from_format) )




def add_font_path(path):
    return Imlib2.add_font_path(path)


def load_font(font, size):
    return Imlib2.load_font(font, size)




def scale(image, size, src_pos = (0, 0), src_size = (-1, -1)):
    image = copy.copy(image)
    image.scale(size, src_pos, src_size)
    return image


def crop(image, pos, size):
    image = copy.copy(image)
    image.crop(pos, size)
    return image


def rotate(image, angle):
    image = image.copy()
    image.rotate(angle)
    return image


def scale_preserve_aspect(image, size):
    image = copy.copy(image)
    image.scale_preserve_aspect(size)
    return image


def thumbnail(src, dst, size):
    return Image( Imlib2.thumbnail(src, dst, size) )


--- NEW FILE: gdkpixbuf_backend.py ---
from gtk import gdk
import pango
import types
import base


def get_capabilities():
        return {
                "to-raw-formats": [ "RGB", "RGBA" ],
                "from-raw-formats": [ "RGB", "RGBA" ],
                "preferred-format": "RGBA",  # Native format
                "shmem": False,
                "pickling": True,
                "unicode": True,
                "layer-alpha": True,
                "alpha-mask": False, # ?
                "cache":  False  # ?

        }


class Image(base.Image):

        def __init__(self, image_or_filename):
                self.filename = None

                if isinstance(image_or_filename, Image):
                        self._image = image_or_filename._image
                        self.filename = image_or_filename.filename
                elif isinstance(image_or_filename, gdk.Pixbuf):
                        self._image = image_or_filename
                elif type(image_or_filename) in types.StringTypes:
                        self._image = 
gdk.pixbuf_new_from_file(image_or_filename)
                        self.filename = image_or_filename
                else:
                        raise ValueError, "Unsupported image type: %s" % 
type(image_or_filename)

        def __getattr__(self, attr):
                if attr == "width":
                        return self._image.get_width()
                elif attr == "height":
                        return self._image.get_height()
                elif attr == "size":
                        return self._image.get_width(), self._image.get_height()
                elif attr == "format":
                        return None
                elif attr == "mode":
                        if self._image.get_has_alpha():
                                return "RGBA"
                        return "RGB"
                return super(Image, self).__getattr__(attr)

        def get_raw_data(self, format = "RGBA"):
                return self._image.get_pixels()
                #return self._image.get_bytes(format)

        def scale(self, size, src_pos = (0, 0), src_size = (-1, -1)):
                pass
                #return Image( self._image.scale(size, src_pos, src_size) )

        def crop(self, pos, size):
                pass
                #return Image( self._image.crop(pos, size) )

        def rotate(self, angle):
                pass
                #return Image( self._image.rotate(angle) )

        def scale_preserve_aspect(self, size):
                pass
                #return Image( self._image.scale_preserve_aspect(size) )

        def copy_rect(self, src_pos, size, dst_pos):
                pass
                #return self._image.copy_rect( src_pos, size, dst_pos )

        def blend(self, srcimg, dst_pos = (0, 0), dst_size = (-1, -1),
                  src_pos = (0, 0), src_size = (-1, -1),
                  alpha = 255, merge_alpha = False):
                pass
                #return self._image.blend(srcimg._image, src_pos, src_size, 
dst_pos, dst_size, alpha, merge_alpha)

        def clear(self, pos = (0, 0), size = (-1, -1)):
                pass
                #self._image.clear( pos, size )

        def draw_mask(self, maskimg, pos):
                pass
                #return self._image.draw_mask(maskimg._image, pos)

        def copy(self):
                pass
                #return Image( self._image.copy() )

        def set_font(self, font_or_fontname):
                pass
                #if isinstance(font_or_fontname, Font):
                #       font_or_fontname = font_or_fontname._font
                #return self._image.set_font(font_or_fontname._font)

        def get_font(self):
                pass
                #return Font(self._image.get_font())
                
        def draw_text(self, pos, text, color = None, font_or_fontname = None):
                pass
                #if isinstance(font_or_fontname, Font):
                #       font_or_fontname = font_or_fontname._font
                #return self._image.draw_text(pos, text, color, 
font_or_fontname)       

        def draw_rectangle(self, pos, size, color, fill = True):
                pass
                #return self._image.draw_rectangle(pos, size, color, fill)

        def draw_ellipse(self, center, size, amplitude, fill = True):
                pass
                #return self._image.draw_ellipse(center, size, amplitude, fill)

        def move_to_shmem(self, format = "BGRA", id = None):
                pass

        def save(self, filename, format = None):
                pass
                #return self._image.save(filename)

        def get_capabilities(self):
                return get_capabilities()


class Font(base.Font):

        def __init__(self, fontdesc, color = (255, 255, 255, 255)):
                pass
                #self._font = Imlib2.Font(fontdesc, color)

        def get_text_size(self, text):
                pass
                #return self._font.get_text_size(text)

        def set_color(self, color):
                pass
                #return self._font.set_color(color)

        def __getattr__(self, attr):
                if attr in ("ascent", "descent", "max_ascent", "max_descent"):
                        return None
                return super(Font, self).__getattr__(attr)


def open(file):
        return Image(file)

def new((w, h), rawdata = None, from_format = "BGRA"):
        if from_format not in get_capabilities()["from-raw-formats"]:
                raise ValueError, "Unsupported raw format: %s" % from_format
        if rawdata:
                has_alpha, bpp = { "RGBA": (True, 4), "RGB": (False, 3) } 
[from_format]
                return Image( gdk.pixbuf_new_from_data(rawdata, 
gdk.COLORSPACE_RGB, 
                                  has_alpha, 8, w, h, w*bpp) )
        else:
                return Image( gdk.Pixbuf(gdk.COLORSPACE_RGB, True, 8, w, h) )

def add_font_path(path):
        pass

def load_font(font, size):
        pass



--- NEW FILE: directfb_backend.py ---
# -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------------
# directfb_backend.py - DirectFB backend for mevas imagelib.
#
# Note: This doesn't work yet don't don't bother trying. :)
#
# TODO: 
#      -improve SurfaceDescription support in pydirectfb (set data)
#      -image transformations
#      -support other raw formats
#      -revise _capabilities
#      -a way to save an image to disk
#      -a bunch of other stuff I forgot
#
# -----------------------------------------------------------------------------
# $Id: directfb_backend.py,v 1.1 2005/06/26 17:02:06 dischi Exp $
#
# -----------------------------------------------------------------------------
# Mevas - MeBox Canvas System
# Copyright (C) 2004-2005 Jason Tackaberry <[EMAIL PROTECTED]>
#
# First Edition: Rob Shortt <[EMAIL PROTECTED]>
# Maintainer:    Rob Shortt <[EMAIL PROTECTED]>
#
# 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 MER-
# CHANTABILITY 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
#
# -----------------------------------------------------------------------------

# python imports
import copy
import types
import traceback
import glob
import os.path

# mevas imports
import base

# pydirectfb
from directfb import *

dfb = DirectFB()


_capabilities =  {
    "to-raw-formats": ["BGRA", ],
    "from-raw-formats": ["BGRA", ],
    "preferred-format": "BGRA",
    "shmem": False,
    "pickling": True,
    "unicode": True,
    "layer-alpha": True,
    "alpha-mask": True,
    "cache": True
    }


_dfb_pixel_format = {
    0x00118005: 'DSPF_A8',
    0x4011420c: 'DSPF_ALUT44',
    0x00418c04: 'DSPF_ARGB',
    0x00211780: 'DSPF_ARGB1555',
    0x08100609: 'DSPF_I420',
    0x4011040b: 'DSPF_LUT8',
    0x00200801: 'DSPF_RGB16',
    0x00300c02: 'DSPF_RGB24',
    0x00400c03: 'DSPF_RGB32',
    0x00100407: 'DSPF_RGB332',
    0x00000000: 'DSPF_UNKNOWN',
    0x00200808: 'DSPF_UYVY',
    0x00200806: 'DSPF_YUY2',
    0x0810060a: 'DSPF_YV12'
    }

_mevas_pixel_format = {
    DSPF_A8       : '',
    DSPF_ALUT44   : '',
    DSPF_ARGB     : 'BGRA',
    DSPF_ARGB1555 : '',
    DSPF_I420     : '',
    DSPF_LUT8     : '',
    DSPF_RGB16    : '',
    DSPF_RGB24    : '',
    DSPF_RGB32    : '',
    DSPF_RGB332   : '',
    DSPF_UNKNOWN  : 'DSPF_UNKNOWN',
    DSPF_UYVY     : '',
    DSPF_YUY2     : '',
    DSPF_YV12     : ''
    }

_font_path = []
_fonts = {}



class Image(base.Image):
    """
    A DirectFB based image class.
    Some methods here are left unimplimented until we find a way to easily
    do what's needed.  It may be possible to still use pyimlib2 for some of
    the things DirectFB doesn't support.
    """
    def __init__(self, image_or_filename):
        self.imageDescription = None
        self.filename = None
        self.has_alpha = 1
        self._color = (255, 255, 255, 255)

        if isinstance(image_or_filename, Image):
            self._image = image_or_filename._image
        elif isinstance(image_or_filename, Surface):
            self._image = image_or_filename
        elif isinstance(image_or_filename, ImageProvider):
            self._image = 
dfb.createSurface(description=image_or_filename.getSurfaceDescription())
            image_or_filename.renderTo(self._image)
        elif type(image_or_filename) in types.StringTypes:
            self.filename = image_or_filename
            provider = dfb.createImageProvider(self.filename)
            self.imageDescription = provider.getImageDescription()
            self._image = 
dfb.createSurface(description=provider.getSurfaceDescription())
            provider.renderTo(self._image)
        elif isinstance(image_or_filename, SurfaceDescription):
            self._image = dfb.createSurface(description=image_or_filename)
        else:
            raise ValueError, "Unsupported image type: %s" % \
                  type(image_or_filename)

        self._image.setBlittingFlags(DSBLIT_BLEND_ALPHACHANNEL)
        self._image.setDrawingFlags(DSDRAW_BLEND)


    def __getattr__(self, attr):
        if attr == "format":
            return _mevas_pixel_format[self._image.getPixelFormat()]

        elif attr == "width":
            return self._image.getSize()[0]

        elif attr == "height":
            return self._image.getSize()[1]

        elif attr == "size":
            return self._image.getSize()

        print 'DEBUG: want attr "%s"' % attr

        if attr in ("pitch"):
            return getattr(self._image.getSurfaceDescription(), attr)

        elif attr in ("mode", "has_alpha", "rowstride", "get_pixel"):
            return getattr(self._image, attr)

        return base.Image.__getattr__(self, attr)


    def get_raw_data(self, format = "BGRA"):
        if format == self.format:
            return str(self._image.getSurfaceDescription().data)

        else:
            # Must decide how to deal with other formats.
            # Maybe we can blit onto a new surface with the desired format
            # then return its surfaceDescription.data.
            return None


    # TODO: Maybe we can add a tools section to pydirectfb to help
    #       with some image transformations, or use pyimlib2.

    def rotate(self, angle):
        print 'Image.rotate not implimented'


    def flip(self):
        print 'Image.flip not implimented'


    def mirror(self):
        print 'Image.mirror not implimented'


    def scale(self, size, src_pos = (0, 0), src_size = (-1, -1)):
        print 'Image.scale called'
         
        if src_size[0] == -1:
            s_w = self.width
        else:
            s_w = src_size[0]

        if src_size[1] == -1:
            s_h = self.height
        else:
            s_h = src_size[1]

        newsurf = dfb.createSurface(caps=self._image.getCapabilities(),
                                    width=size[0], height=size[1],
                                    pixelformat=self._image.getPixelFormat())

        newsurf.stretchBlit(self._image,
                            (src_pos[0], src_pos[1], s_w, s_h),
                            (0, 0, size[0], size[1]))

        self._image = newsurf


    def blend(self, srcimg, dst_pos = (0, 0), dst_size = (-1, -1),
              src_pos = (0, 0), src_size = (-1, -1),
              alpha = 255, merge_alpha = True):

        print 'Image.blend called'
        # print 'src_size: %s,%s' % src_size
        # print 'src_pos: %s,%s' % src_pos
        # print 'dst_pos: %s,%s' % dst_pos

        blittingFlags = DSBLIT_NOFX  

        if alpha == 256: 
            merge_alpha = False
        elif merge_alpha:
            blittingFlags |= DSBLIT_BLEND_ALPHACHANNEL 

        self._image.setBlittingFlags(blittingFlags)

        real_src_size = srcimg._image.getSize()

        if src_size[0] == -1:
            s_w = real_src_size[0]
        else:
            s_w = src_size[0]

        if src_size[1] == -1:
            s_h = real_src_size[1]
        else:
            s_h = src_size[1]

        if dst_size[0] == -1:
            d_w = real_src_size[0]
        else:
            d_w = dst_size[0]

        if dst_size[1] == -1:
            d_h = real_src_size[1]
        else:
            d_h = dst_size[1]

        if (s_w, s_h) == (d_w, d_h):
            # no scaling involved
            print 'use blit: %s %s (%s %s %s %s)' % (dst_pos[0], 
dst_pos[1],src_pos[0], src_pos[1], s_w, s_h)
            #
            # XXX: This blit call segfaults!!!
            #
            #self._image.blit(srcimg._image, dst_pos[0], dst_pos[1], 
            #                 (src_pos[0], src_pos[1], s_w, s_h))
            #
            # replace it with this stretchBlit() call for now, and maybe
            # for good.  If so we can remove the above if statement.
            self._image.stretchBlit(srcimg._image, 
                                    (src_pos[0], src_pos[1], s_w, s_h),
                                    (dst_pos[0], dst_pos[1], d_w, d_h))
        else:
            # scaling, use stretchBlit()
            print 'use stretchBlit'
            self._image.stretchBlit(srcimg._image, 
                                    (src_pos[0], src_pos[1], s_w, s_h),
                                    (dst_pos[0], dst_pos[1], d_w, d_h))


    def clear(self, pos = (0, 0), size = (-1, -1)):
        print 'Image.clear called'
        real_size = self._image.getSize()

        if size[0] == -1:
            s_w = real_size[0]
        else:
            s_w = size[0]

        if size[1] == -1:
            s_h = real_size[1]
        else:
            s_h = size[1]

        # Is position 0,0 top left?
        self._image.setClip((pos[0], pos[1], pos[0]+s_w, pos[1]-s_h))
        self._image.clear(0,0,0,0)
        self._image.setClip()


    def draw_mask(self, maskimg, pos):
        print 'Image.draw_mask not implimented'


    def copy(self):
        print 'Image.copy called'
        return Image(copy(self._image))


    def set_font(self, font_or_fontname):
        if isinstance(font_or_fontname, Font):
            font_or_fontname = font_or_fontname._font
        return self._image.setFont(font_or_fontname)


    def get_font(self):
        return Font(self._image.getFont())


    def set_color(self, color):
        print 'set_color: %s' % str(color)

        if len(color) == 3:
            r, g, b = color
            a = 0xFF
        elif len(color) == 4:
            r, g, b, a = color
        else:
            return
        # print 'color now: %x,%x,%x,%x' % (r, g, b, a)

        try:
            self._image.setColor(r, g, b, a)
            self._color = (r, g, b, a)
        except:
            traceback.print_exc()


    def get_color(self):
        return self._color


    def draw_text(self, pos, text, color = None, font_or_fontname = None):

        if font_or_fontname:
            if isinstance(font_or_fontname, Font):
                font_or_fontname = font_or_fontname._font

            self.set_font(font_or_fontname)

        
        oldcol = self.get_color()

        if color and not color == self.get_color():
            self.set_color(color)
            self._image.drawString(text, pos[0], pos[1], DSTF_LEFT | DSTF_TOP)
            self.set_color(oldcol)
        else:
            self._image.drawString(text, pos[0], pos[1], DSTF_LEFT | DSTF_TOP)


    def draw_rectangle(self, pos, size, color, fill = True):
        oldcol = self.get_color()
        self.set_color(color)
       
        x, y = pos
        w, h = size
        if 0 in [w, h]:  
            print 'Bad rect!'
            print 'rect: %d %d %d %d' % (x, y, w, h)
            return

        self._image.setDrawingFlags(DSDRAW_BLEND)

        if fill:
            self._image.fillRectangle(x, y, w, h)
        else:
            self._image.drawRectangle(x, y, w, h)

        self.set_color(oldcol)


    def draw_ellipse(self, center, amplitude, color, fill = True):
        print 'Image.draw_ellipse called'
        if fill: fill = 1
        else: fill = 0

        self._image.setDrawingFlags(DSDRAW_BLEND)

        oldcol = self.get_color()
        self.set_color(color)
       
        self._image.drawEllipse(center, amplitude, fill)
        self.set_color(oldcol)


    def move_to_shmem(self, format = "BGRA", id = None):
        # TODO: decide if we need this, if not, remove it
        print 'Image.move_to_shmem not implimented'


    def save(self, filename, format = None):
        # TODO: find a way to save an image to file because
        #       IDirectFBImageProvider doesn't support this.
        print 'Image.save not implimented'


    def get_capabilities(self):
        return _capabilities


    def crop(self, pos, size):
        print 'Image.crop called'
         
        newsurf = dfb.createSurface(caps=self._image.getCapabilities(),
                                    width=size[0], height=size[1],
                                    pixelformat=self._image.getPixelFormat())

        newsurf.blit(self._image, 0, 0, (pos[0], pos[1], size[0], size[1]))

        self._image = newsurf


    def scale_preserve_aspect(self, size):
        print 'Image.scale_preserve_aspect called'
        self.scale(size)


    def copy_rect(self, src_pos, size, dst_pos):
        print 'Image.copy_rect called'
        self._image.blit(self._image, dst_pos[0], dst_pos[1], 
                         (src_pos[0], src_pos[1], size[0], size[1]))




class Font(base.Font):
    def __init__(self, font_or_fontdesc, color = (255, 255, 255, 255)):
        global _fonts

        if not type(font_or_fontdesc) in types.StringTypes:
            self._font = font_or_fontdesc
        else:
            (name, size) = font_or_fontdesc.split('/')

            print 'want to load font %s from %s' % (name, _fonts[name])
            try:
                self._font = dfb.createFont(_fonts[name], height=int(size))
            except:
                raise IOError, 'Failed to load font %s' % name


    def get_text_size(self, text):
        # TODO: This most definately needs to be refined.
        w = self._font.getStringWidth(text)
        h = self._font.getHeight()
        ha = self._font.getMaxAdvance()
        va = h

        return (w, h, ha, va)


    def set_color(self, color):
        pass


    def __getattr__(self, attr):
        # TODO: this needs some fixing
        if attr in ("ascent", "descent", "max_ascent", "max_descent"):
            return getattr(self._font, attr)
        return base.Font.__getattr__(self, attr)



def get_capabilities():
    return _capabilities


def open(file):
    return Image(file)


def new(size, rawdata = None, from_format = 'BGRA'):
    if from_format not in _capabilities['from-raw-formats']:
        raise ValueError, 'Unsupported raw format: %s' % from_format
    if rawdata:
        raise ValueError, 'New Image from raw data not yet supported.'

    # TODO: create a new SurfaceDescription using rawdata then pass it
    #       through Image contructor.

    return Image(dfb.createSurface(width=size[0], height=size[1]))



def add_font_path(path):
    global _font_path
    global _fonts

    _font_path.append(path)

    for font in glob.glob( os.path.join(path, '*.[T|t][T|t][F|f]')):
        fontname = os.path.basename(font).split('.')[0]
        _fonts[fontname] = font

    print 'added font path %s, fonts now:' % path
    print _fonts


def load_font(font, size):
    global _fonts

    if font.find('.'):
        font = font.split('.')[0]
    if not _fonts.get(font):
        raise IOError, 'Failed to find font %s' % font

    return Font('%s/%s' % (font, size))



def scale(image, size, src_pos = (0, 0), src_size = (-1, -1)):
    image = copy.copy(image)
    image.scale(size, src_pos, src_size)
    return image


def crop(image, pos, size):
    image = copy.copy(image)
    image.crop(pos, size)
    return image


def rotate(image, angle):
    image = image.copy()
    image.rotate(angle)
    return image


def scale_preserve_aspect(image, size):
    image = copy.copy(image)
    image.scale_preserve_aspect(size)
    return image


def thumbnail(src, dst, size):
    # TODO: return a new Image from surface size, then stretchblit src onto it
    pass


--- NEW FILE: .cvsignore ---
*.pyc *.pyo

--- NEW FILE: base.py ---
# -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------------
# base.py - imagelib base object
# -----------------------------------------------------------------------------
# $Id: base.py,v 1.1 2005/06/26 17:02:06 dischi Exp $
#
# -----------------------------------------------------------------------------
# kaa-mevas - MeBox Canvas System
# Copyright (C) 2004-2005 Jason Tackaberry <[EMAIL PROTECTED]>
#
# First Edition: Jason Tackaberry <[EMAIL PROTECTED]>
# Maintainer:    Dirk Meyer <[EMAIL PROTECTED]>
#
# 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 MER-
# CHANTABILITY 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
#
# -----------------------------------------------------------------------------


class Image(object):
    """
    Base class for mevas imagelib images
    """
    def __init__(self, image_or_filename):
        """
        Create a new Image object wrapper for the given backend.

        Arguments:
          image_or_filename: Instantiate the image from another Image
                     instance, an instance of the backend's image
                     class or type, or a file name from which to load
                     the image.
        """
        pass


    def __getattr__(self, attr):
        """
        These attributes must be available:

              size: tuple containing the width and height of the image
             width: width of the image
            height: height of the image
            format: format of the image if loaded from file (e.g. PNG, JPEG)
          filename: filename if loaded from file
        """
        if attr not in self.__dict__:
            raise AttributeError, attr
        return self.__dict__[attr]


    def get_raw_data(self, format = "RGBA"):
        """
        Returns raw image data.

        Arguments:
          format: pixel format of the raw data to be returned.  If 'format' is
              not a supported format, raise ValueError.

        Returns: A string or buffer object containing the raw image data.
        """
        pass


    def scale(self, (w, h), src_pos = (0, 0), src_size = (-1, -1)):
        """
        Scale the image

        Arguments:
          w, h: the width and height of the new image.  If either argument
            is -1, that dimension is calculated from the other dimension
            while retaining the original aspect ratio.

        Returns: None
        """
        pass


    def crop(self, (x, y), (w, h)):
        """
        Crop the image

        Arguments:
          x, y, w, h: represents the left, top, width, height region in
                  the image.

        Returns: None
        """
        pass


    def rotate(self, angle):
        """
        Rotate the image

        Arguments:
          angle: the angle in degrees by which to rotate the image.

        Return: None
        """
        pass


    def scale_preserve_aspect(self, (w, h)):
        """
        Scales the image while retaining the original aspect ratio

        Arguments:
          w, h: the maximum size of the new image.  The new image will be as
            large as possible, using w, h as the upper limits, while
            retaining the original aspect ratio.

        Return: None
        """
        pass


    def copy_rect(self, src_pos, size, dst_pos):
        """
        Copies a region within the image.

        Arguments:
          src_pos: a tuple holding the x, y coordinates marking the top left
               of the region to be moved.
             size: a tuple holding the width and height of the region to move.
                   If either dimension is -1, then that dimension extends to
               the far edge of the image.
          dst_pos: a tuple holding the x, y coordinates within the image
               where the region will be moved to.

        Returns: None
        """
        pass


    def blend(self, srcimg, dst_pos = (0, 0), dst_size = (-1, -1),
          src_pos = (0, 0), src_size = (-1, -1),
          alpha = 255, merge_alpha = False):
        """
        Blends one image onto another.

        Arguments:
               srcimg: the image being blended onto 'self'
              dst_pos: a tuple holding the x, y coordinates where the source
                   image will be blended onto the destination image.
              src_pos: a tuple holding the x, y coordinates within the source
                   image where blending will start.
             src_size: a tuple holding the width and height of the source
                   image to be blended.  A value of -1 for either one
                   indicates the full dimension of the source image.
             dst_size: a tuple holding the width and height that the source
                   image will be scaled to before blending onto the
                   destination image.
            alpha: the "layer" alpha that is applied to all pixels of the
                   image.  If an individual pixel has an alpha of 128 and
                   this value is 128, the resulting pixel will have an
                   alpha of 64 before it is blended to the destination
                   image.  0 is fully transparent and 255 is fully opaque,
                   and 256 is a special value that means alpha blending is
                   disabled.
          merge_alpha: if True, the alpha channel is also blended.  If False,
                   the destination image's alpha channel is untouched and
                   the RGB values are compensated.

        Returns: None.
        """
        pass


    def clear(self, (x, y) = (0, 0), (w, h) = (-1, -1)):
        """
        Clears the image at the specified rectangle, resetting all pixels in
        that rectangle to fully transparent.

        Arguments:
          x, y: left and top coordinates of the rectangle to be cleared.
            Default is the top left corner.
          w, h: width and height of the rectangle to be cleared.  If either
            value is -1 then the image is cleared to the far edge.

        Returns: None
        """
        pass


    def draw_mask(self, maskimg, (x, y)):
        """
        Applies the luma channel of maskimg to the alpha channel of the
        the current image.

        Arguments:
          maskimg: the image from which to read the luma channel
             x, y: the top left coordinates within the current image where the
               alpha channel will be modified.  The mask is drawn to the
               full width/height of maskimg.

        Returns: None
        """
        pass


    def copy(self):
        """
        Creates a copy of the current image.

        Returns: a new Image instance with a copy of the current image.
        """
        pass


    def set_font(self, font_or_fontname):
        """
        Sets the font context to font_or_font_name.  Subsequent calls to
        draw_text() will be rendered using this font.

        Arguments:
          font_or_fontname: either a Font object, or a string containing the
                    font's name and size.  This string is in the
                    form "Fontname/Size" such as "Arial/16"


        Returns: a Font instance represent the specified font.  It
             'font_or_fontname' is already a Font instance, it is simply
             returned back to the caller.
        """
        pass


    def get_font(self):
        """
        Gets the current Font context.

        Returns: A Font instance as created by set_font() or None if no font
             context is defined.
        """
        pass


    def draw_text(self, (x, y), text, color = None, font_or_fontname = None):
        """
        Draws text on the image.

        Arguments:
                  x, y: the left/top coordinates within the current image
                    where the text will be rendered.
                  text: a string holding the text to be rendered.
                 color: a 3- or 4-tuple holding the red, green, blue, and
                    alpha values of the color in which to render the
                    font.  If color is a 3-tuple, the implied alpha
                    is 255.  If color is None, the color of the font
                    context, as specified by set_font(), is used.
          font_or_fontname: either a Font object, or a string containing the
                    font's name and size.  This string is in the
                    form "Fontname/Size" such as "Arial/16".  If this
                    parameter is none, the font context is used, as
                    specified by set_font().

        Returns: a 4-tuple representing the width, height, horizontal advance,
             and vertical advance of the rendered text.
        """
        pass


    def draw_rectangle(self, (x, y), (w, h), color, fill = True):
        """
        Draws a rectangle on the image.

        Arguments:
           x, y: the top left corner of the rectangle.
           w, h: the width and height of the rectangle.
          color: a 3- or 4-tuple holding the red, green, blue, and alpha
             values of the color in which to draw the rectangle.  If
             color is a 3-tuple, the implied alpha is 255.
           fill: whether the rectangle should be filled or not.  The default
             is true.

        Returns: None
        """
        pass


    def draw_ellipse(self, (xc, yc), (a, b), color, fill = True):
        """
        Draws an ellipse on the image.

        Arguments:
          xc, yc: the x, y coordinates of the center of the ellipse.
            a, b: the horizontal and veritcal amplitude of the ellipse.
           color: a 3- or 4-tuple holding the red, green, blue, and alpha
              values of the color in which to draw the ellipse.  If
              color is a 3-tuple, the implied alpha is 255.
            fill: whether the ellipse should be filled or not.  The default
              is true.

        Returns: None
        """
        pass


    def move_to_shmem(self, format = "RGBA", id = None):
        """
        Creates a POSIX shared memory object and copy the image's raw data.

        Arguments:
          format: the format of the raw data to copy to shared memory.  If
              the specified format is not supported, raise ValueError.
              id: the name of the shared memory object (as passed to
              shm_open(3)).  If id is None, a suitable unique id is
              generated.

        Returns: the id of the shared memory object.
        """
        pass


    def save(self, filename, format = None):
        """
        Saves the image to a file.

        Arguments:
          format: the format of the written file (jpg, png, etc.).  If format
              is None, the format is gotten from the filename extension.

        Returns: None.
        """
        pass


    def get_capabilities(self):
        """
        Get the capabilities of the imagelib backend used to create this
        image.
        """
        return get_capabilities()




class Font(object):

    def __init__(self, fontdesc, color = (255, 255, 255, 255)):
        """
        Create a new Font object wrapper.

        Arguments:
          fontdesc: the description of the font, in the form "Fontname/Size".
                Only TrueType fonts are supported, and the .ttf file must
                exist in a registered font path.  Font paths can be
                registered by calling imagelib.add_font_path().
               color: a 3- or 4-tuple holding the red, green, blue, and alpha
                values of the color in which to render text with this
                font context.  If color is a 3-tuple, the implied alpha
                is 255.  If color is not specified, the default is fully
                opaque white.

        """
        pass


    def get_text_size(self, text):
        """
        Get the font metrics for the specified text as rendered by the
        current font.

        Arguments:
          text: the text for which to retrieve the metric.

        Returns: a 4-tuple containing the width, height, horizontal advance,
             and vertical advance of the text when rendered.
        """
        pass


    def set_color(self, color):
        """
        Sets the default color for text rendered with this font.

        Arguments:
            color: a 3- or 4-tuple holding the red, green, blue, and alpha
             values of the color in which to render text with this
             font context.  If color is a 3-tuple, the implied alpha
             is 255.
        """
        pass


    def __getattr__(self, attr):
        """
        These attributes must be available:

               ascent: the current font's ascent value in pixels.
              descent: the current font's descent value in pixels.
          max_descent: the current font's maximum descent extent.
           max_ascent: the current font's maximum ascent extent.
        """
        if attr not in self.__dict__:
            raise AttributeError, attr
        return self.__dict__[attr]


# These methods must be provided by the backend and are accessed by
# imagelib.functionname when the backend is loaded.

def get_capabilities():
    """
    Returns a dictionary of capabilities for this backend.

    Required items are:
        to-raw-formats: list of supported pixel formats that get_raw_data()
                supports.  e.g. BGRA, RGB, YV12A.
      from-raw-formats: list of supported pixel formats that new() supports.
      preferred-format: the native or preferred pixel format for the backend.
                When format parameters are unspecified, this is the
                default format.
             shmem: If the backend supports writing raw data to shared
                shared memory.
          pickling: If Image and Font objects can be pickled.
           unicode: If the backend correctly supports unicode strings.
           layer-alpha: If the alpha parameter in Image.blend() is supported.
        alpha-mask: If Image.draw_mask() is supported.
             cache: If the the backend implements an image cache.
    """
    return {
    }


def scale(image, (w, h), src_pos = (0, 0), src_size = (-1, -1)):

    """
    Scale the specified image and return a new image.

    Arguments:
      w, h: the width and height of the new image.  If either argument
        is -1, that dimension is calculated from the other dimension
        while retaining the original aspect ratio.

    Returns: a new Image instance representing the scaled image.
    """
    pass


def crop(image, (x, y), (w, h)):
    """
    Crop the specified image and return a new image.

    Arguments:
      x, y, w, h: represents the left, top, width, height region in
              the image.

    Returns: a new Image instance representing the cropped image.
    """
    pass


def rotate(image, angle):
    """
    Rotate the specified image and return a new image.

    Arguments:
      angle: the angle in degrees by which to rotate the image.

    Return: a new Image instance representing the rotated image.
    """
    pass


def scale_preserve_aspect(image, (w, h)):
    """
    Scales the specified image while retaining the original aspect ratio and
    return a new image.

    Arguments:
      w, h: the maximum size of the new image.  The new image will be as
        large as possible, using w, h as the upper limits, while
        retaining the original aspect ratio.

    Return: a new Image insatnce represented the scaled image.
    """
    pass


def open(file):
    """
    Opens a file and returns an Image instance.

    Arguments:
      file: the filename of the image to load.

    Returns: a new Image instance representing the file.
    """
    pass


def new(size, rawdata = None, from_format = "RGBA"):
    """
    Creates a new image and returns an Image instance.

    Arguments:
         size: a tuple containing the width and height of the new image.
          rawdata: the raw image data from which to create the new image.  If
               rawdata is not None, it is expected to be in the same
               format as specified by from_format, and be the required
               size.  If the size is invalid, raise ValueError.  If
               rawdata is not None, the all pixels are initialized to
               fully transparent.
      from_format: the format the raw data is specified in.  If the format is
               not a supported format by this backend, raise ValueError.

    Returns: a new Image instance, either blank if rawdata is not specified,
         or initialized from rawdata.
    """
    pass


def add_font_path(path):
    """
    Adds a path to the list of paths scanned when loading fonts.

    Arguments:
      path: the path name to add.

    Returns: None.
    """
    pass


def load_font(font, size):
    """
    Load the specified font and return a new Font instance.

    Arguments:
      font: the name of the font to load.
      size: the size of font.

    Returns: a new Font instance representing the specified font.
    """
    pass

--- NEW FILE: __init__.py ---
_backend = None

def set_backend(name):
    exec "from %s_backend import *"  % name in globals()
    global _backend
    _backend = name


def get_current_backend():
    return _backend


def get_backend(name):
    try:
        backend = __import__(name + "_backend", globals())
    except ImportError:
        return None
    return backend


# Set default backend
try:
    set_backend("imlib2")
except ImportError:
    pass

if _backend == None:
    raise "No supported image library could be found."


def convert(image, target = None):
    if target == None:
        target = get_current_backend()

    target_backend = get_backend(target)
    if isinstance(image, target_backend.Image):
        return image



-------------------------------------------------------
SF.Net email is sponsored by: Discover Easy Linux Migration Strategies
from IBM. Find simple to follow Roadmaps, straightforward articles,
informative Webcasts and more! Get everything you need to get up to
speed, fast. http://ads.osdn.com/?ad_id=7477&alloc_id=16492&op=click
_______________________________________________
Freevo-cvslog mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/freevo-cvslog

Reply via email to