Wrapping Array indexes.

A quick post to note a method for wrapping Array indexes around if they are out of bounds. A good example use case for this would be for data displayed by a list component that cycles round endlessly.

It works for positive and negative inputs and returns the same index for inputs which are within the range of the length.

Strategies for decoupling views and mediators in PureMVC.

Keeping views and mediators nicely decoupled when using pureMVC can sometimes be a bit tricky. Declaring and using a concrete view within its corresponding mediator often seems the easiest way to accomplish things; but lands you with a very tightly coupled pair. Even though the view probably has no knowledge of the mediator it is the view that is most likely to change, meaning the mediator also requires modification.

Object oriented design advises against using concrete implementations for these very reasons. This article goes through a few ideas of ways to put this into practise.

Using the event model for two way communication.

Events are probably the most common way of achieving view to mediator communication. A mediator that knows its view component implements IEventDispatcher can add listeners and handle events dispatched by the component. Custom event classes can be used to pass data around.

This can work the other way round as well. A mediator that knows its view component implements IEventDispatcher can dispatch events on the view component for the component to handle itself. Custom events can be used once again to pass data from the mediator to the view.

The mediator now only needs to type its view component to IEventDispatcher or some high level implementation of (such as DisplayObject or UIComponent). This way views and mediators can fully communicate their intentions and the data that goes with them without any explicit knowledge of their concrete implementations.

Downsides to this: the code becomes a little harder to follow and you may need to add custom event classes (and the accompanying boilerplate) to pass the necessary data around.

Another similar approach would be to use a different messaging system instead. The Actionscript event model is perhaps a bit over complicated for a straightforward two way communication like the one described above.

Something along the lines of AS3 Signals could be used to create a lighter weight means of mediator-view communication in the same mould.

Using multiple interfaces.

Instead of a mediator having one view component reference - capable of handling all of the responsibilities inherent in their relationship - it could have several. Even if these references all point to the same object this is a way of dividing up the responsibilities the mediator has to the view into simpler, less strongly tied parts.

A mediator could be supplied an IEventDispatcher for event handling, a DisplayObject for positioning and several other interfaces/abstract classes to handle other aspects of the view.

This allows the view to be changed around without touching the mediator. Certain aspects could also be made to be optional in the mediator. For example supply an optional text component reference. If it is set then set its text, otherwise leave it. It also makes extending the mediator easier. To add on another responsibility is as easy as extending the mediator and adding another reference to another interface or class.

On the downside this also adds complexity and more interfaces. It also begs the question "how far do you break things down?". Do you need an IEventDispatcher for events when you've got a DisplayObjectContainer for adding and removing children? Ultimately it will depend whether the first is ever going to be needed without the second. Probably not in this case but the more complex the example the more likely it would be worth doing.

Another issue with this approach is when there is lack of common interfaces defined. A Flex Button has a label property, and a Label has a text property. Both accomplish the same thing, but as there's no common interface for setting their text this method is of no use.

Let the view decide.

Instead of making updating the responsibility of the mediator, make it the responsibility of the view. Then view components only have to implement an updating interface to achieve mediator to view communication.

When a notification is received by the mediator it's body is just passed straight into a call to the view's update method. The view can then check its content (for example check its type) before actioning the necessary update.

The biggest downside to this approach is the loss of compile time type checking. While using value objects can give good runtime checking, it adds processing overhead and invites errors that may not be found for some time.

Finally...

I will add some examples and any more thoughts I have on this subject soon.

UPDATE: A brief Flex example. http://db.tt/PRXGzvaX

FDB; command line Actionscript debugger.

FDB is the command line debugger that comes bundled in with the Flex SDK. While it's arguably not as quick or easy to use as the debugger supplied with Flash Builder it is free and useful to quickly step through a project that you don't have set up in Flash Builder. It's also very straight forward to use as a remote debugger.

Below I will run through some simple usage with FDB.

The program itself lives in the bin folder of the Flex SDK. Running it provides you with a command prompt from which you can launch an application and begin debugging.

Launching

To launch an application you type run or r followed by a space and the address to the swf or mxml application you wish to launch. If you don't specify anything, then FDB will wait for a debug player to connect. This is the method I usually use and is also the only method available to Mac users.

If you just used run with no address to launch you now have a small amount of time to load up the application to be debugged. All going well you should see a message like the one pictured below.

Just a couple of notes: don't launch an swf through the Flash IDE as this will steal the debug connection, and also make sure the swf is debug enabled.

