Archive for the ‘Flex’ Category

What command-line tools are included in the Flex SDK?

Wednesday, January 7th, 2009

Inside the bin directory of the Flex SDK you will find a long list of command-line tools. The following is an overview of what these tools do:

AIR Development Tools

  • aasdoc – For creating documentation of the classes in an AIR application
  • acompc – For creating a SWC component (a reuseable library of source code for use in other projects) for AIR.
  • adl (not included in the Open Source Flex SDK) – AIR Debug Launcher for debugging AIR applications. Described here.
  • adt (not included in the Open Source Flex SDK) – A utility for packaging an application into an AIR installation file, which you can distribute to your users. An AIR installation file is an archive that contains all the application files.
  • amxmlc – The compiler to use when building AIR applications, invokes the standard Flex mxmlc ActionScript and MXML compiler with an additional parameter, +configname=air.

Flex Development Tools

  • asdoc – For creating documentation of MXML and/or ActionScript classes.
  • compc – For creating SWC component libraries, reusable archives of source code that can be used in other projects. Makes distribution of a library of classes easy.
  • copylocale – Utility for helping with localization in Flex Applications.
  • digest – Used after SWCs have been optimized with optimizer to update SWC digest information.
  • fcsh – The Flex Compiler Shell Utility provides a shell environment for compiling Flex applications, modules, and component libraries that is quicker than using mxmlc or compc.
  • fdb – A command-line based debugger.
  • jvm.config – Allows the custom configuration of the JVM (Java Virtual Machine) for more efficient use by the mxmlc and compc.
  • mxmlc – The standard Flex compiler. Converts ActionScript and/or MXML code into a SWF that can run inside the Flash Player.
  • optimizer – Removes debugging code and unnecessary metadata from a SWC library. This can be run after compc.

Curious about Adobe Open Source? Get started with the Flex SDK on Mac OS X

Tuesday, January 6th, 2009

How about creating a SWF that runs in the Adobe Flash Player without building it in the Flash or Flex Builder authoring environment, using tools that are free and open source? Ever since Adobe made the move from ActionScript 2.0 to 3.0 there has been a gem of a toolkit available that allows precisely that. The Flex SDK (Software Development Kit) allows developers to create SWFs from ActionScript and MXML source code, and with the right setup is not difficult to configure and use.

Housed at Adobe Open Source, the Flex SDK is available in two incarnations through the site:

  • The Open Source Flex SDK containing everything needed to create a functional application using ActionScript and/or MXML and the Flex framework.
  • The Free Adobe Flex 3 SDK containing everything in the Open Source Flex SDK plus additional components such as advanced font encoders, tools for packaging Adobe AIR applications, and the Adobe Flash Player.
  • How to use the Flex SDK

    I have developed an Apache Ant build script that makes—after some configuration—the Flex SDK quite easy to use on Mac OS X. Here’s how to configure it:

    1. Download the latest Flex SDK from Adobe Open Source. Rename the SDK folder flex_sdk_3 and place it in /Applications/ on your hard drive.
    2. Locate Apache Ant on your system. Ant will already be installed if you have installed the Mac OS X Developer Tools (which are an optional install included with every version of OS X) or are running Leopard.

      Open Terminal and type:

      whereis ant

      It should say something like

      /usr/bin/ant

      If Ant is not installed, no path will be shown in Terminal. To install Ant I recommend using MacPorts, an excellent open source utility for managing unix tools on Mac OS X (follow these well written directions for installation). If you are not comfortable using the Terminal, there is a GUI available for MacPorts called Porticus.

    3. Copy the Flex Ant tasks to your Ant installation’s library. These will allow Ant to communicate with the major Flex SDK tools. To copy the tasks, first locate the Ant lib directory, which will be in Ant’s main installation folder. For example on Mac OS X 10.5 it appears at usr/share/ant/lib. Copy /Applications/flex_sdk_3/ant/lib/flexTasks.jar into this directory.
    4. If you are an advanced user and would like to utilize Unit Testing using FlexUnit, Download the FlexUnit Ant Tasks. Place these in the Ant installation’s library folder as well.

      (Note: The project template you will download from my site in the next step includes two SWCs for use with unit testing. For those that may be curious where these came from, here are the links to the original locations: FlexUnit SWC library and FlexUnit Optional SWC library)

    5. Download the Flex SDK example application template from my site. Unzip the archive and place the FlexSDKProjectTemplate folder on your desktop. Open the folder.
    6. Make a copy of build.properties.template and rename it build.properties.
    7. Open the build.properties file you just created and edit the REQUIRED TOOL LOCATIONS section to reflect the path to the Flex SDK, your preferred web browser, and the location of the Flash Player (which you will need to download if you have not already done so).
    8. Using Terminal navigate to the example application template. For example:
      cd Desktop/FlexSDKProjectTemplate/

      And then type the following:

      ant run

      The sample application will launch, typing ant usage will show you what other options are available, such as creating documentation, SWCs, or launching the application in a web browser.

    9. Lastly, to enable the trace() method so that it will work from your code when using the Flash debug player, create a textfile called mm.cfg and fill it with the following:

      TraceOutPutFileName=flashlog.txt
      ErrorReportingEnable=1
      TraceOutputFileEnable=1
      MaxWarnings=0

      Place this file at
      /Library/Application Support/Macromedia/mm.cfg
      . Whenever you have a trace("some text"); statement in your code, it will be written to:

      /Users/[your username]/Library/Preferences/Macromedia/Flash Player/Logs/flashlog.txt

    Please leave comments with any suggestions, problems, questions, etc. Enjoy!

    Troubleshooting

    Problem: Running ASDoc produces: Execute failed: java.io.IOException: /Applications/flex_sdk_3/bin/asdoc: cannot execute

    Solution: This mostly likely means the ASDoc script Ant uses is not set to be executable. Type the following in Terminal:

    cd /Applications/flex_sdk_3/bin/
    chmod +x asdoc

    The first line changes the directory to the one ASDoc resides in. The second line makes ASDoc executable.

    Problem: Running ASDoc produces: exec returned: 255

    Solution: This mostly likely means the ASDoc script (which is just a text file) contains Window-style line endings. These will need to be converted to linux.

    Install dos2unix using MacPorts and type the following in Terminal:

    cd /Applications/flex_sdk_3/bin/
    dos2unix asdoc

    This will turn off the executable bit in the permission tables, so you will have to re-enable that using the instructions in the first solution above.

    Problem: Running ASDoc produces: Could not create toplevel.xml: /Applications/flex_sdk_3/asdoc/templates/asDocHelper: cannot execute

    Solution: This mostly likely means that a helper script used by ASDoc is not set to be executable. Type the following in Terminal:

    cd /Applications/flex_sdk_3/asdoc/templates/
    chmod +x asDocHelper

