tag:davespanton.posthaven.com,2013:/posts Dave Spanton's Code Cuts 2015-08-23T11:54:40Z tag:davespanton.posthaven.com,2013:Post/497256 2012-10-07T10:53:00Z 2013-10-08T17:07:53Z Gilded Rose Clojure

I recently read Mike Jansen's 8th Light blog post on The Gilded Rose kata in Clojure and thought I'd give it a crack myself.

First was to get a set of tests setup. The kata is already setup to use the speclj testing library. I'd only used the very fine Midje library for testing in Clojure before, but I thought I'd stick with what was already in the project.

Both allow for very easy and straightforward testing, and both support automatic test running when files change. This makes for a really tight feedback loop when making any changes.

I tried as much as possible to just translate the requirements into a suite of tests without getting bogged down in implementation details. Here it is after the refactoring.

Not very much changed between initially writing the tests and refactoring the main code, just a few bits here and there to match changes made in the core file.

Refactoring the main code basically comprised of splitting each of the different behaviours spread around update-quality into their own functions which could be associated with different items in a declarative fashion. The update-quality function then just became a matter of mapping these functions over the items.

The restriction on being unable to change the item function made this approach a little more convoluted, but best not to enrage the goblin.

Here's the refactored core file.

There's bits I'd like to tweak, but I also wanted to time box it within a reasonable range. One thing I would like to do would be to try core.match on some of the functions; particularly the one relating to concert ticket quality.

]]>
tag:davespanton.posthaven.com,2013:Post/497257 2012-05-03T20:51:00Z 2015-08-23T11:54:40Z Roboguice Assisted Injection on Android

Google-guice's assisted injection extension is useful when you need to inject a contructor or method, but need to manually provide some of the parameters.

Now that Roboguice is at version 2 I thought it time to try out the assisted injection extension on Android.

The assisted inject jar comes with the guice-3.0 zip file available from http://code.google.com/p/google-guice/downloads/.

As I'm using Maven it's a case of adding the following to the dependencies in my pom:

You need the exclusions section to prevent the with aop version of guice being added (you should already have the no-aop version of guice 3.0 added). Otherwise there'll be all manner of errors.

Using it is fairly well documented on the Google-guice wiki: http://code.google.com/p/google-guice/wiki/AssistedInject

It basically comes down to 3 steps. 

  1. Create a factory interface that defines a create method, accepting the manual parameters as arguments.
  2. Use the install method in your custom module to setup the factory for injection.
  3. Annotate the constructor/method in need of assisted injection.

To use it inject an instance of the factory interface and call create on it.

The following markdown brings together an example of the four previously mentioned elements from a project (https://github.com/davespanton/Nutbar)

]]>
tag:davespanton.posthaven.com,2013:Post/497259 2012-03-16T21:24:33Z 2013-10-08T17:07:53Z Upgrading to Roboguice 2.0 beta 3.

Last Tuesday night I was feeling brave and decided it was time to upgrade a my current pet Android project to Roboguice 2.0b3. 

To get it all working I needed to...

Upgrade Dependancies

As the project uses Maven I firstly upgraded the Roboguice dependancy in my pom. This also entails upgrading the Google Guice dependancy as well. They now look like this:

 
<dependency>     
    <groupId>org.roboguice</groupId>     
    <artifactId>roboguice</artifactId>     
    <version>2.0b3</version>     
</dependency> <dependency>         

<groupId>com.google.inject</groupId>     
    <artifactId>guice</artifactId>    
     <version>3.0</version>    
     <classifier>no_aop</classifier>
 </dependency> 

This created quite a few errors.

Remove custom application, update modules.

Next step was to remove the custom application class, test and references from the project. The new version of Roboguice doesn't need an application extending RoboApplication.

Once this was gone l needed to let Roboguice know where my custom module is. The simplest way to do this is create a new resource file in res/values called roboguice.xml. Here's my new one https://github.com/davespanton/Nutbar/blob/master/res/values/roboguice.xml

