/**
 * User: MerlinDS
 * Date: 14.07.2014
 * Time: 19:06
 */
package com.merlinds.miracle_tool.controllers {
	import avmplus.getQualifiedClassName;

	import com.merlinds.debug.log;
	import com.merlinds.miracle_tool.events.EditorEvent;
	import com.merlinds.miracle_tool.models.ProjectModel;
	import com.merlinds.miracle_tool.models.vo.AnimationVO;
	import com.merlinds.miracle_tool.models.vo.ElementVO;
	import com.merlinds.miracle_tool.models.vo.SourceVO;

	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	import org.robotlegs.mvcs.Command;

	public class SWFSeparatorCommand extends Command {

		[Inject]
		public var projectModel:ProjectModel;

		[Inject]
		public var event:EditorEvent;

		private var _target:MovieClip;
		private var _elements:Vector.<ElementVO>;
		private var _totalElements:Vector.<String>;
		private var _outputSize:int;
		//==============================================================================
		//{region							PUBLIC METHODS
		public function SWFSeparatorCommand() {
			super();
		}

		override public function execute():void {
			log(this, "execute");
			var source:SourceVO = this.projectModel.inProgress;
			var container:DisplayObjectContainer = this.event.body;
			if(container != null){
				_totalElements = new <String>[];
				var n:int = container.numChildren;
				for(var i:int = 0; i < n; i++){
					_target = container.getChildAt(i) as MovieClip;
					//create animations value object
					var bounds:Rectangle = _target.getBounds(_target);
					var animation:AnimationVO = new AnimationVO(null, bounds);
					animation.name = getQualifiedClassName(_target);
					animation.totalFrames = _target.totalFrames;
					source.animations.push(animation);
					this.getElements();
					source.elements = source.elements.concat(_elements);
				}
				this.projectModel.outputSize = _outputSize;
				log(this, "execute", "End separation");
			}
		}

		//} endregion PUBLIC METHODS ===================================================

		//==============================================================================
		//{region						PRIVATE\PROTECTED METHODS
		private function getElements():void{
			var element:ElementVO;
			var elementName:String;
			var elementView:DisplayObject;
			var i:int, j:int, n:int, m:int;
			_elements = new <ElementVO>[];
			n = _target.totalFrames + 1;
			for(i = 1; i < n; i++){
				_target.gotoAndStop(i);
				m = _target.numChildren;
				for(j = 0; j < m; j++){
					elementView = _target.getChildAt(j);
					elementName = getQualifiedClassName(elementView);
					if(!this.hasElement(elementName)){
						element = new ElementVO(elementName, elementView);
						_elements.push(element);
						_totalElements.push(elementName);//for searching
					}
				}
			}
			//get bounds of elements
			n = _elements.length;
			for(i = 0; i < n; i++){
				element = _elements[i];
				this.getElementBounds(element);
				if(_outputSize < element.width){
					_outputSize = element.width;
				}
			}
		}

		[Inline]
		private function getElementBounds(element:ElementVO):ElementVO {
			var view:DisplayObject = element.view;
			var ratio:Number = view.width / view.transform.pixelBounds.width;
			var topLeftPoint:Point = new Point(view.transform.pixelBounds.x - view.x - this.projectModel.boundsOffset,
							view.transform.pixelBounds.y - view.y - this.projectModel.boundsOffset);
			topLeftPoint.x *= ratio;
			topLeftPoint.y *= ratio;

			var topRightPoint:Point = new Point(topLeftPoint.x + view.width + this.projectModel.boundsOffset * 2,
					topLeftPoint.y);

			var bottomRightPoint:Point = new Point(topRightPoint.x,
							topRightPoint.y + view.height + this.projectModel.boundsOffset * 2);

			var bottomLeftPoint:Point = new Point(topLeftPoint.x, bottomRightPoint.y);

			element.width = view.width + this.projectModel.boundsOffset * 2;
			element.height = view.height + this.projectModel.boundsOffset * 2;

			element.vertexes = new <Number>[
				Math.ceil(topLeftPoint.x), Math.ceil(topLeftPoint.y), Math.ceil(topRightPoint.x),Math.ceil(topRightPoint.y),
				Math.ceil(bottomRightPoint.x),Math.ceil(bottomRightPoint.y),Math.ceil(bottomLeftPoint.x),Math.ceil(bottomLeftPoint.y)];

			return element;
		}

		[Inline]
		private function hasElement(name:String):Boolean {
			var result:Boolean;
			var i:int, n:int = _totalElements.length;
			for(i = 0; i < n; i++){
				result = _totalElements[i] == name;
				if(result)break;
			}
			return result;
		}
		//} endregion PRIVATE\PROTECTED METHODS ========================================

		//==============================================================================
		//{region							EVENTS HANDLERS
		//} endregion EVENTS HANDLERS ==================================================

		//==============================================================================
		//{region							GETTERS/SETTERS
		//} endregion GETTERS/SETTERS ==================================================
	}
}

/**
 * User: MerlinDS
 * Date: 14.07.2014
 * Time: 19:06
 */
package com.merlinds.miracle_tool.controllers {
	import avmplus.getQualifiedClassName;

	import com.merlinds.debug.log;
	import com.merlinds.miracle_tool.events.EditorEvent;
	import com.merlinds.miracle_tool.models.ProjectModel;
	import com.merlinds.miracle_tool.models.vo.AnimationVO;
	import com.merlinds.miracle_tool.models.vo.ElementVO;
	import com.merlinds.miracle_tool.models.vo.SourceVO;

	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	import org.robotlegs.mvcs.Command;

	public class SWFSeparatorCommand extends Command {

		[Inject]
		public var projectModel:ProjectModel;

		[Inject]
		public var event:EditorEvent;

		private var _target:MovieClip;
		private var _elements:Vector.<ElementVO>;
		private var _totalElements:Vector.<String>;
		private var _outputSize:int;
		//==============================================================================
		//{region							PUBLIC METHODS
		public function SWFSeparatorCommand() {
			super();
		}

		override public function execute():void {
			log(this, "execute");
			var source:SourceVO = this.projectModel.inProgress;
			var container:DisplayObjectContainer = this.event.body;
			if(container != null){
				_totalElements = new <String>[];
				var n:int = container.numChildren;
				for(var i:int = 0; i < n; i++){
					_target = container.getChildAt(i) as MovieClip;
					//create animations value object
					var bounds:Rectangle = _target.getBounds(_target);
					var animation:AnimationVO = new AnimationVO(null, bounds);
					animation.name = getQualifiedClassName(_target);
					animation.totalFrames = _target.totalFrames;
					source.animations.push(animation);
					this.getElements();
					source.elements = source.elements.concat(_elements);
				}
				this.projectModel.outputSize = _outputSize;
				log(this, "execute", "End separation");
			}
		}

		//} endregion PUBLIC METHODS ===================================================

		//==============================================================================
		//{region						PRIVATE\PROTECTED METHODS
		private function getElements():void{
			var element:ElementVO;
			var elementName:String;
			var elementView:DisplayObject;
			var i:int, j:int, n:int, m:int;
			_elements = new <ElementVO>[];
			n = _target.totalFrames + 1;
			for(i = 1; i < n; i++){
				_target.gotoAndStop(i);
				m = _target.numChildren;
				for(j = 0; j < m; j++){
					elementView = _target.getChildAt(j);
					elementName = getQualifiedClassName(elementView);
					if(!this.hasElement(elementName)){
						element = new ElementVO(elementName, elementView);
						_elements.push(element);
						_totalElements.push(elementName);//for searching
					}
				}
			}
			//get bounds of elements
			n = _elements.length;
			for(i = 0; i < n; i++){
				element = _elements[i];
				this.getElementBounds(element);
				if(_outputSize < element.width){
					_outputSize = element.width;
				}
			}
		}

		[Inline]
		private function getElementBounds(element:ElementVO):ElementVO {
			//TODO create tests for this/ This is one of glitches reason
			var view:DisplayObject = element.view;
			var ratio:Number = view.width / view.transform.pixelBounds.width;
			var topLeftPoint:Point = new Point(view.transform.pixelBounds.x - view.x - this.projectModel.boundsOffset,
							view.transform.pixelBounds.y - view.y - this.projectModel.boundsOffset);
			topLeftPoint.x *= ratio;
			topLeftPoint.y *= ratio;

			var topRightPoint:Point = new Point(topLeftPoint.x + view.width + this.projectModel.boundsOffset * 2,
					topLeftPoint.y);

			var bottomRightPoint:Point = new Point(topRightPoint.x,
							topRightPoint.y + view.height + this.projectModel.boundsOffset * 2);

			var bottomLeftPoint:Point = new Point(topLeftPoint.x, bottomRightPoint.y);

			element.width = view.width + this.projectModel.boundsOffset * 2;
			element.height = view.height + this.projectModel.boundsOffset * 2;

			element.vertexes = new <Number>[
				Math.ceil(topLeftPoint.x), Math.ceil(topLeftPoint.y), Math.ceil(topRightPoint.x),Math.ceil(topRightPoint.y),
				Math.ceil(bottomRightPoint.x),Math.ceil(bottomRightPoint.y),Math.ceil(bottomLeftPoint.x),Math.ceil(bottomLeftPoint.y)];

			return element;
		}

		[Inline]
		private function hasElement(name:String):Boolean {
			var result:Boolean;
			var i:int, n:int = _totalElements.length;
			for(i = 0; i < n; i++){
				result = _totalElements[i] == name;
				if(result)break;
			}
			return result;
		}
		//} endregion PRIVATE\PROTECTED METHODS ========================================

		//==============================================================================
		//{region							EVENTS HANDLERS
		//} endregion EVENTS HANDLERS ==================================================

		//==============================================================================
		//{region							GETTERS/SETTERS
		//} endregion GETTERS/SETTERS ==================================================
	}
}

