package aerys.minko.render.renderer
{
	import aerys.minko.ns.minko;
	import aerys.minko.ns.minko_render;
	import aerys.minko.render.Viewport;
	import aerys.minko.render.renderer.state.RendererState;
	import aerys.minko.type.Factory;
	import aerys.minko.type.stream.IndexStream;

	import flash.display.BitmapData;
	import flash.display3D.Context3D;
	import flash.display3D.IndexBuffer3D;
	import flash.utils.getTimer;

	public class DefaultRenderer implements IRenderer
	{
		use namespace minko;
		use namespace minko_render;

		private static const RENDER_STATE	: Factory			= Factory.getFactory(RendererState);
		private static const SORT			: Boolean			= true;
		private static const DEBUG			: Boolean			= false;

		private var _context		: Context3D					= null;
		private var _currentState	: RendererState				= null;
		private var _numTriangles	: uint						= 0;
		private var _viewport		: Viewport					= null;
		private var _drawingTime	: int						= 0;
		private var _frame			: uint						= 0;

		private var _states			: Vector.<RendererState>	= new Vector.<RendererState>();
		private var _numStates		: int						= 0;

		public function get state() 		: RendererState	{ return _currentState; }
		public function get numTriangles()	: uint			{ return _numTriangles; }
		public function get viewport()		: Viewport		{ return _viewport; }
		public function get drawingTime()	: int			{ return _drawingTime; }
		public function get frameId()		: uint			{ return _frame; }

		public function DefaultRenderer(viewport : Viewport, context : Context3D)
		{
			_viewport = viewport;
			_context = context;

			_context.enableErrorChecking = DEBUG;
		}

		public function begin()	: void
		{
			_currentState = RENDER_STATE.create(true) as RendererState;
			_currentState.clear();
		}

		public function end() : void
		{
			_states[int(_numStates++)] = _currentState;
			_currentState = null;
		}

		public function drawTriangles(offset : uint = 0, numTriangles : int = -1) : void
		{
			_currentState.offsets.push(offset);
			_currentState.numTriangles.push(numTriangles);
		}

		public function clear(red		: Number	= 0.,
							  green		: Number	= 0.,
							  blue		: Number	= 0.,
							  alpha		: Number	= 1.,
							  depth		: Number	= 1.,
							  stencil	: uint		= 0,
							  mask		: uint		= 0xffffffff)  :void
		{
//			_context.setScissorRectangle(null);
//			_context.clear(red, green, blue, alpha, depth, stencil, mask);

			_numTriangles = 0;
			_drawingTime = 0;

			_currentState = null;
			_numStates = 0;
		}

		public function drawToBackBuffer() : void
		{
			var time : int = getTimer();

			if (SORT && _numStates > 1)
				RendererState.sort(_states, _numStates);

			var actualState : RendererState = null;

			for (var i : int = 0; i < _numStates; ++i)
			{
				var state			: RendererState = _states[i];
				var offsets 		: Vector.<uint>	= state.offsets;
				var numTriangles 	: Vector.<int> 	= state.numTriangles;
				var numCalls 		: int 			= offsets.length;

				state.prepareContext(_context, actualState);

				for (var j : int = 0; j < numCalls; ++j)
				{
					var iStream : IndexStream	= state._indexStream;
					var iBuffer : IndexBuffer3D = iStream.getIndexBuffer3D(_context);
					var count	: int			= numTriangles[j];

					_numTriangles += count == -1
									 ? state._indexStream.length / 3.
									 : count;

					_context.drawTriangles(iBuffer, offsets[j], count);
				}

				actualState = state;
			}

			_drawingTime += getTimer() - time;
		}

		public function present() : void
		{
			var time : int = getTimer();

			if (_numStates != 0)
				_context.present();

			_drawingTime += getTimer() - time;
			++_frame;
		}

		public function dumpBackbuffer(bitmapData : BitmapData) : void
		{
			var time : int = getTimer();

			_context.drawToBitmapData(bitmapData);

			_drawingTime += getTimer() - time;
			++_frame;
		}
	}
}

package aerys.minko.render.renderer
{
	import aerys.minko.ns.minko;
	import aerys.minko.ns.minko_render;
	import aerys.minko.render.Viewport;
	import aerys.minko.render.renderer.state.RendererState;
	import aerys.minko.type.Factory;
	import aerys.minko.type.stream.IndexStream;

	import flash.display.BitmapData;
	import flash.display3D.Context3D;
	import flash.display3D.IndexBuffer3D;
	import flash.utils.getTimer;

	public class DefaultRenderer implements IRenderer
	{
		use namespace minko;
		use namespace minko_render;

		private static const RENDER_STATE	: Factory			= Factory.getFactory(RendererState);
		private static const SORT			: Boolean			= true;
		private static const DEBUG			: Boolean			= false;

		private var _context		: Context3D					= null;
		private var _currentState	: RendererState				= null;
		private var _numTriangles	: uint						= 0;
		private var _viewport		: Viewport					= null;
		private var _drawingTime	: int						= 0;
		private var _frame			: uint						= 0;

		private var _states			: Vector.<RendererState>	= new Vector.<RendererState>();
		private var _numStates		: int						= 0;

		public function get state() 		: RendererState	{ return _currentState; }
		public function get numTriangles()	: uint			{ return _numTriangles; }
		public function get viewport()		: Viewport		{ return _viewport; }
		public function get drawingTime()	: int			{ return _drawingTime; }
		public function get frameId()		: uint			{ return _frame; }

		public function DefaultRenderer(viewport : Viewport, context : Context3D)
		{
			_viewport = viewport;
			_context = context;

			_context.enableErrorChecking = DEBUG;
		}

		public function begin()	: void
		{
			_currentState = RENDER_STATE.create(true) as RendererState;
			_currentState.clear();
		}

		public function end() : void
		{
			_states[int(_numStates++)] = _currentState;
			_currentState = null;
		}

		public function drawTriangles(offset : uint = 0, numTriangles : int = -1) : void
		{
			_currentState.offsets.push(offset);
			_currentState.numTriangles.push(numTriangles);
		}

		public function clear(red		: Number	= 0.,
							  green		: Number	= 0.,
							  blue		: Number	= 0.,
							  alpha		: Number	= 1.,
							  depth		: Number	= 1.,
							  stencil	: uint		= 0,
							  mask		: uint		= 0xffffffff)  :void
		{
//			_context.setScissorRectangle(null);
//			_context.clear(red, green, blue, alpha, depth, stencil, mask);

			_numTriangles = 0;
			_drawingTime = 0;

			_currentState = null;
			_numStates = 0;
		}

		public function drawToBackBuffer() : void
		{
			var time : int = getTimer();

			if (SORT && _numStates > 1)
				RendererState.sort(_states, _numStates);

			var actualState : RendererState = null;

			for (var i : int = 0; i < _numStates; ++i)
			{
				var state			: RendererState = _states[i];
				var offsets 		: Vector.<uint>	= state.offsets;
				var numTriangles 	: Vector.<int> 	= state.numTriangles;
				var numCalls 		: int 			= offsets.length;

				state.prepareContext(_context, actualState);

				for (var j : int = 0; j < numCalls; ++j)
				{
					var iStream : IndexStream	= state._indexStream;
					var iBuffer : IndexBuffer3D = iStream.getIndexBuffer3D(_context);
					var count	: int			= numTriangles[j];

					_numTriangles += count == -1
									 ? state._indexStream.length / 3.
									 : count;

					_context.drawTriangles(iBuffer, offsets[j], count);
				}

				actualState = state;
			}

			_drawingTime += getTimer() - time;
		}

		public function present() : void
		{
			var time : int = getTimer();

			if (_numStates != 0)
				_context.present();

			_drawingTime += getTimer() - time;
			++_frame;
		}

		public function dumpBackbuffer(bitmapData : BitmapData) : void
		{
			var time : int = getTimer();

			if (_numStates != 0)
				_context.drawToBitmapData(bitmapData);

			_drawingTime += getTimer() - time;
			++_frame;
		}
	}
}

