# -*- mode: python; coding: utf-8 -*-
#
# Pigment Python binding layout example
#
# 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 random, sys, pgm, gobject

HSIZE, VSIZE = 10, 10

# Layout the images
def layout_images(canvas, images):
    width, height = canvas.get_size()
    offset_x, offset_y = canvas.get_pixel_offsets()
    width_offset = width / HSIZE
    height_offset = height / VSIZE
    for j in xrange(VSIZE):
        for i in xrange(HSIZE):
            index = j * VSIZE + i
            images[index].set_bg_color(random.randint(0, 255),
                                       random.randint(0, 255),
                                       random.randint(0, 255), 255)
            images[index].set_position(width_offset * i, height_offset * j, 0.0)
            images[index].set_size(width_offset - offset_x,
                                   height_offset - offset_y)

# Relayout the image on a configure event
def on_configure(viewport, event, canvas, images, ratio):
    layout_images(canvas, images)

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

def main(args):
    # GObject threads initialization
    gobject.threads_init()

    # Canvas and viewport creation
    viewport = pgm.viewport_factory_make('opengl')
    viewport.set_title('Layout')
    screen_width, screen_height = viewport.get_screen_size_mm()
    resolution_width, resolution_height = viewport.get_screen_resolution()
    ratio = (float(resolution_width) / resolution_height) * \
        (float(screen_height) / screen_width)
    viewport.set_size(int(500.0 * ratio), 500)
    canvas = pgm.Canvas()
    canvas.set_size(1, 1)
    viewport.set_canvas(canvas)

    # Create and add images to the canvas
    images = []
    for i in xrange(HSIZE * VSIZE):
        images.append(pgm.Image())
        images[i].show()
        canvas.add(pgm.DRAWABLE_MIDDLE, images[i])

    # Let's connect our callbacks and start the mainloop
    viewport.connect('delete-event', on_delete)
    viewport.connect('configure-event', on_configure, canvas, images, ratio)
    viewport.show()
    pgm.main()

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
