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.

AIR 2 Native Process Example - Mouse Screen Position

I had been wanting to have a play around with the native process classes that were added in AIR 2 for quite some time, but only recently managed to get around to doing so. Something that had always bugged me with AIR (and the Flash platform in general) was the lack of any way of getting the screen mouse position when the application wasn't being interacted with. So as a way of experimenting with the native process feature I wrote a little AIR application that interacts with a c++ process and outputs the mouse position at all times.

Starting and interacting with a native process from AIR is actually pretty straightforward. It is essentially a case of setting up a NativeProcessStartupInfo object, a NativeProcess object and adding event listeners to the NativeProcess. Here is this section in the example application:

This is in fact all the Actionscript code in the example. Application complete calls onAppComplete which checks if native process is supported. If so a NativeProcessStartupInfo is created and a reference to the process file set on it's executable property. This is then passed to a NativeProcess object, which is started and has several listeners added to it.

Of the listeners added the most important to this example is ProgressEvent.STANDARD_OUTPUT_DATA. This listens for updates to the process' standard output, and updates the output variable in the application.

The second part to this example is the c++ application. Before I go into this I'd like to note that I'm no c++ developer, so there are probably faster/cleaner/better ways to go about what I have done. Below is the code for the small application used:

This program takes the current mouse position, converts it to a string of the form 'x : y' and outputs it on the standard output. This is done on an infinite loop every 100 milliseconds. This output is picked up by the AIR application and displayed as described earlier.

This program is built and bundled with the AIR application, which is then built as a native installer for Windows. This is one of the limitations of using native processes. You have to build the application as a native application, which means having to do it for each individual platform you intend it to be deployed on. In this examples case, it will only work on Windows, because the underlying process will only work on Windows. Although it could be built to work on other platforms, doing so would add effort and potential problems.

The c++ element of this example was build using Microsoft Visual c++ 2010 Express as a Win32 console application.

Project Files

Swiz, Degrafa and YouTube Demo Application.

Here's a little demonstration application I recently put together using a combination of Flex, Swiz, Degrafa and the YouTube API.

You can see the application and view/download the source here: http://www.davespanton.com/demo/TubeDemo.html

It uses a presentation model pattern to decouple the views from the rest off the application and Swiz to manage dependency injection and event handling.

The rest of the application speaks for itself, so feel free to dig in and have a look.

UPDATE : Due to changes in the youtube API the demo no longer works as it once did.  

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.

Flex Effects with Pixel Bender filters, part 1.

This is the first of a two part series on using Pixel Bender filters in Flex effects. I've recently started to spend a bit of time with Pixel Bender and have found it to be a good tool for creating interesting effects and transitions in Flex. Even if you don't write any yourself, there are plenty available to use at the Pixel Bender Exchange

In this first part I'll cover an example of making an Effect and EffectInstance that extend the Flex framework and also use a Pixel Bender filter to achieve the effect. In the second part I'll cover writing a Pixel Bender filter to use with a custom effect.

I won't go over embedding and instantiating a filter as a Shader; this is well documented here. There is also a good example of animating a Pixel Bender filter here.

The Pixel Bender filter I'm going to use for this example is a dissolve effect from the BlackBookSafe sample project on Adobe Developer Connection. This filter creates a patterned dissolve effect that can be manipulated via one parameter, 'transition', which goes from 1, invisible, to 0, completely normal. Values in between giving the dissolve effect.

To turn this into an effect I have made two new classes that extend TweenEffect and TweenEffectInstance. Doing this means I take advantage of all the Flex effects functionality, and get to use the effect as a simple MXML component. The first new class, DissolveEffect, is very simple. It has two properties which it will pass onto effect instances and overrides two methods: getAffectedProperties() and initInstance(). Scroll to the bottom to see this class in its entirety.

The second class is DissolveInstance (not to be confused with mx.effects.effectClasses.DissolveInstance). This class has the Pixel Bender filter (the pbj file) embedded into it, as well as a Shader and ShaderFilter. Beyond this it is much like the FadeInstance class in that it does a small amount of validation on its properties and then uses its superclass' tween to create the desired effect. In this case the tween's value updates the transition value on the Pixel Bender filter (or more precisely the transition.value[0]), and updates the target's filters on each tween update.

 
public class DissolveEffect extends TweenEffect 
{ 
    private static var AFFECTED_PROPERTIES:Array = [ "filters" ];
 
    [Inspectable(category="General", defaultValue="undefined")] 
    public var transitionFrom:Number; 
 
    [Inspectable(category="General", defaultValue="undefined")] 
    public var transitionTo:Number; 
 
    public function DissolveEffect(target:Object=null) 
    { 
        super(target); 		 	instanceClass = DissolveInstance; 
    } 


    override public function getAffectedProperties():Array 
    { 
        return AFFECTED_PROPERTIES; 
    } 


    override protected function initInstance(instance:IEffectInstance):void 
    { 
        super.initInstance(instance); 
        var dissolveInstance:DissolveInstance = DissolveInstance(instance);
        dissolveInstance.transitionFrom = transitionFrom; 
        dissolveInstance.transitionTo = transitionTo; 
    } 
} 

 
public class DissolveInstance extends TweenEffectInstance 	
{ 
 
    [Embed(source="assets/disolve.pbj", mimeType="application/octet-stream")] 
    private var dissolveKernel:Class; 
 
    private var dissolveShader:Shader; 
    private var shaderFilter:ShaderFilter; 
 
    public var transitionFrom:Number; 
    public var transitionTo:Number; 
 
    public function DissolveInstance(target:Object) 
    { 
        super(target); 
        dissolveShader = new Shader( new dissolveKernel() ); 
        shaderFilter = new ShaderFilter( dissolveShader ); 
    } 
 