Any custom modules need to be changed to inherit from AbstractModule instead of AbsractAndroidModule. I had to change this for my main custom module and my test module. 

I also had to refactor the main module to no longer take any constructor parameters. It previously took a reference to my application, but this was easily refactored.

Injected Test Runner.

I use Robolectric for unit testing and have an InjectedTestRunner which extends their RobolectricTestRunner. The prepareTest method was updated to:

Preferences Activity.

The only problems I had once the above was done was with my preferences activity injecting a shared preference instance. 

For the time being I simply reverted to manually retrieving the shared preferences rather than injecting them. 

I really need to upgrade the preferences to fragments at some point anyway, which will be a good time to look into getting the injection working once again.

 

Overall a fairly painless upgrade.

Have a browse on https://github.com/davespanton/Nutbar to see it in more detail.

 

 

]]>
tag:davespanton.posthaven.com,2013:Post/497260 2011-12-16T20:53:00Z 2014-06-11T22:23:49Z Spying on Titanium; Titanium Appcelerator and Jasmine.

I've now worked small parts in a couple of Appcelerator projects for iOS. Both times I have been tasked with improving the unit testing.

Jasmine from Pivotal is a great Javascript unit testing framework, (https://github.com/pivotal/jasmine/wiki), and has been modified to work with with the Titanium framework (https://github.com/guilhermechapiewski/titanium-jasmine).

It mostly works excellently with all of Jasmine's features are available. The only issue I had was not being able spy on objects and methods that are a part of the Titanium API.

One way to get around this is to replace the part of the API you intend to use with a stubbed version. Say for example that you wish to spy on Titanium.Network.createHTTPClient. Before exercising any production code that uses it do something like:

It is then possible to call spyOn(Titanium.Network, "createHTTPClient") and subsequently expect this to have been called. Once done Titanium.Network can be set back to originalTiNet if required.

The same can be done for objects returned by Titanium's create methods. Either get your stubbed API (Titanium.Network in this case) to return a stubbed object, or use a spy to do it as in the below example. 

In this case we want to be able to verify that send and open were called on an HttpClient object. By setting up the above (in addition to the first gist) every subsequent call to Titanium.Network.createHTTPClient in our production code will be given stubClient, and we can verify calls made to send and open.

If anyone is interested I can post up a more complete example.

]]>
tag:davespanton.posthaven.com,2013:Post/497262 2011-11-28T21:16:00Z 2013-10-08T17:07:53Z Install a JAR into your local repository.

Had to do this for an android port of smack. Thought I'd write it down for the next time.

 

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>
]]>
tag:davespanton.posthaven.com,2013:Post/497263 2011-11-10T22:29:00Z 2013-10-08T17:07:53Z Switching my Android environment from Eclipse to Intellij IDEA

I've been using Eclipe for Android development pretty much since Android's release. I'm generally pretty happy using Eclipse; finding it always works well for small Android projects. 

More recently I've been using Maven with Android to better co-ordinate working with different libraries. Setting up Maven to work with Android in Eclipse was a bit of a pain, but not too difficult. 

Earlier this week I upgraded my Android SDK to r15; which promptly broke my project in Eclipse with a cryptic "Conversion to Dalvik format failed with error 1". Google reveals a number of people experiencing similar issues, but none of the suggested solutions seemed to work.

Another tack was to move from my old Galileo installation to a shiny new Indigo one and see if that helped. Got it all set up okay, and the old error went away; to be replaced with an out of memory error whenever I tried to launch.

Strangely enough everything still worked fine using Maven from the command line.

At this point I decided maybe Eclipse and it's various plugins were the weak link. Intellij IDEA seemed like it would be worth trying and the setup process was suprisingly straightforward. 

