Categories
Articles

IPhone Basic Dice Roller Animation Using XCode

This is a basic IPhone example that demonstrates an animated UIImageView. The example demonstrates how to take a sequence of images and animate them.

Ready to Animate State

To make the example interesting, I decided to use the roll of one die. This does not show a rolling 3D dice. Rather it is a sequential swapping of die faces on a single plane. When you start the die roll, you can choose when to stop. When the animation is stopped, I am using a random number to select which die value. As such the last animated die face is not the die face for the roll value. I set the animating fast enough for the simulator at least to make it difficult to see which die value was last animated when the stop button is released.

I also shows setting the user interaction states for when the die is being rolled and when it is not. I include some constants for determining the view state based on when the die is rolling or not. For example in this view the app is not animating so the roll button is enabled and the stop button is disabled.

The images for the die faces are very simple.

Source Download
XCode 4 Project

I used the IOS “View-based Application” when creating a new project in XCode. All the coding is in the AnimatedDieFaceViewController UIViewController.

AnimatedDieFaceViewController.h

This sets out the interface for the view controller.

The controller needs to set the enabled and alpha properties of the roll and stop button respectively named as rollButton and stopButton. To do this they are declared as IBOutlet so they can be linked up in the XIB file.

The rollDiceImageView UIImageView is where we will swap 6 images of die faces. Those are UIImage objects stored in the animationImages NSArray.

The method rollButtonPressed, stopButtonPressed, setAnimatingState, animateImages and stopAnimatingImages are explained with the implementation code.

#import <UIKit/UIKit.h>

@interface AnimatedDieFaceViewController : UIViewController {
    UIImageView *rollDiceImageView;
    UIButton *rollButton;
    UIButton *stopButton;
    NSArray *animationImages;

}
@property (nonatomic, retain) IBOutlet UIImageView *rollDiceImageView;
@property (nonatomic, retain) IBOutlet UIButton *rollButton;
@property (nonatomic, retain) IBOutlet UIButton *stopButton;
-(IBAction) rollButtonPressed:(id) sender;
-(IBAction) stopButtonPressed:(id) sender;
-(void) setAnimatingState:(int)animatingState;
-(void) animateImages;
-(void) stopAnimatingImages;
@end

[ad name=”Google Adsense”]

AnimatedDieFaceViewController.m

On lines 9 and 11 I declared two constants,ANIMATING_YES and ANIMATING_NO to indicate the animation state. Those are values to pass to setAnimatingState where the rollButton and the stopButton enabled and alpha properties are set.

In the viewDidLoad method starting on line 84, the animatingImages NSArray is populated with images.

Animating State

Also initial properties for the rollDiceImageView UIImageView are set including

  • image for the initial image when the app starts up.
  • animationImages set to our animatingImages NSArray.
  • animationDuration set to .5 or 1/2 of a second.
  • animationRepeatCount set to 0 to keep the animation running indefinitely.

When the rollButton is pressed, the rollButtonPressed method is called on line 13 which in turn calls the animateImages method on line 18. It is in animateImages the the view state is set and the animation is started. The view state is set so the roll button is disabled and the stop button is enabled.

On line 26 the stopButtonPressed method leads us to the stopAnimatingImages method on line 31. In this method we compute a random number rollValue for the dice roll using arc4random on line 38.

Then on line 40 rollValue is used to determine which image in the animationImages NSArray to assign to the image property of rollDiceImageView UIIMageView.

Line 42 calls setAnimatingState to reset the roll to an enabled state and stop button to a disabled state.

#import "AnimatedDieFaceViewController.h"

@implementation AnimatedDieFaceViewController
@synthesize rollDiceImageView;
@synthesize rollButton;
@synthesize stopButton;

// State is animating. Used to set view.
static const int ANIMATING_YES = 1;
// State is not animating. Used to set view.
static const int ANIMATING_NO = 0;

-(IBAction) rollButtonPressed:(id) sender
{
    NSLog(@"rollButtonPressed");
    [self animateImages];
}
-(void) animateImages
{
    NSLog(@"animateImages");
    //Set view to animating state.
    [self setAnimatingState:ANIMATING_YES];
    // Start the animation
	[rollDiceImageView startAnimating];
}
-(IBAction) stopButtonPressed:(id) sender
{
    NSLog(@"RotatingDiceEx01ViewController.stopButtonPressed");
    [self stopAnimatingImages];
}
-(void) stopAnimatingImages
{
    NSLog(@"RotatingDiceEx01ViewController.stopAnimatingImages");

    // Stop the animation.
    [rollDiceImageView stopAnimating ];
    // Generate a random number from 0 to 5;
    int rollValue =  arc4random() %  6  ;
    // Assign image from the animationImages NSArray using the rollValue as index.
    rollDiceImageView.image = [animationImages objectAtIndex:rollValue];
    //Set view to not animating state.
    [self setAnimatingState:ANIMATING_NO];
}
-(void) setAnimatingState:(int)animatingState
{
    NSLog(@"RotatingDiceEx01ViewController/setAnimatingState(...) - animatingState %i:", animatingState);
    // Set view state to animating.
    if (animatingState == ANIMATING_YES)
    {
        rollButton.enabled = false;
        rollButton.alpha = 0.5f;
        stopButton.enabled = true;
        stopButton.alpha = 1.0f;
    }
    // Set view state to not animating.
    else if (animatingState == ANIMATING_NO)
    {
        rollButton.enabled = true;
        rollButton.alpha = 1.0f;
        stopButton.enabled = false;
        stopButton.alpha = 0.5f;
    }
}
- (void)dealloc
{
    [animationImages release];
    [rollDiceImageView dealloc];
    [rollButton dealloc];
    [stopButton dealloc];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    NSLog(@"RotatingDiceEx01ViewController.viewDidLoad");
    // Build an array of UIImage objects.
    animationImages = [[NSArray arrayWithObjects:
                        [UIImage imageNamed:@"die_face_01.png"],
                        [UIImage imageNamed:@"die_face_02.png"],
                        [UIImage imageNamed:@"die_face_03.png"],
                        [UIImage imageNamed:@"die_face_04.png"],
                        [UIImage imageNamed:@"die_face_05.png"],
                        [UIImage imageNamed:@"die_face_06.png"],
                        nil] retain ];
    // Set the starting image.
    rollDiceImageView.image = [UIImage imageNamed:@"die_face_01.png"];
    // Initialize the animation properties
    rollDiceImageView.animationImages = animationImages; // NSArray of UImage objects.
	rollDiceImageView.animationDuration = .5; // Default = .033333 1/30 sec
	rollDiceImageView.animationRepeatCount = 0; // 0 = continuous

    [super viewDidLoad];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.rollDiceImageView = nil;
    self.rollButton = nil;
    self.stopButton = nil;

}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end

[ad name=”Google Adsense”]

AnimatedDieFaceViewController.xib

AnimatedDieFaceViewController UIView

This is the layout of the interface.

The UIButton with the Stop caption has its enabled property unchecked and its alpha property set to 0.5;

The dimensions of the UIImageView is set to 100 by 100. Each of the die face images are 100 by 100. The UIImageView is dead center in the UIView.

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
AnimatedDieFaceViewController IBOutlets and IBActions

The IBOutlets are for the two UIButtons and the UIImageView so their properties in the controller code can be changed. You can see on lines 40, 97, 99, 100 and 101 setting rollDiceImageView UIImageView properties. In the setAnimatingState method starting on line 44 the alpha and enabled properties for the buttons are set.

The view outlet was set when I choose the IOS View-based Application to create the XCode project.

The IBActions are for the two buttons when the Touch Up Inside event is initiated. You can see the methods rollButtonPressed and stopButtonPressed linked to that event for each button.

Categories
Articles

Titanium Limit the Characters in a TextField

I wanted to create a US zipcode TextField in Titanium for a mobile app. In this case the app was going against a database with only 5 digit zip codes. So I needed to prevent the phone keyboard from allowing more than 5 digits.

The TextField class provides the way to limit the keyboard to just numbers by setting the keyboardType property to Titanium.UI.KEYBOARD_NUMBER_PAD. However it does not have a property to limit the maximum characters.

The solution is to use the TextField change event. This event is fired when the characters change in the TextField. The handler for the TextField change event provides a dynamic reference to the TextField so the properties are exposed. This way we can use the handler for other TextFields assuming they have the same requirement when a change occurs.

The value property of the TextField can be truncated of any additional characters fover a limit with a simple line of code.
[ad name=”Google Adsense”]
Here is a snippet of the code you need. The properties such as top and left you can adjust to your layout needs. Line 12 is how the TextField is limited to number entry.

The change handler is on line 17. Line 19 shows using the slice method to chop off characters. In this example it is resetting the TextField value property to its own characters starting with character 0 and taking the next five.

If you want to improve the coding, you can create a constant to hold the limit value instead of burying the bare number into the handler function.