Fix rendering when scene is empty (backbuffer cannot be dumped when nothing was drawn on it) [Romain's fix].


/**
  * LzXMLTranslator.lzs
  *
  * @copyright Copyright 2001-2008 Laszlo Systems, Inc.  All Rights Reserved.
  *            Use is subject to license terms.
  *
  * @topic Kernel
  * @subtopic AS2
  */

/**
  * @shortdesc: Utility for converting native XML DOM object into LzDataNode tree
  */

public class LzXMLTranslator {

static function copyXML (xmlobj, trimwhitespace, nsprefix) {
    var lfcnode = copyFlashXML(xmlobj, trimwhitespace, nsprefix);
    if (lfcnode == null) {
        trace('LzXMLTranslator.copyXML: lfcnode.children is null', lfcnode);
    }
    var fc = lfcnode;
    if ( fc is LzDataText ) {
        return null;
    }
    return fc;
}

static var whitespaceChars = {' ': true, '\r': true, '\n': true, '\t': true};

/**
  * trim whitespace from start and end of string
  * @access private
  */
static function trim( str ) {
    var whitech = whitespaceChars;
    var len = str.length;
    var sindex = 0;
    var eindex = str.length -1;
    var ch;
    while (sindex < len) {
        ch = str.charAt(sindex);
        if (whitech[ch] != true) break;
        sindex++;
    }

    while (eindex > sindex) {
        ch = str.charAt(eindex);
        if (whitech[ch] != true) break;
        eindex--;
    }

    return str.slice(sindex,eindex+1);
}

// Recursively copy a Flash XML(Node) tree into a LzDataElement
// tree. Used by LzDataNode.stringToLzData
/**
  * @param boolean trimwhitespace: trim whitespace from start and end of text nodes
  * @param boolean nsprefix: preserve namespace prefixes on node names and attribute names
  * @access private
  */
static function copyFlashXML (node, trimwhitespace, nsprefix) {
    var lfcnode = null;
    // text node?
    if (node.nodeKind() == 'text') {
        var nv = node.toString();
        if (trimwhitespace == true) {
            nv = trim(nv);
        }
        lfcnode = new LzDataText(nv);
//PBR Changed to match swf kernel
//    } else if (node.nodeKind() == 'element') {
      } else {
        var nattrs = node.attributes();
        var cattrs = {};
        for (var i:int = 0; i < nattrs.length(); i++) {
            var key = nsprefix ? nattrs[i].name() : nattrs[i].localName();
            cattrs[key] = nattrs[i];
        }

        var nname = node.localName();
        if (nname && !nsprefix) {
            // strip namespace prefix
            var npos = nname.indexOf(':');
            if (npos >= 0) {
                nname = nname.substring(npos+1);
            }
        }

        lfcnode = new LzDataElement(nname, cattrs);
        var children = node.children();
        var newchildren = [];
        for (var i  = 0; i < children.length(); i++ ) {
            var child = children[i];
            var lfcchild = copyFlashXML(child, trimwhitespace, nsprefix);
            newchildren[i] = lfcchild;
        }
        lfcnode.setChildNodes(newchildren);
    }
    return lfcnode;
}

} // End of LzXMLTranslator

/**
  * LzXMLTranslator.lzs
  *
  * @copyright Copyright 2001-2008 Laszlo Systems, Inc.  All Rights Reserved.
  *            Use is subject to license terms.
  *
  * @topic Kernel
  * @subtopic AS2
  */

/**
  * @shortdesc: Utility for converting native XML DOM object into LzDataNode tree
  */

public class LzXMLTranslator {

static function copyXML (xmlobj:XML, trimwhitespace:Boolean, nsprefix:Boolean) :LzDataElementMixin {
    var lfcnode:LzDataNodeMixin = copyFlashXML(xmlobj, trimwhitespace, nsprefix);
    if (lfcnode == null) {
        trace('LzXMLTranslator.copyXML: lfcnode.children is null', lfcnode);
    }

    if ( lfcnode is LzDataText ) {
        return null;
    }

    return (lfcnode cast LzDataElementMixin);
}

static var whitespaceChars = {' ': true, '\r': true, '\n': true, '\t': true};

/**
  * trim whitespace from start and end of string
  * @access private
  */
static function trim( str:String ) :String {
    var whitech:Object = whitespaceChars;
    var len:int = str.length;
    var sindex:int = 0;
    var eindex:int = str.length -1;
    var ch:String;
    while (sindex < len) {
        ch = str.charAt(sindex);
        if (whitech[ch] != true) break;
        sindex++;
    }

    while (eindex > sindex) {
        ch = str.charAt(eindex);
        if (whitech[ch] != true) break;
        eindex--;
    }

    return str.slice(sindex,eindex+1);
}

// Recursively copy a Flash XML(Node) tree into a LzDataElement
// tree. Used by LzDataNode.stringToLzData
/**
  * @param boolean trimwhitespace: trim whitespace from start and end of text nodes
  * @param boolean nsprefix: preserve namespace prefixes on node names and attribute names
  * @access private
  */
static function copyFlashXML (node:XML, trimwhitespace:Boolean, nsprefix:Boolean) :LzDataNodeMixin {
    var lfcnode:LzDataNodeMixin = null;
    // text node?
    if (node.nodeKind() == 'text') {
        var nv:String = node.toString();
        if (trimwhitespace == true) {
            nv = trim(nv);
        }
        lfcnode = new LzDataText(nv);
//PBR Changed to match swf kernel
//    } else if (node.nodeKind() == 'element') {
      } else {

        var nattrs:XMLList = node.attributes();
        var cattrs:Object = {};
        for (var i:int = 0; i < nattrs.length(); i++) {
            var attr:XML = nattrs[i];
            var qattr:QName = attr.name();
            if (nsprefix) {
                var ns:Namespace = attr.namespace();
                var key:String;
                if (ns != null && ns.prefix != "") {
                    key = ns.prefix + ":" + qattr.localName;
                } else {
                    key = qattr.localName;
                }
                cattrs[key] = attr.toString();
            } else {
                cattrs[qattr.localName] = attr.toString();
            }
        }

        var nname:String;
        var qname:QName = node.name();
        if (nsprefix) {
            var ns:Namespace = node.namespace();
            if (ns != null && ns.prefix != "") {
                nname = ns.prefix + ":" + qname.localName;
            } else {
                nname = qname.localName;
            }
        } else {
            nname = qname.localName;
        }

        lfcnode = new LzDataElement(nname, cattrs);
        var children:XMLList = node.children();
        var newchildren:Array = [];
        for (var i:int  = 0; i < children.length(); i++ ) {
            var child:XML = children[i];
            var lfcchild:LzDataNodeMixin = copyFlashXML(child, trimwhitespace, nsprefix);
            newchildren[i] = lfcchild;
        }
        (lfcnode cast LzDataElement).setChildNodes(newchildren);
    }
    return lfcnode;
}

} // End of LzXMLTranslator

Change 20080601-bargull-Vzq by bargull@dell--p4--2-53 on 2008-06-01 00:56:07
    in /home/Admin/src/svn/openlaszlo/trunk
    for http://svn.openlaszlo.org/openlaszlo/trunk

Summary: Add nsprefix support to swf9

New Features:

Bugs Fixed: LPP-6078

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

Documentation:

Release Notes:

Details:
Added support for nsprefix to the xml-translator.

Tests:

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


package server {
	dynamic public class FMSClient extends Object {
		public function FMSClient() {
			super();
		}

		public function onRegisterUser(user:String, result:Object):void {
			trace('FMSClient.onRegisterUser:', user, result);
		}

		public function onSigninUser(user:String, result:Object):void {
			trace('FMSClient.onSigninUser:', user, result);
		}

		public function onStartGame(user:String):void {
			trace('FMSClient.onStartGame:', user);
		}

		public function onChangePlayer(user:String, player:uint):void {
			trace('FMSClient.onChangePlayer:', user, player);
		}

		public function onUpdateScore(score:uint):void {
			trace('FMSClient.onUpdateScore:', score);
		}

		public function onDisconnect(user:String):void {
			trace('FMSClient.onDisconnect:', user);
		}
	}
}

package server {
	dynamic public class FMSClient extends Object {
		public function FMSClient() {
			super();
		}

		public function onRegisterUser(user:String, result:Object):void {
			trace('FMSClient.onRegisterUser:', user, result);
		}

		public function onSigninUser(user:String, result:Object):void {
			trace('FMSClient.onSigninUser:', user, result);
		}

		public function onStartGame(user:String):void {
			trace('FMSClient.onStartGame:', user);
		}

		public function onChangePlayer(user:String, player:uint):void {
			trace('FMSClient.onChangePlayer:', user, player);
		}

		public function onUpdateScore(user:String, score:uint):void {
			trace('FMSClient.onUpdateScore:', user, score);
		}

		public function onDisconnect(user:String):void {
			trace('FMSClient.onDisconnect:', user);
		}
	}
}

Update FMSClient.as

Update FMSClient.as


package com.kaltura.kdpfl.plugin
{
	import com.akamai.osmf.utils.AkamaiStrings;
	import com.kaltura.kdpfl.model.ConfigProxy;
	import com.kaltura.kdpfl.model.MediaProxy;
	import com.kaltura.kdpfl.model.type.NotificationType;
	import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;

	import org.osmf.events.MediaElementEvent;
	import org.osmf.traits.DVRTrait;
	import org.osmf.traits.MediaTraitType;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;

	public class akamaiHDMediator extends Mediator
	{

		public static const NAME:String = "akamaiHDMediator";
		/**
		 * default buffer length to be used when playing with HD Akamai plugin
		 */
		public static const DEFAULT_HD_BUFFER_LENGTH:int = 20;

		/**
		 * default bandwith check time in seconds
		 */
		public static const DEFAULT_HD_BANDWIDTH_CHECK_TIME:int = 2;

		private var _mediaProxy:MediaProxy;
		private var _flashvars:Object;

		public function akamaiHDMediator(viewComponent:Object=null)
		{
			super(NAME, viewComponent);
		}

		override public function onRegister():void
		{
			_mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
			_flashvars = (facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy).vo.flashvars;
			super.onRegister();
		}

		override public function listNotificationInterests():Array
		{
			return [
				NotificationType.MEDIA_READY,
				NotificationType.PLAYER_PLAYED,
				NotificationType.MEDIA_ELEMENT_READY
			];
		}

		override public function handleNotification(notification:INotification):void
		{
			switch (notification.getName())
			{
				case NotificationType.PLAYER_PLAYED:
					//workaround to display the bitrate that was automatically detected by akamai
					if (_flashvars.hdnetworkEnableBRDetection && _flashvars.hdnetworkEnableBRDetection=="true")
					{
						_mediaProxy.notifyStartingIndexChanged((facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).player.currentDynamicStreamIndex);
					}
					break;

				case NotificationType.MEDIA_READY:
					//add akamai metadata on the stream resource

					//find last index of resource metadata flashvars.
					var i:int = 0;
					while (_flashvars.hasOwnProperty("objMetadataNamespace" + i) && _flashvars.hasOwnProperty("objMetadataValues" + i))
					{
						i++;
					}

					var bufferLength:int = DEFAULT_HD_BUFFER_LENGTH;
					if (_flashvars.hdnetworkBufferLength && _flashvars.hdnetworkBufferLength!="")
					{
						bufferLength = _flashvars.hdnetworkBufferLength;
					}

					//Then add akamai resource metadata on the next index
					_flashvars["objMetadataNamespace"+i] = AkamaiStrings.AKAMAI_ADVANCED_STREAMING_PLUGIN_METADATA_NAMESPACE;
					//set buffer length
					var akamaiMetadataValues:String = AkamaiStrings.AKAMAI_METADATA_KEY_MAX_BUFFER_LENGTH + "=" + bufferLength;

					if (_flashvars.hdnetworkEnableBRDetection && _flashvars.hdnetworkEnableBRDetection=="true")
					{
						//var bwEstimationObject:Object = new Object();
						//bwEstimationObject.enabled = true;
						var bandwidthEstimationPeriodInSeconds:int;
						if (_flashvars.hdnetworkBRDetectionTime && _flashvars.hdnetworkBRDetectionTime!="")
						{
							bandwidthEstimationPeriodInSeconds = _flashvars.hdnetworkBRDetectionTime;
						}
						else
						{
							bandwidthEstimationPeriodInSeconds = DEFAULT_HD_BANDWIDTH_CHECK_TIME;
						}
						//enable akamai BW detection
						akamaiMetadataValues += "&"+ AkamaiStrings.AKAMAI_METADATA_KEY_SET_BANDWIDTH_ESTIMATION_ENABLED + "={enabled:true,bandwidthEstimationPeriodInSeconds:"+bandwidthEstimationPeriodInSeconds+"}";
					}
					else
					{
						var preferedIndex:int = _mediaProxy.getFlavorByBitrate(_mediaProxy.vo.preferedFlavorBR);
						if (preferedIndex!=-1)
						{
							akamaiMetadataValues += "&" + AkamaiStrings.AKAMAI_METDATA_KEY_MBR_STARTING_INDEX + "=" + preferedIndex;
							_mediaProxy.notifyStartingIndexChanged(preferedIndex);
						}
					}

					_flashvars["objMetadataValues"+i] = akamaiMetadataValues;
					break;

				case NotificationType.MEDIA_ELEMENT_READY:
					if (_mediaProxy.vo.isLive && _mediaProxy.vo.canSeek && _mediaProxy.vo.media)
					{
						_mediaProxy.vo.media.addEventListener(MediaElementEvent.TRAIT_ADD, onMediaTraitAdd);

					}
					break;
			}
		}

		/**
		 * sets DVR window size according to actual window size (including Akamai's padding)
		 * @param e
		 *
		 */
		private function onMediaTraitAdd(e: MediaElementEvent) :  void
		{
			if (e.traitType==MediaTraitType.DVR)
			{
				var dvrTrait:DVRTrait = _mediaProxy.vo.media.getTrait(MediaTraitType.DVR) as DVRTrait;
				(facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).dvrWinSize = dvrTrait.windowDuration;
				_mediaProxy.vo.media.removeEventListener(MediaElementEvent.TRAIT_ADD, onMediaTraitAdd);
			}

		}

	}
}

package com.kaltura.kdpfl.plugin
{
	import com.akamai.osmf.utils.AkamaiStrings;
	import com.kaltura.kdpfl.model.ConfigProxy;
	import com.kaltura.kdpfl.model.MediaProxy;
	import com.kaltura.kdpfl.model.type.NotificationType;
	import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;

	import org.osmf.events.MediaElementEvent;
	import org.osmf.traits.DVRTrait;
	import org.osmf.traits.MediaTraitType;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;

	public class akamaiHDMediator extends Mediator
	{

		public static const NAME:String = "akamaiHDMediator";
		/**
		 * default buffer length to be used when playing with HD Akamai plugin
		 */
		public static const DEFAULT_HD_BUFFER_LENGTH:int = 20;

		/**
		 * default bandwith check time in seconds
		 */
		public static const DEFAULT_HD_BANDWIDTH_CHECK_TIME:int = 2;

		private var _mediaProxy:MediaProxy;
		private var _flashvars:Object;

		public function akamaiHDMediator(viewComponent:Object=null)
		{
			super(NAME, viewComponent);
		}

		override public function onRegister():void
		{
			_mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
			_flashvars = (facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy).vo.flashvars;
			super.onRegister();
		}

		override public function listNotificationInterests():Array
		{
			return [
				NotificationType.MEDIA_READY,
				NotificationType.PLAYER_PLAYED,
				NotificationType.MEDIA_ELEMENT_READY
			];
		}

		override public function handleNotification(notification:INotification):void
		{
			switch (notification.getName())
			{
				case NotificationType.PLAYER_PLAYED:
					//workaround to display the bitrate that was automatically detected by akamai
					if (_flashvars.hdnetworkEnableBRDetection && _flashvars.hdnetworkEnableBRDetection=="true")
					{
						_mediaProxy.notifyStartingIndexChanged((facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).player.currentDynamicStreamIndex);
					}
					break;

				case NotificationType.MEDIA_READY:
					//add akamai metadata on the stream resource

					//find last index of resource metadata flashvars.
					var i:int = 0;
					while (_flashvars.hasOwnProperty("objMetadataNamespace" + i) && _flashvars.hasOwnProperty("objMetadataValues" + i))
					{
						i++;
					}

					var bufferLength:int = DEFAULT_HD_BUFFER_LENGTH;
					if (_flashvars.hdnetworkBufferLength && _flashvars.hdnetworkBufferLength!="")
					{
						bufferLength = _flashvars.hdnetworkBufferLength;
					}

					//Then add akamai resource metadata on the next index
					_flashvars["objMetadataNamespace"+i] = AkamaiStrings.AKAMAI_ADVANCED_STREAMING_PLUGIN_METADATA_NAMESPACE;
					//set buffer length
					var akamaiMetadataValues:String = AkamaiStrings.AKAMAI_METADATA_KEY_MAX_BUFFER_LENGTH + "=" + bufferLength;

					if (_flashvars.hdnetworkEnableBRDetection && _flashvars.hdnetworkEnableBRDetection=="true")
					{
						//var bwEstimationObject:Object = new Object();
						//bwEstimationObject.enabled = true;
						var bandwidthEstimationPeriodInSeconds:int;
						if (_flashvars.hdnetworkBRDetectionTime && _flashvars.hdnetworkBRDetectionTime!="")
						{
							bandwidthEstimationPeriodInSeconds = _flashvars.hdnetworkBRDetectionTime;
						}
						else
						{
							bandwidthEstimationPeriodInSeconds = DEFAULT_HD_BANDWIDTH_CHECK_TIME;
						}
						//enable akamai BW detection
						akamaiMetadataValues += "&"+ AkamaiStrings.AKAMAI_METADATA_KEY_SET_BANDWIDTH_ESTIMATION_ENABLED + "={enabled:true,bandwidthEstimationPeriodInSeconds:"+bandwidthEstimationPeriodInSeconds+"}";
					}
					else
					{
						var preferedIndex:int = _mediaProxy.getFlavorByBitrate(_mediaProxy.vo.preferedFlavorBR);
						if (preferedIndex!=-1)
						{
							akamaiMetadataValues += "&" + AkamaiStrings.AKAMAI_METADATA_KEY_MBR_STARTING_INDEX + "=" + preferedIndex;
							_mediaProxy.notifyStartingIndexChanged(preferedIndex);
						}
					}

					_flashvars["objMetadataValues"+i] = akamaiMetadataValues;
					break;

				case NotificationType.MEDIA_ELEMENT_READY:
					if (_mediaProxy.vo.isLive && _mediaProxy.vo.canSeek && _mediaProxy.vo.media)
					{
						_mediaProxy.vo.media.addEventListener(MediaElementEvent.TRAIT_ADD, onMediaTraitAdd);

					}
					break;
			}
		}

		/**
		 * sets DVR window size according to actual window size (including Akamai's padding)
		 * @param e
		 *
		 */
		private function onMediaTraitAdd(e: MediaElementEvent) :  void
		{
			if (e.traitType==MediaTraitType.DVR)
			{
				var dvrTrait:DVRTrait = _mediaProxy.vo.media.getTrait(MediaTraitType.DVR) as DVRTrait;
				(facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).dvrWinSize = dvrTrait.windowDuration;
				_mediaProxy.vo.media.removeEventListener(MediaElementEvent.TRAIT_ADD, onMediaTraitAdd);
			}

		}

	}
}

fix akamai mbr starting index type

fix akamai mbr starting index type


package aerys.minko.type.loader
{
	import aerys.minko.render.resource.texture.TextureResource;
	import aerys.minko.type.Signal;

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	import flash.utils.getQualifiedClassName;

	public class TextureLoader implements ILoader
	{
		private var _progress			: Signal;
		private var _error				: Signal;
		private var _complete			: Signal;

		private var _isComplete			: Boolean;

		private var _mipmap				: Boolean;
		private var _textureResource	: TextureResource;

		public function get progress() : Signal
		{
			return _progress;
		}

		public function get error() : Signal
		{
			return _error;
		}

		public function get complete() : Signal
		{
			return _complete;
		}

		public function get isComplete() : Boolean
		{
			return _isComplete;
		}

		public function get textureResource() : TextureResource
		{
			return _textureResource;
		}

		public function TextureLoader(enableMipmapping : Boolean = true)
		{
			_mipmap				= enableMipmapping;

			_textureResource 	= new TextureResource();
			_isComplete 		= false;
			_error				= new Signal('TextureLoader.error');
			_progress			= new Signal('TextureLoader.progress');
			_complete			= new Signal('TextureLoader.complete');
		}

		public function load(request : URLRequest) : void
		{
			var loader : URLLoader = new URLLoader();

			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler);
			loader.addEventListener(Event.COMPLETE, loadCompleteHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR, loadIoErrorHandler);
			loader.load(request);
		}

		private function loadIoErrorHandler(e : IOErrorEvent) : void
		{
			_textureResource = null;
			_error.execute(this, e.errorID, e.text);
		}

		private function loadProgressHandler(e : ProgressEvent) : void
		{
			_progress.execute(this, e.bytesLoaded, e.bytesTotal);
		}

		private function loadCompleteHandler(e : Event) : void
		{
			loadBytes(URLLoader(e.currentTarget).data);
		}

		public function loadClass(classObject : Class) : void
		{
			var assetObject : Object		= new classObject();

			if (assetObject is Bitmap || assetObject is BitmapData)
			{
				var bitmapData : BitmapData = assetObject as BitmapData;
				if (bitmapData == null)
					bitmapData = Bitmap(assetObject).bitmapData;

//				_textureResource = new TextureResource();
				_textureResource.setContentFromBitmapData(bitmapData, _mipmap);
				_complete.execute(this, _textureResource);
				_isComplete = true;
			}
			else if (assetObject is ByteArray)
			{
				loadBytes(ByteArray(assetObject));
			}
			else
			{
				var className : String = getQualifiedClassName(classObject);
				className = className.substr(className.lastIndexOf(':') + 1);

				_isComplete = true;

				throw new Error('No texture can be created from an object of type \'' + className + '\'');
			}
		}

		public function loadBytes(bytes : ByteArray) : void
		{
			bytes.position = 0;

			if (bytes.readByte() == 'A'.charCodeAt(0) &&
				bytes.readByte() == 'T'.charCodeAt(0) &&
				bytes.readByte() == 'F'.charCodeAt(0))
			{
				bytes.position = 0;
//				_textureResource = new TextureResource();
				_textureResource.setContentFromATF(bytes);
				_complete.execute(this, _textureResource);
				_isComplete = true;
			}
			else
			{
				bytes.position = 0;

				var loader : Loader = new Loader();
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadBytesCompleteHandler);
				loader.loadBytes(bytes);
			}
		}

		private function loadBytesCompleteHandler(e : Event) : void
		{
			var displayObject : DisplayObject = LoaderInfo(e.currentTarget).content;

			if (displayObject is Bitmap)
			{
				_textureResource.setContentFromBitmapData(Bitmap(displayObject).bitmapData, _mipmap);
				_complete.execute(this, _textureResource);
				_isComplete = true;
			}
			else
			{
				var className : String = getQualifiedClassName(displayObject);

				className = className.substr(className.lastIndexOf(':') + 1);
				_isComplete = true;
				throw new Error('No texture can be created from an object of type \'' + className + '\'');
			}
		}

		public static function loadClass(classObject 		: Class,
										 enableMipMapping 	: Boolean = true) : TextureResource
		{
			var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);

			textureLoader.loadClass(classObject);

			return textureLoader.textureResource;
		}

		public static function load(request				: URLRequest,
									enableMipMapping 	: Boolean = true) : TextureResource
		{
			var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);

			textureLoader.load(request);

			return textureLoader.textureResource;
		}

		public static function loadBytes(bytes				: ByteArray,
										 enableMipMapping 	: Boolean = true) : TextureResource
		{
			var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);

			textureLoader.loadBytes(bytes);

			return textureLoader.textureResource;
		}
	}
}

