AIR/Flash Builder 4: A Simple Basecamp Client

I was playing around with Flash Builder 4 & Flex 4 after the public beta was announced, and decided to whip up a quick, very simple AIR client for Basecamp.  It’s pretty straight forward and there’s not much code, but if you’re having trouble getting started with AIR, Flex 4, or Gumbo, perhaps it will help.  

Basecamp provides a very simple REST-based API, which is documented at http://developer.37signals.com/basecamp/. I just used URLLoader and URLRequest to pull the data, with authentication turned on. When authentication is turned on, your OS will handle username and password requests.

I ended up using anchor-based layouts because I couldn’t figure out, with the spark components, how to center my screens.  Maybe this is the way you’re supposed to do it…I’m not sure.  If anyone has any input as to best practices for the new layout mechanisms in Flex 4, I’d love to hear about them.

Beyond that, there’s not much to the application…just a sample.  Maybe I’ll flush this thing out as I continue to play with Flash Builder 4.  All in all, in regards to my feelings about Flash Builder 4 and Flex 4, I am going to reserver judgement until I have a larger data set to work with.  Building this sample was very easy, but I don’t think I accessed enough of the new features to cast judgement yet.

Download source as a Flash Builder 4 Project Here!

Interview with Branden from FITC

Check it out! Tom Krcha of Flash Realtime did an interview with Branden at Flash in the Can (FITC) in Amsterdam. The interview is more of a human interest piece. If you’ve ever wondered what voice to use when you read his posts, now you know.


Branden Hall interviewed by Tom Krcha

tags: , ,

Comments: 1 comment

AIR and External SWFs

Let’s just say, for the sake of argument, that you were building an AIR application that needed to load external SWFs. Let’s also say you needed to communicate back and forth between that SWF and the AIR application. As it says on old maps - “here by dragons”.

AIR introduces two properties to the LoaderInfo object - parentSandboxBridge and childSandboxBridge. You can use these to communicate from the child to parent and vice versa. However, there are a few gotchas.

First, it appears that the the ability for the child SWF to set the “childSandboxBridge” property on it’s instance of LoaderInfo depends on AIR to do some magic. If your child SWF is small, it will probably happen prior to your constructor being called, but you can’t depend on that. It turns out you need to listen for the Event.INIT event coming from the SWFs LoaderInfo to know when you can actually start to populate childSandboxBridge.

Secondly, anything that goes through the sandbox bridge gets totally stripped down to essentially generic objects with properties - there are no methods and I have yet to find a way to cast these generic blobs of data back into a proper instance of a class (this even applies for built in classes, like ByteArray and BitmapData!). The only real good news here it is possible to take any class that supports the [] operator (such as ByteArray) go across the bridge, you just have to do a bit of work. On the receiving end of the data you just create an instance of the class you want, then loop through the data that came over the bridge (it’s length property will work) and use that data to populate your object. (I just used this to send Bitmaps through the bridge via a Bitmap -> BitmapData ->ByteArray ->BitmapData -> Bitmap progression. It worked, but YUCK!)

Understanding Adobe Alchemy

Adobe recently announced the first public release of a research project code-named Alchemy. Alchemy is a C/C++ to ActionScript compiler that opens up a huge new world for the Flash platform.

Automata Studios has worked closely with engineers over at Adobe for the past few months testing Alchemy and preparing some public samples. We were very happy to help present the public release at the day 2 keynote of Adobe MAX 2008 earlier this week. You can also see some video of me talking about our work porting Ogg Vorbis using Alchemy on Adobe Labs.

There is currently quite a bit of confusion about Alchemy and this article is a quick attempt to answer the most common questions about the technology. First, let’s look at what Alchemy really is and what it is doing.

One of the main pieces of Alchemy is a new backend to the LLVM compiler infrastructure. LLVM is short for Low Level Virtual Machine. The big idea behind LLVM is that the core LLVM compiler will take code in many different languages and compile it into simple RISC-like instructions that are platform neutral. Then, anyone can write a backend to LLVM that can take LLVMs simple instructions and turn them into actual executables for a given platform. Platforms include x64, ARM, PowerPC, and now ActionScript.