// Textfield for 5 digit zip code
var zip_tf = Titanium.UI.createTextField({
        color:'#000',
	font:{
		fontFamily:'Helvetica Neue',
		fontSize:15
	},
	height:35,
	top:10,
	left:80,
	width:60,
	keyboardType:Titanium.UI.KEYBOARD_NUMBER_PAD,
	returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
	borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
// Handler for zip_tf change event.
zip_tf.addEventListener('change', function(e)
{
	e.source.value = e.source.value.slice(0,5);
});

[ad name=”Google Adsense”]

Categories
Articles

Titanium IPhone Client Server Echo Hello Example Using PHP

[Update 4/27/2011. I added this same example done in XCode 4 in case you want to compare the work. See XCode IPhone Client Server Echo Hello Example Using PHP

Started my self education process for mobile development. My foothold app was to have a client server communication from the phone to a web server and back. I first did one with XCode and Objective C. Then I tried the same using Titanium from Appcelerator and is the subject of this post. The learning curve with IPhone is steep but doable as there are plenty of open resources available. With Titanium, the field of learning choices is much narrower, however the learning curve bent down to level where a Javascript and JQUERY UI type of developer will feel grounded.

This first app is a real minimalist example. It simply sends text entered on the phone and returns it with the word “Hello” prefixed. It uses HTTP and the POST protocol. The server app is a simple PHP script.

Titanium is designed to develop for both the Android devices and IPhone devices. You can use the same source code.

This app runs on IPhone simulator. It also runs on the Android simulator but the UI components overlay each other and size differently from the IPhone. So I have work to do there to unravel the differences. There are ways to detect the device and make choices. Its faster to test IPhone in Titanium. Android is painfully slow.

This is the IPhone screen when the application first runs. The text input will show the keyboard when typing. The send button closes the keyboard and starts the HTTP session. There is no error handling should the connection fail or the server fail.

This is the screen after the Send button was pressed.

app.js – The Application Script UI Components
This is the application script. I created the view, input_view, on line 5 to contain the Label, TextField and Button respectively named name_lbl, name_tf and send_btn. Using a container helps simplify the position of these. I added a TextArea named response_ta to the window on line 55.

// Default background.
Titanium.UI.setBackgroundColor('#ccc');

// Application window
var app_win = Titanium.UI.createWindow();

// A view container for name_lbl and name_tf.
var input_view = Ti.UI.createView({
	top:0,
	height:40,
	width:'100%',
	backgroundColor:'#999'
});

// Label for the name_tf.
var name_lbl = Titanium.UI.createLabel({
	color:'#fff',
	text:'Name: ',
	top:5,
	left:0,
	height:30,
	textAlign:'right',
	right:'80%'
});
// Add name_lbl to input_view.
input_view.add( name_lbl );

// Name input TextField
var name_tf = Ti.UI.createTextField(
{
	width:'60%',
	backgroundColor:'#fff',
	color:'#000',
	top:5,
	right:'20%',
	height:30,
	value:'Dude Yo'
});
// Add name_tf to input_view.
input_view.add(name_tf);

// Button to send name_tf to server.
var send_btn = Ti.UI.createButton({
	title:'Send',
	width:"16%",
	height:30,
	top:5,
	right: 5
});

// Add send_btn to app_win.
input_view.add(send_btn);

// Label to show server response.
var response_ta = Titanium.UI.createTextArea({
	color:'#000',
	value:'Enter Your Name and Press Send',
	font:{fontSize:20, fontFamily:'Helvetica Neue'},
	editable:false,
	top:80
});

[ad name=”Google Adsense”]
app.js – The Application Script UI Button Listener and HTTPClient
Line 63 sets up a listener to the send_btn click event. It also creates an anonymous function to process the click event. Inside on line 66 the name_tf focus is removed to close any open keyboard on the phone.

Line 68 creates the HTTPClient object. Line 70 provides the handler for the HTTPClient onLoad event. In the onLoad event handler we set the response_ta TextArea with the HTTPClient responseText property.

Line 75 you need to modify with your own url for example http://YOUR_DOMAIN/SCRIPT_NAME. Line 78 sends the request and line 79 shows how to set up the name value pairs.

The remainder of the script is attaching the View and the TextArea objects to the Window.

// Handler for send_btn click event.
send_btn.addEventListener("click",function(){
	Ti.API.info('app.js - send_btn.addEventListener');
	// Remove focus from name_tf. Closes the keyboard for name_tf.
	name_tf.blur();
	// Create a HTTPClient.
	var xhr = Ti.Network.createHTTPClient();
	// Handler for xhr onLoad event.
	xhr.onload = function(e) {
		Ti.API.info('app.js - xhr.onload - receiving ' + xhr.responseText + ' from server');
		response_ta.value = xhr.responseText;
	};
	// Specify http protocols and url.
	xhr.open('POST', '{PUT_YOUR_URL_TO_SERVER_SCRIPT_HERE}');
	// Send data to server.
	Ti.API.info('app.js - sending ' + name_tf.value + ' to server');
	xhr.send({
		name:name_tf.value
	});
});

// Add input_view to app_win.
app_win.add( input_view );

// Add response_ta to app_win.
app_win.add(response_ta);
app_win.open();

[ad name=”Google Adsense”]
echo_hello.php – Server Script
Very simple echo script. The name identifier on line 79 of app.js is picked up in the PHP $_REQUEST object as you might expect. The value of $_REQUEST[‘name’] is appended to ‘Hello’ plus a space and returned without any data markup.

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

Basic Parsley MVC Flash Builder Actionscript Project

This is a basic model view controller example of a Parsley Actionscript project created in Flash Builder. I posted in this blog a minimalist example of using Parsley without implementing model view controller. See Parsley Hello World For A Flash Builder Actionscript Project.. In that post I explained the messaging in Parsley and will not repeat that explanation in this post other than to point them out where used in the model view controller implementation.

This model view controller example is as basic as I can make it while best trying to show the decoupling magic in Parsley. This is accomplished using the Parsley messaging and injection. I attempted to keep the view decoupled from the controller and model. The model and the controller could be decoupled from each other. How far you go with this depends on how many messages you want to design. To keep simple I did have the controller include the model and directly call model methods. This could be decoupled with a Parsley message.

This example follows a few techniques in a referenced example found in the Spicefactory Parsley Developer Manual in chapter 1 under “Other Resources”. This example is found at BloggingLemon. It was written in July 2009. There is a live demo and you can view the source code. Unfortunately the article has no explanations. It did provide me a good template for the Parsley bootstrapping. I tried to streamline that example even further and document what I know here.

You can build this with the free Flex SDK by using the code in the src folder and be sure to include a path to the Parsley and Spicelib library. I have included the Flash Builder 4 project file here you can download.

[ad name=”Google Adsense”]
Application Class – ParsleyFramework_MVC_AS.as

This is the bootstrap application class. One of the issues in Flash using the XML Parsley configuration file are classes not tied to the view. These classes need to be compiled early so that Parsley can reflect on them. In our case the ApplicationModel and ApplicationController classes fall into this category. There are three techniques to include them for Parsley and I repeated the Parsley Developer’s Manual notes in the comments on line 35 – 39. I borrowed the first technique also used in the BloggingLemon example which is considered by some a hack. Line 41 shows including these classes in an array that has no other use in this class and seems simple enough but should be clearly documented so they are not removed as orphaned code.

Lines 53 – 60 configure the Parsley log messaging useful for debugging Parsley. Here we are suppressing the Parsley messaging so you can view the trace statements I added to help follow the application model view controller and Parsely messaging.

Lines 89 and 90 of the initApp method load the Parsley xml configuration file shown later in this post.

Lines 100 and 103 of the contextEventInitializedHandler method create Parsley managed objects for the two views in this application. The input view allows you to enter and send a message. The output view is a Flash TextField that shows all the messages in reverse entry order. Actually the ApplicationModel maintains the reverse order and the view only displays the model.

The trace statements will show you the flow of the class as it bootstraps.

package
{
	import controllers.ApplicationController;
	
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	
	import models.ApplicationModel;
	
	import org.spicefactory.lib.flash.logging.Appender;
	import org.spicefactory.lib.flash.logging.FlashLogFactory;
	import org.spicefactory.lib.flash.logging.LogLevel;
	import org.spicefactory.lib.flash.logging.impl.DefaultLogFactory;
	import org.spicefactory.lib.flash.logging.impl.TraceAppender;
	import org.spicefactory.lib.logging.LogContext;
	import org.spicefactory.lib.logging.Logger;
	import org.spicefactory.parsley.core.context.Context;
	import org.spicefactory.parsley.core.events.ContextEvent;
	import org.spicefactory.parsley.flash.logging.FlashLoggingXmlSupport;
	import org.spicefactory.parsley.xml.XmlContextBuilder;
	
	import views.InputView;
	import views.OutputView;

	[SWF(frameRate="30", width="800", height="650", backgroundColor="0x666666")]	
	
	public class ParsleyFramework_MVC_AS extends Sprite
	{
		/**
		 * Hack to force compiling of classes configured in ParsleyConfiguration.xml 
		 * not used in this class so Parsley can reflect on them. 
		 * 
		 * Alternatives to this hack include either 
		 * compiling them into an SWC (with compc you can include 
		 * whole source folders into the SWC) and then include the whole SWC into your SWF 
		 * with the -include-libraries option of the mxmlc compiler.
		 * or include individual classes with the -includes option of the mxmlc compiler. 
		 * */
		protected var classImporter:Array = [ApplicationModel, ApplicationController];
		/**
		 * This app's context for Parsley.
		 * */
		protected var mainContext:Context;
		/**
		 * Application bootstrap class.
		 * */
		public function ParsleyFramework_MVC_AS()
		{
			super();
			trace("INIT: ParsleyFramework_MVC_AS()");
			var factory:FlashLogFactory = new DefaultLogFactory();
			// Spicefactory warning level for logging.
			factory.setRootLogLevel(LogLevel.WARN);
			var traceApp:Appender = new TraceAppender();
			// Suppress SpiceFactory lib tracing.
			traceApp.threshold = LogLevel.OFF;
			factory.addAppender(traceApp);
			LogContext.factory = factory;
			if (stage == null) 
			{
				addEventListener(Event.ADDED_TO_STAGE, addedToStageEventHandler);
			}
			else 
			{
				initApp();
			}
		}
		/**
		 * Handler for ADDED_TO_STAGE EVENT
		 */
		protected function addedToStageEventHandler(event:Event):void
		{
			trace("INIT: ParsleyFramework_MVC_AS.addedToStageEventHandler(...)");
			removeEventListener(Event.ADDED_TO_STAGE, addedToStageEventHandler);
			initApp();
		} 
		/**
		 * Initialize the stage and load Parsley configuration.
		 */
		protected function initApp():void
		{            
			trace("INIT: ParsleyFramework_MVC_AS.initApp()");
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			FlashLoggingXmlSupport.initialize();
			// INITIALIZE CONTEXT
			mainContext = XmlContextBuilder.build("ParsleyConfiguration.xml");
			mainContext.addEventListener(ContextEvent.INITIALIZED, contextEventInitializedHandler); 
		}
		/**
		 * Handler for Parsley ContextEvent.INITIALIZED event.
		 */
		protected function contextEventInitializedHandler(event:ContextEvent):void
		{    
			trace("INIT: ParsleyFramework_MVC_AS.contextEventInitializedHandler(...)");
			mainContext.removeEventListener(ContextEvent.INITIALIZED, contextEventInitializedHandler);
			// Add in the views.
			var inputView:InputView = mainContext.getObjectByType(InputView) as InputView;
			addChild(inputView);  
			inputView.y = 50;
			var outputView:OutputView = mainContext.getObjectByType(OutputView) as OutputView;
			addChild(outputView);  
			outputView.y = inputView.y + inputView.height + 5;
		}        
	}
}

Parsley Configuration XML File – ParsleyConfiguration.xml
For Parsley to look for the Parsley metatags and other management tasks, it needs to know which classes to search. Loading an XML configuration file is how that is done. Here you see the model, controller and two views referenced by their package identification.

<?xml version="1.0" encoding="UTF-8"?>
<objects 
    xmlns="http://www.spicefactory.org/parsley"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.spicefactory.org/parsley 
        http://www.spicefactory.org/parsley/schema/2.3/parsley-core.xsd"
    >
     <!-- Objects managed by Parsley -->
 	<object type="models.ApplicationModel" />
 	<object type="controllers.ApplicationController" />
     
	<object type="views.InputView" />
	<object type="views.OutputView"  /> 
</objects>

[ad name=”Google Adsense”]
The Input View – InputView.as
This is an input TextField and an extended SimpleButton to take any typed message and send a Parsley message.

Line 102 is where a message is dispatched for Parsley to broadcast. Lines 37 and 38 show the Parsley injection for the messaging method.

There is no reference to a controller or a model in this view. The message on line 102 is dispatched for the chosen controller to handle. That choice is made in the controller.

package views
{
	import events.SendTextMessageEvent;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flashx.textLayout.formats.TextAlign;
	import ui.simple.QuickButton;
	/**
	 * Demonstrates UI components sending messages confined to this view while
	 * using Parsley to send the SendTextMessageEvent outside for a controller to handle.
	 * */
	public class InputView extends Sprite
	{
		/**
		 * Output TextField component.
		 * */
		private var input_tf:TextField;
		/**
		 * TextFormat for input_tf.
		 * */
		private var tfFormat:TextFormat;
		/**
		 * The send button
		 * */
		private var sendButton:QuickButton;
		/**
		 * The off button
		 * */
		private var offButton:QuickButton;
		/**
		 * Parsley injected message dispatcher
		 * */
		[MessageDispatcher]
		public var dispatcher:Function;
		/**
		 * Constructor
		 * */
		public function InputView()
		{
			trace("VIEW: InputView()");
			super();
			createChildren();
		}
		/**
		 * Parsley calls automatically after context parsing.
		 */
		[Init]
		public function parsleyInit():void
		{
			trace("VIEW: InputView.parsleyInit()");
		}
		/**
		 * Build the UI for this display object.
		 */
		public function createChildren():void
		{
			trace("VIEW: InputView.createChildren()");
			// TextFormat
			tfFormat = new TextFormat();
			tfFormat.align = TextAlign.LEFT;
			tfFormat.bold = true;
			tfFormat.font = "_typewriter";
			// Input TextField.
			input_tf = new TextField();
			input_tf.border = true; 
			input_tf.multiline = false;
			input_tf.type = TextFieldType.INPUT;
			input_tf.background = true;
			input_tf.width = 600;
			input_tf.height = 20;
			input_tf.addEventListener(Event.CHANGE, input_tf_changeHandler);
			addChild(input_tf);	
			// Create QuickButton and add to display list.
			sendButton = new QuickButton("Send",60);
			sendButton.addEventListener(MouseEvent.CLICK, sendButtonClickHandler);
			addChild(sendButton);	
			input_tf.width -= sendButton.width + 10;
			sendButton.x = input_tf.x + input_tf.width + 10;
		}
		/**
		 * Handler for input_tf_changeHandler Event.CHANGE. To maintain format while changing input
		 * text.
		 * */
		private function input_tf_changeHandler(e:Event):void
		{
			//trace("VIEW: InputView.input_tf_changeHandler(...)");
			input_tf.setTextFormat(tfFormat);
		}
		/**
		 * Handler for sendButton MouseEvent.CLICK
		 * */
		private function sendButtonClickHandler(e:MouseEvent):void
		{
			trace("VIEW: InputView.sendButtonClickHandler(...)");
			// There is text to send
			if (input_tf.length > 0)
			{
				dispatcher( new SendTextMessageEvent(SendTextMessageEvent.SEND, input_tf.text) );
				input_tf.text = "";
				stage.focus = input_tf;
			}
		}
	}
}

The Output View – OutputView.as

As in the InputView there is no reference to a controller or a model. Line 68 shows using Parsley to pick up a message. Of course in a model-view-controller implementation the model should dispatch this message when the model updates.

package views
{
	import events.SendTextMessageEvent;
	import events.SentTextMessagesUpdateEvent;
	
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	
	import flashx.textLayout.formats.TextAlign;

	/**
	 * Simple output view. Demonstrates receiving Parsley managed messages and updating from model changes.
	 * */
	public class OutputView extends Sprite
	{
		/**
		 * Output TextField component.
		 * */
		private var output_tf:TextField;
		/**
		 * TextFormat for output_tf.
		 * */
		private var tfFormat:TextFormat;
		/**
		 * Constructor
		 * */
		public function OutputView()
		{
			trace("VIEW: OutputView()");
			super();
			createChildren();
		}
		/**
		 * Parsley calls automatically after context parsing.
		 */
		[Init]
		public function parsleyInit():void
		{
			trace("VIEW: OutputView.parsleyInit()");
		}
		/**
		 * Build the UI for this display object.
		 */
		public function createChildren():void
		{
			trace("VIEW: OutputView.createChildren()");
			// TextFormat
			tfFormat = new TextFormat();
			tfFormat.align = TextAlign.LEFT;
			tfFormat.bold = true;
			tfFormat.font = "_typewriter";
			// TextField.
			output_tf = new TextField();
			output_tf.border = true; 
			output_tf.multiline = true;
			output_tf.background = true;
			output_tf.width = 600;
			output_tf.height = 100;
			addChild(output_tf);
		}
		/**
		 * Parsley event handler. Listening for SentTextMessagesUpdateEvent.UPDATE type. Shows using a selector.
		 * Other Parsley managed views can do the same.
		 */
		[MessageHandler(selector="event.SentTextMessagesUpdateEvent.UPDATED")]
		public function sentTextMessagesUpdateEventHandler(event:SentTextMessagesUpdateEvent):void
		{
			trace("VIEW: OutputView.sentTextMessagesUpdateEventHandler(...) - event.type: " + event.type);
			output_tf.text = event.sentTextMessages;
			output_tf.setTextFormat(tfFormat);
		} 
	}
}

The Model – ApplicationModel.as

On line 12 of the model the one data element, sentTextMessages, holds all the text messages sent in the application. The addSentTextMessage method is where the model is updated with new text messages and where sentTextMessages is maintained. The text messages in sentTextMessages are kept in “last in” order.

Line 30 notifies the Parsley framework of changes in sentTextMessages. The wiring we applied in the Parsley framework incudes the views and the views have handlers to receive the message. In our case it is the OutputView which simply displays the sentTextMessages value as is.

package models
{
	import events.SentTextMessagesUpdateEvent;
	/**
	 * The model responsible for application data.
	 * */
	public class ApplicationModel
	{
		/**
		 * All text messages sent separated by new line \n.
		 * */
		private var sentTextMessages:String = "";
		/**
		 * Parsley injected message dispatcher
		 * */
		[MessageDispatcher]
		public var dispatcher:Function;
		/**
		 * Updates the sentTextMessages property and broadcasts SentTextMessagesUpdateEvent.
		 * @param messageText A text message sent.
		 * */
		public function addSentTextMessage(messageText:String):void
		{
			trace("MODEL: ApplicationModel.addSentTextMessage(...)");
			if (sentTextMessages.length > 0)
			{
				messageText += "\n";
			}
			sentTextMessages = messageText + sentTextMessages;
			dispatcher( new SentTextMessagesUpdateEvent(SentTextMessagesUpdateEvent.UPDATED, sentTextMessages) );
		}
	}
}

[ad name=”Google Adsense”]
The Controller– ApplicationController.as

Lines 34 and 35 uses the Parsley messaging to listen for view messages and in this case the event.SendTextMessageEvent.SEND message. Views do not need to couple to this controller. Neither does the controller need to know anything about the views.

Line 38 shows the updating of the model. However you could replace this with Parsley messaging to decouple the controller from the model. I did not in order to reduce the number of messages for the example.

package controllers
{
	import events.SendTextMessageEvent;
	
	import models.ApplicationModel;

	/**
	 * The controller responsible for application level control.
	 * */
	public class ApplicationController
	{
		/**
		 * The model injected by Parsley.
		 * */
		[Inject]
		public var model:ApplicationModel;
		/**
		 * Parsley injected message dispatcher
		 * */
		[MessageDispatcher]
		public var dispatcher:Function;
		/**
		 * Parsley calls automatically after context parsing.
		 */
		[Init]
		public function parsleyInit():void
		{
			trace("CONTROLLER: ApplicationController.parsleyInit()");
		}
		/**
		 * Parsley event handler. Listening for SendTextMessageEvent.SEND type. Shows using a selector.
		 * Other Parsley managed views can do the same.
		 */
		[MessageHandler(selector="event.SendTextMessageEvent.SEND")]
		public function sendTextMessageEventHandler(event:SendTextMessageEvent):void
		{
			trace("CONTROLLER: ApplicationController.sendTextMessageEventHandler(...) - event.type: " + event.type);
			model.addSentTextMessage(event.messageText);
		} 
	}
}

The SendTextMessageEvent– SendTextMessageEvent.as

This is a custom Actionscript event. The purpose is to carry a new text message.

package events
{
	import flash.events.Event;
	/**
	 * Event for demonstrating Parsley. View sending a new text message.
	 * */
	public class SendTextMessageEvent extends Event
	{
		/**
		 * The event send type.
		 * */
		public static const SEND:String = "event.SendTextMessageEvent.SEND";
		/**
		 * The text sent.
		 * */
		public var messageText:String;
		/**
		 * Constructor
		 * @param messageText The text sent.
		 * */
		public function SendTextMessageEvent(type:String, messageText:String, bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
			this.messageText = messageText;
			trace ("EVENT: SendTextMessageEvent(...) type: " + type);
		}
		override public function clone():Event
		{
			return new SendTextMessageEvent(type, messageText, bubbles, cancelable);
		}
	}
}

The SentTextMessagesUpdateEvent – SentTextMessagesUpdateEvent .as

Another custom Actionscript event. The model’s sentTextMessages property is carried in this event.

package events
{
	import flash.events.Event;
	/**
	 * Event for demonstrating Parsley with mvc. Model notification of sentTextMessages updated. 
	 * The event does not need to be specific to the model so references to the model in
	 * documentation is for helping in tracing the Parsley mvc being demonstrated.
	 * */
	public class SentTextMessagesUpdateEvent extends Event
	{
		/**
		 * The event updated type.
		 * */
		public static const UPDATED:String = "event.SentTextMessagesUpdateEvent.UPDATED";
		/**
		 * The model value of all the sent text messages.
		 * */
		public var sentTextMessages:String;
		/**
		 * Constructor
		 * @param sentTextMessages The model's value of the sentTextMessages.
		 * */
		public function SentTextMessagesUpdateEvent(type:String, sentTextMessages:String, bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
			this.sentTextMessages = sentTextMessages;
			trace ("EVENT: SentTextMessagesUpdateEvent(...) type: " + type);
		}
		override public function clone():Event
		{
			return new SentTextMessagesUpdateEvent(type, sentTextMessages, bubbles, cancelable);
		}
	}
}

The QuickButton- QuickButton.as
This is just an Actionscript SimpleButton to use for the demo.

package ui.simple
{
	import flash.display.DisplayObject;
	import flash.display.Shape;
	import flash.display.SimpleButton;
	import flash.events.MouseEvent;
	public class QuickButton extends SimpleButton
	{
		/**
		 * The up state background color;
		 * */
		private var upColor:uint   = 0xFFCC00;
		/**
		 * The over state background color;
		 * */
		private var overColor:uint = 0xCCFF00;
		/**
		 * The down state background color;
		 * */
		private var downColor:uint = 0x00CCFF;
		/**
		 * Width.
		 * */
		private var buttonWidth:Number;;
		/**
		 * Label.
		 * */
		private var label:String;
		/**
		 * Constructor.
		 * @param label The caption for button.
		 * @param buttonWidth Width of the button. Height is 1/3 of buttonWidth
		 * */
		public function QuickButton(label:String = "Button", buttonWidth:Number = 80)
		{
			trace("UI: QuickButton() - label: " + label);
			this.label = label;
			this.buttonWidth = buttonWidth;
			downState      = new QuickButtonDisplayShape(label, downColor, buttonWidth);
			overState      = new QuickButtonDisplayShape(label, overColor, buttonWidth);
			upState        = new QuickButtonDisplayShape(label, upColor, buttonWidth);
			hitTestState   = new QuickButtonDisplayShape(label, upColor, buttonWidth);
			useHandCursor  = true;
		}
	}
}

The QuickButton Skin – QuickButtonDisplayShape.as
How I skinned the QuickButton.

package ui.simple
{
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flashx.textLayout.formats.TextAlign;
	/**
	 * Rounded button with text label. Width and height and not margins or padding.
	 * */
	public class QuickButtonDisplayShape extends Sprite
	{
		/**
		 * Background color.
		 * */
		private var bgColor:uint;
		/**
		 * Width.
		 * */
		private var buttonWidth:Number;
		/**
		 * Height.
		 * */
		private var buttonHeight:Number;
		/**
		 * Label TextField component.
		 * */
		private var tf:TextField;
		/**
		 * Left padding for tf inside the button shape.
		 * */
		private const TF_LEFT_PADDING:Number = 6;
		/**
		 * Right padding for tf inside the button shape.
		 * */
		private const TF_RIGHT_PADDING:Number = 6;
		/**
		 * Ratio of button height to the buttonWidth.
		 * */
		private const BUTTON_HEIGHT_RATIO:Number = 1/3;
		/**
		 * Constructor.
		 * @param label The caption for button.
		 * @param bgColor Color for the button background.
		 * @param buttonWidth Width of the button. Height is 1/3 of buttonWidth
		 * */
		public function QuickButtonDisplayShape(label:String,bgColor:Number, buttonWidth:Number)
		{
			// Consume parameters
			this.bgColor = bgColor;
			this.buttonWidth = buttonWidth;
			this.buttonHeight = buttonWidth * BUTTON_HEIGHT_RATIO;
			// Draw button graphics.
			draw();
			// TextField for the button caption.
			tf = new TextField();
			var tfFormat:TextFormat = new TextFormat();
			tf.text = label;
			// Format for centering.
			tfFormat.align = TextAlign.CENTER;
			tfFormat.bold = true;
			tfFormat.font = "_sans";
			//tf.border = true; // Design guide for layout.
			tf.setTextFormat(tfFormat);
			// Position and size the caption.
			tf.x = TF_LEFT_PADDING;
			tf.width = buttonWidth - (TF_LEFT_PADDING + TF_RIGHT_PADDING);
			tf.height = tf.textHeight + 2;
			tf.y = Math.max(0, ( buttonHeight - (tf.textHeight + 4)) / 2);
			// Add caption.
			addChild(tf);
		}
		/**
		 * Draw graphics.
		 * */
		private function draw():void 
		{
			graphics.beginFill(bgColor);
			graphics.drawRoundRect(0, 0, buttonWidth, buttonHeight, 20, 20);
			graphics.endFill();
		}
	}
}

Categories
Articles

Using ExternalInterface To Send Messages to Firebug Console

There are times that you do not have the debugger version of Flash Player running when testing in a web browser so you cannot use various extensions and plugins such as Flashbug that will display Actionscript tracing to the browser window. Flashbug is a Firefox Firebug extension.

However you can use the Firebug console window directly from Actionscript using ExternalInterface. In fact you can use it for sending messages to any Javascript console you may have created or use.

ExternalInterface allows you to call Javascript function from within Actionscript. So we can apply it to calling the Firebug console.log method as well.

I have seen other examples of this code on the internet. Most have a few problems with handling errors. The most egregious is not testing if there is a Firebug console available. The problem is that it is easy to overlook removing Firebug console.log statements when you are working in Javascript. The result is errors when viewing the page in a browser like IE or any browser not having Firebug. The same applies to Actionscript calling Javascript functions. A test is needed to verify that the console.log method is available.

Second it the matter of fact inclusion of testing if ExternalInterface is available. ExternalInterface does not support all web browsers. You can check this out on the ExternalInterface documentation page.

This example contains a method you can add to a class in your Flash or Flex classes and call.

[ad name=”Google Adsense”]
Sending a Message To Firebug console.log Method

This log method demonstrates code you might want to use. I gave it two purposes. One to trace to the standard Flash log you see on line 3. The second is to trace to the Firebug console. Putting all of this into one method makes it easy enough to turn off all tracing by commenting out the body of the method. Of course you may want to integrate this into a singleton class and use it throughout your code.

Line 4 insures the browser has ExternalInterface capability available.

Lines 7 to 9 compose a anonymous Javascript function that looks like this:
function(){if (window.console) console.log('Hello World');}

Then line 11 calls the function.

		private function log(message:String):void
		{
			trace (message);
			if (ExternalInterface.available)
			{
				// Create Javascript function to call the Firebug console log method and append the message.
				message = "function(){if (window.console) console.log('" + message;
				// Close the Firebug console log method and the Javascript function.
				message +=  "');}";
				// Request running the function.
				ExternalInterface.call(message);
			}
		}

[ad name=”Google Adsense”]

To use the function, simply call it with your tracing message and you will get the message both in the regular Flash trace consoles you are using and as well in the Firebug console.

log("Hello Firebug Console From Actionscript");
Categories
Articles

Parsley Hello World For A Flash Builder Actionscript Project


I had reasonable success using the SpiceFactory Parsley framework for Flex and AIR projects. I posted a basic Flex Example in this blog. I also wanted to use it for Actionscript projects in Flash Builder. This is as minimalist example as I could make. It shows how to configure the Actionscript project for Parsley, how to wire in your view and how to access the Parsley messaging framework.

[UPDATE] I posted a second example that includes a minimalist model view controller with Parsley: Basic Parsley MVC Flash Builder Actionscript Project.

The only basic example for Flash I could find is referenced from the Spicefactory Parsley Developer Manual in chapter 1 under “Other Resources”. This example is found at BloggingLemon. It was written in July 2009. There is a live demo and you can view the source code. Unfortunately the article has no explanations. It did provide me a good template for the Parsley bootstrapping.

The BloggingLemon article attempts to show using model-view-controller with Parsley. I stripped that out so you have a real basic example that, to my search efforts, is not available on the web or at the SpiceFactory web site.

You can build this with the free Flex SDK by using the code in the src folder and be sure to include a path to the Parsley and Spicelib library. I have included the Flash Builder 4 project file here you can download.

[ad name=”Google Adsense”]
Application Class – ParsleyFramework_HelloWorld_AS.as
This is the bootstrap application class. The constructor lines 33 – 40 configure the Parsley log messaging useful for debugging Parsley. Here we are suppressing the Parsley messaging so you can view the trace statements I added to help follow the application and Parsely messaging.

Lines 69 and 70 of the initApp method load the Parsley xml configuration file shown later in this post.

Lines 79 an 81 of the contextEventInitializedHandler method create Parsley managed objects for the two views in this application. The input view is two buttons labeled on and off. The output view is a Flash TextField.

The trace statements will show you the flow of the class.

package
{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import org.spicefactory.lib.flash.logging.Appender;
	import org.spicefactory.lib.flash.logging.FlashLogFactory;
	import org.spicefactory.lib.flash.logging.LogLevel;
	import org.spicefactory.lib.flash.logging.impl.DefaultLogFactory;
	import org.spicefactory.lib.flash.logging.impl.TraceAppender;
	import org.spicefactory.lib.logging.LogContext;
	import org.spicefactory.lib.logging.Logger;
	import org.spicefactory.parsley.core.context.Context;
	import org.spicefactory.parsley.core.events.ContextEvent;
	import org.spicefactory.parsley.flash.logging.FlashLoggingXmlSupport;
	import org.spicefactory.parsley.xml.XmlContextBuilder;
	import views.InputView;
	import views.OutputView;
	[SWF(frameRate="30", width="800", height="650", backgroundColor="0x666666")]	
	public class ParsleyFramework_HelloWorld_AS extends Sprite
	{
		/**
		 * This app's context for Parsley.
		 * */
		protected var _mainContext:Context;
		/**
		 * Application bootstrap class.
		 * */
		public function ParsleyFramework_HelloWorld_AS()
		{
			super();
			var factory:FlashLogFactory = new DefaultLogFactory();
			// Spicefactory warning level for logging.
			factory.setRootLogLevel(LogLevel.WARN);
			var traceApp:Appender = new TraceAppender();
			// Suppress SpiceFactory lib tracing.
			traceApp.threshold = LogLevel.OFF;
			factory.addAppender(traceApp);
			LogContext.factory = factory;
			if (stage == null) 
			{
				addEventListener(Event.ADDED_TO_STAGE, addedToStageEventHandler);
			}
			else 
			{
				initApp();
			}
		}
		/**
		 * Handler for ADDED_TO_STAGE EVENT
		 */
		protected function addedToStageEventHandler(event:Event):void
		{
			trace("INIT: ParsleyFramework_HelloWorld01_AS.addedToStageEventHandler(...)");
			removeEventListener(Event.ADDED_TO_STAGE, addedToStageEventHandler);
			initApp();
		} 
		/**
		 * Initialize the stage and load Parsley configuration.
		 */
		protected function initApp():void
		{            
			trace("INIT: ParsleyFramework_HelloWorld01_AS.initApp()");
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			FlashLoggingXmlSupport.initialize();
			// INITIALIZE CONTEXT
			_mainContext = XmlContextBuilder.build("ParsleyConfiguration.xml");
			_mainContext.addEventListener(ContextEvent.INITIALIZED, contextEventInitializedHandler); 
		}
		/**
		 * Handler for Parsley ContextEvent.INITIALIZED event.
		 */
		protected function contextEventInitializedHandler(event:ContextEvent):void
		{    
			trace("INIT: ParsleyFramework_HelloWorld01_AS.contextEventInitializedHandler(...)");
			_mainContext.removeEventListener(ContextEvent.INITIALIZED, contextEventInitializedHandler);
			var inputView:InputView = _mainContext.getObjectByType(InputView) as InputView;
			addChild(inputView);  
			var outputView:OutputView = _mainContext.getObjectByType(OutputView) as OutputView;
			addChild(outputView);  
			outputView.y = inputView.y + inputView.height + 5;
		}        
	}
}

Parsley Configuration XML File – ParsleyConfiguration.xml
For Parsley to look for the Parsley metatags and other management tasks, it needs to know which classes to search. Loading an XML configuration file is how that is done.

Lines 11 and 12 show how to wire in the two classes we are using.

<?xml version="1.0" encoding="UTF-8"?>
<objects 
    xmlns="http://www.spicefactory.org/parsley"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.spicefactory.org/parsley 
        http://www.spicefactory.org/parsley/schema/2.3/parsley-core.xsd"
    >
    <!-- Classes managed by Parsley -->
	<object type="views.InputView"  />
	<object type="views.OutputView"  />
</objects>

The Input View – InputView.as
This input view is two buttons labeled on and off. The UI classes for the buttons is shown later in this post.

The key items to see here are the Parsley metatags. The first is line 25 where [MessageDispatcher] defines this class as a dispatcher of Parsley messages. Line 26 follows with the name of the function for message sending. Lines 65 and 73 show this dispatcher function in action.

Line 39 shows the [Init] metatag. There may be times that you need to wait until Parsley is fully configured before adding display objects or performing other class initialization tasks. The [Init] metatag defines the function that Parsley will call when it is fully configured. An example is included here for demonstration purposes but we have no need for it other than to display a trace message for you to follow in your output console.

You can appreciate the two buttons sending their messages within the InputView and then the InputView dispatching messages to Parsley for other objects to handle. InputView is decoupled from the overall application and can be easily inserted into another application without a concern about the application messaging framework.

I made the InputView class so it would also handle the messages is gives to Parsley. You see this on lines 79, 89 and 97 with the [MessageHandler] metatags. These lines indentify functions that will act as Parsley message handlers. These are the methods that follow the [MessageHandler] metatags on lines 80, 90 and 98.

The message selection works by comparing the event in the [MessageHandler] method’s argument. A further feature can target the message using a selector. You see this with lines 89 and 89 where the event’s type becomes a filter for calling the method. You will see these event types later in the OnOffEvent class which is a common custom Actionscript event class.

package views
{
	import events.OnOffEvent;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import ui.simple.QuickButton;
	/**
	 * Demonstrates UI components sending messages confined to this view while
	 * using Parsley to send messages outside. This view also
	 * handles the Parsley messages it dispatches.
	 * */
	public class InputView extends Sprite
	{
		/**
		 * The on button
		 * */
		private var onButton:QuickButton;
		/**
		 * The off button
		 * */
		private var offButton:QuickButton;
		/**
		 * Parsley injected message dispatcher
		 * */
		[MessageDispatcher]
		public var dispatcher:Function;
		/**
		 * Constructor
		 * */
		public function InputView()
		{
			trace("VIEW: InputView()");
			super();
			createChildren();
		}
		/**
		 * Parsley calls automatically after context parsing.
		 */
		[Init]
		public function parsleyInit():void
		{
			trace("VIEW: InputView.parsleyInit()");
		}
		/**
		 * Build the UI for this display object.
		 */
		public function createChildren():void
		{
			trace("VIEW: InputView.createChildren()");
			// Create two QuickButtons and add to display list.
			onButton = new QuickButton("On");
			onButton.addEventListener(MouseEvent.CLICK, onButtonClickHandler);
			addChild(onButton);	
			offButton = new QuickButton("Off");
			offButton.addEventListener(MouseEvent.CLICK, offButtonClickHandler);
			offButton.x = onButton.x + onButton.width + 10;
			addChild(offButton);
		}
		/**
		 * Handler for onButton MouseEvent.CLICK
		 * */
		private function onButtonClickHandler(e:MouseEvent):void
		{
			trace("VIEW: InputView.onButtonClickHandler(...)");
			dispatcher( new OnOffEvent(OnOffEvent.ON) );
		}
		/**
		 * Handler for offButton MouseEvent.CLICK
		 * */
		private function offButtonClickHandler(e:MouseEvent):void
		{
			trace("VIEW: InputView.offButtonClickHandler(...)");
			dispatcher( new OnOffEvent(OnOffEvent.OFF) );
		}
		/**
		 * Parsley event handler. Listening for OnOffEvent all types. 
		 * Other Parsley managed views can do the same.
		 */
		[MessageHandler]
		public function offOnEventHandler(event:OnOffEvent):void
		{
			trace("VIEW: InputView.offOnEventHandler(...) - event.type: " + event.type);
		} 
		/**
		 * Parsley event handler. Listening for OnOffEvent ON type. Shows using a selector.
		 * Other Parsley managed views can do the same.
		 */
		[MessageHandler(selector="event.OnOffEvent.OFF")]
		public function offEventHandler(event:OnOffEvent):void
		{
			trace("VIEW: InputView.offEventHandler(...)");
		} 
		/**
		 * Parsley event handler. Listening for OnOffEvent all types. Shows using a selector.
		 * Other Parsley managed views can do the same.
		 */
		[MessageHandler(selector="event.OnOffEvent.ON")]
		public function onEventHandler(event:OnOffEvent):void
		{
			trace("VIEW: InputView.onEventHandler(...)");
		} 
	}
}

[ad name=”Google Adsense”]
The Output View – OutputView.as
The OutputView class receives Parsley messages in the same way the InputView class does. In fact they are both receiving the same Parsley messages on line 64, 73 and 82. The one difference is that the view is updated.

The messaging is the InputView buttons result in Parsley messages that the OutputView receives.

You also see the [Init] metatag on line 36 to further demonstrate Parsley providing its ready message to managed objects.

package views
{
	import events.OnOffEvent;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flashx.textLayout.formats.TextAlign;
	/**
	 * Simple output view. Demonstrates receiving Parsley managed messages.
	 * */
	public class OutputView extends Sprite
	{
		/**
		 * Output TextField component.
		 * */
		private var tf:TextField;
		/**
		 * TextFormat for tf.
		 * */
		private var tfFormat:TextFormat;
		/**
		 * Constructor
		 * */
		public function OutputView()
		{
			trace("VIEW: OutputView()");
			super();
			createChildren();
		}
		/**
		 * Parsley calls automatically after context parsing.
		 */
		[Init]
		public function parsleyInit():void
		{
			trace("VIEW: OutputView.parsleyInit()");
		}
		/**
		 * Build the UI for this display object.
		 */
		public function createChildren():void
		{
			trace("VIEW: OutputView.createChildren()");
			// TextFormat
			tfFormat = new TextFormat();
			tfFormat.align = TextAlign.LEFT;
			tfFormat.bold = true;
			tfFormat.font = "_typewriter";
			// TextField.
			tf = new TextField();
			tf.border = true; 
			tf.multiline = true;
			tf.background = true;
			tf.width = 600;
			tf.height = 400;
			addChild(tf);	
		}
		/**
		 * Parsley event handler. Listening for OnOffEvent all types. 
		 * Other Parsley managed views can do the same.
		 */
		[MessageHandler]
		public function offOnEventHandler(event:OnOffEvent):void
		{
			addText("VIEW: OutputView.offOnEventHandler(...) - event.type: " + event.type);
		} 
		/**
		 * Parsley event handler. Listening for OnOffEvent ON type. Shows using a selector.
		 * Other Parsley managed views can do the same.
		 */
		[MessageHandler(selector="event.OnOffEvent.OFF")]
		public function offEventHandler(event:OnOffEvent):void
		{
			addText("VIEW: OutputView.offEventHandler(...)");
		} 
		/**
		 * Parsley event handler. Listening for OnOffEvent all types. Shows using a selector.
		 * Other Parsley managed views can do the same.
		 */
		[MessageHandler(selector="event.OnOffEvent.ON")]
		public function onEventHandler(event:OnOffEvent):void
		{
			addText("VIEW: OutputView.onEventHandler(...)");
		} 
		/**
		 * Appends to tf and adds to Flash trace output.
		 * @param message Text to append
		 * */
		private function addText(message:String):void
		{
			trace(message);
			tf.appendText(message + "\n");
			tf.setTextFormat(tfFormat);
		}
	}
}

[ad name=”Google Adsense”]
The OnOffEvent – OnOffEvent.as
This is a typical Actionscript custom event class. The clone method is optional for Parsley messaging. However you might need to use the event for both Parsley and Flash messaging so it is no bother to include it for consistency.

Lines 9 and 10 show the event types. The string descriptors are used as selectors in two of the [MessageHandler] metatag methods in both the InputView and OutputView. Since these need to be hardwired in the selector for the [MessageHandler] metatag, you must manually manage any changes to the string descriptors throughout the application. An alternative is to create two separate events.

Data can be sent with the event via Parsley in the same way you are accustomed with Actionscript custom events.

package events
{
	import flash.events.Event;
	/**
	 * Event for demonstrating Parsley. Simply reports an on or off state event.
	 * */
	public class OnOffEvent extends Event
	{
		public static const ON:String = "event.OnOffEvent.ON";
		public static const OFF:String = "event.OnOffEvent.OFF";
		public function OnOffEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
			trace ("EVENT: OnOffEvent(...) type: " + type);
		}
		override public function clone():Event
		{
			return new OnOffEvent(type, bubbles, cancelable);
		}
	}
}

The QuickButton- QuickButton.as
This is just an Actionscript SimpleButton to use for the demo.

package ui.simple
{
	import flash.display.DisplayObject;
	import flash.display.Shape;
	import flash.display.SimpleButton;
	import flash.events.MouseEvent;
	public class QuickButton extends SimpleButton
	{
		/**
		 * The up state background color;
		 * */
		private var upColor:uint   = 0xFFCC00;
		/**
		 * The over state background color;
		 * */
		private var overColor:uint = 0xCCFF00;
		/**
		 * The down state background color;
		 * */
		private var downColor:uint = 0x00CCFF;
		/**
		 * Width.
		 * */
		private var buttonWidth:Number;;
		/**
		 * Label.
		 * */
		private var label:String;
		/**
		 * Constructor.
		 * @param label The caption for button.
		 * @param buttonWidth Width of the button. Height is 1/3 of buttonWidth
		 * */
		public function QuickButton(label:String = "Button", buttonWidth:Number = 80)
		{
			trace("UI: QuickButton() - label: " + label);
			this.label = label;
			this.buttonWidth = buttonWidth;
			downState      = new QuickButtonDisplayShape(label, downColor, buttonWidth);
			overState      = new QuickButtonDisplayShape(label, overColor, buttonWidth);
			upState        = new QuickButtonDisplayShape(label, upColor, buttonWidth);
			hitTestState   = new QuickButtonDisplayShape(label, upColor, buttonWidth);
			useHandCursor  = true;
		}
	}
}

The QuickButton Skin – QuickButtonDisplayShape.as
How I skinned the QuickButton.

package ui.simple
{
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flashx.textLayout.formats.TextAlign;
	/**
	 * Rounded button with text label. Width and height and not margins or padding.
	 * */
	public class QuickButtonDisplayShape extends Sprite
	{
		/**
		 * Background color.
		 * */
		private var bgColor:uint;
		/**
		 * Width.
		 * */
		private var buttonWidth:Number;
		/**
		 * Height.
		 * */
		private var buttonHeight:Number;
		/**
		 * Label TextField component.
		 * */
		private var tf:TextField;
		/**
		 * Left padding for tf inside the button shape.
		 * */
		private const TF_LEFT_PADDING:Number = 6;
		/**
		 * Right padding for tf inside the button shape.
		 * */
		private const TF_RIGHT_PADDING:Number = 6;
		/**
		 * Ratio of button height to the buttonWidth.
		 * */
		private const BUTTON_HEIGHT_RATIO:Number = 1/3;
		/**
		 * Constructor.
		 * @param label The caption for button.
		 * @param bgColor Color for the button background.
		 * @param buttonWidth Width of the button. Height is 1/3 of buttonWidth
		 * */
		public function QuickButtonDisplayShape(label:String,bgColor:Number, buttonWidth:Number)
		{
			// Consume parameters
			this.bgColor = bgColor;
			this.buttonWidth = buttonWidth;
			this.buttonHeight = buttonWidth * BUTTON_HEIGHT_RATIO;
			// Draw button graphics.
			draw();
			// TextField for the button caption.
			tf = new TextField();
			var tfFormat:TextFormat = new TextFormat();
			tf.text = label;
			// Format for centering.
			tfFormat.align = TextAlign.CENTER;
			tfFormat.bold = true;
			tfFormat.font = "_sans";
			//tf.border = true; // Design guide for layout.
			tf.setTextFormat(tfFormat);
			// Position and size the caption.
			tf.x = TF_LEFT_PADDING;
			tf.width = buttonWidth - (TF_LEFT_PADDING + TF_RIGHT_PADDING);
			tf.height = tf.textHeight + 2;
			tf.y = Math.max(0, ( buttonHeight - (tf.textHeight + 4)) / 2);
			// Add caption.
			addChild(tf);
		}
		/**
		 * Draw graphics.
		 * */
		private function draw():void 
		{
			graphics.beginFill(bgColor);
			graphics.drawRoundRect(0, 0, buttonWidth, buttonHeight, 20, 20);
			graphics.endFill();
		}
	}
}

Categories
Articles

FLVPlayback Component in a Flash Builder 4 Actionscript Project

This is an example of how to include the Flash CS5 Actionscript 3 FLVPlayback component in a Flash Builder 4 Actionscript project. I used Mark Walters’s FLVPlayback directly in Flex article to understand how to get the FLVPlaybackAS3.swc file needed and the rest was very similar to doing this in Flash CS5.

In locating the FLVPlaybackAS3.swc I was on a Mac and just used Finder to locate the files with “FLVPlaybackAS” as my search string.

You need include the FLVPlaybackAS swc in your project. Create a folder in your project and then in the project properties include the folder in the Actionscript Build Path under Library Path. I like to call this folder libs.

You need to get a skin SWF file for the FLVPlayer. The easiest method is to create a Flash CS5 document and add the FLVPlayer component. Then include your video and select the skin in the component properties. Then publish. You will see the SWF file for the skin for example SkinOverAll.swf is one possible from CS5.

Downloads

[ad name=”Google Adsense”]
Application Class – FLVPlayerEx01
You need to add your Flash video FLV file on line 19 and the FLVPlayer skin SWF file on line 21. These could be in the debug-bin folder or another project level folder. This all depends on where you plan to keep these files in relation to the published swf.

package
{
	import fl.video.FLVPlayback;
	import fl.video.VideoScaleMode;
	import flash.display.Sprite;
	[SWF (width=640, height=450, backgroundColor=0xeeeeee, frameRate=24)]
	/**
	 * Starter application class demonstration loading the FLVPlayer Component.
	 * */
	public class FLVPlayBackEx01 extends Sprite
	{
		private var flashVars:Object;
		public function FLVPlayBackEx01()
		{
			var videoPlayer:FLVPlayback = new FLVPlayback();
			videoPlayer.width = 640;
			videoPlayer.height = 450;
			addChild( videoPlayer );
			videoPlayer.play( "YOUR_FLV_FILE_NAME_HERE" );
			videoPlayer.scaleMode = VideoScaleMode.MAINTAIN_ASPECT_RATIO;
			videoPlayer.skin = "YOUR_SKIN_SWF_FILE_NAME_HERE";
			videoPlayer.skinAutoHide = true;
		}
	}
}


[ad name=”Google Adsense”]

Categories
Articles

Read Flash SWF Header in AIR with Parsley Framework

I was asked to look for open source tools to read the basic information contained in a Flash swf file. Most of the items you find are for reverse engineering swf files. In the search process I found two sources to parse the swf file header.

The first was a php script written by Carlos Falo Hervá. You need to scroll down to the end of the post to find his work. This works just fine if you want to run off a server.

The second is written in Actionscript for Flash CS5. Only the author’s handle, jared, and not the author’s name is not available at the site. The download works nice and you can run from the author’s web page. You need type or paste in a url for the swf file name. The code is all dropped in on the first frame.

This site also provided a nice link to the Adobe SWF file version 10 specifications if you care to know. Page 25 has the key information on the SWF header. This is also repeated in the SWFHeaderParser parser class presented in this post.

I took the code for the second example and created a drag and drop version Adobe Air. First I separated the code into two Actionscript classes. One for parsing and one for loading swf file bytes. These classes are named respectively SWFHeaderParser and SWFHeaderLoader. I added a value object, SWFHeader_vo, to pass around the values.

I glued those items together in an Air project using the Parsley framework. This gave me a chance to use Parsley DynamicObject for the SWFHeaderLoader class that loads the SWF file for the parser.

The result is a fully decoupled version that serves as a super example of model-view-controller using Parsley for an Air app.

Download files:
Here is the Flex project if you want to explore the code and the Air installer in case you just want the tool.

[ad name=”Google Adsense”]

SWF Parser – SWFHeaderParser.as
The parser class is first as that is what you might want to integrate into your code. Note it returns the SWFHeader_vo class. The comments are scant in this class since I did write the code and only converted it into a class, returned a value object and removed code not specific to parsing the bytes. The value object is created and populated on lines 85 – 95.

package swf
{
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	import vo.SWFHeader_vo;
	/**
	 * SWF Header parsing. Code adapted from http://simplistika.com/parsing-reading-swf-header/.
	 * */
	public class SWFHeaderParser
	{
		private var xByte : uint;
		private var xNBits : int;
		private var xOffset : int;
		public function SWFHeaderParser()
		{
		}
		/**
		 * Get a SWFHeader_vo object from a ByteArray
		 * @param swfByteArray Any byte array, but expecting a SWF binary file or header from SWF file.
		 * @return Parsed values in SWFHeader_vo object.
		 * */
		public function parseBytes(swfByteArray : ByteArray) : SWFHeader_vo
		{
			return fParse(swfByteArray);
		}
		/**
		 * Original code from http://simplistika.com/parsing-reading-swf-header/ changed to 
		 * return SWFHeader_vo object.
		 * */
		private function fParse(v : ByteArray) : SWFHeader_vo
		{
			/*
			Field		Type 	Comment
								Signature byte
			Signature	UI8		"F" indicates uncompressed
								"C" indicates compressed (SWF 6 and later only)
			Signature	UI8		Signature byte always "W"
			Signature	UI8		Signature byte always "S"
			
			Version		UI8		Single byte file version
			FileLength	UI32	Length of entire file in bytes
			FrameSize	RECT	Frame size in twips
			FrameRate	UI16	Frame delay in 8.8 fixed number of frames per second
			FrameCount	UI16	Total number of frames in file
			The header begins with a three-byte signature of either 0×46, 0×57, 0×53 ("FWS"); or 0×43, 0×57, 0×53 (“CWS”). An FWS signature indicates an uncompressed SWF file; CWS indicates that the entire file after the first 8 bytes (that is, after the FileLength field) was compressed by using the ZLIB open standard. The data format that the ZLIB library uses is described by Request for Comments (RFCs) documents 1950 to 1952. CWS file compression is permitted in SWF 6 or later only.
			
			A one-byte version number follows the signature. 
			The version number is not an ASCII character, 
			but an 8-bit number. For example, for SWF 4, the version byte is 0×04, not the 
			ASCII character “4? (0×34). The FileLength field is the total length of the 
			SWF file, including the header. If this is an uncompressed SWF file (FWS signature), 
			the FileLength field should exactly match the file size. If this is a compressed SWF file 
			(CWS signature), the FileLength field indicates the total length of the file after decompression, 
			and thus generally does not match the file size. Having the uncompressed size available can make 
			the decompression process more efficient. The FrameSize field defines the width and height 
			of the on-screen display. This field is stored as a RECT structure, meaning that its size 
			may vary according to the number of bits needed to encode the coordinates. The FrameSize 
			RECT always has Xmin and Ymin value of 0; the Xmax and Ymax members define the width and 
			height. The FrameRate is the desired playback rate in frames per second.
			
			Source: http://simplistika.com/parsing-reading-swf-header/
			
			*/
			var vFormat : String;
			var vSwfVersion : int;
			var vFileLength : int;
			var vFrameRate : int;
			var vTotalFrames : int;
			var vFrameSize : Rectangle;
			v.endian = Endian.LITTLE_ENDIAN;
			vFormat = v.readUTFBytes(3);
			vSwfVersion = v.readByte();
			vFileLength = v.readUnsignedInt();
			v.readBytes(v);
			v.length -= 8;
			if (vFormat == "CWS")
				v.uncompress();
			v.position = 0;
			vFrameSize = new Rectangle();
			vFrameSize.left = xfReadNBits(v, true) / 20;
			vFrameSize.right = xfReadNBits(v) / 20;
			vFrameSize.top = xfReadNBits(v) / 20;
			vFrameSize.bottom = xfReadNBits(v) / 20;
			vFrameRate = v.readUnsignedByte() / 256 + v.readUnsignedByte();
			vTotalFrames = v.readUnsignedShort();
			var swfHeader_vo:SWFHeader_vo = new SWFHeader_vo();
			swfHeader_vo.format = vFormat;
			swfHeader_vo.swfVersion = vSwfVersion;
			swfHeader_vo.sizeUncompressed = vFileLength;
			swfHeader_vo.width = vFrameSize.width;
			swfHeader_vo.height =vFrameSize.height;
			swfHeader_vo.frameRate = vFrameRate;
			swfHeader_vo.totalFrames = vTotalFrames;
			return swfHeader_vo;
		}
		/**
		 * Original code from http://simplistika.com/parsing-reading-swf-header/.
		 * */
		private function xfReadNBits(v : ByteArray, vStart : Boolean = false) : uint
		{
			var n : uint;
			if (vStart)
			{
				xByte = v.readUnsignedByte();
				xNBits = xByte >> 3;
				xOffset = 3;
			}
			n = xByte << (32 - xOffset) >> (32 - xNBits);
			xOffset -= xNBits;
			while (xOffset < 0)
			{
				xByte = v.readUnsignedByte();
				n |= (xOffset < -8) ? (xByte << (-xOffset - 8)) : (xByte >> (-xOffset - 8));
				xOffset += 8;
			}
			return n;
		}
	}
}

SWF Loader – SWFHeaderLoader.as
This is my class to load the SWF and it uses Parsley messaging. If you do not intend to use Parsley, you need to add your own messaging.

Most of this is standard URLLoader coding.

The SWFHeaderParser is called on line 62. On line 63, the actual bytes are not gotten from the SWFHeaderParser. So it can be a bit misleading that that is information found in the SWF header. The SWF header only contains the uncompressed file size.

package swf
{
	import events.SWFHeaderLoaderCompleteEvent;
	import events.SWFHeaderLoaderErrorEvent;
	import events.SWFHeaderLoaderProgressEvent;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import models.SWFHeaderModel;
	import vo.SWFHeader_vo;
	/**
	 * Byte loader for a SWF file.
	 * */
	public class SWFHeaderLoader 
	{
		/**
		 * Has a URLLoader
		 * */
		private var urlLoader:URLLoader;
		/**
		 * Model
		 * */
		[Inject]
		public var model:SWFHeaderModel;
		/**
		 * Receives Parsley messages.
		 * */
		[MessageDispatcher]
		public var dispatcher:Function;
		/**
		 * Load the bytes from a file.
		 * */
		public function load(url:String):void
		{
			urlLoader = new URLLoader();
			urlLoader.addEventListener(Event.COMPLETE, urlLoader_completeEventHandler);
			urlLoader.addEventListener(ProgressEvent.PROGRESS, urlLoader_progressHandler);
			urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, urlLoader_securityErrorHandler);
			urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, urlLoader_httpStatusHandler);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, urlLoader_ioErrorHandler);
			urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
			urlLoader.load( new URLRequest(url) );
		}
		/**
		 * Handler for the urlLoader ProgressEvent.PROGRESS event.
		 * */
		private function urlLoader_progressHandler(event:ProgressEvent):void 
		{
			dispatcher(new SWFHeaderLoaderProgressEvent(SWFHeaderLoaderProgressEvent.PROGRESS, event.bytesLoaded, event.bytesTotal));
		}
		/**
		 * Handler for the urlLoader Event.COMPLETE event.
		 * */
		private function urlLoader_completeEventHandler(event:Event):void
		{
			var swfHeader_vo:SWFHeader_vo = new SWFHeader_vo();
			swfHeader_vo  = new SWFHeaderParser().parseBytes(urlLoader.data);
			swfHeader_vo.sizeCompressed = urlLoader.bytesLoaded;
			dispatcher(new SWFHeaderLoaderCompleteEvent(SWFHeaderLoaderCompleteEvent.COMPLETE, swfHeader_vo));
		}
		/**
		 * Handler for the urlLoader SecurityErrorEvent.SECURITY_ERROR event.
		 * */
		private function urlLoader_securityErrorHandler(event:SecurityErrorEvent):void 
		{
			dispatcher(new SWFHeaderLoaderErrorEvent(SWFHeaderLoaderErrorEvent.SECURITY_ERROR));
		}
		/**
		 * Handler for the urlLoader HTTPStatusEvent.HTTP_STATUS event.
		 * */
		private function urlLoader_httpStatusHandler(event:HTTPStatusEvent):void 
		{
			if (event.status != 200 && event.status != 0)
			{
				dispatcher(new SWFHeaderLoaderErrorEvent(SWFHeaderLoaderErrorEvent.HTTP_ERROR));
			}
		}
		/**
		 * Handler for the urlLoader IOErrorEvent.IO_ERROR event.
		 * */
		private function urlLoader_ioErrorHandler(event:IOErrorEvent):void 
		{
			dispatcher(new SWFHeaderLoaderErrorEvent(SWFHeaderLoaderErrorEvent.IO_ERROR));
		}
	}
}