package aerys.minko.type.loader
{
	import aerys.minko.render.resource.texture.TextureResource;
	import aerys.minko.type.Signal;

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	import flash.utils.getQualifiedClassName;

	public class TextureLoader implements ILoader
	{
		private var _progress			: Signal;
		private var _error				: Signal;
		private var _complete			: Signal;

		private var _isComplete			: Boolean;

		private var _mipmap				: Boolean;

		protected var _textureResource	: TextureResource;

		public function get progress() : Signal
		{
			return _progress;
		}

		public function get error() : Signal
		{
			return _error;
		}

		public function get complete() : Signal
		{
			return _complete;
		}

		public function get isComplete() : Boolean
		{
			return _isComplete;
		}

		public function get textureResource() : TextureResource
		{
			return _textureResource;
		}

		public function TextureLoader(enableMipmapping : Boolean = true)
		{
			_mipmap				= enableMipmapping;

			_textureResource 	= new TextureResource();
			_isComplete 		= false;
			_error				= new Signal('TextureLoader.error');
			_progress			= new Signal('TextureLoader.progress');
			_complete			= new Signal('TextureLoader.complete');
		}

		public function load(request : URLRequest) : void
		{
			var loader : URLLoader = new URLLoader();

			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler);
			loader.addEventListener(Event.COMPLETE, loadCompleteHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR, loadIoErrorHandler);
			loader.load(request);
		}

		private function loadIoErrorHandler(e : IOErrorEvent) : void
		{
			_textureResource = null;
			_error.execute(this, e.errorID, e.text);
		}

		private function loadProgressHandler(e : ProgressEvent) : void
		{
			_progress.execute(this, e.bytesLoaded, e.bytesTotal);
		}

		private function loadCompleteHandler(e : Event) : void
		{
			loadBytes(URLLoader(e.currentTarget).data);
		}

		public function loadClass(classObject : Class) : void
		{
			var assetObject : Object		= new classObject();

			if (assetObject is Bitmap || assetObject is BitmapData)
			{
				var bitmapData : BitmapData = assetObject as BitmapData;
				if (bitmapData == null)
					bitmapData = Bitmap(assetObject).bitmapData;

//				_textureResource = new TextureResource();
				_textureResource.setContentFromBitmapData(bitmapData, _mipmap);
				_complete.execute(this, _textureResource);
				_isComplete = true;
			}
			else if (assetObject is ByteArray)
			{
				loadBytes(ByteArray(assetObject));
			}
			else
			{
				var className : String = getQualifiedClassName(classObject);
				className = className.substr(className.lastIndexOf(':') + 1);

				_isComplete = true;

				throw new Error('No texture can be created from an object of type \'' + className + '\'');
			}
		}

		public function loadBytes(bytes : ByteArray) : void
		{
			bytes.position = 0;

			if (bytes.readByte() == 'A'.charCodeAt(0) &&
				bytes.readByte() == 'T'.charCodeAt(0) &&
				bytes.readByte() == 'F'.charCodeAt(0))
			{
				bytes.position = 0;
//				_textureResource = new TextureResource();
				_textureResource.setContentFromATF(bytes);
				_complete.execute(this, _textureResource);
				_isComplete = true;
			}
			else
			{
				bytes.position = 0;

				var loader : Loader = new Loader();
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadBytesCompleteHandler);
				loader.loadBytes(bytes);
			}
		}

		private function loadBytesCompleteHandler(e : Event) : void
		{
			var displayObject : DisplayObject = LoaderInfo(e.currentTarget).content;

			if (displayObject is Bitmap)
			{
				_textureResource.setContentFromBitmapData(Bitmap(displayObject).bitmapData, _mipmap);
				_complete.execute(this, _textureResource);
				_isComplete = true;
			}
			else
			{
				var className : String = getQualifiedClassName(displayObject);

				className = className.substr(className.lastIndexOf(':') + 1);
				_isComplete = true;
				throw new Error('No texture can be created from an object of type \'' + className + '\'');
			}
		}

		public static function loadClass(classObject 		: Class,
										 enableMipMapping 	: Boolean = true) : TextureResource
		{
			var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);

			textureLoader.loadClass(classObject);

			return textureLoader.textureResource;
		}

		public static function load(request				: URLRequest,
									enableMipMapping 	: Boolean = true) : TextureResource
		{
			var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);

			textureLoader.load(request);

			return textureLoader.textureResource;
		}

		public static function loadBytes(bytes				: ByteArray,
										 enableMipMapping 	: Boolean = true) : TextureResource
		{
			var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);

			textureLoader.loadBytes(bytes);

			return textureLoader.textureResource;
		}
	}
}