You may notice how much ActionScript stands out in that list. All of the rest of the members are CPUs - not programming languages. In fact, if you manage to stop Alchemy mid-compile (when it has created the ActionScript, but not yet compiled it into a SWF) and look at the ActionScript that it creates it will look like some odd hybrid of ActionScript 3 and assembly language. In fact you’ll even see sections that looks suspiciously like inline assembler. This is because the ActionScript compiler that ships with Alchemy does in fact allow for inline AVM2 byte codes.

Essentially when you compile some C or C++ code with Alchemy the end result is a class that is basically a virtual machine written in ActionScript and AVM2 bytecode. This is also why Alchemy generated SWCs are on the large side - they include everything that C or C++ may need such as the C standard library and POSIX support. For example the stringcho example that ships with Alchemy takes 54 lines of C and spits out 27415 lines of ActionScript. This is also why Alchemy can do things like its built-in “green threads” that let’s you run synchronous C asynchronously inside of the Flash Player.

In addition to the LLVM backend, Alchemy includes a set of scripts that are drop-in replacements for standard development tools like make and autoconf. This allows you to use the standard UNIX-style tool chain to create SWFs and SWCs (and thus easily recompile most existing source with Alchemy). The alc-on and alc-off scripts that ship with Alchemy are in fact swapping the standard tools for the Alchemy tools and vice versa.

The output you get from Alchemy is generally a SWC (you can get just a SWF if you want, but usually it won’t be terribly useful on its own). SWCs created from Alchemy can be used in Flex 3 (as long as the build can target FP10), Flex 4 (”Gumbo” - in public preview) and Flash CS4. While I believe there are some switches to make Alchemy compiled code target Flash Player 9, this should be avoided as there were specific changes made to Flash Player 10 that greatly increase runtime speed.

As you may have guessed by now, once C and C++ code is compiled with Alchemy into a SWF it is subject to all of the rules and limitations of a normal SWF. That means you’re still in the security sandbox, all visual output goes through the display list, and all network and file access goes through the existing classes. Under the surface, when you instantiate your Alchemy compiled library, the code is allocating a nice chunk of memory into a ByteArray. This is how Alchemy takes pointers, malloc, free, etc and makes those concepts work in ActionScript.

Knowing that Alchemy is just spitting out the same AVM2 bytecode that Flash and Flex spit out it is pretty confusing how Alchemy code could be faster than standard ActionScript. In fact, it is not faster across the board - just in specific types of operations and when the length of a task can be used to overcome Alchemy’s intrinsic overhead. Now, that’s not to say that Alchemy compiled code is slouchy by default. In fact, because LLVM does a lot of optimizations, whereas Flash and Flex have no optimization step built into their compilers, Alchemy code manages to overcome a lot of it is overhead just on its own.

Now, what are these operations that Alchemy does so well? Memory access and function calls. Alchemy compiled code utilizes new bytecodes added to FP10 for working with ByteArrays - which as you’ll remember are what make up the “RAM” in Alchemy. Function calls are faster because in ActionScript function calls require that their parameters be “boxed” and “unboxed” into and out of objects for each call. Alchemy code doesn’t have to do this.

All of this speediness can be undone though by jumping back and forth between Alchemy code and regular ActionScript. This process is called marshaling and you’ll want to keep it to a minimum. Marshaling is expensive so you’ll want to try to create calls that stay in the C code as long as possible. You’ll also want to try to limit the number of parameters you’re passing back and forth (it’s actually best to work directly with Alchemy’s “RAM” if possible).

As you can see, Alchemy is very powerful, but it is not some magic bullet. More than anything else Alchemy has the potential to drastically speed up the process of bringing existing C/C++ code to the Flash Platform - something that had to be done line-by-line by hand previously. If the ActionScript wrapper around an Alchemy compiled library is well written to take advantage of Alchemy’s strengths it is even possible to get significant speed improvements (up to an order of magnitude or so) over hand-written ActionScript.

That’s it for now, but I plan on writing more about compiling with Alchemy, using GlueGen (a special language you can use with Alchemy to somewhat automate the task of writing C-to-ActionScript glue code), and utlizing Alchemy-compiled libraries within Flash and Flex.