SWF Header Value Object – SWFHeader_vo.as
The value object I use in the SWFHeaderLoader and SWFHeaderParser.

package vo
{
	/**
	 * Defines the values in the SWF file header record needed for app
	 * */
	[Bindable]
	public class SWFHeader_vo
	{
		public var format:String;			//	3 characters.
											//  First character:
											//  	"F" indicates uncompressed.
											// 		"C" indicates compressed (SWF 6 and later only).
											//  Second character always "W".
											//  Third character always "S".
		public var swfVersion:Number;		//	The swf version.
		public var frameRate:Number;		//	Frame rate.
		public var totalFrames:Number;		//	Number of frames on main timeline.
		public var width:Number;			//	Stage width.
		public var height:Number;			//	Stage height.
		public var sizeUncompressed:Number;	//	File size before compression.
		public var sizeCompressed:Number;	//	Actual file size.
	}
}

[ad name=”Google Adsense”]
The remainder code listings are the wiring into a Parsley Framework and published as an Adobe Air project.

Application Class – SWFHeader.mxml

This is the application mxml file. Gotta love how Parsley helps make these application mxml files minimal.

<?xml version="1.0" encoding="utf-8"?>
<!--- 
Application container
-->
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
					   xmlns:s="library://ns.adobe.com/flex/spark" 
					   xmlns:mx="library://ns.adobe.com/flex/mx"
					   xmlns:parsley="http://www.spicefactory.org/parsley" 
					   xmlns:views="views.*"
					   height = "450"
					   backgroundAlpha="0"
					   showStatusBar="false" 					>
	<fx:Declarations>
		<!-- Place non-visual elements (e.g., services, value objects) here -->
		<parsley:ContextBuilder config="ParsleyConfiguration"  />
		<parsley:Configure/>
	</fx:Declarations>
	<views:Main  />