What is Flex?

Wednesday, December 17th, 2008

There was a question posted on the Flash Coders group on LinkedIn.com last night asking the simple question: “What is Flex?”

I think reading about Flex for the first time can be a little confusing and intimidating, so here are some points to keep in mind:

  • If you are coming from the Flash world, you can think of Flex as building Flash applications using a set of pre-built components (think of what appears under the Components panel in the Flash authoring tool’s Window menu).
  • Flex actually refers to a set of technologies, most notably what is known as the “Flex Framework,” a library of reusable components for rapidly creating Rich Internet Applications (RIAs) — that is applications on the web that behave like desktop computer applications. The components that make up the library are ActionScript class files (read up on Object-Oriented Programming if that is meaningless) that may be instantiated (created) using MXML or ActionScript. Interactivity between the components is generally provided by ActionScript, whether or not the application was built using MXML or not. All Flex Framework components reside under the “mx” package in the Flex API reference (which is a list of all the ActionScript classes you can use in your Flex projects, as well as those available to Flash projects).
  • MXML is an XML markup language that makes the creation and layout of visual components of the Flex Framework more intuitive. The XML-style syntax of MXML makes it easy to see what visual components are nested within others. For example, a set of Buttons inside a Panel (a panel is like a window you would find within a desktop application, except it can not be dragged around the screen) may look like:
     <mx:Panel title="A Panel Example">	
    	<mx:Button label="Button A"/>
    	<mx:Button label="Button B"/>
    	<mx:Button label="Button C"/>
    </mx:Panel>
  • Flex Builder is a commercial product by Adobe that offers time saving development tools such as a “Design” mode that streamlines the laying out of Graphical User Interfaces (GUIs). It is built upon an open source product called Eclipse, which is a software development tool that originally was for developing primarily Java-based software. In addition to Flex Builder, Adobe offers a “Flex Builder Plugin” for Eclipse, since the two products are so closely related.
  • The Flex SDK (Software Development Kit) is an open source package released by Adobe that includes the Flex Framework classes and a compiler (called mxmlc) used to turn ActionScript and MXML source code into a SWF that can then be run inside a webpage, etc. using the Adobe Flash Player plugin. Other tools are included in the Flex SDK such as a tool for creating documentation of the ActionScript class files (asDoc) and a tool for creating SWC files (called compc. SWC files are ActionScript libraries — essentially a bunch of ActionScript classes in a zipped archive, which make them portable for use in other projects).

