// vim: tabstop=4 shiftwidth=4

// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
// Copyright (c) 2012 , Yang Bo. All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.

package com.netease.protobuf {
	import flash.errors.*
	import flash.utils.*
	/**
	 * @private
	 */
	public final class ReadUtils {
		public static function skip(input:IDataInput, wireType:uint):void {
			switch (wireType) {
			case WireType.VARINT:
				while (input.readUnsignedByte() > 0x80) {}
				break
			case WireType.FIXED_64_BIT:
				input.readInt()
				input.readInt()
				break
			case WireType.LENGTH_DELIMITED:
				for (var i:uint = read$TYPE_UINT32(input); i != 0; i--) {
					input.readByte()
				}
				break
			case WireType.FIXED_32_BIT:
				input.readInt()
				break
			default:
				throw new IOError("Invalid wire type: " + wireType)
			}
		}
		public static function read$TYPE_DOUBLE(input:IDataInput):Number {
			return input.readDouble()
		}
		public static function read$TYPE_FLOAT(input:IDataInput):Number {
			return input.readFloat()
		}
		public static function read$TYPE_INT64(input:IDataInput):Int64 {
			const result:Int64 = new Int64
			var b:uint
			var i:uint = 0
			for (;; i += 7) {
				b = input.readUnsignedByte()
				if (i == 28) {
					break
				} else {
					if (b >= 0x80) {
						result.low |= ((b & 0x7f) << i)
					} else {
						result.low |= (b << i)
						return result
					}
				}
			}
			if (b >= 0x80) {
				b &= 0x7f
				result.low |= (b << i)
				result.high = b >>> 4
			} else {
				result.low |= (b << i)
				result.high = b >>> 4
				return result
			}
			for (i = 3;; i += 7) {
				b = input.readUnsignedByte()
				if (i < 32) {
					if (b >= 0x80) {
						result.high |= ((b & 0x7f) << i)
					} else {
						result.high |= (b << i)
						break
					}
				}
			}
			return result
		}
		public static function read$TYPE_UINT64(input:IDataInput):UInt64 {
			const result:UInt64 = new UInt64
			var b:uint
			var i:uint = 0
			for (;; i += 7) {
				b = input.readUnsignedByte()
				if (i == 28) {
					break
				} else {
					if (b >= 0x80) {
						result.low |= ((b & 0x7f) << i)
					} else {
						result.low |= (b << i)
						return result
					}
				}
			}
			if (b >= 0x80) {
				b &= 0x7f
				result.low |= (b << i)
				result.high = b >>> 4
			} else {
				result.low |= (b << i)
				result.high = b >>> 4
				return result
			}
			for (i = 3;; i += 7) {
				b = input.readUnsignedByte()
				if (i < 32) {
					if (b >= 0x80) {
						result.high |= ((b & 0x7f) << i)
					} else {
						result.high |= (b << i)
						break
					}
				}
			}
			return result
		}
		public static function read$TYPE_INT32(input:IDataInput):int {
			return int(read$TYPE_UINT32(input))
		}
		public static function read$TYPE_FIXED64(input:IDataInput):UInt64 {
			const result:UInt64 = new UInt64
			result.low = input.readUnsignedInt()
			result.high = input.readUnsignedInt()
			return result
		}
		public static function read$TYPE_FIXED32(input:IDataInput):uint {
			return input.readUnsignedInt()
		}
		public static function read$TYPE_BOOL(input:IDataInput):Boolean {
			return read$TYPE_UINT32(input) != 0
		}
		public static function read$TYPE_STRING(input:IDataInput):String {
			const length:uint = read$TYPE_UINT32(input)
			return input.readUTFBytes(length)
		}
		public static function read$TYPE_BYTES(input:IDataInput):ByteArray {
			const result:ByteArray = new ByteArray
			const length:uint = read$TYPE_UINT32(input)
			if (length > 0) {
				input.readBytes(result, 0, length)
			}
			return result
		}
		public static function read$TYPE_UINT32(input:IDataInput):uint {
			var result:uint = 0
			for (var i:uint = 0;; i += 7) {
				const b:uint = input.readUnsignedByte()
				if (i < 32) {
					if (b >= 0x80) {
						result |= ((b & 0x7f) << i)
					} else {
						result |= (b << i)
						break
					}
				} else {
					while (input.readUnsignedByte() >= 0x80) {}
					break
				}
			}
			return result
		}
		public static function read$TYPE_ENUM(input:IDataInput):int {
			return read$TYPE_INT32(input)
		}
		public static function read$TYPE_SFIXED32(input:IDataInput):int {
			return input.readInt()
		}
		public static function read$TYPE_SFIXED64(input:IDataInput):Int64 {
			const result:Int64 = new Int64
			result.low = input.readUnsignedInt()
			result.high = input.readInt()
			return result
		}
		public static function read$TYPE_SINT32(input:IDataInput):int {
			return ZigZag.decode32(read$TYPE_UINT32(input))
		}
		public static function read$TYPE_SINT64(input:IDataInput):Int64 {
			const result:Int64 = read$TYPE_INT64(input)
			const low:uint = result.low
			const high:uint = result.high
			result.low = ZigZag.decode64low(low, high)
			result.high = ZigZag.decode64high(low, high)
			return result
		}
		public static function read$TYPE_MESSAGE(input:IDataInput,
				message:Message):Message {
			const length:uint = read$TYPE_UINT32(input)
			if (input.bytesAvailable < length) {
				throw new IOError("Invalid message length: " + length)
			}
			const bytesAfterSlice:uint = input.bytesAvailable - length
			message.used_by_generated_code::readFromSlice(input, bytesAfterSlice)
			if (input.bytesAvailable != bytesAfterSlice) {
				throw new IOError("Invalid nested message")
			}
			return message
		}
		public static function readPackedRepeated(input:IDataInput,
				readFuntion:Function, value:Array):void {
			const length:uint = read$TYPE_UINT32(input)
			if (input.bytesAvailable < length) {
				throw new IOError("Invalid message length: " + length)
			}
			const bytesAfterSlice:uint = input.bytesAvailable - length
			while (input.bytesAvailable > bytesAfterSlice) {
				value.push(readFuntion(input))
			}
			if (input.bytesAvailable != bytesAfterSlice) {
				throw new IOError("Invalid packed repeated data")
			}
		}
	}
}

// vim: tabstop=4 shiftwidth=4

// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
// Copyright (c) 2012 , Yang Bo. All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.

package com.netease.protobuf {
	import flash.errors.*
	import flash.utils.*
	/**
	 * @private
	 */
	public final class ReadUtils {
		public static function skip(input:IDataInput, wireType:uint):void {
			switch (wireType) {
			case WireType.VARINT:
				while (input.readUnsignedByte() >= 0x80) {}
				break
			case WireType.FIXED_64_BIT:
				input.readInt()
				input.readInt()
				break
			case WireType.LENGTH_DELIMITED:
				for (var i:uint = read$TYPE_UINT32(input); i != 0; i--) {
					input.readByte()
				}
				break
			case WireType.FIXED_32_BIT:
				input.readInt()
				break
			default:
				throw new IOError("Invalid wire type: " + wireType)
			}
		}
		public static function read$TYPE_DOUBLE(input:IDataInput):Number {
			return input.readDouble()
		}
		public static function read$TYPE_FLOAT(input:IDataInput):Number {
			return input.readFloat()
		}
		public static function read$TYPE_INT64(input:IDataInput):Int64 {
			const result:Int64 = new Int64
			var b:uint
			var i:uint = 0
			for (;; i += 7) {
				b = input.readUnsignedByte()
				if (i == 28) {
					break
				} else {
					if (b >= 0x80) {
						result.low |= ((b & 0x7f) << i)
					} else {
						result.low |= (b << i)
						return result
					}
				}
			}
			if (b >= 0x80) {
				b &= 0x7f
				result.low |= (b << i)
				result.high = b >>> 4
			} else {
				result.low |= (b << i)
				result.high = b >>> 4
				return result
			}
			for (i = 3;; i += 7) {
				b = input.readUnsignedByte()
				if (i < 32) {
					if (b >= 0x80) {
						result.high |= ((b & 0x7f) << i)
					} else {
						result.high |= (b << i)
						break
					}
				}
			}
			return result
		}
		public static function read$TYPE_UINT64(input:IDataInput):UInt64 {
			const result:UInt64 = new UInt64
			var b:uint
			var i:uint = 0
			for (;; i += 7) {
				b = input.readUnsignedByte()
				if (i == 28) {
					break
				} else {
					if (b >= 0x80) {
						result.low |= ((b & 0x7f) << i)
					} else {
						result.low |= (b << i)
						return result
					}
				}
			}
			if (b >= 0x80) {
				b &= 0x7f
				result.low |= (b << i)
				result.high = b >>> 4
			} else {
				result.low |= (b << i)
				result.high = b >>> 4
				return result
			}
			for (i = 3;; i += 7) {
				b = input.readUnsignedByte()
				if (i < 32) {
					if (b >= 0x80) {
						result.high |= ((b & 0x7f) << i)
					} else {
						result.high |= (b << i)
						break
					}
				}
			}
			return result
		}
		public static function read$TYPE_INT32(input:IDataInput):int {
			return int(read$TYPE_UINT32(input))
		}
		public static function read$TYPE_FIXED64(input:IDataInput):UInt64 {
			const result:UInt64 = new UInt64
			result.low = input.readUnsignedInt()
			result.high = input.readUnsignedInt()
			return result
		}
		public static function read$TYPE_FIXED32(input:IDataInput):uint {
			return input.readUnsignedInt()
		}
		public static function read$TYPE_BOOL(input:IDataInput):Boolean {
			return read$TYPE_UINT32(input) != 0
		}
		public static function read$TYPE_STRING(input:IDataInput):String {
			const length:uint = read$TYPE_UINT32(input)
			return input.readUTFBytes(length)
		}
		public static function read$TYPE_BYTES(input:IDataInput):ByteArray {
			const result:ByteArray = new ByteArray
			const length:uint = read$TYPE_UINT32(input)
			if (length > 0) {
				input.readBytes(result, 0, length)
			}
			return result
		}
		public static function read$TYPE_UINT32(input:IDataInput):uint {
			var result:uint = 0
			for (var i:uint = 0;; i += 7) {
				const b:uint = input.readUnsignedByte()
				if (i < 32) {
					if (b >= 0x80) {
						result |= ((b & 0x7f) << i)
					} else {
						result |= (b << i)
						break
					}
				} else {
					while (input.readUnsignedByte() >= 0x80) {}
					break
				}
			}
			return result
		}
		public static function read$TYPE_ENUM(input:IDataInput):int {
			return read$TYPE_INT32(input)
		}
		public static function read$TYPE_SFIXED32(input:IDataInput):int {
			return input.readInt()
		}
		public static function read$TYPE_SFIXED64(input:IDataInput):Int64 {
			const result:Int64 = new Int64
			result.low = input.readUnsignedInt()
			result.high = input.readInt()
			return result
		}
		public static function read$TYPE_SINT32(input:IDataInput):int {
			return ZigZag.decode32(read$TYPE_UINT32(input))
		}
		public static function read$TYPE_SINT64(input:IDataInput):Int64 {
			const result:Int64 = read$TYPE_INT64(input)
			const low:uint = result.low
			const high:uint = result.high
			result.low = ZigZag.decode64low(low, high)
			result.high = ZigZag.decode64high(low, high)
			return result
		}
		public static function read$TYPE_MESSAGE(input:IDataInput,
				message:Message):Message {
			const length:uint = read$TYPE_UINT32(input)
			if (input.bytesAvailable < length) {
				throw new IOError("Invalid message length: " + length)
			}
			const bytesAfterSlice:uint = input.bytesAvailable - length
			message.used_by_generated_code::readFromSlice(input, bytesAfterSlice)
			if (input.bytesAvailable != bytesAfterSlice) {
				throw new IOError("Invalid nested message")
			}
			return message
		}
		public static function readPackedRepeated(input:IDataInput,
				readFuntion:Function, value:Array):void {
			const length:uint = read$TYPE_UINT32(input)
			if (input.bytesAvailable < length) {
				throw new IOError("Invalid message length: " + length)
			}
			const bytesAfterSlice:uint = input.bytesAvailable - length
			while (input.bytesAvailable > bytesAfterSlice) {
				value.push(readFuntion(input))
			}
			if (input.bytesAvailable != bytesAfterSlice) {
				throw new IOError("Invalid packed repeated data")
			}
		}
	}
}