</s:WindowedApplication>

Parsley Configuration File – ParsleyConfiguration.mxml
My first example that uses a Parsley DynamicObject. It is the SWFHeaderLoader class. I had a lot of silent failures before I could get this to stick. The result is that Parsley manages objects made from SWFHeaderLoader so we can have Parsley messaging and insertions. Only tried it with one object however.

<?xml version="1.0" encoding="utf-8"?>
<!--- 
Parsley framework configuration file
-->
<Objects 
	xmlns:fx="http://ns.adobe.com/mxml/2009"
	xmlns="http://www.spicefactory.org/parsley"
	xmlns:spicefactory="http://www.spicefactory.org/parsley"
	xmlns:models="models.*" 
	xmlns:controllers="controllers.*" 
	xmlns:s="library://ns.adobe.com/flex/spark" 
	>
	<fx:Script>
		<![CDATA[
			// Required for DynamicObject SWFHeaderLoader.
			import swf.*; 
		]]>
	</fx:Script>
	<fx:Declarations>
		<!--
		Parsley defined objects.
		-->
		<spicefactory:DynamicObject type = "{SWFHeaderLoader}" />
		<models:ApplicationModel/>
		<models:SWFHeaderModel/>
		<controllers:ApplicationController/>
	</fx:Declarations>