Update version

Update version


////////////////////////////////////////////////////////////////////////////////
//
//  Licensed to the Apache Software Foundation (ASF) under one or more
//  contributor license agreements.  See the NOTICE file distributed with
//  this work for additional information regarding copyright ownership.
//  The ASF licenses this file to You under the Apache License, Version 2.0
//  (the "License"); you may not use this file except in compliance with
//  the License.  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

package org.apache.flex.collections
{

import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;

import mx.core.mx_internal;
import mx.collections.ICollectionView;
import mx.collections.ListCollectionView;

use namespace mx_internal;

[DefaultProperty("source")]

/**
 *  The VectorCollection class is a wrapper class that exposes a Vector as a collection
 *  that can be accessed and manipulated using the methods and properties of the
 *  ICollectionView or IList interfaces. Operations on a ArrayCollection instance modify
 *  the data source; for example, if you use the removeItemAt() method on
 *  VectorCollection, you remove the item from the underlying Vector.
 */
public class VectorCollection extends ListCollectionView implements ICollectionView
{

    //--------------------------------------------------------------------------
    //
    //  Constructor
    //
    //--------------------------------------------------------------------------

    /**
     *  Constructor.
     *
     *
Creates a new VectorCollection using the specified source vector.
     *  If no Vector is specified an empty vector of type<*> will be used.
     *

	 *
	 *
Due to the way the compiler (not the runtime) checks Vectors, we need to
	 *  leave the source as an <*> until a compiler change can be implemented.
	 *

     */
    public function VectorCollection(source:* = null)
    {
        super();

        this.source = source;
    }

    //--------------------------------------------------------------------------
    //
    //  Properties
    //
    //--------------------------------------------------------------------------

    //----------------------------------
    //  source
    //----------------------------------

    [Inspectable(category="General", arrayType="Object")]
    [Bindable("listChanged")] //superclass will fire this

    /**
     *  The source of data in the VectorCollection.
     *  The VectorCollection object does not represent any changes that you make
     *  directly to the source Vector. Always use
     *  the ICollectionView or IList methods to modify the collection.
     */
    public function get source():*
    {
        if (list && (list is VectorList))
        {
            return VectorList(list).source;
        }

        return null;
    }

    /**
     *  @private
     */
    public function set source(s:*):void
    {
		//Provides a default VectorList
		list = new VectorList( s );
    }
}

}

////////////////////////////////////////////////////////////////////////////////
//
//  Licensed to the Apache Software Foundation (ASF) under one or more
//  contributor license agreements.  See the NOTICE file distributed with
//  this work for additional information regarding copyright ownership.
//  The ASF licenses this file to You under the Apache License, Version 2.0
//  (the "License"); you may not use this file except in compliance with
//  the License.  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

package org.apache.flex.collections
{

import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;

import mx.core.mx_internal;
import mx.collections.ICollectionView;
import mx.collections.ListCollectionView;

use namespace mx_internal;

[DefaultProperty("source")]

/**
 *  The VectorCollection class is a wrapper class that exposes a Vector as a collection
 *  that can be accessed and manipulated using the methods and properties of the
 *  ICollectionView or IList interfaces. Operations on a VectorCollection instance modify
 *  the data source; for example, if you use the removeItemAt() method on
 *  VectorCollection, you remove the item from the underlying Vector.
 */
public class VectorCollection extends ListCollectionView implements ICollectionView
{

    //--------------------------------------------------------------------------
    //
    //  Constructor
    //
    //--------------------------------------------------------------------------

    /**
     *  Constructor.
     *
     *
Creates a new VectorCollection using the specified source vector.
     *  If no Vector is specified an empty vector of type<*> will be used.
     *

	 *
	 *
Due to the way the compiler (not the runtime) checks Vectors, we need to
	 *  leave the source as an <*> until a compiler change can be implemented.
	 *

     */
    public function VectorCollection(source:* = null)
    {
        super();

        this.source = source;
    }

    //--------------------------------------------------------------------------
    //
    //  Properties
    //
    //--------------------------------------------------------------------------

    //----------------------------------
    //  source
    //----------------------------------

    [Inspectable(category="General", arrayType="Object")]
    [Bindable("listChanged")] //superclass will fire this

    /**
     *  The source of data in the VectorCollection.
     *  The VectorCollection object does not represent any changes that you make
     *  directly to the source Vector. Always use
     *  the ICollectionView or IList methods to modify the collection.
     */
    public function get source():*
    {
        if (list && (list is VectorList))
        {
            return VectorList(list).source;
        }

        return null;
    }

    /**
     *  @private
     */
    public function set source(s:*):void
    {
		//Provides a default VectorList
		list = new VectorList( s );
    }
}

}

Fix typo

Fix typo


package
{
	import com.adobe.audio.format.WAVWriter;
	import flash.events.TimerEvent;
	import flash.events.Event;
	import flash.events.ErrorEvent;
	import flash.events.SampleDataEvent;
	import flash.external.ExternalInterface;
	import flash.media.Microphone;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.system.Capabilities;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;
	import flash.utils.Timer;
	import flash.system.Security;
	import flash.system.SecurityPanel;
	import flash.events.StatusEvent;
    import flash.utils.getQualifiedClassName;

	import mx.collections.ArrayCollection;

	import ru.inspirit.net.MultipartURLLoader;

	public class Recorder
	{
		public function Recorder(logger)
		{
			this.logger = logger;
		}

		private var logger;
		public function addExternalInterfaceCallbacks():void {
			ExternalInterface.addCallback("record", 		this.record);
			ExternalInterface.addCallback("_stop",  		this.stop);
			ExternalInterface.addCallback("_play",          this.play);
			ExternalInterface.addCallback("upload",         this.upload);
			ExternalInterface.addCallback("audioData",      this.audioData);
			ExternalInterface.addCallback("showFlash",      this.showFlash);
			ExternalInterface.addCallback("recordingDuration",     this.recordingDuration);
			triggerEvent("initialized", {});
			logger.log("Recorder initialized");
		}

		protected var isRecording:Boolean = false;
		protected var isPlaying:Boolean = false;
		protected var microphoneWasMuted:Boolean;
		protected var playingProgressTimer:Timer;
		protected var microphone:Microphone;
		protected var buffer:ByteArray;
		protected var sound:Sound;
		protected var channel:SoundChannel;
		protected var recordingStartTime = 0;
		protected static var sampleRate = 44.1;

		protected function record():void
		{
			if(!microphone){
				setupMicrophone();
			}

			microphoneWasMuted = microphone.muted;
			if(microphoneWasMuted){
				logger.log('showFlashRequired');
				triggerEvent('showFlash','');
			}else{
				notifyRecordingStarted();
			}

			buffer = new ByteArray();
			microphone.addEventListener(SampleDataEvent.SAMPLE_DATA, recordSampleDataHandler);
		}

		protected function recordStop():int
		{
			logger.log('stopRecording');
			isRecording = false;
			triggerEvent('recordingStop', {duration: recordingDuration()});
			microphone.removeEventListener(SampleDataEvent.SAMPLE_DATA, recordSampleDataHandler);
			return recordingDuration();
		}

		protected function play():void
		{
			logger.log('startPlaying');
			isPlaying = true;
			triggerEvent('playingStart', {});
			buffer.position = 0;
			sound = new Sound();
			sound.addEventListener(SampleDataEvent.SAMPLE_DATA, playSampleDataHandler);

			channel = sound.play();
			channel.addEventListener(Event.SOUND_COMPLETE, function(){
				playStop();
			});

			if(playingProgressTimer){
				playingProgressTimer.reset();
			}
			playingProgressTimer = new Timer(250);
			playingProgressTimer.addEventListener(TimerEvent.TIMER, function playingProgressTimerHandler(event:TimerEvent){
				triggerEvent('playingProgress', int(channel.position));
			});
			playingProgressTimer.start();
		}

		protected function stop():int
		{
			playStop();
			return recordStop();
		}

		protected function playStop():void
		{
			logger.log('stopPlaying');
			if(channel){
				channel.stop();
				playingProgressTimer.reset();

				triggerEvent('playingStop', {});
				isPlaying = false;
			}
		}

		/* Networking functions */

		protected function upload(uri:String, audioParam:String, parameters): void
		{
			logger.log("upload");
			buffer.position = 0;
			var wav:ByteArray = prepareWav();
			var ml:MultipartURLLoader = new MultipartURLLoader();
			ml.addEventListener(Event.COMPLETE, onReady);
			function onReady(e:Event):void
			{
				triggerEvent('uploadSuccess', externalInterfaceEncode(e.target.loader.data));
				logger.log('uploading done');
			}

			if(getQualifiedClassName(parameters.constructor) == "Array"){
				for(var i=0; i<parameters.length; i++){
					ml.addVariable(parameters[i][0], parameters[i][1]);
				}
			}else{
				for(var k in parameters){
					ml.addVariable(k, parameters[k]);
				}
			}

			ml.addFile(wav, 'audio.wav', audioParam);
			ml.load(uri, false);

		}

		private function externalInterfaceEncode(data:String){
			return data.split("%").join("%25").split("\\").join("%5c").split("\"").join("%22").split("&").join("%26");
		}

		protected function audioData():String
		{
			var ret:String="";
			buffer.position = 0;
			while (buffer.bytesAvailable > 0)
			{
				ret += buffer.readFloat().toString() + ";";
			}
			return ret;
		}

		protected function showFlash():void
		{
			Security.showSettings(SecurityPanel.PRIVACY);
			triggerEvent('showFlash','');
		}

		/* Recording Helper */
		protected function setupMicrophone():void
		{
			logger.log('setupMicrophone');
			microphone = Microphone.getMicrophone();
			microphone.codec = "Nellymoser";
			microphone.setSilenceLevel(0);
			microphone.rate = sampleRate;
			microphone.gain = 50;
			microphone.addEventListener(StatusEvent.STATUS, function statusHandler(e:Event) {
				logger.log('Microphone Status Change');
				if(microphone.muted){
					triggerEvent('recordingCancel','');
				}else{
					if(!isRecording){
						notifyRecordingStarted();
					}
				}
			});

			logger.log('setupMicrophone done: ' + microphone.name + ' ' + microphone.muted);
		}

		protected function notifyRecordingStarted():void
		{
			if(microphoneWasMuted){
				microphoneWasMuted = false;
				triggerEvent('hideFlash','');
			}
			recordingStartTime = getTimer();
			triggerEvent('recordingStart', {});
			logger.log('startRecording');
			isRecording = true;
		}

		/* Sample related */

		protected function prepareWav():ByteArray
		{
			var wavData:ByteArray = new ByteArray();
			var wavWriter:WAVWriter = new WAVWriter();
			buffer.position = 0;
			wavWriter.numOfChannels = 1; // set the inital properties of the Wave Writer
			wavWriter.sampleBitRate = 16;
			wavWriter.samplingRate = sampleRate * 1000;
			wavWriter.processSamples(wavData, buffer, sampleRate * 1000, 1);
			return wavData;
		}

		protected function recordingDuration():int
		{
			var latency = 650;
			var duration = int(getTimer() - recordingStartTime - latency);
			return Math.max(duration, 0);
		}

		protected function recordSampleDataHandler(event:SampleDataEvent):void
		{
			while(event.data.bytesAvailable)
			{
				var sample:Number = event.data.readFloat();

				buffer.writeFloat(sample);
				if(buffer.length % 40000 == 0){
					triggerEvent('recordingProgress', recordingDuration(), 	microphone.activityLevel);
				}
			}
		}

		protected function playSampleDataHandler(event:SampleDataEvent):void
		{
			for (var i:int = 0; i < 8192 && buffer.bytesAvailable; i++)
			{
				var sample:Number = buffer.readFloat();
				event.data.writeFloat(sample);
				event.data.writeFloat(sample);
			}
		}

		/* ExternalInterface Communication */

		protected function triggerEvent(eventName:String, arg0, arg1 = null):void
		{
			ExternalInterface.call("Recorder.triggerEvent", eventName, arg0, arg1);
		}
	}
}