Fix #35

Fix #35


/**
 * User: MerlinDS
 * Date: 18.07.2014
 * Time: 17:42
 */
package com.merlinds.miracle_tool.viewer {
	import com.bit101.components.List;
	import com.bit101.components.Window;
	import com.merlinds.debug.log;
	import com.merlinds.miracle.Miracle;
	import com.merlinds.miracle.animations.Animation;
	import com.merlinds.miracle.display.MiracleImage;
	import com.merlinds.miracle.utils.Asset;
	import com.merlinds.miracle.utils.MafReader;
	import com.merlinds.miracle_tool.models.AppModel;

	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;

	[SWF(backgroundColor="0x333333", frameRate=60)]
	public class ViewerView extends Sprite {

		private var _model:AppModel;
		private var _assets:Vector.<Asset>;
		private var _window:Window;
		private var _name:String;

		public function ViewerView(model:AppModel = null) {
			super();
			_model = model;
			if(_model == null){
				_model = new AppModel();
			}

			this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
		}
		//==============================================================================
		//{region							PUBLIC METHODS
		//} endregion PUBLIC METHODS ===================================================

		//==============================================================================
		//{region						PRIVATE\PROTECTED METHODS
		private function initialize(event:Event):void {
			this.removeEventListener(event.type, this.initialize);
			this.stage.scaleMode = StageScaleMode.NO_SCALE;
			this.stage.align = StageAlign.TOP_LEFT;
			Miracle.start(this.stage, this.createHandler, true);
		}

		private function choseAnimation():void {
			//find animation asset and add all of animations to chose list
			var n:int = _assets.length;
			for(var i:int = 0; i < n; i++){
				var asset:Asset = _assets[i];
				if(asset.type == Asset.TIMELINE_TYPE){
					//parse output
					_window = new Window(this, 0, 0, "Chose mesh");
					var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
					_window.x = this.stage.stageWidth - _window.width;
					list.addEventListener(Event.SELECT, this.selectAnimationHandler);
				}
			}
		}

		[Inline]
		private function getAnimations(bytes:ByteArray):Array {
			var result:Array = [];
			var reader:MafReader = new MafReader();
			reader.execute(bytes);
			var animations:Vector.<Animation> = reader.animations;
			for each(var animation:Animation in animations){
				result.push(animation.name);
			}
			return result;
		}
		//} endregion PRIVATE\PROTECTED METHODS ========================================

		//==============================================================================
		//{region							EVENTS HANDLERS
		private function createHandler(animation:Boolean = false):void {
			//TODO: Show view if it exit
			if(animation || _model.viewerInput == null){
				_model.viewerInput = _model.lastFileDirection;
				_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
				_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
						+ "file that you want to view");
			}
		}

		private function selectFileHandler(event:Event):void {
			_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
			_model.lastFileDirection = _model.viewerInput.parent;
			var byteArray:ByteArray = new ByteArray();
			var stream:FileStream = new FileStream();
			stream.open(_model.viewerInput, FileMode.READ);
			stream.readBytes(byteArray);
			stream.close();
			//parse
			if(_assets == null)_assets = new <Asset>[];
			var asset:Asset = new Asset(_model.viewerInput.name, byteArray);
			if(asset.type == Asset.TIMELINE_TYPE){
				_name = asset.name;
			}
			_assets.push(asset);
//			var name:String = asset.name;
			if(_assets.length > 1){
				this.choseAnimation();
				Miracle.createScene(_assets, 1);
				Miracle.currentScene.createImage(_name)
						.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
				Miracle.resume();
			}else{
				this.createHandler(true);
			}
		}

		private function selectAnimationHandler(event:Event):void {
			var list:List = event.target as List;
			//add animation to miracle
			var name:String = list.selectedItem.toString();
			log(this, "selectAnimationHandler", name);
		}

		private function imageAddedToStage(event:Event):void {
			var target:MiracleImage = event.target as MiracleImage;
			target.moveTO(
					this.stage.stageWidth - target.width >> 1,
					this.stage.stageHeight - target.height >> 1
			);
		}
		//} endregion EVENTS HANDLERS ==================================================

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

/**
 * User: MerlinDS
 * Date: 18.07.2014
 * Time: 17:42
 */
package com.merlinds.miracle_tool.viewer {
	import com.bit101.components.List;
	import com.bit101.components.Window;
	import com.merlinds.debug.log;
	import com.merlinds.miracle.Miracle;
	import com.merlinds.miracle.animations.Animation;
	import com.merlinds.miracle.display.MiracleDisplayObject;
	import com.merlinds.miracle.display.MiracleImage;
	import com.merlinds.miracle.utils.Asset;
	import com.merlinds.miracle.utils.MafReader;
	import com.merlinds.miracle_tool.models.AppModel;

	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;

	[SWF(backgroundColor="0x333333", frameRate=60)]
	public class ViewerView extends Sprite {

		private var _model:AppModel;
		private var _assets:Vector.<Asset>;
		private var _window:Window;
		private var _name:String;

		public function ViewerView(model:AppModel = null) {
			super();
			_model = model;
			if(_model == null){
				_model = new AppModel();
			}

			this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
		}
		//==============================================================================
		//{region							PUBLIC METHODS
		//} endregion PUBLIC METHODS ===================================================

		//==============================================================================
		//{region						PRIVATE\PROTECTED METHODS
		private function initialize(event:Event):void {
			this.removeEventListener(event.type, this.initialize);
			this.stage.scaleMode = StageScaleMode.NO_SCALE;
			this.stage.align = StageAlign.TOP_LEFT;
			Miracle.start(this.stage, this.createHandler, true);
		}

		private function choseAnimation():void {
			//find animation asset and add all of animations to chose list
			var n:int = _assets.length;
			for(var i:int = 0; i < n; i++){
				var asset:Asset = _assets[i];
				if(asset.type == Asset.TIMELINE_TYPE){
					//parse output
					_window = new Window(this, 0, 0, "Chose mesh");
					var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
					_window.x = this.stage.stageWidth - _window.width;
					list.addEventListener(Event.SELECT, this.selectAnimationHandler);
				}
			}
		}

		[Inline]
		private function getAnimations(bytes:ByteArray):Array {
			var result:Array = [];
			var reader:MafReader = new MafReader();
			reader.execute(bytes);
			var animations:Vector.<Animation> = reader.animations;
			for each(var animation:Animation in animations){
				result.push(animation.name);
			}
			return result;
		}
		//} endregion PRIVATE\PROTECTED METHODS ========================================

		//==============================================================================
		//{region							EVENTS HANDLERS
		private function createHandler(animation:Boolean = false):void {
			//TODO: Show view if it exit
			if(animation || _model.viewerInput == null){
				_model.viewerInput = _model.lastFileDirection;
				_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
				_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
						+ "file that you want to view");
			}
		}

		private function selectFileHandler(event:Event):void {
			_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
			_model.lastFileDirection = _model.viewerInput.parent;
			var byteArray:ByteArray = new ByteArray();
			var stream:FileStream = new FileStream();
			stream.open(_model.viewerInput, FileMode.READ);
			stream.readBytes(byteArray);
			stream.close();
			//parse
			if(_assets == null)_assets = new <Asset>[];
			var asset:Asset = new Asset(_model.viewerInput.name, byteArray);
			if(asset.type == Asset.TIMELINE_TYPE){
				_name = asset.name;
			}
			_assets.push(asset);
//			var name:String = asset.name;
			if(_assets.length > 1){
				this.choseAnimation();
				Miracle.createScene(_assets, 1);
				Miracle.resume();
			}else{
				this.createHandler(true);
			}
		}

		private function selectAnimationHandler(event:Event):void {
			var list:List = event.target as List;
			//add animation to miracle
			var animation:String = list.selectedItem.toString();
			log(this, "selectAnimationHandler", animation);
			Miracle.currentScene.createAnimation(_name, animation)
					.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
		}

		private function imageAddedToStage(event:Event):void {
			var target:MiracleDisplayObject = event.target as MiracleDisplayObject;
			target.moveTO(
					this.stage.stageWidth - target.width >> 1,
					this.stage.stageHeight - target.height >> 1
			);
		}
		//} endregion EVENTS HANDLERS ==================================================

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

Add animation instance and fix viewer for this


package com.kaltura.hls.m2ts
{
    import flash.utils.ByteArray;
    import flash.net.ObjectEncoding;
    import flash.utils.ByteArray;
    import flash.utils.Endian;
    import flash.utils.IDataInput;
    import flash.utils.IDataOutput;

    /**
     * NALU processing utilities.
     */
    public class NALUProcessor
    {
        private static var ppsList:Vector.<ByteArray> = new Vector.<ByteArray>;
        private static var spsList:Vector.<ByteArray> = new Vector.<ByteArray>;

        private static function sortSPS(a:ByteArray, b:ByteArray):int
        {
            var ourEg:ExpGolomb = new ExpGolomb(a);
            ourEg.readBits(28);
            var Id_a:int = ourEg.readUE();

            ourEg = new ExpGolomb(b);
            ourEg.readBits(28);
            var Id_b:int = ourEg.readUE();

            return Id_a - Id_b;
        }

        private static function sortPPS(a:ByteArray, b:ByteArray):int
        {
            var ourEg:ExpGolomb = new ExpGolomb(a);
            ourEg.readBits(8);
            var Id_a:int = ourEg.readUE();

            ourEg = new ExpGolomb(b);
            ourEg.readBits(8);
            var Id_b:int = ourEg.readUE();

            return Id_a - Id_b;
        }

        /**
         * Actually perform serialization of the AVCC.
         */
        private static function serializeAVCC():ByteArray
        {
            // Some sanity checking, easier than special casing loops.
            if(ppsList == null)
                ppsList = new Vector.<ByteArray>();
            if(spsList == null)
                spsList = new Vector.<ByteArray>();

            if(ppsList.length == 0 || spsList.length == 0)
                return null;

            var avcc:ByteArray = new ByteArray();
            var cursor:uint = 0;

            avcc[cursor++] = 0x00; // stream ID
            avcc[cursor++] = 0x00;
            avcc[cursor++] = 0x00;

            avcc[cursor++] = 0x01; // version
            avcc[cursor++] = spsList[0][1]; // profile
            avcc[cursor++] = spsList[0][2]; // compatiblity
            avcc[cursor++] = spsList[0][3]; // level
            avcc[cursor++] = 0xFC | 3; // nalu marker length size - 1, we're using 4 byte ints.
            avcc[cursor++] = 0xE0 | spsList.length; // reserved bit + SPS count

            spsList.sort(sortSPS);

            for(var i:int=0; i<spsList.length; i++)
            {
                // Debug dump the SPS
                var spsLength:uint = spsList[i].length;

                //trace("SPS #" + i + " profile " + spsList[i][1] + "   " + Hex.fromArray(spsList[i], true));

                var eg:ExpGolomb = new ExpGolomb(spsList[i]);
                // constraint_set[0-5]_flag, u(1), reserved_zero_2bits u(2), level_idc u(8)
                eg.readBits(16);
                //trace("Saw id " + eg.readUE());

                avcc.position = cursor;
                spsList[i].position = 0;
                avcc.writeShort(spsLength);
                avcc.writeBytes(spsList[i], 0, spsLength);
                cursor += spsLength + 2;
            }

            avcc[cursor++] = ppsList.length; // PPS count.

            ppsList.sort(sortPPS);

            for(i=0; i<ppsList.length; i++)
            {
                var ppsLength:uint = ppsList[i].length;
                //trace("PPS length #" + i + " is " + ppsLength + "   " + Hex.fromArray(ppsList[i], true));
                avcc.position = cursor;
                ppsList[i].position = 0;
                avcc.writeShort(ppsLength);
                avcc.writeBytes(ppsList[i], 0, ppsLength);
                cursor += ppsLength + 2;
            }

            return avcc;
        }

        /**
         * Update our internal list of SPS entries, merging as needed.
         */
        private static function setAVCSPS(bytes:ByteArray, cursor:uint, length:uint):void
        {
            var sps:ByteArray = new ByteArray();
            sps.writeBytes(bytes, cursor, length);

            var ourEg:ExpGolomb = new ExpGolomb(sps);
            ourEg.readBits(16);
            var ourId:int = ourEg.readUE();

            // If not present in list add it!
            var found:Boolean = false;
            for(var i:int=0; i<spsList.length; i++)
            {
                // If it matches our ID, replace it.
                var eg:ExpGolomb = new ExpGolomb(spsList[i]);
                eg.readBits(16);
                var foundId:int = eg.readUE();

                if(foundId == ourId)
                {
                    //trace("Got SPS match for " + foundId + "!");
                    spsList[i] = sps;
                    return;
                }

                if(spsList[i].length != length)
                    continue;

                // If identical don't append to list.
                for(var j:int=0; j<spsList[i].length && j<sps.length; j++)
                    if(spsList[i][j] != sps[j])
                        continue;

                found = true;
                break;
            }

            // Maybe we do have to add it!
            if(!found)
                spsList.push(sps);
        }

        /**
         * Update our internal list of PPS entries, merging as needed.
         */
        private static function setAVCPPS(bytes:ByteArray, cursor:uint, length:uint):void
        {
            var pps:ByteArray = new ByteArray;
            pps.writeBytes(bytes, cursor, length);

            var ourEg:ExpGolomb = new ExpGolomb(pps);
            var ourId:int = ourEg.readUE();

            // If not present in list add it!
            var found:Boolean = false;
            for(var i:int=0; i<ppsList.length; i++)
            {
                // If it matches our ID, replace it.
                var eg:ExpGolomb = new ExpGolomb(ppsList[i]);
                var foundId:int = eg.readUE();

                if(foundId == ourId)
                {
                    //trace("Got PPS match for " + foundId + "!");
                    ppsList[i] = pps;
                    return;
                }

                if(ppsList[i].length != length)
                    continue;

                // If identical don't append to list.
                for(var j:int=0; j<ppsList[i].length && j<pps.length; j++)
                    if(ppsList[i][j] != pps[j])
                        continue;

                found = true;
                break;
            }

            // Maybe we do have to add it!
            if(!found)
                ppsList.push(pps);
        }

        /**
         * Given a buffer containing NALUs, walk through them and call callback
         * with the extends of each. It's given in order the buffer, start, and
         * length of each found NALU.
         */
        public static function walkNALUs(bytes:ByteArray, cursor:int, callback:Function, flushing:Boolean = false):void
        {
            var originalStart:int = int(cursor);
            var start:int = int(cursor);
            var end:int;
            var naluLength:uint;

            start = NALU.scan(bytes, start, false);
            while(start >= 0)
            {
                end = NALU.scan(bytes, start, true);

                if(end >= 0)
                {
                    naluLength = end - start;
                }
                else if(flushing)
                {
                    naluLength = bytes.length - start;
                }
                else
                {
                    break;
                }

                callback(bytes, uint(start), naluLength);

                cursor = start + naluLength;
                start = NALU.scan(bytes, cursor, false);
            }
        }

        /**
         * NALUs use 0x000001 to indicate start codes. However, data may need
         * to contain this code. In this case an 0x03 is inserted to break up
         * the start code pattern. This function strips such bytes.
         */
        public static function stripEmulationBytes(buffer:ByteArray, cursor:uint, length:uint):ByteArray
        {
            var tmp:ByteArray = new ByteArray();
            for(var i:int=cursor; i<cursor+length; i++)
            {
                if(buffer[i] == 0x03 && (i-cursor) >= 3)
                {
                    if(buffer[i-1] == 0x00 && buffer[i-2] == 0x00)
                    {
                        //trace("SKIPPING EMULATION BYTE @ " + i);
                        continue;
                    }
                }

                tmp.writeByte(buffer[i]);
            }

            return tmp;
        }

        private static function extractAVCCInner(bytes:ByteArray, cursor:uint, length:uint):void
        {
            // If we need to piggyback a callback, do it now.
            if(activeCallback != null)
                activeCallback(bytes, cursor, length);

            // What's the type?
            var naluType:uint = bytes[cursor] & 0x1f;
            if(naluType == 7)
            {
                // Handle SPS
                var spsStripped:ByteArray = stripEmulationBytes(bytes, cursor, length);
                setAVCSPS(spsStripped, 0, spsStripped.length)
            }
            else if(naluType == 8)
            {
                // Handle PPS
                var ppsStripped:ByteArray = stripEmulationBytes(bytes, cursor, length);
                setAVCPPS(ppsStripped, 0, ppsStripped.length)
            }
        }

        private static var activeCallback:Function = null;

        public static function startAVCCExtraction():void
        {
            spsList = new Vector.<ByteArray>();
            ppsList = new Vector.<ByteArray>();
        }

        public static function pushAVCData(unit:NALU):void
        {
            // Go through each buffer and find all the SPS/PPS info.
            activeCallback = null;
            walkNALUs(unit.buffer, 0, extractAVCCInner, true)
        }

        /**
         * Scan a set of NALUs and come up with an AVCC record.
         */
        public static function extractAVCC(unit:NALU, perNaluCallback:Function):ByteArray
        {
            // Go through each buffer and find all the SPS/PPS info.
            if(unit)
            {
                activeCallback = perNaluCallback;
                walkNALUs(unit.buffer, 0, extractAVCCInner, true)
                activeCallback = null;
            }

            // Generate and return the AVCC.
            return serializeAVCC();
        }
    }
}

package com.kaltura.hls.m2ts
{
    import flash.utils.ByteArray;
    import flash.net.ObjectEncoding;
    import flash.utils.ByteArray;
    import flash.utils.Endian;
    import flash.utils.IDataInput;
    import flash.utils.IDataOutput;
    //import com.hurlant.util.Hex;

    /**
     * NALU processing utilities.
     */
    public class NALUProcessor
    {
        private static var ppsList:Vector.<ByteArray> = new Vector.<ByteArray>;
        private static var spsList:Vector.<ByteArray> = new Vector.<ByteArray>;

        private static function sortSPS(a:ByteArray, b:ByteArray):int
        {
            var ourEg:ExpGolomb = new ExpGolomb(a);
            ourEg.readBits(8);
            ourEg.readBits(24);
            var Id_a:int = ourEg.readUE();

            ourEg = new ExpGolomb(b);
            ourEg.readBits(8);
            ourEg.readBits(24);
            var Id_b:int = ourEg.readUE();

            return Id_a - Id_b;
        }

        private static function sortPPS(a:ByteArray, b:ByteArray):int
        {
            var ourEg:ExpGolomb = new ExpGolomb(a);
            ourEg.readBits(8);
            var Id_a:int = ourEg.readUE();

            ourEg = new ExpGolomb(b);
            ourEg.readBits(8);
            var Id_b:int = ourEg.readUE();

            return Id_a - Id_b;
        }

        /**
         * Actually perform serialization of the AVCC.
         */
        private static function serializeAVCC():ByteArray
        {
            // Some sanity checking, easier than special casing loops.
            if(ppsList == null)
                ppsList = new Vector.<ByteArray>();
            if(spsList == null)
                spsList = new Vector.<ByteArray>();

            if(ppsList.length == 0 || spsList.length == 0)
                return null;

            var avcc:ByteArray = new ByteArray();
            var cursor:uint = 0;

            avcc[cursor++] = 0x00; // stream ID
            avcc[cursor++] = 0x00;
            avcc[cursor++] = 0x00;

            avcc[cursor++] = 0x01; // version
            avcc[cursor++] = spsList[0][1]; // profile
            avcc[cursor++] = spsList[0][2]; // compatiblity
            avcc[cursor++] = spsList[0][3]; // level
            avcc[cursor++] = 0xFC | 3; // nalu marker length size - 1, we're using 4 byte ints.
            avcc[cursor++] = 0xE0 | spsList.length; // reserved bit + SPS count

            spsList.sort(sortSPS);

            for(var i:int=0; i<spsList.length; i++)
            {
                // Debug dump the SPS
                var spsLength:uint = spsList[i].length;

                //trace("SPS #" + i + " profile=" + spsList[i][1] + "   " + Hex.fromArray(spsList[i], true));

                var eg:ExpGolomb = new ExpGolomb(spsList[i]);
                // constraint_set[0-5]_flag, u(1), reserved_zero_2bits u(2), level_idc u(8)
                eg.readBits(8);
                eg.readBits(24);
                //trace("Saw id " + eg.readUE());

                avcc.position = cursor;
                spsList[i].position = 0;
                avcc.writeShort(spsLength);
                avcc.writeBytes(spsList[i], 0, spsLength);
                cursor += spsLength + 2;
            }

            avcc[cursor++] = ppsList.length; // PPS count.

            ppsList.sort(sortPPS);

            for(i=0; i<ppsList.length; i++)
            {
                var ppsLength:uint = ppsList[i].length;
                //trace("PPS length #" + i + " is " + ppsLength + "   " + Hex.fromArray(ppsList[i], true));

                eg = new ExpGolomb(ppsList[i]);
                // constraint_set[0-5]_flag, u(1), reserved_zero_2bits u(2), level_idc u(8)
                eg.readBits(8);
                //trace("Saw id " + eg.readUE());

                avcc.position = cursor;
                ppsList[i].position = 0;
                avcc.writeShort(ppsLength);
                avcc.writeBytes(ppsList[i], 0, ppsLength);
                cursor += ppsLength + 2;
            }

            return avcc;
        }

        /**
         * Update our internal list of SPS entries, merging as needed.
         */
        private static function setAVCSPS(bytes:ByteArray, cursor:uint, length:uint):void
        {
            var sps:ByteArray = new ByteArray();
            sps.writeBytes(bytes, cursor, length);

            var ourEg:ExpGolomb = new ExpGolomb(sps);
            ourEg.readBits(8);
            ourEg.readBits(24);
            var ourId:int = ourEg.readUE();

            // If not present in list add it!
            for(var i:int=0; i<spsList.length; i++)
            {
                // If it matches our ID, replace it.
                var eg:ExpGolomb = new ExpGolomb(spsList[i]);
                eg.readBits(8);
                eg.readBits(24);
                var foundId:int = eg.readUE();

                if(foundId != ourId)
                    continue;

                //trace("Got SPS match for " + foundId + "!");
                spsList[i] = sps;
                return;
            }

            // Maybe we do have to add it!
            spsList.push(sps);
        }

        /**
         * Update our internal list of PPS entries, merging as needed.
         */
        private static function setAVCPPS(bytes:ByteArray, cursor:uint, length:uint):void
        {
            var pps:ByteArray = new ByteArray;
            pps.writeBytes(bytes, cursor, length);

            var ourEg:ExpGolomb = new ExpGolomb(pps);
            ourEg.readBits(8);
            var ourId:int = ourEg.readUE();

            // If not present in list add it!
            for(var i:int=0; i<ppsList.length; i++)
            {
                // If it matches our ID, replace it.
                var eg:ExpGolomb = new ExpGolomb(ppsList[i]);
                eg.readBits(8);
                var foundId:int = eg.readUE();

                if(foundId != ourId)
                    continue;

                //trace("Got PPS match for " + foundId + "!");
                ppsList[i] = pps;
                return;
            }

            // Maybe we do have to add it!
            ppsList.push(pps);
        }

        /**
         * Given a buffer containing NALUs, walk through them and call callback
         * with the extends of each. It's given in order the buffer, start, and
         * length of each found NALU.
         */
        public static function walkNALUs(bytes:ByteArray, cursor:int, callback:Function, flushing:Boolean = false):void
        {
            var originalStart:int = int(cursor);
            var start:int = int(cursor);
            var end:int;
            var naluLength:uint;

            start = NALU.scan(bytes, start, false);
            while(start >= 0)
            {
                end = NALU.scan(bytes, start, true);

                if(end >= 0)
                {
                    naluLength = end - start;
                }
                else if(flushing)
                {
                    naluLength = bytes.length - start;
                }
                else
                {
                    break;
                }

                callback(bytes, uint(start), naluLength);

                cursor = start + naluLength;
                start = NALU.scan(bytes, cursor, false);
            }
        }

        /**
         * NALUs use 0x000001 to indicate start codes. However, data may need
         * to contain this code. In this case an 0x03 is inserted to break up
         * the start code pattern. This function strips such bytes.
         */
        public static function stripEmulationBytes(buffer:ByteArray, cursor:uint, length:uint):ByteArray
        {
            var tmp:ByteArray = new ByteArray();
            for(var i:int=cursor; i<cursor+length; i++)
            {
                if(buffer[i] == 0x03 && (i-cursor) >= 3)
                {
                    if(buffer[i-1] == 0x00 && buffer[i-2] == 0x00)
                    {
                        //trace("SKIPPING EMULATION BYTE @ " + i);
                        continue;
                    }
                }

                tmp.writeByte(buffer[i]);
            }

            return tmp;
        }

        private static function extractAVCCInner(bytes:ByteArray, cursor:uint, length:uint):void
        {
            // If we need to piggyback a callback, do it now.
            if(activeCallback != null)
                activeCallback(bytes, cursor, length);

            // What's the type?
            var naluType:uint = bytes[cursor] & 0x1f;
            if(naluType == 7)
            {
                // Handle SPS
                var spsStripped:ByteArray = stripEmulationBytes(bytes, cursor, length);
                setAVCSPS(spsStripped, 0, spsStripped.length)
            }
            else if(naluType == 8)
            {
                // Handle PPS
                var ppsStripped:ByteArray = stripEmulationBytes(bytes, cursor, length);
                setAVCPPS(ppsStripped, 0, ppsStripped.length)
            }
        }

        private static var activeCallback:Function = null;

        public static function startAVCCExtraction():void
        {
            spsList = new Vector.<ByteArray>();
            ppsList = new Vector.<ByteArray>();
        }

        public static function pushAVCData(unit:NALU):void
        {
            // Go through each buffer and find all the SPS/PPS info.
            activeCallback = null;
            walkNALUs(unit.buffer, 0, extractAVCCInner, true)
        }

        /**
         * Scan a set of NALUs and come up with an AVCC record.
         */
        public static function extractAVCC(unit:NALU, perNaluCallback:Function):ByteArray
        {
            // Go through each buffer and find all the SPS/PPS info.
            if(unit)
            {
                activeCallback = perNaluCallback;
                walkNALUs(unit.buffer, 0, extractAVCCInner, true)
                activeCallback = null;
            }

            // Generate and return the AVCC.
            return serializeAVCC();
        }
    }
}

Fix SPS/PPS parsing.

Fix SPS/PPS parsing.


import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;

class menuColouridiomes extends MovieClip

	{
		public var cat, es, en ,fr:MovieClip;
		public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");

		function menuColourIdiomes ():Void

		{

		this.onRollOver = this.mOver;
		this.onRollOut = this.mOut;
		this.onRelease =this.mOver;

		}

		private function mOver()

		{

                arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc");

		}

		private function mOut()

		{

                arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc");

		}

	}

import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;

class menuColouridiomes extends MovieClip

	{
		public var cat, es, en ,fr:MovieClip;
		public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");

		function menuColourIdiomes ():Void

		{

		this.onRollOver = this.mOver;
		this.onRollOut = this.mOut;
		this.onRelease =this.mOver;

		}

		private function mOver()

		{
			var i:Number;

				for (var i = 0; i < arrayLang_arr.length; i++)
				{
	                		arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc");
	                	]

		}

		private function mOut()

		{
			var i:Number;

				for (var i = 0; i < arrayLang_arr.length; i++)
				{
			                arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc");
	                	}

		}

	}

Update menuColourIdiomes.as

Update menuColourIdiomes.as


////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed 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 com.esri.builder.controllers.supportClasses
{

import flash.net.LocalConnection;

import mx.logging.ILogger;
import mx.logging.Log;

public final class LocalConnectionDelegate
{
    private static const LOG:ILogger = Log.getLogger('com.esri.builder.controllers.supportClasses.LocalConnectionDelegate');
    private static const CNAME:String = '_flexViewer';

    private var m_localConnection:LocalConnection;

    private function get localConnection():LocalConnection
    {
        if (m_localConnection === null)
        {
            if (Log.isDebug())
            {
                LOG.debug("Acquiring local connection");
            }

            m_localConnection = new LocalConnection();
        }
        return m_localConnection;
    }

    public function setTitles(title:String, subtitle:String):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending titles changes: title {0} - subtitle {1}", title, subtitle);
        }

        localConnection.send(CNAME, 'setTitles', title, subtitle);
    }

    public function setLogo(value:String):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending logo changes {0}", value);
        }

        localConnection.send(CNAME, 'setLogo', value);
    }

    public function setTextColor(value:uint):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending text color changes {0}", value);
        }

        localConnection.send(CNAME, 'setTextColor', value);
    }

    public function setBackgroundColor(value:uint):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending background color changes {0}", value);
        }

        localConnection.send(CNAME, 'setBackgroundColor', value);
    }

    public function setRolloverColor(value:uint):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending rollover color changes {0}", value);
        }

        localConnection.send(CNAME, 'setRolloverColor', value);
    }

    public function setSelectionColor(value:uint):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending selection color changes {0}", value);
        }

        localConnection.send(CNAME, 'setSelectionColor', value);
    }

    public function setTitleColor(value:uint):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending title color changes {0}", value);
        }

        localConnection.send(CNAME, 'setTitleColor', value);
    }

    public function setLocale(localeChain:String):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending locale changes {0}", localeChain);
        }

        localConnection.send(CNAME, 'setLocale', localeChain);
    }

    public function setFontName(value:String):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending font name changes {0}", value);
        }

        localConnection.send(CNAME, 'setFontName', value);
    }

    public function setAppTitleFontName(value:String):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending app title font name changes {0}", value);
        }

        localConnection.send(CNAME, 'setAppTitleFontName', value);
    }

    public function setSubTitleFontName(value:String):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending subtitle font name changes {0}", value);
        }

        localConnection.send(CNAME, 'setSubTitleFontName', value);
    }

    public function setAlpha(value:Number):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending alpha changes {0}", value);
        }

        localConnection.send(CNAME, 'setAlpha', value);
    }

    public function setPredefinedStyles(value:Object):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending predefined changes {0}", value);
        }

        localConnection.send(CNAME, 'setPredefinedStyles', value);
    }
}
}