</Objects>

Air Application Descriptor File – SWFHeader-app.xml
Key here is that this an Air 2.0 project indicated on line 2 and line 8.

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<application xmlns="http://ns.adobe.com/air/application/2.0">

<!-- Adobe AIR Application Descriptor File Template.

	Specifies parameters for identifying, installing, and launching AIR applications.

	xmlns - The Adobe AIR namespace: http://ns.adobe.com/air/application/2.0
			The last segment of the namespace specifies the version 
			of the AIR runtime required for this application to run.
			
	minimumPatchLevel - The minimum patch level of the AIR runtime required to run 
			the application. Optional.
-->

	<!-- The application identifier string, unique to this application. Required. -->
	<id>SwfHeader</id>

	<!-- Used as the filename for the application. Required. -->
	<filename>SWFHeaderInspector</filename>

	<!-- The name that is displayed in the AIR application installer. 
	     May have multiple values for each language. See samples or xsd schema file. Optional. -->
	<name>SWF Header Inspector</name>

	<!-- An application version designator (such as "v1", "2.5", or "Alpha 1"). Required. -->
	<version>v0.01</version>

	<!-- Description, displayed in the AIR application installer.
	     May have multiple values for each language. See samples or xsd schema file. Optional. -->
	<!-- <description></description> -->

	<!-- Copyright information. Optional -->
	<!-- <copyright></copyright> -->

	<!-- Publisher ID. Used if you're updating an application created prior to 1.5.3 -->
	<!-- <publisherID></publisherID> -->

	<!-- Settings for the application's initial window. Required. -->
	<initialWindow>
		<!-- The main SWF or HTML file of the application. Required. -->
		<!-- Note: In Flash Builder, the SWF reference is set automatically. -->
		<content>[This value will be overwritten by Flash Builder in the output app.xml]</content>
		
		<!-- The title of the main window. Optional. -->
		<!-- <title></title> -->

		<!-- The type of system chrome to use (either "standard" or "none"). Optional. Default standard. -->
		<systemChrome>none</systemChrome>

		<!-- Whether the window is transparent. Only applicable when systemChrome is none. Optional. Default false. -->
		<transparent>true</transparent>

		<!-- Whether the window is initially visible. Optional. Default false. -->
		<!-- <visible></visible> -->

		<!-- Whether the user can minimize the window. Optional. Default true. -->
		<!-- <minimizable></minimizable> -->

		<!-- Whether the user can maximize the window. Optional. Default true. -->
		<!-- <maximizable></maximizable> -->

		<!-- Whether the user can resize the window. Optional. Default true. -->
		<!-- <resizable></resizable> -->

		<!-- The window's initial width. Optional. -->
		<!-- <width></width> -->

		<!-- The window's initial height. Optional. -->
		<!-- <height></height> -->

		<!-- The window's initial x position. Optional. -->
		<!-- <x></x> -->

		<!-- The window's initial y position. Optional. -->
		<!-- <y></y> -->

		<!-- The window's minimum size, specified as a width/height pair, such as "400 200". Optional. -->
		<!-- <minSize></minSize> -->

		<!-- The window's initial maximum size, specified as a width/height pair, such as "1600 1200". Optional. -->
		<!-- <maxSize></maxSize> -->
	</initialWindow>

	<!-- The subpath of the standard default installation location to use. Optional. -->
	<!-- <installFolder></installFolder> -->

	<!-- The subpath of the Programs menu to use. (Ignored on operating systems without a Programs menu.) Optional. -->
	<!-- <programMenuFolder></programMenuFolder> -->

	<!-- The icon the system uses for the application. For at least one resolution,
		 specify the path to a PNG file included in the AIR package. Optional. -->
	<!-- <icon>
		<image16x16></image16x16>
		<image32x32></image32x32>
		<image48x48></image48x48>
		<image128x128></image128x128>
	</icon> -->

	<!-- Whether the application handles the update when a user double-clicks an update version
	of the AIR file (true), or the default AIR application installer handles the update (false).
	Optional. Default false. -->
	<!-- <customUpdateUI></customUpdateUI> -->
	
	<!-- Whether the application can be launched when the user clicks a link in a web browser.
	Optional. Default false. -->
	<!-- <allowBrowserInvocation></allowBrowserInvocation> -->

	<!-- Listing of file types for which the application can register. Optional. -->
	<!-- <fileTypes> -->

		<!-- Defines one file type. Optional. -->
		<!-- <fileType> -->

			<!-- The name that the system displays for the registered file type. Required. -->
			<!-- <name></name> -->

			<!-- The extension to register. Required. -->
			<!-- <extension></extension> -->
			
			<!-- The description of the file type. Optional. -->
			<!-- <description></description> -->
			
			<!-- The MIME content type. -->
			<!-- <contentType></contentType> -->
			
			<!-- The icon to display for the file type. Optional. -->
			<!-- <icon>
				<image16x16></image16x16>
				<image32x32></image32x32>
				<image48x48></image48x48>
				<image128x128></image128x128>
			</icon> -->
			
		<!-- </fileType> -->
	<!-- </fileTypes> -->