Setting up

Depending on how you ran FDB up there is a chance you will now need to add source directories. This is achieved by typing directory or dir followed by a ';' delimited list (':' on a Mac) of source paths. You can list current source paths by typing info sources or i so.

Now you can add break points. This is done by typing something like the following: break Main.as:20. This will add a break point at line 20 of the file Main.as. You can also specify method names instead of line numbers, e.g. break Main.as:getSomething. You can review break points by typing info break or i b and delete them by type delete n or d n where n is the number given to the break point when it was created.

Once you have finished setting break points continue the swfs execution by typing continue or c.

 

Stepping through code

Once a break point is encountered execution halts and you will be presented with a screen like this.

From here you can use a number of commands to analyse the situation. You can type step or s to step over a line of code, next or n to step into a line of code or finish (f) to step return to the calling method. You can print variables by typing print varname as well as list all of an object properties with print object. (notice the full stop after the property name).

 

Other useful commands while execution is halted are bt or where to print a backtrace of all stack frames. Print out lines of source code using list either alone or with a line number, method name or file name/line number combination. For more information on these command type help either alone or followed by any other command for general or specific information.

Once you are finished looking at this particular break point type continue to resume execution.

Finishing

To finish either close the Flash Player, or when execution is halted type kill or k followed by y when prompted. From here you can begin another session by typing run, and if it is the same swf then all your previous source paths and break points will still exist.

This covers basic operation. Hopefully I will have time to cover some of FDB's more advanced features in another post.

Deploying Flash / Flex to server using Ant.

This post contains a few simple steps to setting up an Ant target that will deploy a Flash or Flex project ( or anything really ) to a server.

This is a useful addition to an Ant build, saving time copying files manually and preventing potential errors occurring when trying to remember which files to copy.

To begin with it is assumed that you are using Flash/Flex Builder/Eclipse and that Ant is set up for it. If you don't have Ant set up then there are plenty of good tutorials showing how to, such as this one.

The main Ant task used is the SCP task, documentation for which can be found here. This isn't included in the Ant distribution and requires the jsch library. I had problems using the latest version in Flex Builder 3 with Ant 1.7, but found version 0.1.29 to work fine. This version is available here.

To set up the jar file in Eclipse go to the Window menu and select Preferences.... Open Ant in the tree menu on the left and select Runtime. Then under the Classpath tab to the right select Global Entries and click on the Add External JARs... button. Browse to and select the jsch jar file. You should now be set to use the various jsch tasks including the SCP task.

A basic target to copy a bin folder to a folder on a server would look something like this:


<target name="deploy" >
    <scp 
        trust="true"
        password="${password}" 
        todir="${server.user}@${server.address}:${server.loc}">
        <fileset dir="${bindir}" /> 
    </scp> 
</target>

Obviously all the variables are held in a .properties file declared earlier in the build file making the target more reusable, but you could equally hard code the values in.

If you don't want to have a password in a .properties file then you can add a dialog to the task for password entry. Ant offers the input task, but doesn't provide any way of *ing out the text entry. There are several third party tasks that offer this functionality. One good one is the query task from the JeraAntTasks library.

To use this download the jar file from the above link and add it to Ant's Global Entries in Eclipse the same way the jsch jar was added above. Then go to the Types tab and click on the Add Type... button. In the window that opens enter a name ( this is the name that you will use in your build file ), select the JeraAntTasks.jar from the location dropdown. Navigate to the anttasks package in the bottom left tree menu and select Query.class in the bottom right hand menu. Press OK.

You can now add a password dialog box to the target so it looks something like this:


<target name="deploy" > 
    <query name="password" password="true" />
    <scp
        trust="true" 
        password="${password}" 
        todir="${server.user}@${server.address}:${server.loc}"> 
        <fileset dir="${bindir}" /> 
    </scp> 
</target> 

In place of having a password variable in a .properties file, it is now declared by the query task. Remember to replace query with whatever you called it in the previous step.

This is a relatively simple target, but could be expanded to do pretty much whatever you like when combined with other build targets and other tasks, such as the SSHEXEC task for example.

Swiz BeanProvider in Actionscript another way.

In my previous post about using Swiz in Actionscript projects I demonstrated one way of implementing a BeanProvider class. This method essentially mimics what Flex does when it compiles an mxml bean provider into actionscript.