Make TextureLoader extendable.

Make TextureLoader extendable.


//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

package com.threerings.ezgame {

import flash.display.DisplayObject;
import flash.display.Sprite;

import flash.text.StyleSheet;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;

/**
 * A sample component that displays the players of a game.  If the game has a turn holder, the
 * current turn holder will be highlighted.
 *
 * This class demonstrates that the 'Game' interface may be implemented by any DisplayObject that
 * want access to the GameObject, not just the actual DisplayObject that is displaying the
 * game. Here, all we are interested in is the names of the players and the current turn holder.
 *
 * You may use this, with any modifications you desire, in your game. Feel free to copy/modify or
 * extend this class.
 */
public class PlayersDisplay extends Sprite
    implements StateChangedListener
{
    /**
     * Set the game control that will be used with this display.
     */
    public function setGameControl (gameCtrl :EZGameControl) :void
    {
        _gameCtrl = gameCtrl;
        _gameCtrl.registerListener(this);

        configureInterface();
    }

    // from StateChangedListener
    public function stateChanged (event :StateChangedEvent) :void
    {
        displayCurrentTurn();
    }

    /**
     * Set up the player labels and configure the look of the entire UI.
     */
    protected function configureInterface () :void
    {
        var border :int = getBorderSpacing();
        var pad :int = getInternalSpacing();
        var y :Number = border;
        var maxWidth :Number = 0;
        var label :TextField;
        var icon :DisplayObject;

        // create a label at the top, above the player names
        label = createHeader();
        if (label != null) {
            label.x = border;
            label.y = y;
            addChild(label);
            y += label.textHeight + pad;
            maxWidth = label.textWidth + TEXTWIDTH_ADD;
        }

        if (!_gameCtrl.isConnected()) {
            return; // nothing to do
        }

        var players :Array = _gameCtrl.seating.getPlayerIds();

        // create a label for each player
        for each (var playerId :int in players) {
            var name :String = _gameCtrl.getOccupantName(playerId);
            label = createPlayerLabel(playerId, name);
            icon = createPlayerIcon(playerId, name);
            var iconW :int = 0;
            var iconH :int = 0;
            if (icon != null) {
                iconW = icon.width + pad;
                iconH = icon.height;

                icon.x = border;
                icon.y = y;
                addChild(icon);
            }
            label.x = border + iconW;
            label.y = y;
            addChild(label);
            y += Math.max(label.textHeight, iconH) + pad;
            maxWidth = Math.max(maxWidth, iconW + label.textWidth + TEXTWIDTH_ADD);

            _playerLabels.push(label);
        }

        // make all the player labels the same width (looks nice when highlighted)
        for each (label in _playerLabels) {
            label.autoSize = TextFieldAutoSize.NONE;
            label.width = maxWidth - (label.x - border);
        }

        // y has a pad at the end, we want border instead
        y += border - pad;
        drawBorder(maxWidth);

        displayCurrentTurn();
    }

    protected function createHeader () :TextField
    {
        var label :TextField = new TextField();
// damn stylesheet doesn't seem to actually -work-
//        var style :StyleSheet = new StyleSheet();
//        style.fontWeight = "bold";
//        style.color = "#0000FF";
//        style.fontFamily = "serif";
//        style.fontSize = 18;
//        label.styleSheet = style;
        label.autoSize = TextFieldAutoSize.LEFT;
        label.selectable = false;
        label.text = "Players";
        return label;
    }

    /**
     * Create a TextArea that will be used to display player names.
     */
    protected function createPlayerLabel (playerId :int, name :String) :TextField
    {
        var label :TextField = new TextField();
        label.autoSize = TextFieldAutoSize.LEFT;
        label.background = true;
        label.selectable = false;
        label.text = name;
        return label;
    }

    protected function createPlayerIcon (playerId :int, name :String) :DisplayObject
    {
        return null;
    }

    protected function drawBorder (var maxWidth :int) :void
    {
        // draw a blue rectangle around everything
        graphics.clear();
        graphics.lineStyle(1, 0x0000FF);
        graphics.drawRect(0, 0, maxWidth + (border * 2), y);
    }

    protected function getBackground (isTurn :Boolean) :uint
    {
        return isTurn ? 0xFF9999 : 0xFFFFFF;
    }

    protected function getBorderSpacing () :int
    {
        return 6;
    }

    protected function getInternalSpacing () :int
    {
        return 2;
    }

    /**
     * Re-set the background color for every player label, highlighting only the player who has the
     * turn.
     */
    protected function displayCurrentTurn () :void
    {
        var idx :int = _gameCtrl.isInPlay() ?
            _gameCtrl.seating.getPlayerPosition(_gameCtrl.getTurnHolder()) : -1;
        for (var ii :int = 0; ii < _playerLabels.length; ii++) {
            var label :TextField = (_playerLabels[ii] as TextField);
            label.backgroundColor = getBackground(ii == idx);
        }
    }

    /** Our game Control. */
    protected var _gameCtrl :EZGameControl;

    /** An array of labels, one for each player name. */
    protected var _playerLabels :Array = [];

    /** These are fucking ridiculous. */
    protected static const TEXTWIDTH_ADD :int = 5;
    protected static const TEXTHEIGHT_ADD :int = 4;
}
}