To see how all these Technologies interact together, check out the Adobe Flash Platform diagram. If you wish to learn Flex I would suggest first having a solid understanding of ActionScript 3.0 and Object-Oriented Programming. The most confusing part to me in the beginning was understanding that everything in a Flex project is ActionScript, even when laying something out using MXML. At the end of the day, there is an ActionScript class behind each component declared in MXML. MXML is just a convenience language, and as such is not necessary to developing Flex applications.

Cairngorm versus PureMVC, the most basic example application!

Friday, December 5th, 2008

Awhile back when I was learning to use the Cairngorm framework, Nicolas Lierman had a very basic example of a Cairngorm application. At the time I was trying to slog through the Cairngorm Store example, racking my brains trying to figure out what was going on. I didn’t need such a complex example to start from, just something extremely simple that would compile, and I could build from there. Looking at Nicolas’ example application was an ‘ah ha’ moment when it all came together in my mind. Now I have been learning the PureMVC framework and would like to resurrect a slightly modified version of that Cairngorm example (Nicolas’ used WebService, this uses HTTPService) side-by-side with the same example written in PureMVC. If you are trying to learn either of these frameworks, reference the Cairngorm Explorer and/or the PureMVC Conceptual Diagram and build on these examples. I hope they will help you as much as they helped me to learn the framework’s architecture.

Below is the example application written using the Cairngorm framework. Since the PureMVC example looks and functions exactly the same I will omit it. As you can see it is very simple. Type in your name and it sends it to the server and returns a message.

This movie requires Flash Player 9

The php backend is extremely simple:

<?php
	echo "Hello " . $_REQUEST['name'] . "!";
?>

Download Source Here (You will also need to download Cairngorm and PureMVC).

After creationComplete a Flex component’s stage property is… what? null?

Friday, August 22nd, 2008

When creating a custom Flex component, it may be desirable to access the stage when initializing the component. However, as stated in the documentation, the stage property of a DisplayObject only becomes accessible (that is, does not appear as null) when the display object has been added to the display list. It would seem intuitive then that the stage property should have a value when the added or the more Flex-specific UIComponent’s creationComplete event has fired. However, the stage property only acquires a value after the display object has been added to the stage’s display list, not just any display list. For example, when the component is added to its parent’s display list the added event is triggered, but the stage property would still be null as the parent had yet to be added to the stage’s display list.

Thankfully buried somewhere in Flex’s vast API there is an event for every need, or one would hope. And with the update from Flex 2 to Flex 2.0.1 a new event was added to DisplayObject called addedToStage, which consistently provides a way to run initialization code that depends on the stage, such as references to stage.stageWidth, etc.

Consider the following component, which traces out the firing of certain initialization events:

package com.anselmbradford
{
	import mx.core.UIComponent;
	import flash.events.Event;
	import mx.events.FlexEvent;
	import mx.core.Application;
 
 
	public class Component extends UIComponent 
	{		
		public function Component() 
		{
			this.addEventListener( Event.ADDED , addedHandler );			
			this.addEventListener( Event.ADDED_TO_STAGE , addedToStageHandler );
			this.addEventListener( FlexEvent.CREATION_COMPLETE , creationCompleteHandler );			
			Application.application.addEventListener( FlexEvent.APPLICATION_COMPLETE , applicationCompleteHandler );
		}
 
		private function addedHandler( event:Event ) : void
		{
			trace( this , "addedHandler called" , stage );
		}
 
		private function addedToStageHandler( event:Event ) : void
		{
			trace( this , "addedToStageHandler called" , stage );
		}
 
		private function creationCompleteHandler( event:FlexEvent ) : void
		{
			trace( this , "creationCompleteHandler called" , stage );
		}
 
		private function applicationCompleteHandler( event:Event ) : void
		{
			trace( this , "applicationCompleteHandler called" , stage );
		}
 
	}
}

A really nice thing about Flex is that this component could either be instantiated via MXML or ActionScript syntax, since at compile time it all becomes ActionScript anyway. If the position of this component within the layout is important, MXML would be the preferred method.

Instantiating the component with MXML:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:ab="com.anselmbradford.*"
>
     <ab:Component/>
</mx:Application>

Instantiating the component with ActionScript:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
applicationComplete="init()"
>
      <mx:Script>
        <![CDATA[
 
            import com.anselmbradford.Component;
 
            private function init() : void
            {
            	this.addChild( new Component() );
            }
 
        ]]>
      </mx:Script>
</mx:Application>

Now take a look at the difference in how the same component’s events are triggering by instantiating the component in MXML versus ActionScript:

Output via MXML instantiation:

Main0.Component4 addedHandler called null
Main0.Component4 creationCompleteHandler called null
Main0.Component4 addedToStageHandler called [object Stage]
Main0.Component4 applicationCompleteHandler called [object Stage]