This is a somewhat laborious way of doing things, and on bigger projects ends up large and difficult to read. Below is an example of another way to make an actionscript BeanProvider:

 
package 
{ 
    import org.swizframework.core.Bean;
    import org.swizframework.core.BeanProvider; 
    import org.swizframework.core.Prototype; 
 
    public class Beans extends BeanProvider 
    { 
 
        public function Beans(beans:Array=null)
        { 
            beans = createBeans( beans ); 
            super(beans);
        }


        protected function createBeans( beans:Array ):Array 
        { 
            if( !beans ) 
                beans = []; 

            beans.push( new Bean( 
                new SomeController(), "someController"  ) ); 
            beans.push(
                new Bean( new SomeModel(), "someModel" ) ); 



            var prototype:Prototype = new Prototype( SomePresModel ); 
            prototype.singleton = true; 
            prototype.constructorArguments = ["abc", 123, true ]; 
            beans.push( new Bean( prototype ) );	

            return beans;
        }
    } 
}
 

In this example Bean instances are created and passed instances of our controllers/model or prototypes. An Array of these beans is then passed onto the superclass' constructor. It's as simple as that.

I have chosen to move the population of the beans array in to a separate protected method to allow greater control to sub classes, but it's by no means a necessary step.

Loading AS2 swfs as AS3 swf using ForcibleLoader.

This is a quick post to recommend using Spark projects ForcibleLoader (available here) class if you're ever in the situation of needing to load an old AS2 swf (that you probably have no source to) as an AS3 swf within an AS3 project.

You will then end up with a MovieClip rather than an AVM1Movie, and are able to manipulate it as you would a basic MovieClip class.

Unfortunately this won't let you load up scripted AS2 swfs and interact with them as though they were AS3, but in certain circumstances it can be a massive time saver (as I found recently).

Below is a simple use example. It doesn't really need any explanation, as it's all fairly straight forward.

 
package 
 { 
 import flash.display.Loader; 
 import flash.display.Sprite; 
 import flash.events.Event; 
 import flash.events.IOErrorEvent; 
 import flash.events.SecurityErrorEvent; 
 import flash.net.URLRequest; 
 import org.libspark.utils.ForcibleLoader; 
 
public class Main extends Sprite 
 { 
    public var loader:Loader; 
    public var forceLoader:ForcibleLoader; 
 
    public function Main() 
    { 
        loader = new Loader(); 
        forceLoader = new ForcibleLoader( loader ); 
 
        loader.contentLoaderInfo.addEventListener( 
            Event.COMPLETE, loadCompleteHandler ); 
        loader.contentLoaderInfo.addEventListener(     
            IOErrorEvent.IO_ERROR, ioErrorHandler );
        loader.contentLoaderInfo.addEventListener( 
            SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler );
        forceLoader.load( new URLRequest( "anOldAs2Movie.swf" ) );
    } 
 
    private function loadCompleteHandler(e:Event):void 
    { 
        //TODO handle load 
    } 
 
    private function securityErrorHandler(e:SecurityErrorEvent):void 
    { 
        //TODO handle some security errors 
    }


    private function ioErrorHandler(e:IOErrorEvent):void 
    { 
        //TODO handle some IO errors 
    } 
 } 
} 

Swiz in Actionscript Projects (including Flash IDE projects)

I've been spending a bit of time with Swiz 1.0 and thought I would see how easy it was to get it working with actionscript projects. Most of the documentation focuses on how to configure Swiz in Flex 3 and 4, but not how to do so in pure actionscript.

Turns out its actually pretty easy: either in Flex Builder or the Flash IDE. The only caveat to it being truely pure actionscript is that you need to use Flex's framework.swc in order to let Swiz use data binding, and rpc.swc to use some of Swiz's service classes.

The first step is to setup the project. For this you'll need to download a copy of Swiz and a copy of the Flex SDK. Then setup a new project and add the Swiz swc (e.g. swiz-framework-1.0.0-RC1), and Flex's framework.swc (found in flex_sdk_dir/frameworks/libs/) to the project's library path.

By using the Swiz swc there is no need to add the -keep-as3-metadata compiler argument. If you're using the Flash IDE, then you'll need to turn on the 'Export SWC' option in the Publish Settings' flash menu. This is a little workaround that stops Flash stripping the metadata out of your code. ( Thanks to Patrick Mowrer for that ).

Next step is to configure Swiz. This is usually done in MXML in a Flex project, but can just as easily be done in actionscript.