//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

package com.threerings.ezgame {

import flash.display.DisplayObject;
import flash.display.Sprite;

import flash.text.StyleSheet;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;

/**
 * A sample component that displays the players of a game.  If the game has a turn holder, the
 * current turn holder will be highlighted.
 *
 * This class demonstrates that the 'Game' interface may be implemented by any DisplayObject that
 * want access to the GameObject, not just the actual DisplayObject that is displaying the
 * game. Here, all we are interested in is the names of the players and the current turn holder.
 *
 * You may use this, with any modifications you desire, in your game. Feel free to copy/modify or
 * extend this class.
 */
public class PlayersDisplay extends Sprite
    implements StateChangedListener
{
    /**
     * Set the game control that will be used with this display.
     */
    public function setGameControl (gameCtrl :EZGameControl) :void
    {
        _gameCtrl = gameCtrl;
        _gameCtrl.registerListener(this);

        configureInterface();
    }

    // from StateChangedListener
    public function stateChanged (event :StateChangedEvent) :void
    {
        displayCurrentTurn();
    }

    /**
     * Set up the player labels and configure the look of the entire UI.
     */
    protected function configureInterface () :void
    {
        var border :int = getBorderSpacing();
        var pad :int = getInternalSpacing();
        var y :Number = border;
        var maxWidth :Number = 0;
        var label :TextField;
        var icon :DisplayObject;

        // create a label at the top, above the player names
        label = createHeader();
        if (label != null) {
            label.x = border;
            label.y = y;
            addChild(label);
            y += label.textHeight + pad;
            maxWidth = label.textWidth + TEXTWIDTH_ADD;
        }

        if (!_gameCtrl.isConnected()) {
            return; // nothing to do
        }

        var players :Array = _gameCtrl.seating.getPlayerIds();

        // create a label for each player
        for each (var playerId :int in players) {
            var name :String = _gameCtrl.getOccupantName(playerId);
            label = createPlayerLabel(playerId, name);
            icon = createPlayerIcon(playerId, name);
            var iconW :int = 0;
            var iconH :int = 0;
            if (icon != null) {
                iconW = icon.width + pad;
                iconH = icon.height;

                icon.x = border;
                icon.y = y;
                addChild(icon);
            }
            label.x = border + iconW;
            label.y = y;
            addChild(label);
            y += Math.max(label.textHeight, iconH) + pad;
            maxWidth = Math.max(maxWidth, iconW + label.textWidth + TEXTWIDTH_ADD);

            _playerLabels.push(label);
        }

        // make all the player labels the same width (looks nice when highlighted)
        for each (label in _playerLabels) {
            label.autoSize = TextFieldAutoSize.NONE;
            label.width = maxWidth - (label.x - border);
        }

        // y has a pad at the end, we want border instead
        y += border - pad;
        drawBorder(maxWidth);

        displayCurrentTurn();
    }

    protected function createHeader () :TextField
    {
        var label :TextField = new TextField();
// damn stylesheet doesn't seem to actually -work-
//        var style :StyleSheet = new StyleSheet();
//        style.fontWeight = "bold";
//        style.color = "#0000FF";
//        style.fontFamily = "serif";
//        style.fontSize = 18;
//        label.styleSheet = style;
        label.autoSize = TextFieldAutoSize.LEFT;
        label.selectable = false;
        label.text = "Players";
        return label;
    }

    /**
     * Create a TextArea that will be used to display player names.
     */
    protected function createPlayerLabel (playerId :int, name :String) :TextField
    {
        var label :TextField = new TextField();
        label.autoSize = TextFieldAutoSize.LEFT;
        label.background = true;
        label.selectable = false;
        label.text = name;
        return label;
    }

    protected function createPlayerIcon (playerId :int, name :String) :DisplayObject
    {
        return null;
    }

    protected function drawBorder (maxWidth :int) :void
    {
        // draw a blue rectangle around everything
        graphics.clear();
        graphics.lineStyle(1, 0x0000FF);
        graphics.drawRect(0, 0, maxWidth + (getBorderSpacing() * 2), y);
    }

    protected function getBackground (isTurn :Boolean) :uint
    {
        return isTurn ? 0xFF9999 : 0xFFFFFF;
    }

    protected function getBorderSpacing () :int
    {
        return 6;
    }

    protected function getInternalSpacing () :int
    {
        return 2;
    }

    /**
     * Re-set the background color for every player label, highlighting only the player who has the
     * turn.
     */
    protected function displayCurrentTurn () :void
    {
        var idx :int = _gameCtrl.isInPlay() ?
            _gameCtrl.seating.getPlayerPosition(_gameCtrl.getTurnHolder()) : -1;
        for (var ii :int = 0; ii < _playerLabels.length; ii++) {
            var label :TextField = (_playerLabels[ii] as TextField);
            label.backgroundColor = getBackground(ii == idx);
        }
    }

    /** Our game Control. */
    protected var _gameCtrl :EZGameControl;

    /** An array of labels, one for each player name. */
    protected var _playerLabels :Array = [];

    /** These are fucking ridiculous. */
    protected static const TEXTWIDTH_ADD :int = 5;
    protected static const TEXTHEIGHT_ADD :int = 4;
}
}

