Tag Archives: gui interpreter

A cute hack: Changing the scope of System.out

This isn’t any sort of deep trick. I just found the results surprisingly pleasant, so thought I’d share.

In the GUI interpreter I need to be able to capture standard out. Doing println in the interpreter should print to the screen, not the console. And that’s fine. Java provides System.setOut. I had to fight the stupidities of java.io a bit to make it work (annoying details with flushing among other things), but it did in the end.

There is of course a problem with this. System.out is basically a great honking big global variable. We’ve now made it impossible to run multiple interpreters in the same VM. Le sigh.

Ok. So, what we do is a bit of juggling and set System.out appropriately before interpreting each thing. Right?

Nope. Doesn’t work. These things can and do live in separate threads. And for that matter, what about background threads spawned by one of the interpreters?

The solution is to make System.out thread local. And not just any type of thread local – an inheritable thread local. Spawned threads need to inherit the System.out of their parent thread so that something like spawn { println(“Hello world”) } prints to the right screen.

Once you have this, the idea is obvious. You define an object which extends OutputStream but delegates all functionality to some thread local variable (snarfing the System.out that was present when the object loads as the default value), set System.out to be a print stream wrapping that and you’re done. You can now set its value in a thread local way and multiple interpreters can coexist peacefully.

Like I said, nothing special, but it seems like a surprisingly handy trick.

This entry was posted in programming and tagged , , , on by .

GUI interpreter frontend coming along nicely

I’ve separated the interpreter frontend out into its own separate project. It’s available at http://www.drmaciver.com/repos/guinterpreter/

It’s doing pretty well. The UI has been improved, it supports multiple interpreter windows in the same VM, and is generally in a pretty usable state. It still has a few quirks, but it’s getting there (still a little bit of a headache to set up, but I’ll work on that). My plans for the immediate future mainly revolve around UI polishing and embeddability – I’d like it to be really easy to include this inside another (Jambi) application. hemant / gnufied has been taking a look at the code and has some interesting plans for it, starting with syntax highlighting. I’ve given him commit access, so we’ll see what happens on that front.

If you want to give it a try, go right ahead. You’ll need to resolve the Jambi dependency yourself, but otherwise it should be pretty easy (I will probably set up some sort of maven (sigh) repository for the jambi dependencies and switch the build script over to buildr so it can use them at some point, but I haven’t yet).

This entry was posted in programming and tagged , , on by .