</xml>

Main.mxml
The layout is a header and a body. The header is set up to be the move area for the window. he header is the top_hg HGroup on line 60. The body is the SWFHeaderBasic component on line 62. Here you could swap another body view easily.

<?xml version="1.0" encoding="utf-8"?>
<!--- 
Main view
-->
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009" 
		 xmlns:s="library://ns.adobe.com/flex/spark" 
		 xmlns:mx="library://ns.adobe.com/flex/mx" 
		 xmlns:sf="http://www.spicefactory.org/parsley"
		 
		 width="100%" height="100%"
		 xmlns:views="views.*" 
		 xmlns:ui="ui.*"
		 >
	<fx:Script>
		<![CDATA[
			import ui.ApplicationCloseButtonSkin;
			/**
			 * Called once Parsley framework has reflected.
			 * */
			[Init]
			public function parsleyInit():void
			{
				top_hg.addEventListener(MouseEvent.MOUSE_DOWN, top_hg_onMouseDown);
			}
			/**
			 * Handler for top_hg MouseEvent.MOUSE_DOWN. Handles OS window move.
			 * */
			private function top_hg_onMouseDown( evt:MouseEvent):void 
			{ 
				stage.nativeWindow.startMove(); 
			}
		]]>
	</fx:Script>
	<fx:Declarations>
		<sf:Configure/>
	</fx:Declarations>
	<fx:Style>
		#appName_lbl {
			font-weight:bold;
			color: #291F65;
			font-size:18px;
		}
		#version_lbl {
			font-weight:bold;
			color: #291F65;
			font-size:10px;
		}
	</fx:Style>
	<s:VGroup width="100%" height="100%">
	<s:BorderContainer width="100%" height="100%"
					   cornerRadius="20" borderWeight="3" 
					   borderColor="0x000000" dropShadowVisible="true"
					   backgroundColor="#858282">
		<s:VGroup  verticalAlign="middle" width="100%" height="100%"
			paddingLeft="6" paddingRight="6" paddingBottom="12" 
				>
			<!--- 
			Appplication header and drag area.
			--> 			
			<s:HGroup id = "top_hg" width="100%"  verticalAlign="middle" paddingTop="12"  >
				<s:HGroup  paddingLeft="5" verticalAlign="middle" horizontalAlign="left" width="100%"  gap="30">
					<mx:Image source="@Embed(source='../assets/Adobe-swf_icon_40x40_published.png')" />
					<s:Label id = "appName_lbl" text = "SWF Header Inspection Tool"/>
				</s:HGroup>	
				<s:HGroup  paddingRight="12" verticalAlign="middle" horizontalAlign="right" width="100%"  >
					<ui:ApplicationCloseButton  
						click="NativeApplication.nativeApplication.exit()" skinClass="ui.ApplicationCloseButtonSkin"/>
					
				</s:HGroup>			
		
			</s:HGroup>
			<views:SWFHeaderBasic    width="100%" height="100%" />	
			<s:Label id = "version_lbl" text = "Version 1.00"/>
		</s:VGroup>

	</s:BorderContainer>
	</s:VGroup>	