package
{
	import com.adobe.audio.format.WAVWriter;
	import flash.events.TimerEvent;
	import flash.events.Event;
	import flash.events.ErrorEvent;
	import flash.events.SampleDataEvent;
	import flash.external.ExternalInterface;
	import flash.media.Microphone;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.system.Capabilities;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;
	import flash.utils.Timer;
	import flash.system.Security;
	import flash.system.SecurityPanel;
	import flash.events.StatusEvent;
    import flash.utils.getQualifiedClassName;

	import mx.collections.ArrayCollection;

	import ru.inspirit.net.MultipartURLLoader;

	public class Recorder
	{
		public function Recorder(logger)
		{
			this.logger = logger;
		}

		private var logger;
		public function addExternalInterfaceCallbacks():void {
			ExternalInterface.addCallback("record", 		this.record);
			ExternalInterface.addCallback("_stop",  		this.stop);
			ExternalInterface.addCallback("_play",          this.play);
			ExternalInterface.addCallback("upload",         this.upload);
			ExternalInterface.addCallback("audioData",      this.audioData);
			ExternalInterface.addCallback("showFlash",      this.showFlash);
			ExternalInterface.addCallback("recordingDuration",     this.recordingDuration);
			triggerEvent("initialized", {});
			logger.log("Recorder initialized");
		}

		protected var isRecording:Boolean = false;
		protected var isPlaying:Boolean = false;
		protected var microphoneWasMuted:Boolean;
		protected var playingProgressTimer:Timer;
		protected var microphone:Microphone;
		protected var buffer:ByteArray;
		protected var sound:Sound;
		protected var channel:SoundChannel;
		protected var recordingStartTime = 0;
		protected static var sampleRate = 44.1;

		protected function record():void
		{
			if(!microphone){
				setupMicrophone();
			}

			microphoneWasMuted = microphone.muted;
			if(microphoneWasMuted){
				logger.log('showFlashRequired');
				triggerEvent('showFlash','');
			}else{
				notifyRecordingStarted();
			}

			buffer = new ByteArray();
			microphone.addEventListener(SampleDataEvent.SAMPLE_DATA, recordSampleDataHandler);
		}

		protected function recordStop():int
		{
			logger.log('stopRecording');
			isRecording = false;
			triggerEvent('recordingStop', {duration: recordingDuration()});
			microphone.removeEventListener(SampleDataEvent.SAMPLE_DATA, recordSampleDataHandler);
			return recordingDuration();
		}

		protected function play():void
		{
			logger.log('startPlaying');
			isPlaying = true;
			triggerEvent('playingStart', {});
			buffer.position = 0;
			sound = new Sound();
			sound.addEventListener(SampleDataEvent.SAMPLE_DATA, playSampleDataHandler);

			channel = sound.play();
			channel.addEventListener(Event.SOUND_COMPLETE, function(){
				playStop();
			});

			if(playingProgressTimer){
				playingProgressTimer.reset();
			}
			playingProgressTimer = new Timer(250);
			playingProgressTimer.addEventListener(TimerEvent.TIMER, function playingProgressTimerHandler(event:TimerEvent){
				triggerEvent('playingProgress', int(channel.position));
			});
			playingProgressTimer.start();
		}

		protected function stop():int
		{
			playStop();
			return recordStop();
		}

		protected function playStop():void
		{
			logger.log('stopPlaying');
			if(channel){
				channel.stop();
				playingProgressTimer.reset();

				triggerEvent('playingStop', {});
				isPlaying = false;
			}
		}

		/* Networking functions */

		protected function upload(uri:String, audioParam:String, parameters): void
		{
			logger.log("upload");
			buffer.position = 0;
			var wav:ByteArray = prepareWav();
			var ml:MultipartURLLoader = new MultipartURLLoader();
			ml.addEventListener(Event.COMPLETE, onReady);
			function onReady(e:Event):void
			{
				triggerEvent('uploadSuccess', externalInterfaceEncode(e.target.loader.data));
				logger.log('uploading done');
			}

			if(getQualifiedClassName(parameters.constructor) == "Array"){
				for(var i=0; i<parameters.length; i++){
					ml.addVariable(parameters[i][0], parameters[i][1]);
				}
			}else{
				for(var k in parameters){
					ml.addVariable(k, parameters[k]);
				}
			}

			ml.addFile(wav, 'audio.wav', audioParam);
			ml.load(uri, false);

		}

		private function externalInterfaceEncode(data:String){
			return data.split("%").join("%25").split("\\").join("%5c").split("\"").join("%22").split("&").join("%26");
		}

		protected function audioData():String
		{
			var ret:String="";
			buffer.position = 0;
			while (buffer.bytesAvailable > 0)
			{
				ret += buffer.readFloat().toString() + ";";
			}
			return ret;
		}

		protected function showFlash():void
		{
			Security.showSettings(SecurityPanel.PRIVACY);
			triggerEvent('showFlash','');
		}

		/* Recording Helper */
		protected function setupMicrophone():void
		{
			logger.log('setupMicrophone');
			microphone = Microphone.getMicrophone();
			microphone.codec = "Nellymoser";
			microphone.setSilenceLevel(0);
			microphone.rate = sampleRate;
			microphone.gain = 50;
			microphone.addEventListener(StatusEvent.STATUS, function statusHandler(e:Event) {
				logger.log('Microphone Status Change');
				if(microphone.muted){
					triggerEvent('recordingCancel','');
				}else{
					if(!isRecording){
						notifyRecordingStarted();
					}
				}
			});

			logger.log('setupMicrophone done: ' + microphone.name + ' ' + microphone.muted);
		}

		protected function notifyRecordingStarted():void
		{
			if(microphoneWasMuted){
				microphoneWasMuted = false;
				triggerEvent('hideFlash','');
			}
			recordingStartTime = getTimer();
			triggerEvent('recordingStart', {});
			logger.log('startRecording');
			isRecording = true;
		}

		/* Sample related */

		protected function prepareWav():ByteArray
		{
			var wavData:ByteArray = new ByteArray();
			var wavWriter:WAVWriter = new WAVWriter();
			buffer.position = 0;
			wavWriter.numOfChannels = 1; // set the inital properties of the Wave Writer
			wavWriter.sampleBitRate = 16;
			wavWriter.samplingRate = sampleRate * 1000;
			wavWriter.processSamples(wavData, buffer, sampleRate * 1000, 1);
			return wavData;
		}

		protected function recordingDuration():int
		{
			var latency = 650;
			var duration = int(getTimer() - recordingStartTime - latency);
			return Math.max(duration, 0);
		}

		protected function recordSampleDataHandler(event:SampleDataEvent):void
		{
			while(event.data.bytesAvailable)
			{
				var sample:Number = event.data.readFloat();

				buffer.writeFloat(sample);
				if(buffer.length % 40000 == 0){
					triggerEvent('recordingProgress', recordingDuration(), 	microphone.activityLevel);
				}
			}
		}

		protected function playSampleDataHandler(event:SampleDataEvent):void
		{
			var expectedSampleRate = 44.1;
			var writtenSamples = 0;
			var channels = 2;
			var maxSamples = 8192 * channels;
			// if the sampleRate doesn't match the expectedSampleRate of flash.media.Sound (44.1) write the sample multiple times
			// this will result in a little down pitchshift.
			// also write 2 times for stereo channels
			while(writtenSamples < maxSamples && buffer.bytesAvailable)
			{
				var sample:Number = buffer.readFloat();
			  for (var j:int = 0; j < channels * (expectedSampleRate / sampleRate); j++){
					event.data.writeFloat(sample);
					writtenSamples++;
					if(writtenSamples >= maxSamples){
						break;
					}
				}
			}
			logger.log("Wrote " + writtenSamples + " samples");
		}

		/* ExternalInterface Communication */

		protected function triggerEvent(eventName:String, arg0, arg1 = null):void
		{
			ExternalInterface.call("Recorder.triggerEvent", eventName, arg0, arg1);
		}
	}
}