Finally, let me just give a public “THANK YOU!” and “OMFG U RULEZ!” to Scott Petersen(the father of alchemy), Joe Steele, and all of the other employees at Adobe that made Alchemy happen - it’s simply an awesome tool!

Spiking Greedy SWFs

A project we’re working on requires third parties to be able to load SWFs of their own design into an overall “shell” that we’re building. So far, so good - particularly with the new unloadAndStop method that’s part of Flash Player 10. That means I can fully unload the SWFs no matter where they managed to sink their teeth/event listeners.

Then I started to think about a weird edge case… what if the creators of these SWFs accidentally does something spectacularly bad like get stuck in an infinite loop? I had a few ideas for a solution, and so I decided to spike them and see if any of them worked (The link explains what spiking is - but in a nutshell it’s a quick-and-dirty end-to-end solution that tests out an idea).

To test my solutions I made two SWFs - one with a simple spinning animation (spinner.swf) and another that, with the push of a button, would lock up for 5 seconds (greedy.swf). My first idea was to put the SWFs on the same HTML page and have them talk via LocalConnection. The spinner would monitor the greedy SWF (when ever the greedy one started, it would tell the spinner) and if the greedy SWF went on too long the spinner would talk back out to Javascript and tell it to replace the Flash Player instance.

That didn’t work in the slightest.

As soon as the greedy SWF started getting greedy, the spinner would lock up too. I even tried putting the SWFs in separate HTML files and loading in one via an iframe - same result.

The next solution was to have Javascript do the monitoring. So now the greedy SWF would call out to Javascript before it started getting greedy and the Javascript would then start a timer. If that timer wasn’t reset by the greedy SWF finishing it would unload the Flash Player running the greedy SWF. Pretty decent idea, yeah? Nope.

It seems like (at least in the browsers I tested, Safari and Firefox), when Flash is locked up the rest of the browser, including JS is locked up too. The timer would only first AFTER the greedy SWF stopped on it’s own accord.

So where does that bring us? Well, these solutions or something like that may work in IE, particularly since it’s running on a whole different plugin architecture. It may also work in Chrome since it’s whole architecture is based on isolating processes. That being said, a real cross-browser solution remains elusive. I guess I’ll just have to hope the 3rd party SWFs don’t suck and maybe do a bit of testing on them before I roll them out to the public.

LAFlashapaloozastock III

Branden will both be speaking at the free Flash conference LAFlashapaloozastock III in Venice Beach, CA on December 6, 2008.

To help keep the event free Branden will also be teaching a very cool course of his own titled “Creating Killer ActionScript Robots For Fun & Profit” on December 4th and 5th. It’s going to be a two day romp through ActionScript 3 learning advanced programming techniques in order to make software robots with which the students will do battle! The course is $499 per student. If you’re interested click the course title to find out more.

Comments: Leave a comment

SOAP is Just XML

Recently, Branden and I were tasked to build a Flash UI on top of a web service.  Seems like pretty standard development…but, as you have to know by now, nothing is ever “standard” at Automata.  After some research, trial & error, and hand-wringing, we realized that the device we were attempting to connect to was using SOAP 1.2.  Well, unfortunately, Flex only supports up to SOAP 1.1, so we had a bit of a problem.

It didn’t take us long to remember that SOAP was just XML, and that Flex’s web service API was just a nice class that makes it easy to speak that language.  After deciding to nix the Flex solution (we were only using Flex for the WebService API), we moved to an all Flash solution.  We created a connector class to act as a web service API, and simply sent XML packets directly to the server using URLLoader.  One note about this solution is that it will only work if you have knowledge of the web service you are trying to use.  In our case, we had the entire schema at our disposal, so we knew the exact format of the service operations.

The connector class contains public methods to call the individual web service operations.  Additionally, we created individual request classes for each of the operations that extended a class called Abstract Request.  AbstractRequest provides a method send(uri:String, headers:Array) that uses URLLoader to send the request to the server.

The “uri” parameter of send() is the full path to the web service, with the “http://” attached.  The headers are the HTTP headers that you need to send to the web service for such things as authentication.  In our code, these are set in the Connector class, and passed to each request as it is needed.  The “_request” property holds the XML object that you will pass to the server.  This XML is formatted as an XML packet specific for this web service.  The value for this property is defined in the AbstractRequest sub-classes.

