ActionScript 3 inheritance: developers beware!

Following on from my recent post regarding variable scope within ActionScript, I’m going to explain another “gotcha” that can catch out developers used to “proper” OO languages, such as C# and Java. That gotcha relates to class/ static member inheritance.

Consider the following C#/ Java code (ignoring package-level considerations, it will compile in either language):

With C# and Java, there is nothing spectacular about this code. Sadly though, achieving this functionality in ActionScript requires a significant work-around. If we simply rewrite the above using AS3 syntax, we get the following errors:

and this code won’t compile. Instead we get:

As the “Static properties not inherited” section of the language reference explains, AS3 doesn’t support static member inheritance, thus the errors. This limitation can be worked around with a rather ugly bodge. Modify ChildClass to the following:

and the errors go away. Having to do this for every class that inherits from a parent with static members though would be both tedious and unmaintainable. It is therefore probably more practical to simply accept this shortfall with the AS3 language and work with it, rather than fighting it.

As a final point, the scoping rules of AS3 cause a weird effect related to this issue. Consider the following version of ChildClass:

This code compiles just fine. Even though i and method aren’t accessible via ChildClass for code external to ChildClass, within that class, all parent and other ancestor static members are accessible.

FOTB 2009 Day 3

Flash on the Beach 09The Flash Platform in a multi-screen world
Day 3 sadly got off to a bad start by me. I embarrassingly assumed that Serge Jespers’ session entitled “The Flash Platform in a multi-screen world” would be about running a flash-based application across multiple monitors. So I went to his session, only to discover that he was indisposed (not sure if he was ill or not) and so Mark Doherty was standing in for him. I went to a talk by Mark last year. I have nothing personally against the guy, I just really do not like his presentation style, nor do I find his subject matter very interesting. By this point though, with the session having started, there was no point in me leaving and heading off to my second choice for this slot: Koen de Weggheleire’s talk on vectors, as that was in the Pavelion Threater and so would be full.

As a quick ranting aside, Koen’s talk was on real vectors, ie lines connecting points in n-dimensional space. It was not about the “generics by the back door, but only for one class” type-safe arrays that Adobe added to flash player 10, but then annoyingly called vectors. One would have thought that in a company that produces Illustrator and Flash, someone would have been able to explain to the developer involved just what a vector was, and what a type-safe array was. My guess is the developer in question in Java-trained as – as far as I know – Java was the first language to introduce this bizarre naming practice.

Anyway, as I had no interest in applications on mobile phones, which was the true topic of Serge – and thus Mark’s – talk, I spent the hour writing my day 2 blog post, which goes some way to explaining the horrendous number of mistakes in it that the boss spotted and kindly pointed out to me <blush>.

Preparing for the Flash Catalyst’s era
The next session was by Marco Casario and covered Flash Catalyst. This was another session that the boss and I attended together and we were split on our opinions of it. Marco has a style of presentation that seems to divide people. He plods along at a slow pace, covering things very carefully. The boss’ take on it was that Mike Anders built two Catalyst-based applications in 40 minutes and Marco didn’t even build one in over an hour (he overran). My take on it was that Mike Anders clicked away like mad, so I got an idea of what Catalyst could do, but no idea how he did it. Marco on the other hand took it nice and slow and so I now know how to navigate my way around Catalyst as a result.

Jam Throwdown
After lunch (I skipped the next session  as nothing appealed), was the “Jam Throwdown”. We had six top quality speakers given 10 minutes each. They’d had little time to prepare, so the fact that all six were great is a testament to their skill.

First up was Grant Skinner, showed us how he plays with balls a lot. Some of his balls were really quite pretty.

Next up was some guy – I didn’t get his name, sorry – doing some clever stuff with encoding images in ways that could be sent over twitter and other low-bandwidth mediums. This seemed to involve firstly reducing the image to a small number of cells (inversely sized in relation to the area’s complexity) and then iteratively generating images via deterministic “noise”, or rotating existing images and using “best fit” area matches to populate the image.

To dive off into yet another aside, it struck me as wonderfully ironic that, in an age where rather strange folk in the US patent office view editing XML data files as “invention”, this man was prepared to show us his genuine inventiveness with no strings attached. Hopefully he is happier than all the world’s software patent layers combined, as he deserves to be.