write samples multiple times when playing it back if sampleRate is < 44.1


////////////////////////////////////////////////////////////////////////////////
//
//  Licensed to the Apache Software Foundation (ASF) under one or more
//  contributor license agreements.  See the NOTICE file distributed with
//  this work for additional information regarding copyright ownership.
//  The ASF licenses this file to You under the Apache License, Version 2.0
//  (the "License"); you may not use this file except in compliance with
//  the License.  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.Shape;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFieldType;

    import org.apache.flex.core.BeadViewBase;
	import org.apache.flex.core.CSSTextField;
	import org.apache.flex.core.IBeadView;
	import org.apache.flex.core.IStrand;
	import org.apache.flex.core.ITextModel;
	import org.apache.flex.core.ValuesManager;
	import org.apache.flex.events.Event;
	import org.apache.flex.events.IEventDispatcher;
	import org.apache.flex.html.TextButton;
	import org.apache.flex.utils.CSSUtils;
    import org.apache.flex.utils.SolidBorderUtil;
    import org.apache.flex.utils.StringTrimmer;

    /**
     *  The CSSTextButtonView class is the default view for
     *  the org.apache.flex.html.TextButton class.
     *  It allows the look of the button to be expressed
     *  in CSS via the background-image style and displays
     *  a text label.  This view does not support right-to-left
     *  text.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10.2
     *  @playerversion AIR 2.6
     *  @productversion FlexJS 0.0
     */
	public class CSSTextButtonView extends BeadViewBase implements IBeadView
	{
        /**
         *  Constructor.
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		public function CSSTextButtonView()
		{
			upSprite = new Sprite();
			downSprite = new Sprite();
			overSprite = new Sprite();
			upTextField = new CSSTextField();
			downTextField = new CSSTextField();
			overTextField = new CSSTextField();
			upTextField.selectable = false;
			upTextField.type = TextFieldType.DYNAMIC;
			downTextField.selectable = false;
			downTextField.type = TextFieldType.DYNAMIC;
			overTextField.selectable = false;
			overTextField.type = TextFieldType.DYNAMIC;
			upTextField.autoSize = "left";
			downTextField.autoSize = "left";
			overTextField.autoSize = "left";
			upSprite.addChild(upTextField);
			downSprite.addChild(downTextField);
			overSprite.addChild(overTextField);
		}

		private var textModel:ITextModel;

		private var shape:Shape;

        /**
         *  @copy org.apache.flex.core.IBead#strand
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		override public function set strand(value:IStrand):void
		{
			_strand = value;
			textModel = value.getBeadByType(ITextModel) as ITextModel;
			textModel.addEventListener("textChange", textChangeHandler);
			textModel.addEventListener("htmlChange", htmlChangeHandler);
			shape = new Shape();
			shape.graphics.beginFill(0xCCCCCC);
			shape.graphics.drawRect(0, 0, 10, 10);
			shape.graphics.endFill();
            upTextField.styleParent = _strand;
            downTextField.styleParent = _strand;
            overTextField.styleParent = _strand;
            upTextField.parentDrawsBackground = true;
            downTextField.parentDrawsBackground = true;
            overTextField.parentDrawsBackground = true;
            upTextField.parentHandlesPadding = true;
            downTextField.parentHandlesPadding = true;
            overTextField.parentHandlesPadding = true;
			SimpleButton(value).upState = upSprite;
			SimpleButton(value).downState = downSprite;
			SimpleButton(value).overState = overSprite;
			SimpleButton(value).hitTestState = shape;
			if (textModel.text !== null)
				text = textModel.text;
			if (textModel.html !== null)
				html = textModel.html;

            setupSkins();

			IEventDispatcher(_strand).addEventListener("widthChanged",sizeChangeHandler);
			IEventDispatcher(_strand).addEventListener("heightChanged",sizeChangeHandler);
		}

        protected function setupSkins():void
        {
            setupSkin(overSprite, overTextField, "hover");
            setupSkin(downSprite, downTextField, "active");
            setupSkin(upSprite, upTextField);
            updateHitArea();
        }

		private function setupSkin(sprite:Sprite, textField:TextField, state:String = null):void
		{
			var sw:uint = DisplayObject(_strand).width;
			var sh:uint = DisplayObject(_strand).height;

			textField.defaultTextFormat.leftMargin = 0;
			textField.defaultTextFormat.rightMargin = 0;
            // set it again so it gets noticed
			textField.defaultTextFormat = textField.defaultTextFormat;

			var borderColor:uint;
			var borderThickness:uint;
			var borderStyle:String;
			var borderStyles:Object = ValuesManager.valuesImpl.getValue(_strand, "border", state);
			if (borderStyles is Array)
			{
				borderColor = CSSUtils.toColor(borderStyles[2]);
				borderStyle = borderStyles[1];
				borderThickness = borderStyles[0];
			}
            else if (borderStyles is String)
                borderStyle = borderStyles as String;
			var value:Object = ValuesManager.valuesImpl.getValue(_strand, "border-style", state);
			if (value != null)
				borderStyle = value as String;
			value = ValuesManager.valuesImpl.getValue(_strand, "border-color", state);
			if (value != null)
				borderColor = CSSUtils.toColor(value);
			value = ValuesManager.valuesImpl.getValue(_strand, "border-width", state);
			if (value != null)
				borderThickness = value as uint;
            if (borderStyle == "none")
            {
                borderStyle = "solid";
                borderThickness = 0;
            }

            var borderRadius:String;
            var borderEllipseWidth:Number = NaN;
            var borderEllipseHeight:Number = NaN;
            value = ValuesManager.valuesImpl.getValue(_strand, "border-radius", state);
            if (value != null)
            {
                if (value is Number)
                    borderEllipseWidth = 2 * (value as Number);
                else
                {
                    borderRadius = value as String;
                    var arr:Array = StringTrimmer.splitAndTrim(borderRadius, "/");
                    borderEllipseWidth = 2 * CSSUtils.toNumber(arr[0]);
                    if (arr.length > 1)
                        borderEllipseHeight = 2 * CSSUtils.toNumber(arr[1]);
                }
            }

			var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding", state);
			var paddingLeft:Object = ValuesManager.valuesImpl.getValue(_strand, "padding-left", state);
			var paddingRight:Object = ValuesManager.valuesImpl.getValue(_strand, "padding-right", state);
			var paddingTop:Object = ValuesManager.valuesImpl.getValue(_strand, "padding-top", state);
			var paddingBottom:Object = ValuesManager.valuesImpl.getValue(_strand, "padding-bottom", state);
            var pl:Number = CSSUtils.getLeftValue(paddingLeft, padding, DisplayObject(_strand).width);
            var pr:Number = CSSUtils.getRightValue(paddingRight, padding, DisplayObject(_strand).width);
            var pt:Number = CSSUtils.getTopValue(paddingTop, padding, DisplayObject(_strand).height);
            var pb:Number = CSSUtils.getBottomValue(paddingBottom, padding, DisplayObject(_strand).height);

			var backgroundColor:Object = ValuesManager.valuesImpl.getValue(_strand, "background-color", state);
            var bgColor:uint;
            var bgAlpha:Number = 1;
            if (backgroundColor != null)
            {
                bgColor = CSSUtils.toColorWithAlpha(backgroundColor);
                if (bgColor & 0xFF000000)
                {
                    bgAlpha = bgColor >>> 24 / 255;
                    bgColor = bgColor & 0xFFFFFF;
                }
            }
			if (borderStyle == "solid")
			{
				var useWidth:Number = Math.max(sw,textField.textWidth);
				var useHeight:Number = Math.max(sh,textField.textHeight);

				if ((useWidth-pl-pr-2*borderThickness) < textField.textWidth)
					useWidth = textField.textWidth+pl+pr+2*borderThickness;
				if ((useHeight-pt-pb-2*borderThickness) < textField.textHeight)
					useHeight = textField.textHeight+pt+pb+2*borderThickness;

                sprite.graphics.clear();
				SolidBorderUtil.drawBorder(sprite.graphics,
					0, 0, useWidth, useHeight,
					borderColor, backgroundColor == null ? null : bgColor, borderThickness, bgAlpha,
                    borderEllipseWidth, borderEllipseHeight);
				textField.y = ((useHeight - textField.textHeight) / 2) - 2;
				textField.x = ((useWidth - textField.textWidth) / 2) - 2;
			}
			var backgroundImage:Object = ValuesManager.valuesImpl.getValue(_strand, "background-image", state);
			if (backgroundImage)
			{
				var loader:Loader = new Loader();
				sprite.addChildAt(loader, 0);
				var url:String = backgroundImage as String;
				loader.load(new URLRequest(url));
				loader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, function (e:flash.events.Event):void {
					var useWidth:Number = Math.max(sw,textField.textWidth);
					var useHeight:Number = Math.max(sh,textField.textHeight);

					if ((useWidth-2*Number(padding)-2*borderThickness) < textField.textWidth)
						useWidth = textField.textWidth+2*Number(padding)+2*borderThickness;
					if ((useHeight-2*Number(padding)-2*borderThickness) < textField.textHeight)
						useHeight = textField.textHeight+2*Number(padding)+2*borderThickness;

					textField.y = (useHeight - textField.height) / 2;
					textField.x = (useWidth - textField.width) / 2;
					updateHitArea();
				});
			}
			var textColor:Object = ValuesManager.valuesImpl.getValue(_strand, "color", state);
			if (textColor) {
				textField.textColor = Number(textColor);
			}
		}

		private function textChangeHandler(event:org.apache.flex.events.Event):void
		{
			text = textModel.text;
		}

		private function htmlChangeHandler(event:org.apache.flex.events.Event):void
		{
			html = textModel.html;
		}

		private function sizeChangeHandler(event:org.apache.flex.events.Event):void
		{
			setupSkins();
		}

		private var upTextField:CSSTextField;
		private var downTextField:CSSTextField;
		private var overTextField:CSSTextField;
		private var upSprite:Sprite;
		private var downSprite:Sprite;
		private var overSprite:Sprite;

        /**
         *  The text to be displayed in the button
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		public function get text():String
		{
			return upTextField.text;
		}

        /**
         *  @private
         */
		public function set text(value:String):void
		{
			upTextField.text = value;
			downTextField.text = value;
			overTextField.text = value;
			updateHitArea();
		}

		private function updateHitArea():void
		{
			var useWidth:uint = Math.max(DisplayObject(_strand).width, upTextField.textWidth);
			var useHeight:uint = Math.max(DisplayObject(_strand).height, upTextField.textHeight);

			shape.graphics.clear();
			shape.graphics.beginFill(0xCCCCCC);
			shape.graphics.drawRect(0, 0, useWidth, useHeight);
			shape.graphics.endFill();

		}

        /**
         *  The html-formatted text to be displayed in the button
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		public function get html():String
		{
			return upTextField.htmlText;
		}

        /**
         *  @private
         */
		public function set html(value:String):void
		{
			upTextField.htmlText = value;
			downTextField.htmlText = value;
			overTextField.htmlText = value;
		}
	}
}