</s:Group>

SWFHeaderBasic.mxml
Body section for the application. You can easily plug in your own view to replace this one.

<?xml version="1.0" encoding="utf-8"?>
<!--- 
Basic view.
-->
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009" 
		 xmlns:s="library://ns.adobe.com/flex/spark" 
		 xmlns:sf="http://www.spicefactory.org/parsley"
		 xmlns:mx="library://ns.adobe.com/flex/mx" 
		 >
	<fx:Script>
		<![CDATA[
			import events.LoadSwfUrlHeaderRequestEvent;
			import models.SWFHeaderModel;
			import mx.binding.utils.BindingUtils;
			import mx.binding.utils.ChangeWatcher;
			import mx.events.FlexEvent;
			/**
			 * File name extracted from url or path.
			 * */
			[Bindable]
			private var fileName:String = '';
			[Inject]
			[Bindable]
			public var model:SWFHeaderModel;

			[MessageDispatcher]
			public var dispatcher:Function;
			/**
			 * Called once Parsley framework has reflected.
			 * */
			[Init]
			public function parsleyInit():void
			{
				// Bind the model changes from bytesLoaded in order to call a method.
				ChangeWatcher.watch(model, "bytesLoaded", updateProgressBar);
				addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER, onDragEnterHandler);
				addEventListener(NativeDragEvent.NATIVE_DRAG_DROP, onDragDropHandler);
			}
			/**
			 * Handler for the load_btn Mouse.Click event.
			 * */
			protected function load_btn_clickHandler(event:MouseEvent):void
			{
				fileName = url_ti.text.substr(   url_ti.text.lastIndexOf( '/' ) + 1);
				dispatcher(new LoadSwfUrlHeaderRequestEvent (LoadSwfUrlHeaderRequestEvent.LOAD, url_ti.text));
			}
			/**
			 * Handler for the load_btn Mouse.Click event.
			 * */
			private function updateProgressBar(bytesLoaded:Number):void
			{
				//trace (className + ".updateProgressBar(...) - model.bytesLoaded: " + model.bytesLoaded);	
				//trace (className + ".updateProgressBar(...) - model.bytesTotal: " + model.bytesTotal);	
				bar.setProgress(model.bytesLoaded,model.bytesTotal);
				var pct:Number = Math.round((model.bytesLoaded/model.bytesTotal) * 100);
				bar.label= "Current Progress" + " " + pct + "%";
			}
			/**
			 * Handler for the NativeDragEvent.NATIVE_DRAG_ENTER event.
			 * */
			private function onDragEnterHandler(e:NativeDragEvent):void
			{
				//trace (className + ".onDragEnterHandler(...)");	
				if(e.clipboard.hasFormat(ClipboardFormats.FILE_LIST_FORMAT))
				{
					//Get the array of File objects
					var files:Array = e.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
					var file:File = File(files[0]);
					//Allow only one file as only supporting one in this application and soft check it is a swf file.
					if( files.length == 1 && file.url.substr(file.url.length-4).toLowerCase() == ".swf" )
					{
						//Triggers NativeDragEvent.NATIVE_DRAG_DROP event. 
						//This is when we see the drop icon.
						NativeDragManager.acceptDragDrop(this);
					}
				}
			}
			/**
			 * Handler for the NativeDragEvent.NATIVE_DRAG_DROP event.
			 * */
			private function onDragDropHandler(e:NativeDragEvent):void
			{
				//trace (className + ".onDragDropHandler(...)");	
				var files:Array = e.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
				var file:File = File(files[0]);
				//trace (className + ".onDragDropHandler(...) - file.url:" + file.url);
				url_ti.text = file.url;
				fileName = file.name;
				// Optional can initiate the load automatically.
				dispatcher(new LoadSwfUrlHeaderRequestEvent (LoadSwfUrlHeaderRequestEvent.LOAD, url_ti.text));
			}
		]]>
	</fx:Script>
	<fx:Declarations>
		<sf:Configure/>
		<mx:NumberFormatter id="numberFormatter" precision="0"  useThousandsSeparator="true" />
	</fx:Declarations>
	<!--- 
	Create NativeDrag target with BorderContainer
	--> 
	<s:BorderContainer 
				width="100%" height="100%"
					   borderAlpha="0"	
					   backgroundColor="0xffffff"
					   >
	<s:VGroup verticalAlign="top"  horizontalAlign="center" width="100%" height="100%"   
			   paddingTop="10"
			   >
		<s:HGroup >
			<s:Label  text="SWF URL:" paddingTop="6" />
			<s:VGroup >
				<s:HGroup  verticalAlign="middle">
				<s:TextInput id="url_ti" text="Enter swf http url or drag from desktop" width="294" />
				<s:Button  label="Load SWF" id="load_btn" click="load_btn_clickHandler(event)"/>	
				</s:HGroup>
				<!--- 
				Progress bar for slow loads such as the internet.
				--> 		
				<mx:ProgressBar id="bar"   labelPlacement="bottom" minimum="0" visible="true" maximum="100"
								color="0x323232" 
								label="Current Progress 0%" direction="right" 
								mode="manual" width="100%"/>
			</s:VGroup>
		</s:HGroup>
		<!--- 
		The result values
		--> 
		<mx:Form width="100%" height="100%"       >
			<mx:FormItem label="SWF File name: ">
				<s:Label color="0x000000" text="{fileName}"/>
			</mx:FormItem>
			<mx:FormItem label="Flash player version: ">
				<s:Label color="0x000000" text="{numberFormatter.format(model.swfHeader_vo.swfVersion)}"/>
			</mx:FormItem>
			<s:HGroup>
				<mx:FormItem label="Size uncompressed: ">
					<s:Label color="0x000000" text="{numberFormatter.format(model.swfHeader_vo.sizeUncompressed)}"/>
				</mx:FormItem>
				<mx:FormItem label="Compressed: ">
					<s:Label color="0x000000" text="{numberFormatter.format(model.swfHeader_vo.sizeCompressed)}"/>
				</mx:FormItem>			
			</s:HGroup>
			<mx:FormItem label="Frame rate: ">
				<s:Label color="0x000000" text="{numberFormatter.format(model.swfHeader_vo.frameRate)}"/>
			</mx:FormItem>
			<mx:FormItem label="Total frames: ">
				<s:Label color="0x000000" text="{numberFormatter.format(model.swfHeader_vo.totalFrames)}"/>
			</mx:FormItem>
			<mx:FormItem label="Width: ">
				<s:Label  color="0x000000" text="{numberFormatter.format(model.swfHeader_vo.width)}"/>
			</mx:FormItem>
			<mx:FormItem label="Height: ">
				<s:Label color="0x000000" text="{numberFormatter.format(model.swfHeader_vo.height)}"/>
			</mx:FormItem>
		</mx:Form>
	</s:VGroup>
	</s:BorderContainer>