The next session was by Julian Dolce and was much more up my “Nerd Street”. It covered an ANT plugin that lets a developer working within FlexBuilder generate and test SWF’s from FLA’s. The caveat – I think – is the fact that it was achieved by driving the Flash authoring tool, so it was of little use to those of us who see the Flash authoring tool as little more than “a bit of a waste of money really”.

Next was a demonstration of some clever sound generating software by Andre Michelle. I have the musical ability of a two year old, so whilst undoubtedly clever, this stuff really went straight over my head.

Jeremy Thorp was the next speaker. He is currently working on designing a playground using software that randomly generates swirling paths through 3D space, constrained by the need for example for slopes of no more than 5 degrees, to ensure wheelchair access. Google Earth was used to get the terrain data and – assuming the satellite images get updated at some point, his “artwork” will also appear on Google Earth in future.

The final “speaker” was Joa Ebert, though he didn’t speak. Instead he wrote – from scratch in 9 minutes 40 seconds – a OpenGL-based Java program that played music and had a 3D shaded box-like visualisation component in it. And he used a blank-key Das Keyboard to do it. Every developer present now hates him as our bosses will be wanting to know why we can’t code that fast 🙂

Research Realtime graphics with Flash 10
Ralph Hauwert’s session in the Pavilion Theatre was packed out and the room was unpleasantly hot as a result. Having accidentally lost all the work he’d prepared for FOTB, he’d produced a new session that took us through his personal graphics journey, from the days of the Commodore 64, through the greatness that was the Amiga and on to Flash. Using 3D techniques that went totally over my head, he demonstrated some really amazing graphical effects that Flash can achieve. He interestingly also pointed out that little of it used pixel bender as it isn’t actually that fast compared with what can be achieved with AS3 and Alchemy (and presumably a lot of “tinkering”). At the end of his session, Ralph announced he was leaving the PaperVision team. As I wasn’t even aware he was on the PaperVision team, this announcement was wasted on me. I gather it came as a real shock to some people though.

The last session of the day was a really great inspirational talk by the ActionScript-programming, tattoo-covered, skateboarding artist, Joshua Davis. He was very funny, very talented and he did something truly amazing: he explained the point of Flash on the Beach to me. I tend to complain about the lack of developer-orientated sessions and the over-abundance of “arty farty inspiration” sessions. For example, Grant Skinner’s spheres spinning about on the screen pulsing in time to music are all very pretty, but they are useless. So why does Flash on the Beach have so many of them. Joshua’s take on it was that he spends around half of his year just playing with those “pretty, but they are useless” ideas and half actually doing productive work that earns him money. The former may not directly yield anything useful, but it inspires him in his productive work. Likewise, Grant’s spheres may not directly have any real-world use, but they inspire him to learn more about Maths, Flash and ActionScript and so indirectly benefit him in his real work.

If John Davey is reading this, I’m sure he’s thinking “finally, the dimwitted developer has got it” as I’m sure that was John’s aim all along with FOTB: to inspire people to think beyond their comfort zone and to open their minds to new ideas and new ways of thinking. It’s taken me three years to get it, but I finally have got it. I’ll still continue to want more of the seriously hard-core nerdy programming sessions that I tend to bemoan the lack of, but I’ll also embrace the inspirational sessions far more too.

To wrap up, I’d like to publicly make a suggestion to John Davey. Each year, the number of attendees at Flash on the Beach. This year, hundreds of people really did say “bollocks to the recession, let’s go to Flash on the Beach” and they did so in record numbers. The result though was that the Pavilion Theatre could not cope with the numbers of people that wanted to attend the sessions there. If the conference is to grow any more, then it needs a bigger venue. The obvious solution (I’ve no idea of the practicality) is to expand it into the Theatre Royal, which is opposite the Dome and to add a forth, more technical, “track” that would take place in the Pavilion Theatre. That way the numbers of people attending could increase and we could have more technical sessions. Everyone would then be a winner.

So that’s it, the sensation that is Flash on the Beach 2009 is over and it was absolutely brilliant. Here’s looking forward to next year…

FOTB 2009 Day 2

FLash on the Beach 09Elevator Pitch
The first session of the day was a new – and it turns out, highly successful – experiment. We had 20 speakers, each given just three minutes for their talk. As one person spoke, so the next person’s laptop was plugged in to the projector switch box in readiness, so there was almost no delay between talks.