Fix booches.

Fix booches.

git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@335 c613c5cb-e716-0410-b11b-feb51c14d237


package flails.mxml {
  import com.asfusion.mate.actions.AbstractServiceInvoker;
  import com.asfusion.mate.actionLists.IScope;
  import com.asfusion.mate.actions.IAction;

  import mx.rpc.events.ResultEvent;
  import mx.rpc.events.FaultEvent;

  import flails.request.RequestPipe;
  import flails.resource.Resources;
  import flails.resource.Resource;

  public class ResourcefulServiceInvoker extends AbstractServiceInvoker implements IAction {
    public var resource:Resource;
    public var data:Array;
    public var type:String;
    public var id:String;
    public var parent:Object;

    [Bindable] public var result:Object;

    public function ResourcefulServiceInvoker() {
      currentInstance = this;
    }

    override protected function prepare(scope:IScope):void {
      super.prepare(scope);
    }

    override protected function run(scope:IScope):void {
      trace ("Using resource " + resource);

      var rp:RequestPipe = resource.newRequestPipe();

      innerHandlersDispatcher = rp;

      if (resultHandlers && resultHandlers.length > 0) {
        createInnerHandlers(scope, ResultEvent.RESULT, resultHandlers);
      }

      if (faultHandlers && faultHandlers.length > 0) {
        createInnerHandlers(scope, FaultEvent.FAULT, faultHandlers);
      }

      trace("calling " + type + "()");

      rp[type].apply(rp, data);
    }
  }
}

package flails.mxml {
  import com.asfusion.mate.actions.AbstractServiceInvoker;
  import com.asfusion.mate.actionLists.IScope;
  import com.asfusion.mate.actions.IAction;

  import mx.rpc.events.ResultEvent;
  import mx.rpc.events.FaultEvent;

  import flails.request.RequestPipe;
  import flails.resource.Resources;
  import flails.resource.Resource;

  public class ResourcefulServiceInvoker extends AbstractServiceInvoker implements IAction {
    private var _data:Array;

    public var resource:Resource;
    public var type:String;
    public var id:String;
    public var parent:Object;

    [Bindable] public var result:Object;

    public function set data(args:Object):void {
      trace("setting data");

      if (args is Array)
        _data = args as Array;
      else
        _data = [args];
    }

    override protected function prepare(scope:IScope):void {
      currentInstance = this;

      super.prepare(scope);
    }

    override protected function run(scope:IScope):void {
      trace ("Using resource " + resource);

      var rp:RequestPipe = resource.newRequestPipe();

      innerHandlersDispatcher = rp;

      if (resultHandlers && resultHandlers.length > 0) {
        createInnerHandlers(scope, ResultEvent.RESULT, resultHandlers);
      }

      if (faultHandlers && faultHandlers.length > 0) {
        createInnerHandlers(scope, FaultEvent.FAULT, faultHandlers);
      }

      trace("calling " + type + "() with " + _data);

      rp[type].apply(rp, _data);
    }
  }
}

Set currentInstance on prepare, not on instantiation time.


////////////////////////////////////////////////////////////////////////////////
//
//  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.utils
{
import org.apache.flex.core.UIMetrics;
import org.apache.flex.core.ValuesManager;

/**
 *  The BeadMetrics class is a utility class that computes the offset of the content
 *  in a container based on border-thickness and padding styles.
 *
 *  @langversion 3.0
 *  @playerversion Flash 10.2
 *  @playerversion AIR 2.6
 *  @productversion FlexJS 0.0
 */
public class BeadMetrics
{

    /**
     *  Compute the offset of the content
     *  in a container based on border-thickness and padding styles.
     *
     *  @param object The object with style values.
     *  @return The offsets of the content.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10.2
     *  @playerversion AIR 2.6
     *  @productversion FlexJS 0.0
     */
	public static function getMetrics(object:Object) : UIMetrics
	{
		var borderThickness:Object = ValuesManager.valuesImpl.getValue(object,"border-thickness");
		var borderOffset:Number;
		if( borderThickness == null ) {
			borderOffset = 0;
		}
		else {
			borderOffset = Number(borderThickness);
			if( isNaN(borderOffset) ) borderOffset = 0;
		}

		var paddingLeft:Object;
		var paddingTop:Object;
		var paddingRight:Object;
		var paddingBottom:Object;

		var padding:Object = ValuesManager.valuesImpl.getValue(object, "padding");
		if (padding is Array)
		{
			if (padding.length == 1)
				paddingLeft = paddingTop = padding[0];
			else if (padding.length <= 3)
			{
				paddingTop = padding[0];
				paddingLeft = padding[1];
				paddingBottom = padding[0];
				paddingRight = padding[1];
			}
			else if (padding.length == 4)
			{
				paddingTop = padding[0];
				paddingLeft = padding[1];
				paddingBottom = padding[2];
				paddingRight = padding[3];
			}
		}
		else if (padding == null)
		{
			paddingLeft = ValuesManager.valuesImpl.getValue(object, "padding-left");
			paddingTop = ValuesManager.valuesImpl.getValue(object, "padding-top");
			paddingRight = ValuesManager.valuesImpl.getValue(object, "padding-right");
			paddingBottom = ValuesManager.valuesImpl.getValue(object, "padding-bottom");
		}
		else
		{
			paddingLeft = paddingTop = padding;
			paddingRight = paddingBottom = padding;
		}
		var pl:Number = Number(paddingLeft);
		var pt:Number = Number(paddingTop);
		var pr:Number = Number(paddingRight);
		var pb:Number = Number(paddingBottom);

		var marginLeft:Object;
		var marginRight:Object;
		var marginTop:Object;
		var marginBottom:Object;
		var margin:Object;
		margin = ValuesManager.valuesImpl.getValue(object, "margin");

		if (margin is Array)
		{
			if (margin.length == 1)
				marginLeft = marginTop = marginRight = marginBottom = margin[0];
			else if (margin.length <= 3)
			{
				marginLeft = marginRight = margin[1];
				marginTop = marginBottom = margin[0];
			}
			else if (margin.length == 4)
			{
				marginLeft = margin[3];
				marginBottom = margin[2];
				marginRight = margin[1];
				marginTop = margin[0];
			}
		}
		else if (margin == null)
		{
			marginLeft = ValuesManager.valuesImpl.getValue(object, "margin-left");
			marginTop = ValuesManager.valuesImpl.getValue(object, "margin-top");
			marginRight = ValuesManager.valuesImpl.getValue(object, "margin-right");
			marginBottom = ValuesManager.valuesImpl.getValue(object, "margin-bottom");
		}
		else
		{
			marginLeft = marginTop = marginBottom = marginRight = margin;
		}
		var ml:Number;
		var mr:Number;
		var mt:Number;
		var mb:Number;
		var lastmr:Number;
		if (marginLeft == "auto")
			ml = 0;
		else
		{
			ml = Number(marginLeft);
			if (isNaN(ml))
				ml = 0;
		}
		if (marginRight == "auto")
			mr = 0;
		else
		{
			mr = Number(marginRight);
			if (isNaN(mr))
				mr = 0;
		}
		mt = Number(marginTop);
		if (isNaN(mt))
			mt = 0;
		mb = Number(marginBottom);
		if (isNaN(mb))
			mb = 0;

		var result:UIMetrics = new UIMetrics();
		result.top = borderOffset + pt;
		result.left = borderOffset + pl;
		result.bottom = borderOffset + pb;
		result.right = borderOffset + pr;
		result.marginTop = mt;
		result.marginLeft = ml;
		result.marginBottom = mb;
		result.marginRight = mr;

		return result;
	}
}
}

