
"A texture using Cairo for 2D drawing."

import cairo

import OpenGL.GL as gl

from glitch.texture import Texture

class CairoTexture(Texture):
    "A texture using Cairo for 2D drawing."

    y_flip = True

    def __init__(self, width, height):
        # Data is created later.
        Texture.__init__(self, width, height, None)
        self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)

        # XXX: This assumes little-endian.
        self.format = gl.GL_BGRA

    def draw_cairo(self, cr):
        """Called when the texture needs to be rendered.

        @param cr: The Cairo context to draw using.
        """

        cr.set_source_rgba(0, 0, 0, 0)
        cr.paint()

        cr.set_source_rgb(1, 0, 0)
        cr.move_to(0, 0)
        cr.line_to(self.width, 0)
        cr.line_to(self.width, self.height)
        cr.line_to(0, self.height)
        cr.line_to(0, 0)
        cr.set_line_width(20)
        cr.stroke()

    def upload(self, ctx):
        cr = cairo.Context(self.surface)
        self.draw_cairo(cr)
        # XXX: Eww.
        self.data = str(self.surface.get_data())
        Texture.upload(self, ctx)

