Dark themes for Flash Builder

Spending a lot of time in front of a bright LCD monitor can be a real pain for the eyes. But there’s no good reason why you should keep the default white background behind your code. After a search I found that some people have already prepared configurations that will allow you to have bright text on a dark background.

Quick list of themes

fb-zenburnishhttp://www.noiseandheat.com/blog/
Dark theme for Flash Builder 4http://www.likidu.com/blog/
The Typography of My Flash Builder http://kevinsuttle.com/

After testing them for a while I’m currently using fb-zenburnish.

Installing a theme

First download the file, and unzip if necessary. You should have an .epf file. Now go to the Flash Builder, and from the File menu select Import->Other. (you might want to backup your current settings before importing the new ones, just choose Export instead of Import and it should be a straight forward process)
Import -> Other
Than choose Preferences from the General node and click Next.
Preferences
Than just browse for the epf file and click Finish.

Your brand new color scheme should be set.

From photoshop design to a Flex 4 skin

When looking at some old project folders I’ve found one of the first skins I’ve created while starting with the Flex 4 skinning model, and I thought it might be an interesting case to look at, source code is included at the end of the post. It’s based on a really nice design done by Adrian Pelletier. What we’ll try to do is create a button which looks more or less like one of his button designs:

What makes it a good design is not only the way it looks but also the way the Photoshop file is created – it’s mostly based on shapes and layer effects which are easy to translate to Flex skin code.

Styling a Flex 4 Button

The Flex 4 skinning model is different from the one used in Flex 3, to keep the introduction short, let’s just say it’s now much easier to create programmatic skins, and you can do it with newly introduced MXML tags. If you ever used Degrafa to skin your components it’s should be fairly familiar, if not please check the example code. The basic usage is straight forward – you need to create a mxml file and you can start putting the new tags to design the skin.

Let’s start with the shadow behind the button, as you can see on the picture above it has 3 parts – a gradient fill, a stroke and an inner shadow, and all of them thrown on a shape of a rounded rectangle. Let’s translate this to graphic tags. First of we need that rounded rectangle, so we define a Rectangle with the corner radius using the new tags:

<s:Rect radiusY="24"
        radiusX="24"/>

That’s how easy it is to create shapes using the new syntax. Next we need to define a fill, which according to the Photoshop design is a linear gradient starting from color 0x0f2835 and ending with color 0×153445. We also need an inner drop shadow on it, so let’s add it. We also need a stroke above all this, so we need to add another rectangle which will not have the drop shadow on it, and will define that gradient stroke, just like the design. A few minutes later we have:

<s:Rect radiusY="24"
            radiusX="24"
            x="0"
            y="0"
            width="{this.width}"
            height="{this.height}"
        >
        <s:filters>
            <s:DropShadowFilter inner="true"
                                distance="0"  
                                strength="1"/>
        </s:filters>
        <s:fill>
            <mx:LinearGradient rotation="90">
                <mx:GradientEntry color="0x0f2835"/>
                <mx:GradientEntry color="0x153445"/>
            </mx:LinearGradient>
        </s:fill>
    </s:Rect>
    <s:Rect radiusY="24"
            radiusX="24"
            x="0"
            y="0"  alpha="0.8"
            width="{this.width}"
            height="{this.height}" >
        <s:stroke>
            <mx:LinearGradientStroke rotation="90"
                                     weight="2"
                                     pixelHinting="true">
                <mx:GradientEntry color="0x102a39"/>
                <mx:GradientEntry color="0x20516c"/>
            </mx:LinearGradientStroke>
        </s:stroke>
    </s:Rect>

It’s not the shortest listing, but remember that I’m only copying the settings from the design. The final flash result looks like this:

It’s almost a easy to create the rest of the design, take a look a the working button with some Flex magic thrown in to get nice transitions between states (viewsource enabled), and after the jump, I’ll quickly point to different parts of the design which are used in the ButtonSkin.mxml

Result

What makes a skin – looking at ButtonSkin.mxml