Beyond downloading and unzipping the community edition I had to setup the Sun JDK and JRE (https://help.ubuntu.com/community/Java) instead of using the OpenJDK. I also had to setup an M2_HOME environment variable to point to my Maven install. Both of steps tasks were spelled out by the IDE. 

Within about 15 minutes of downloading I had the project error free, building and running on a device. 

So for developing in the new environment has been good. I'll post an update once I've done a bit more with it.

]]>
tag:davespanton.posthaven.com,2013:Post/497265 2011-10-19T08:38:00Z 2013-10-08T17:07:53Z Handy wrappers for FileMerge as Subversion diff tool.

I've still not found a totally satifactory Mac based subversion client.

So while still doing a lot of humping around on the command line I found some handy scripts that to enable FileMerge to be used as a diff tool for Subversion.

They can be found along with instructions here.

]]>
tag:davespanton.posthaven.com,2013:Post/497267 2011-10-07T15:23:00Z 2013-10-08T17:07:53Z New Home

Having not blogged for a few months I've finally got round to moving from as3offcuts.com to somewhere I can babble about a broader range of software development related topics including Android, Google Go, Haskell, bearded squid, embedded device shenanigans etc.

]]>
tag:davespanton.posthaven.com,2013:Post/497269 2011-02-27T21:23:00Z 2013-10-08T17:07:53Z 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.

]]>
tag:davespanton.posthaven.com,2013:Post/497271 2011-02-01T00:22:00Z 2013-10-08T17:07:53Z 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

]]>
tag:davespanton.posthaven.com,2013:Post/497274 2010-12-31T21:59:00Z 2013-10-08T17:07:53Z 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.

]]>
tag:davespanton.posthaven.com,2013:Post/497276 2010-11-18T18:40:00Z 2013-10-08T17:07:53Z 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.

]]>
tag:davespanton.posthaven.com,2013:Post/497278 2010-11-09T17:55:00Z 2013-10-08T17:07:53Z A few notes on Git

I have been using git for a while now on my own projects; largely using github to host them. ( Having lost vpn access to my old firm's svn repository :) )

I recently started to learn more about the system having stumbled across this excellent - and free - online book. It is highly recommended reading for anyone looking to get into, or learn more about git.

Git offers quite a few benefits over centrally managed version control systems. I would definitely recommend checking out the book linked above for a more comprehensive overview, but those features I have found most useful are:

  • Faster. Most operations occur locally, so it is a lot faster to use for most operations.
  • Branching. The branching system is far superior, allowing you to easily switch between different branches of work with very little effort or overhead.
  • Local. I can make commits, branches and do what I like without a network connection. Then once I have one I can push my work back to a remote.

There are quite a few other benefits, but these are the ones that have stood out for me over the last few months. On the downside, compared to svn for example, it does seem a little more complicated and there aren't quite as many good gui tools around. Here are a few worth having a look at:

As a side note, this guy is doing some interesting stuff with git at the moment. I particularly like the idea of his ShowOff project for presentations.

]]>
tag:davespanton.posthaven.com,2013:Post/497280 2010-11-01T04:42:14Z 2013-10-08T17:07:53Z Flash debug player in Chrome. Because Chrome comes with its own Flash plugin it takes a couple of quick steps to get the debug version of the player working.

Before anything ensure the Plugin content debugger is installed. This is downloadable for here and the currently running version can be checked here.

Next load up Chrome and go to about:plugins from the address bar.

Click on the Details button to show more information about each plugin and scroll down to the Flash plugin section.

