Categories
Articles

“Anyone Can Write an App” Mobile Development Platform List


Mobile development products are springing up forming a new industry. These are called mobile frameworks, development tools and mobile kits for example. Some embrace an enterprise level and some just client side. The products are aimed at the need to leverage skills of developers to build applications for devices cheaper and quicker.

To help you keep up, I am maintaining this list as the industry unfolds and will update as I find new products. There are links to the web site and to product overview videos or demo videos.

There is no particular ranking to the list. However those vendors that have clear links to overview videos and have a good hello world or the like video are listed first. It shows enthusiasm to communicate and is a criteria for any comparisons. Other than that the list is somewhat in the order I discovered the vendor. It is important for all vendors to know that ease of use depends on the simple atomic how to videos to win minds of developers. The faster you get into the mind of a developer the more likely you win that mind.

The List

  1. WireNode is a mobile website management platform. It boasts delivery to any device with their mobile core called Anypage ©. They claim it supports: Nokia, Sony Ericsson, Siemens, LG, Motorola, Apple (iPhone), Palm (Treo), RIM (BlackBerry) and many Windows CE devices with outputs in the WAP (WLM), XHTML mobile profile, XHTML basic, cHTML and standard HTML formats. There is a mobile page editor which allows integration with PostgreSQL, Struts (for page flow), Red Hat, Apache, and Hibernate (as database framework). Current customer listing examples are not impressive and lack the polish of a JQuery Mobile UI. However this is an example of offering trends where a CMS, or at least back end, plus multiple front end delivery with same content. Web site was not clear about tablets.
  2. Cabana This is built in HTML5 and provides a drag and drop wireframe type of app development tool. This visual approach also include RESTful JSON and XML APIs, and you can bind them to your user interface. It appears Cabana handles store distribution and updates are automatic which may indicate you are really creating a web app. Also they have a Fan Page Mobilizer tool that lets you take your Facebook Fan Page and convert it to an app.
  3. Marmalde Not only promising a cross deployment solution but includes converting IOS apps to Andriod and covers Kindle Fire. Here is their line: “Marmalade is the world’s most powerful SDK for the creation of richer apps and games on iOS, Android and other platforms. Marmalade’s unique technical architecture offers maximum performance through true native code. “
  4. AMPchroma from Antenna Software. AMPchroma is the first cloud platform for managing the entire mobile lifecycle. All design, development, management, and analytics functionality are presented as a suite of software modules accessible from a user-friendly web interface.
  5. Kendo UI | Demo | Kendo UI Mobile helps developers build apps and sites for mobile devices that always look native. On iOS, Kendo UI Mobile widgets look native to iOS. On Android, Kendo UI Mobile widgets look native to Android. Automatically. Kendo UI Mobile detects the device and applies the proper styling.
  6. Appcelerator Titanium | Video Demo | A free and open source application development platform, Titanium lets you create native mobile, tablet and desktop application experiences using existing web skills like Javascript, HTML, CSS, Python, Ruby, and PHP.
  7. Red Foundry | Video Demo | Creating, developing mobile IPhone app is free as is publishing yourself for apps started withing a limited time offering. Publishing the app through Redfoundry has a monthly cost but they handle all the details. Android expected Q2 2011.
  8. RhoMobile | Video Demo | Rhodes is Ruby-based framework that enables the creation of native apps for major smartphone operating systems (iPhone, Windows Mobile, RIM, Symbian and Android). Developers can create native iPhone and iPad apps from a Windows-based PC using in HTML, Javascript and Ruby.
  9. appMobi | Video Overview | Video Demo. HTML5, CSS and JavaScript to create mobile apps using their cloud. Uses WebKit based MobiUs browser to access native phone functionality.
  10. jQ.Mobil JQuery written from the ground up for mobile, HTML5 on IOS and Andriod device. In beta as of 1/18/12.
  11. Trigger.IO/ HTML5, CSS and JavaScript to create mobile apps free while in beta. Write once, submit to PhoneGap and download all the supported platforms ready for submission. Supported platforms currently IPhone Andriod, Symbian and Palm.
  12. PhoneGap HTML5, CSS3 and JavaScript to create mobile apps and the Trigger.IO service converts to native apps while retaining deployment to web browsers. Free conversion service has Trigger.IO branding on splash screen and in the description; and free conversion serviceis limited to free apps. Monthly fee service extends to paid apps and drops the in app Trigger.IO branding.
  13. Mobile Nation | Video Overview | Video Demos. Design, build and publish mobile apps for iPhone and Android devices using their web based environment. Use a QR code, their installed app and your device camera to load to your testing phone. Looks like a corker.
  14. MoSync | Video Demo | Open source SDK using C++ and a set of powerful APIs, you can harness the full power of modern smartphone platforms while still supporting Java ME devices using a single codebase. MoSync produces real native IPhone and Android applications, packaged and ready for distribution in each platforms’ native installation format.
  15. OpenPlug | Video Demo — Actionscript interestingly
  16. QT Nokia | Video Overview
  17. Adobe CS 5.5 | Video Demo with PhoneGap
  18. Jo HTML Mobile App Framework | Video Demo | JavaScript framework for HTML5 capable browsers and devices. It was originally designed to work on mobile platforms as a GUI and light data layer on top of PhoneGap. Since its creation, Jo has also been tested successfully as a lightweight framework for mobile browsers, newer desktop browsers, and even Dashboard widgets.
  19. LiveCode | Video Demo is on Home Page
  20. Whoop
  21. Corona
  22. BuzzTouch
  23. Appshed
  24. Senica Touch This is a Javascript library that produces the native look and feel of mobile devices. You would integrate with PhoneGap for device features like Accelerometer
  25. Kony Solutions
  26. Nimble Kit
  27. Service2Media
  28. AppMakr No Coding Required. Use the templates for loading data feeds such as blogs, video and photos. Customize with PhoneGap. Look and feel all customized from menu systems. Handles push notification service. Will publish using your developer account. Has a portfolio of accounts that have used this to publish apps.
  29. Tiggr This is a cloud based development tool with a software subscription service.
  30. StackMob Offers a mobile development sandbox environment with backend api for mobile apps remote data and remote services.
  31. JQTouch A JQuery plugin for mobile web development.
  32. JQuery Mobile HTML5-based user interface system for all popular mobile device platforms and built on the JQuery platform.
  33. IUI Video and demo.
  34. XUI A super micro tiny dom library for authoring html5 mobile web applications. Targeted builds for webkit, ie mobile, and blackberry
  35. Local Mobile Geared towards businesses needing to reach customers versus towards developers such as with SMS, QR and Ecommerce. They do all the work for hosting, at a fee, the app.
  36. AppFurnance is a set of online tools that help you to create all kinds of apps without having to be a programming genius. It gives you control to design interfaces, create location-aware experiences and, if you want to take it further, add your own JavaScript and produce exactly what experience you want.
  37. Codiqa Drag and drop approach to prototype, build, and manage fully functional mobile web apps with jQuery Mobile.
  38. Tiggzi HTML5 CSS PhoneGap cloud-based mobile app builder.

[ad name=”Google Adsense”]



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”]