////////////////////////////////////////////////////////////////////////////////
//
//  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.utils
{
import org.apache.flex.core.UIMetrics;
import org.apache.flex.core.ValuesManager;

/**
 *  The BeadMetrics class is a utility class that computes the offset of the content
 *  in a container based on border-thickness and padding styles.
 *
 *  @langversion 3.0
 *  @playerversion Flash 10.2
 *  @playerversion AIR 2.6
 *  @productversion FlexJS 0.0
 */
public class BeadMetrics
{

    /**
     *  Compute the offset of the content
     *  in a container based on border-thickness and padding styles.
     *
     *  @param object The object with style values.
     *  @return The offsets of the content.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10.2
     *  @playerversion AIR 2.6
     *  @productversion FlexJS 0.0
     */
	public static function getMetrics(object:Object) : UIMetrics
	{
		var borderThickness:Object = ValuesManager.valuesImpl.getValue(object,"border-width");
		var borderOffset:Number;
		if( borderThickness == null )
        {
            borderThickness = ValuesManager.valuesImpl.getValue(object,"border");
            if (borderThickness != null)
            {
                if (borderThickness is Array)
                    borderOffset = CSSUtils.toNumber(borderThickness[0], object.width);
                else
                    borderOffset = CSSUtils.toNumber(borderThickness as String, object.width);
            }
            else
                borderOffset = 0;
		}
		else {
			borderOffset = Number(borderThickness);
			if( isNaN(borderOffset) ) borderOffset = 0;
		}

		var paddingLeft:Object;
		var paddingTop:Object;
		var paddingRight:Object;
		var paddingBottom:Object;

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

		var marginLeft:Object;
		var marginRight:Object;
		var marginTop:Object;
		var marginBottom:Object;
		var margin:Object;
		margin = ValuesManager.valuesImpl.getValue(object, "margin");
		marginLeft = ValuesManager.valuesImpl.getValue(object, "margin-left");
		marginTop = ValuesManager.valuesImpl.getValue(object, "margin-top");
		marginRight = ValuesManager.valuesImpl.getValue(object, "margin-right");
		marginBottom = ValuesManager.valuesImpl.getValue(object, "margin-bottom");
		var ml:Number;
		var mr:Number;
		var mt:Number;
		var mb:Number;
		var lastmr:Number;
		if (marginLeft == "auto")
			ml = 0;
		else
        {
            ml = CSSUtils.getLeftValue(marginLeft, margin, object.width);
            if (isNaN(ml))
                ml = 0;
        }
		if (marginRight == "auto")
			mr = 0;
		else
        {
            mr = CSSUtils.getRightValue(marginRight, margin, object.width);
            if (isNaN(mr))
                mr = 0;
        }
		mt = CSSUtils.getTopValue(marginTop, margin, object.height);
		if (isNaN(mt))
			mt = 0;
        mb = CSSUtils.getBottomValue(marginBottom, margin, object.height);
		if (isNaN(mb))
			mb = 0;

        borderOffset *= 2; // border on each side
		var result:UIMetrics = new UIMetrics();
		result.top = borderOffset + pt;
		result.left = borderOffset + pl;
		result.bottom = borderOffset + pb;
		result.right = borderOffset + pr;
		result.marginTop = mt;
		result.marginLeft = ml;
		result.marginBottom = mb;
		result.marginRight = mr;

		return result;
	}
}
}

refactor to get style precedence correct


