<?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</title>
	<atom:link href="http://www.stuartaxon.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.stuartaxon.com</link>
	<description>Adding LOC to the web.</description>
	<lastBuildDate>Fri, 28 May 2010 02:32:50 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Simple python spectrograph with shoebot</title>
		<link>http://www.stuartaxon.com/2010/05/17/shoebot-spectrograph/</link>
		<comments>http://www.stuartaxon.com/2010/05/17/shoebot-spectrograph/#comments</comments>
		<pubDate>Mon, 17 May 2010 20:14:02 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[audio]]></category>
		<category><![CDATA[fft spectrograph]]></category>
		<category><![CDATA[nodebox]]></category>
		<category><![CDATA[portaudio]]></category>
		<category><![CDATA[pyaudio]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[shoebot]]></category>
		<category><![CDATA[visualisation]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=264</guid>
		<description><![CDATA[Seeing&#8221;Realtime FFT Graph of Audio WAV File or Microphone Input  with Python&#8230;&#8221;  on python.reddit.com reminded me of one I&#8217;d built in python with shoebot.
While it works OK, I feel like I&#8217;m missing a higher level audio library (especially having seen Minim, for C++ and Java).

To run it in shoebot:
sbot -w audiobot.bot
audiobot.bot
# Major library imports
import [...]]]></description>
			<content:encoded><![CDATA[<p>Seeing&#8221;<a title="Permanent Link: Realtime FFT Graph of Audio WAV  File or Microphone Input with Python, Scipy, and WCKgraph" rel="bookmark" href="http://www.swharden.com/blog/2010-03-05-realtime-fft-graph-of-audio-wav-file-or-microphone-input-with-python-scipy-and-wckgraph/">Realtime FFT Graph of Audio WAV File or Microphone Input  with Python</a>&#8230;&#8221;  on python.reddit.com reminded me of one I&#8217;d built in python with <a href="http://shoebot.net">shoebot</a>.</p>
<p>While it works OK, I feel like I&#8217;m missing a higher level audio library (especially having seen Minim, for C++ and Java).</p>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/05/graphs.gif"><img class="alignnone size-full wp-image-265" title="graphs" src="http://www.stuartaxon.com/wp-content/uploads/2010/05/graphs.gif" alt="" width="358" height="288" /></a></p>
<p>To run it in shoebot:</p>
<pre class="brush:shell">sbot -w audiobot.bot</pre>
<h3>audiobot.bot</h3>
<pre class="brush:python"># Major library imports
import atexit
import pyaudio
from numpy import zeros, short, fromstring, array
from numpy.fft import fft

NUM_SAMPLES = 512
SAMPLING_RATE = 11025

def setup():
    size(350, 260)
    speed(SAMPLING_RATE / NUM_SAMPLES)

_stream = None

def read_fft():
    global _stream
    pa = None

    def cleanup_audio():
        if _stream:
            _stream.stop_stream()
            _stream.close()
        pa.terminate()

    if _stream is None:
        pa = pyaudio.PyAudio()
        _stream = pa.open(format=pyaudio.paInt16, channels=1,
                           rate=SAMPLING_RATE,
                           input=True, frames_per_buffer=NUM_SAMPLES)
        atexit.register(cleanup_audio)

    audio_data  = fromstring(_stream.read(NUM_SAMPLES), dtype=short)
    normalized_data = audio_data / 32768.0

    return fft(normalized_data)[1:1+NUM_SAMPLES/2]

def flatten_fft(scale = 1.0):
    """
    Produces a nicer graph, I'm not sure if this is correct
    """
    for i, v in enumerate(read_fft()):
        yield scale * (i * v) / NUM_SAMPLES

def triple(audio):
    '''return bass/mid/treble'''
    c = audio.copy()
    c.resize(3, 255 / 3)
    return c

def draw():
    '''Draw 3 different colour graphs'''
    global NUM_SAMPLES
    audio = array(list(flatten_fft(scale = 80)))
    freqs = len(audio)
    bass, mid, treble = triple(audio)

    colours = (0.5, 1.0, 0.5), (1, 1, 0), (1, 0.2, 0.5)

    fill(0, 0, 1)
    rect(0, 0, WIDTH, 400)
    translate(50, 200)

    for spectrum, col in zip((bass, mid, treble), colours):
        fill(col)
        for i, s in enumerate(spectrum):
            rect(i, 0, 1, -abs(s))
        else:
            translate(i, 0)

    audio = array(list(flatten_fft(scale = 80)))
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/05/17/shoebot-spectrograph/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Cairo: Surface for recording commands and playback</title>
		<link>http://www.stuartaxon.com/2010/05/13/cairo-surface-for-recording-commands-and-playback/</link>
		<comments>http://www.stuartaxon.com/2010/05/13/cairo-surface-for-recording-commands-and-playback/#comments</comments>
		<pubDate>Thu, 13 May 2010 20:08:18 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[cairo python graphics]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=258</guid>
		<description><![CDATA[An update on my latest cairo adventures&#8230;
When cairo 1.10 comes out we&#8217;ll get a RecordingSurface so you can record commands and play them back to another surface, but how to do something similar now ?
Skip to the end if you just want the code, explanation of how I got there ahead:
My first advice was to [...]]]></description>
			<content:encoded><![CDATA[<h2>An update on my latest cairo adventures&#8230;</h2>
<p>When cairo 1.10 comes out we&#8217;ll get a RecordingSurface so you can record commands and play them back to another surface, but how to do something similar now ?</p>
<p>Skip to the end if you just want the code, explanation of how I got there ahead:</p>
<p>My first advice was to try using PDFSurface, and set the file object to None.</p>
<pre class="brush:python"># Record a red rectangle onto a surface.
#
# Create another surface and draw a background on it
# Draw the first surface onto this surface
#
from cairo import PDFSurface, ImageSurface, FORMAT_ARGB32, Context

recording = PDFSurface(None, 200, 200)
target = ImageSurface(FORMAT_ARGB32, 200, 200)

# Record a red rectangle
cr = Context(recording)
cr.set_source_rgb(1.0, 0.0, 1.0)
cr.rectangle(20, 20, 10, 10)

cr.fill_preserve()
cr.set_source_rgb(0.0, 0.0, 1.0)
cr.stroke()

target_context = Context(target)

# Draw background
target_context.set_source_rgb(1.0, 1.0, 0)
target_context.paint()

# Replay recording to target
target_context.set_source_surface(recording)
target_context.paint()

target.write_to_png('output.png')
</pre>
<p>That seems to work, except when I tried in Windows, when it complained that the file object was wrong.</p>
<p>OK, we can work round that:</p>
<pre class="brush:python">def RecordingSurface(w, h):
    if os.name == 'nt':
        fobj = 'nul'
    else:
        fobj = None
    return PDFSurface(fobj, w, h)
</pre>
<p>This seems to be working, but my animation seemed slow&#8230;  time for some benchmarking; I rendered 1000 frames and got a rough wall clock time:<br />
1m48.</p>
<p>Hmm&#8230; perhaps SVGSurface will be quicker:<br />
1m28</p>
<p>This is much better, 20 seconds difference just by changing what kind of surface is returned!</p>
<h3>Animation not smooth though</h3>
<p>The animation still seemed jerky it occured to me that when the surfaces are disposed they will attempt to out their content to the file object !</p>
<p>Luckily, get_similar_surface() comes to the rescue; it returns a surface not associated with a file object.  Using this the original surface can be kept around forever, and never output.</p>
<p>Wallclock time:<br />
50 seconds!</p>
<h3>And here it is:</h3>
<pre class="brush:python">_svg_surface = None
def RecordingSurface(*size):
    '''
    We don't have RecordingSurfaces until cairo 1.10, so this kludge is used

    SVGSurfaces are created, but to stop them ever attempting to output, they
    are kept in a dict.

    When a surface is needed, create_similar is called to get a Surface from
    the SVGSurface of the same size
    '''
    global _svg_surface
    if os.name == 'nt':
        fobj = 'nul'
    else:
        fobj = None
    if _svg_surface is None:
        _svg_surface = SVGSurface(fobj, 0, 0)
    return _svg_surface.create_similar(cairo.CONTENT_COLOR_ALPHA, *size)
</pre>
<p>This is really useful, you can record commands and play them back to other surfaces.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/05/13/cairo-surface-for-recording-commands-and-playback/feed/</wfw:commentRss>
		<slash:comments>0</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 [...]]]></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>Processing with Jython and Nodebox/Shoebot libraries</title>
		<link>http://www.stuartaxon.com/2010/02/10/processing-with-jython-and-nodeboxshoebot-libraries/</link>
		<comments>http://www.stuartaxon.com/2010/02/10/processing-with-jython-and-nodeboxshoebot-libraries/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 22:44:21 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[nodebox]]></category>
		<category><![CDATA[processing]]></category>
		<category><![CDATA[shoebot]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=234</guid>
		<description><![CDATA[Update: 26/April/2010
Problems I was having with incomplete images have been fixed in the current version of the web library, available in shoebots mecurial repository.
Using Processing from Jython is a promising idea, so I took the base from this post on backspaces.net where they explained how to use Jython and built on it a little.
This is [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>Update: 26/April/2010</p>
<p>Problems I was having with incomplete images have been fixed in the current version of the web library, available in shoebots mecurial repository.</p></blockquote>
<p>Using <a href="http://processing.org/">Processing</a> from <a href="http://www.jython.org">Jython</a> is a promising idea, so I took the base from this post on <a href="http://backspaces.net/30/processing-with-jython/">backspaces.net</a> where they explained how to use Jython and built on it a little.</p>
<p>This is great as Shoebot/Nodebox have great libraries for data manipulation, while processing is more focused on graphics.</p>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/slowcessing.png"><img class="alignnone size-medium wp-image-235" title="slowcessing" src="http://www.stuartaxon.com/wp-content/uploads/2010/02/slowcessing-300x203.png" alt="" width="300" height="203" /></a></p>
<p>The result is the attached Netbeans project which demonstrates using the nodebox web library and  drawing with processing.</p>
<h2>Slowcessing</h2>
<p>The glue code is in slowcessing.py</p>
<p>Theres a special version of PApplet (PJApplet), and &#8216;pj_frame&#8217; which can put this in a JFrame.</p>
<p>The other method is &#8217;shoebot_imports&#8217; adds the shoebot imports to the library path</p>
<p>In case anybody doesn&#8217;t want to download the whole project, heres the code:</p>
<p>imagestrip.py</p>
<pre class="brush:python">from slowcessing import PJApplet, pj_frame, shoebot_imports
from processing.opengl import *

shoebot_imports()
import web
import thread

class ImageQueue(list):
    """
    Download images in the background and add them to a list
    """
    def __init__(self, search, size):
        list.__init__(self)
        self._search = search
        self._image_size = size
        thread.start_new_thread(self._get_images, ())

    def _image_downloaded(self, path):
        p = PJApplet()
        self.append(p.loadImage(path))

    def _get_images(self):
        for image in self._search:
            image.download(self._image_size, asynchronous=False)
            self._image_downloaded(image.path)

class WebTest (PJApplet):
  def setup(self):
    self.size(400, 400, self.P3D)
    self.images = ImageQueue(web.morguefile.search("sweets", max=1), size='small')

  def draw(self):
    self.background(0);
    y = (self.height * 0.2) - self.mouseY * (len(self.images) * 0.58)
    for image in self.images:
        self.image(image, 20, y)
        y += image.height

if __name__ == '__main__':
    pj_frame(WebTest)
</pre>
<p>slowcessing.py</p>
<pre class="brush:python">from javax.swing import JFrame

from processing.core import PApplet

class PJApplet(PApplet):
  # rqd due to PApplet's using frameRate and frameRate(n) etc.
  def getField(self, name):
      return PApplet.getDeclaredField(name).get(self)

def pj_frame(pj_applet, **kwargs):
    from time import sleep

    frame = JFrame(kwargs.get('title', 'Slowcessing'))
    frame.defaultCloseOperation = kwargs.get('defaultCloseOperation', JFrame.EXIT_ON_CLOSE)
    frame.resizable = kwargs.get('resizable', False)

    panel = pj_applet()
    frame.add(panel)
    panel.init()

    while panel.defaultSize and not panel.finished:
        sleep(0.5)

    frame.pack()
    frame.visible = 1

    return frame

def shoebot_imports():
    """
    Allow import of the shoebot libraries
    """
    ##APP = 'shoebot'
    import sys
    DIR = sys.prefix + '/share/shoebot/locale'
    ##locale.setlocale(locale.LC_ALL, '')
    ##gettext.bindtextdomain(APP, DIR)
    ###gettext.bindtextdomain(APP)
    ##gettext.textdomain(APP)
    ##_ = gettext.gettext

    LIB_DIR = sys.prefix + '/share/shoebot/lib'
    sys.path.append(LIB_DIR)<span style="text-decoration: line-through;">
</span></pre>
<h2>Problems</h2>
<p>There are some things I couldn&#8217;t work :</p>
<p><span style="text-decoration: line-through;">The callback to say that images have been downloaded happens before the whole file is available, for this reason there are grey parts on the images on the first run.</span></p>
<h3>Nodebox web&#8230;</h3>
<p><span style="text-decoration: line-through;">While I did manage to fix things to get this working in Jython and get Morguefile working, I had a lot of trouble understanding what was going on here.</span></p>
<p>Cheers to Tom De Smedt for fixing these the areas of nodebox-web that I couldn&#8217;t <img src='http://www.stuartaxon.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>Processing&#8230;</h3>
<p>Some parts of PApplet to do with image loading seem to be static, which may also explain problems I was getting with reentrancy.</p>
<h2>Download</h2>
<p>If you want to have a go, you&#8217;ll need to:</p>
<p>Install Netbeans 6.8</p>
<p>Install <a href="http://www.jython.org">Jython</a> (2.5 or higher) by installing the Netbeans python module</p>
<p>Add python to the path (if using Netbeans it&#8217;s copy is where Netbeans is installed).</p>
<p>Get nodebox-web by downloading <a href="https://code.goto10.org/hg/shoebot">shoebot</a> and install it with:</p>
<pre>jython setup.py install</pre>
<p>In Netbeans, add all the jars in the processing\lib folder to the Jython classpath, and opengl\library\opengl.jar<br />
<a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/jythonprocessing.png"><img class="alignnone size-medium wp-image-236" title="jythonprocessing" src="http://www.stuartaxon.com/wp-content/uploads/2010/02/jythonprocessing-300x219.png" alt="" width="300" height="219" /></a></p>
<p>Download the <a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/PythonOnProcessing.zip">PythonOnProcessing</a> (tested on Netbeans 6.8)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/02/10/processing-with-jython-and-nodeboxshoebot-libraries/feed/</wfw:commentRss>
		<slash:comments>2</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 I&#8217;d recommend [...]]]></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 &#8217;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>6</slash:comments>
		</item>
		<item>
		<title>Scripts to help workflow now on google code.</title>
		<link>http://www.stuartaxon.com/2010/01/25/scripts-to-help-workflow-now-on-google-code/</link>
		<comments>http://www.stuartaxon.com/2010/01/25/scripts-to-help-workflow-now-on-google-code/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 14:33:21 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[making windows usable]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[batch]]></category>
		<category><![CDATA[cmd]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[workflow]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=210</guid>
		<description><![CDATA[I&#8217;ve uploaded my scripts to help workflow to google code, naming the project batch flow.
Heres a summary of some of the things you can do.
Clipboard integration
Go to a directory in the clipboard.
If you have the address bar enabled in explorer:
Copy the location, go to the prompt and enter &#8216;pcd&#8217; to go to that folder
Go to [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve uploaded my scripts to help workflow to google code, naming the project <a href="http://code.google.com/p/batch-flow/">batch flow</a>.</p>
<p>Heres a summary of some of the things you can do.</p>
<h2>Clipboard integration</h2>
<h3>Go to a directory in the clipboard.</h3>
<p>If you have the address bar enabled in explorer:</p>
<p>Copy the location, go to the prompt and enter &#8216;pcd&#8217; to go to that folder</p>
<p>Go to the location of a setting in netbeans or eclipse:</p>
<p>Copy the location , go to the prompt and enter &#8216;pcd&#8217; to go to the folder (or folder containing the file).</p>
<h3>Get the current directory without dragging:</h3>
<p>Enter &#8216;ccd&#8217;</p>
<h2>Directory bookmarks</h2>
<p>dirsave and dirload let you save named bookmarks.</p>
<h3>Using hotkeys</h3>
<p>If you use the alternate shell <a href="http://www.jpsoft.com/">4nt</a> (or the free <a href="http://www.jpsoft.com/">TCC/LE</a>) you can use the supplied configuration and aliases to access the bookmark functionality from the keyboard:</p>
<p>In the 4nt or tcc/le prompt enter &#8220;option&#8221;, under the &#8220;TCStart/TCExit&#8221; path, change the location to the location where batch-flow is installed + &#8220;\conf&#8221;, for instance on my computer batch-flow is installed to c:\usr\batch-flow, so I set it to</p>
<pre>c:\usr\batch-flow\conf</pre>
<p>Now in new TCC/LE prompts F5-F10 are reserved for directories: Ctrl+Fkey to save, and Alt+Fkey to load.  Alt-F12 lists these shortcuts.</p>
<p>Note:  Alt-F12 only lists shortcuts on FKeys, to list these and other shortcuts enter dirload /l</p>
<blockquote><p>batch-flow comes with other handy hotkeys, use &#8216;alias&#8217; in TCC/LE to see what they are.</p></blockquote>
<h2>Path manipulation</h2>
<h3>addpath</h3>
<p>It&#8217;s annoying after installing a program to have to add it to the path, so there is an &#8216;addpath&#8217; command to do this.</p>
<h3>regpath</h3>
<p>This is a more general utility for viewing the registry path, you can list it, validate it, check for the location of files within it.</p>
<p>Also useful is &#8216;regpath /L&#8217; which sets the local prompts path to the one in the registry.</p>
<h2>Further help</h2>
<p>Most of the commands have help builtin, which you can access by using the /? option.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/01/25/scripts-to-help-workflow-now-on-google-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Access files in a Linux virtual machine from Windows</title>
		<link>http://www.stuartaxon.com/2010/01/21/access-files-in-a-linux-virtual-machine-from-windows/</link>
		<comments>http://www.stuartaxon.com/2010/01/21/access-files-in-a-linux-virtual-machine-from-windows/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 04:46:17 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ext3]]></category>
		<category><![CDATA[filesystem]]></category>
		<category><![CDATA[interoperability]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[virtual-machine]]></category>
		<category><![CDATA[vm]]></category>
		<category><![CDATA[vmware]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[workflow]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=195</guid>
		<description><![CDATA[I recently found a neat way of accessing files in a linux VMWare image.   This is really useful, as theres never really a good time to break your VMWare image, this is also handy if you don&#8217;t want to run the whole machine, but just access the files inside.
There is one caveat:

It only works if [...]]]></description>
			<content:encoded><![CDATA[<p>I recently found a neat way of accessing files in a linux VMWare image.   This is really useful, as theres never really a good time to break your VMWare image, this is also handy if you don&#8217;t want to run the whole machine, but just access the files inside.</p>
<p>There is one caveat:</p>
<ul>
<li>It only works if the filesystem is ext2 (ext3 works, and ext4 probably works).</li>
</ul>
<h2>Install VMWare DiskMount Utility</h2>
<p>Accept the EULA, download and install the <a href="http://www.vmware.com/download/eula/diskmount_ws_v55.html">VMWare DiskMount utility</a>.</p>
<p>For convenience add the utilities folder to the path:</p>
<pre>C:\Program Files\VMware\VMware DiskMount Utility</pre>
<blockquote><p>Do this through the Windows Gui, or even use my <a href="http://code.google.com/p/batch-flow/">addpath</a> utility.</p></blockquote>
<p>At this point you can mount Windows VMWare images.</p>
<p>The usage is:  <em>vmware-mount drive-letter vmdk-image</em>.</p>
<p>Heres how I mount my Ubuntu image to the j: drive</p>
<blockquote>
<pre>[C:\vmware\Ubuntu]vmware-mount j: ubuntu.vmdk</pre>
<pre>[C:\vmware\Ubuntu]</pre>
</blockquote>
<p>No output here indicates success.</p>
<p>At this point everything seems fine, but a crucial piece of the puzzle is still missing; try and view the files and you still can&#8217;t:</p>
<p style="text-align: center;"><a href="http://www.stuartaxon.com/wp-content/uploads/2010/01/vmware-mount-no-ext2.png"><img class="size-full wp-image-198 aligncenter" title="vmware-mount-no-ext2" src="http://www.stuartaxon.com/wp-content/uploads/2010/01/vmware-mount-no-ext2.png" alt="Failing to see files in an ext2 VMWare image" width="677" height="340" /></a></p>
<div style="clear:both;"></div>
<p>The next step is to make Windows understand the ext2 filesystem, using a special driver.</p>
<h2>Install ext2ifs</h2>
<p>Grab ext2ifs from <a href="http://www.fs-driver.org/">www.fs-driver.org</a> and install.</p>
<p>If the following steps don&#8217;t work then you may need to reboot.</p>
<h2>Thats it!</h2>
<p>You should be now able to access files inside your VMWare image (assuming it&#8217;s ext2 and not reiserfs), remount the image and have a go:</p>
<p>In my case I did:</p>
<blockquote>
<pre>[C:\vmware\Ubuntu]vmware-mount j: ubuntu.vmdk</pre>
<pre>[C:\vmware\Ubuntu] dir j:</pre>
</blockquote>
<p>Heres the output &#8211; hooray, I can copy my work out of the image !</p>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/01/vmware-mount-and-ext2ifs.png"><img class="size-full wp-image-197 aligncenter" title="vmware-mount-and-ext2ifs" src="http://www.stuartaxon.com/wp-content/uploads/2010/01/vmware-mount-and-ext2ifs.png" alt="Viewing files inside a VMWare image with ext2fs" width="677" height="580" /></a></p>
<div style="clear:both;"></div>
<p>This is very useful, especially if you do dist-upgrade in ubuntu and can&#8217;t access the network.</p>
<h2>Bonus tip:</h2>
<p>Newer versions of VMWare player let you install VMWare tools from inside the GUI, this is another way to fix the kind of catestrophic problems you can cause yourself by accidentally upgrading the kernel in an image.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/01/21/access-files-in-a-linux-virtual-machine-from-windows/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Some useful scripts for windows.</title>
		<link>http://www.stuartaxon.com/2009/09/06/some-useful-scripts-for-windows/</link>
		<comments>http://www.stuartaxon.com/2009/09/06/some-useful-scripts-for-windows/#comments</comments>
		<pubDate>Sun, 06 Sep 2009 01:32:43 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[making a really nice work environment in windows]]></category>
		<category><![CDATA[making windows usable]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=185</guid>
		<description><![CDATA[Stoyan of PHPIED.com has found the joy using javascript for scripting in the OS&#8230;
I&#8217;ve put up a few scripts I find useful in windows (download at the end of the article):

addpath.js &#8211; Add a path to the registry path.
dt.cmd &#8211; Change to desktop folder.
e.cmd &#8211; Open explorer in current or specified folder.
regpath.js  &#8211; Output the [...]]]></description>
			<content:encoded><![CDATA[<p>Stoyan of PHPIED.com has found the joy using <a href="http://www.phpied.com/javascript-shell-scripting/">javascript for scripting in the OS</a>&#8230;</p>
<p>I&#8217;ve put up a few scripts I find useful in windows (download at the end of the article):</p>
<ul>
<li>addpath.js &#8211; Add a path to the registry path.</li>
<li>dt.cmd &#8211; Change to desktop folder.</li>
<li>e.cmd &#8211; Open explorer in current or specified folder.</li>
<li>regpath.js  &#8211; Output the path stored in the registry.</li>
<li>updateenvironment.js &#8211; Updates running apps with any changed settings in the registry.</li>
</ul>
<p>And a couple that use <a href="http://www.python.org/download/">python</a> and <a href="http://sourceforge.net/projects/pywin32/">pywin32</a>:</p>
<ul>
<li>ccwd.py &#8211; Copy the current working directory to the clipboard</li>
<li>cpath.py &#8211; Copy the current path to the clipboard</li>
</ul>
<p>All of have acompanying batch files to run them, I generally have everything in a folder c:\usr\cmd, but they should work from anywhere in the path.</p>
<p>Download  <a href="http://www.stuartaxon.com/wp-content/uploads/2009/09/cmd.zip">cmd.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2009/09/06/some-useful-scripts-for-windows/feed/</wfw:commentRss>
		<slash:comments>0</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[Uncategorized]]></category>
		<category><![CDATA[projects]]></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 (in vmware), [...]]]></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/">&#8217;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>&#8217;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>&#8217;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>
		<item>
		<title>The Bloggage and slacking</title>
		<link>http://www.stuartaxon.com/2009/08/07/the-bloggage-and-slacking/</link>
		<comments>http://www.stuartaxon.com/2009/08/07/the-bloggage-and-slacking/#comments</comments>
		<pubDate>Fri, 07 Aug 2009 01:28:25 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=150</guid>
		<description><![CDATA[Just been checking out what Mr Palmer has been up to&#8230; quite a lot it seems&#8230;   if I could get further than 2 chapters in 6 months with Getting Things Done maybe I could stop procrastination and start GTD too  
And I&#8217;ve been checking out some online comics&#8230;
My 6 monthlyish check on SayUncle comics [...]]]></description>
			<content:encoded><![CDATA[<p>Just been checking out what <a href="http://brettpalmergroup.webs.com/apps/blog/">Mr Palmer</a> has been up to&#8230; quite a lot it seems&#8230;   if I could get further than 2 chapters in 6 months with Getting Things Done maybe I could stop procrastination and start GTD too <img src='http://www.stuartaxon.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>And I&#8217;ve been checking out some online comics&#8230;</p>
<p>My 6 monthlyish check on <a href="http://sayunclecomics.livejournal.com/">SayUncle comics blog</a> always makes me want to do some drawing.</p>
<p>Also Quite enjoying the <a href="http://nedroidcomics.livejournal.com/240308.html">Beartato in space storyline</a> in nedroid.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2009/08/07/the-bloggage-and-slacking/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