Output via ActionScript instantiation:

Main0.Component7 addedHandler called [object Stage]
Main0.Component7 addedToStageHandler called [object Stage]
Main0.Component7 creationCompleteHandler called [object Stage]

You’ll notice the only event with a consistently initialized stage property across these two methods of instantiating the component is, not surprisingly, the addedToStage event. The applicationComplete event does not even fire in the ActionScript instantiation example, because the instantiation occurred within the handler for the applicationComplete event of the main application MXML file, and therefore the component was constructed after that event had already fired.

The bottom line: listen for the addedToStage event if you want to be sure the stage property has a value when it is accessed.

2008 Spring <br/> Conference video player online

Wednesday, August 20th, 2008

I wrapped the great open source Flex FX Video Player in a Cairngorm web app and voila… a video player for the Spring <br/> conference videos.

Scaling a DisplayObject to fit to a container’s dimensions

Monday, June 30th, 2008

I’ve often run into the problem of proportionally scaling an image (or other DisplayObject) to the dimensions of its parent container. I always end up having to scavenge around in my code bank for the line of code to do this—which really is a simple bit of code—but I prefer to copy-and-paste it than rewrite it. SO I am posting it here so I never have to search for it again:

var scale:Number = ((container.height/container.width) > (image.height/image.width)) ? (container.width/image.width) : (container.height/image.height);
image.scaleX = scale;
image.scaleY = scale;

Download an example here

Transformational Canvas v1.0

Wednesday, May 14th, 2008

I wanted to create a Flex Canvas-based component that acted like a camera looking down on a tabletop containing objects. Any item added to the canvas would automatically be able to be dragged as a group and individually, while the whole view could be zoomed and rotated. Here is the result:

 

This movie requires Flash Player 9

Download Source Here

This component uses the Draggable Behavior classes described in this post.

By default the canvas center point is the center of the canvas, obtained by retrieving one half of the width and height of the canvas. This way the center point always remains in the center (+/- the x,y center point offsets) of the canvas even if the canvas is resized. However, the center point can be made to remain at a specific x,y coordinate by binding the x,y center point offset to negative one half the width and height of the canvas and adding x and y values of a desired amount. The following example keeps the center point at the x,y coordinates 100,100, even if the canvas is resized:

<ab:TransformationalCanvas
id="tcanvas" 
centerPointOffsetX = "{-(tcanvas.width/2)+100}"
centerPointOffsetY = "{-(tcanvas.height/2)+100}"
>

Also, note that the Transformational Canvas origin x,y (0,0) coordinate is at the center point, not at the upper-lefthand corner. That means that children placed at 0,0 will appear at the center point, not at the upper-lefthand corner.

Please post bugs, questions, etc.

Encapsulating interactive behavior in Flex applications for better code readability

Wednesday, May 7th, 2008

Consider for a moment dragging an element within an application. The steps required for this operation are as follows:

Behavior Description Event to listen for
START DRAGGING… When the mouse button is pressed down over the element. MouseEvent.MOUSE_DOWN
DRAG… While the mouse is moving and the mouse button is pressed down over the element. MouseEvent.MOUSE_MOVE
STOP DRAGGING… When the mouse button is released over the element. MouseEvent.MOUSE_UP
When the mouse is moved outside the stage (e.g. outside the application window). This is necessary because we cannot determine whether the mouse button has been released while the mouse is outside the application window. Event.MOUSE_LEAVE

Adobe Flex’s event model makes it easy to listen for interactive mouse events within an application. A simple operation like a mouse click only requires listening for a MouseEvent.CLICK event being dispatched from the element in question, like so:

element.addEventListener( MouseEvent.CLICK , _element_clickHandler );
...
protected function _element_clickHandler( event:MouseEvent ) : void
{
// handle click on element
}

While handling a mouse click is simple enough to do, more complex interactive behavior such as dragging requires listening to multiple events from both the element in question as well as the stage. Implementing this behavior can clutter your code and not be as clear as it could be, since there is not a dragging event to listen for natively in Flex (Drag and Drop aside).

An alternative is to encapsulate the dragging behavior in a separate class that acts as a proxy for the element and issues its own events that the main application listens for. For example:

var behavior:DraggableBehavior = new DraggableBehavior(element);
element.addEventListener( DraggableBehaviorEvent.DRAGGING , _element_draggingHandler );
...
protected function _element_draggingHandler( event:DraggableBehaviorEvent ) : void
{
// handle dragging of element
}

This moves all the event handling methods and listeners to a separate class file, organizing your code better. It also creates an event that more accurately reflects what operation is going on.

 

This movie requires Flash Player 9

Download Source Here