#
# The Python Imaging Library
# $Id: GbrImagePlugin.py 2134 2004-10-06 08:55:20Z fredrik $
#
# load a GIMP brush file
#
# History:
#       96-03-14 fl     Created
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1996.
#
# See the README file for information on usage and redistribution.
#

import Image, ImageFile

def i32(c):
    return ord(c[3]) + (ord(c[2])<<8) + (ord(c[1])<<16) + (ord(c[0])<<24L)

def _accept(prefix):
    return i32(prefix) >= 20 and i32(prefix[4:8]) == 2

##
# Image plugin for the GIMP brush format.

class GbrImageFile(ImageFile.ImageFile):

    format = "GBR"
    format_description = "GIMP brush file"

    def _open(self):
        header_size = i32(self.fp.read(4))
        version = i32(self.fp.read(4))
        if header_size < 20 or version != 2:
            raise SyntaxError, "not a GIMP brush"

        width = i32(self.fp.read(4))
        height = i32(self.fp.read(4))
        bytes = i32(self.fp.read(4))
        if width <= 0 or height <= 0 or bytes != 1 and bytes != 4:
            raise SyntaxError, "not a GIMP brush"

        gimp = self.fp.read(4)
        spacing = i32(self.fp.read(4))
        comment = self.fp.read(header_size - 28)[:-1]

        if bytes == 1:
            self.mode = "L"
        else:
            self.mode = "RGBA"
        self.size = width, height

        self.info["comment"] = comment
        self.info["spacing"] = spacing
        self.info["gimp"] = gimp

        if bytes == 1:
            # Since the brush is so small, we read the data immediately
            data = self.fp.read(width * height)
            self.data = []
            for i in data:
                self.data.append((0x00,0x00,0x00, ord(i)))
                self.mode = "RGBA"
        else:
            self.data = []
            for i in range(width * height):
                r = ord(self.fp.read(1))
                g = ord(self.fp.read(1))
                b = ord(self.fp.read(1))
                a = ord(self.fp.read(1))
                self.data.append((r,g,b,a))

    def load(self):

        if not self.data:
            return

        # create an image out of the brush data block
        self.im = Image.core.new(self.mode, self.size)
        self.im.putdata(self.data)
        self.data = ""

#
# registry

Image.register_open("GBR", GbrImageFile, _accept)

Image.register_extension("GBR", ".gbr")