////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed 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 com.esri.builder.controllers.supportClasses
{

import flash.events.StatusEvent;
import flash.net.LocalConnection;

import mx.logging.ILogger;
import mx.logging.Log;

public final class LocalConnectionDelegate
{
    private static const LOG:ILogger = Log.getLogger('com.esri.builder.controllers.supportClasses.LocalConnectionDelegate');
    private static const CNAME:String = '_flexViewer';

    private var m_localConnection:LocalConnection;

    private function get localConnection():LocalConnection
    {
        if (m_localConnection === null)
        {
            if (Log.isDebug())
            {
                LOG.debug("Acquiring local connection");
            }

            m_localConnection = new LocalConnection();
            m_localConnection.addEventListener(StatusEvent.STATUS, localConnection_statusHandler);
        }
        return m_localConnection;
    }

    private function localConnection_statusHandler(event:StatusEvent):void
    {
        if (event.level == "error")
        {
            if (Log.isDebug())
            {
                LOG.debug("Call failed: {0}", event.toString());
            }
        }
    }

    public function setTitles(title:String, subtitle:String):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending titles changes: title {0} - subtitle {1}", title, subtitle);
        }

        callViewerMethod('setTitles', title, subtitle);
    }

    private function callViewerMethod(methodName:String, ... values):void
    {
        try
        {
            //use Function#apply to avoid passing rest argument as Array
            localConnection.send.apply(null, [ CNAME, methodName ].concat(values));
        }
        catch (error:Error)
        {
            if (Log.isDebug())
            {
                LOG.debug("Call to Viewer method {0} failed: {1}", methodName, error);
            }
        }
    }

    public function setLogo(value:String):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending logo changes {0}", value);
        }

        callViewerMethod('setLogo', value);
    }

    public function setTextColor(value:uint):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending text color changes {0}", value);
        }

        callViewerMethod('setTextColor', value);
    }

    public function setBackgroundColor(value:uint):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending background color changes {0}", value);
        }

        callViewerMethod('setBackgroundColor', value);
    }

    public function setRolloverColor(value:uint):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending rollover color changes {0}", value);
        }

        callViewerMethod('setRolloverColor', value);
    }

    public function setSelectionColor(value:uint):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending selection color changes {0}", value);
        }

        callViewerMethod('setSelectionColor', value);
    }

    public function setTitleColor(value:uint):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending title color changes {0}", value);
        }

        callViewerMethod('setTitleColor', value);
    }

    public function setLocale(localeChain:String):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending locale changes {0}", localeChain);
        }

        callViewerMethod('setLocale', localeChain);
    }

    public function setFontName(value:String):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending font name changes {0}", value);
        }

        callViewerMethod('setFontName', value);
    }

    public function setAppTitleFontName(value:String):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending app title font name changes {0}", value);
        }

        callViewerMethod('setAppTitleFontName', value);
    }

    public function setSubTitleFontName(value:String):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending subtitle font name changes {0}", value);
        }

        callViewerMethod('setSubTitleFontName', value);
    }

    public function setAlpha(value:Number):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending alpha changes {0}", value);
        }

        callViewerMethod('setAlpha', value);
    }

    public function setPredefinedStyles(value:Object):void
    {
        if (Log.isDebug())
        {
            LOG.debug("Sending predefined changes {0}", value);
        }

        callViewerMethod('setPredefinedStyles', value);
    }
}
}

