Archive for August, 2009

Linked Containers in Flex 4 using Text Layout Framework

Using the latest capabilities of Flash Player 10 in terms of text engine, Text Layout Framework offers much more extensible and feature-rich text layouts. Here is a list of capabilities for the new text framework:

- Bidirectional text, vertical text and over 30 writing scripts including Arabic, Hebrew, Chinese, Japanese, Korean, Thai, Lao, Vietnamese, and others.
- Selection, editing and flowing text across multiple columns and linked containers.
- Vertical text, Tate-Chu-Yoko (horizontal within vertical text) and justifier for East Asian typography.
- Rich typographical controls, including kerning, ligatures, typographic case, digit case, digit width and discretionary hyphens.
- Cut, copy, paste, undo and standard keyboard and mouse gestures for editing
- Rich developer APIs to manipulate text content, layout, markup and create custom text components.
- ActionScript-based object-oriented model for rich text layout enabling live updates.

What we’ll touch in this post is linked containers. What is this all about is that you can have a flow of text (TextFlow) displayed on two or more separate containers and manage them using controllers and composers. From the last sentence we can clearly distinct the three main part of the framework, following MVC approach:

- Model would be the TextFlow along with all it’s elements.
- View would be the container.
- Controller would be the controllers and everything that relates to user interaction on the text.

Starting our demo we want to have 2 containers displayed that will share the same text flow. Sizes for containers will be changed when resizing the application to force the text to span across one or both of them, depending on the size. For the sake of simplicity we will build up a SparkSkin and have everything declared in it.
First we need the TextFlow, an xml file actually that declares the TextFlow. This will be converted into actual text layout format.

1
2
3
4
5
6
7
8
9
10
11
12
13
<fx:Declarations>
    <fx:XML id="xml">
        <TextFlow xmlns="http://ns.adobe.com/textLayout/2008" fontSize="14" fontFamily="Verdana">
            <p>The Text Layout Framework is an extensible ActionScript library, built on the new
               text engine in Adobe® Flash® Player 10 and Adobe AIR 1.5, which delivers advanced,
               easy-to-integrate typographic and text layout features for rich, sophisticated and
               innovative typography on the web. The framework is designed to be used with Adobe
               Flex® or Adobe Flash Professional and is included in Flex 4, code named "Gumbo".
               Developers can use or extend existing components, or use the framework to create
               their own text components.</p>
        </TextFlow>
    </fx:XML>
</fx:Declarations>

Second, we need the containers where the text will be displayed:

1
2
3
4
5
6
<s:Group id="contentGroup" horizontalCenter="0">
   
    <mx:UIComponent id="container1"/>
    <mx:UIComponent id="container2" x="250"/>
   
</s:Group>

As declarations, we have the text flow which will result from converting the xml object and two controllers for the containers we just displayed. These controllers will be used to compute how much text to display in each container, depending on all properties of the text flow.

1
2
3
private var textFlow:TextFlow;
private var controller1:ContainerController;
private var controller2:ContainerController;

At creation complete we just link all components together, converting the text flow, creating controllers for containers and add them to the text flow and update them.

1
2
3
4
5
6
7
8
9
10
11
protected function creationCompleteHandler( event:FlexEvent ):void
{
    textFlow = TextConverter.importToFlow( xml, TextConverter.TEXT_LAYOUT_FORMAT );
    controller1 = new ContainerController( container1 );
    controller2 = new ContainerController( container2 );
   
    textFlow.flowComposer.addController( controller1 );
    textFlow.flowComposer.addController( controller2 );
   
    updateControllers();
}

Updating controllers method is separate because we will also call it when resizing the application:

1
2
3
4
5
6
7
8
9
10
11
12
protected function resizeHandler( event:ResizeEvent ):void
{
    if( initialized )
        updateControllers();
}

private function updateControllers():void
{
    controller1.setCompositionSize( 200, height );
    controller2.setCompositionSize( 200, height );
    textFlow.flowComposer.updateAllControllers();
}