</s:Group>

ApplicationCloseButton.as
Own version of the spark Button class.

package ui
{
	import spark.components.Button;
	/**
	 * Button to close the application
	 * */
	public class ApplicationCloseButton extends Button
	{
		public function ApplicationCloseButton()
		{
			super();
		}
	}
}

ApplicationCloseButtonSkin.mxml
Skin for the application close button class, ApplicationCloseButton. I had some trouble with the edges of the images causing a repeating state change on rollover. I solved this by making a transparent background on line 29 a few pixels larger than the bitmaps. The bitmaps then had their verticalCenter and horizontalCenter properities set to zero to keep them in the middle. See lines 34 and 36.

<?xml version="1.0" encoding="utf-8"?>
<!--- 
Skin for ui.ApplicationCloseButton
-->
<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009"
			 xmlns:s="library://ns.adobe.com/flex/spark"
			 xmlns:fb="http://ns.adobe.com/flashbuilder/2009"
			 
			 alpha.disabled="0.5">
	
	<!-- host component -->
	<fx:Metadata>
		<![CDATA[
		/* @copy spark.skins.spark.ApplicationSkin#hostComponent 	*/
		[HostComponent("ui.ApplicationCloseButton")]
		]]>
	</fx:Metadata>
	
	<!-- states -->
	<s:states>
		<s:State name="up" />
		<s:State name="over" />
		<s:State name="down" />
		<s:State name="disabled" />
	</s:states>
	<!--- 
	Hit area.
	-->	
	<s:Rect  left="0" right="0" top="0" bottom="0"  width="34" height="34">
		<s:fill>
			<s:SolidColor color="0xffffff" alpha="0" />
		</s:fill>	
	</s:Rect>
	<s:BitmapImage  verticalCenter="0"  horizontalCenter="0" source="@Embed('../assets/red_glossy_close_up_button_published.png')" 
				   includeIn="up, disabled, down "/>
	<s:BitmapImage verticalCenter="0"  horizontalCenter="0"  source="@Embed('../assets/green_glossy_close_up_button_published.png')" 
				   includeIn="over"/>
	
</s:SparkSkin>

ApplicationModel.as
I could have merged the two models, but as a practice in Parsley frameworks, I create an ApplicationModel by default.

package models
{
	/**
	 * Application model.
	 * */
	public class ApplicationModel
	{

	}
}

[ad name=”Google Adsense”]
SWFHeaderModel.as
The model containing all the bound data. Flex binding is magnificent for creating model-view-controller solutions.

package models
{
	import vo.SWFHeader_vo;
	/**
	 * Model for the SWF header information.
	 * */
	public class SWFHeaderModel
	{
		/**
		 * Swf header field values.
		 * */
		[Bindable]
		public var swfHeader_vo:SWFHeader_vo;
		/**
		 * Nest the ApplicationModel.
		 * */		
		[Inject]
		[Bindable]
		public var applicationModel:ApplicationModel;
		/**
		 * Bytes loaded.
		 * */
		[Bindable]
		public var bytesLoaded:Number;
		/**
		 * Total bytes to load.
		 * */		
		[Bindable]
		public var bytesTotal:Number;
		/**
		 * Initialize model values.
		 * */		
		public function SWFHeaderModel()
		{
			swfHeader_vo = new SWFHeader_vo();
		}
	}
}

ApplicationController.as
I could have created a controller just for the SWF header if I wanted a separate model-view-controller for SWF header decoupled from the application.

package controllers
{
	import events.LoadSwfUrlHeaderRequestEvent;
	import events.SWFHeaderLoaderCompleteEvent;
	import events.SWFHeaderLoaderErrorEvent;
	import events.SWFHeaderLoaderProgressEvent;
	import flash.net.URLRequest;
	import models.SWFHeaderModel;
	import mx.controls.Alert;
	import swf.SWFHeaderLoader;
	import vo.SWFHeader_vo;
	/**
	 * Application controller
	 * */
	public class ApplicationController
	{
		/**
		 * Toggle to indicate if an Alert error is being shown. All loading errors are 
		 * routed to one method and so if there are more than one per SWFHeaderLoader.load
		 * request, this prevents multiple Alert popups.
		 * @see swfHeaderErroMessageHandler
		 * */
		private var showingSwfLoadError:Boolean = false;
		/**
		 * The SWFHeaderLoader
		 * */
		[Inject]
		public var swfHeaderLoader:SWFHeaderLoader;
		/**
		 * The model for MVC.
		 * */
		[Inject]
		[Bindable]
		public var model:SWFHeaderModel;
		/**
		 * Information Alert dialog title.
		 * */
		private var lang_info_alert_title:String = "Attention";
		/**
		 * Message when file name does not contain a .swf extension.
		 * */
		private var lang_tool_requires_swf:String = "Tool is designed for Flash Movie \".swf\" files";
		/**
		 * Message when swf file could not be loaded for any reason.
		 * */
		private var lang_unable_to_load_swf:String = "Sorry, unable to load the file.";
		/**
		 * Handler for LoadSwfUrlHeaderRequestEvent. Validate file extension. Load swf.
		 * */
		[MessageHandler]
		public function swfUrlLoadRequestMessageHandler( message : LoadSwfUrlHeaderRequestEvent ):void
		{
			model.swfHeader_vo = new SWFHeader_vo();
			// File url does not have a .swf at end.
			if ( message.swf_url.substr(message.swf_url.length-4).toLowerCase() != ".swf"  )
			{
				Alert.show(lang_tool_requires_swf ,lang_info_alert_title);
			}
			// File url has a .swf at end.
			else
			{
				showingSwfLoadError = false;
				swfHeaderLoader.load(message.swf_url);
			}
		}
		/**
		 * Handler for SWFHeaderLoaderProgressEvent.
		 * */
		[MessageHandler]
		public function swfHeaderProgressMessageHandler( message : SWFHeaderLoaderProgressEvent ):void
		{
			model.bytesTotal = message.bytesTotal;
			model.bytesLoaded = message.bytesLoaded;
		}
		/**
		 * Handler for SWFHeaderLoaderCompleteEvent.
		 * */
		[MessageHandler]
		public function swfHeaderLoadedMessageHandler( message : SWFHeaderLoaderCompleteEvent ):void
		{
			model.swfHeader_vo = message.swfHeader_vo;
		}
		/**
		 * Handler for SWFHeaderLoaderErrorEvent.
		 * */
		[MessageHandler]
		public function swfHeaderErroMessageHandler( message : SWFHeaderLoaderErrorEvent ):void
		{
			if (!showingSwfLoadError)
			{
				showingSwfLoadError = true;
				Alert.show(lang_unable_to_load_swf,lang_info_alert_title);
			}
		}		
	}
}

LoadSwfUrlHeaderRequestEvent.as
Event handler for requests to load a swf. Note how Parsley simplifies the event code.

package events
{
	import flash.events.Event;
	/**
	 * Request the loading of a swf file.
	 * */
	public class LoadSwfUrlHeaderRequestEvent extends Event
	{
		public static const LOAD:String = "event.load";
		public var swf_url:String;
		public function LoadSwfUrlHeaderRequestEvent(type:String, swf_url:String, bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
			this.swf_url = swf_url;
		}
	}
}

SWFHeaderLoaderProgressEvent.as
For monitoring the loading particularly when over the internet.

package events
{
	import flash.events.Event;
	/**
	 * Progress of loading a swf file.
	 * */	
	public class SWFHeaderLoaderProgressEvent extends Event
	{
		public static const PROGRESS:String = "event_SWFHeaderLoaderEvent_progress";
		/**
		 * Bytes loaded.
		 * */	
		public var bytesLoaded:Number;
		/**
		 * Total bytes to load.
		 * */		
		public var bytesTotal:Number;
		public function SWFHeaderLoaderProgressEvent(type:String, bytesLoaded:Number, bytesTotal:Number, bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
			this.bytesLoaded = bytesLoaded;
			this.bytesTotal = bytesTotal;
			
		}
	}
}

SWFHeaderLoaderCompleteEvent.as
When an SWF is completely loaded. You may want to redesign to stop once the header is loaded. However I had thought it might be nice to show the SWF at one point or proceed to extract other information.

package events
{
	import flash.events.Event;
	import vo.SWFHeader_vo;
	/**
	 * Completion of loading a swf file.
	 * */
	public class SWFHeaderLoaderCompleteEvent extends Event
	{
		public static const COMPLETE:String = "event_SWFHeaderLoaderEvent_complete";
		/**
		 * Swf file header data.
		 * */	
		public var swfHeader_vo:SWFHeader_vo;
		public function SWFHeaderLoaderCompleteEvent(type:String, swfHeader_vo:SWFHeader_vo, bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
			this.swfHeader_vo = swfHeader_vo;
		}
	}
}

SWFHeaderLoaderErrorEvent.as
Errors in loading the Swf file.

package events
{
	import flash.events.Event;
	/**
	 * Errors from loading a swf file.
	 * */
	public class SWFHeaderLoaderErrorEvent extends Event
	{
		public static const SECURITY_ERROR:String = "event_SWFHeaderLoaderEvent_security";
		public static const HTTP_ERROR:String = "event_SWFHeaderLoaderEvent_HTTP";
		public static const IO_ERROR:String = "event_SWFHeaderLoaderEvent_IO";
		public function SWFHeaderLoaderErrorEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
		}
	}
}