The topics covered included rotoscoping using flash, games creation, SQLite, generative art, applications for phones and RestfulX. Most were really good. Of special note was a hilarious presentation by Conrad Winchester on the topic of ASAXB, which appears to be a great framework for automatic serialization/ deserialization of AS3 objects to XML and vice versa.

Flash Catalyst in Action
Mike Anders gave us another tour of Flash Catalyst. It was similar to last year’s talk, but used the Flash Catalyst beta, rather than the Thermo pre-release he had last year. As ever, his talk was good. He demonstrated creating a aquarium information application, which included layered graphics, embedded video, test fading in and out etc. What was really great about it was the fact that absolutely no nasty, evil .fla’s were involved, the whole thing (excluding the graphic and video resources of course) was 100% editable FXG/ MXML. The spark component set, along with FXG, is really shaping up to be an excellent development toolset.

Leaving The Sandbox
I had been looking forward to Joa Ebert’s session. As a hard-core nerdy developer, my main criticism of FOTB is that it contains too many “arty farty” designer and/ or inspirational sessions and the developer sessions tend to be a bit on the basic side. A session on a code validation tools sounded just the sort of thing I’d been wanting. Boy were we in for a treat.

It started well with a quick run through compiler theory (as someone who’s developed compilers using lex and yacc in my distant past, this was just my sort of thing). Then he moved straight on to AS3V, by announcing he’d abandoned the project. Turns out that Adobe have been working on a similar code validator called FlexPMD.

At this point I was concerned I’d wondered into yet another “use ++i rather than i++ to shave milliseconds off your execution times” type optimisation talk. How wrong I was, for we were in for a roller-coaster ride of SWF compiler/ decompiler projects:

  • Apparat.  This is Joa’s basic SWF/ SWC optimization framework, from which he has built a rich set of tools.
  • Dump. This tool can be used to generate such things as UML and inheritance diagrams of the classes in a SWF/ SWC.
  • Reducer – This tool squashes the data for PNGs inside SWFs/SWCs to make them significantly smaller. It does this by converting the PNGs to JPEGs. By adjusting the JPEG compression level one can vary the amount by which the resultant SWF/ SWC in reduced in size.
  • TAAS – this is an automatic optimizer tool that let’s the developer write clean, easy to read, code and then inlines functions, converts power of two multiplications/ divisions into bitshifts, changes i++’s into ++i’s etc.

Having left the audience stunned, Joa then showed Steve Jobs how to do a real “one more thing moment” (we even had a Steve Jobs parody slide) by demonstrating two projects he’s working on that compile C# and Java code to SWFs. He even coped with the fact that – being a dinosaur language who’s spec is controlled by dullards – Java cannot cope with closures and neatly mapped Flex’s closure-based event handlers to Java’s class-based bodge-event handlers.

Joa earned himself a well-deserved standing ovation.

Application Frameworks: The good, the bad, and the ugly
After lunch, we attempted to get into Richard Lord’s session on frameworks. Sadly due to the session times being skewed all morning, lunch had been shortened (and we hadn’t been told), so the hall was full when we arrived. Hopefully it was therefore a really rubbish session 🙂

More than Bending Pixels
Paul Burnett’s session on pixel bender was pretty good. Pixel bender is a programatically-simple language, but clever maths-orientated people can use it to do some really stunning effects with graphics and audio. Of more interest to me though is the fact that it can manipulate any data and runs on a separate thread to the main flash player. So it has potential to be of use in encryption and geo-spatial calculations for example, without affecting the player performance.

Unconventional Web Applications
The day wrapped up with a very nice presentation on design conventions by an Irish company, Contrast. They explored why we have conventions, why it’s sometimes bad to break them and sometimes it’s essential to do so. It contained some really good advice. Take a look at their website to get an idea of their conventions-breaking design approach.

And so the day ended for me at least. It was a brilliant day, in fact I’d even go so far as to say it was the best FOTB day I’ve ever attended (this is my third year, so 2006 may have had a better one that I missed). Can’t wait for tomorrow…

FOTB 2009 Day 1

