<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>/dev/stu &#187; cairo</title>
	<atom:link href="http://www.stuartaxon.com/tag/cairo/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.stuartaxon.com</link>
	<description>Adding LOC to the web.</description>
	<lastBuildDate>Mon, 09 Jan 2012 18:11:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Using PyCha with Django</title>
		<link>http://www.stuartaxon.com/2011/02/25/using-pycha-with-django/</link>
		<comments>http://www.stuartaxon.com/2011/02/25/using-pycha-with-django/#comments</comments>
		<pubDate>Fri, 25 Feb 2011 00:10:50 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[cairo]]></category>
		<category><![CDATA[charting]]></category>
		<category><![CDATA[charts]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[pycha]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=290</guid>
		<description><![CDATA[A quick post on using Python Charts to generate nice SVG charts for your django website (I&#8217;ve had the code hanging around for ages &#8211; so should just post it). The code is based on the examples there, here I integrate it into Django. To install you&#8217;ll need to do pip install pycha Heres the [...]]]></description>
			<content:encoded><![CDATA[<p>A quick post on using <a href="http://bitbucket.org/lgs/pycha/">Python Charts</a> to generate nice SVG charts for your django website (I&#8217;ve had the code hanging around for ages &#8211; so should just post it).  The code is based on the examples there, here I integrate it into Django.</p>
<p>To install you&#8217;ll need to do</p>
<pre>pip install pycha</pre>
<p>Heres the code for a simple view to output a chart directly to SVG:</p>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2011/02/linechart.png"><img class="alignnone size-full wp-image-291" title="linechart" src="http://www.stuartaxon.com/wp-content/uploads/2011/02/linechart.png" alt="" width="401" height="316" /></a></p>
<pre class="brush:python"># views.py

from StringIO import StringIO
from django.http import HttpResponse

import cairo

def colors(request):
    in_req = 1

    svg_buffer = StringIO()

    width, height = (500, 400)
    surface = cairo.SVGSurface(svg_buffer, width, height)

    dataSet = (
     ('dataSet 1', ((0, 1), (1, 3), (2, 2.5))),
     ('dataSet 2', ((0, 2), (1, 4), (2, 3))),
     ('dataSet 3', ((0, 5), (1, 1), (2, 0.5))),
    )

    options = {
       'legend': {'hide': True},
       'background': {'color': '#f0f0f0'},
    }

    #import pycha.bar
    #chart = pycha.bar.VerticalBarChart(surface, options)

    import pycha.line
    chart = pycha.line.LineChart(surface, options)
    chart.addDataset(dataSet)
    chart.render()

    del chart
    del surface

    response = ''
    response = HttpResponse(mimetype='image/svg+xml')
    svg_buffer.seek(0)
    response.write( svg_buffer.read() )
    return response
</pre>
<p>The basic idea is that &#8211; instead of the chart outputting to an svg file, the output goes to a buffer, this is triggered by calling the destructors of the chart and it&#8217;s cairo surface.  Once the data is in the buffer, it is rewound and played back to the Http Response.</p>
<p>&nbsp;</p>
<h2>Inline SVG</h2>
<p>As is, this won&#8217;t work as inline svg, because outputting the XML preamble in the middle of the page will cause problems.  Below is an example that let&#8217;s you decide if you need the preamble (full SVG output), or not (SVG fragment for inclusion in a page or another SVG):</p>
<pre class="brush:python"># Create your views here.

from StringIO import StringIO
from django.http import HttpResponse
from django.shortcuts import render_to_response

import cairo

XML_PREAMBLE = '&lt;?xml version="1.0" encoding="UTF-8"?&gt;'

def colors_chart(inline = False):
    """
    Generate colours chart

    Set inline to True to disable the XML preamble
    """
    in_req = 1

    svg_buffer = StringIO()

    width, height = (500, 400)
    surface = cairo.SVGSurface(svg_buffer, width, height)

    dataSet = (
     ('dataSet 1', ((0, 1), (1, 3), (2, 2.5))),
     ('dataSet 2', ((0, 2), (1, 4), (2, 3))),
     ('dataSet 3', ((0, 5), (1, 1), (2, 0.5))),
    )

    options = {
       'legend': {'hide': True},
       'background': {'color': '#f0f0f0'},
    }

    import pycha.bar
    chart = pycha.bar.VerticalBarChart(surface, options)

    #import pycha.line
    #chart = pycha.line.LineChart(surface, options)
    chart.addDataset(dataSet)
    chart.render()

    del chart
    del surface

    response = ''

    if inline:
        svg_buffer.seek(len(XML_PREAMBLE))
    else:
        svg_buffer.seek(0)
    return svg_buffer.read()

def colors_svg(request):
    """ render a pure SVG chart """
    response = HttpResponse(mimetype='image/svg+xml')
    response.write(colors_chart(inline = False))
    return response

def index(request):
    """ render a chart into the template """
    chart_svg = colors_chart(inline = True)

    return render_to_response(
        'shapes_index.html',
        { "chart" : chart_svg },
        mimetype='application/xhtml+xml')
</pre>
<p>An example project with the above code is available here:<br />
<a href="http://www.stuartaxon.com/wp-content/uploads/2011/02/pycha_django.zip">pycha_django</a></p>
<p>&nbsp;</p>
<p>[EDIT 25/2/2011] Fixed PyCha URL</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2011/02/25/using-pycha-with-django/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A simple cairo draw queue using closures</title>
		<link>http://www.stuartaxon.com/2010/05/12/a-simple-cairo-draw-queue-using-closures/</link>
		<comments>http://www.stuartaxon.com/2010/05/12/a-simple-cairo-draw-queue-using-closures/#comments</comments>
		<pubDate>Wed, 12 May 2010 19:53:53 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[. closure]]></category>
		<category><![CDATA[cairo]]></category>
		<category><![CDATA[pycairo]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=251</guid>
		<description><![CDATA[Often it&#8217;s useful to be able to store up drawing commands so you can use them later somewhere else (or even just pass them to another thread). This is a simple drawing model, implemented in cairo, hopefully somebody will find it useful. Queue class DrawQueue: ''' A list of draw commands, stored as callables that, [...]]]></description>
			<content:encoded><![CDATA[<p>Often it&#8217;s useful to be able to store up drawing commands so you can use them later somewhere else (or even just pass them to another thread).</p>
<p>This is a simple drawing model, implemented in cairo, hopefully somebody will find it useful.</p>
<p>Queue</p>
<pre class="brush:python">class DrawQueue:
    '''
    A list of draw commands, stored as callables that, are
    passed a set of parameters to draw on from the canvas
    implementation.
    '''
    def __init__(self, render_callables = None):
        self.render_callables = render_callables or deque()

    def append(self, render_callable):
        '''
        Add a render callable to the queue
        '''
        self.render_callables.append(render_callable)

    def render(self, cairo_ctx):
        '''
        Call all the render callables with cairo_ctx
        '''
        for render_callable in self.render_callables:
            render_callable(cairo_ctx)
</pre>
<p>The queue just accepts callables (any old function), and calls them when you call render, passing them a cairo context you pass in.</p>
<p>To get useful functions you can call closure functions like these:</p>
<pre class="brush:python">def paint_closure():
    def paint(ctx):
        ctx.paint()
    return paint

def fill_closure():
    def fill(ctx):
        ctx.fill()
    return fill

def set_source_rgb_closure(r, g, b):
    def set_source_rgb(ctx):
        ctx.set_source_rgb(r, g, b)
    return set_source_rgb

def moveto_closure(x, y):
    def moveto(ctx):
        ctx.move_to(x, y)
    return moveto

def rectangle_closure(x, y, w, h):
    def rectangle(ctx):
        ctx.rectangle(x, y, w, h)
    return rectangle
</pre>
<p>Adding commands to the queue is simple:</p>
<pre class="brush:python">dq = DrawQueue()
dq.append(set_source_rgb_closure(1, 1, 1))
dq.append(paint_closure())
dq.append(moveto_closure(10, 0))
dq.append(rectangle_closure(0, 0, 20, 20))
dq.append(set_source_rgb_closure(0, 0, 0))
dq.append(fill_closure())
</pre>
<p>This is the same drawing model I&#8217;m using in my branch of shoebot, I&#8217;m hoping to expand it to be multithreaded; while a foreground thread adds commands a background thread is executing them.</p>
<p>Here it is all put together in a simple example to draw a black rectangle</p>
<pre class="brush:python">from collections import deque
import cairo

class DrawQueue:
    '''
    A list of draw commands, stored as callables that, are
    passed a set of parameters to draw on from the canvas
    implementation.
    '''
    def __init__(self, render_callables = None):
        self.render_callables = render_callables or deque()

    def append(self, render_callable):
        '''
        Add a render callable to the queue
        '''
        self.render_callables.append(render_callable)

    def render(self, cairo_ctx):
        '''
        Call all the render callables with cairo_ctx
        '''
        for render_callable in self.render_callables:
            render_callable(cairo_ctx)

#### drawing closures
def paint_closure():
    def paint(ctx):
        ctx.paint()
    return paint

def fill_closure():
    def fill(ctx):
        ctx.fill()
    return fill

def set_source_rgb_closure(r, g, b):
    def set_source_rgb(ctx):
        ctx.set_source_rgb(r, g, b)
    return set_source_rgb

def moveto_closure(x, y):
    def moveto(ctx):
        ctx.move_to(x, y)
    return moveto

def rectangle_closure(x, y, w, h):
    def rectangle(ctx):
        ctx.rectangle(x, y, w, h)
    return rectangle

#### /drawing closures

dq = DrawQueue()

# Add some commands to the drawing queue
dq.append(set_source_rgb_closure(1, 1, 1))
dq.append(paint_closure())
dq.append(moveto_closure(10, 0))
dq.append(rectangle_closure(0, 0, 20, 20))
dq.append(set_source_rgb_closure(0, 0, 0))
dq.append(fill_closure())

# Create a surface and context
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 200)
ctx = cairo.Context(surface)

# run defered rendering
dq.render(ctx)

surface.write_to_png('output.png')
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/05/12/a-simple-cairo-draw-queue-using-closures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Cairo to generate SVG in Django</title>
		<link>http://www.stuartaxon.com/2010/02/03/using-cairo-to-generate-svg-in-django/</link>
		<comments>http://www.stuartaxon.com/2010/02/03/using-cairo-to-generate-svg-in-django/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 00:36:27 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[cairo]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=217</guid>
		<description><![CDATA[Cairo is a 2D vector graphics api used by Firefox, Gtk and other desktop projects. I&#8217;m going to show here that it can also be used to generate web content, using Django. I&#8217;m going to port two examples from the Michael Urmans Cairo Tutorial for PyGTK Programmers. To understand the cairo and it&#8217;s drawing model [...]]]></description>
			<content:encoded><![CDATA[<p>Cairo is a 2D vector graphics api used by Firefox, Gtk and other desktop projects.</p>
<p>I&#8217;m going to show here that it can also be used to generate web content, using Django.</p>
<p>I&#8217;m going to port two examples from the Michael Urmans <a href="http://www.tortall.net/mu/wiki/PyGTKCairoTutorial">Cairo Tutorial  for PyGTK Programmers</a>.</p>
<p>To understand the cairo and it&#8217;s drawing model I&#8217;d recommend his his <a href="http://www.tortall.net/mu/wiki/CairoTutorial">Cairo Tutorial for Python  Programmers.</a></p>
<blockquote><p>Note:  In this example I&#8217;ll be generating SVGs&#8230;  as I.E. (as of 2010) does not support them, you might want to generate PNG or PDF &#8211; if you need to do this with cairo, look for one of the many cairo tutorials on the web.</p></blockquote>
<p>The example django project can be downloaded at the end of the article.</p>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_shapes.png"><img class="alignnone size-full wp-image-223" title="django_cairo_shapes" src="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_shapes.png" alt="" width="302" height="230" /></a></p>
<p><span id="more-217"></span></p>
<h2>Prerequisites</h2>
<p>You&#8217;ll need django and pycairo installed&#8230; and a little bit of Django knowledge.</p>
<p>In Windows you can do use easy_install to get the python dependencies:</p>
<pre class="brush:shell">
easy_install pycairo
easy_install django
</pre>
<p>In linux you&#8217;ll need to use your favourite package manager.</p>
<p>Onto the code&#8230;</p>
<h2>Hosting Framework</h2>
<p>The pygtk example starts by building a simple hosting framework</p>
<pre class="brush:python">#! /usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk, gobject, cairo

# Create a GTK+ widget on which we will draw using Cairo
class Screen(gtk.DrawingArea):

    # Draw in response to an expose-event
    __gsignals__ = { "expose-event": "override" }

    # Handle the expose-event by drawing
    def do_expose_event(self, event):

        # Create the cairo context
        cr = self.window.cairo_create()

        # Restrict Cairo to the exposed area; avoid extra work
        cr.rectangle(event.area.x, event.area.y,
                event.area.width, event.area.height)
        cr.clip()

        self.draw(cr, *self.window.get_size())

    def draw(self, cr, width, height):
        # Fill the background with gray
        cr.set_source_rgb(0.5, 0.5, 0.5)
        cr.rectangle(0, 0, width, height)
        cr.fill()

# GTK mumbo-jumbo to show the widget in a window and quit when it's closed
def run(Widget):
    window = gtk.Window()
    window.connect("delete-event", gtk.main_quit)
    widget = Widget()
    widget.show()
    window.add(widget)
    window.present()
    gtk.main()

if __name__ == "__main__":
    run(Screen)
</pre>
<p>This needs to be made ready for the web and the Gtkisms removed:</p>
<p>cairodraw.py</p>
<pre class="brush:python">from cairo import Context, SVGSurface

# Create a GTK+ widget on which we will draw using Cairo
class CairoWidget:

    def __init__(self, Surface = None):
        if Surface == None:
            Surface = SVGSurface

        self.Surface = Surface

    def draw(self, cr, width, height):
        # Fill the background with gray
        cr.set_source_rgb(0.5, 0.5, 0.5)
        cr.rectangle(0, 0, width, height)
        cr.fill()

def draw_widget(dest, Widget, Surface = SVGSurface, width = 100, height = 100):
    """
    Convenience function to output CairoWidget to a buffer
    """
    widget = Widget(Surface)
    surface = widget.Surface(dest, width, height)
    widget.draw(Context(surface), width, height)
    surface.finish()
</pre>
<h3>Changes:</h3>
<ul>
<li> Screen class is now CairoWidget as Screen made less sense in this context.</li>
<li>run() is replaced with draw_widget() and it has some new parameters to help it be rendered with django.</li>
<li>The new file is &#8216;cairodraw.py&#8217;, not &#8216;framework.py&#8217;</li>
</ul>
<h2>Initial view&#8230;</h2>
<p>Heres the initial views.py</p>
<pre class="brush:python"># Create your views here.

from django.http import HttpResponse
from cairo import SVGSurface

import cairodraw

from math import pi

class Shapes(cairodraw.CairoWidget):
    def draw(self, cr, width, height):
        cr.set_source_rgb(0.5, 0.5, 0.5)
        cr.rectangle(0, 0, width, height)
        cr.fill()

        # draw a rectangle
        cr.set_source_rgb(1.0, 1.0, 1.0)
        cr.rectangle(10, 10, width - 20, height - 20)
        cr.fill()

        # draw lines
        cr.set_source_rgb(0.0, 0.0, 0.8)
        cr.move_to(width / 3.0, height / 3.0)
        cr.rel_line_to(0, height / 6.0)
        cr.move_to(2 * width / 3.0, height / 3.0)
        cr.rel_line_to(0, height / 6.0)
        cr.stroke()

        # and a circle
        cr.set_source_rgb(1.0, 0.0, 0.0)
        radius = min(width, height)
        cr.arc(width / 2.0, height / 2.0, radius / 2.0 - 20, 0, 2 * pi)
        cr.stroke()
        cr.arc(width / 2.0, height / 2.0, radius / 3.0 - 10, pi / 3, 2 * pi / 3)
        cr.stroke()

class Transform(cairodraw.CairoWidget):
    def draw(self, cr, width, height):
        cr.set_source_rgb(0.5, 0.5, 0.5)
        cr.rectangle(0, 0, width, height)
        cr.fill()

        # draw a rectangle
        cr.set_source_rgb(1.0, 1.0, 1.0)
        cr.rectangle(10, 10, width - 20, height - 20)
        cr.fill()

        # set up a transform so that (0,0) to (1,1)
        # maps to (20, 20) to (width - 40, height - 40)
        cr.translate(20, 20)
        cr.scale((width - 40) / 1.0, (height - 40) / 1.0)

        # draw lines
        cr.set_line_width(0.01)
        cr.set_source_rgb(0.0, 0.0, 0.8)
        cr.move_to(1 / 3.0, 1 / 3.0)
        cr.rel_line_to(0, 1 / 6.0)
        cr.move_to(2 / 3.0, 1 / 3.0)
        cr.rel_line_to(0, 1 / 6.0)
        cr.stroke()

        # and a circle
        cr.set_source_rgb(1.0, 0.0, 0.0)
        radius = 1
        cr.arc(0.5, 0.5, 0.5, 0, 2 * pi)
        cr.stroke()
        cr.arc(0.5, 0.5, 0.33, pi / 3, 2 * pi / 3)
        cr.stroke()

def shapes(request):
    response = HttpResponse(mimetype='image/svg+xml')
    cairodraw.draw_widget(response, Shapes)
    return response

def transform(request):
    response = HttpResponse(mimetype='image/svg+xml')
    cairodraw.draw_widget(response, Transform)
    return response
</pre>
<p>The main difference is that Shape and Transform are the same, except they extend cairodraw.CairoWidget.</p>
<h3>urls.py</h3>
<p>This is pretty straightforward.</p>
<pre>(r'^shapes/shapes/$', 'shapes.views.shapes'),</pre>
<pre>(r'^shapes/transform/$', 'shapes.views.transform'),</pre>
<h2>Taking stock&#8230;</h2>
<p>This is a good stage to try things out, heres the django project so far: <a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_1a.zip">django_cairo_1a</a>.</p>
<p>Enter the svgsite directory and run</p>
<pre>python manage.py runserver</pre>
<p>If all is well it should output something like this:</p>
<pre>Validating models...
0 errors found

Django version 1.1.1, using settings 'svgsite.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.</pre>
<p>If you visit the two URLs in most browsers except I.E. the output will look like this:</p>
<h3>http://127.0.0.1:8000/shapes/transform/</h3>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_transform.png"><img class="alignnone size-full wp-image-222" title="django_cairo_transform" src="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_transform.png" alt="" width="302" height="230" /></a></p>
<h3>http://127.0.0.1:8000/shapes/shapes/</h3>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_shapes.png"><img class="alignnone size-full wp-image-223" title="django_cairo_shapes" src="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_shapes.png" alt="" width="302" height="230" /></a></p>
<h2>Inline SVG and templates&#8230;</h2>
<p>The previous examples output straight SVG, however it would be much better to be able to incorperate SVG into templates and use it with HTML.</p>
<p>Luckily modern browsers support this, and with a couple of changes we can make templates that will output mixed documents like <a href="http://jwatt.org/svg/demos/xhtml-with-inline-svg.xhtml">this</a>.</p>
<h3>Example template:</h3>
<pre>&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
 &lt;head&gt;
 &lt;title&gt;SVG embedded inline in XHTML&lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
 &lt;h1&gt;Transform&lt;/h1&gt;
 &lt;div style="width:50%, height:40px"&gt;{{transform|safe}}&lt;/div&gt;
 &lt;div&gt;&lt;a href="transform"&gt;Full screen svg&lt;/a&gt;&lt;/div&gt;
 &lt;h1&gt;Shapes&lt;/h1&gt;
 &lt;div style="width:50%"&gt;{{shapes|safe}}&lt;/div&gt;
 &lt;div&gt;&lt;a href="shapes"&gt;Full screen svg&lt;/a&gt;&lt;/div&gt;
 &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The variables &#8216;shapes&#8217; and &#8216;transform&#8217; will be the svg, the key is the &#8216;|safe&#8217;, which means the XML won&#8217;t be processed by django.</p>
<h3>Changes to views to support inline</h3>
<p>To use templates the SVG data is needed as a string to pass to the template.</p>
<p>Heres an index view demonstrating this:</p>
<pre class="brush:python">def index(request):
    buff = StringIO()
    cairodraw.draw_widget(buff, Shapes)
    shapes = buff.getvalue()[38:]

    buff = StringIO()
    cairodraw.draw_widget(buff, Transform)
    transform = buff.getvalue()[38:]

    return render_to_response(
    'shapes_index.html',
    {"transform": transform, "shapes": shapes},
    mimetype='application/xhtml+xml')
</pre>
<p>The main differences are that -<br />
cairodraw.draw_widget() is called with a temporary buffer, we use templates.</p>
<blockquote>
<h4>Evil hack alert:</h4>
<p>OK, I did something naughty&#8230; notice the [38:] ?   Unfortunately django doesn&#8217;t like having  in the middle of the output.  I couldn&#8217;t find a way to turn this off so we chop it off the beginning of the string.</p></blockquote>
<p>Apart from the evil hack this works well and you get output like this:</p>
<h3>http://127.0.0.1:8000/shapes/</h3>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_inline_svg.png"><img class="alignnone size-full wp-image-230" title="django_cairo_inline_svg" src="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_inline_svg.png" alt="" width="294" height="652" /></a></p>
<h1></h1>
<h2>Final Version</h2>
<p>Cool, every thing seems to be working !</p>
<p>The final version to try <a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_1b.zip">django_cairo_1b</a>.</p>
<h2>Next time&#8230;.</h2>
<p>I&#8217;ll be looking at using a Cairo based library,  <a href="http://bitbucket.org/lgs/pycha/wiki/Home">PyCha</a> library with django to output smooth looking charts in SVG.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/02/03/using-cairo-to-generate-svg-in-django/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Using Java2Python to port a JavaCairo tutorial</title>
		<link>http://www.stuartaxon.com/2009/08/21/using-java2python-to-port-a-javacairo-tutorial/</link>
		<comments>http://www.stuartaxon.com/2009/08/21/using-java2python-to-port-a-javacairo-tutorial/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 00:22:15 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[cairo]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[javagnome]]></category>
		<category><![CDATA[porting]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=158</guid>
		<description><![CDATA[I recently came across Java2Python.  As I&#8217;m interested in Cairo I thought it would be interesting to try porting one of the example tutorials from ZetCode. I&#8217;ll run through the steps involved in porting then try and reach some conclusions at the end . 1. Get setup This is easiest in Linux, I&#8217;m running Ubuntu [...]]]></description>
			<content:encoded><![CDATA[<p>I recently came across <a title="J2Py" href="http://code.google.com/p/java2python/">Java2Python</a>.  As I&#8217;m interested in Cairo I thought it would be interesting to try porting one of the <a href="http://zetcode.com/tutorials/javagnometutorial/firststeps/">example tutorials</a> from ZetCode.</p>
<p>I&#8217;ll run through the steps involved in porting then try and reach some conclusions at the end <img src='http://www.stuartaxon.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<h4>1. Get setup</h4>
<p>This is easiest in Linux, I&#8217;m running Ubuntu (in vmware), and installed</p>
<pre>antlr 2.x
python2.5.x
sun java6
pygtk
java-gnome</pre>
<p>You can install them like this:</p>
<pre class="brush:shell"># sudo apt-get install antlr python2.5 sun-java6-bin libjava-gnome-java
</pre>
<p>Then install Python2Java with easy_install</p>
<pre class="brush:shell"># sudo easy_install-2.5 java2python</pre>
<p>To test if it&#8217;s working run j2py -i.  It should complain there is no file:</p>
<pre class="brush:shell"># j2py -i
Usage: j2py [options]

j2py: error: -i option requires an argument</pre>
<p>If you get any other errors your missing some packages.</p>
<h4>2. Get the Java Code from the Simple Example.</h4>
<p>Save the <a href="http://zetcode.com/tutorials/javagnometutorial/firststeps/">&#8216;simple.java&#8217; example</a> as &#8216;GSimple.java&#8217;</p>
<p>If java-gnome is running ok, compiling and running it you should see a window:</p>
<pre>
# javac GSimple.java
# java GSimple
</pre>
<p><img src="http://www.stuartaxon.com/wp-content/uploads/2009/08/gsimple.png" alt="gsimple" title="gsimple" width="258" height="178" class="alignnone size-full wp-image-171" /></p>
<div style="clear:both;">
<p>Now we&#8217;ll run through the code, it&#8217;s important to understand what it does before we port it&#8230;</p>
<p><span id="more-158"></span></p>
<pre class="brush:java">package com.zetcode;

import org.gnome.gdk.Event;
import org.gnome.gtk.Gtk;
import org.gnome.gtk.Widget;
import org.gnome.gtk.Window;
import org.gnome.gtk.WindowPosition;

/**
 * ZetCode Java Gnome tutorial
 *
 * This program is a simple Java Gnome
 * application.
 *
 * @author jan bodnar
 * website zetcode.com
 * last modified March 2009
 */

public class GSimple extends Window  {

    public GSimple() {

        setTitle("Simple");

        connect(new Window.DeleteEvent() {
            public boolean onDeleteEvent(Widget source, Event event) {
                Gtk.mainQuit();
                return false;
            }
        });

        setDefaultSize(250, 150);
        setPosition(WindowPosition.CENTER);
        show();
    }

    public static void main(String[] args) {
        Gtk.init(args);
        new GSimple();
        Gtk.main();
    }
}</pre>
<h5>Code Runthrough</h5>
<ul>
<li> Import java-gnome bindings</li>
<li> Create a class that extends org.gnome.gtk.Window</li>
<li> Set the size of the window</li>
<li> Connect the &#8216;delete&#8217; event to an InnerClass.  When a delete event arrives,  &#8216;onDeleteEvent&#8217; is called which in turn calls Gtk.mainQuit().<br />
<blockquote><p>Gtk.mainQuit() will quit program and cleanup gtk.</p></blockquote>
</li>
<li> set window size</li>
<li> show the window</li>
<h4>3. Use j2py to create the initial python code.</h4>
<p>The first stage is to generate the python.</p>
<pre class="brush:shell"># j2py -i GSimple.java &gt; gsimple.py</pre>
<p>Output [gsimple.py]:</p>
<pre class="brush:python">#!/usr/bin/env python
# -*- coding: utf-8 -*-

class GSimple(Window):
    """ generated source for GSimple

    """

    def __init__(self):
        setTitle("Simple")

        def onDeleteEvent(self, source, event):
            Gtk.mainQuit()
            return False

        connect(Window.DeleteEvent())
        setDefaultSize(250, 150)
        setPosition(WindowPosition.CENTER)
        show()

    @classmethod
    def main(cls, args):
        Gtk.init(args)
        GSimple()
        Gtk.cls.main()

if __name__ == '__main__':
    import sys
    GSimple.main(sys.argv)</pre>
<h4>5. Analyze</h4>
<p>Unfortunately j2py is not magic, it&#8217;s time to have a look at the code..</p>
<p>Things are missing and others look wrong, heres an initial list of problems:</p>
<ul>
<li>no imports</li>
<li>&#8216;self&#8217; not specified in class constructor</li>
<li>CamelCase used &#8211; this is suspicious, it&#8217;s unlikely the cairo bindings work like this</li>
<li>@classmethod is probably not nessacary here</li>
<li>Gtk.cls.main() &#8211; This looks particularly suspicious</li>
</ul>
<p>Indeed &#8211; If you try and run it, the missing imports become apparent:</p>
<pre class="brush:shell">bagside@bagvapp:~/jythongnome$ python gsimple.py
Traceback (most recent call last):
  File "gsimple.py", line 5, in
    class GSimple(Window):
NameError: name 'Window' is not defined</pre>
<h4>6.  Fixing the initial Problems</h4>
<p>Some problems are easy to fix, others involve learning the differences between the java and python APIs.</p>
<p>Starting with the easiest&#8230;</p>
<h5>&#8216;self&#8217; not specified in class constructor</h5>
<p>This looks easiest so we&#8217;ll tackle it first, heres the new constructor:</p>
<pre class="brush:python">        self.setTitle("Simple")

        def onDeleteEvent(self, source, event):
            Gtk.mainQuit()
            return False

        self.connect(Window.DeleteEvent())
        self.setDefaultSize(250, 150)
        self.setPosition(WindowPosition.CENTER)
        self.show()</pre>
<p>Doing this does emphasize how wrong the CamelCase looks, also the onDeleteEvent being a function in the constructor doesn&#8217;t look right, we could probably move it up a level.</p>
<h5>No imports</h5>
<p>In the java code there is</p>
<pre class="brush:java">import org.gnome.gdk.Event;
import org.gnome.gtk.Gtk;
import org.gnome.gtk.Widget;
import org.gnome.gtk.Window;
import org.gnome.gtk.WindowPosition;</pre>
<p>Googling for <strong>Window module</strong> and <strong>gtk</strong> you&#8217;ll end up at the <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkwindow.html">pygtk site</a>.<br />
The documentation shows the Window class is in the gtk module.  Further research on the site or in the python prompt shows most of the other classes are in the same module too.</p>
<pre class="brush:python"># To do research in the python prompt, simply start python and try
import gtk
dir(gtk)
help(gtk)
help(gtk.Window)</pre>
<p>It&#8217;s worth having a glance at the python help to see if the bindings look the same, start python and try:</p>
<pre class="brush:python">import gtk
help(gtk.Window)</pre>
<p>&#8230;[output snipped]&#8230;</p>
<pre class="brush:python"> |  set_skip_taskbar_hint(...)
 |
 |  set_startup_id(...)
 |
 |  set_title(...)
 |
 |  set_transient_for(...)
 |
 |  set_type_hint(...)
 |
 |  set_urgency_hint(...)</pre>
<p>It&#8217;s fairly obvious that CamelCase is not used here, as suspected (remember to change this later&#8230;)</p>
<p>As &#8220;Window&#8221; is quite generic, I&#8217;ll move everything into the &#8216;gtk&#8217; namespace, add</p>
<pre class="brush:python">import gtk</pre>
<p>To the top of the code, and change all instances of the gtk classes to &#8216;gtk.ClassName&#8217;, e.g. gtk.Window:</p>
<pre class="brush:python">#!/usr/bin/env python
# -*- coding: utf-8 -*-

import gtk

class GSimple(gtk.Window):
    """ generated source for GSimple

    """

    def __init__(self):
        self.setTitle("Simple")

        def onDeleteEvent(self, source, event):
            Gtk.mainQuit()
            return False

        self.connect(gtk.Window.DeleteEvent())
        self.setDefaultSize(250, 150)
        self.setPosition(WindowPosition.CENTER)
        self.show()

    @classmethod
    def main(cls, args):
        Gtk.init(args)
        GSimple()
        Gtk.cls.main()

if __name__ == '__main__':
    import sys
    GSimple.main(sys.argv)</pre>
<p>And try running it:</p>
<pre class="brush:shell">Traceback (most recent call last):
  File "gsimple.py", line 31, in
    GSimple.main(sys.argv)
  File "gsimple.py", line 25, in main
    Gtk.init(args)
NameError: global name 'Gtk' is not defined</pre>
<p>It&#8217;s complaining about the &#8216;main&#8217; class method on GSimple, we can just remove it and move everything into the main method of the module:</p>
<pre class="brush:python">if __name__ == '__main__':
    import sys
    Gtk.init(args)
    GSimple()
    Gtk.cls.main()</pre>
<p>This still won&#8217;t work for sure as &#8216;Gtk&#8217; is not in the namespace.</p>
<p>The first step is to work out whats going on, consult the java code then the relevant documentation.</p>
<pre class="brush:java">
<pre>[GSimple.java]</pre>
<p>public static void main(String[] args) {</p>
<p>Gtk.init(args);</p>
<p>new GSimple();</p>
<p>Gtk.main();</p>
<p>}</pre>
<p>OK, the code is the same, what does the java gnome documentation say about Gtk.init ?</p>
<blockquote><p>init</p>
<p>public static void init(String[] args)</p>
<p>Initialize the GTK libraries. This must be called before any other org.gnome.* classes are used.</p>
<p>Parameters:<br />
args &#8211; The command line arguments array. This is passed to the underlying library to allowing user (or window manager) to alter GTK&#8217;s behaviour.<br />
Since:<br />
4.0.0</p></blockquote>
<p>Looking in pygtk there isn&#8217;t &#8216;init&#8217; (it would be confusing having this and __init__ anyway).</p>
<p>Looking in the pygtk documentation there is no &#8216;init&#8217; method (which makes sense as it could be confused with  &#8216;__init__&#8217;.   There is however <a href="http://www.pygtk.org/docs/pygtk/gtk-functions.html#function-gtk--main">gtk.main</a>:</p>
<blockquote><p>gtk.main</p>
<p>def gtk.main()</p>
<p>The gtk.main() function runs the main loop until the gtk.main_quit() function is called. You can nest calls to gtk.main(). In that case the call to the gtk.main_quit() function will make the innermost invocation of the main loop return.</p></blockquote>
<p>Here I confess some prior knowledge, I already had a vague idea the main loop might be involved as I&#8217;d worked with gtk before.</p>
<p>So we&#8217;ll try gtk.main, and commenting out the line calling main on the class as I&#8217;m not entirely sure what it does:</p>
<pre class="brush:python">if __name__ == '__main__':
    import sys
    gtk.main()  # Note gtk.main takes no parameters
    GSimple()
    # Gtk.cls.main()</pre>
<h5>Try running</h5>
<p>And&#8230; nothing happens &#8211; you have to quit with CTRL-C!</p>
<p>It looks like it&#8217;s not even getting to the constructor (as there should be errors here, maybe gtk.main() needs to run *after* the GSimple() constructor..</p>
<p>Sure enough:</p>
<pre class="brush:shell"># python gsimple.py
Traceback (most recent call last):
  File "gsimple.py", line 30, in
    GSimple()
  File "gsimple.py", line 13, in __init__
    self.setTitle("Simple")
AttributeError: 'GSimple' object has no attribute 'setTitle'</pre>
<h5>Fixing the CamelCase</h5>
<p>The pygtk documentation seemed all be underscored_lowercase, it&#8217;s probably safe to speculatively change everything to this then fix any errors:</p>
<pre class="brush:python">#!/usr/bin/env python
# -*- coding: utf-8 -*-

import gtk

class GSimple(gtk.Window):
    """ generated source for GSimple

    """

    def __init__(self):
        self.set_title("Simple")

        def on_delete_event(self, source, event):
            gtk.main_quit()
            return False

        self.connect(gtk.Window.DeleteEvent())
        self.set_default_size(250, 150)
        self.set_position(WindowPosition.CENTER)
        self.show()

if __name__ == '__main__':
    import sys
    GSimple()
    gtk.main()  # Note gtk.main takes no parameters
    #    Gtk.cls.main()</pre>
<p>Output:</p>
<pre> python gsimple.py
gsimple.py:12: GtkWarning: gtk_window_set_title: assertion `GTK_IS_WINDOW (window)' failed
  self.set_title("Simple")
Traceback (most recent call last):
  File "gsimple.py", line 28, in
    GSimple()
  File "gsimple.py", line 18, in __init__
    self.connect(gtk.Window.DeleteEvent())
AttributeError: type object 'gtk.Window' has no attribute 'DeleteEvent'</pre>
<p>Thats progress!  It means the self.set_title call probably works, and there is a self.connect call too.</p>
<p>There is no DeleteEvent in the <a href="http://library.gnome.org/devel/pygtk/stable/">pygtk documentation</a>&#8230; which is not suprising as it looks more java than python.<br />
Better to step back and have a look at self.connect, in the end I googled</p>
<pre>gtk connect delete event</pre>
<p>And got to a <a href="http://www.pygtk.org/pygtk2tutorial/ch-GettingStarted.html">getting started with pygtk</a> page:</p>
<blockquote><pre>
36  # When the window is given the "delete_event" signal (this is given
37  # by the window manager, usually by the "close" option, or on the
38  # titlebar), we ask it to call the delete_event () function
39  # as defined above. The data passed to the callback
40  # function is NULL and is ignored in the callback function.
41  self.window.connect("delete_event", self.delete_event)</pre>
</blockquote>
<p>Note here they have &#8216;window&#8217; as their delegating, our generated code extends this class.</p>
<p>The signature is slightly different, also instead of &#8216;on_delete_event&#8217; the function is just called &#8216;delete_event&#8217;, this seems more pythonic so we&#8217;ll do the same.</p>
<p>This would also be a good time to move the function into the main class, out of the constructor:</p>
<pre class="brush:python">class GSimple(gtk.Window):
    """ generated source for GSimple

    """

    def __init__(self):
        self.set_title("Simple")

        self.connect('delete_event', delete_event)
        self.set_default_size(250, 150)
        self.set_position(WindowPosition.CENTER)
        self.show()

    def delete_event(self, source, event):
	gtk.main_quit()
	return False</pre>
<p>And the output:</p>
<pre>gsimple.py:12: GtkWarning: gtk_window_set_title: assertion `GTK_IS_WINDOW (window)' failed
  self.set_title("Simple")
Traceback (most recent call last):
  File "gsimple.py", line 29, in
    GSimple()
  File "gsimple.py", line 14, in __init__
    self.connect('delete_event', delete_event)
NameError: global name 'delete_event' is not defined</pre>
<p>The first line assertion <em>`GTK_IS_WINDOW (window)&#8217; failed </em>is the important one here; it makes sense, the constructor of the gtk.Window has not been called yet.</p>
<p>Add
<pre>gtk.Window.__init__(self)</pre>
<p> to the top of the constructor and run.</p>
<pre>
Traceback (most recent call last):
File "gsimple.py", line 30, in <module>
GSimple()
File "gsimple.py", line 17, in __init__
self.set_position(WindowPosition.CENTER)
NameError: global name 'WindowPosition' is not defined
</pre>
<h6>And again&#8230;</h6>
<p>Repeating the same process for WindowPosition and set_position, you&#8217;ll find that the set_position line should look like this:</p>
<pre class="brush:python">
self.set_position(gtk.WIN_POS_CENTER)
</pre>
<p>And the output&#8230;<br />
<img src="http://www.stuartaxon.com/wp-content/uploads/2009/08/gsimple.png" alt="gsimple" title="gsimple" width="258" height="178" class="alignnone size-full wp-image-171" /></p>
<div style="clear:both;">
<p>Huzzah!  Success!</p>
<h4>Final Source code</h4>
<pre class="brush:python">
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import gtk

class GSimple(gtk.Window):

    def __init__(self):
	gtk.Window.__init__(self)
        self.set_title("Simple")

        self.connect('delete_event', self.delete_event)
        self.set_default_size(250, 150)
        self.set_position(gtk.WIN_POS_CENTER)
        self.show()

    def delete_event(self, source, event):
	gtk.main_quit()
	return False

if __name__ == '__main__':
    import sys
    GSimple()
    gtk.main()
</pre>
<h4>Conclusions</h4>
<p>Although Cairo APIs are available for Java and Python they are of course quite different.   One implication of this is that if you wanted to use Cairo from a Jython java applet (via native methods) it couldn&#8217;t have code 100% the same as a normal python app.<br />
java2python is good, but you still need to put the work in.<br />
Working in this way is also a good way to find differences within implementations of an API.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2009/08/21/using-java2python-to-port-a-javacairo-tutorial/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>