////////////////////////////////////////////////////////////////////////////////
//
//  Licensed to the Apache Software Foundation (ASF) under one or more
//  contributor license agreements.  See the NOTICE file distributed with
//  this work for additional information regarding copyright ownership.
//  The ASF licenses this file to You under the Apache License, Version 2.0
//  (the "License"); you may not use this file except in compliance with
//  the License.  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.Shape;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFieldType;

    import org.apache.flex.core.BeadViewBase;
	import org.apache.flex.core.CSSTextField;
	import org.apache.flex.core.IBeadView;
	import org.apache.flex.core.IStrand;
	import org.apache.flex.core.ITextModel;
	import org.apache.flex.core.ValuesManager;
	import org.apache.flex.events.Event;
	import org.apache.flex.events.IEventDispatcher;
	import org.apache.flex.html.TextButton;
	import org.apache.flex.utils.CSSUtils;
    import org.apache.flex.utils.SolidBorderUtil;
    import org.apache.flex.utils.StringTrimmer;

    /**
     *  The CSSTextButtonView class is the default view for
     *  the org.apache.flex.html.TextButton class.
     *  It allows the look of the button to be expressed
     *  in CSS via the background-image style and displays
     *  a text label.  This view does not support right-to-left
     *  text.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10.2
     *  @playerversion AIR 2.6
     *  @productversion FlexJS 0.0
     */
	public class CSSTextButtonView extends BeadViewBase implements IBeadView
	{
        /**
         *  Constructor.
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		public function CSSTextButtonView()
		{
			upSprite = new Sprite();
			downSprite = new Sprite();
			overSprite = new Sprite();
			upTextField = new CSSTextField();
			downTextField = new CSSTextField();
			overTextField = new CSSTextField();
			upTextField.selectable = false;
			upTextField.type = TextFieldType.DYNAMIC;
			downTextField.selectable = false;
			downTextField.type = TextFieldType.DYNAMIC;
			overTextField.selectable = false;
			overTextField.type = TextFieldType.DYNAMIC;
			upTextField.autoSize = "left";
			downTextField.autoSize = "left";
			overTextField.autoSize = "left";
			upSprite.addChild(upTextField);
			downSprite.addChild(downTextField);
			overSprite.addChild(overTextField);
		}

		private var textModel:ITextModel;

		private var shape:Shape;

        /**
         *  @copy org.apache.flex.core.IBead#strand
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		override public function set strand(value:IStrand):void
		{
			_strand = value;
			textModel = value.getBeadByType(ITextModel) as ITextModel;
			textModel.addEventListener("textChange", textChangeHandler);
			textModel.addEventListener("htmlChange", htmlChangeHandler);
			shape = new Shape();
			shape.graphics.beginFill(0xCCCCCC);
			shape.graphics.drawRect(0, 0, 10, 10);
			shape.graphics.endFill();
            upTextField.styleParent = _strand;
            downTextField.styleParent = _strand;
            overTextField.styleParent = _strand;
            upTextField.parentDrawsBackground = true;
            downTextField.parentDrawsBackground = true;
            overTextField.parentDrawsBackground = true;
            upTextField.parentHandlesPadding = true;
            downTextField.parentHandlesPadding = true;
            overTextField.parentHandlesPadding = true;
			SimpleButton(value).upState = upSprite;
			SimpleButton(value).downState = downSprite;
			SimpleButton(value).overState = overSprite;
			SimpleButton(value).hitTestState = shape;
			if (textModel.text !== null)
				text = textModel.text;
			if (textModel.html !== null)
				html = textModel.html;

            setupSkins();

			IEventDispatcher(_strand).addEventListener("widthChanged",sizeChangeHandler);
			IEventDispatcher(_strand).addEventListener("heightChanged",sizeChangeHandler);
            IEventDispatcher(_strand).addEventListener("sizeChanged",sizeChangeHandler);
		}

        protected function setupSkins():void
        {
            setupSkin(overSprite, overTextField, "hover");
            setupSkin(downSprite, downTextField, "active");
            setupSkin(upSprite, upTextField);
            updateHitArea();
        }

		private function setupSkin(sprite:Sprite, textField:TextField, state:String = null):void
		{
			var sw:uint = DisplayObject(_strand).width;
			var sh:uint = DisplayObject(_strand).height;

			textField.defaultTextFormat.leftMargin = 0;
			textField.defaultTextFormat.rightMargin = 0;
            // set it again so it gets noticed
			textField.defaultTextFormat = textField.defaultTextFormat;

			var borderColor:uint;
			var borderThickness:uint;
			var borderStyle:String;
			var borderStyles:Object = ValuesManager.valuesImpl.getValue(_strand, "border", state);
			if (borderStyles is Array)
			{
				borderColor = CSSUtils.toColor(borderStyles[2]);
				borderStyle = borderStyles[1];
				borderThickness = borderStyles[0];
			}
            else if (borderStyles is String)
                borderStyle = borderStyles as String;
			var value:Object = ValuesManager.valuesImpl.getValue(_strand, "border-style", state);
			if (value != null)
				borderStyle = value as String;
			value = ValuesManager.valuesImpl.getValue(_strand, "border-color", state);
			if (value != null)
				borderColor = CSSUtils.toColor(value);
			value = ValuesManager.valuesImpl.getValue(_strand, "border-width", state);
			if (value != null)
				borderThickness = value as uint;
            if (borderStyle == "none")
            {
                borderStyle = "solid";
                borderThickness = 0;
            }

            var borderRadius:String;
            var borderEllipseWidth:Number = NaN;
            var borderEllipseHeight:Number = NaN;
            value = ValuesManager.valuesImpl.getValue(_strand, "border-radius", state);
            if (value != null)
            {
                if (value is Number)
                    borderEllipseWidth = 2 * (value as Number);
                else
                {
                    borderRadius = value as String;
                    var arr:Array = StringTrimmer.splitAndTrim(borderRadius, "/");
                    borderEllipseWidth = 2 * CSSUtils.toNumber(arr[0]);
                    if (arr.length > 1)
                        borderEllipseHeight = 2 * CSSUtils.toNumber(arr[1]);
                }
            }

			var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding", state);
			var paddingLeft:Object = ValuesManager.valuesImpl.getValue(_strand, "padding-left", state);
			var paddingRight:Object = ValuesManager.valuesImpl.getValue(_strand, "padding-right", state);
			var paddingTop:Object = ValuesManager.valuesImpl.getValue(_strand, "padding-top", state);
			var paddingBottom:Object = ValuesManager.valuesImpl.getValue(_strand, "padding-bottom", state);
            var pl:Number = CSSUtils.getLeftValue(paddingLeft, padding, DisplayObject(_strand).width);
            var pr:Number = CSSUtils.getRightValue(paddingRight, padding, DisplayObject(_strand).width);
            var pt:Number = CSSUtils.getTopValue(paddingTop, padding, DisplayObject(_strand).height);
            var pb:Number = CSSUtils.getBottomValue(paddingBottom, padding, DisplayObject(_strand).height);

			var backgroundColor:Object = ValuesManager.valuesImpl.getValue(_strand, "background-color", state);
            var bgColor:uint;
            var bgAlpha:Number = 1;
            if (backgroundColor != null)
            {
                bgColor = CSSUtils.toColorWithAlpha(backgroundColor);
                if (bgColor & 0xFF000000)
                {
                    bgAlpha = bgColor >>> 24 / 255;
                    bgColor = bgColor & 0xFFFFFF;
                }
            }
			if (borderStyle == "solid")
			{
				var useWidth:Number = Math.max(sw,textField.textWidth);
				var useHeight:Number = Math.max(sh,textField.textHeight);

				if ((useWidth-pl-pr-2*borderThickness) < textField.textWidth)
					useWidth = textField.textWidth+pl+pr+2*borderThickness;
				if ((useHeight-pt-pb-2*borderThickness) < textField.textHeight)
					useHeight = textField.textHeight+pt+pb+2*borderThickness;

                sprite.graphics.clear();
				SolidBorderUtil.drawBorder(sprite.graphics,
					0, 0, useWidth, useHeight,
					borderColor, backgroundColor == null ? null : bgColor, borderThickness, bgAlpha,
                    borderEllipseWidth, borderEllipseHeight);
				textField.y = ((useHeight - textField.textHeight) / 2) - 2;
				textField.x = ((useWidth - textField.textWidth) / 2) - 2;
			}
			var backgroundImage:Object = ValuesManager.valuesImpl.getValue(_strand, "background-image", state);
			if (backgroundImage)
			{
				var loader:Loader = new Loader();
				sprite.addChildAt(loader, 0);
				var url:String = backgroundImage as String;
				loader.load(new URLRequest(url));
				loader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, function (e:flash.events.Event):void {
					var useWidth:Number = Math.max(sw,textField.textWidth);
					var useHeight:Number = Math.max(sh,textField.textHeight);

					if ((useWidth-2*Number(padding)-2*borderThickness) < textField.textWidth)
						useWidth = textField.textWidth+2*Number(padding)+2*borderThickness;
					if ((useHeight-2*Number(padding)-2*borderThickness) < textField.textHeight)
						useHeight = textField.textHeight+2*Number(padding)+2*borderThickness;

					textField.y = (useHeight - textField.height) / 2;
					textField.x = (useWidth - textField.width) / 2;
					updateHitArea();
				});
			}
			var textColor:Object = ValuesManager.valuesImpl.getValue(_strand, "color", state);
			if (textColor) {
				textField.textColor = Number(textColor);
			}
		}

		private function textChangeHandler(event:org.apache.flex.events.Event):void
		{
			text = textModel.text;
		}

		private function htmlChangeHandler(event:org.apache.flex.events.Event):void
		{
			html = textModel.html;
		}

		private function sizeChangeHandler(event:org.apache.flex.events.Event):void
		{
			setupSkins();
		}

		private var upTextField:CSSTextField;
		private var downTextField:CSSTextField;
		private var overTextField:CSSTextField;
		private var upSprite:Sprite;
		private var downSprite:Sprite;
		private var overSprite:Sprite;

        /**
         *  The text to be displayed in the button
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		public function get text():String
		{
			return upTextField.text;
		}

        /**
         *  @private
         */
		public function set text(value:String):void
		{
			upTextField.text = value;
			downTextField.text = value;
			overTextField.text = value;
			updateHitArea();
		}

		private function updateHitArea():void
		{
			var useWidth:uint = Math.max(DisplayObject(_strand).width, upTextField.textWidth);
			var useHeight:uint = Math.max(DisplayObject(_strand).height, upTextField.textHeight);

			shape.graphics.clear();
			shape.graphics.beginFill(0xCCCCCC);
			shape.graphics.drawRect(0, 0, useWidth, useHeight);
			shape.graphics.endFill();

		}

        /**
         *  The html-formatted text to be displayed in the button
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		public function get html():String
		{
			return upTextField.htmlText;
		}

        /**
         *  @private
         */
		public function set html(value:String):void
		{
			upTextField.htmlText = value;
			downTextField.htmlText = value;
			overTextField.htmlText = value;
		}
	}
}

