<?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"
	>

<channel>
	<title>talkingCode</title>
	<atom:link href="http://talkingcode.co.uk/feed/" rel="self" type="application/rss+xml" />
	<link>http://talkingcode.co.uk</link>
	<description>Linux, Software Development, Technology</description>
	<pubDate>Sun, 07 Jun 2009 14:59:47 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<item>
		<title>iPojoRC - An iPOJO-based OSGi IRC Bot</title>
		<link>http://talkingcode.co.uk/2009/06/07/ipojorc-an-ipojo-based-osgi-irc-bot/</link>
		<comments>http://talkingcode.co.uk/2009/06/07/ipojorc-an-ipojo-based-osgi-irc-bot/#comments</comments>
		<pubDate>Sun, 07 Jun 2009 14:59:13 +0000</pubDate>
		<dc:creator>codders</dc:creator>
		
		<category><![CDATA[code]]></category>

		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://talkingcode.co.uk/?p=57</guid>
		<description><![CDATA[I&#8217;ve been doing a fair bit of work recently in OSGi land. OSGi is a dynamic module system for Java designed to facilitate the creation, distribution and consumption of modular Java code. The idea is that anybody who has an application running on an OSGi platform implementation (Felix, Equinox) can retrieve your module (optionally stored [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing a fair bit of work recently in <a href="http://www.osgi.org/">OSGi</a> land. OSGi is a dynamic module system for Java designed to facilitate the creation, distribution and consumption of modular Java code. The idea is that anybody who has an application running on an OSGi platform implementation (<a href="http://felix.apache.org/">Felix</a>, <a href="http://www.eclipse.org/equinox/">Equinox</a>) can retrieve your module (optionally stored in an <a href="http://www.osgi.org/Repository">OBR</a>) and have it load in to their running system without upsetting anything. Exactly how well the hot-swapping of bundles works depends heavily on how well the application is written and how well the bundle being loaded / unloaded is written, but it can be made to work.</p>
<h3>The Whiteboard Pattern</h3>
<p>I&#8217;m not quite sure why it&#8217;s called a <a href="http://www.osgi.org/wiki/uploads/Links/whiteboard.pdf">whiteboard pattern</a>, but one of the neat things about the OSGi platform is the service registry. Service consumers and producers interact through the service registry that the platform provides, which takes care (in principle) of service lifecycle and dependency resolution. A correctly written service only becomes available to a correctly written consumer when the service&#8217;s dependencies have been met and its initialisation is complete. If the dependencies of any service are no longer satisfied (because of the disappearance of a required bundle), the service is removed from the registry and consumers are notified. Not rocket science, but saves developers a fair bit of effort and makes interoperable components easier to write. </p>
<p>The canonical example of the whiteboard pattern is <a href="http://www.theserverside.com/tt/articles/article.tss?l=WhiteboardForOSGi">an IRC bot whose commands are implemented as services</a>. In this example, an IRC Bot is created that maintains its connection to the IRC server while commands are loaded and unloaded from the Bot on the fly. Here, the ServiceTracker is used to listen for the appearance and disappearance of bundles. Neat, but there&#8217;s still some associated boilerplate:</p>
<pre>
  private ServiceTracker serviceTracker;

  public void start(BundleContext context) throws Exception {
    serviceTracker = new ServiceTracker(context,
                              MyTrackedService.class.getName(), null);
    serviceTracker.open();
    ... startup code...
  }

  public void doStuff() {
    Object[] implementors = serviceTracker.getServices();
    if (implementors != null &#038;&#038; implementors.length > 0) {
      for (Object o : implementors) {
        MyService myService = (MyService) o;
        &#8230; do stuff&#8230;
      }
    }
  }

  public void stop(BundleContext context) throws Exception {
    serviceTracker.close();
    serviceTracker = null;
    &#8230; shutdown code &#8230;
  }
</pre>
<h3>iPOJO</h3>
<p><a href="http://felix.apache.org/site/ipojo-concepts-overview.html">iPOJO</a> attempts to reduce this boilerplate and make service registration and listening even simpler. Under iPOJO, the boilerplate is reduced to:</p>
<pre>
  @Requires
  private MyService[] implementors;
</pre>
<p>plus some hand waving. iPOJO takes care of making sure that the <em>implementors</em> array contains registered implementations of <em>MyService</em> - all your application has to do is iterate over them.</p>
<h3>iPojoRC</h3>
<p>With a view to having a play around with this stuff, I thought I&#8217;d implement the IRC Bot using iPOJO. You can find the fruits of that labour on <a href="http://github.com/codders/ipojorc/">my github account</a>. It seems to work pretty well. I&#8217;ve so far not had a problem adding and removing commands on the fly. It&#8217;s even possible (if you&#8217;re really careful with versions) to rev parts of the IRCCommand API and have the old and new versions running side by side, but in practice it&#8217;s much easier just to <em>mvn clean install</em>.</p>
<h3>Why?</h3>
<p>Summut to do, innit. More seriously, OSGi seems to be gaining ground as a way of building and distributing Java applications. It plays very nicely with Maven and there are some quite neat bundles available that you can just drop in to your application with very little wiring. That said, one of the challenges of OSGi is dealing with packages and dependencies when you create your own bundles. Most of the tutorials recommend starting with all your code in a single bundle, with good reason - I invariably spend more time sorting out dependency and classloader issues with my bundles than I do writing the code inside them. If you&#8217;re going to start a serious OSGi project, it&#8217;s good to have experience of bundling simple things and the IRC Bot is a great example of simple code in many bundles.</p>
]]></content:encoded>
			<wfw:commentRss>http://talkingcode.co.uk/2009/06/07/ipojorc-an-ipojo-based-osgi-irc-bot/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Mysterious ClassCastException from Scala</title>
		<link>http://talkingcode.co.uk/2009/05/19/mysterious-classcastexception-from-scala/</link>
		<comments>http://talkingcode.co.uk/2009/05/19/mysterious-classcastexception-from-scala/#comments</comments>
		<pubDate>Tue, 19 May 2009 20:33:44 +0000</pubDate>
		<dc:creator>codders</dc:creator>
		
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://talkingcode.co.uk/?p=56</guid>
		<description><![CDATA[So here&#8217;s one that&#8217;s got me thinking. I think this is a fairly straightforward use case, but maybe I&#8217;m doing something odd. I have an application where I&#8217;m putting objects in to a hash and I want to be able to pull them out with the &#8220;correct&#8221; types. Which is to say I want to [...]]]></description>
			<content:encoded><![CDATA[<p>So here&#8217;s one that&#8217;s got me thinking. I think this is a fairly straightforward use case, but maybe I&#8217;m doing something odd. I have an application where I&#8217;m putting objects in to a hash and I want to be able to pull them out with the &#8220;correct&#8221; types. Which is to say I want to be able not to have to cast the objects on their way out but rather have their types inferred by their use context.</p>
<p>The following code compiles. There&#8217;s a method where I&#8217;m putting the type hints in, a method where I&#8217;m not, and a method where I&#8217;m passing the retrieved hash value directly to an explicitly typed function. In all three cases, at least in principle, the runtime types should match - I&#8217;m putting in a String, I expect a String out the other side.</p>
<p>There is, so we&#8217;re clear, a runtime cast (call to asInstanceOf), but this is where I&#8217;m expecting the developer using my class to be right. And where they&#8217;re right, what I don&#8217;t expect is a ClassCastException.</p>
<pre>
import scala.collection.mutable.Map

object Main {
  def printIt(optString: Option[String])
  {
    optString match
    {
      case x: Some[_] =&gt; println(&#8221;Got: &#8221; + x.get.substring(0,2))
      case None =&gt; println(&#8221;Got nothing&#8221;)
    }
  }

  def withInferredType(token: Token)
  {
    println(&#8221;\n&#8212; With Inferred Type &#8212;&#8221;)

    val fish = token.get(&#8221;fish&#8221;)
    printIt(fish)
  }

  def withoutExplicitType(token: Token)
  {
    println(&#8221;\n&#8212; Without Explicit Type &#8212;&#8221;)

    val fish = token.get(&#8221;fish&#8221;)
    fish match
    {
      case x: Some[_] =&gt; println(&#8221;Got: &#8221; + x.get.substring(0,2))
      case None =&gt; println(&#8221;Got nothing&#8221;)
    }
  }

  def withExplicitType(token: Token)
  {
    println(&#8221;\n&#8212; With Explicit Type &#8212;&#8221;)

    val fish = token.get[String](&#8221;fish&#8221;)
    fish match
    {
      case x: Some[_] =&gt; println(&#8221;Got: &#8221; + x.get.substring(0,2))
      case None =&gt; println(&#8221;Got nothing&#8221;)
    }
  }

  def main(args: Array[String])
  {
    val token = new Token
    token.put(&#8221;fish&#8221;, &#8220;cat&#8221;)
    withExplicitType(token)
    withInferredType(token)
    withoutExplicitType(token)
  }
}

class Token()
{
  private var elements = Map[String,Object]()

  def get[A &lt;: Object](key: String): Option[A] =
  {
    for (val value &lt;- elements.get(key))
      return Some(value.asInstanceOf[A])
    return None
  }

  def put[A &lt;: Object](key: String, value: A)
  {
    elements.put(key, value)
  }
}
</pre>
<p>resulting in:</p>
<pre>
 scalac Token.scala &#038;&#038; scala Main

--- With Explicit Type ---
Got: ca

--- With Inferred Type ---
Got: ca

--- Without Explicit Type ---
java.lang.ClassCastException: java.lang.String cannot be cast to scala.runtime.RichString
        at Main$.withoutExplicitType(Token.scala:29)
        at Main$.main(Token.scala:52)
        at Main.main(Token.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at scala.tools.nsc.ObjectRunner$$anonfun$run$1.apply(ObjectRunner.scala:75)
        at scala.tools.nsc.ObjectRunner$.withContextClassLoader(ObjectRunner.scala:49)
        at scala.tools.nsc.ObjectRunner$.run(ObjectRunner.scala:74)
        at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:154)
        at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
</pre>
<p>In all three cases I&#8217;m doing the same thing with the same data. In the &#8216;Inferred Type&#8217; case, it&#8217;s actually doing the thing I want in production. But all three cases compile and one throws a ClassCastException - I had very much hoped that the type system would pick me up on the broken case.</p>
<p>What am I doing wrong, lazyweb? Any comments greatly appreciated.</p>
<h3>Considered Harmful</h3>
<p>Morning. I&#8217;ve had a think about it and as usual with me writing about Scala, it&#8217;s my mistake rather than the language&#8217;s. What I&#8217;d hoped to achieve was something like duck-typing where I could pull something out of the hash and use it as whatever made sense in the code. Static type inference doesn&#8217;t work this way though.</p>
<p>In the above code, in the two cases where I was constraining the type, it works fine. In the case where I don&#8217;t constrain the type, Scala can legitimately choose any type that implements <em>substring</em>; in this case it chose <em>RichString</em>, which happens not to be the type I put in to the hash. In general, this is a pretty dangerous approach - what I want is for the type system to force me to nominate a type for the result of the <em>get</em> before I use it.</p>
<p>Turns out the way to do this is to have <em>get</em> return <em>Object</em> and use <em>asInstanceOf</em> at the call site. C&#8217;est la vie.</p>
]]></content:encoded>
			<wfw:commentRss>http://talkingcode.co.uk/2009/05/19/mysterious-classcastexception-from-scala/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A modest copyright reform proposal</title>
		<link>http://talkingcode.co.uk/2009/04/20/a-modest-copyright-reform-proposal/</link>
		<comments>http://talkingcode.co.uk/2009/04/20/a-modest-copyright-reform-proposal/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 13:13:36 +0000</pubDate>
		<dc:creator>codders</dc:creator>
		
		<category><![CDATA[rant]]></category>

		<guid isPermaLink="false">http://talkingcode.co.uk/?p=55</guid>
		<description><![CDATA[Copyright law is a little bit broken. Lawrence thought (thinks, presumably) so, Rufus thinks so, I think so. What&#8217;s to be done though? Efforts at legislative reform have, to date, been pretty ineffective. The issues are complex and difficult for laypeople to understand / care about, the opposing lobbyists are a powerful bunch, and it&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>Copyright law is a little bit broken. <a href="http://lessig.org/blog/2008/01/last_free_culture_lecture_firs.html">Lawrence</a> thought (thinks, presumably) so, <a href="http://www.rufuspollock.org/2009/04/02/talk-on-copyright-enforcement-at-juri-working-group-on-authors-rights/">Rufus</a> thinks so, I think so. What&#8217;s to be done though? Efforts at legislative reform have, to date, been pretty ineffective. The issues are complex and difficult for laypeople to understand / care about, the opposing lobbyists are a powerful bunch, and it&#8217;s hard even to convince artists in whose interest copyright should be reformed of the benefits of doing so. How might we possibly fix it?</p>
<p>I&#8217;m going to keep my proposal brief, partly to avoid TL;DR-ism, and partly because it&#8217;s probably garbage, but here goes.</p>
<h2>Creative Commons over Time</h2>
<p>Legislative reform is a tough battle. Let&#8217;s just side-step it. Take the existing <a href="http://creativecommons.org/about/licenses/">CC licenses</a> and extend them to allow CC/T; the creator retains all the rights to their work afforded under &#8220;default&#8221; copyright until a nominated date, after which the work is covered by the nominated CC license. Instead of saying &#8220;CC BY SA&#8221;, you&#8217;d say &#8220;CC BY SA / T2015&#8243;. Until the expiry date is reached, the creator can exploit the work in whatever way they see fit, just as they can today under the &#8220;default&#8221; copyright regime.</p>
<h3>How does that help?</h3>
<p>The idea here (and I confess I&#8217;ve not talked to any artists) is that going completely CC is scary for artists whose living is made from their creative output. As fervently as you might believe their work would be better served by a CC license, it&#8217;s really tough to persuade people to &#8220;give away&#8221; their livelihoods. Instead, the pitch goes like this&#8230; Their work is going to end up in the public domain; everything created today is implicitly &#8220;PD / T2150&#8243; (let&#8217;s say). All I&#8217;m proposing is that instead of using the default date, they choose a date themselves and a license for use after the date has passed. They might well choose &#8220;CC / T2100&#8243;, or &#8220;CC / T2050&#8243;, but it&#8217;d be an improvement.</p>
<h3>Raising awareness</h3>
<p>In and of itself, that won&#8217;t achieve anything, but if you can convince artists to take control over the relationship between their work and society, that&#8217;s already a small win. The bigger win will require use of technology. Assuming some plucky evangelist can persuade artists to start using these licenses, the next step is to write a webservice to map the (for instance) <a href="http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/">ASIN</a> for a CD / track / book to an expiry date. That done, you could a) set up you own shop highlighting the expiry date on the items or b) write a <a href="https://addons.mozilla.org/firefox/addon/748">GreaseMonkey</a> script to overlay the expiry date on Amazon&#8217;s existing shop. You could colour code works - Red for &#8220;PD / T2150&#8243;, Green if the creator has nominated an expiry date (we needn&#8217;t be any more divisive than that to begin with).</p>
<h3>Working out the &#8220;correct&#8221; term</h3>
<p>The plan, in case it&#8217;s not clear, is to let the market work out the &#8220;right&#8221; value for copyright term without global multilateral legislative reform. <b>If</b> you can get adoption and <b>if</b> you can raise awareness and <b>if</b> consumers actually care, what you might hope to see is a dutch auction in copyright term lengths. Artists could compete to best serve their fans by varying the amount of time they felt they needed to profit from a work. This won&#8217;t necessarily be the optimal value for society (consumers may underestimate the value to them of reduced term), but one would hope we&#8217;d end up with a smaller number for copyright term than that selected by legislation.</p>
<h3>What about artists&#8217; retirements?</h3>
<p>It&#8217;s a commonly held misconception that part of copyright&#8217;s role is as a pension scheme for aging artists or a life insurance policy for their families. Society affords artists a temporary monopoly on their work so as to encourage them to create more work, on the understanding that the work is donated to the commons after that monopoly expires. It&#8217;s easy to find examples of outliers for whom extended term is a key concern, but the majority of artists won&#8217;t see continued revenue from their work that is anything like as substantial as the value to society of having all that work in the public domain. If they&#8217;re looking for a pension / insurance scheme one might politely suggest that they should invest in a pension / insurance scheme.</p>
<h3>Won&#8217;t we just end up eating our CC babies?</h3>
<p>There is obviously a risk in this that artists who might otherwise choose a pure CC license end up choosing to exploit their works under a CC/T license. Much like GPL vs. LGPL, we&#8217;d obviously prefer that CC/T licenses didn&#8217;t exist at all lest they tempt people away from the &#8220;right&#8221; answer. I think it&#8217;s a risk worth taking to try and accelerate the copyfight and get people thinking about the relationship between copyrighted work and society.</p>
]]></content:encoded>
			<wfw:commentRss>http://talkingcode.co.uk/2009/04/20/a-modest-copyright-reform-proposal/feed/</wfw:commentRss>
		</item>
		<item>
		<title>My new game - Civil Liberties Trolling</title>
		<link>http://talkingcode.co.uk/2009/03/25/my-new-game-civil-liberties-trolling/</link>
		<comments>http://talkingcode.co.uk/2009/03/25/my-new-game-civil-liberties-trolling/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 07:26:53 +0000</pubDate>
		<dc:creator>codders</dc:creator>
		
		<category><![CDATA[rant]]></category>

		<guid isPermaLink="false">http://talkingcode.co.uk/?p=54</guid>
		<description><![CDATA[I know, I know. You prefer the posts about code. Go read JSR #170, #277, #283, #311, revise the two kinds of JMS and have a butchers at JPA. That&#8217;ll keep you occupied while I rant.
So. Cory writes to tell us of an exciting new police initiative (hot-linked here - could change to goatse at [...]]]></description>
			<content:encoded><![CDATA[<p>I know, I know. You prefer the posts about code. Go read JSR #170, #277, #283, #311, revise the two kinds of JMS and have a butchers at JPA. That&#8217;ll keep you occupied while I rant.</p>
<p>So. <a href="http://www.boingboing.net/2009/03/24/london-cops-reach-ne.html">Cory writes</a> to tell us of an exciting new police initiative (hot-linked here - could change to goatse at any moment):</p>
<p><img src="http://craphound.com/images/street_chemicals_cctv.jpg" alt="Police Initiative" /></p>
<p>Yay. But does taking photos of CCTV cameras make you a terrorist? I&#8217;ve decided to find out. To play my new game, you will need:</p>
<ul>
<li>A Nokia Series 60 3rd Edition phone with internet connection</li>
<li>A <a href="http://betalabs.nokia.com/betas/view/location-tagger">geo-tagging application</a></li>
<li>A <a href="http://www.flickr.com">Flickr account</a> that you&#8217;ve enabled for <a href="http://www.flickr.com/account/geo/exif">auto geotagging</a></li>
<li>An app to <a href="http://www.symbian-freeware.com/download-shozu-share-it-s60-3rd-edition.html">upload your photos to Flickr</a></li>
</ul>
<p>Now all you have to do is snap pictures of the cameras you find and upload them to Flickr before the police confiscate your camera. Of course, you can delete the photos from your phone the second they&#8217;re uploaded. No point leaving them hanging around - at best you&#8217;ll look like a weirdo in the unlikely event that the police go rifling through your personal property.</p>
<p>Here&#8217;s <a href="http://www.flickr.com/photos/36693923@N05/map/">my photo stream</a> - where&#8217;s yours? (Remember to tag your photos &#8216;cctvfun&#8217;).</p>
<h2>Aren&#8217;t you helping the terrorists?</h2>
<p>Let&#8217;s get some perspective. You&#8217;re still more likely to die <a href="http://www.nationmaster.com/graph/mor_dro_and_sub_whi_in_bat_tub-drowning-submersion-while-bath-tub">in your bath</a> than you are to die <a href="http://www.nationmaster.com/graph/mor_exp-mortality-explosions">in an explosion</a>. If people photographing CCTV cameras represents a significant threat to everyone&#8217;s safety, we should make some kind of law against it. At least that way there would be some kind of review of whether or not such a restriction on our freedoms makes sense and is proportionate to the threat. We shouldn&#8217;t allow the police to make up their own laws - that way madness lies.</p>
<p>As long as it&#8217;s legal to do so (and possibly even after it stops being legal to do so), I would encourage everyone to join in my new game and help redress the balance of surveillance.</p>
]]></content:encoded>
			<wfw:commentRss>http://talkingcode.co.uk/2009/03/25/my-new-game-civil-liberties-trolling/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Abstract Type Members - Augmenting Scala classes</title>
		<link>http://talkingcode.co.uk/2009/03/11/abstract-type-members-augmenting-scala-classes/</link>
		<comments>http://talkingcode.co.uk/2009/03/11/abstract-type-members-augmenting-scala-classes/#comments</comments>
		<pubDate>Wed, 11 Mar 2009 22:28:27 +0000</pubDate>
		<dc:creator>codders</dc:creator>
		
		<category><![CDATA[code]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://talkingcode.co.uk/?p=53</guid>
		<description><![CDATA[So, Scala&#8217;s cool.
About a month ago, a colleague was whining about having to write Java and it was hard not to sympathise. He&#8217;s a Python man, and Java&#8217;s Kingdom Of Nouns can seem a little clumsy. Sometimes, you just want to map{}, and trying to do that in Java can leave you feeling dirty.
There are [...]]]></description>
			<content:encoded><![CDATA[<p>So, Scala&#8217;s cool.</p>
<p>About a month ago, a colleague was whining about having to write Java and it was hard not to sympathise. He&#8217;s a Python man, and Java&#8217;s <a href="http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html">Kingdom Of Nouns</a> can seem a little clumsy. Sometimes, you just want to map{}, and trying to do that in Java can leave you feeling dirty.</p>
<p>There are proposals for first class functions and <a href="http://www.javac.info/">closures in Java</a> - <a href="http://gafter.blogspot.com/">Neal Gafter</a> is your man there. They look fun n&#8217;all, but they are apparently a little way off. What I needed in order to silence my colleague was less irritating Java in production straight away. In order to satisfy the needs of m&#8217;colleague, m&#8217;self and m&#8217;company I would need a couple of things.</p>
<p><b>Pour lui</b></p>
<ul>
<li>Concise variable declarations - none of this
<pre>Map&lt;String,List&lt;Integer&gt;&gt; map = new HashMap&lt;String, List&lt;Integer&gt;&gt;()</pre>
<p> nonsense</li>
<li>Functions as first class values</li>
<li>Excellent library support</li>
</ul>
<p><b>Pour moi</b></p>
<ul>
<li>Strong, static typing</li>
<li>Eclipse integration</li>
<li>Monads. Everybody loves monads</li>
</ul>
<p><b>For practicality&#8217;s sake</b></p>
<ul>
<li>Maven integration</li>
<li>Interoperation with the existing Java code base</li>
</ul>
<p>I had a look on <a href="http://en.wikipedia.org/wiki/List_of_JVM_languages">Wikipedia for a suitable JVM language</a> since that would ensure the easy interoperation and give us a decent set of libraries. It turns out <a href="http://www.scala-lang.org">Scala</a> has everything we need. It&#8217;s mixed paradigm functional / object-oriented, it&#8217;s got a <a href="http://en.wikipedia.org/wiki/Type_inference">Hindley-Milner style type inference</a> system, and it&#8217;s got a really active community. The eclipse/maven integration isn&#8217;t <em>quite</em> there yet, but it gets much better as you get closer to the bleeding edge.</p>
<h2>Some Code</h2>
<p>There have been too many cool things to mention really, but here&#8217;s the first one that seemed apt for a blog post. Scala has some nice XML support, but lacks some of the functions you might like on an XML Node like, for example, &#8216;getAttributeValue(attributeName)&#8217;. In Haskell, you could define a new <a href="http://www.haskell.org/tutorial/classes.html">typeclass</a> and create an instance for Node. In Java / C++ you could <a href="http://en.wikipedia.org/wiki/Delegation_pattern">delegate</a> (if you like pain). In Ruby, you could <a href="http://en.wikipedia.org/wiki/Mixin">mixin</a>. The answer in Scala appears to be&#8230; an Abstract Type Member.</p>
<p><b>Disclaimer:</b><br />
I don&#8217;t know what the right answer actually is, but this works and seems kinda cool</p>
<pre>
import scala.xml.NodeSeq
import scala.xml.Node

object XmlTest
{
  implicit def nodeToNodePlus(node: Node):NodePlus =
  {
    return new NodePlus { type T = Node; val init = node }
  }

  abstract class NodePlus
  {
    type T <: scala.xml.Node
    val init: T
    private var value: T = init

    def getAttributeValue(name: String): String =
    {
      return value.attribute(name).get.first.text
    }
  }

  def main(args: Array[String])
  {
    println("Hello")
    val xmlDoc = &lt;hi&gt;&lt;hello id="world"/&gt;&lt;/hi&gt;
    val hello = (xmlDoc\"hello").first
    println(hello.getAttributeValue("id"))
  }
}
</pre>
<p>The mechanics of what&#8217;s going on there are&#8230; err&#8230; pretty opaque to me. But to break that down a little:</p>
<ul>
<li>An <em>object</em> is a singleton class, equivalent in most senses to a static class in Java.</li>
<li>An <em>implicit</em> is a function from A to B which the compiler will use whenever inference tells it that you need a B but have an A (yes, evil, but okay if used carefully).</li>
<li><em>type T</em> is an Abstract Type Member. I think.</li>
<li><em>&lt;:</em> is a subclass restriction</li>
</ul>
<p>&#8230; all of which allows me to introduce a new function to an existing class without access to that class&#8217;s constructor. Handy.</p>
<p>That&#8217;s probably garbage. No doubt I&#8217;ll find out that&#8217;s not the way to do it or that it won&#8217;t do what I expect, but it seems to work. The take-away is that Scala is an easy transition from Java, is much prettier and cooler, and that I can&#8217;t think of a good reason to write any more Java code.</p>
<h2>&#8230; having slept on it&#8230;</h2>
<p>Ah. You see. What I did there was&#8230; I got carried away. My NodePlus class is actually no better than a wrapper - I can&#8217;t actually do any Node operations on it. The <em>implicit</em> mechanism makes it look like I can, but I can&#8217;t. And the Abstract Type Member was a bit of a red herring. What the Abstract Type Member is doing is letting me parameterise my type which is, I guess, a kind of useful. Given that Scala types accept formal parameters, though, it&#8217;s not completely clear how much win is involved.</p>
<p>I&#8217;ll let you know if I find out how to do the thing I actually want to do.</p>
]]></content:encoded>
			<wfw:commentRss>http://talkingcode.co.uk/2009/03/11/abstract-type-members-augmenting-scala-classes/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Me, the IWF and child porn</title>
		<link>http://talkingcode.co.uk/2009/03/02/me-the-iwf-and-child-porn/</link>
		<comments>http://talkingcode.co.uk/2009/03/02/me-the-iwf-and-child-porn/#comments</comments>
		<pubDate>Mon, 02 Mar 2009 13:33:15 +0000</pubDate>
		<dc:creator>codders</dc:creator>
		
		<category><![CDATA[rant]]></category>

		<guid isPermaLink="false">http://talkingcode.co.uk/?p=52</guid>
		<description><![CDATA[I went to the Convention on Modern Liberty on Saturday, which was a pleasure to attend. It was great to be in the company of vaguely like-minded people who care deeply about the [alleged] slow but steady erosion of our civil liberties, and to hear some compelling arguments that the danger to our freedom is [...]]]></description>
			<content:encoded><![CDATA[<p>I went to the <a href="http://www.modernliberty.net/">Convention on Modern Liberty</a> on Saturday, which was a pleasure to attend. It was great to be in the company of vaguely like-minded people who care deeply about the [alleged] slow but steady erosion of our civil liberties, and to hear some compelling arguments that the danger to our freedom is real (not just a figment of my fevered imagination).</p>
<p>One of the morning sessions in Cambridge was a discussion about censorship and the role of the <a href="http://www.iwf.org.uk/">IWF</a> and, being fairly strongly anti-censorship, I chose to go to that session. Long story short, I <em>may</em> have gone on record defending my right to view images of child abuse. I don&#8217;t think I made my point as eloquently as I might have done, so I thought I&#8217;d summarise the issue here.</p>
<h2>The Role of the IWF</h2>
<p>I should start by saying that I think the IWF does &#8220;a good thing&#8221;. As an organisation, they&#8217;re run fairly openly and one of their many functions is to be the UK&#8217;s notice and take down body. If you have a problem with the UK internet and you want to get it sorted, they&#8217;re the people to contact. As such, they are a fairly innocuous alternative to regulation of the UK internet which, I believe, would be a pretty bad idea. Their primary function is not the blocking of child pornography / images of abuse for which they have become so (in)famous recently, and I was pleased that their representative there (<a href="http://www.iwf.org.uk/media/page.66.204.htm">Sarah Robertson</a>) acknowledged that their blocking system is imperfect / ineffective. One of the things I objected to most strongly about the blocking system as a technologically-minded person was the idea that an organisation like the IWF imagined it was even possible to censor the internet. It turns out they don&#8217;t, which is a relief.</p>
<h2>My Question</h2>
<p>So, given that Sarah acknowledged that the system was flawed - that it served merely as a deterrent and to avoid people accidentally browsing to images of abuse - my question was why the system isn&#8217;t opt-in, or at the very least opt-out. If I want my connection filtered, I would be able to go to the IWF or, install some other filtering software. Sarah replied that the system <b>is</b> opt-in, which is true if you&#8217;re an ISP, but I happen not to be. I made the point that as an individual, I couldn&#8217;t opt out of having my internet connection censored (by what I cheekily described as an opaque organisation - I meant merely that I had no way of knowing what was on the block list). To an extent, it&#8217;s possible for users to vote with their feet and sign up with ISPs that don&#8217;t implement the IWF scheme, but these ISPs are being pressured in to joining the majority of providers in installing the software / hardware required.</p>
<h2>Sarah&#8217;s Question</h2>
<p>Why would I want to opt out of the system? The IWF blocking system stops me viewing images of abuse which I presumably wouldn&#8217;t want to anyway, and moreover, it stops me breaking the law. If I browse without the protection of the system I could accidentally navigate to an illegal image and open myself to prosecution under UK law. Fair point. And at the time I didn&#8217;t have an answer, but have since been thinking about it because it&#8217;s a really good question.</p>
<h2>The Individual and the State</h2>
<p>One of the reasons we had all gathered in London, Cambridge and across the UK, was to discuss what some feel is a radical change that is taking place in the relationship between &#8220;us&#8221; as citizens and &#8220;them&#8221; as the government. In theory, the state and its machinery exists at our behest and is there to serve us. Some of the attendees at the Convention were there because they felt that this is increasingly not the case. Why do police photograph protesters at peaceful demonstrations? Why can&#8217;t protestors photograph the police? (Why, indeed, can the press not photograph the police, making it difficult to publicise and document a demonstration?) The Home Office seem determined to reduce the risk of the population coming to harm at the expense of curtailing our civil liberties - ought we not to be given a say in the amount of risk that we&#8217;re prepared to accept? And it&#8217;s not entirely the Home Office&#8217;s fault. Society and the press tend to blame the government when &#8220;bad things&#8221; happen - the only way for them to avoid further blame is to reduce the incidence of bad things.</p>
<h2>The real question</h2>
<p>Why would I want to break the law? I guess that&#8217;s not even really the question. I don&#8217;t really want to break that law. I certainly don&#8217;t want to view images of child abuse, accidentally or otherwise. But I would very much like the <em>option</em> to break any law. The IWF conscientiously populates the blocking list with the locations of images deemed to be illegal to view and, as far as I&#8217;m aware, no &#8220;right thinking&#8221; person would want to see the images that have been blocked. What they&#8217;re doing, though, is implementing a system which allows the government to have content they define as illegal &#8220;removed&#8221; from the UK internet.</p>
<h2>I sometimes disagree with the government</h2>
<p>There. I said it. Sometimes I break copyright law. Sometimes I drive too fast. Sometimes I start composing blog posts while I&#8217;m stuck in traffic. If someone offered to install a chip in my brain that would make it impossible for me to break the law, controversially, I don&#8217;t think I&#8217;d take them up on the offer. &#8220;If you don&#8217;t like the law, you should try to have it changed&#8221;. True. I absolutely believe that. But as (I think) <a href="http://en.wikipedia.org/wiki/Shami_Chakrabarti">Shami Chakrabarti</a> aptly put it on Saturday, whoever you vote for, the government tends to get elected.</p>
<p>I can&#8217;t change laws quite as quickly as they&#8217;re being introduced. It&#8217;s simply not practical for me to campaign against everything with which I disagree, and I don&#8217;t think there&#8217;s enough popular support today for me to make a difference even if I did. I&#8217;ll continue to support the work of <a href="http://www.no2id.net/">NO2ID</a> and <a href="http://www.openrightsgroup.org/">the Open Rights Group</a>, and I&#8217;ll continue to get as involved as I can with things like the Convention on Modern Liberty. For the time being, though, I&#8217;d like to keep my moral autonomy; to be able to choose which laws I obey and which I don&#8217;t, to have the option to do things that the government doesn&#8217;t necessarily want me to do. </p>
<p>I promise I&#8217;ll be good <img src='http://talkingcode.co.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><br/><br />
P.S. Obviously the IWF blocking list is a bit of a moot issue for me. I can bypass the filtering in any number of ways if I choose to do so. Recommend you check out <a href="http://www.torproject.org/">Tor</a> and/or <a href="http://osdir.com/ml/user-groups.ale/2003-03/msg01182.html">ssh -D</a> if you&#8217;d like to be able to do the same.</p>
]]></content:encoded>
			<wfw:commentRss>http://talkingcode.co.uk/2009/03/02/me-the-iwf-and-child-porn/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Pixmap, Pixbuf and memory lane</title>
		<link>http://talkingcode.co.uk/2009/01/05/pixmap-pixbuf-gtk-haskell/</link>
		<comments>http://talkingcode.co.uk/2009/01/05/pixmap-pixbuf-gtk-haskell/#comments</comments>
		<pubDate>Mon, 05 Jan 2009 09:11:29 +0000</pubDate>
		<dc:creator>codders</dc:creator>
		
		<category><![CDATA[code]]></category>

		<category><![CDATA[gtk]]></category>

		<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://talkingcode.co.uk/?p=51</guid>
		<description><![CDATA[So how&#8217;s the Haskell project going? So far, so good. When I last wrote, I&#8217;d managed to load a &#8220;Hello World!&#8221; GUI for my application. Since then I&#8217;ve managed to parse up some content and render it to the screen. Current revision is 121ed7f2.
Antediluvian file formats
The project, in case you&#8217;ve not been following on github, [...]]]></description>
			<content:encoded><![CDATA[<p>So how&#8217;s the Haskell project going? So far, so good. When I last wrote, I&#8217;d managed to load a &#8220;Hello World!&#8221; GUI for my application. Since then I&#8217;ve managed to parse up some content and render it to the screen. Current revision is <a href="http://github.com/codders/gp3/commit/121ed7f2386d76c8cb525a8c789480bd4bfbd7f0">121ed7f2</a>.</p>
<h3>Antediluvian file formats</h3>
<p>The project, in case you&#8217;ve not been following on github, is to resurrect a long-since abandoned game. This game was released as a <a href="http://coverdisk.net/">cover disk</a> on an Amiga magazine back in &#8220;the day&#8221; and the code has since been made available by the authors (in 68000 assembly), ported to BlitzBasic and (abortively) ported to C++/SDL.</p>
<p>The maps for the BlitzBasic game were stored as tile maps. Each game level combines a tile set and a map to place the tiles on the screen. For additional kicks, some of the files are compressed under a scheme called &#8220;BPCK&#8221; which involves fairly simple run-length encoding. The <a href="http://github.com/codders/gp3/tree/121ed7f2386d76c8cb525a8c789480bd4bfbd7f0/src/BPackReader.hs">code to parse up those files</a> was&#8230; err&#8230; relatively straightforward to write although I did have some issues with bit-order and palette mapping.</p>
<h3>Tiles as Pixbufs</h3>
<p>The tiles are stored as sequences of <a href="http://en.wikipedia.org/wiki/Nibble">nibbles</a> mapping pixels on to a 16-colour palette. In order to draw these, I extracted the RGB for the nibbles and inserted that 3-byte-per-pixel sequence into a pixmap (<a href="http://github.com/codders/gp3/tree/121ed7f2386d76c8cb525a8c789480bd4bfbd7f0/src/GP3GUI.hs">this is the source</a>):</p>
<pre>
buildTile :: [BPCK.PaletteEntry] -> BPCK.Gliph -> IO Pixbuf
buildTile palette g = do
    let gData = BPCK.gliphData g
    buf <- pixbufNew ColorspaceRgb False 8 gliphX gliphY
    pbData <- (pixbufGetPixels buf :: IO (PixbufData Int Word8))
    rowStride <- pixbufGetRowstride buf
    chan <- pixbufGetNChannels buf -- Hopefully this is 3 (R,G,B)
    bits <- pixbufGetBitsPerSample buf -- Hopefully this is 8
    doFromTo 0 (gliphX - 1) $ \y ->
      doFromTo 0 (gliphY - 1) $ \x -> do
        let pixbufoffset = x*chan + y*rowStride
        let gliphOffset = fromIntegral $ x + y*gliphX
        let paletteIndex = B.index gData gliphOffset
        let thiscolor = palette !! fromIntegral paletteIndex
        writeArray pbData (pixbufoffset) (fromIntegral $ BPCK.red thiscolor)
        writeArray pbData (1 + pixbufoffset) (fromIntegral $ BPCK.green thiscolor)
        writeArray pbData (2 + pixbufoffset) (fromIntegral $ BPCK.blue thiscolor)
    return buf
    where gliphX = BPCK.gliphWidth g
             gliphY = BPCK.gliphHeight g
</pre>
<h3>Maps as Pixmaps</h3>
<p>The difference between a pixbuf and a pixmap is, as I understand it, that a pixbuf is an X-client side block of data into which you can load pixel information and a pixmap is an X-server side drawable (in the GTK sense) object. Pixbuf is more like a brush for painting, and Pixmap is an off-screen canvas. So to build my map I blatted the tile pixbufs on to a pixmap:</p>
<pre>
createTiledPixmap :: BPCK.ParsedImage -> BPCK.ParsedTileMap -> IO Pixmap
createTiledPixmap tileSet tileMap = do
    putStrLn $ "Building tile pixmaps"
    tiles <- tilesFromImageData tileSet
    let tileCount = length tiles
    putStrLn $ "Creating new pixmap " ++ show totalWidthPixels ++ " x " ++ show totalHeightPixels
    pixmap <- pixmapNew (Nothing :: Maybe DrawWindow) totalWidthPixels totalHeightPixels (Just 24)
    gc <- gcNew pixmap
    doFromTo 0 (tilesHigh - 1) $ \iy ->
      doFromTo 0 (tilesAcross - 1) $ \ix -> do
        let tileIndex = ix + (iy * tilesAcross)
        let tileId = (min (fromIntegral (BPCK.tileMap tileMap !! tileIndex)) tileCount) `mod` tileCount
        let curX = ix * tileSizePixels
        let curY = iy * tileSizePixels
        postGUIAsync $ drawPixbuf pixmap gc (tiles !! tileId) 0 0 curX curY tileSizePixels tileSizePixels RgbDitherNone 0 0
    return pixmap
    where tileSizePixels = BPCK.gliphSize tileSet
             tilesAcross = BPCK.tilesAcross tileMap
             tilesHigh = BPCK.tilesHigh tileMap
             totalWidthPixels = tileSizePixels * tilesAcross
             totalHeightPixels = tileSizePixels * tilesHigh
</pre>
<h3>Results</h3>
<p>The finished article looks a bit like this:<br/><br />
<img src='http://talkingcode.co.uk/wp-content/2009/01/screen1.jpg' alt='Screenshot'/><br />
or this:</br><br />
<img src='http://talkingcode.co.uk/wp-content/2009/01/screen2.jpg' alt='Screenshot'/><br />
and pressing the space bar cycles through the maps on account of this:</p>
<pre>
onKeyPress app (\x@(Key { eventKeyName = name,
                              eventKeyChar = char }) -> do
    case char of
      Just ' ' -> do
        putStrLn $ "Switching map"
        currentState <- readIORef mapStateRef
        nextState <- nextMapState currentState
        writeIORef mapStateRef nextState
        drawWin <- widgetGetDrawWindow canvas
        gc <- gcNew drawWin
        (width, height) <- drawableGetSize drawWin
        postGUIAsync $ drawDrawable drawWin gc (renderedMap nextState) 0 0 0 0 width height
      Just c -> putStrLn $ &#8220;Press &#8221; ++ name ++ &#8220;(&#8217;&#8221; ++ [c] ++ &#8220;&#8216;)&#8221;
      Nothing -> putStrLn $ &#8220;weird key: &#8221; ++ name
    return (eventSent x))
</pre>
<h3>Conclusions</h3>
<p>I&#8217;m now a lot more comfortable with Haskell and think I&#8217;ve mastered the &#8220;word-for-word translation of imperative to pseudo-functional&#8221; style. The file parsing code I&#8217;ve written performs like a dog on account of that, but it&#8217;s not on a critical path for anything. One thing that has struck me is how easy it is to refactor Haskell code (as long as you use hanging &#8216;do&#8217;s to avoid formatting upsets). So I&#8217;ll stick at it and see if I can&#8217;t finish this project inside of a year.</p>
<h3>Why not SDL?</h3>
<p>FYYFDANSEIC, etc.</p>
]]></content:encoded>
			<wfw:commentRss>http://talkingcode.co.uk/2009/01/05/pixmap-pixbuf-gtk-haskell/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Un-overriding hashCode in Java</title>
		<link>http://talkingcode.co.uk/2008/12/11/un-overriding-hashcode-in-java/</link>
		<comments>http://talkingcode.co.uk/2008/12/11/un-overriding-hashcode-in-java/#comments</comments>
		<pubDate>Thu, 11 Dec 2008 11:33:38 +0000</pubDate>
		<dc:creator>pav</dc:creator>
		
		<category><![CDATA[code]]></category>

		<category><![CDATA[concurrency]]></category>

		<category><![CDATA[hashing]]></category>

		<category><![CDATA[inheritance]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[memory model]]></category>

		<guid isPermaLink="false">http://talkingcode.co.uk/?p=49</guid>
		<description><![CDATA[Problem: you are inheriting from a class in Java. This class has overridden Object.hashCode(). However, you do not want the behaviour of the overriding method, but rather that of the original implementation in the Object class.
Solution: in your new class, create a private field of type Object. Override the hashCode() method in the class to [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Problem:</strong> you are inheriting from a class in Java. This class has overridden <a title="Java API docs on Object.hashCode()" href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#hashCode()" target="_self">Object.hashCode()</a>. However, you do not want the behaviour of the overriding method, but rather that of the original implementation in the Object class.</p>
<p><strong>Solution:</strong> in your new class, create a private field of type Object. Override the hashCode() method in the class to call hashCode() on that field. The result should follow a pattern similar to that below:</p>
<pre>public class CustomHashSet&lt;T&gt; extends HashSet&lt;T&gt; {
    private Object hasher;

    public CustomSpecHashSet() {
        super();
        hasher = new Object();
    }</pre>
<pre>    @SuppressWarnings("unchecked")
    public synchronized Object clone() {
        CustomHashSet&lt;T&gt; copy = (CustomHashSet&lt;T&gt;)super.clone();
        copy.hasher = new Object();
        return copy;
    }

    public int hashCode() { return hasher.hashCode(); }

    public boolean equals(Object o) { return this == o; }
}</pre>
<h3>Discussion</h3>
<p>In Java, once a method has been overridden, it is impossible to get at the original implementation from any inheriting classes. I recently had to deal with this when I wanted to keep some objects that inherited from various <a title="Java API docs on Collection" href="http://java.sun.com/javase/6/docs/api/java/util/Collection.html" target="_self">Collection</a>s inside <a title="Java API docs on HashSet" href="http://java.sun.com/javase/6/docs/api/java/util/HashSet.html" target="_self">HashSet</a>s, and wanted distinct objects in the set to not be treated as equals just because they happened to contain the same elements. In other words, I needed to use the Object implementations of the hashCode() and equals() methods, rather than the versions defined by the Collections. This is because Object.hashCode() returns a unique integer for every distinct object (typically by using the memory address of an object).</p>
<p>At first, I thought this problem could be solved with <a title="Java API docs on reflection" href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/package-summary.html" target="_self">reflection</a>. The soloution should simply involve getting a <a title="Java API docs on Method" href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html" target="_self">Method</a> instance for Object.hashCode(), and invoke that on any object. Unfortunately, that does not work; <a title="Java API docs on Method.invoke()" href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object,%20java.lang.Object...)" target="_self">calling a method using reflection</a> in Java results in a dynamic method lookup based on the object the method is being invoked on.</p>
<p>Since Java does not permit un-overriding methods, one has to cheat. An object that is never leaked to the outside world can be used to provide a unique integer for each instance. However, care must be taken when implementing classes that support cloning (i.e. implement the <a title="Java API docs on Cloneable" href="http://java.sun.com/javase/6/docs/api/java/lang/Cloneable.html" target="_self">Cloneable</a> interface, or inherit from a class that does). Since the <a title="Java API docs on Object.clone()" href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#clone()" target="_self">clone()</a> method only does a <a title="Explanation of object copying techniques." href="http://en.wikipedia.org/wiki/Shallow_copy" target="_self">shallow copy</a> of an object, it is essential to override clone(), and make sure that any copies created there get their own instance of the hashing object. There is another gotcha; in the presense of multiple threads accessing the same object, the following clone() implementation would be unsafe:</p>
<pre>public Object clone() {
    MyObject copy = (MyObject)super.clone();
    copy.hasher = new Object();
    return copy;
}</pre>
<p>This is because the Java memory model only guarantees <a title="Java memory model FAQ" href="http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#jsr133" target="_self">initialization safety</a> for objects created using a constructor. What this means is that, for an object created using clone() and changing fields after the call to clone(), the updates to those fields are not guaranteed to be seen immediately by other threads accessing that object. A simple way to address this is to put the initialization of the cloned object inside a synchronized block, as in the code given at the top of this recipe.</p>
]]></content:encoded>
			<wfw:commentRss>http://talkingcode.co.uk/2008/12/11/un-overriding-hashcode-in-java/feed/</wfw:commentRss>
		</item>
		<item>
		<title>GTK, Glade, Haskell and gnome_program_init()</title>
		<link>http://talkingcode.co.uk/2008/12/09/gtk-glade-haskell-and-gnome_program_init/</link>
		<comments>http://talkingcode.co.uk/2008/12/09/gtk-glade-haskell-and-gnome_program_init/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 21:43:58 +0000</pubDate>
		<dc:creator>codders</dc:creator>
		
		<category><![CDATA[c]]></category>

		<category><![CDATA[code]]></category>

		<category><![CDATA[gtk]]></category>

		<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://talkingcode.co.uk/?p=47</guid>
		<description><![CDATA[So. I finished the book (at length, and to be fair I mostly skimmed the last chapters), which means it&#8217;s time for me to start actually writing Haskell code. I thought I&#8217;d start with a simple GUI app, but it turned out not to be quite so simple.
I&#8217;ve put the code that I&#8217;m working on [...]]]></description>
			<content:encoded><![CDATA[<p>So. I finished <a href="http://book.realworldhaskell.org">the book</a> (at length, and to be fair I mostly skimmed the last chapters), which means it&#8217;s time for me to start actually writing Haskell code. I thought I&#8217;d start with a simple GUI app, but it turned out not to be quite so simple.</p>
<p>I&#8217;ve put the code that I&#8217;m working on up on <a href="http://github.com">GitHub</a> because that&#8217;s what all the cool kids are doing. My project is called <a href="http://github.com/codders/gp3/tree/master">GP3</a> for reasons that ought eventually to become clear. HEAD at time of writing is <a href="http://github.com/codders/gp3/commit/7b01940a9dfc307363e530c94732b2680007dc13">7b01940</a></p>
<p><strong>Glade</strong><br />
Glade is a GTK UI designer. I won&#8217;t go in to a lot of detail - there&#8217;s been plenty written about it. What I will say, though, is that at version 3, you can often find yourself creating unexpected dependencies for your program by using the more complex widgets. I unwittingly picked something from the &#8220;GNOME User Interface&#8221; toolbox, which has a Glade class of &#8220;GnomeApp&#8221;. This includes a &#8220;BonoboDock&#8221; and a &#8220;BonoboDockItem&#8221;. </p>
<p><strong>Launching your app</strong><br />
Borrowing heavily from <a href="http://book.realworldhaskell.org/read/gui-programming-with-gtk-hs.html">the book</a>, here&#8217;s part of the code I was using to launch my app:</p>
<pre>
main :: FilePath -> IO ()
main gladepath =
  do
    unsafeInitGUIForThreadedRTS
    timeoutAddFull (yield >> return True) priorityDefaultIdle 100
    gui <- loadGlade gladepath
    connectGui gui
    windowPresent (mainApp gui)
    mainGUI
</pre>
<p><strong>gnome_program_init()</strong><br />
Having made the mistake of using a GNOME-UI widget, I saw this when I ran my app:</p>
<pre>
GnomeUI-ERROR **: You must call gnome_program_init()
          before creating a GnomeApp
</pre>
<p>This is because my Glade UI requires libgnomeui to be initialised. To make matters worse, libgnomeui isn&#8217;t linked by default in to Gtk2Hs. In my limited understanding of Haskell and Gnome, there are two options at this point. One is to import the gnome_program_init function from libgnomeui over FFI. The other is to write a C program to wrap a call to gnome_program_init and re-export a simpler function for you to import over FFI. I chose the latter option:</p>
<pre>
// gtk_docker.c
#include <gnome.h>

void do_gnome_init()
{
  static char **argv = NULL;
  if (argv == NULL)
  {
    argv = malloc(2);
    argv[0] = &#8220;gtk_docker&#8221;;
    argv[1] = &#8216;\0&#8242;;
  }
  gnome_init(&#8221;my-app&#8221;, &#8220;my-version&#8221;, 1, argv);
}
</pre>
<p>&#8230; and a header file</p>
<pre>
// gtk_docker.h
void do_gnome_init(void);
</pre>
<p>Astute observers will see that this is a bit of a cheat. GnomeUI wants the command line arguments that were passed to the executable. It would be possible, but irritating, to arrange this. I couldn&#8217;t easily divine how to pass an array of CStrings over FFI, so I wimped out. Also, I&#8217;m not technically calling <em>gnome_program_init</em> - this call appears to be deprecated in favour of <em>gnome_init</em>, and the latter call also silences the error message.</p>
<p><strong>Compilation</strong><br />
We haven&#8217;t solved the compilation problem yet. The compiler still needs to know where to find <em>gnome.h</em> and its included headers, and needs to know where to find the associated libraries for linking. There are good ways and bad ways to solve this problem&#8230; here&#8217;s a bad way:</p>
<pre>
#Makefile
LDFLAGS = -lgnomeui-2 -lcairo -lglade-2.0
CFLAGS = -I/usr/include/libgnomeui-2.0 -I/usr/include/gtk-2.0/ \
              -I/usr/include/cairo/ -I/usr/include/glib-2.0/ \
              -I/usr/lib/glib-2.0/include/ \
              -I/usr/include/pango-1.0/ \
              -I/usr/lib/gtk-2.0/include/ \
              -I/usr/include/atk-1.0/ \
              -I/usr/include/libgnome-2.0/ \
              -I/usr/include/libbonobo-2.0/ \
              -I/usr/include/libgnomecanvas-2.0/ \
              -I/usr/include/libart-2.0/ \
              -I/usr/include/libbonoboui-2.0/ \
              -I/usr/include/gnome-vfs-2.0/ -Werror -Wall

GHCC=ghc

default: gp3

gp3: gtk_docker.o GP3Main.hs GP3GUI.hs
        $(GHCC) --make $(LDFLAGS) $^

clean:
  rm -f *.o *.hi GP3Main
</pre>
<p>The real answer probably involves <a href="http://www.gnu.org/software/autoconf/">GNU AutoTools</a> for the C toolchain or some craziness with <a href="http://www.haskell.org/cabal/">Cabal</a>. I&#8217;m sure I&#8217;ll get round to that <img src='http://talkingcode.co.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Calling the function</strong><br />
Now to clear that error message. We just need to&#8230;</p>
<pre>
{-# LANGUAGE ForeignFunctionInterface #-}

foreign import ccall unsafe "gtk_docker.h do_gnome_init"
      c_gnome_init :: IO ()
</pre>
<p>and</p>
<pre>
main :: FilePath -> IO ()
main gladepath =
  do
    unsafeInitGUIForThreadedRTS
    c_gnome_init
    ...
</pre>
<p>and we&#8217;re done.</p>
<p><strong>Portability</strong><br />
Linking libgnomeui probably makes my code a lot less portable. Hard-coding the include paths certainly does. Fortunately I don&#8217;t have to care about other users just yet, and I&#8217;m unlikely ever to care about other platforms <img src='http://talkingcode.co.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p>
]]></content:encoded>
			<wfw:commentRss>http://talkingcode.co.uk/2008/12/09/gtk-glade-haskell-and-gnome_program_init/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Haskell, GTK and Multi-Threading</title>
		<link>http://talkingcode.co.uk/2008/12/02/haskell-gtk-and-multi-threading/</link>
		<comments>http://talkingcode.co.uk/2008/12/02/haskell-gtk-and-multi-threading/#comments</comments>
		<pubDate>Tue, 02 Dec 2008 18:11:09 +0000</pubDate>
		<dc:creator>pav</dc:creator>
		
		<category><![CDATA[code]]></category>

		<category><![CDATA[concurrency]]></category>

		<category><![CDATA[debian]]></category>

		<category><![CDATA[gtk]]></category>

		<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://talkingcode.co.uk/?p=46</guid>
		<description><![CDATA[I have been working on an application in Haskell, using Gtk2Hs for the user interface. Now, you normally want a graphical user interface (GUI) to be responsive, so you avoid doing tasks that take a long time in the thread that handles the GUI. Instead, your main computation happens in other application threads, and all [...]]]></description>
			<content:encoded><![CDATA[<p>I have been working on an application in Haskell, using <a title="Gtk2Hs" href="http://www.haskell.org/gtk2hs/" target="_self">Gtk2Hs</a> for the user interface. Now, you normally want a graphical user interface (GUI) to be responsive, so you avoid doing tasks that take a long time in the thread that handles the GUI. Instead, your main computation happens in other application threads, and all that happens in the GUI thread is updating of interface elements. It turns out that there are several issues that come up when you mix Haskell, GTK and multiple threads, which is why this post is here.</p>
<h3>Part 1: The GTK event loop</h3>
<p>Most programs that use Gtk2Hs first do all the GUI-related initialization, and then execute the <a title="Gtk2Hs API docs on mainGUI" href="http://www.haskell.org/gtk2hs/docs/current/Graphics-UI-Gtk-General-General.html#v%3AmainGUI" target="_self">mainGUI</a> computation. This is actually a loop that processes GTK-related events until the user quits the program. Because of the way <a title="GHC thread pre-emption." href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent.html#12" target="_self">thread switching works</a> in Haskell, a thread executing a loop like that will not let any other &#8220;lightweight&#8221; threads run. (Lightweight threads are threads created using the forkIO computation.) One <a title="Gtk2Hs Blog on Multi-Threaded GUIs" href="http://haskell.org/gtk2hs/archives/2005/07/24/writing-multi-threaded-guis/" target="_self">frequently</a> <a title="Real World Haskell on Threaded GUIs" href="http://book.realworldhaskell.org/read/gui-programming-with-gtk-hs.html#PodMainGUI.hs:main" target="_self">suggested</a> way to solve this problem is to make the GTK event loop periodically yield to any other Haskell threads by adding the following to your GUI initialization code:</p>
<pre>timeoutAddFull (yield &gt;&gt; return True) priorityDefaultIdle 100</pre>
<p>Note that this is only an issue when all lightweight Haskell threads run on top of a single operating system thread, as in the single-threaded RTS of GHC. If Haskell threads are allowed to run on multiple OS threads, then yielding is not necessary.</p>
<h3>Part 2: GTK thread safety</h3>
<p>It turns out that that GTK (the C library wrapped by Gtk2Hs) is not thread-safe. What this means is that all modifications of GTK state must happen from a single OS thread, which also must be the same thread that is executing the GTK event loop. If all Haskell threads are run on top of a single OS thread, this is easy to ensure. However, if you use a system where lightweight threads may be mapped to different OS threads (such as in the <a title="GHC's multi-threaded RTS" href="http://haskell.org/haskellwiki/GHC/Concurrency#Multiprocessor_GHC" target="_self">multi-threaded RTS in GHC</a>), care must be taken when accessing a GUI. Essentially, application threads need to put GUI modification events onto a queue, with the thread that runs the GTK event loop processing the events from that queue. Fortunately, Gtk2Hs comes with such a queue built-in; you can use the <a title="Gtk2Hs postGUISync" href="http://www.haskell.org/gtk2hs/docs/current/Graphics-UI-Gtk-General-General.html#v%3ApostGUISync" target="_self">postGUI</a> functions to give the event loop blocks of IO to execute.</p>
<p>Note that, by default, Gtk2Hs will produce a warning when running under the GHC multi-threaded RTS. To get rid of this, use <a title="Gtk2Hs API docs on unsafeInitGUIForThreadedRTS" href="http://www.haskell.org/gtk2hs/docs/current/Graphics-UI-Gtk-General-General.html#v%3AunsafeInitGUIForThreadedRTS" target="_self">unsafeInitGUIForThreadedRTS</a> instead of the usual <a title="Gtk2Hs API docs on initGUI" href="http://www.haskell.org/gtk2hs/docs/current/Graphics-UI-Gtk-General-General.html#v%3AinitGUI" target="_self">initGUI</a> to perform GTK initialization. The &#8220;unsafe&#8221; part of the computation name signifies that you are aware of the requirement to only modify GTK state from the correct OS thread.</p>
<h3>Part 3: Deconstructing the GTK event loop</h3>
<p>There might come a time when you want to do something more complicated than the above solutions allow. In such a case, you can actually substitute the mainGUI event loop with your own. Gtk2Hs <a title="Gtk2Hs main loop functions" href="http://www.haskell.org/gtk2hs/docs/current/Graphics-UI-Gtk-General-General.html#4" target="_self">provides functions</a> that will process a single event at a time off the GTK event queue. Put these in a loop, sprinkle with your custom logic (such as pulling events off multiple queues), and you&#8217;re done!</p>
<h3>Context</h3>
<p>This was written with the <a title="GHC" href="http://www.haskell.org/ghc/" target="_self">GHC</a> environment in mind. Other Haskell compilers and/or interpreters may differ in their implementations.</p>
]]></content:encoded>
			<wfw:commentRss>http://talkingcode.co.uk/2008/12/02/haskell-gtk-and-multi-threading/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
<!--eexi6--><u style="display:none;"><li><a href="http://bangbrosnetwork.com/t1/cfree=watchit/sitemap.htm">momsanaladventure</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/assparade.html">ass parade</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/bigmouthfuls.html">bigmouthfuls</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=vix/free_movies_pictures_bangbros/maapaige.html">Mature Anal Sex</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/sitemap.htm">bigtitcreampie</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb4173-cock-hungry-sarajay.html">cock hungry</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/milflessons.html">milf lessons</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/backroommilf.html">Backroommilf</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/magicalfeet.html">Magical Feet</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/tugjobs.html">Tug Job</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/sitemap.htm">magicalfeet</a>
<a href="http://www.sinfulcomics.com/default.php?id=2638&site=26">sinfulcomics</a>
<a href="http://x.milfsandfantasies.com/gal/ms6595-1/p/vix/">milf soup</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/sitemap.htm">ballhoneys</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=watchit/updates.htm?search_input=Double+Hand+Job&menu=search&search_type=shoot">Double Hand Job</a>
<a href="http://bangbrosnetwork.com/t1/pps=vix/free_movies_pictures_bangbros/btramandy.html">fucked real hard</a>
<a href="http://bangbrosnetwork.com/t1/pps=vix/free_movies_pictures_bangbros/ms4324.html">milf boss</a>
<a href="http://bangbrosnetwork.com/t1/pps=vix/free_movies_pictures_bangbros/nnmary34d.html">Big Tits, Round Asses</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/milfsoup.html">milfsoup</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/sitemap.htm">blowjobninjas</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb4461-sex-and-jennacide.html">gothic chick</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=vix/profiles?m=Vivian-West1">Vivian West</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/ballhoneys.html">ball honeys</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/workinglatinas.html">workinglatinas</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=vix/intro?s=ap6105">Esperanza Gomez</a>
<a href="http://bangbrosnetwork.com/t1/pps=vix/free_movies_pictures_bangbros/blkg4038.html">sexy Dominican</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/bigmouthfuls.html">big mouthfuls</a>
<a href="http://bangbus.com/t3/pps=vix/">bangbus</a>
<a href="http://bangbrosnetwork.com/t1/cfree=watchit/sitemap.htm">fuckteamfive</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb3729-milfhunting-got-me-brittny-sexy-stripper.html">sweet pussy</a>
<a href="http://bangbrosnetwork.com/t1/pps=vix/free_movies_pictures_bangbros/ff3819.html">perfect ass</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb4149-gianna-quest-for-cock.html">juicy round ass</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=watchit/updates.htm?search_input=Double+Detention+Penetration&menu=search&search_type=shoot">Double Detention Penetration</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb4345-eva-angelina-wild-bus-ride.html">eva angelina</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb2776-squirting-flower-power.html">squirting</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=vix/profiles?m=Sophie-Dee2">Sophie Dee</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=vix/profiles?m=Marquetta-Jewel1">Marquetta Jewel</a>
<a href="http://x.themilfsoup.com/gal/ms6626-1/p/vix/">milfsoup</a>
<a href="http://www.facialfest.com/t1/cfree=watchit/facialfest.html">facialfest</a>
<a href="http://www.fuckteamfive.com/t1/PPS=watchit/girls3.html">Fuck Team Five</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb1342-alanis.html">latina lips</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb3601-that-what-bang-bus-is-all-about.html">bangbus</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb2797-pushing-up-daisy.html">pushing up daisies</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bbdylan-dylan.html">Catholic school girls</a>
<a href="http://www.celeb-king.com/default.php?id=2638&site=13">celeb king</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=vix/profiles?m=Jessi-Summers1">Jessi Summers</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb3877-sexy-amy-does-anal-on-the-bus.html">crazy ass fucking</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=watchit/updates.htm?search_input=Fuck+team+five&menu=search&search_type=shoot">Fuck team five</a>
<a href="http://www.milfsoup.com/t1/pps=vix/shoots/ms4017.htm">Puma Sweede</a>
<a href="http://www.celeb-king.com/t2/movie_caps.php?id=2638&site=13&tr=60">Celeb Nudity</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=vix/free_movies_pictures_bangbros/omsyndee.html">chickie baby</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=vix/profiles?m=Eva-Angelina1">Eva Angelina</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb2840-nautica-big-bubble-butt.html">big bubble butt</a>
<a href="http://www.milfsoup.com/t1/pps=vix/shoots/ms3722.htm">Busty Milf</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb4541-double-fun-at-the-bang-bus.html">bang bus</a>
<a href="http://x.everyonelovesmilfs.com/gal/ms6596-1/p/vix/">milf soup</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=vix/profiles?m=Sativa-Rose1">Sativa Rose</a>
<a href="http://x.latinaswhowork.com/gal/lw3942-2/p/vix/">milfsoup</a>
<a href="http://baitbus.gay-movie-clips.com">Bait Bus</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb6177-bus-stop-pimpin.html">pimpin</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=vix/intro?s=ap6105">Spanish Diosa</a>
<a href="http://bangbrosnetwork.com/t1/pps=vix/free_movies_pictures_bangbros/ps2668.html"></a>
<a href="http://www.milfsoup.com/t1/pps=vix/popular2.htm">milfsoup</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=vix/profiles?m=Shy-Love1">Shy Love</a>
<a href="http://bangbus.com/t3/cfree=vix/trailers/bb4957-britney-is-back-on-the-bus.html">Britney Blew</a>
<a href="http://www.bangbrosnetwork.com/t1/pps=watchit/updates.htm?search_input=Tug+Job&menu=search&search_type=shoot">Amazing Tug Job</a>
</li></u>