What’s happening is that the controllers will adjust the required sizes depending on the height of the application, and while the containers are linked (with flowCompose.addContainer), text will span across both of them in necessary. You can view the example here http://ayonesoftware.com/blog/examples/tlf with right-click for view source.

Asynchronous Testing using FlexUnit 4

As you might have known there is a new version of FlexUnit in development on the opensource site at Adobe http://opensource.adobe.com/wiki/display/flexunit/FlexUnit for a few months now. This is a new breed between FlexUnit 1 and Fluint. Before delving into the asynchronous topic i would like to mention some improvements to the framework:

1. You are not any more required to explicitly extend TestSuite and TestCase classes. For the suite you just mark it as being a suite by placing [Suite] metadata tag. All test case classes that you want the suite to run should then be added as public properties in this class. The TestCase class does not require having methods that begin with “test”. Instead you mark the test methods by [Test] metadata.

2. The runner is externalized, requiring FlexUnit4UIRunner.swc for default runner. You specify the runner which a suite used by placing [RunWith] metadata tag, default runner looking like [RunWith("org.flexunit.runners.Suite")]. This being the case you can always create a custom runner and add new capabilities/functionalities in test runs.

3. Flash Builder 4 has a built in mechanism for testing, allowing one to choose what suites or test cases to run and display results in FlexUnit Results view. I wouldn’t recommend this approach right now as it has some huge memory issues which eventually will get the builder to a halt.

For a big picture about new capabilities of FlexUnit 4 go to http://opensource.adobe.com/wiki/display/flexunit/FlexUnit+4+feature+overview

Now on the asynchronous area, which has been a lot improved since the addition of Fluint. To mark a method as being part of an async process, you just add “async” under [Test] metadata [Test(async)]. This will let you access the asynchronous capabilities of the framework. The one that we’ll exemplify is usage of a RemoteObject call.

First we build the basic test class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package
{
   
import mx.rpc.remoting.RemoteObject;

public class TestRemoteObject
{
    //------------------------------------------------------------
    //
    // Properties
    //
    //------------------------------------------------------------
   
    /**
     * Service to be used in testing async calls.
     * @private
     */

    private static var service:RemoteObject;
   
    //------------------------------------------------------------
    //
    // Methods
    //
    //------------------------------------------------------------
   
    [BeforeClass]
    public static function setUp():void
    {
        service = new RemoteObject();
        service.endpoint = "yourEndpointHere";
    }
}

}