There should be two plugins listed. Simply disable the one in the Chrome application data folder (probably the first one) and the debug player will be active.

]]>
tag:davespanton.posthaven.com,2013:Post/497282 2010-09-30T22:20:11Z 2013-10-08T17:07:53Z Stop Firefox killing Flash plugin while debugging. For quite a long time now I've just allowed Firefox to kill the Flash plugin while I'm debugging. Annoying, but not annoying enough to do anything about it. However, with a quick settings tweak I can now leave Firefox hanging for as long as I like while debugging. Simply navigate to about:config in Firefox, continue past its warnings and then find (for Windows) dom.ipc.plugins.enabled.npswf32.dll in the list. Right-click on it and toggle it to false. For Mac OS/X and Linux the value to toggle is dom.ipc.plugins.enabled.libflashplayer.so. Also check that dom.ipc.plugins.enabled is on its default setting of false. Alternatively, look for dom.ipc.plugins.timeoutSecs and change it to -1. Newer builds of Firefox (3.7a1pre and above) only use the dom.ipc.plugins.enabled value, which is true by default. If you're using one of these versions just change it to false. If you only want to disable crash protection for Flash then manually add in an entry for dom.ipc.plugins.enabled.flash player.plugin. Having just said this about newer build, during a quick test on 4.0b7pre Windows with default settings, the plugin hang for as long as I allowed it without being terminated. For more information, have a look here.]]> tag:davespanton.posthaven.com,2013:Post/497283 2010-08-31T16:52:00Z 2013-10-08T17:07:53Z 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

]]>
tag:davespanton.posthaven.com,2013:Post/497285 2010-08-02T15:57:00Z 2013-10-08T17:07:53Z 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.

]]>
tag:davespanton.posthaven.com,2013:Post/497287 2010-07-30T15:28:00Z 2013-10-08T17:07:53Z 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 
    } 
 } 
} 
]]>
tag:davespanton.posthaven.com,2013:Post/497290 2010-06-03T16:40:00Z 2013-10-08T17:07:53Z 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.

    ]]>
    tag:davespanton.posthaven.com,2013:Post/497291 2010-05-14T05:10:00Z 2013-10-08T17:07:53Z 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.  

    ]]>
    tag:davespanton.posthaven.com,2013:Post/497258 2010-03-21T22:27:00Z 2013-10-08T17:07:53Z 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.

     

    ]]>
    tag:davespanton.posthaven.com,2013:Post/497261 2010-03-08T20:30:00Z 2013-10-08T17:07:53Z 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.]]>
    tag:davespanton.posthaven.com,2013:Post/497264 2010-03-01T21:55:00Z 2013-10-08T17:07:53Z 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.

    ]]>
    tag:davespanton.posthaven.com,2013:Post/497266 2010-02-28T21:34:00Z 2013-10-08T17:07:53Z 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; 
        } 
    } 
    ]]>
    tag:davespanton.posthaven.com,2013:Post/497268 2010-02-06T07:08:00Z 2013-10-08T17:07:53Z Dynamically resizing AIR windows with non-resizing content.

    Following on from my previous post concerning dyncamically resizing AIR windows with user resize (based on Daniel Wabyick’s example here), I wanted to cover a further modification I made; that of having the window resize dynamically, but the content stay the same.

    To be more specific, I wanted a content area to remain a fixed size when the window resized dynamically, but maintain a percentage width of the area when the window was resized by the user. (If that makes no sense, download the example after the jump.)

    There are two main additions made to the previous example to achieve this. Firstly was to fix the width of the non-resizing area at the start of the resize effect. This was done by adding effectStart="{mainHBox.width=mainHBox.width}" to the Resize effect.

    The second part is to return the area to a percent width when the user resizes the window, so the gripperDownHandler method becomes:

     
    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); 
     
        mainHBox.percentWidth = 
            (mainHBox.width / (chrome.width - (mainContent.getStyle("paddingLeft")  		+
            mainContent.getStyle("paddingRight") + mainContent.borderMetrics.left 		+
            mainContent.borderMetrics.right))) 		*100;
    
    
        nativeWindow.startResize(); 
    } 

    The resizeHandler code has also undergone a slight tweak. It now bases the reduction target size for the chrome on the width of mainHbox. This prevents rounding errors, which could create scrollbars or slowly enlarging margins on continued resizes.

    ]]>
    tag:davespanton.posthaven.com,2013:Post/497270 2010-01-28T20:48:00Z 2013-10-08T17:07:53Z 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); 
    } 
    
    ]]>
    tag:davespanton.posthaven.com,2013:Post/497272 2010-01-21T08:11:17Z 2013-10-08T17:07:53Z 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]]>
    tag:davespanton.posthaven.com,2013:Post/497273 2010-01-18T01:34:00Z 2013-10-08T17:07:53Z Static initialisers two ways.

    Static initialisers are good ways of running code for a class before any instances of it are created. Very useful for setting up things like loggers or defining default styles for custom components. Two different methods of achieving this are outlined below.

    The first method looks something like this:

    
     private static var classConstructed:Boolean = classConstruct();
     
    private static function classConstruct():Boolean
     { 
        //do some initialising...
        return true;
     }
    

    When the static variable classContructed gets initialised, it calls the static method classConstruct executing whatever initialisation code is needed.

    The second method looks like this:

     
    [Mixin] 
    public class SomeClass 
    { 
        public static function init (systemManager:ISystemManager) :void 
        { 
            //do some initialising... 
        }
    

    This method uses slightly less code as it hooks into Flex's built in initialisation. All classes that use the [Mixin] metadata tag have thier static init method called during the SystemManager's mx_internal docFrameHandler method.

    ]]>
    tag:davespanton.posthaven.com,2013:Post/497275 2010-01-12T20:55:00Z 2013-10-08T17:07:53Z How to use custom bitwise flags in Actionscript

    The Alert class in AS3 is a good example of using bitwise flags to specify a configuration without having to set lots of separate Boolean flags. Its also very easy to create bitflags for yourself, which save time, code and memory! Below is an example of custom bitflags as well as an explanation of how it all works. You can have various buttons enabled in the Flex Alert - “OK”, “NO”, “Cancel” etc. Any combination can be used, and the configuration is all set via one argument. Each value is separated with the bitwise OR operator (the pipe | – not to be confused with the logical OR operator || - two pipes).

    The example below would contain OK, NO and CANCEL buttons.

     
    Alert.show(“My Alert message”, “My Alert tittle”, Alert.OK | Alert.NO | Alert.CANCEL );
     

    Below details how this works in terms of bitwise operations, but first here is an example of how to use this in your own program.

    Example of using custom bitwise flags in actionscript Create a static class to hold the values and a method to test them.

     
    package 
    { 
     
    public class Colours 
     { 
     
        public static const ULTRA_RED:uint 		= 1; 
        public static const RED:uint 			= 2; 
        public static const ORANGE:uint 		= 4; 
        public static const YELLOW:uint 		= 8; 
        public static const GREEN:uint			= 16; 
        public static const BLUE:uint			= 32; 
        public static const INDIGO:uint 		= 64; 
        public static const VIOLETE:uint 		= 128; 
        public static const ULTRA_VIOLETE:uint 	= 256; 
     
        //convenience const to enable all flags 
        public static const ALL:uint = ULTRA_RED | RED | ORANGE | YELLOW | GREEN | BLUE | INDIGO | VIOLETE | ULTRA_VIOLETE; 
     
        public static function test(flags:uint, testFlag:uint):Boolean 
        { 
            return (flags & testFlag) == testFlag;
        } 
     } 
    } 
    

    Now, you can pass a combination of flags around as one single argument. The flags are combined using the bitwise OR operator.

     
    var chosenColours:uint = Colours.RED | Colours.BLUE | Colours.VIOLETE; 
    

    Then later test to see if the flag you want is in that single argument.

     
    if ( Colours.test(chosenColours, Colours.RED) ) 
        trace(“We have RED”); 
    else 
        trace(“We don’t have RED”); 
    

    Note the Colours.ALL const, which is just a convenient way to enable all the flags in one go. 

    And that's it. Makes life very simple, less method arguments, less var declaration, less database columns if you store a configuration, less memory used. Very simple to implement and very useful!

    How it works - creating Each of the constants that define the flags Colours.RED, Colours.YELLOW etc are all integers. The separate flags must be multiples of 2 (which will become clearer later), so they would be 1,2,4,8,16,32 etc. The bitwise OR looks at the binary representation of each integer and analyses each bit of each integer in turn. Each bit is treated as a Boolean flag. If the bit is 1, its on, if its 0 its off. The bitwise OR will look at all the corresponding bits of each value in the list, starting with the first bit, then the second etc. If any of the bits are 1, the resulting bit for that position is 1, if ALL are 0 the resulting bit for that position is 0.
            0001  ( decimal 1 )         0010  ( decimal 2 )         1000  ( decimal 8 ) Bitwise OR =         1011  ( decimal 11 )
    So, looking down each column of bits, the OR checks if any are 1, if so, the resulting bit is 1, else its 0. So the output of ( 1 | 2 | 8 ) is 1011,which is decimal 11. As the integers are multiples of 2 you don’t get multiple “1” bits in the binary representation of any number so only 1 column is ever marked as “on” by any flag – as in the example above. If you added 0110 ( binary 10 ) to the example above it would end up with 2 columns marked as "on" for one flag, which would break the system as you could not then calculate if the resulting bit flag contained a specific flag, as explained below.


    How it works - testing Now you have one value that represents multiple flags. The next step is to check if it contains a particular flag. This is very similar, except you reverse the process and use the bitwise operator AND (the ampersand &, not to be confused with the logical AND &&) This looks at the columns of bits, and if ALL of them are 1, the result is 1, if not its 0. In the same way, as the columns are unique due to multiples of 2, we can check if the combined integer contains our value.
            1011 (decimal 11 - our combined flags)         0010 (decimal 2 - the flag to check for) Bitwise AND =         0010 (decimal 2)
    As only the 2nd (from right) column contined both “On” bits, the result is 0010, which is our decimal 2, the value we wanted to check! So you can easily check to see if your value is in the combined flags by doing the following.


    
    var hasValue:Boolean = ((flags & value) == value)
    

    Very useful stuff!]]>
    tag:davespanton.posthaven.com,2013:Post/497277 2010-01-04T22:29:00Z 2013-10-08T17:07:53Z AutoComplete component sizing.

    The Flex Components AutoComplete ( Link ) offers a great auto suggestion text input component, which often makes for a better experience than a combo box or list. What it didn't do was resize quite how a wanted it to.

    I was using the AutoComplete component as the auto-resizing part of a horizontal panel in an AIR application. When the window was resized by the user, the AutoComplete would enlarge or shrink to fit, down a minimum size set on the window.

    The problem was that I couldn't seem to get the AutoComplete to fit without scrollbars appearing. After a bit of digging I found the minimum width gets set to the longest item in the data provider in the measure method of ComboBase. This was exacerbated by the long items in the data provider I was using, forcing scroll bars onto any reasonable size of window.

    Extending AutoComplete and overriding measure with the following fixes the problem, and hasn't given me any issues so far.

     
    override protected function measure():void 
    { 
        measuredWidth = mx.core.UIComponent.DEFAULT_MEASURED_WIDTH; 
        measuredHeight = UIComponent.DEFAULT_MEASURED_HEIGHT; 
        measuredMinWidth = UIComponent.DEFAULT_MEASURED_MIN_WIDTH;
        measuredMinHeight = UIComponent.DEFAULT_MEASURED_MIN_HEIGHT; 
    } 
    

    By not calling super and setting the four properties above then the component takes on the default minimum width of 40 and re-flows as expected. Obviously some of the items in the drop down may be cut off, but the text in the input field is draggable, so it's always possible to see all of it one way or another. A future improvement to this might be to include a tool-tip rollover to truncated drop down items.

    I might improve this if I reuse the component in the future - maybe include some measurement logic similar to TextInput, or just some provision for borders and padding. In it's current application it works though, so I might just leave well alone!

    ]]>