check for size change

check for size change


package aerys.minko.render.shader.part.environment
{
	import aerys.minko.render.material.environment.EnvironmentMappingProperties;
	import aerys.minko.render.shader.SFloat;
	import aerys.minko.render.shader.Shader;
	import aerys.minko.render.shader.part.BlendingShaderPart;
	import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
	import aerys.minko.render.shader.part.projection.BlinnNewellProjectionShaderPart;
	import aerys.minko.render.shader.part.projection.ProbeProjectionShaderPart;
	import aerys.minko.type.enum.Blending;
	import aerys.minko.type.enum.EnvironmentMappingType;
	import aerys.minko.type.enum.SamplerDimension;
	import aerys.minko.type.enum.SamplerFiltering;
	import aerys.minko.type.enum.SamplerFormat;
	import aerys.minko.type.enum.SamplerMipMapping;
	import aerys.minko.type.enum.SamplerWrapping;

	import flash.geom.Rectangle;

	public class EnvironmentMappingShaderPart extends LightAwareShaderPart
	{
		private var _blinnNewellProjectionPart	: BlinnNewellProjectionShaderPart;
		private var _probeProjectionPart		: ProbeProjectionShaderPart;
		private var _blending					: BlendingShaderPart;

		public function EnvironmentMappingShaderPart(main : Shader)
		{
			super(main);

			_blinnNewellProjectionPart	= new BlinnNewellProjectionShaderPart(main);
			_probeProjectionPart		= new ProbeProjectionShaderPart(main);
			_blending					= new BlendingShaderPart(main);
		}

		public function getEnvironmentColor() : SFloat
		{
			// compute reflected vector
			var cWorldCameraPosition	: SFloat = this.cameraPosition;
			var vsWorldVertexToCamera	: SFloat = normalize(subtract(cWorldCameraPosition, vsWorldPosition));
			var reflected				: SFloat = normalize(interpolate(reflect(vsWorldVertexToCamera.xyzz, vsWorldNormal.xyzz)));
			var reflectionType 			: int	 = meshBindings.getProperty(
				EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE
			);
            var reflectionMap           : SFloat    = getEnvironmentMap(reflectionType);

			// retrieve reflection color from reflection map
			var reflectionMapUV			: SFloat;
			var reflectionColor			: SFloat;

			switch (reflectionType)
			{
				case EnvironmentMappingType.NONE:
					reflectionColor = float4(0, 0, 0, 0);
					break;

				case EnvironmentMappingType.PROBE:
					reflectionMapUV = _probeProjectionPart.projectVector(reflected, new Rectangle(0, 0, 1, 1));
					reflectionColor = sampleTexture(reflectionMap, reflectionMapUV);
					break;

				case EnvironmentMappingType.BLINN_NEWELL:
					reflectionMapUV = _blinnNewellProjectionPart.projectVector(reflected, new Rectangle(0, 0, 1, 1));
					reflectionColor = sampleTexture(reflectionMap, reflectionMapUV);
					break;

				case EnvironmentMappingType.CUBE:
					reflectionColor = sampleTexture(reflectionMap, reflected);
					break;

				default:
					throw new Error('Unsupported reflection type');
			}

			// modifify alpha color
			if (meshBindings.propertyExists(EnvironmentMappingProperties.REFLECTIVITY))
			{
				var reflectivity : SFloat = meshBindings.getParameter(
					EnvironmentMappingProperties.REFLECTIVITY, 1
				);

				reflectionColor = float4(reflectionColor.xyz, multiply(reflectionColor.w, reflectivity));
			}

			return reflectionColor;
		}

        public function getEnvironmentMap(environmentMappingType : uint = 0) : SFloat
        {
            if (!environmentMappingType)
                meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE);

            return meshBindings.getTextureParameter(
                EnvironmentMappingProperties.ENVIRONMENT_MAP,
                meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, SamplerFiltering.NEAREST),
                meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, SamplerMipMapping.DISABLE),
                meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, SamplerWrapping.CLAMP),
                environmentMappingType == EnvironmentMappingType.CUBE ? SamplerDimension.CUBE : SamplerDimension.FLAT,
                meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, SamplerFormat)
            );
        }

		public function applyEnvironmentMapping(diffuse : SFloat) : SFloat
		{
			if (!meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE))
				return diffuse;

			return _blending.blend(
				getEnvironmentColor(),
				diffuse,
				meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, Blending.ALPHA)
			);
		}
	}
}