Handle Viewer connection message failures.


////////////////////////////////////////////////////////////////////////////////
//
//  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.layouts
{
	import org.apache.flex.core.IBead;
	import org.apache.flex.core.IStrand;
	import org.apache.flex.events.Event;
	import org.apache.flex.events.IEventDispatcher;

	/**
	 *  The LayoutChangeNotifier notifies layouts when a property
     *  it is watching changes.
	 *
	 *  @langversion 3.0
	 *  @playerversion Flash 10.2
	 *  @playerversion AIR 2.6
	 *  @productversion FlexJS 0.0
	 */
	public class LayoutChangeNotifier implements IBead
	{
		/**
		 *  constructor.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		public function LayoutChangeNotifier()
		{
		}

		private var _strand:IStrand;

		/**
		 *  @copy org.apache.flex.core.IBead#strand
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		public function set strand(value:IStrand):void
		{
			_strand = value;
		}

        private var _value:* = undefined;

		/**
		 *  The number of tiles to fit horizontally into the layout.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		public function set watchedProperty(value:Object):void
		{
			if (_value !== value)
            {
                _value = value;
                IEventDispatcher(_strand).dispatchEvent(new Event("layoutNeeded"));
            }
		}

	}
}

////////////////////////////////////////////////////////////////////////////////
//
//  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.layouts
{
	import org.apache.flex.core.IBead;
    import org.apache.flex.core.IBeadView;
	import org.apache.flex.core.IStrand;
	import org.apache.flex.events.Event;
	import org.apache.flex.events.IEventDispatcher;

	/**
	 *  The LayoutChangeNotifier notifies layouts when a property
     *  it is watching changes.
	 *
	 *  @langversion 3.0
	 *  @playerversion Flash 10.2
	 *  @playerversion AIR 2.6
	 *  @productversion FlexJS 0.0
	 */
	public class LayoutChangeNotifier implements IBead
	{
		/**
		 *  constructor.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		public function LayoutChangeNotifier()
		{
		}

		private var _strand:IStrand;

		/**
		 *  @copy org.apache.flex.core.IBead#strand
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		public function set strand(value:IStrand):void
		{
			_strand = value;
		}

        private var _value:* = undefined;

		/**
		 *  The number of tiles to fit horizontally into the layout.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		public function set watchedProperty(value:Object):void
		{
			if (_value !== value)
            {
                _value = value;
                IBeadView(_strand).host.dispatchEvent(new Event("layoutNeeded"));
            }
		}

	}
}

use host

use host


////////////////////////////////////////////////////////////////////////////////
//
//  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.Bitmap;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.net.URLRequest;

    import org.apache.flex.core.BeadViewBase;
	import org.apache.flex.core.IBeadView;
	import org.apache.flex.core.IImageModel;
	import org.apache.flex.core.IStrand;
	import org.apache.flex.core.UIBase;
	import org.apache.flex.events.Event;
	import org.apache.flex.events.IEventDispatcher;

	/**
	 *  The ImageView class creates the visual elements of the org.apache.flex.html.Image component.
	 *
	 *  @langversion 3.0
	 *  @playerversion Flash 10.2
	 *  @playerversion AIR 2.6
	 *  @productversion FlexJS 0.0
	 */
	public class ImageView extends BeadViewBase implements IBeadView
	{
		/**
		 *  constructor.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		public function ImageView()
		{
		}

		private var bitmap:Bitmap;
		private var loader:Loader;

		private var _model:IImageModel;

		/**
		 *  @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
		{
			super.strand = value;

			IEventDispatcher(_strand).addEventListener("widthChanged",handleSizeChange);
			IEventDispatcher(_strand).addEventListener("heightChanged",handleSizeChange);

			_model = value.getBeadByType(IImageModel) as IImageModel;
			_model.addEventListener("urlChanged",handleUrlChange);

			handleUrlChange(null);
		}

		/**
		 * @private
		 */
		private function handleUrlChange(event:Event):void
		{
			if (_model.source) {
				loader = new Loader();
				loader.contentLoaderInfo.addEventListener("complete",onComplete);
				loader.load(new URLRequest(_model.source));
			}
		}

		/**
		 * @private
		 */
		private function onComplete(event:Object):void
		{
            var host:UIBase = UIBase(_strand);
			if (bitmap) {
				host.removeChild(bitmap);
			}

			bitmap = Bitmap(LoaderInfo(event.target).content);

			host.addChild(bitmap);

            if (isNaN(host.explicitWidth) && isNaN(host.percentWidth))
                host.dispatchEvent(new Event("widthChanged"));
            if (isNaN(host.explicitHeight) && isNaN(host.percentHeight))
                host.dispatchEvent(new Event("heightChanged"));

		}

		/**
		 * @private
		 */
		private function handleSizeChange(event:Object):void
		{
            var host:UIBase = UIBase(_strand);
            if (bitmap) {
                if (!isNaN(host.explicitWidth) || !isNaN(host.percentWidth))
	    			bitmap.width = UIBase(_strand).width;
                if (!isNaN(host.explicitHeight) || !isNaN(host.percentHeight))
    				bitmap.height = UIBase(_strand).height;
			}
		}
	}
}

////////////////////////////////////////////////////////////////////////////////
//
//  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.Bitmap;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.net.URLRequest;

    import org.apache.flex.core.BeadViewBase;
	import org.apache.flex.core.IBeadView;
	import org.apache.flex.core.IImageModel;
	import org.apache.flex.core.IStrand;
	import org.apache.flex.core.UIBase;
	import org.apache.flex.events.Event;
	import org.apache.flex.events.IEventDispatcher;

	/**
	 *  The ImageView class creates the visual elements of the org.apache.flex.html.Image component.
	 *
	 *  @langversion 3.0
	 *  @playerversion Flash 10.2
	 *  @playerversion AIR 2.6
	 *  @productversion FlexJS 0.0
	 */
	public class ImageView extends BeadViewBase implements IBeadView
	{
		/**
		 *  constructor.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		public function ImageView()
		{
		}

		private var bitmap:Bitmap;
		private var loader:Loader;

		private var _model:IImageModel;

		/**
		 *  @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
		{
			super.strand = value;

			IEventDispatcher(_strand).addEventListener("widthChanged",handleSizeChange);
			IEventDispatcher(_strand).addEventListener("heightChanged",handleSizeChange);

			_model = value.getBeadByType(IImageModel) as IImageModel;
			_model.addEventListener("urlChanged",handleUrlChange);

			handleUrlChange(null);
		}

		/**
		 * @private
		 */
		private function handleUrlChange(event:Event):void
		{
			if (_model.source) {
				loader = new Loader();
				loader.contentLoaderInfo.addEventListener("complete",onComplete);
				loader.load(new URLRequest(_model.source));
			}
		}

		/**
		 * @private
		 */
		private function onComplete(event:Object):void
		{
            var host:UIBase = UIBase(_strand);
			if (bitmap) {
				host.removeChild(bitmap);
			}

			bitmap = Bitmap(LoaderInfo(event.target).content);

			host.addChild(bitmap);

            if (isNaN(host.explicitWidth) && isNaN(host.percentWidth))
                host.dispatchEvent(new Event("widthChanged"));
            else
                bitmap.width = UIBase(_strand).width;

            if (isNaN(host.explicitHeight) && isNaN(host.percentHeight))
                host.dispatchEvent(new Event("heightChanged"));
            else
                bitmap.height = UIBase(_strand).height;

		}

		/**
		 * @private
		 */
		private function handleSizeChange(event:Object):void
		{
            var host:UIBase = UIBase(_strand);
            if (bitmap) {
                if (!isNaN(host.explicitWidth) || !isNaN(host.percentWidth))
	    			bitmap.width = UIBase(_strand).width;
                if (!isNaN(host.explicitHeight) || !isNaN(host.percentHeight))
    				bitmap.height = UIBase(_strand).height;
			}
		}
	}
}

set size on bitmap if needed

set size on bitmap if needed


package com.threerings.util {

import flash.events.IEventDispatcher;

import com.threerings.mx.events.CommandEvent;

public class Controller
{
    /**
     * Set the panel being controlled.
     */
    protected function setControlledPanel (panel :IEventDispatcher) :void
    {
        if (_panel != null) {
            _panel.removeEventListener(
                CommandEvent.TYPE, handleCommandEvent);
        }
        _panel = panel;
        if (_panel != null) {
            _panel.addEventListener(
                CommandEvent.TYPE, handleCommandEvent);
        }
    }

    /**
     * Post an action so that it can be handled by this controller or
     * another controller above it in the display list.
     */
    public final function postAction (cmd :String, arg :Object = null) :void
    {
        CommandEvent.dispatch(_panel, cmd, arg);
    }

    /**
     * Handle an action that was generated by our panel or some child.
     *
     * @return true if the specified action was handled, false otherwise.
     *
     * When creating your own controller, override this function and return
     * true for any command handled, and call super for any unknown commands.
     */
    public function handleAction (cmd :String, arg :Object) :Boolean
    {
        // fall back to a method named the cmd
        try {
            var fn :Function = (this["handle" + cmd] as Function);
            if (fn != null) {
                try {
                    fn(arg);
                } catch (e :Error) {
                    var log :Log = Log.getLog(this);
                    log.warning("Error handling controller " +
                        "command [error=" + e + ", cmd=" + cmd +
                        ", arg=" + arg + "].");
                    log.logStackTrace(e);
                }
                // we "handled" the event, even if it threw an error
                return true;
            }
        } catch (e :Error) {
            // suppress, and fall through
        }

        return false; // not handled
    }

    /**
     * Private function to handle the controller event and call
     * handleAction.
     */
    private function handleCommandEvent (event :CommandEvent) :void
    {
        if (handleAction(event.command, event.arg)) {
            // if we handle the event, stop it from moving outward to another
            // controller
            event.preventDefault();
            event.stopImmediatePropagation();
        }
    }

    /** The panel currently being controlled. */
    private var _panel :IEventDispatcher;
}
}

package com.threerings.util {

import flash.events.IEventDispatcher;

import com.threerings.mx.events.CommandEvent;

public class Controller
{
    /**
     * Set the panel being controlled.
     */
    protected function setControlledPanel (panel :IEventDispatcher) :void
    {
        if (_panel != null) {
            _panel.removeEventListener(
                CommandEvent.TYPE, handleCommandEvent);
        }
        _panel = panel;
        if (_panel != null) {
            _panel.addEventListener(
                CommandEvent.TYPE, handleCommandEvent);
        }
    }

    /**
     * Post an action so that it can be handled by this controller or
     * another controller above it in the display list.
     */
    public final function postAction (cmd :String, arg :Object = null) :void
    {
        CommandEvent.dispatch(_panel, cmd, arg);
    }

    /**
     * Handle an action that was generated by our panel or some child.
     *
     * @return true if the specified action was handled, false otherwise.
     *
     * When creating your own controller, override this function and return
     * true for any command handled, and call super for any unknown commands.
     */
    public function handleAction (cmd :String, arg :Object) :Boolean
    {
        // fall back to a method named the cmd
        try {
            var fn :Function = (this["handle" + cmd] as Function);
            if (fn != null) {
                try {
                    try {
                        // try calling it with the arg
                        fn(arg);
                    } catch (ae :ArgumentError) {
                        if (arg == null) {
                            // try calling it without the arg
                            fn();
                        } else {
                            throw ae;
                        }
                    }

                } catch (e :Error) {
                    var log :Log = Log.getLog(this);
                    log.warning("Error handling controller " +
                        "command [error=" + e + ", cmd=" + cmd +
                        ", arg=" + arg + "].");
                    log.logStackTrace(e);
                }
                // we "handled" the event, even if it threw an error
                return true;
            }
        } catch (e :Error) {
            // suppress, and fall through
        }

        return false; // not handled
    }

    /**
     * Private function to handle the controller event and call
     * handleAction.
     */
    private function handleCommandEvent (event :CommandEvent) :void
    {
        if (handleAction(event.command, event.arg)) {
            // if we handle the event, stop it from moving outward to another
            // controller
            event.preventDefault();
            event.stopImmediatePropagation();
        }
    }

    /** The panel currently being controlled. */
    private var _panel :IEventDispatcher;
}
}

Allow the handleCOMMAND functions to have no arg if the command's arg is null.

git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4347 542714f4-19e9-0310-aa3c-eee0fc999fb1


package cc.milkshape.grid.process
{
	import cc.milkshape.gateway.Gateway;
	import cc.milkshape.gateway.GatewayController;
	import cc.milkshape.grid.GridModel;
	import cc.milkshape.grid.process.events.SquareProcessEvent;
	import cc.milkshape.grid.process.files.SquareProcessFileDownload;
	import cc.milkshape.grid.process.files.SquareProcessFileUpload;

	import flash.events.Event;
	import flash.net.Responder;
	import flash.utils.ByteArray;

	public class SquareProcessController extends GatewayController
	{
		private var _fileDownload:SquareProcessFileDownload;
		private var _fileUpload:SquareProcessFileUpload;
		public function SquareProcessController()
		{
			_fileDownload = new SquareProcessFileDownload();
			_fileDownload.addEventListener(Event.COMPLETE, _templateDownloaded);
			_fileUpload = new SquareProcessFileUpload();
		}

		public function book(posX:int, posY:int, issueSlug:String):void
		{
			_responder = new Responder(_book, _onFault);
			Gateway.getInstance().call("square.book", _responder, posY, posX, issueSlug);
		}

		private function _book(result:Object):void
		{
			if(result){
				_fileDownload.setURI(result.template_url);
				dispatchEvent(new SquareProcessEvent(SquareProcessEvent.BOOKED));
			}
		}

		public function release(posX:int, posY:int, issueSlug:String):void
		{
			_responder = new Responder(_released, _onFault);
			Gateway.getInstance().call("square.release", _responder, posY, posX, issueSlug);
		}

		private function _released(result:Object):void
		{
			dispatchEvent(new SquareProcessEvent(SquareProcessEvent.CANCELED));
		}

		public function loadTemplate(posX:int, posY:int, issueSlug:String):void
		{
			_responder = new Responder(_template, _onFault);
			Gateway.getInstance().call("square.template", _responder, posY, posX, issueSlug);
		}

		public function template():void
		{
			_fileDownload.downloadTpl();
		}

		private function _templateDownloaded(e:Event):void
		{
			trace("template downloaded");
		}

		private function _template(result:Object):void
		{
			_fileDownload.setURI(result as String);
			dispatchEvent(new SquareProcessEvent(SquareProcessEvent.DOWNLOAD));
		}

		public function fill(posX:int, posY:int, issueSlug:String):void
		{
			_fileUpload.addEventListener(Event.COMPLETE,
				function(e:Event):void
				{
					dispatchEvent(new SquareProcessEvent(SquareProcessEvent.UPLOADING));
					var data:ByteArray = new ByteArray();
					_fileUpload.data.readBytes(data, 0, _fileUpload.data.length);
					_responder = new Responder(_uploaded, _onFault);
					Gateway.getInstance().call("square.fill", _responder, posY, posX, issueSlug, data);
					trace("test");
					dispatchEvent(new SquareProcessEvent(SquareProcessEvent.UPLOADING2));
				}
			);
			_fileUpload.browseTpl();
		}

		public function _uploaded(result:Object):void
		{
			dispatchEvent(new SquareProcessEvent(SquareProcessEvent.SUCCESS));
		}

		public function reload():void
		{
			trace('reload issue');
		}

		public function show():void
		{
			dispatchEvent(new SquareProcessEvent(SquareProcessEvent.SHOW));
		}

		public function hide():void
		{
			dispatchEvent(new SquareProcessEvent(SquareProcessEvent.HIDE));
		}
	}
}

package cc.milkshape.grid.process
{
	import cc.milkshape.gateway.Gateway;
	import cc.milkshape.gateway.GatewayController;
	import cc.milkshape.grid.GridModel;
	import cc.milkshape.grid.process.events.SquareProcessEvent;
	import cc.milkshape.grid.process.files.SquareProcessFileDownload;
	import cc.milkshape.grid.process.files.SquareProcessFileUpload;

	import flash.events.Event;
	import flash.net.Responder;
	import flash.utils.ByteArray;

	public class SquareProcessController extends GatewayController
	{
		private var _fileDownload:SquareProcessFileDownload;
		private var _fileUpload:SquareProcessFileUpload;
		public function SquareProcessController()
		{
			_fileDownload = new SquareProcessFileDownload();
			_fileDownload.addEventListener(Event.COMPLETE, _templateDownloaded);
			_fileUpload = new SquareProcessFileUpload();
		}

		public function book(posX:int, posY:int, issueSlug:String):void
		{
			_responder = new Responder(_book, _onFault);
			Gateway.getInstance().call("square.book", _responder, posX, posY, issueSlug);
		}

		private function _book(result:Object):void
		{
			if(result){
				_fileDownload.setURI(result.template_url);
				dispatchEvent(new SquareProcessEvent(SquareProcessEvent.BOOKED));
			}
		}

		public function release(posX:int, posY:int, issueSlug:String):void
		{
			_responder = new Responder(_released, _onFault);
			Gateway.getInstance().call("square.release", _responder, posX, posY, issueSlug);
		}

		private function _released(result:Object):void
		{
			dispatchEvent(new SquareProcessEvent(SquareProcessEvent.CANCELED));
		}

		public function loadTemplate(posX:int, posY:int, issueSlug:String):void
		{
			_responder = new Responder(_template, _onFault);
			Gateway.getInstance().call("square.template", _responder, posX, posY, issueSlug);
		}

		public function template():void
		{
			_fileDownload.downloadTpl();
		}

		private function _templateDownloaded(e:Event):void
		{
			trace("template downloaded");
		}

		private function _template(result:Object):void
		{
			_fileDownload.setURI(result as String);
			dispatchEvent(new SquareProcessEvent(SquareProcessEvent.DOWNLOAD));
		}

		public function fill(posX:int, posY:int, issueSlug:String):void
		{
			_fileUpload.addEventListener(Event.COMPLETE,
				function(e:Event):void
				{
					dispatchEvent(new SquareProcessEvent(SquareProcessEvent.UPLOADING));
					var data:ByteArray = new ByteArray();
					_fileUpload.data.readBytes(data, 0, _fileUpload.data.length);
					_responder = new Responder(_uploaded, _onFault);
					Gateway.getInstance().call("square.fill", _responder, posX, posY, issueSlug, data);
					trace("test");
					dispatchEvent(new SquareProcessEvent(SquareProcessEvent.UPLOADING2));
				}
			);
			_fileUpload.browseTpl();
		}

		public function _uploaded(result:Object):void
		{
			dispatchEvent(new SquareProcessEvent(SquareProcessEvent.SUCCESS));
		}

		public function reload():void
		{
			trace('reload issue');
		}

		public function show():void
		{
			dispatchEvent(new SquareProcessEvent(SquareProcessEvent.SHOW));
		}

		public function hide():void
		{
			dispatchEvent(new SquareProcessEvent(SquareProcessEvent.HIDE));
		}
	}
}

fix upload process

fix upload process


package aerys.minko.scene.controller.mesh
{
	import aerys.minko.ns.minko_math;
	import aerys.minko.render.geometry.Geometry;
	import aerys.minko.scene.controller.AbstractController;
	import aerys.minko.scene.node.Group;
	import aerys.minko.scene.node.ISceneNode;
	import aerys.minko.scene.node.Mesh;
	import aerys.minko.scene.node.Scene;
	import aerys.minko.scene.node.camera.AbstractCamera;
	import aerys.minko.type.binding.DataBindings;
	import aerys.minko.type.enum.FrustumCulling;
	import aerys.minko.type.math.BoundingBox;
	import aerys.minko.type.math.BoundingSphere;
	import aerys.minko.type.math.Matrix4x4;
	import aerys.minko.type.math.Vector4;

	/**
	 * The MeshVisibilityController watches the Mesh and the active Camera of a Scene
	 * to determine whether the object is actually inside the view frustum or not.
	 *
	 * @author Jean-Marc Le Roux
	 *
	 */
	public final class MeshVisibilityController extends AbstractController
	{
		use namespace minko_math;

		private static const TMP_VECTOR4		: Vector4	= new Vector4();

		private static const STATE_UNDEFINED	: uint		= 0;
		private static const STATE_INSIDE		: uint		= 1;
		private static const STATE_OUTSIDE		: uint		= 2;

		private var _mesh			    : Mesh;
		private var _state			    : uint;
		private var _lastTest		    : int;
		private var _boundingBox	    : BoundingBox;
		private var _boundingSphere	    : BoundingSphere;

        private var _frustumCulling     : uint;
        private var _insideFrustum      : Boolean;
        private var _computedVisibility : Boolean;

		public function get frustumCulling() : uint
		{
			return _frustumCulling;
		}
		public function set frustumCulling(value : uint) : void
		{
			_frustumCulling = value;
            testCulling();
		}

		public function get insideFrustum() : Boolean
		{
			return _insideFrustum;
		}

        public function get computedVisibility() : Boolean
        {
            return _frustumCulling == FrustumCulling.DISABLED || _computedVisibility;
        }

		public function MeshVisibilityController()
		{
			super(Mesh);

			initialize();
		}

		private function initialize() : void
		{
			_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
			_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);

            _state = STATE_UNDEFINED;

			targetAdded.add(targetAddedHandler);
			targetRemoved.add(targetRemovedHandler);
		}

		private function targetAddedHandler(ctrl	: MeshVisibilityController,
											target	: Mesh) : void
		{
			if (_mesh != null)
				throw new Error();

			_mesh = target;

			target.added.add(addedHandler);
			target.removed.add(removedHandler);

			if (target.root is Scene)
				addedHandler(target, target.root as Scene);
		}

		private function targetRemovedHandler(ctrl		: MeshVisibilityController,
											  target	: Mesh) : void
		{
			_mesh = null;

			target.added.remove(addedHandler);
			target.removed.remove(removedHandler);

			if (target.root is Scene)
				removedHandler(target, target.root as Scene);
		}

		private function addedHandler(mesh : Mesh, ancestor : Group) : void
		{
			var scene : Scene = mesh.scene;

			if (!scene)
				return ;

			scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);

            meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
			mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
            mesh.visibilityChanged.add(visiblityChangedHandler);
            mesh.parent.computedVisibilityChanged.add(visiblityChangedHandler);
            mesh.removed.add(meshRemovedHandler);
		}

        private function meshRemovedHandler(mesh : Mesh, ancestor : Group) : void
        {
            if (!mesh.parent)
                ancestor.computedVisibilityChanged.remove(visiblityChangedHandler);
        }

		private function removedHandler(mesh : Mesh, ancestor : Group) : void
		{
			var scene : Scene = ancestor.scene;

			if (!scene)
				return ;

			scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);

			mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
            mesh.visibilityChanged.remove(visiblityChangedHandler);
            mesh.removed.remove(meshRemovedHandler);
			if (mesh.parent)
				mesh.parent.computedVisibilityChanged.remove(visiblityChangedHandler);
		}

        private function visiblityChangedHandler(node : ISceneNode, visibility : Boolean) : void
        {
            _computedVisibility = _mesh.visible && _mesh.parent.computedVisibility
                && _insideFrustum;
            _mesh.computedVisibilityChanged.execute(_mesh, _computedVisibility);
        }

		private function worldToScreenChangedHandler(bindings	    : DataBindings,
                                                     propertyName	: String,
                                                     oldValue		: Matrix4x4,
                                                     newValue		: Matrix4x4) : void
		{
			testCulling();
		}

		private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
		{
			var geom 	: Geometry 	= _mesh.geometry;
			var culling	: uint		= _frustumCulling;

			if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
				return ;

			if (culling & FrustumCulling.BOX)
				transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);

			if (culling & FrustumCulling.SPHERE)
			{
				var center 	: Vector4 	= transform.transformVector(geom.boundingSphere.center);
				var scale 	: Vector4 	= transform.deltaTransformVector(Vector4.ONE);
				var radius	: Number	= geom.boundingSphere.radius * Math.max(
					Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
				);

				_boundingSphere.update(center, radius);
			}

			testCulling();
		}

		private function testCulling() : void
		{
			var culling	: uint	= _frustumCulling;

			if (culling != FrustumCulling.DISABLED && _mesh && _mesh.geometry.boundingBox
                && _mesh.visible)
			{
				var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;

				if (!camera)
					return ;

				_lastTest = camera.frustum.testBoundingVolume(
					_boundingSphere,
					_boundingBox,
					null,
					culling,
					_lastTest
				);

				var inside : Boolean = _lastTest == -1;

				if (inside && _state != STATE_INSIDE)
				{
					_insideFrustum = true;
                    _computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
                    _mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
					_state = STATE_INSIDE;
				}
				else if (!inside && _state != STATE_OUTSIDE)
				{
					_insideFrustum = false;
                    _computedVisibility = false;
                    _mesh.computedVisibilityChanged.execute(_mesh, false);
					_state = STATE_OUTSIDE;
				}
			}
		}

		override public function clone() : AbstractController
		{
			return new MeshVisibilityController();;
		}
	}
}