The _request property is an XML object that defines the format, and uses Flex-style binding to add the actual data from the constructor parameters.  This is a little-known XML trick you can do in AS3.  Branden found it in the Help section of the Flash CS3 IDE.  Pretty neat if you ask me.

Back to the AbstractRequest class, we simply set the data property of the URLRequest intstance to be the string representaton of the request XML, and call URLLoader.load(), passing in the URLRequest instance.  This sends the XML packet to the server.  The handler for Event.COMPLETE will receive the XML returned from the server.

Our connector class has methods like:

1
2
3
4
5
6
public function addGroup(groupId:String, groupName:String, flag:String):void {
	var request:AddGroupRequest = new AddGroupRequest(groupId, groupName, flag);
	request.addEventListener(ISYResultEvent.EVENT, onResult);
	request.addEventListener(ISYFaultEvent.EVENT, onFault);
	request.send(_uri, _headers);
}

This actually executes the web service call.

And just like that, you’ve build your own web service class.  While it’s quite specific to the web service you are using, you could certainly expand it to consume a WSDL file so you can use it for any web service.

Flash on the Beach 2008, Brighton, UK

Branden will be giving his talk on “Brilliant Ideas that I’ve Blatently Stolen” at Flash on the Beach which runs from September 28 - October 1. Branden will be speaking on Monday, September 29 so if you are there, be sure to catch his session!

Simplifying code with finite state machines

Yes, it’s been a while. We’ve been busy. The good news (for you) is that we’ve been making fun new things (i.e. code libraries) that we’ll be sharing soon!

Now, on to the actual topic of this post - finite state machines. What is a finite state machine you ask? Well it’s just a construct that lets you track the states within a piece of code and ensure that you only do what you’re allowed to do when you’re allowed to do it.

A while back I wrote a generic finite state machine (I called it PastaMachine - since every time I wrote FSM I thought of the Flying Spaghetti Monster). It is exceptionally generic - you just define states, define the allowed transitions between those states (state A can go to state B, but B can’t go back to A, etc) and the actions that each state may take (an action may trigger a transition, but it doesn’t have to). The states themselves can have attached to them an arbitrary amount of metadata and in less than 340 lines of code you have a simple finite state machine.

What can you do with it? Well, originally it was written to handle a branching logic game where depending on the users success at a simple game they went down multiple paths and were shown various different videos (yeah… it was a PG-13 strip poker game). But recently Keenan has been using PastaMachine to track the logic of an application to assist doctors in treating patients with HPV. If that’s not a nice range of usefulness, I don’t know what is!

One nice extra trick PastaMachine has up it’s sleeve is that once you’ve defined a state machine with it you can export the information about that state machine to data in DOT format. That DOT data can be loaded into the ever-so-awesome GraphViz and BAM! you have a directed graph diagram of your state machine! It’s actually really useful in debugging the state machine’s connections, but beyond that it adds a very nice “WOW!” factor when you present it to your client.

Over the next few weeks we’ll be cleaning up PastaMachine and sharing it with everyone. Then, if everything goes smoothly, there will be a number of other Automata code libraries following along behind it.

Charles - A great web application debugging tool!

During a recent project of ours we found ourselves in the position where the developer creating the server-side code was a full 5 time zones away. This meant that we often had to do debugging over email. This was, as one would expect, excruciatingly slow. The issues that arose during integration almost always resolved around how we were mapping the servers .Net classes to our AS3 classes - one small change to the server class could break things on our end in a non-obvious way.

Luckily early in this process we discovered a piece of shareware called Charles, a web debugging proxy that’s available for Mac, PC, and Linux. Once you fire Charles up it acts as a proxy for all of your web traffic. This lets you capture, view, and even throttle the data that’s flowing between your machine and the web server. And best of all for us, it lets you view inside of AMF packets and see exactly what’s coming over the wire. Once we got Charles up and working we able to tackle kind of issues that used to take us hours and resolve them in minutes.

We haven’t done a done with Charles yet, but so far our only wish is that we knew about it sooner. Suffice it to say that we found the $50 registration fee to be well worth it!

Older Posts »

Built by Automata Studios