First of you should define a component for which the skin is designed.

 [HostComponent("spark.components.Button")]

Next you need to define all the states which are defined by the host component (you can check this info on livedocs) which is done in this code:

    <s:states>
        <mx:State name="up"/>
        <mx:State name="down"/>
        <mx:State name="over"/>
        <mx:State name="disabled"/>
    </s:states>

After that’s done you also need to put the parts of the skin that the host components assumes your skin will have (this is called skinning contract and I’ll write a post about it when I have some time). In the case of Button we need to display a single string (the button label as stated in livedocs) we’re going to use a Label for that and give it an id of labelDisplay according to the contract.

<s:Label left="17" right="17" color="0xffffff"
    height="{this.height}" verticalAlign="middle" id="labelDisplay" >

Than we can start putting in the graphics, using the same tags we used while creating the shadow. The only additions is that the values of the gradients change depending on the state, thanks to the new state syntax in Flex 4 it’s much more readable – there’s a different color when the button is in an over state (color.over) and a different one when the button is in the down state (color.down)

<mx:GradientEntry id="ge1" color="0x387dda"
        color.over="0x3e81de" color.down="0x88bafe" />

To add the smooth color fades between states we also define a bunch of transitions which work on our gradient entries.

<s:Transition   fromState="up" toState="over" autoReverse="true" >
   <s:AnimateColor targets="{[ge1, ge2, ge3, ge4]}"  duration="250"/>
 </s:Transition>

Feel free to download the source code and play with it, hopefully it will be a good starting point.

Download source code.

How not to use “services_config.xml”

The most common way to use RemoteServices in flex is by creating a separate file to keep the configuration, and adding the “-services” switch to the compiler arguments. It’s a good way to do it, but not always, and is especially painful when explaining remoting to someone. But you can skip the whole file and configure the same thing using MXML tags. I’ll take a sample “services_config” file (this one is for zend_amf) and translate it to MXML.

<?xml version="1.0" encoding="UTF-8"?>
<services-config>
    <services>
        <service id="amfphp-flashremoting-service"
        class="flex.messaging.services.RemotingService"
        messageTypes="flex.messaging.messages.RemotingMessage">
            <destination id="zend">
                <channels>
                    <channel ref="library"/>
                </channels>
                <properties>
                    <source>*</source>
                </properties>
            </destination>
        </service>      
    </services>  
    <channels>  
         <channel-definition id="library"
            class="mx.messaging.channels.AMFChannel" >
         <endpoint uri="http://localhost/librarySample/amf.php"
            class="flex.messaging.endpoints.AMFEndpoint" />
        </channel-definition>        
    </channels>
</services-config>

translates to:

<mx:ChannelSet id="chanelSet" >
      <mx:AMFChannel
      uri="http://localhost/librarySample/sampleamf.php" />
</mx:ChannelSet>

<mx:RemoteObject  
      channelSet="{chanelSet}" >       
 </mx:RemoteObject>

So what you need to do is create a ChannelSet, put a channel inside (in this case AMFChannel) and set its uri to the one you would usually put as endpoint uri in the config file.
Once you do that you can start using your RemoteObjects without the services_config.

Of course you should add the rest of the things you usually put inside a remote object. For people who would like an example:

<mx:RemoteObject  
        channelSet="{chanelSet}"
        source="myServerSideClassName"  
        destination="zend" >
        <mx:method
            name="serverSideFunctionName"
            result="someResultFunction()" />           
</mx:RemoteObject>

Things you might not know about calling actionscript functions

OK, my guess would be that everybody used a function at one point or another. But there are some things which are less than obvious about an actionscript function. Let’s take a quick look.

Calling functions

Let’s create a simple function which will accept any number of parameters.

function sum(...arg):int
{
      var val:int = 0;
      for each (var i:int in arg)
            val+=i;
      return val;
}
// The usual way to call it
sum(0,1,2);

