Category: ActionScript

  • Example for Flex Component Kit for Flash CS3

    If you saw the amount of work you have to do in my past article, you’ll appreciate how much work you DON’T have to do using the new Flex Component Kit for Flash CS3 (now on labs with 50% more beta!). I’ve modified my example from that article using the new kit to show you how much easier it is to both create Flash assets for Flex, but also to use them IN Flex 2. Deadline at work, so too little time to do another Captivate; hopefully images’ll do.

    First, let’s take a look at the FLA in CS3 on my MacBook. Notice, nothing on the root timeline / stage.

    Going into the BackgroundPanel symbol in the library, notice no code on frames. You can see the bottom layer is where I put my bounding box. This is a convention used since Flash 5 (before my time, hehe) which gives the MovieClip a “default width and height”. Now, for Flash components, this was typically used for the size methods written in ActionScript. In Flex, it does a whole lot more. Flex has a layout engine that measures MovieClip’s, and that way “knows” when to show scrollbars. By default UIMovieClip measures every frame so if your Flash animation increases in size, so too will your content in Flex. When you are playing inside of containers inside of Flex, this is VERY important. Here, though, I actually WANT to remain square. Therefore, I make a 800 x 600 MovieClip with an instance name of “boundingBox”.

    Now, the contract you have to abide by as a Flash Designer when creating assets for Flex is 2 things: states and transitions. You create different “states” that your component / animation exists in. In my panel’s case, these are: hidden, intro, main, and spin. Flash Developers typically would use either the timeline or different redraw methods. A Flex Developer uses the state tags. These 2 will now be combined. The Flash component will “represent” the state tags in Flex via frame labels on the MovieClip symbol’s timeline. This way, a Flex Developer can use the familiar syntax on your component:

    panel.currentState = “spin”;

    The second is transitions. Transitions are the changes that happen form one state to the next. For example, in my Login Form example, I show how you can change from one state to the other and give visual feedback to the user you’ve changed state. You represent transitions in Flash via specifically named frame labels.

    For good or ill, transitions are (at least with the version I have) all or nothing. Most Flash Designers who are timeline junkies will read that and laugh. That’s the attitude. I’ve found the component acts weird if you only define transitions for some states, and not others. Best to do at least the default transition to each state.

    One quirky thing is that the UIMovieClip will go to your state frame label when it’s done playing the transition, if any. I didn’t really like this. The compromise Adobe came up with is to put your state frame label on the same frame as your ending transition frame label. Now, most of us Flash Purists think putting 2 frame labels on the same frame is blasphemy… madness!

    …however, it actually works out well here (thanks Glenn Ruehle!). It makes it easier for as an animator to have my ending transition “end” on the state. However, for more complex animations, like the one Grant Skinner showed at 360Flex, it actually behooves you to animate unique transitions for each state change.

    For example, if I were animating a human character, he could have 3 states: stand, run, and sit. If I were to set the current state from sit to run, I wouldn’t want him to immediately start running; I’d have to animate him to stand first. For non-animators, this can seem like a lot of work. For those of us in the know, it’s necessary for a good looking component.

    So, again, you may find another frame label timeline convention you dig; no worries.

    The syntax for states are “my state”; basically whatever you want. The syntax for transitions is a little more complex. It follows the way transitions in Flex work. They have a “fromState” property and a “toState” property. Transitions are always bound to a state change. You can choose a state name as a string OR a *. A * means “any state”. So, if you write fromState=”*” toState=”spin”, that means anytime the state changes to spin, play this transition.

    Frame labels in Flash use a “from-to:state” syntax. Dissecting this, the from is your from state, and can be the name of the state, OR *. Same goes for the to; the to state name or a *. The state is the name of the state, and must be a state name. Always put a start and end set of transition frame labels. If you misspell the frame label, currently there is no JSFL to help you out, and the Flex Dev will most likely get an error dialogue that isn’t easily debug-able. He’ll probably blame you so just make sure for every “start” you see an “end”. Keep in mind too that for some transitions, it’ll use the end frame to play them backwards depending on what state you are changing too, so animate accordingly.

    You’ll notice for my simple example, I’ve been slack and just put the state frame labels at the end of the transition animations.

    For example, if the Flex Developer were to use this component, and set the currentState = “intro”, then it would do a gotoAndPlay for the “*-intro:start” frame.

    Same goes for the spin, regardless of what state you were on previously:

    Notice that the main state doesn’t really have any transition; it’s just the main state where you mainly are, and thus it is plain Jane, reflective a main type of state. Word. Yes, it does have an event sound, though.

    Now, when creating this component, you do what you typically do in Flash. Create a new MovieClip symbol, name it, and hit ok. You’ll notice the Linkage dialogue in Flash CS3 has a new field: All Your Base Class are Belong to Adobe. When you create a MovieClip in Flash CS3, it’ll default to flash.display.MovieClip. Good, leave it be, let it create your symbol.

    Later, you can run the Flex Kit JSFL command, and it’ll put the needed SWC in the Library, and then convert your symbol for you to have the correct base class (mx.flash.UIMovieClip); all you have to do is select it in the Library. It’ll tweak your FLA settings (in a good way) too.

    Poof; it’s exported as an SWC where your SWF usually is. Done!

    Few more quirks. Flex states are based around the Flash Player 9 DisplayList model. DisplayObjectContainers are basically MovieClip like things. Except, instead of createEmptyMovie, attachMovie, duplicateMovieClip, unloadMovie, and removeMovieClip, we have a brand new API. This API allows us to create MovieClips, but NOT have them draw. In the past, we’d stop it’s animations, turn it invisible, move it off stage, and pray. This didn’t work so well with a ton of MovieClips. Now, we can just go:

    var a:MovieClip = new MovieClip();

    And call methods on it, but not actually have it automatically have to be drawn in some depth. Now, we go:

    addChild(a);

    And THEN it’ll draw. Cool, right? You can even re-parent it, and remove it without killing all the code on it. Dope.

    Problem? Flex states are built atop this. When you go to a state, things are removed from the DisplayList and others are added. What happens to those that are removed? Flash Player does what it was built to do; it removes them from memory as needed.

    Great for application developers, suck for designers. From the day I got into this industry, I’ve made it my mission to ensure my stuff plays hot, and if it means taking all of your CPU and RAM to do so, so be it; it’s there for the taking Blackbeard style.

    The hack I showed at 360Flex has been modified slightly. Basically, I’d put all of the frames on a MovieClip, since those have to be preloaded before drawn, and then put it before the animation. Now, I’ve found better results doing the same thing, but having it last he entire tween. Notice the spin and intro preloader layers in the above pictures below the animations. You can see what’s inside of those MovieClips here. Technically, you should just put them all on one frame, but I ran out of time. I then just made them alpha 0. If you move the off-stage, the measuring code will think your Flash component got really really big, and then you’ll see scrollbars in Flex, and go wtf?

    So, what do you do with your SWC? You give to the Flex Dev, and smoke ’em if ya got ’em. The Flex Dev then, if he’s a purist, he’ll throws it in a lib directory. For this example, I just throw it in the root project. You then link it to your Flex Project via adding it to the Flex Build path as a Library via Project > Properties, and then Flex Build Path, Library Path tab, and then Add SWC button.

    You’ll notice a sample implementation here with Buttons setting the current state of the panel. Notice the lack of strong-typing; I’m such a rebel (-es=true -as3=false -strict=false 4 uber h@X!!!).

    Now, I think I broke something, but the convention is “boundingBox”… or it’s ilk. You name your MovieClip that, and that’ll define your component’s rect. In MXML (or AS if you were so inclined) you can set the bounding box instance name to use. I don’t recommend this, but hey, freedom’s rad, choose what you want.

    This’ll compile to something like this. If you’d like to play, click the image. WARNING: Has sound – she’s loud.

    To give you a visual example of what this would look like in Flex (uber simplified btw), here’s the states defined in MXML instead.

    And the corresponding (optional) transitions that match those states.

    Some dig MXML, some dig Timelines, I dig both.

    Few final tips. Every time you recompile a new SWC (Test Movie / Publish, whateva’), don’t forget to Refresh the Flex Project, or you’ll get the cached version. I usually use an Ant script to just copy the new .SWC from the assets directory (or however you setup your Flex projects). Also, not sure if it’s fixed, but if you’re Flex Dev starts getting code hints for “frame31():Object”, don’t be alarmed. If you put code on the timeline, I’m the only guy I know that fires people for that (except stops of course… I’m not THAT mean). These methods are merely created from code you have on that specific frame (thanks Robert Penner!).

    One thing to notice in some of the above images of Flash’s timeline is the Flex friendly layer vs. the Flash friendly. You un-guide the Flex friendly one for development and testing. That way, Flex Builder doesn’t chug loading all of those uncompressed PNG’s into memory, thus making Flex Builder compiling really slow. When ready, you just un-guide the Flash friendly one, and re-guide the Flex friendly one, and finally recompile. Naturally, most people are using video nowadays or hand animated bitmaps & vectors which are immensely less RAM intensive. Then again, good to know.

    Also, this whole example didn’t use any ActionScript. There is no reason I couldn’t make an ActionScript 3 class for my component. If you don’t write a class, Flash CS3 will make one for you. So, I didn’t have to make a “BackgroundPanel2.as” file. If I wanted to, I could of written an AS3 class to maybe play some other scripted animations, or play sounds… video, whatever.

    Finally, don’t forget to remind the Flex Dev to up his framerate via the Application tag (or compiler… either or)!

  • Invalidation Strategies for Flash Player

    Skip Intro

    Had the honor of meeting up with an old friend yesterday. Chris Skogen, one of the talented gents at Gizmolabs, was my manager & tech lead when I worked at BellSouth. He’s an extremely talented programmer, doing a lot of C, C++, assembly, and Java. Below is some of his team’s coding + hardware work in action. This is not actually the record music playing, but rather, the record’s time code being used to scrub an MP3. Plethora of other features but… isn’t this one alone enough to make you go, “OMFG!!!”

    He’s been doing it for a long time, and since I respect anyone who has a lot of experience in this industry, I pretty much spent the day absorbing every word. We were supposed to meet for lunch since her majesty and I skipped out on going to a Christmas party of a friend of his that we RSVP’d too. Figured, I could buy him lunch and he’d forgive me. Anyway, instead of staying an hour at noon, stayed till 7pm mainly talking shop, finishing with Gears of War coop. He’s the guy that got me typing my brackets on a new line after he and another C coder at BellSouth started making fun of my if statements (Flex Builder is biased against this way of coding, btw…bleh !). He was also the guy who first introduced me to the Command pattern, and wondered if the Flash community had any framework like that. Four months later, I was all into ARP, which has the Command pattern as its central crux.

    I spent some of the time asking about invalidation methods. Invalidation being defined as “painting the screen with pixels in an efficient manner”, also known as redraw. Since he develops for multiple platforms, he knows the libraries and strategies involved for screen redrawing on Linux, OSX, Windows, and various devices. I remember one of Bruce Epstein’s books, Director in a Nutshell describing “The Great White Flash”. It’s been so long I can’t really remember the cause, but the redraw of the window caused the application to start with this white flash, basically a redraw of the screen that sabotaged the initial experience with various ways around it. When Chris would describe Windows redraw events compared to other platforms, it sounded all too familiar. The Director mantra back then was, “If you build it on PC, you know for a FACT it’ll work just fine on a Mac. If you develop on a Mac, it will NOT work on a PC.” A lot of the intricacies of when something redraws an area, how you have to manage it, etc. seemed really gross, and painful. However, like a lot of C guys I’ve talked to, he seemed to take it stride, view it as a conquered fiefdom, and begin to relay the double-buffering strategy employed in some cross platform library. Must… get… that… attitude!!!!

    In particular, I recently had the good fortune of getting Greg Burch’s, bloke employed at Adobe on the Mobile Team, feedback on my Flash Lite 2 component set. The guy clearly knows his stuff, has massive knowledge in ActionScript optimization, and is very focused in achieving that goal. He also understands mobile GUI development as well as the experience users expect on devices. After talking to him on the phone, I can clearly see why he is employed with Adobe on the Mobile Team. In our discussions, both offline and on, he basically set out in the opposite direction as me. While I was originally interested in creating a nice API as a tertiary benefit to the original 3 goals, he instead approached it from a “we must make it lightweight”. Even 10 seconds of his recounting of past projects with no supportive details clearly indicates that he has earned in blood a lot of great techniques and understandings. Basically, he is making the code look as much like ActionScript 1 as possible (even C for that matter), not as an intention, just a result that optimization and ActionScript 2 & OOP do not go hand in hand. While he is confident and happy with these potential changes, I was somewhat disheartened. His suggestions all met the first goal of “if it runs Flash Lite 2, the framework needs to work”, but I felt it was losing a lot of it’s utility to developers; they would now have to do a lot more work (typing basically, and not all of it comfortable). However, if you are going to run under the insane CPU & RAM restraints, no one is left unscathed. Welcome to the suck.

    After talking to Chris, however, he pretty much corroborated everything Greg was suggesting and had little empathy for my forlorn yearning for OOP. This lead to a very interesting discussion about inheritance vs. interfaces. He’s a big believer in programming by contract; having classes implement interfaces instead of using the extends keyword. After hearing him recount the challenges of being “a slave to the base class”, I totally understand and agree… for large scale projects with uber-knowledgeable individuals. If you are on a deadline, and have a variety of skill sets on your team, abstracting details seems to me like a good thing. I hate those projects, though,hehe! Flash Lite, however, has no room for interfaces as they too are basically objects like classes, and take up RAM. I digress I know, but it’s fun stuff.


    Anyway, let me give some context first. There are multiple ways to redraw things to the screen in the Flash Player, with different repercussions in performance and developer approach. You basically have the following options in Flash Player 9:

    1. DisplayList
    2. Blitting
    3. Drawing

    Both blitting and drawing depend on the DisplayList, but they are not mutually exclusive. The DisplayList is the act of adding a graphic object to a list of “things to draw”. If the Flash Player see’s it in there, it’ll get drawn. You can remove the object from the list, and it’ll no longer be drawn. This has a lot of positive repercussions in that a graphical object can exist in RAM without taking up CPU resources being drawn. Flash Player 8 and below did not do this. If you created a graphical object, like a MovieClip for example, even if it was invisible, it would still take up system resources being drawn every frame.

    Suddenly, the programmer now has control over what is drawn, and when. This makes coding easier, too, because you can choose when to draw things, therefore writing more scalable & efficient applications… just what Flex needed when you started writing these gigantor Enterprise apps that made Flash Player 7 & 8 scream in pain.

    There is something, however, more efficient than the above. This is called blitting. It is the act of painting a bitmap to the screen. A Bitmap is a DisplayObject in Flash Player 9, meaning it can be painted, or not painted, to the screen at the developer’s discretion. While Flash Player 9 has removed the problem of “too many objects == too much system resources”, Bitmap never has this problem even if those objects are in the billions. This is because you only ever have 1 bitmap (usually) that you paint on top of. Therefore, you actually have multiple small objects in memory that are then redrawn at some interval to the screen, and ONLY those areas that have changed. This is actually what is probably under the hood of the Flash Player, written in C/C++, that is redrawing all of your DisplayObjects. However, if you know going in that you’ll have a lot of objects which aren’t interactive, blitting is a wonderful technique that scales well, uses less RAM than the DisplayObject , and CPU is minimal because Bitmaps don’t use a lot of CPU to redraw compared to vector graphics. This technique can be used in the Flash Player 8 as well, although, there is no DisplayList so even if the Bitmap isn’t being visibly shown, it is still taking up CPU cycles to redraw it. Both can be combined with double-buffering where you paint to an off-screen bitmap, and copy pixels onto a on screen, smaller one.

    Finally, there is drawing. Drawing is the act of using the Flash Player’s vector drawing API to create vector graphics. These are wonderful in that the engine to create them is small, and they take next to no RAM. They look nice in terms of anti-aliasing, and the API is simple enough you can create some pretty sophisticated results by building atop that foundation. The downside is that drawing doesn’t scale very well. A lot of “anything” in Flash Player 8 and below used a lot of CPU, and vector content is definitely a prime candidate to use those resources. There are various techniques you can apply in Flash Player 8 and 9 using cacheAsBitmap, scrollRect, or even blitting the resulting drawing and thus removing the vector part.

    The way each of the above is rendered is doing on an interval, called a “frame”. Flash Player was built originally as a vector to pixel renderer , and later incorporated a timeline to show changes in these images over time. In effect, a lightweight animation tool was the result, hence Flash Player’s rising popularity for design in the Internet during the modem, low bandwidth days. These frame ticks run on some developer / designer set time code, like “15 frames a second”, or “120 frames a second”.

    What that means is that the Flash Player will update the screen 15 times a second, but more no more. It is not guaranteed to update the screen that many times for various reasons such as screen refresh, CPU usage, etc., but it IS guaranteed not to update more than the set frame rate. This is useful for animators to convey motion. As Ted Patrick has written about in the past, the introduction of the ActionScript Virtual Machine share’s this time between rendering. The important thing to understand, though, is that ActionScript for the most part is single-threaded. This means that once it starts, it doesn’t stop till it’s done running all of it’s code. If you have a lot of “stuff” happening when a user clicks a button, that code is run, and nothing else can really happen in the meantime. There are various threads that the Flash Player spawns to handle network operations, keep tabs to see if theAVM stopped responding for whatever reason, but none of these are accessible to the developer. Bottom line, if you’re code is busy doing things, you’ve allocated less time to the Flash Player graphics renderer to redraw the screen, and thus you’ll lose redraw fidelity.

    How do you then lessen this impact, and create an effective invalidation solution given the technology?

    In Flash MX and Flash MX 2004, an invalidation routine was created that ensured that components were only ever changed visually once per frame. This was done because while the developer was more than capable of changing a MovieClip‘s x and y coordinates on the screen multiple times in a few milliseconds, it would only actually render once. Changing those properties directly actually triggers a need to redraw event in the Player, and thus you are being very inefficient in your use of the Flash Player. To remove this problem, the first technique was a convention called drawing and invalidation. You would have a few private properties in a base class that abstracted MovieClip , and allowed you to change it’s properties with the ability to then invalidate on your own time. Some would invalidate immediately. It was a good first attempt, but was more formalized and better implemented when ActionScript 2 came onto the scene in Flash MX 2004. While AS2 still outputted the same bytecode as AS, it still implemented the main function that made this possible, introduced flexibly in Flash Player 6: onEnterFrame.

    The enter frame event is something emitted every frame. In Flash Player 9, DisplayObjects do this regardless of whether something has a timeline or not, 1 frame or 10 billion such as MovieClip & Sprite. While the name itself is somewhat legacy, it is useful to understand what it really means. First, it is guaranteed to be fired once per frame. Unlike setInterval which can fire randomly (at most 10 times per frame, or less for longer intervals), you can depend on the onEnterFrame function to run when you expect it to run. When it actually fires within a frame context isn’t important. What is important to know is that it is synonymous with “redrawing now”. Since you can only redraw once per frame, it fits in nicely with knowing when you are best suited to do so effectively. FlashMX & Flash MX 2004 would use the invalidate method for graphical components. This meant, “redraw next frame”. So, the developer could change a bunch of properties, styles, etc. and theMovieClip wouldn’t actually redraw itself visually (by setting _x, _width, applying a color, etc.) until the next screen redrawn, no matter how many were changed, or how many times the same one was changed.

    This was great in theory, but a lot of the race conditions with measurement and styles made it hard to effectively do. Regardless, it was THE best way to ensure effective redraw. This was slightly improved upon in the Flex 1.5 framework with a more formal system:
    – set a property
    – if it causes a redraw, invalidate a draw function, otherwise have that property’s dirty flag set
    – if a dirty flag was set, determine what type of redraw to perform, a draw, size, measurement, or style change
    – invalidate one of those functions if applicable
    – one of the invalidated functions would run at the next redraw

    This made possible larger Flash Player applications. The problem was, though, that even if things weren’t redrawing and just sitting there, they were still taking up resources, regardless of the wonderful invalidation implementation. Hence Flash Player 9’s DisplayList being invented.

    Blitting is kind of a low-level, boilerplate affair, and it’s currently not used a lot by the Flex framework. This is a shame. While the Charting components and Flex components both make extensive use of caching as bitmap and setting effective scrollrects , I think for some of the non-interactive parts of charting, they could scale effectively better. I have not, however, read reports of problems with the charting components not scaling. Props to the power of ActionScript 3!

    A significant amount of the framework is being drawn with vector graphics via the Drawing API, and all uses extensive use of theDisplayList.

    So, returning to my invalidation implementation, I chose to use the Flex framework invalidation methodology in my implementation of a Flash Lite 2 component framework. Granted, I didn’t have the added or render event’s, but enter frame is all you really need. Seemed logical enough; you want something to efficiently redraw on a device that REALLY needs to be efficient. As I later found, some on my own, some with Greg’s help, there are a few problems with this.

    1. Most dirty flags in the Flex framework start out with default values of false. This default value takes up RAM, RAM that I don’t have.
    2. I am making an assumption that a developer wants to have the component redrawn when they change a property. This is an incorrect assumption to make.

    Regarding #1, one solution is to simply not define default values for the dirty flags. The if ( flag == true ) still results in a correct evaluation if the default value is false, undefined, or null. That way, the flags would only last for 1 frame. Unfortunately, that is still a lot because Objects, what all data-types derive and thus extend in pre-AS3, take up a lot of overhead so even a Boolean has a valid cost to think about.

    Regarding #2, there are numerous cases where data isn’t ready for consumption by GUI controls, or some other process hasn’t completed yet. Some of that data or relevant process may be needed to do internal calculations for redrawing. I’m slowly to see ways for developers to implement their own call to invalidate. So, instead of doing this:

    attachMovie ( ComboBox.SYMBOL_NAME, “cb”, 0 );
    cb.prompt = “– select a value –“;
    cb.dataProvider = someArray;
    cb.setClickHandler ( this, onClick );

    You would instead do (per Greg):

    attachMovie ( ComboBox.SYMBOL_NAME, “cb”, 0 );
    cb.prompt = “– select a value –“;
    cb.dataProvider = someArray;
    cb.setClickHandler ( this, onClick );
    cb.invalidate();

    Notice the only difference is the addition of a invalidate method call. This triggers a redraw. The former, every single public property set, and some methods may trigger a redraw, usually via getter / setters (which have a lot of overhead…). Yes, it’s efficient in that it supports an infinite amount of property setting with only one redraw, but again, I’m assuming the developer WANTS to redraw. Maybe they have the data, want to set it, throw it away, but are awaiting more. Maybe they need the above, plus they are doing it to multiple controls over a sequence so they can effectively deliver a large amount of data through a small series of steps the device can handle. Later, they can then redraw when they deem it necessarey to do so.

    In discussing this stratgedy with Chris, he’d recount a lot of techniques Apple’s Cocoa uses as well as some of his own implementations. He found the most successful (and I’m paraphrasing badly here) is when parents are responsible for drawing their children. This allows you can redraw just one section of the GUI, or if you need to redraw everything, you can call invalidate on the main parent, and it’ll cascade down the tree of children, who in turn call invalidate on their children.

    What I find interesting is that this technique could not only work in Flash Lite 2 / 2.1 which is basically Flash Player 7, but also in blitting in Flash Player 8 as well as utilizing the DisplayObject API in Flash Player 9. In fact, it’d be really nice if Flex 3 gave us this option. I think the reason it’s not in Flex 2 is a lot of people need an accessible framework; meaning, low learning curve. Some people have never developed or programmed before, or not done that level of heavy GUI work, etc. Bottom line, I think the decision by the Flex team is “developers shouldn’t have to know how the Flash Player works to effectively write applications atop it”. I totally agree. I also believe, however, that there should be a way to optionally allow those of us who know what we’re doing to redraw when we see fit. It’d really help those larger applications, or when you are trying to squeeze all you can out of an implementation, say, Flash Lite 3 which could possibly use the new AVM on a device :: crosses fingers ::.

    While it’s more work for the developer, I understand why Greg suggested what he did now, and have more context as to the ramifications what power this really gives developers. I guess I just don’t really have in my head best practices on implementing this. The abstracted invalidation model that Flex has removes any care, and provides a nice convention for me to build atop of. Now, I suddenly have to care when I redraw things which could be different for each GUI control. Furthermore, the less utility I add to a framework by making it more efficient instead, the more the expectations of the Flash Lite community shifts to wanting more features out of controls. Not sure the best approaches to either. Fun, regardless!

  • Modular ActionScript Development

    In doing Flash Development for a multi-swf site, we ran into the “first class wins” problem. Basically, an ActionScript class’ bytecode is stored with the SWF that uses it. If the compiler detects a SWF being used, it’ll compile it in. This means, in a website that utilizes multiple SWF’s, 2 SWF’s that utilize the same class will both have their own copy. This is a waste of filesize which costs the user bandwidth.

    All classes in Flash Player 8 and below are stored on the _global namespace. This is a special object added in Flash Player 6 that allows the storage of data common to all SWF’s that are loaded in dynamically at runtime, either via loadMovie or loadMovieNum. Before _global, classes were stored on _level0 …usually.

    Flash Player 8 and below have a concept of levels. These allow SWF’s to be stacked on top of one another. You could do the same thing with MovieClips stacked on top of one another, but they had to exist in _root. Levels on the other hand each had their own _root. Now, there was a safe way to ensure every SWF was looking at the same data, and a great place to put classes.

    No class could be overwritten, however. Classes are basically written in an #ifdef fashion behind the scenes when using ActionScript 2, like so:

    // if the class isn't defined"
    if ( _global.Ball == undefined)
    {
            // define it
            _global.Ball = function(){};
    }

    Using that code above as a base, you can see how all subsequent loading of SWF’s have their classes of the same name / package ignored. The Flash Player assumes it’s already loaded, and thus does not use the class bytecode in the loaded SWF. On a job I’m on currently, we ran into this problem. We put a trace in our code, and it never ran when we deployed our SWF to the website. That’s because the website was already loading a SWF that had the same class, and thus was ignoring our new one since our SWF loaded later. Again, first class in wins.

    This same problem also exhibited itself with loading applications into Central, Macromedia’s early foray in getting SWF applications onto the desktop (pre Apollo). Since Central was a SWF loader of sorts, you’d have classes left defined on _global, like they should be. This caused problems however, when you would load in a new SWF to test and not see your changes. If you didn’t reload Central, or delete your class from _global, it’d stick around, and your newly loaded SWFs would use the old classes.

    The way class definitions work with loaded SWFs is not a bug and is by design for a few reasons. Additionally, it has been significantly improved in Flash Player 9.

    Paraphrasing Roger’s entry about flash.system.ApplicationDomain, the justifications are basically:

    • A Loader should control what it’s loading
    • Classes not being replaced by loaded SWFs eases security concerns
    • Makes static / Singleton implementations predictable, and work with child content accessing the same classes

    There are others, but those are the ones relevant to this discussion concerning Flash Player 8 and below.

    You can additionally use this implementation to your advantage. Roger discusses some ways with the pro’s can con’s to each with regards to Flex development. For Flash development, some additional points are a little different.

    For example, using Interfaces to allow 2 or more SWFs to talk to each other prevents the same class being included in both SWFs, and thus saving space. This includes all class dependencies, so you can see how this is a great way to encourage the good practice of coding by contracts (using interfaces) with strong-typing, both in ActionScript 2 and 3. This also prevents you from having to go through the laborious process of using Remote Shared Libraries. While RSL’s are great, there are currently no good tools (aside from ANT in Eclipse which Flash doesn’t have) to help management of RSL’s, thus they are a card house. When you get them working, they rock and look great. They are not change friendly; one breeze of scope creep or refactoring, and the whole thing comes crashing down. Hell, if it makes Darron Schall sweat, you know they are hard.

    Roger mentions that using implied dependencies via external-library-path isn’t such a good idea because the reverse, having the shell exclude loaded classes, doesn’t work as a use case and is backwards. With context to Flash, I disagree with the first part. I do agree that a shell excluding child classes is silly. Now, interfaces imply you have a good API designed. Our API and designs fluctuate daily. While I agree with Roger that usually your implementation changes, yes, in application development, I’d agree. However, in the Flash world, the shiz is chaos. It may sound like a cop-out, and it is. I refuse to write good code knowing it’ll get torched tomorrow. I’d rather write working code that is maintainable and flexible enough to adjust to change requests. If 20% of what I’ve been writing dies, so be it. In the design world, things change down to the deadline. We also don’t have the kind of time to “flesh out” out our API’s. We can make a great first pass, yes, but when your design can change at a moment’s notice, what’s the point? “Man, this ComboBox is phat! It extends our base TweenComponent, and moves really well in that list. Huh? What do you mean they want the list items to fade in now vs. the list zooming up!? I thought they liked it and signed off on it last week? Son of a LKEJRLKJgfdsjglkdfjg””. That’s not sarcasm; it does happen, a lot. Imagine re-writing an entire list component and all sub-classes… it sucks. Will you now spend the same amount of time hammering out an API… or just make it “good enough”? What if you suddenly have no need for a List in the first place?

    Using the exclude.xml functionality built into Flash, having loaded SWF’s exclude classes that the shell will contain for them can work quite well. The trade off is, you need to remember to compile the “framework.swf” every time you make a change to a shared class. That way, all of your child SWF’s that are loaded into the main one use the same class, and are smaller since they don’t have to keep a copy of it.

    How do you create & mange this framework FLA without tools like ANT? JSFL – JavaScript for Flash. There are four things you need to do.

    First, you need to identify commonly used classes. These are classes, visual components and/or utility classes, that many FLA’s use. You then put these, like so, into a framework.fla on frame 1:

    com.company.project.Class;

    Notice the lack of import. Flash will recognize that as a usage and compile the class into the SWF. Keep in mind you do not need the MovieClip assets that go with visual components. With Flash Player 8 and below, these cannot be shared in a simplified fashion. Thus, you’re best bet is to externalize your bigger assets like images and sounds so they’ll be downloaded to the internet cache, and other SWF’s can load the same images and sounds. For frameworks like the mx one, it’s kind of a big deal, because the base component framework has a lot of built-in graphic assets that now have to be duplicated in many SWF’s. However, most design frameworks are made to be skinned, and thus are usually just lightweight MovieClips; containing a bounding box, a stop, and maybe more lightweight base classes on their assets layer, so this really isn’t that bad.

    The second thing to do is to write a JSFL script that can auto-generate exclude.xml files. These text files that must reside next to your FLA file must also have the name yourfile_exclude.xml where the yourfile is replaced with the name of your FLA file. When you compile your FLA, Flash will look for this file, and if it finds it, it’ll make sure NOT to include any classes listed in the exclude.xml file in the SWF.

    What your JSFL file will do is loop through all library items, and if it finds a class that is used the base framework, it’ll make sure to add that class to the list in the exclude.xml.

    The downside? You won’t be able to test this SWF locally. That is unacceptable. Therefore, the third thing you need to do is to write another JSFL that deletes the exclude.xml file if there, and then performs a test movie.

    Both of the above JSFL files can run in Flash MX 2004 7.2 and Flash 8 which both include the FLfile.dll. This allows JSFL to read and write text fields.

    With Flash Player 9, it’s different. It also depends on if you are using the Flex 2 framework or not. Without repeating Roger’s good entry on it, Flash Player 9 has made a new place to manage the different sections where these classes are. The reason for this is because SWFs are no longer always tied to the display. Now, with the DisplayList, classes that represent display objects can exist independently, and need to be managed someplace with relation to, but not being tied to, the DisplayList. There is also a little more control over how these loaded classes are handled, and where they are stored.

    When loading a SWF, you can determine which AppDom (pronounced like Kingdom – Roger’s slang for them) the Loader will use when loading the SWF. When the SWF is loaded, the classes are held in that context.

    Someone, sometime, is going to have to handle this for ActionScript 3 in an easier way than is done currently with regards to Flash. Not all of us are building Enterprise Applications with SWF. Some of us don’t need the large Flex 2 component framework for our work. We need something lighter weight, like the set that Grant n’ Friends are working on for Flash 9 (Blaze), with less dependencies so it’s easier to modularize classes without the need for interfaces and Remote Shared Libraries.

    Again, I agree with Interfaces with regards to Flex 2 apps, but in the design world, we don’t have that kind of time, nor can we garner that kind of commitment to API’s. Until I get a better IDE, I’ll never agree with RSL’s. To be fair, I haven’t given them a hardcore run through in a sizable Flex 2 project yet.

    Anyway, I haven’t had time to peruse Roger’s Module source yet, but the “on the fly class loader” sounds pretty hot. It’d certainly make that skins on the fly tons easier via DLL-like SWFs, yes? I hope to write more about this subject in the future when I have some scripts to show as well as example file size savings. Additionally, while some bitch about how it’ll be hard to do this kind of stuff with the Flex 2 framework, SOME of it can be done, enough to make a positive impact I’m sure. When I’m done doing Flash consulting, hopefully I can jump back to some Flex 2! Till then, attach this.

  • Porting Flashcom Applications to ActionScript 3

    Regardless if you Flex or Flash, I ran into a porting issue with a Flashcom app I wrote in Flex 1.5 & ActionScript 2. A lot of the server-side code, which is written in case sensitive JavaScript 1, utilizes the Flashcom Component Framework. This framework utilizes a namespace scheme to allow clients to identify server components, and server components to identify client components. This allows them to send messages to each other, and works really well…

    …except in Flash Player 9. For some reason, the namespace mechanism doesn’t work for ActionScript 3 classes. This isn’t a big deal for playing existing content. All of my existing Flashcom apps I wrote in Flash MX 2004 & Flex 1.5 (Flash Player 7) still run just fine in Flash Player 9 in both Firefox & IE.

    It’s when you have a server-side script do a NetConnection.call on an Flash Player 9 created SWF that things don’t work. You CAN call a method that your class has defined as public assuming you point the NetConnection’s client property to your class; protected and private don’t work. However, the namespace mechanism commonly used in ActionScript 2 doesn’t work with the server; it constantly reports method not found. You’d typically decorate the client side NetConnection object reference that you’re component got passed in via it’s loose interface “connect” method. This decoration with the namespaces pointing to your component allowed the server-side to find it. The server-side Flashcom Component Framework already has a built-in namespace mechanism that still works just fine.

    You can emulate this by extending NetConnection, and making the class dynamic. Still, you’ll get the method not found error.

    My only guess at the problem is I think it has to do with the lack of support of “slash syntax”. I’m not sure the new ActionScript Virtual Machine supports it. I know AVM does; it’s how Flash Player 4 SWF’s will work the same as they always have. However, it seems the FCS Component Framework utilizes this behind the scenes somehow. When you do this on the server-side:

    nc.call ( this.callPrefix + "method" );

    You’re basically going:

    nc.call ( "YourComponent/InstanceName/method" );

    …I guess. I gave up after 3 nights of trying to get it to work. I didn’t mind porting client code, but I didn’t want to port server-side code. Anyway, fix for me is to pass in the callPrefix as the first parameter to the method, and have the client side Observer class just parse out “who this message goes to”.

    If you get it to work on your end, drop a note in the comments. I’m using Flex 2 & FCS 1.5 on Windows via Flash Player 9 in Firefox 1.5.