package aerys.minko.render.shader.part.environment
{
	import aerys.minko.render.material.environment.EnvironmentMappingProperties;
	import aerys.minko.render.shader.SFloat;
	import aerys.minko.render.shader.Shader;
	import aerys.minko.render.shader.part.BlendingShaderPart;
	import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
	import aerys.minko.render.shader.part.projection.BlinnNewellProjectionShaderPart;
	import aerys.minko.render.shader.part.projection.ProbeProjectionShaderPart;
	import aerys.minko.type.enum.Blending;
	import aerys.minko.type.enum.EnvironmentMappingType;
	import aerys.minko.type.enum.SamplerDimension;
	import aerys.minko.type.enum.SamplerFiltering;
	import aerys.minko.type.enum.SamplerFormat;
	import aerys.minko.type.enum.SamplerMipMapping;
	import aerys.minko.type.enum.SamplerWrapping;

	import flash.geom.Rectangle;

	public class EnvironmentMappingShaderPart extends LightAwareShaderPart
	{
		private var _blinnNewellProjectionPart	: BlinnNewellProjectionShaderPart;
		private var _probeProjectionPart		: ProbeProjectionShaderPart;
		private var _blending					: BlendingShaderPart;

		public function EnvironmentMappingShaderPart(main : Shader)
		{
			super(main);

			_blinnNewellProjectionPart	= new BlinnNewellProjectionShaderPart(main);
			_probeProjectionPart		= new ProbeProjectionShaderPart(main);
			_blending					= new BlendingShaderPart(main);
		}

		public function getEnvironmentColor() : SFloat
		{
            if (!meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE)
                || !meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAP))
                return float4(0, 0, 0, 0);

			// compute reflected vector
			var cWorldCameraPosition	: SFloat = this.cameraPosition;
			var vsWorldVertexToCamera	: SFloat = normalize(subtract(cWorldCameraPosition, vsWorldPosition));
			var reflected				: SFloat = normalize(interpolate(reflect(vsWorldVertexToCamera.xyzz, vsWorldNormal.xyzz)));
			var reflectionType 			: int	 = meshBindings.getProperty(
				EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE
			);
            var reflectionMap           : SFloat    = getEnvironmentMap(reflectionType);

			// retrieve reflection color from reflection map
			var reflectionMapUV			: SFloat;
			var reflectionColor			: SFloat;

			switch (reflectionType)
			{
				case EnvironmentMappingType.NONE:
					reflectionColor = float4(0, 0, 0, 0);
					break;

				case EnvironmentMappingType.PROBE:
					reflectionMapUV = _probeProjectionPart.projectVector(reflected, new Rectangle(0, 0, 1, 1));
					reflectionColor = sampleTexture(reflectionMap, reflectionMapUV);
					break;

				case EnvironmentMappingType.BLINN_NEWELL:
					reflectionMapUV = _blinnNewellProjectionPart.projectVector(reflected, new Rectangle(0, 0, 1, 1));
					reflectionColor = sampleTexture(reflectionMap, reflectionMapUV);
					break;

				case EnvironmentMappingType.CUBE:
					reflectionColor = sampleTexture(reflectionMap, reflected);
					break;

				default:
					throw new Error('Unsupported reflection type');
			}

			// modifify alpha color
			if (meshBindings.propertyExists(EnvironmentMappingProperties.REFLECTIVITY))
			{
				var reflectivity : SFloat = meshBindings.getParameter(
					EnvironmentMappingProperties.REFLECTIVITY, 1
				);

				reflectionColor = float4(reflectionColor.xyz, multiply(reflectionColor.w, reflectivity));
			}

			return reflectionColor;
		}

        public function getEnvironmentMap(environmentMappingType : uint = 0) : SFloat
        {
            if (!environmentMappingType)
                meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE);

            return meshBindings.getTextureParameter(
                EnvironmentMappingProperties.ENVIRONMENT_MAP,
                meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, SamplerFiltering.NEAREST),
                meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, SamplerMipMapping.DISABLE),
                meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, SamplerWrapping.CLAMP),
                environmentMappingType == EnvironmentMappingType.CUBE ? SamplerDimension.CUBE : SamplerDimension.FLAT,
                meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, SamplerFormat)
            );
        }

		public function applyEnvironmentMapping(diffuse : SFloat) : SFloat
		{
			if (!meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE))
				return diffuse;

			return _blending.blend(
				getEnvironmentColor(),
				diffuse,
				meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, Blending.ALPHA)
			);
		}
	}
}

update EnvironmentMappingShaderPart.getEnvironmentColor() to return (0, 0, 0, 0) if ENVIRONMENT_MAPPING_TYPE or ENVIRONMENT_MAP are not set


package {
  import stdio.flash.Sprite
  import stdio.process
  import stdio.Interactive

  [SWF(width=0, height=0)]
  public class test_readline_flash extends Sprite implements Interactive {
    public function main(): void {
      process.prompt = "What’s your name? "
      process.gets(function (name: String): void {
        process.puts("Hello, " + name + "!")
        process.prompt = "Favorite color? "
        process.gets(function (color: String): void {
          process.puts("I like " + color + " too!")
          process.exit()
        })
      })
    }
  }
}

package {
  import stdio.colorize
  import stdio.flash.Sprite
  import stdio.process
  import stdio.Interactive

  [SWF(width=0, height=0)]
  public class test_readline_flash extends Sprite implements Interactive {
    public function main(): void {
      process.prompt = "What’s your name? "
      process.gets(function (name: String): void {
        process.puts("Hello, " + name + "!")
        process.prompt = "What’s your favorite color? "
        process.gets(function (color: String): void {
          color = color.toLowerCase()
          process.puts(
            "I like " + colorize(
              "%{bold}%{" + color + "}" + color + "%{none}"
            ) + " too!"
          )
          process.exit()
        })
      })
    }
  }
}

Use `colorize` in readline test.

Use `colorize` in readline test.


/******************************************************************************
 * LzReplicationManager.as
 *****************************************************************************/

//* A_LZ_COPYRIGHT_BEGIN ******************************************************
//* Copyright 2001-2007 Laszlo Systems, Inc.  All Rights Reserved.            *
//* Use is subject to license terms.                                          *
//* A_LZ_COPYRIGHT_END ********************************************************

/* An application source file contains XML that describes a view that
 * will be instantiated when the application is loaded.  These XML
 * elements are called view templates, and occur either directly
 * within the document root, or within another view template.  A root
 * view template is a view template that occurs directly within the
 * document root.
 *
 * The interface compiler compiles each root view template into
 * ActionScript bytecodes that, when executed, create an instance of
 * the object that the XML element describes.  It does this by
 * appending to the output file instructions to push a succint
 * description of the XML hierarchy onto the stack, followed by a call
 * to LzInstantiateView (below) with the runtime representation of the
 * root view template as its argument.
 *
 * The format of the runtime representation is documented in the
 * Javadoc for org.openlaszlo.ic.ScriptCompiler.xmlToScript.  In
 * brief, an XML element is compiled to a runtime object with the
 * following attributes:
 *   tagName: The element, or tag name (e.g. "window")
 *   attrs: An object whose properties are attributes, e.g.
 *     {title: "Contacts", x: 10, y: 20}
 *   children: An array of child elements.
 *
 * --- ows
 */

/* A map of element names, to functions that create instances of the
 * appropriate type. */
    // none of these have been tested except window
//  dataSource: function (args) {return new DataSource(_root, args.source);}
//  gridView: function (args) {return new lzGridView(args);}
//  menu: function (args) {return new lzMenu(args, []);}
    //view: function (args) {return new lzView(args);}
ConstructorMap = {
    agent: "LzAgent",
    animator: "LzAnimator" ,
    animatorgroup: "LzAnimatorGroup" ,
    canvas: "LzCanvas" ,
    centerconstraint: "LzCenterConstraint",
    command: "LzCommand",
    connection: "LzConnection",
    connectiondatasource: "LzConnectionDatasource",
    datapath: "LzDatapath",
    datapointer: "LzDatapointer",
    dataselectionmanager: "LzDataSelectionManager" ,
    dataset: "LzDataset",
    datasource: "LzHTTPDatasource",
    drawview: "LzDrawView",
    debug: "LzDebugWindow",
    floormodifier: "LzFloorModifier" ,
    httpdatasource: "LzHTTPDatasource",
    'import': "LzLibrary",
    inputtext: "LzInputText" ,
    javadatasource: "LzJavaDatasource",
    layout: "LzLayout" ,
    limitmodifier: "LzLimitModifier" ,
    mappingview: "LzPagingView" ,
    node: "LzNode",
    params: "LzParam",
    propconstraint: "LzViewPropConstraint" ,
    propmodifier: "LzPropertyModifier" ,
    script: "LzScript",
    selectionmanager: "LzSelectionManager" ,
    state: "LzState",
    text:  "LzText",
    userclass: "LzUserClass",
    view:  "LzView",
    viewtemplate: "LzViewTemplate"
};