package aerys.minko.scene.controller.mesh
{
	import aerys.minko.ns.minko_math;
	import aerys.minko.render.geometry.Geometry;
	import aerys.minko.scene.controller.AbstractController;
	import aerys.minko.scene.node.Group;
	import aerys.minko.scene.node.ISceneNode;
	import aerys.minko.scene.node.Mesh;
	import aerys.minko.scene.node.Scene;
	import aerys.minko.scene.node.camera.AbstractCamera;
	import aerys.minko.type.binding.DataBindings;
	import aerys.minko.type.enum.FrustumCulling;
	import aerys.minko.type.math.BoundingBox;
	import aerys.minko.type.math.BoundingSphere;
	import aerys.minko.type.math.Matrix4x4;
	import aerys.minko.type.math.Vector4;

	/**
	 * The MeshVisibilityController watches the Mesh and the active Camera of a Scene
	 * to determine whether the object is actually inside the view frustum or not.
	 *
	 * @author Jean-Marc Le Roux
	 *
	 */
	public final class MeshVisibilityController extends AbstractController
	{
		use namespace minko_math;

		private static const TMP_VECTOR4		: Vector4	= new Vector4();

		private static const STATE_UNDEFINED	: uint		= 0;
		private static const STATE_INSIDE		: uint		= 1;
		private static const STATE_OUTSIDE		: uint		= 2;

		private var _mesh			    : Mesh;
		private var _state			    : uint;
		private var _lastTest		    : int;
		private var _boundingBox	    : BoundingBox;
		private var _boundingSphere	    : BoundingSphere;

        private var _frustumCulling     : uint;
        private var _insideFrustum      : Boolean;
        private var _computedVisibility : Boolean;

		public function get frustumCulling() : uint
		{
			return _frustumCulling;
		}
		public function set frustumCulling(value : uint) : void
		{
			_frustumCulling = value;
            testCulling();
		}

		public function get insideFrustum() : Boolean
		{
			return _insideFrustum;
		}

        public function get computedVisibility() : Boolean
        {
            return _frustumCulling == FrustumCulling.DISABLED || _computedVisibility;
        }

		public function MeshVisibilityController()
		{
			super(Mesh);

			initialize();
		}

		private function initialize() : void
		{
			_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
			_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);

            _state = STATE_UNDEFINED;

			targetAdded.add(targetAddedHandler);
			targetRemoved.add(targetRemovedHandler);
		}

		private function targetAddedHandler(ctrl	: MeshVisibilityController,
											target	: Mesh) : void
		{
			if (_mesh != null)
				throw new Error();

			_mesh = target;

			target.added.add(addedHandler);
			target.removed.add(removedHandler);

			if (target.root is Scene)
				addedHandler(target, target.root as Scene);
		}

		private function targetRemovedHandler(ctrl		: MeshVisibilityController,
											  target	: Mesh) : void
		{
			_mesh = null;

			target.added.remove(addedHandler);
			target.removed.remove(removedHandler);

			if (target.root is Scene)
				removedHandler(target, target.root as Scene);
		}

		private function addedHandler(mesh : Mesh, ancestor : Group) : void
		{
			var scene : Scene = mesh.scene;

			if (!scene)
				return ;

			scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);

            meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
			mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
            mesh.visibilityChanged.add(visiblityChangedHandler);
            mesh.parent.computedVisibilityChanged.add(visiblityChangedHandler);
            mesh.removed.add(meshRemovedHandler);
		}

        private function meshRemovedHandler(mesh : Mesh, ancestor : Group) : void
        {
            if (!mesh.parent)
                ancestor.computedVisibilityChanged.remove(visiblityChangedHandler);
        }

		private function removedHandler(mesh : Mesh, ancestor : Group) : void
		{
			var scene : Scene = ancestor.scene;

			if (!scene)
				return ;

			scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);

			mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
            mesh.visibilityChanged.remove(visiblityChangedHandler);
            mesh.removed.remove(meshRemovedHandler);
			if (mesh.parent)
				mesh.parent.computedVisibilityChanged.remove(visiblityChangedHandler);
		}

        private function visiblityChangedHandler(node : ISceneNode, visibility : Boolean) : void
        {
            _computedVisibility = _mesh.visible && _mesh.parent.computedVisibility
                && (_frustumCulling == FrustumCulling.DISABLED || _insideFrustum);
            _mesh.computedVisibilityChanged.execute(_mesh, _computedVisibility);
        }

		private function worldToScreenChangedHandler(bindings	    : DataBindings,
                                                     propertyName	: String,
                                                     oldValue		: Matrix4x4,
                                                     newValue		: Matrix4x4) : void
		{
			testCulling();
		}

		private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
		{
			var geom 	: Geometry 	= _mesh.geometry;
			var culling	: uint		= _frustumCulling;

			if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
				return ;

			if (culling & FrustumCulling.BOX)
				transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);

			if (culling & FrustumCulling.SPHERE)
			{
				var center 	: Vector4 	= transform.transformVector(geom.boundingSphere.center);
				var scale 	: Vector4 	= transform.deltaTransformVector(Vector4.ONE);
				var radius	: Number	= geom.boundingSphere.radius * Math.max(
					Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
				);

				_boundingSphere.update(center, radius);
			}

			testCulling();
		}

		private function testCulling() : void
		{
			var culling	: uint	= _frustumCulling;

			if (culling != FrustumCulling.DISABLED && _mesh && _mesh.geometry.boundingBox
                && _mesh.visible)
			{
				var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;

				if (!camera)
					return ;

				_lastTest = camera.frustum.testBoundingVolume(
					_boundingSphere,
					_boundingBox,
					null,
					culling,
					_lastTest
				);

				var inside : Boolean = _lastTest == -1;

				if (inside && _state != STATE_INSIDE)
				{
					_insideFrustum = true;
                    _computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
                    _mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
					_state = STATE_INSIDE;
				}
				else if (!inside && _state != STATE_OUTSIDE)
				{
					_insideFrustum = false;
                    _computedVisibility = false;
                    _mesh.computedVisibilityChanged.execute(_mesh, false);
					_state = STATE_OUTSIDE;
				}
			}
		}

		override public function clone() : AbstractController
		{
			return new MeshVisibilityController();;
		}
	}
}

fix wrong computation for _computedVisibility because _insideFrustum is always false when frustum culling is disabled