But that’s something everybody knew how to do. The interesting thing is that in Actionscript 3.0 there is a class called Function which also has it’s own methods defined, and all the functions are instances of that class. Most of the methods are inherited from Object but there are two defined for it, which are used to achieve a similar thing – calling the function, this are apply() and call(). The first parameter of both functions is almost always ignored [1].

The definition of call – call(thisArg:*, ...args):* shows that it also takes any number of parameters, than it uses them as arguments, so, as the first parameter is ignored – sum.call(null,0,1,2) is the same as sum(0,1,2).
The problem with calling functions like this is that you actually need to know how many parameters you’re going to use.

Luckily apply() has an array as a second parameter. Which means you can call a function, and pass any number of parameters as an Array. Quick sample of achieving the exact same functionality as before using apply.

// this array can be dynamically generated
var params:Array = [0,1,2];
sum.apply(null,params);

Which is much more flexible.

arguments variable

One more thing which is worth knowing is that inside functions you can access the arguments variable. It’s holds all the variables passed to the function, with the limitation that it doesn’t work when using the ...arg notation in the function definition. So this will not work:

function sum(...arg):int
{
      trace (arguments);
      // throws an error
      [...]
}

But it will work with functions without the ...arg in the definition, for example this prints out both strings:

function printStrings(s:String,s2:String):void
{
      trace (arguments);
}

Apart from that this variable also holds the reference to the currently executing function in the arguments.callee property. Things like this come in handy sometimes.

Sample

Using all the tools described (callee, arguments, apply) we can build a quick sample, a class that records the calls to it’s functions in an easy way, and is able to replay them when needed.

CallRecorder.as

package
{
    import mx.collections.ArrayCollection;
    public class CallRecorder
    {
        // Just a sample function
        public function printJohn(s:String):void
        {
            rememberTheCall(arguments);
            trace ('John says ' + s);
        }
       
        // Just a another sample function
        // notice that it has a different set of arguments
        public function printBob(s:String,times:int = 1):void
        {
            rememberTheCall(arguments);
            while (times-- > 0)
                trace ('Bob says ' + s);
        }              
       
        /** Replays all the calls in memory **/
        public function replay():void
        {
            replayIsOn = true;
            trace ("--- Starting the replay ---");
            // Notice we actually don't need to worry
            // about the arguments  
            for each (var arg:Object in memory)
                (arg.callee).apply(this,arg);
            replayIsOn = false;
            trace ("--- Stoping the replay ---");
        }
       
        /** True if currently  replaying **/
        private var replayIsOn:Boolean = false;
        /** Used for storing the history of function calls **/
        private var memory:ArrayCollection = new ArrayCollection();
       
        /** Stores a call in memory, if not called while replay **/
        private function rememberTheCall(passedArguments:Object):void
        {
            if (!replayIsOn)
                memory.addItem(passedArguments);           
        }
               
    }
}

Sample execution:

var recorder:CallRecorder = new CallRecorder();
recorder.printBob("I do");
recorder.printJohn("I do too");
recorder.printBob(":)",3);
recorder.printJohn(":)");
recorder.replay();
// results in
// Bob says I do
// John says I do too
// Bob says :)
// Bob says :)
// Bob says :)
// John says :)
// --- Starting the replay ---
// Bob says I do
// John says I do too
// Bob says :)
// Bob says :)
// Bob says :)
// John says :)
// --- Stoping the replay ---

Not a great piece of software but hopefully interesting.
———————————–
[1] The only case it’s not ignored which I could find is when using anonymous functions.
LiveDocs on Function class
LiveDocs on arguments class

Spark Group, SkinPart and Error 1020

I’ve recently started a project that uses new Flex 4 skinning. It was going great until I’ve added some SkinParts and it started throwing a strange error message on those definitions :

1020: Method marked override must override another method.

After starring at it for a while with utter confusion, I’ve started to investigate what might be the problem. Turns out I was adding skin parts to a spark Group, and the documentation states:

To improve performance and minimize application size,
the Group container cannot be skinned.
If you want to apply a skin, use the SkinnableContainer instead.

Which is exactly what I needed to do. Too bad there was no hint about it in the error string.

/