A simple declaration of the RemoteObject and a [BeforeClass] marked method. What [BeforeClass] states is that the method is called only once before the whole class is executed in the test queue. We just setup the RemoteObject with any valid endpoint. The next and final step of the test case is actually testing a method of the service:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[Test(async)]
public function testMyMethod():void
{
    var token:AsyncToken = service.myMethod();
        token.addResponder( Async.asyncResponder( this,
                                new TestResponder( verifyResult, verifyFault ), 2000 );
}
   
protected function verifyResult( e:ResultEvent, token:AsyncToken ):void
{
    Assert.assertTrue( "Result is what i want it to be", e.result is ArrayCollection );
}
   
protected function verifyFault( e:FaultEvent, token:AsyncToken ):void
{
    Assert.fail( "Unintended fault from service" );
}

Taking it from the in out, we define a TestResponder which is nothing else than a simple Responder, only that it adds an extra parameter “passThroughData” (more on this in a later post) to the result and fault methods. This responder is then added into the async capabilities of the framework using Async.asyncResponder, registering the test case (this – first param), responder (which we just built) and the timeout for call failure. On the verifyResult method you can assert everything you want from the result object and under verifyFault, if this fault is not intentional, you can just Assert.fail, telling the framework that the call failed.

Another goodie about the asynchronous testing in FlexUnit 4 is that you’re no longer needed to chain multiple async methods with events and listeners. You can accomplish this by using “order” param under [Test] metadata. So for the first async method tested you would have [Test(async,order=1)], for the second one [Test(async,order=2)] and so on. The framework will route them handy async one after another.

Next step would be to build the suite class, which as described above should look very simple:

1
2
3
4
5
6
7
8
9
10
11
package
{

[Suite]
[RunWith("org.flexunit.runners.Suite")]
public class TestSuite
{
    public var testRO:TestRemoteObject;
}

}

And the final step is getting everything to work under an Application. The one that does that is FlexUnitCore, which as the name states is the core component coupling the suite and test cases with the runner:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:flexUnitUIRunner="http://www.adobe.com/2009/flexUnitUIRunner"
    creationComplete="creationCompleteHandler( event )">
   
        <fx:Script>
        <![CDATA[
   
    import mx.events.FlexEvent;
   
    import org.flexunit.runner.FlexUnitCore;

    protected function creationCompleteHandler( event:FlexEvent ):void
    {
        var core:FlexUnitCore = new FlexUnitCore();
        core.addListener( runner );
       
        core.run( TestSuite );
    }
   
    ]]>
    </fx:Script>
   
    <flexUnitUIRunner:TestRunnerBase id="runner" width="100%" height="100%"/>
   
</s:Application>

The runner, being externalized, is added into the works using core.addListener, thus receiving events from core regarding the tests. Simply call core.run() on the suite and hope that green checks are everywhere. To view the detailed code for async capabilities in FlexUnit go to http://opensource.adobe.com/svn/opensource/flexunit/branches/4.x/FlexUnit4/src/org/flexunit/async/.

Download example source code from here

Flex 4 Layout Capabilities

A major headache in Flex 3 was to slightly change the layout of components. Say you would want to change a List display from vertical to horizontal. No chance. You would need to build up another component, HorizontalList, and have all the logic in there. With the Flex 4 approach to layouts, things are much more simple. Having a layout class that takes care of a component’s children offers support for extensibility. This way there is no difference between a normal vertical list and a horizontal list for example, in terms of data processing/children creations. The only difference is that the components have a different layout attached. This is achieved by specifying the layout property on the component.

The two base components that support layout inside the Flex 4 SDK are:

1. GroupBase, a class for displaying visual elements. Visual elements here means both UIComponent and GraphicElement, elements that can be laid out on the stage.

2. SkinnableDataContainer, a class for displaying visual elements based on data content. This is the base class for all list-based classes on Spark. This is where the journey begins for allowing a List component to display it’s children in different ways.

As the first component is plain simple, we’ll do a demo of customizing a DataContainer’s layout. Let’s suppose we need a menu in a circle fashion like in the image below.
Circle Layout
It looks heavy stuff at a first sight, but all we need is a spark List and a CircleLayout class that computes the positions for each element on the list. The layout class takes in functionalities for measurement/sizing/placing elements on the component.

For positioning and sizing the elements on the stage, setLayoutBoundsPosition and setLayoutBoundsSize would be used. In this process, helper methods are called on the elements when needed to get the preferred size/position such as getPreferredBoundsWidth, getPreferredBoundsHeight. All methods are listed in mx.core.ILayoutElement interface.

For the CircleLayout that we want to build, we only need a radius specified that will help to determine the locations of the elements on a circle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * @private
 */

private var _radius:Number;

/**
 * Circle radius at which the elements will be laid out.
 * @return
 */

public function get radius():Number
{
    return _radius;
}

/**
 * @private
 * @param value
 */

public function set radius( value:Number ):void
{
    _radius = value;
   
    target.invalidateSize();
    target.invalidateDisplayList();
}

The target is the actual component to which the layout is attached. Each time a property is updated that affects the size or display of the component after layout processing, invalidateSize and invalidateDisplayList methods should be called. These are familiar from the Flex 3 invalidation model.
These will translate on calling measure and updateDisplayList on the component which for a ILayoutElement will forward the chain to the layout’s measure and updateDisplayList.

For our example, measure will set the measured width and height on the component based on the radius and sizes for each children elements. As we are not changing anything on a children’s size, we let the components size themselves by using getPreferredBoundsWidth and getPreferredBoundsHeight. Here is the measure method in it’s complete form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * @private
 */

override public function measure():void
{
    super.measure();
   
    target.measuredWidth = radius * 2;
    target.measuredHeight = radius * 2;
   
    var numElements:int = target.numElements;
    var element:ILayoutElement;
   
    for( var i:int = 0; i < numElements; i++ )
    {
        element = target.getElementAt( i );
        element.setLayoutBoundsSize( element.getPreferredBoundsWidth(),
                                     element.getPreferredBoundsHeight() );
    }
}

Now we actually need to place the elements at their specific positions inside updateDisplayList method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * @private
 */

override public function updateDisplayList( width:Number, height:Number ):void
{
    super.updateDisplayList( width, height );
   
    var stepAngle:Number = 360 / getNumLayoutElements();
    var angle:Number;
    var numElements:uint = target.numElements;
    var element:ILayoutElement;
    var x:Number;
    var y:Number;
    var boundsWidth:Number;
    var boundsHeight:Number;
   
    for( var i:int = 0; i < numElements; i++ )
    {
        element = target.getElementAt( i );
       
        if( !element.includeInLayout )
            continue;
       
        DisplayObject( element ).rotation = stepAngle * i;
       
        boundsWidth = element.getPreferredBoundsWidth( true );
        boundsHeight = element.getPreferredBoundsHeight( true );
       
        angle = Math.PI - stepAngle * i * Math.PI / 180;
        x = radius + Math.sin( Math.PI - angle ) * radius - boundsWidth / 2;
        y = radius + Math.sin( Math.PI / 2 - angle ) * radius - boundsHeight / 2;
       
        element.setLayoutBoundsPosition( x, y );
    }
}

Basically what it does it calculates the angles, rotations and positions for each element (if included in layout). One goodie to mention here is the getPreferredBoundsWidth and getPreferredBoundsHeight parameter. This being true, the method will return the value post layout transform. In our case, after the element has been rotated. Other than that it’s pure math.

In a previous post i detailed how the states work in a spark component. Using that knowledge we will have two states for our demo application, one normal state and one selected state. For the selected state, the circle radius will be a little bigger and we’ll display something in the middle.

The list component looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<s:List id="list" horizontalCenter="0" verticalCenter="0"
    selectionChanging="listSelectionChangingHandler()"
    skinClass="com.ayone.examples.circleMenu.ui.skins.ListSkin"
    clipAndEnableScrolling="false" labelField="name">
   
    <s:layout>
        <layouts:CircleLayout id="circleLayout" radius.normal="57" radius.selected="200"/>
    </s:layout>
   
    <s:ArrayCollection>
        <fx:Object name="Menu1"/>
        <fx:Object name="Menu2"/>
        <fx:Object name="Menu3"/>
        <fx:Object name="Menu4"/>
        <fx:Object name="Menu5"/>
    </s:ArrayCollection>
   
</s:List>

Note the radius property on the layout is set based on the current state, normal or selected. This along with the invalidation mechanism will assure that the component will have its elements updated each time the state is changed. Using a custom skin to display the ellipse on the list and all is ready:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
      minWidth="112" minHeight="112"
      alpha.disabled="0.5">
   
    <s:states>
        <s:State name="normal" />
        <s:State name="disabled" />
    </s:states>
   
    <s:Ellipse top="1" bottom="1" left="1" right="1">
        <s:stroke>
            <s:SolidColorStroke color="0x000000"/>
        </s:stroke>
    </s:Ellipse>
   
    <s:Scroller left="1" top="1" right="1" bottom="1" id="scroller" focusEnabled="false">
        <s:DataGroup id="dataGroup" itemRenderer="spark.skins.default.DefaultItemRenderer">
            <s:layout>
                <s:VerticalLayout gap="0" horizontalAlign="contentJustify" />
            </s:layout>
        </s:DataGroup>
    </s:Scroller>
   
</s:SparkSkin>

And to add a little flavor to it, we’ll animate the transition between states with a MotionPath that basically updates the target property over a period of time.

1
2
3
4
5
6
7
<s:transitions>
    <s:Transition>
        <s:Animate target="{ circleLayout }" duration="200" effectEnd="effectEndHandler(event)">
            <s:SimpleMotionPath property="radius"/>
        </s:Animate>
    </s:Transition>
</s:transitions>

You can view the running application here and view the source here