To begin with we create a new SwizConfig instance, and set its eventPackages and viewPackages properties to match our package structure. There are a lot of other properties we could set here, but there's no need for a normal project.

Next we create a Swiz instance, passing it:

  • An EventDispatcher. One high up on the display list to catch views being added, and bubbling events they dispatch.
  • Our config instance.
  • An array of BeanProviders (or BeanLoaders), either as instances or class references. More on this below.
  • We then call init on our Swiz instance, and that's it, we're off.

    Stepping back a second though, we needed a BeanProvider to pass to Swiz in the previous step. An actionscript BeanProvider looks something like this:

    Essentially just defining a getter/setter for each bean is all that's needed. There are other ways to do this, but I won't go into details here.

    That's all there is to it. You're now set to start using Swiz in your project. I've included a very basic skeleton project that has both a Flex Builder and Flash IDE version. To use them you'll need to change the library path locations for framework.swc so they point to wherever you have your flex sdk installed. The project doesn't do very much, just trace out statements showing that Swiz is working the way it should.

    Actionscript Swiz example.

    Flex Effects with Pixel Bender filters, part 2.

    This is the second part of a series on using Pixel Bender to create effects in Flex. In this part I'll go through making a simple filter in Pixel Bender that can be used to animate an effect in a similar way to the last post.

    You can get hold of a copy of the Pixel Bender toolkit here and also get hold of a lot of good reading material to get started using it.

    The filter I've made basically alters the alpha value of pixels based on their y position in the image. Using a sine function this is done in horizontal stripes to create a shutter show/hide effect. Here the code for the filter:

    <languageVersion : 1.0;>
    kernel ShutterFade
    <   namespace : "com.as3offcuts.filters";
        vendor : "as3offcuts";
        version : 1;
        description : "shutter fade";
    >
    
    
    {
        //input pixel
        input image4 src;
        //output pixel
        output pixel4 dst;
    
    
        //parameter that takes the image through the effect from fully visible (0) to invisible (1)
        parameter float transition
        <
            minValue:       0.0;
            maxValue:       1.0;
            defaultValue:   0.0;
        >;
    
    
        //parameter that governs the height of the 'shutters'. The higher the number, the bigger the shutter.
        parameter float shutterHeight
        <
            minValue:       1.0;
            maxValue:       10.0;
            defaultValue:   1.0;
        >;
    
    
        void 
        evaluatePixel() 
        {
            //sample the current pixel
            pixel4 pix = sampleNearest( src, outCoord() );
            //get a base value from a sin function of the pixel's y position divided by the shutterHeight parameter
            float sinHeight = sin( outCoord().y / shutterHeight );
            //assign the base value adjusted by the transition value to the current pixel's alpha
            pix.a = sinHeight - ((transition * 3.) -2.);
            //assign the transformed pixel to the output
            dst = pix;
        }
    }

     

    Shutterfade source

    This filter calculates a value based on the sine of the pixel's y position divided by the shutterHeight parameter. This value is then either exaggerated or reduced based on the transition parameter before being assigned to the output pixel's alpha value. This gives a graduated opaque-transparent effect in horizontal stripes going down the image.

    Using this in a custom Flex effect is just a case of exporting the filter as a .pbj file and plugging it into an effect class in the same way as in the last post, and manipulating the transition parameter to create the animation.

     

    Using the Flex Singleton register Pt 2/3 (Overriding Flex implementations)

    This is the second in a 3 parter about the flex singleton register. This post will look at how to register your own classes with the Singleton register so you can actually use your custom implementations instead of the Flex default implementations.

    The first post on the Singleton register can be found here


    Registering custom implementations - the problem The last post showed that you simply use:

    
    Singleton.registerClass("mx.managers::IPopUpManager", mx.managers.PopUpManagerImpl);  

    So, in theory you just add in your own class. The problem is the Singleton.registerClass method works on a first come first serve basis - once a class is registered against an interface, no subsequent classes can be registered.

    All the Flex default implementations are registered as the framework is initialized (in SystemManager.mx_internal::docFrameHandle). So, there is no chance for you to register your own implementation.


    Registering custom implementations - the solution Create a custom preloader for the main Flex application. If you define your own preloader, you can register classes BEFORE the SystemManager registers the Flex classes.

     
    <mx:Application  	xmlns:mx="http://www.adobe.com/2006/mxml" 	preloader="com.myDomain.preloaders.ApplicationPreloader" 	> 

    And then in your preloader...

    package com.myDomain.preloaders 
     { 
        import mx.core.Singleton; 
        import mx.preloaders.DownloadProgressBar; 
     
        public class ApplicationPreloader extends DownloadProgressBar
        { 
            private static var classConstructed:Boolean = staticInitializer();
    
            private static function staticInitializer():Boolean 		{         
                Singleton.registerClass("mx.managers::IPopUpManager",    
                com.myDomain.managers.MyCustomPopUpManagerImpl);  			 			return true; 
            } 
        } 
     }

    And now we have registered our implementations before Flex does!

    To tidy things up you could have a static class that does all the reigstration, and in this preloader simply call com.myDomain.manager.SingletonImplManager.register();.

    The next post will look at using all this with a transparent modal background for Air applications.

    Using the Flex Singleton register Pt 1/3

    This is the first in a 3 part post about using the Flex Singleton register. This post will deal with what the Flex Singleton register is as well as how and why its used. The second will look at how to register your own classes with the Singleton register (not as easy as it sounds) and the third will be a real life example.

    The final post will show you how to give the Alert control the ability to create a modal overlay that supports a custom chrome in Adobe Air. The big pain with a custom chrome (say a splat shape) is that the modal overlay covers the entire bounds of the window - including any transparent areas. So for irregular shapes/chrome - like a splat as a background, you get a big square slapped over the top - not ideal. What you want is ONLY the splat to be overlaid with the modal background.

    By using the Singleton register and a custom implementation of the PopupManager we can add this functionality without having to create a custom Alert class. You don't have to change any of your existing app code where Alerts are used, all existing calls to Alert will now have our new and improved modal background!


    The Singleton register

    Flex has many singletons that are used as the default functionality for its components - the popup manager being one of them. At start up, the default implementations that flex uses are registered with the static class Singleton. When a class such as the PopupManager is first used, it will retrieve the class that defines its core functionality from the Singleton class.

    The classes are registered against an interface, and it is by the interface that they are retrieved. Thus any class implementing the correct interface could be registered and used instead of the default class.

    The ability to define custom implementations is a great feature of the flex framework, but is largely undocumented and support for actually overriding the default implementations is greatly lacking. However, it can be done!


    Retrieving a class from the register

    The PopupManager class is simply a Static class, that upon first use, will retrieve a singleton object that defines its core functionality.

    Below is how the PopupManager retrieves the singleton that it will use for its core functionality. This is a static method in the PopupManager.

     
    private static function get impl():IPopUpManager 
    { 
        if (!_impl) 
        { 
            _impl = IPopUpManager( 		Singleton.getInstance("mx.managers::IPopUpManager"); 
        } 
    
        return _impl; 
    } 

    The key line is :

     
    Singleton.getInstance("mx.managers::IPopUpManager") 
    

    This will perform a look up on the static class Singleton for a class that has been registered against the interface mx.managers::IPopUpManager.

    If one is found, its static getInstance method is called and the instantiated singleton is returned. This instance is then used as the implementation of the PopupManagers core functionality. So, if you could register your own class against mx.managers::IPopUpManager, you could completely change how the PopupManager works!
    Registering a class with the Singleton register

    When the flex framework initializes, it registers each of these implementations with the static class Singleton. This simply adds the class to a class map, indexed by the interface name that it implements.

    The class that is registered must adhere to the following 2 points.

    1. It must implement the interface it is registered against.
    2. It must implement a static method getInstance that returns the singleton instance of itself.


    In the case of the PopupManager, the singleton class that is registered is mx.managers.PopUpManagerImpl. Its is registered against, and implements the interface mx.managers.IPopUpManager and it contains a static method getInstance as below...

     
     public static function getInstance():IPopUpManager 
     { 
        if (!instance)             instance = new PopUpManagerImpl(); 
        return instance; 
     } 
     

    The registration is on a first come first serve basis, so the first class to be registered against a particular interface is stored in the Singleton registry. Any subsequent registrations for the same interface are ignored.

    The PopupManger will be registered like this...

     
    Singleton.registerClass("mx.managers::IPopUpManager", mx.managers.PopUpManagerImpl); 


    Custom registration..... The drawback is, that all the classes are registered by the time the Flex framework has initialized, and as the register is on a first come first serve basis any subsequent registrations would be ignored.

    The next post will show you how to register your own implementations before the Flex classes are registered.