# -*- mode: python; coding: utf-8 -*-
#
# Pigment Python binding cairo integration example using the gradient cairo
# snippets translated to Python.
#
# Copyright © 2006, 2007, 2008 Fluendo Embedded S.L.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#
# Author: Loïc Molinari <loic@fluendo.com>

import sys, math, array, pgm, cairo

# Terminate the mainloop on a delete event
def on_delete(viewport, event):
    pgm.main_quit()

# Draw a gradient in a memory buffer with Cairo
def cairo_drawing(width, height):
    # Store the Cairo surface in an array
    data = array.array('c', chr(0) * width * height * 4)
    surface = cairo.ImageSurface.create_for_data (data, cairo.FORMAT_ARGB32,
                                                  width, height, width * 4)
    # Create the context
    ctx = cairo.Context(surface)
    ctx.scale(width, height)

    # Draw a sphere
    pat = cairo.RadialGradient(0.45, 0.4, 0.1, 0.4, 0.4, 0.5)
    pat.add_color_stop_rgba(0, 0.8, 0.8, 1, 1)
    pat.add_color_stop_rgba(1, 0, 0, 1, 1)
    ctx.set_source(pat)
    ctx.arc(0.5, 0.5, 0.3, 0, 2 * math.pi)
    ctx.fill()

    # And return the buffer as a Python string
    return data.tostring()

# Entry point
def main():
    # OpenGL viewport creation
    gl = pgm.viewport_factory_make('opengl')
    gl.title = 'Sphere'

    # Canvas and image drawable creation
    cvs = pgm.Canvas()
    cvs.size = (800.0, 600.0)

    # Bind the canvas to the OpenGL viewport
    gl.set_canvas(cvs)

    # Draw a gradient with cairo and put it in a Pigment Image
    img = pgm.Image()
    data = cairo_drawing(400, 400)
    img.set_from_buffer(pgm.IMAGE_BGRA, 400, 400, 400 * 4, 400 * 400 * 4, data)
    img.bg_color = (255, 255, 255, 0)
    img.position = (200.0, 100.0, 0.0)
    img.size = (400.0, 400.0)
    img.show()

    # Add the drawable to the middle layer of the canvas
    cvs.add(pgm.DRAWABLE_MIDDLE, img)

    # Let's connect our callbacks and start the mainloop
    gl.connect('delete-event', on_delete)
    gl.show()
    pgm.main()

if __name__ == '__main__':
    sys.exit(main())