/**
 * 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.AnimationHelper;
	import com.merlinds.miracle.display.MiracleAnimation;
	import com.merlinds.miracle.display.MiracleDisplayObject;
	import com.merlinds.miracle.geom.Color;
	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;
	import flash.utils.setTimeout;

	[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;
		private var _current:MiracleAnimation;

		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 animation");
					var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
					_window.x = this.stage.stageWidth - _window.width;
					_window.setSize(_window.height, list.height + 20);
					list.addEventListener(Event.SELECT, this.selectAnimationHandler);
				}
			}
			var w2:Window = new Window(this, _window.x, _window.y + _window.height + 10, "FPS");
			list = new List(w2, 0, 0, [1, 5, 16, 24, 30, 35, 40, 60]);
			w2.height = 120;
			list.addEventListener(Event.SELECT, this.selectFpsHandler);
		}

		[Inline]
		private function getAnimations(bytes:ByteArray):Array {
			var result:Array = [];
			var reader:MafReader = new MafReader();
			reader.execute(bytes, 1);
			var animations:Vector.<AnimationHelper> = reader.animations;
			for each(var animation:AnimationHelper 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);
			if(_assets.length > 1){
				this.choseAnimation();
				Miracle.createScene(_assets,null, 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);
			var mesh:String = animation.substr(0, animation.lastIndexOf("."));
			animation = animation.substr(animation.lastIndexOf(".") + 1);
			if(_current == null){
				_current = Miracle.scene.createAnimation(mesh, animation, 60);
				_current.moveTO(this.stage.stageWidth >> 1, this.stage.stageHeight >> 1);
				_current.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
			}else{
				_current.mesh = mesh;
				_current.animation = animation;
				_current.play();
			}
		}

		private function imageAddedToStage(event:Event):void {
			trace("Added to stage");
		}

		private function selectFpsHandler(event:Event):void {
			var list:List = event.target as List;
			//add animation to miracle
			if(_current != null){
				_current.fps = int(list.selectedItem);
			}
		}
		//} 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.PushButton;
	import com.merlinds.miracle.Miracle;
	import com.merlinds.miracle.animations.AnimationHelper;
	import com.merlinds.miracle.display.MiracleDisplayObject;
	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.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.FileFilter;
	import flash.utils.ByteArray;

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

		private var _model:AppModel;
		private var _startBtn:PushButton;
		private var _texture:ByteArray;
		private var _animation:ByteArray;
		private var _fileName:String;
		private var _list:List;
		private var _instance:MiracleDisplayObject;

		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;
			_startBtn = new PushButton(this, this.stage.stageWidth >> 1, this.stage.stageHeight >> 1,
					"Start", this.startBtnHandler );
		}

		function clear():void
		{
			if(_animation != null) _animation.clear();
			if(_texture != null) _texture.clear();
			_texture = null;
			_animation = null;
			_fileName = null;
		}

		private function startHandler():void {
			trace("Miracle was started");
			var maf:Asset = new Asset(_fileName + ".maf", _animation);
			var mtf:Asset = new Asset(_fileName + ".mtf", _texture);
			Miracle.createScene(new <Asset>[maf, mtf], this.createdHandler, 1);
		}

		private function createdHandler():void {
			trace("Scene created");
			this.getAnimationList();
		}

		private function getAnimationList():void {
			var mafReader = new MafReader();
			mafReader.execute(_animation, 1);
			var animationsName:Array = [];
			for each(var animation:AnimationHelper in mafReader.animations)
			{
				animationsName.push(animation.name);
			}
			trace("Was get animations", animationsName);
			_list = new List(this, this.stage.stageWidth - 200, 0, animationsName);
			_list.width = 200;
			_list.addEventListener(Event.SELECT, this.selectAnimationHandler);
		}

		private function getAnimation():void {
			var file:File = _model.lastFileDirection;
			file.browseForOpen("Get animation file", [new FileFilter("Miracle animation format", "*.maf")] );
			file.addEventListener(Event.SELECT, this.animationSelected);
			file.addEventListener(Event.CANCEL, this.animationSelected);
		}

		private function readAnimation(file:File):void {
			_animation = new ByteArray();
			var fileStream:FileStream = new FileStream();
			fileStream.open(file, FileMode.READ);
			fileStream.readBytes(_animation);
			fileStream.close();
		}

		private function getTexture(file:File):void {
			_fileName = file.name.substr(0, -file.extension.length - 1);
			file.browseForOpen("Get texture file", [new FileFilter("Miracle texture format", _fileName + ".mtf")] );
			file.addEventListener(Event.SELECT, this.animationSelected);
			file.addEventListener(Event.CANCEL, this.animationSelected);
		}

		private function readTexture(file:File):void {
			_texture = new ByteArray();
			var fileStream:FileStream = new FileStream();
			fileStream.open(file, FileMode.READ);
			fileStream.readBytes(_texture);
			fileStream.close();
		}

		public function startBtnHandler(event:Event):void{
			_startBtn.visible = false;
			getAnimation();
		}

		private function animationSelected(event:Event):void {
			if(event.type == Event.CANCEL)
			{
				this.clear();
				_startBtn.visible = true;
			}else
			{
				if(_animation == null)
				{
					this.readAnimation(event.target as File);
					this.getTexture(event.target as File);
				}else
				{
					this.readTexture(event.target as File);
					trace("All loaded");
					Miracle.start(this.stage, this.startHandler, true);
				}
			}
		}

		private function selectAnimationHandler(event:Event):void {
			if(_instance != null)
			{
				Miracle.scene.removeInstance(_instance);
			}
			var selected:String = _list.selectedItem as String;
			var dot:int = selected.lastIndexOf(".");
			var animation:String = selected.substr(dot+1);
			var mesh:String = selected.substr(0, dot);
			_instance = Miracle.scene.createAnimation(mesh, animation, 30);
			_instance.x = this.stage.stageWidth >> 1;
			_instance.y = this.stage.stageHeight >> 1;
			_instance.visible = true;
		}
		//} endregion EVENTS HANDLERS ==================================================

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

Fix viewer

Fix viewer


/**
 * 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.AnimationHelper;
	import com.merlinds.miracle.display.MiracleAnimation;
	import com.merlinds.miracle.display.MiracleDisplayObject;
	import com.merlinds.miracle.geom.Color;
	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;
	import flash.utils.setTimeout;

	[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;
		private var _current:MiracleAnimation;

		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 animation");
					var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
					_window.x = this.stage.stageWidth - _window.width;
					_window.setSize(_window.height, list.height + 20);
					list.addEventListener(Event.SELECT, this.selectAnimationHandler);
				}
			}
			var w2:Window = new Window(this, _window.x, _window.y + _window.height + 10, "FPS");
			list = new List(w2, 0, 0, [1, 5, 16, 24, 30, 35, 40, 60]);
			w2.height = 120;
			list.addEventListener(Event.SELECT, this.selectFpsHandler);
		}

		[Inline]
		private function getAnimations(bytes:ByteArray):Array {
			var result:Array = [];
			var reader:MafReader = new MafReader();
			reader.execute(bytes, 1);
			var animations:Vector.<AnimationHelper> = reader.animations;
			for each(var animation:AnimationHelper 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);
			if(_assets.length > 1){
				this.choseAnimation();
				Miracle.createScene(_assets,null, 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);
			var mesh:String = animation.substr(0, animation.lastIndexOf("."));
			animation = animation.substr(animation.lastIndexOf(".") + 1);
			if(_current == null){
				_current = Miracle.currentScene.createAnimation(mesh, animation, 60);
				_current.moveTO(this.stage.stageWidth >> 1, this.stage.stageHeight >> 1);
				_current.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
			}else{
				_current.mesh = mesh;
				_current.animation = animation;
				_current.play();
			}
		}

		private function imageAddedToStage(event:Event):void {
			trace("Added to stage");
		}

		private function selectFpsHandler(event:Event):void {
			var list:List = event.target as List;
			//add animation to miracle
			if(_current != null){
				_current.fps = int(list.selectedItem);
			}
		}
		//} 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.AnimationHelper;
	import com.merlinds.miracle.display.MiracleAnimation;
	import com.merlinds.miracle.display.MiracleDisplayObject;
	import com.merlinds.miracle.geom.Color;
	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;
	import flash.utils.setTimeout;

	[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;
		private var _current:MiracleAnimation;

		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 animation");
					var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
					_window.x = this.stage.stageWidth - _window.width;
					_window.setSize(_window.height, list.height + 20);
					list.addEventListener(Event.SELECT, this.selectAnimationHandler);
				}
			}
			var w2:Window = new Window(this, _window.x, _window.y + _window.height + 10, "FPS");
			list = new List(w2, 0, 0, [1, 5, 16, 24, 30, 35, 40, 60]);
			w2.height = 120;
			list.addEventListener(Event.SELECT, this.selectFpsHandler);
		}

		[Inline]
		private function getAnimations(bytes:ByteArray):Array {
			var result:Array = [];
			var reader:MafReader = new MafReader();
			reader.execute(bytes, 1);
			var animations:Vector.<AnimationHelper> = reader.animations;
			for each(var animation:AnimationHelper 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);
			if(_assets.length > 1){
				this.choseAnimation();
				Miracle.createScene(_assets,null, 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);
			var mesh:String = animation.substr(0, animation.lastIndexOf("."));
			animation = animation.substr(animation.lastIndexOf(".") + 1);
			if(_current == null){
				_current = Miracle.scene.createAnimation(mesh, animation, 60);
				_current.moveTO(this.stage.stageWidth >> 1, this.stage.stageHeight >> 1);
				_current.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
			}else{
				_current.mesh = mesh;
				_current.animation = animation;
				_current.play();
			}
		}

		private function imageAddedToStage(event:Event):void {
			trace("Added to stage");
		}

		private function selectFpsHandler(event:Event):void {
			var list:List = event.target as List;
			//add animation to miracle
			if(_current != null){
				_current.fps = int(list.selectedItem);
			}
		}
		//} endregion EVENTS HANDLERS ==================================================

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

rename currentScene to scene

rename currentScene to scene


/*
	Weave (Web-based Analysis and Visualization Environment)
	Copyright (C) 2008-2011 University of Massachusetts Lowell

	This file is a part of Weave.

	Weave is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License, Version 3,
	as published by the Free Software Foundation.

	Weave is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Weave.  If not, see <http://www.gnu.org/licenses/>.
*/
package weave.visualization.tools
{
	import weave.api.WeaveAPI;
	import weave.compiler.Compiler;
	import weave.core.LinkableHashMap;
	import weave.core.LinkableString;

	public class ExternalTool extends LinkableHashMap
	{
		private var toolUrl:LinkableString;
		private var toolPath:Array;
		private var windowName:String;

		public function ExternalTool()
		{
			toolUrl = requestObject("toolUrl", LinkableString, true);
			toolUrl.addGroupedCallback(this, toolPropertiesChanged);
		}
		private function toolPropertiesChanged():void
		{
			if (toolUrl.value != "")
			{
				launch();
			}
		}
		public function launch():void
		{
			if (toolPath == null)
			{
				toolPath = WeaveAPI.SessionManager.getPath(WeaveAPI.globalHashMap, this);
				windowName = Compiler.stringify(toolPath);
			}
			WeaveAPI.executeJavaScript(
				{
					windowName: windowName,
					toolPath: toolPath,
					url: toolUrl.value,
					features: "menubar=no,status=no,toolbar=no"
				},
				"if (!weave.external_tools) weave.external_tools = {};\
				 weave.external_tools[windowName] = window.open(url, windowName, features);\
				 weave.external_tools[windowName].toolPath = toolPath;\
				 weave.external_tools[windowName].weave = weave;"
			);
		}
		override public function dispose():void
		{
			super.dispose();
			WeaveAPI.executeJavaScript(
				{windowName: windowName},
				"if (weave.external_tools && weave.external_tools[windowName])\
					weave.external_tools[windowName].close();"
			);
		}
	}
}

/*
	Weave (Web-based Analysis and Visualization Environment)
	Copyright (C) 2008-2011 University of Massachusetts Lowell

	This file is a part of Weave.

	Weave is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License, Version 3,
	as published by the Free Software Foundation.

	Weave is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Weave.  If not, see <http://www.gnu.org/licenses/>.
*/
package weave.visualization.tools
{
	import weave.api.WeaveAPI;
	import weave.compiler.Compiler;
	import weave.core.LinkableHashMap;
	import weave.core.LinkableString;

	public class ExternalTool extends LinkableHashMap
	{
		private var toolUrl:LinkableString;
		private var toolPath:Array;
		private var windowName:String;

		public function ExternalTool()
		{
			toolUrl = requestObject("toolUrl", LinkableString, true);
			toolUrl.addImmediateCallback(this, toolPropertiesChanged);
		}
		private function toolPropertiesChanged():void
		{
			if (toolUrl.value != "")
			{
				launch();
			}
		}
		public function launch():void
		{
			if (toolPath == null)
			{
				toolPath = WeaveAPI.SessionManager.getPath(WeaveAPI.globalHashMap, this);
				windowName = Compiler.stringify(toolPath);
			}
			WeaveAPI.executeJavaScript(
				{
					windowName: windowName,
					toolPath: toolPath,
					url: toolUrl.value,
					features: "menubar=no,status=no,toolbar=no"
				},
				"if (!weave.external_tools) weave.external_tools = {};",
				"weave.external_tools[windowName] = window.open(url, windowName, features);",
				"console.log(toolPath);",
				"weave.external_tools[windowName].toolPath = toolPath;",
				"weave.external_tools[windowName].weave = weave;"
			);
		}
		override public function dispose():void
		{
			super.dispose();
			WeaveAPI.executeJavaScript(
				{windowName: windowName},
				"if (weave.external_tools && weave.external_tools[windowName])\
					weave.external_tools[windowName].close();"
			);
		}
	}
}

ExternalTool: Switch to immediate callback for toolPropertiesChanged