Flash on the Beach 09This year’s Flash on the Beach keynote started on a high with a hilarious act from three faux Mexicans. Having got everyone in the mood, John Davey came on stage to rapturous applause and introduced the folk from Adobe who were to do the main keynote piece. Sadly the keynote then went downhill and left me wondering quite why I’d bothered. As much of the Flash stable (Flash Catalyst, Flex 4 SDK & FlashBuilder) are all currently in beta – and with just 2 weeks until MAX – there was little in the way of new stuff to show us. So we were subjected to yet more AIR applications along with some style-over-substance (or “proof of concept” to be more generous) 3D and sound demos.

Toward the end of the keynote, we were at least treated to some sneak peaks at upcoming features in the next release of the Flash Pro authoring tool, including better integration with FlashBuilder. There was also a hint that there might be news on Flash Player 10  finally appearing on smart phones (though presumably not the iPhone) at MAX.

Next up was a presentation on AIR by Mike Chambers. It was a curious mix of self-promotion of his as3corelib project and some details on features coming in AIR 2.0. The latter is to gain built-in support for detecting removable drives being mounted/ unmounted and a new native application mode. The native mode will be built as a .exe (or the MAC equivalent) and can communicate with other native applications via stdin and stdout pipes. This seems an odd solution when the likes of Mike’s own Command Proxy project offer a much richer solution already. I guess we will have to wait for more details from MAX to understand the solution better.

The only other session of note – in this developer’s view – was a session on Spark by Mike Jones. Sadly Adobe have dumped the great name “gumbo” and replaced it with the far more boring “spark” for their new skinnable component set. The session described the current state of the spark components (subject to change of course as it’s all still in beta). Despite many criticising the namespace in CSS solution Adobe came up with to support both halo and spark in the one application, I personally think it’s a very nice solution. Catalyst remains a odd one. At the moment it just doesn’t work to my mind: it is too product-skin focused and only really goes one way from designer -> developer. I fully agree with Mike’s hope that the final product better support general (and custom) component skinning and that it better support a two way design/ develop workflow.

Tomorrow has far more developer-orientated content than today, so hopefully should prove a more fruitful day for me.

Napkee: converting Balsamiq mockups into flex views just became a complete breeze

Balsamiq mockups is a truly outstanding mock-up drawing tool. It is simple to use, yet enables the quick and easy creation of detailed mock-ups of even quite complicated user interfaces. Yet it has always had one big problem: it only creates mock-ups. The design then has to be painstakingly recreated using some application-dependent GUI creation tool, for example Flex Builder. What Balsamiq mockups lacks is the ability to generate MXML directly from a mock-up.

Step forward a new application: Napkee. It is an Adobe AIR application (so should work with Windows, Linux and Mac OS X) with a simple yet effective aim: transforming Balsamiq-generated mock-ups into web pages and Flex views. As this is something I’ve wanted to do for a while, I took the application for a spin, with the following results.

Being an AIR application, installation was a breeze. Simply visit the Napkee website and click on the Launch Now button. On Windows, if you haven’t got AIR installed, it prompts you to install that first automatically. Then the application itself is installed. I don’t know if this simple installation method applies to Linux and OS X, but I assume it does.

Functionality overview
Napkee is very simple to use: start it up, import a mock-up and convert it to a Napkee file. This can then be previewed, copied to the clipboard and saved as a Flex project. And that is about it. Simple, yet effective.

Putting Napkee through its paces
To test it out, I created the following mock-up. It’s not going to win any design rewards, but it shoehorns lots of controls into a space small enough to display here 😉

Balsamiq mockup for my Napkee test
Balsamiq mock-up for my Napkee test

So it has:

  • A canvas with a scrollbar, containing:
    • An accordion opened on “Item One”. containing:
      • A button bar and menu
      • Breadcrumbs and a button
      • A checkbox (not ticked) and a text box
      • An expanded combo-box and a text field
      • Then on the left going down: a collapsed combo-box, two radio buttons, a link and a numeric stepper.
      • Beside them, a tab set on tab One, containing:
        • Vertical divider, with a label above and a progress bar below.

I then saved this, started up Napkee and imported my mock-up. It loaded it OK and presented me with the following preview:

Napkee preview of the imported mockup
Napkee preview of the imported mock-up

Visually, it looks near spot-on. The only things that didn’t get imported were the vertical divider and scrollbar. The preview is actually created using real Flex controls, so one can interact with it. Doing so reveals that the values for the top combo-box were successfully imported. As the screen shot below shows though, it also reveals a flaw with the program:

Rendering problems with the Flex view
Rendering problems with the Flex view

I’ve selected “Item Four” on the accordion and “Four” on the tab set. This reveals (in a rather messy fashion) that Napkee failed to treat these items as containers, so as the tabs change, the visual contents do not.

Finally I exported the project, fired up Flex Builder and imported the project. Running it reveals another odd bit of behaviour: the project MXML has no size constraint and the canvas created from the mock-up has a x=4, y=8 offset. This results in a flex-coloured background filling the browser windows, with a white rectangle slightly offset from the top left corner. After fixing these, I ended up with the following SWF:

And another thing
The MXML code that Napkee generates automatically assigns id’s to the imported components. The resultant code ends up looking like:

I feel is OK, but is very little messy. I’d really like to be able to give the components real names. Given that Balsamiq doesn’t have the facility to name components, I’d like to see Napkee providing some facility for applying useful labels to components. This could either be in the form of some interactive import dialogue, or by being able to select items in the preview and name them.

Napkee costs $49 for the Flex license (a version that can output HTML+CSS as well is available for $79) and for that you get a very effective tool for turning Balsamiq mock-ups into Flex MXML code. Sure I have a couple of gripes with it and feel it has a key missing feature, but the developers aim to provide frequent updates to the product. Hopefully therefore, these issues will be addressed soon. I have no hesitation therefore in recommending this product to anyone who does Flex development.

Reference files
You can download the source files I used for this article via the links below:

The original Balsamiq mock-up file

The Napkee source file

A zip of the Flex Builder project Napkee generated

iTunes 9: nice new features, shame about the face

UPDATE 26/11/2009
As of version, which I got around to installing today, iTunes support of Windows 7 features is greatly improved. It now has a drop shadow like other windows and supports the auto maximizing, 1/2 screen sizing etc features of Windows 7. The naff pseudo-OS X look remains, but it is a huge improvement on the original v9.

itunesToday saw the release of iTunes 9 from Apple. It has brought a range of great new features:

  • Home Sharing: share your iTunes stuff between home computers with ease. In theory, it will automatically sync purchases between computers, though this didn’t seem to work properly for me. I was able to manually copy them across just fine.
  • Genius Mixes: these are like standard Genius playlists, ie related music grouped into playlists, but the Genius Mixes are 12 automatically generated endless playlists based on your music collection.
  • Improved Syncing: you can now organise your iPhone apps from within iTunes, rather than via the very fiddly method on the phone itself. There are other syncing features, but this is the big one in my view.

Sadly all this greatness is let down by the crappiness of the iTune’s interface. Continue reading “iTunes 9: nice new features, shame about the face”

ActionScript 3 variable scope: developers beware!

Consider, if you will, the following piece of non-language-specific code:

If you are a C#, Java, C++ etc developer, such a piece of code might look decidedly unspectacular. Not so with ActionScript 3 (AS3) though as I recently discovered.

The equivalent in AS3 would be:

and this code won’t compile. Instead it will report an error due to variable i being redefined as a different type. Further, if you change i in the first loop to be an int too, the compiler will then issue a warning that you are redefining i.

Being used to languages such as Java, C# and C++, I put this down to a compiler bug, disabled what I thought was a pointless warning message in my projects and carried on happy I’d hidden an annoying bug. How wrong I was. I recently discovered a bug in my code was due to a variable defined inside a loop changing the value of a variable of the same name at the method-scope level. It turns out that AS3 doesn’t support block-level scope for variables. Variables can only have one of three scopes:

  • Global
  • Class
  • Function

Whilst a function-level variable can override a class-level one, variables defined inside code blocks (such as loops, try blocks etc) have method-level scope.

The following code illustrates how AS3 variable scoping works:

Tracing through the code, I would have expected the following output:

The resultant SWF is included below. The results are really rather different:

The version of aVariable defined in go() is in scope from the start of the method, so label1 picks up its default value, rather than the class-scoped variable’s value. And the loop uses the same variable, so label4 is 4, rather than 2.

For more information on AS3 variable scoping, I refer you to the “Understanding variable scope” section of Adobe’s official AS3 language reference.

You can download a zip of the FlexBuilder project used to create the above SWF here.