    override public function initEffect(event:Event):void 
    { 
        super.initEffect(event); 
 
        switch (event.type) 
        {	
            case "childrenCreationComplete": 
            case FlexEvent.CREATION_COMPLETE: 
            case FlexEvent.SHOW: 
            case Event.ADDED: 
            { 
                if (isNaN(transitionFrom)) 
                    transitionFrom = 1; 
                
                if (isNaN(transitionTo)) 
                    transitionTo = 0; 


                break;
            } 
            case FlexEvent.HIDE: 
            case Event.REMOVED: 
            { 
                if (isNaN(transitionFrom))
                    transitionFrom = 0; 
 
                if (isNaN(transitionTo)) 
                    transitionTo = 1; 
                break; 
            } 
        } 
    } 
 
    override public function play():void 
    { 
        super.play(); 
 
        var values:PropertyChanges = propertyChanges; 
 
        if (isNaN(transitionFrom) && isNaN(transitionTo)) 
        {	
            if (values && values.end["transition"] !== undefined) 
            { 
                transitionFrom = 1; 
                transitionTo = values.end["transition"]; 
            } 
            else 
            { 
                transitionFrom = 1; 
                transitionTo = 0; 
            } 
        } 
        else if (isNaN(transitionFrom)) 
        { 
            transitionFrom = (transitionTo == 0) ? 1 : 0; 
        } 
        else if (isNaN(transitionTo)) 
        { 
            if (values && values.end["transition"] !== undefined) 
            { 
                transitionTo = values.end["transition"]; 
            } 
            else
            { 
                transitionTo = (transitionFrom == 0) ? 1 : 0;
            } 
        }	
 
        tween = createTween(this, transitionFrom, transitionTo, duration);
        dissolveShader.data.transition.value[0] = transitionFrom;
 
        if(target.filters) 
        { 
            setTargetFilters( false, true ); 
        } 
        else 
            target.filters = [ shaderFilter ]; 
    }


    override public function onTweenUpdate(value:Object):void 
    { 
        dissolveShader.data.transition.value[0] = value; 
        setTargetFilters( true, true ); 
    } 
 
    override public function onTweenEnd(value:Object):void 
    { 
        super.onTweenEnd(value);	
        setTargetFilters( true, false ); 
    }


    private function setTargetFilters( splice:Boolean, push:Boolean ):void 
    { 
        var arr:Array = target.filters; 
        if( splice ) 
            arr.splice( target.filters.indexOf( shaderFilter ), 1 ); 
 
        if( push ) 
            arr.push( shaderFilter ); 	target.filters = arr; 
    } 
} 

Resize Flex Image correctly and add Bitmap smoothing

If you have ever used the Flex Image component, set its minWidth / minHeight or percentWidth / percentHeight you may have noticed some strange layout issues, and that the scaled quality is not that good. You can use 3rd party Image components to get round these issues, or this very simple load handler on the image. When using these properties, the Image component itself is NOT changed, rather the content within it. So it may appear to have scaled down, but the outer bounds of the Image component (not the bitmap within it) remain the original size.

Also, when scaling the Image component, bitmap smoothing is not enabled, and as it is private you cant do anything about it - so your scaled down image is a bit jagged. There are 3rd party Image components to get round these issues, or this very simple load handler on the image...

 
private function imageLoaded(event:Event):void 
{ 
    var img:Image = event.target as Image; 

    // re set the image source to a new Bitamp that is created from the current image 
    // bitmap data, but this time with smoothing enabled 	
    img.source = new Bitmap( Bitmap(img.content).bitmapData, "auto", true ); 

    // Set the scaling of the image to 20px 	
    img.scaleX = img.scaleY = (20 / img.contentHeight); 
} 

Dynamically resizing AIR windows with user resize (gripper).

I am a big fan of Daniel Wabyick's dynamically resizing window example. ( http://www.wabysabi.com/blog/2008/01/29/example-air-app-dynamically-resizing-windows-based-on-content-area/ ). A simple and elegant solution to accommodate dynamically expanding and contracting windows in an AIR application.

I've since extended this example to fill two extra requirements. The first of these was to add a gripper that allows users to resize the window; the focus of this article. The second was to allow the window to dynamically resize, but to keep it's content the same, which I will cover in the future.

For the addition of a gripper to handle user window resizing, I've essentially added three extra elements to the original example. The main one is an Image component positioned in the bottom right that acts as the resize control. The other two elements are a mouseUp and mouseDown handler on this Image which handler the resize.

The mouseDown removes the resize effect from the main content area, locks the main content area to the window and starts the native window resize. The mouseUp then resets the resize effect and main content position.

Here are the two event handler added to the gripper component:

[sourcecode language="ActionScript3"] private function gripperDownHandler():void { //adds an extra bit of safety incase the mouseUp occures outside the gripper stage.addEventListener( MouseEvent.MOUSE_UP, gripperUpHandler ); chrome.setStyle("top", 10); chrome.setStyle("bottom", 10); chrome.setStyle("left", 10); chrome.setStyle("right", 10); chrome.setStyle("resizeEffect", null); nativeWindow.startResize(); } private function gripperUpHandler(event:MouseEvent=null):void { chrome.x = chrome.y = 10; chrome.setStyle("resizeEffect", resize); //clean up the event added in gripperUpHandler stage.removeEventListener( MouseEvent.MOUSE_UP, gripperUpHandler ); } [/sourcecode]

I've attached an example project which differs a little from the original example on Daniel Wabyick's blog, but should illustrate the principle at work.

My apologies in advance for it's ugliness.

AirResizeGripperExample