/* This constructor map overwrites the regular ConstructorMap *just* for the
 * doc generation. e.g. dataset cannot have an API (the LFC would break), but
 * the generated LZX Reference is going to look stupid if the dataset tag is
 * not linked to the Dataset API.
 * In short, this allows for intuitive linking for the docs ONLY. LFC does not
 * use this array at all.
ConstructorMapDocs = {
    datasource : "Datasource",
    dataset : "LzDataset"
};
*/

TagFunctionMap = {
    dataset: "setDatasetType"
}

/* Create an object from an XML element.  Operates recursively on the
 * element and its children, whose instances which are added to the
 * instance created from the element.  If the element has an "id"
 * attribute, make it available as a global variable with this name.
 *
 * The name of this function must match the value of
 * org.openlaszlo.ic.CompilationEnvironment.VIEW_INSTANTIATION_FNAME. */

function LzInstantiateView(e, tn)
{
    //LzInstantiateSubviews(canvas, e);

    // For now, intercept traits and directly construct an LzTrait object with
    // the given attributes
    if ( e.name == "trait" ){
        new LzTrait( e );
        return;
    }

    //fix tags
    LzFixTags( e );

    if ( typeof(tn) == "undefined" ){
        tn = 1;
    }
    canvas.initiatorAddNode( e  , tn );
}

function LzFixTags ( e ){
    // If this code is changed, the code in ClassNode.java should be
    // changed too.
    if ( _root.ConstructorMap[ e.name ] !=null ){
        e.name = _root.ConstructorMap[ e.name ];
    }
    if ( e.id != null )
        e.attrs.id = e.id; // Does id really still some in this way?

    var i = 0;
    while ( i < e.children.length ){
        var c = e.children[ i ];

        if ( c.name == 'datapath' ){
            //remove from child array
            if ( !e.attrs ){
                e.attrs = {};
            }
            c.name =_root.ConstructorMap[ c.name ];
            e.attrs.$datapath = c;
            e.children.splice( i , 1 );
            continue;
        }

        LzFixTags( e.children[ i++ ] );
    }
}

function lzAddLocalData(name, d) {
    return new LzDataset(null, {name: name, initialdata: d });
}

/******************************************************************************
 * LzReplicationManager.as
 *****************************************************************************/

//* A_LZ_COPYRIGHT_BEGIN ******************************************************
//* Copyright 2001-2007 Laszlo Systems, Inc.  All Rights Reserved.            *
//* Use is subject to license terms.                                          *
//* A_LZ_COPYRIGHT_END ********************************************************

/* An application source file contains XML that describes a view that
 * will be instantiated when the application is loaded.  These XML
 * elements are called view templates, and occur either directly
 * within the document root, or within another view template.  A root
 * view template is a view template that occurs directly within the
 * document root.
 *
 * The interface compiler compiles each root view template into
 * ActionScript bytecodes that, when executed, create an instance of
 * the object that the XML element describes.  It does this by
 * appending to the output file instructions to push a succint
 * description of the XML hierarchy onto the stack, followed by a call
 * to LzInstantiateView (below) with the runtime representation of the
 * root view template as its argument.
 *
 * The format of the runtime representation is documented in the
 * Javadoc for org.openlaszlo.ic.ScriptCompiler.xmlToScript.  In
 * brief, an XML element is compiled to a runtime object with the
 * following attributes:
 *   tagName: The element, or tag name (e.g. "window")
 *   attrs: An object whose properties are attributes, e.g.
 *     {title: "Contacts", x: 10, y: 20}
 *   children: An array of child elements.
 *
 * --- ows
 */

/* A map of element names, to functions that create instances of the
 * appropriate type. */
    // none of these have been tested except window
//  dataSource: function (args) {return new DataSource(_root, args.source);}
//  gridView: function (args) {return new lzGridView(args);}
//  menu: function (args) {return new lzMenu(args, []);}
    //view: function (args) {return new lzView(args);}
ConstructorMap = {
    agent: "LzAgent",
    animator: "LzAnimator" ,
    animatorgroup: "LzAnimatorGroup" ,
    canvas: "LzCanvas" ,
    centerconstraint: "LzCenterConstraint",
    command: "LzCommand",
    connection: "LzConnection",
    connectiondatasource: "LzConnectionDatasource",
    datapath: "LzDatapath",
    datapointer: "LzDatapointer",
    dataselectionmanager: "LzDataSelectionManager" ,
    dataset: "LzDataset",
    datasource: "LzHTTPDatasource",
    drawview: "LzDrawView",
    debug: "LzDebugWindow",
    floormodifier: "LzFloorModifier" ,
    httpdatasource: "LzHTTPDatasource",
    'import': "LzLibrary",
    inputtext: "LzInputText" ,
    javadatasource: "LzJavaDatasource",
    layout: "LzLayout" ,
    limitmodifier: "LzLimitModifier" ,
    mappingview: "LzPagingView" ,
    node: "LzNode",
    params: "LzParam",
    propconstraint: "LzViewPropConstraint" ,
    propmodifier: "LzPropertyModifier" ,
    script: "LzScript",
    selectionmanager: "LzSelectionManager" ,
    state: "LzState",
    text:  "LzText",
    userclass: "LzUserClass",
    view:  "LzView",
    viewtemplate: "LzViewTemplate"
};

/* This constructor map overwrites the regular ConstructorMap *just* for the
 * doc generation. e.g. dataset cannot have an API (the LFC would break), but
 * the generated LZX Reference is going to look stupid if the dataset tag is
 * not linked to the Dataset API.
 * In short, this allows for intuitive linking for the docs ONLY. LFC does not
 * use this array at all.
ConstructorMapDocs = {
    datasource : "Datasource",
    dataset : "LzDataset"
};
*/

TagFunctionMap = {
    dataset: "setDatasetType"
}

/* Create an object from an XML element.  Operates recursively on the
 * element and its children, whose instances which are added to the
 * instance created from the element.  If the element has an "id"
 * attribute, make it available as a global variable with this name.
 *
 * The name of this function must match the value of
 * org.openlaszlo.ic.CompilationEnvironment.VIEW_INSTANTIATION_FNAME. */

function LzInstantiateView(e, tn)
{
    //LzInstantiateSubviews(canvas, e);

    // For now, intercept traits and directly construct an LzTrait object with
    // the given attributes
    if ( e.name == "trait" ){
        new LzTrait( e );
        return;
    }

    //fix tags
    LzFixTags( e );

    if ( typeof(tn) == "undefined" ){
        tn = 1;
    }
    canvas.initiatorAddNode( e  , tn );
}

function LzFixTags ( e ){
    // If this code is changed, the code in ClassNode.java should be
    // changed too.
    if ( _root.ConstructorMap[ e.name ] !=null ){
        e.name = _root.ConstructorMap[ e.name ];
    }
    if ( e.id != null )
        e.attrs.id = e.id; // Does id really still some in this way?

    var i = 0;
    while ( i < e.children.length ){
        var c = e.children[ i ];

        if ( c.name == 'datapath' ){
            //remove from child array
            if ( !e.attrs ){
                e.attrs = {};
            }
            c.name =_root.ConstructorMap[ c.name ];
            e.attrs.$datapath = c;
            e.children.splice( i , 1 );
            continue;
        }

        LzFixTags( e.children[ i++ ] );
    }
}

function lzAddLocalData(name, d) {
    return new LzDataset(canvas, {name: name, initialdata: d });
}

Change 20070212-hqm-2 by hqm@IBM-112E6A12815 on 2007-02-12 17:21:57 EST
    in /cygdrive/c/users/hqm/openlaszlo/trunk/WEB-INF/lps/lfc

Summary:  fix for inifinte loop in debugger check on datasets

New Features:

Bugs Fixed: infinte loop in debug mode

Technical Reviewer: pkang (pending)
QA Reviewer: (pending)
Doc Reviewer: (pending)

Documentation:

Release Notes:

Details:

Tests:

git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@3795 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c


package org.openforis.collect.i18n {
	import mx.resources.ResourceManager;

	/**
	 * @author Mino Togna
	 * */
	public class Message {

		public function Message() {
		}

		public static function get(resource:String, parameters:Array=null, bundle:String="messages"):String {
			return ResourceManager.getInstance().getString(bundle, resource, parameters);
		}
	}
}

package org.openforis.collect.i18n {
	import mx.resources.ResourceManager;

	/**
	 * @author Mino Togna
	 * @author S. Ricci
	 * */
	public class Message {

		public function Message() {
		}

		public static function get(resource:String, parameters:Array=null, bundle:String="messages"):String {
			var message:String = ResourceManager.getInstance().getString(bundle, resource, parameters);
			if(message != null) {
				return message;
			} else {
				return resource;
			}
		}
	}
}

Return resource name instead of null if not found