/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package corsaair.server.spitfire
{

    import C.errno.*;
    import C.arpa.inet.*;
    import C.netdb.*;
    import C.netinet.*;
    import C.sys.socket.*;
    import C.sys.select.*;
    import C.stdlib.*;
    import C.unistd.*;

    import flash.utils.ByteArray;

    /**
     * A simple socket server upgrade 1.
     *
     * This time we do use a loop to listen and interact with multiple clients.
     *
     * @see http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#select a cheezy multiperson chat server
     */
    public class SimpleSocketServerSelect
    {

        // the port users will be connecting to
        public const PORT:String = "3490";

        // how many pending connections queue will hold
        public const BACKLOG:uint = 10;

        public function SimpleSocketServerSelect()
        {
            super();
        }

        public function showAddressInfo1():void
        {
            var hints:addrinfo = new addrinfo();
            var info:addrinfo;

            /* Note:
               because we want to bind
               eg. ai_flags = AI_PASSIVE
               it will automatically use the wildcard address 0.0.0.0
               which means you're binding to every IP address on your machine
            */
            hints.ai_family   = AF_UNSPEC;
            hints.ai_socktype = SOCK_STREAM;
            hints.ai_flags    = AI_PASSIVE; // indicate we want to bind

            var eaierr:CEAIrror = new CEAIrror();
            var addrlist:Array  = getaddrinfo( null, "http", hints, eaierr );

            if( !addrlist )
            {
                throw eaierr;
            }

            trace( "found " + addrlist.length + " addresses" );
            for( var i:uint = 0; i < addrlist.length; i++ )
            {
                info = addrlist[i];
                trace( "[" + i + "] = " + inet_ntop( info.ai_family, info.ai_addr ) );
            }
        }

        public function showAddressInfo2():void
        {
            var hints:addrinfo = new addrinfo();
            var info:addrinfo;

            /* Note:
               Without ai_flags = AI_PASSIVE
               the first local address will be the loopback
               eg. 127.0.0.1
            */
            hints.ai_family   = AF_UNSPEC;
            hints.ai_socktype = SOCK_STREAM;

            var eaierr:CEAIrror = new CEAIrror();
            var addrlist:Array  = getaddrinfo( null, "http", hints, eaierr );

            if( !addrlist )
            {
                throw eaierr;
            }

            trace( "found " + addrlist.length + " addresses" );
            for( var i:uint = 0; i < addrlist.length; i++ )
            {
                info = addrlist[i];
                trace( "[" + i + "] = " + inet_ntop( info.ai_family, info.ai_addr ) );
            }
        }

        public function showAddressInfo3( hostname:String = "" ):void
        {
            /* Note:
               gethostname() will obtain your local hostname
               and use the IP address used on your local network
               for ex: 192.168.0.xyz

               if you pass a custom hostname like "www.as3lang.org"
               it will resolve to the IP address of that remote hostname

               it can also return many IP addresses depending on
               the remote hostname configuration, for ex: with something
               like cloudlfare it can  returns 2 or more addresses
               etc.
            */
            if( hostname == "" )
            {
                hostname = gethostname();
            }

            trace( "hostname = " + hostname );

            var hints:addrinfo = new addrinfo();
            var info:addrinfo;

            hints.ai_family   = AF_UNSPEC;
            hints.ai_socktype = SOCK_STREAM;

            var eaierr:CEAIrror = new CEAIrror();
            var addrlist:Array  = getaddrinfo( hostname, "http", hints, eaierr );

            if( !addrlist )
            {
                throw eaierr;
            }

            trace( "found " + addrlist.length + " addresses" );
            for( var i:uint = 0; i < addrlist.length; i++ )
            {
                info = addrlist[i];
                trace( "[" + i + "] = " + inet_ntop( info.ai_family, info.ai_addr ) );
            }
        }

        public function main():void
        {
            var sockfd:int; // listening socket descriptor

            var new_fd:int;  // newly accept()ed socket descriptor

            var hints:addrinfo = new addrinfo();
            var servinfo:addrinfo;

            hints.ai_family   = AF_UNSPEC;
            hints.ai_socktype = SOCK_STREAM;
            hints.ai_flags    = AI_PASSIVE; // use my IP

            var eaierr:CEAIrror = new CEAIrror();
            var addrlist:Array  = getaddrinfo( null, PORT, hints, eaierr );

            if( !addrlist )
            {
                throw eaierr;
            }

            var option:int;
            var bound:int;

            // loop through all the results and bind to the first we can
            for( var i:uint = 0; i < addrlist.length; i++ )
            {
                servinfo = addrlist[i];

                sockfd = socket( servinfo.ai_family, servinfo.ai_socktype, servinfo.ai_protocol );
                if( sockfd == -1 )
                {
                    trace( "selectserver: socket" )
                    trace( new CError( "", errno ) );
                    continue;
                }

                option = setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, 1 );
                if( option == -1 )
                {
                    trace( "setsockopt" );
                    trace( new CError( "", errno ) );
                    exit( 1 );
                }

                bound = bind( sockfd, servinfo.ai_addr );
                if( bound == -1 )
                {
                    close( sockfd );
                    trace( "selectserver: bind" );
                    trace( new CError( "", errno ) );
                    continue;
                }

                break;
            }

            if( servinfo == null )
            {
                trace( "selectserver: failed to bind" );
                exit( 1 );
            }

            var listening:int = listen( sockfd, BACKLOG );
            if( listening == -1 )
            {
                trace( "listen" );
                trace( new CError( "", errno ) );
                exit( 1 );
            }

            trace( "selectserver: waiting for connections..." );

            /* Note:
               so what is a select() server exactly ?

               it is simple
               - you use 'fd_set' to delcare sets of file descriptor (like an Array)
               - you use FD_SOMETHING macros to read/write/clear data from those sets
                 FD_ZERO to reset a 'fd_set'
                 FD_ISSET to know if a socket descriptor is set
                 FD_SET to set a socket descriptor into a set
                 FD_CLR to remove a socket descriptor from a set
               - then you use the function select()
                 to loop trough all those sets

               And you know what, I messed up the implementation of select()
               "as is" it does not work or half-work, ok my bad

               but wait ...
               a 'fd_set' is like an array so you know what
               it's pretty simple to do like select() without select()
               simply put
               - add each new socket descriptor into an array
               - loop trough the array
               - detect if the socket is readable

               humm how to detect if a socket is readable ?
               well in C.sys.select.* you can find 3 functions
               isReadable()    - Test if a socket is ready for reading.
               isWritable()    - Test if a socket is ready for writing.
               isExceptional() - Test if a socket has an exceptional condition pending.
               and those are working :)
               (long sotry short strangely under the hood they alos use 'fd_set' but in
               a very simple stupid way that works)
            */

            // reset the list
            var connections:Array = [];

            // add the listener to the master set
            connections.push( sockfd );
            trace( "selectserver: server on socket " + sockfd );

            var run:Boolean = true;

            /* Note:
               it can be a for(;;), a while(1), a while(true), etc.
               but yes you get it, here we need an infinite loop

               no worries it's Redtamarin, not Flash/AIR
               we can loop forever it will not cause a script timeout
            */
            // main loop
            for(;;)
            {

            	if( !run )
            	{
            		break;
            	}

                // run through the existing connections looking for data to read
                for( var j:uint = 0; j < connections.length; j++ )
                {
                    //trace( "selectserver: selecting socket " + connections[j] );

                    /* Note:
                       if the socket descriptor is readable
                       then we do our work

                       ATTENTION
                       in 'connections' you have both the server and all the clients
                       - for the server
                         being readable mean someone try to connect to the server
                         and if no one try to connect then the server is not readable
                       - for the client
                         being readable mean the client try to send data to the server
                         and if the client do nto send data then it is not readable

                       so here the loop works like
                       - loop trough all the socket descriptor
                       - only do work if there is osmethign to read
                         - if server, create a new connection
                         - if client, read the client data
                       - otherwise keep looping
                    */
                    // we got one!!
                    if( isReadable( connections[j] ) )
                    {
                        // the server
                        if( connections[j] == sockfd )
                        {
                            // handle new connections
                            var client_addr:sockaddr_in = new sockaddr_in();
                            new_fd = accept( sockfd, client_addr );
                            if( new_fd == -1 )
                            {
                                trace( "accept" );
                                trace( new CError( "", errno ) );
                            }
                            else
                            {
                                // add to master set
                                connections.push( new_fd );

                                // keep track of the max
                                /* Note:
                                   the array index does that for us
                                */

                                var s:String = inet_ntop( client_addr.sin_family, client_addr );
                                trace( "selectserver: new connection from " + s  + ", socket " + new_fd );

                                var msg_out:String = "Hello, world!\n";
                                var bytes_out:ByteArray = new ByteArray();
                                    bytes_out.writeUTFBytes( msg_out );
                                    bytes_out.position = 0;

                                var sent:int = send( new_fd, bytes_out );
                                if( sent == -1 )
                                {
                                    trace( "send" );
                                    trace( new CError( "", errno ) );
                                }
                                else
                                {
                                    trace( "sent " + sent + " bytes to the client " + new_fd );
                                }

                            }

                        }
                        else
                        {
                            // handle data from a client
                            var msg_in:String;
                            var bytes_in:ByteArray = new ByteArray();

                            var received:int = recv( connections[j], bytes_in );
                            if( received <= 0 )
                            {
                                // got error or connection closed by client
                                if( received == 0 )
                                {
                                    // connection closed
                                    trace( "selectserver: socket " + connections[j] + " hung up" );
                                }
                                else
                                {
                                    trace( "recv" );
                                    trace( new CError( "", errno ) );
                                }

                                close( connections[j] ); // bye!

                                // remove from master set
                                connections.splice( j, 1 );
                            }
                            else
                            {
                                // we got some data from a client
                                trace( "received " + received + " bytes from client " + connections[j] );
                                bytes_in.position = 0;
                                msg_in = bytes_in.readUTFBytes( bytes_in.length );
                                msg_in = msg_in.split( "\n" ).join( "" );
                                trace( connections[j] + " : " + msg_in );

                                if( msg_in == "shutdown" )
                                {
                                	trace( "selectserver: received 'shutdown' command" );
                                	run = false;
                                	break;
                                }
                            }

                        } // END handle data from client

                    } // END got new incoming connection

                } // END looping through file descriptors

            } // END for(;;)--and you thought it would never end!

            trace( "selectserver: connections left [" + connections + "]" );

            /* Note:
               properly close all clients before
            */
            for( var k:uint = 0; k < connections.length; k++ )
            {
            	if( connections[k] != sockfd )
            	{
            		trace( "selectserver: terminate " + connections[k] );
            		close( connections[k] );
            		connections.splice( k, 1 );
            		k = 0; //rewind
            	}
            }

            trace( "shutting down server" );
            shutdown( sockfd, SHUT_RDWR );
            close( sockfd );

            exit( 0 );

        }

    }
}

add basic select server

add basic select server

git-svn-id: 44dac414ef660a76a1e627c7b7c0e36d248d62e4@17 c2cce57b-6cbb-4450-ba62-5fdab5196ef5


// vim: tabstop=4 shiftwidth=4

// Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved.
//
//         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 {
	public final class ZigZag {
		public static function encode32(n:int):int {
			return (n << 1) ^ (n >> 31)
		}
		public static function decode32(n:int):int {
			return (n >>> 1) ^ -(n & 1)
		}
		public static function encode64low(low:uint, high:int):uint {
			return (low << 1) ^ (high >> 31)
		}
		public static function encode64high(low:uint, high:int):int {
			return (low >>> 31) ^ (high << 1) ^ (high >> 31)
		}
		public static function decode64low(low:uint, high:int):uint {
			return (high << 31) ^ (low >>> 1) ^ -(low & 1)
		}
		public static function decode64high(low:uint, high:int):int {
			return (high >>> 1) ^ -(low & 1)
		}
	}
}

添加遗漏的 ZigZag.as

添加遗漏的 ZigZag.as


/* ----------------------------------------------------------------------------
		Ghost Comps is a set of controls to manipulate user interface objects.
		Copyright (C) 2010 Jan Cássio
	---------------------------------------------------------------------------

		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

	Ghost Comps Project
	http://github.com/jancassio/ghostcomps/

	------------------------------------------------------------------------ */

package ghost.helpers
{
	import ghost.events.SliderEvent;

	import flash.events.EventDispatcher;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	[Event (name="sliderDrag", type="ghost.events.SliderEvent")]
	[Event (name="sliderDrop", type="ghost.events.SliderEvent")]
	[Event (name="sliderUpdate", type="ghost.events.SliderEvent")]

	/**
	 *  Helper to assist in slider based interactions/instructions.
	 *
	 *  @example
	 *  <code>
	 *
	 *  var slider : Slider2D;
	 *  var rect : Rectangle;
	 *  var point : Point;
	 *
	 *  slider = new Slider;
	 *  rect = new Rectangle(0, 0, 100, 100);
	 *  point = new Point(50, 50);
	 *
	 *  slider.area = rect;
	 *  slider.position = point;
	 *
	 *  trace("percentage x over area is: ", slider.percentageX); // .5;
	 *  slider.percentageY = .2;
	 *  trace("position Y over area is: ", slider.positionY); // 20;
	 *  </code>
	 *
	 *  @author jancassio | janio@jancassio.com
	 */
	public class Slider2D extends EventDispatcher
	{

		/** lock x axis */
		public static const HORIZONTAL	: String = "horizontal";

		/** lock y axis */
		public static const VERTICAL	: String = "vertical";

		private var _pos 	: Point;
		private var _area	: Rectangle;
		private var _axis	: String;

		/**
		 *	Creates a new Slider2D instance.
		 */
		public function Slider2D (
			area : Rectangle = null,
			position : Point = null,
			percentage : Point = null,
			axis : String = null
		)
		{
			conf(
				area != null ? area.clone() : new Rectangle,
				position != null ? position.clone() : new Point,
				axis
			);
		}

		protected function conf (area : Rectangle, point : Point, axis : String) : void
		{
			this._area	= area;
			this._pos	= point;
			this._axis	= axis;
		}

		/**
		 *	The point x and y position.
		 */
		public function set position (value : Point):void
		{
			_pos.x = Math.max( _area.x, Math.min(_area.width + _area.x, value.x) );
			_pos.y = Math.max( _area.y, Math.min(_area.height + _area.y, value.y) );

			dispatch(SliderEvent.UPDATE);
		}

		/**
		 *	The x axis position.
		 */
		public function set positionX (value : Number):void
		{
			position = new Point( value, positionY );
		}

		/**
		 *	The y axis position.
		 */
		public function set positionY (value : Number) : void
		{
			position = new Point( positionX, value );
		}

		public function get position () : Point
		{
			return _pos.clone();
		}

		public function get positionX () : Number
		{
			return _pos.x;
		}

		public function get positionY () : Number
		{
			return _pos.y;
		}

		/**
		 *	The point position percentage over area.
		 */
		public function set percentage (value : Point):void
		{
			position = new Point(
			 	_area.x + (_area.width * value.x),
				_area.y + (_area.height * value.y)
			);
			dispatch(SliderEvent.UPDATE);
		}

		/**
		 *	The x axis slide percentage over area position.
		 */
		public function set percentageX (value : Number):void
		{
			percentage = new Point( value, percentageY );
		}

		/**
		 *	The y axis slide percentage over area position.
		 */
		public function set percentageY (value : Number) : void
		{
			percentage = new Point( percentageX, value );
		}

		public function get percentage () : Point
		{
			var x : Number;
			var y : Number;

			x = (position.x - _area.x) / _area.width;
			y = (position.y - _area.y) / _area.height;

			x = isNaN(x) ? 1 : x;
			y = isNaN(y) ? 1 : y;

			return new Point( x, y );
		}

		public function get percentageX () : Number
		{
			return percentage.x;
		}

		public function get percentageY () : Number
		{
			return percentage.y;
		}

		/**
		 *	Slider area.
		 */
		public function set area (rectangle : Rectangle) : void
		{
			var oldPct : Point;
			oldPct = percentage.clone();
			_area = rectangle.clone();

			if(_axis != null)
			{
				if(_axis == HORIZONTAL) _area.height = 0;
				if(_axis == VERTICAL) _area.width = 0;
			}
			percentage = oldPct;
		}

		public function get area () : Rectangle
		{
			return _area.clone();
		}

		/**
		 *	Active axis on slider.
		 */
		public function set axis (value : String) : void
		{
			_axis = value;
		}

		public function get axis () : String
		{
			return _axis;
		}

		/**
		 *	The x, y Point offset.
		 */
		public function get offset () : Point
		{
			var x : Number;
			var y : Number;

			x = (_pos.x - _area.x);
			y = (_pos.y - _area.y);

			return new Point( x, y );
		}

		/**
		 *	Disposes object.
		 */
		public function dispose () : void
		{
			_pos = undefined;
			_area = undefined;
			_axis = undefined;
		}

		internal function dispatch(type : String):Boolean
		{
			var event : SliderEvent;

			event				= new SliderEvent( type );
			event.percentage	= percentage;
			event.position		= position;
			event.offset		= offset;
			event.area			= area;

			return dispatchEvent( event );
		}

	}
}

add ghost slider helper class

add ghost slider helper class


package krewfw.builtin_actor.system {

    import krewfw.core.KrewActor;

    /**
     * Base class for event-driven command player.
     */
    //------------------------------------------------------------
    public class KrewScenarioPlayer extends KrewActor {

        private var _eventList:Array;
        private var _eventsByTrigger:Object;

        private var _triggers:Object = {};
        private var _methods:Object  = {};

        //------------------------------------------------------------
        public function KrewScenarioPlayer() {
            displayable = false;
        }

        protected override function onDispose():void {
            _eventList       = null;
            _eventsByTrigger = null;
            _triggers        = null;
            _methods         = null;
        }

        //------------------------------------------------------------
        // public
        //------------------------------------------------------------

        /**
         * @params eventList Example:
         *

         * [
         *     {
         *         "trigger_key" : "start_turn",
         *         "trigger_params": {"turn": 1},
         *         "method": "dialog",
         *         "params": {
         *             "messages": [ ... ]
         *         },
         *         "next": [
         *             {
         *                 "method": "overlay",
         *                 "params": { ... }
         *             }
         *         ]
         *     },
         *     ...
         * ]
         *

         */
        public function setData(eventList:Array):void {
            _eventList = eventList;

            _eventsByTrigger = {};
            for each (var eventData:Object in _eventList) {
                var triggerKey:String = eventData.trigger_key;
                if (!triggerKey) { continue; }

                if (!_eventsByTrigger[triggerKey]) {
                    _eventsByTrigger[triggerKey] = [];
                }
                _eventsByTrigger[triggerKey].push(eventData);
            }
        }

        /**
         * @param checker Schema: function(eventArgs;Object, triggerParams:Object):Boolean
         */
        public function addTrigger(triggerKey:String, eventName:String, checker:Function):void {
            _triggers[triggerKey] = new TriggerInfo(eventName, checker);
        }

        /**
         * @param triggerInfoList Example:
         *

         * [
         *     ["triggerKey", "eventName", checkerFunc],
         *     ...
         * ]
         *

         */
        public function addTriggers(triggerInfoList:Array):void {
            for each (var info:Array in triggerInfoList) {
                addTrigger(info[0], info[1], info[2]);
            }
        }

        /**
         * @param handler Schema: function(params:Object, onComplete:Function):void
         */
        public function addMethod(methodName:String, handler:Function):void {
            _methods[methodName] = handler;
        }

        /**
         * @param triggerInfoList Example:
         *

         * [
         *     ["methodName", methodFunc],
         *     ...
         * ]
         *

         */
        public function addMethods(methodList:Array):void {
            for each (var info:Array in methodList) {
                addMethod(info[0], info[1]);
            }
        }

        /**
         * Activate player.
         * Please call this after setData(), addTriggers(), addMethods(), and init().
         */
        public function activate():void {
            for (var triggerKey:String in _eventsByTrigger) {
                _listenEvent(triggerKey);
            }
        }

        //------------------------------------------------------------
        // private
        //------------------------------------------------------------

        private function _listenEvent(triggerKey:String):void {
            var info:TriggerInfo = _triggers[triggerKey];
            if (!info) {
                throw new Error('[KrewEventPlayer] trigger not registered: ' + triggerKey);
                return;
            }

            listen(info.eventName, function(eventArgs:Object):void {
                for each (var eventData:Object in _eventsByTrigger[triggerKey]) {

                    var triggerParams:Object = eventData.trigger_params;
                    if (!info.checker(eventArgs, triggerParams)) { continue; }

                    _callMethod(eventData);
                }
            });
        }

        private function _callMethod(eventData:Object):void {
            var methodName:String = eventData.method;
            if (!methodName) {
                throw new Error('[KrewEventPlayer] method name not found. (trigger: '
                                + eventData.trigger_key + ')');
                return;
            }

            var method:Function = _methods[methodName];
            if (method == null) {
                throw new Error('[KrewEventPlayer] method not registered: ' + methodName);
                return;
            }

            method(eventData.params, function():void {
                _callNextMethod(eventData);
            });
        }

        private function _callNextMethod(parentEventData:Object):void {
            if (!parentEventData.next) { return; }

            for each (var nextEventData:Object in parentEventData.next) {
                _callMethod(nextEventData);
            }
        }

    }
}

class TriggerInfo {

    public var eventName:String;
    public var checker:Function;

    public function TriggerInfo(eventName:String, checker:Function) {
        this.eventName = eventName;
        this.checker   = checker;
    }

}

Add KrewScenarioPlayer

Add KrewScenarioPlayer


package dolly {

import dolly.core.dolly_internal;
import dolly.data.NotCopyableSubclass;

import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;

use namespace dolly_internal;

public class CopyingOfNotCopyableSubclassTest {

	private var notCopyableSubclass:NotCopyableSubclass;
	private var notCopyableSubclassType:Type;

	[Before]
	public function before():void {
		notCopyableSubclass = new NotCopyableSubclass();
		notCopyableSubclass.property1 = "property1 value";
		notCopyableSubclass.property2 = "property2 value";
		notCopyableSubclass.writableField1 = "writableField1 value";
		notCopyableSubclass.writableField2 = "writableField2 value";

		notCopyableSubclassType = Type.forInstance(notCopyableSubclass);
	}

	[After]
	public function after():void {
		notCopyableSubclass = null;
		notCopyableSubclassType = null;
	}

	[Test]
	public function findingAllCopyableFieldsForType():void {
		const copyableFields:Vector.<Field> = Copier.findCopyableFieldsForType(notCopyableSubclassType);
		assertNotNull(copyableFields);
		assertEquals(2, copyableFields.length);
		assertNotNull(copyableFields[0]);
		assertNotNull(copyableFields[1]);
	}

	[Test]
	public function copyingByCopier():void {
		const copyInstance:NotCopyableSubclass = Copier.copy(notCopyableSubclass);
		assertNotNull(copyInstance);
		assertNotNull(copyInstance.property1);
		assertEquals(copyInstance.property1, notCopyableSubclass.property1);
		assertNotNull(copyInstance.property2);
		assertFalse(copyInstance.property2 == notCopyableSubclass.property2);
		assertNotNull(copyInstance.writableField1);
		assertEquals(copyInstance.writableField1, notCopyableSubclass.writableField1);
		assertNotNull(copyInstance.writableField2);
		assertFalse(copyInstance.writableField2 == notCopyableSubclass.writableField2);
	}

	[Test]
	public function copyingByCopyFunction():void {
		const copyInstance:NotCopyableSubclass = copy(notCopyableSubclass);
		assertNotNull(copyInstance);
		assertNotNull(copyInstance.property1);
		assertEquals(copyInstance.property1, notCopyableSubclass.property1);
		assertNotNull(copyInstance.property2);
		assertFalse(copyInstance.property2 == notCopyableSubclass.property2);
		assertNotNull(copyInstance.writableField1);
		assertEquals(copyInstance.writableField1, notCopyableSubclass.writableField1);
		assertNotNull(copyInstance.writableField2);
		assertFalse(copyInstance.writableField2 == notCopyableSubclass.writableField2);
	}
}
}

Create new test class CopyingOfNotCopyableSubclassTest for testing of creation copies for NotCopyableSubclass.


package com.dotfold.dotvimstat.view.animation
{
	import com.greensock.TweenLite;

	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.setTimeout;

	/**
	 * Sequence the alpha animation of a list of DisplayObject.
	 *
	 * @author jamesmcnamee
	 *
	 */
	public class ElementAnimationSequencer extends EventDispatcher
	{

		private var _queue:Array;

		/**
		 * Constructor.
		 */
		public function ElementAnimationSequencer()
		{
			super();

			_queue = [];
		}

		/**
		 * Adds a DisplayObject to the sequence.
		 *
		 * @param element DisplayObject to add to sequence.
		 * @return this for chaining
		 *
		 */
		public function addElement(element:DisplayObject):ElementAnimationSequencer
		{
			_queue.push(element);

			return this;
		}

		/**
		 * Starts the sequence.
		 */
		public function play():void
		{
			animateNext();
		}

		/**
		 * Animate the next item in the sequence, is called recursively after
		 * a delay until the queue is empty.
		 */
		private function animateNext():void
		{
			var next:DisplayObject = _queue.shift();
			if (next)
			{
				TweenLite.to(next, 0.4, { alpha: 1, delay: 0.3} );
				setTimeout(animateNext, 0.3);
			}
			else
			{
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}

	}
}

add animation sequencer

[feat] add animation sequencer

- create an abstracted animation sequencer for display objects


package battlecode.world.signals {
    import battlecode.common.AttackType;
    import battlecode.common.MapLocation;

    public class RobotInfoSignal implements Signal {
        private var robotID:uint;
        private var health:Number;

        public function RobotInfoSignal(robotID:uint, health:Number) {
            this.robotID = robotID;
            this.health = health;
        }

        public function getRobotID():uint {
            return robotID;
        }

        public function getHealth():Number {
            return health;
        }

        public function accept(handler:SignalHandler):* {
            return handler.visitRobotInfoSignal(this);
        }

    }

}

add missing file

add missing file


/**
 * Hex
 *
 * Utility class to convert Hex strings to ByteArray or String types.
 * Copyright (c) 2007 Henri Torgemane
 *
 * See LICENSE.txt for full license information.
 */
package util
{
	import flash.utils.ByteArray;

	public class Hex
	{
		/**
		 * Support straight hex, or colon-laced hex.
		 * (that means 23:03:0e:f0, but *NOT* 23:3:e:f0)
		 * Whitespace characters are ignored.
		 */
		public static function toArray(hex:String):ByteArray {
			hex = hex.replace(/\s|:/gm,'');
			var a:ByteArray = new ByteArray;
			if (hex.length&1==1) hex="0"+hex;
			for (var i:uint=0;i<hex.length;i+=2) {
				a[i/2] = parseInt(hex.substr(i,2),16);
			}
			return a;
		}

		public static function fromArray(array:ByteArray, colons:Boolean=false):String {
			var s:String = "";
			for (var i:uint=0;i<array.length;i++) {
				s+=("0"+array[i].toString(16)).substr(-2,2);
				if (colons) {
					if (i<array.length-1) s+=":";
				}
			}
			return s;
		}

		/**
		 *
		 * @param hex
		 * @return a UTF-8 string decoded from hex
		 *
		 */
		public static function toString(hex:String):String {
			var a:ByteArray = toArray(hex);
			return a.readUTFBytes(a.length);
		}

		/**
		 *
		 * @param str
		 * @return a hex string encoded from the UTF-8 string str
		 *
		 */
		public static function fromString(str:String, colons:Boolean=false):String {
			var a:ByteArray = new ByteArray;
			a.writeUTFBytes(str);
			return fromArray(a, colons);
		}

	}
}

Add hex tool

Add hex tool


package aerys.minko.render.material.phong
{
    import aerys.minko.render.RenderTarget;
    import aerys.minko.render.material.basic.BasicShader;
    import aerys.minko.render.shader.SFloat;
    import aerys.minko.render.shader.ShaderSettings;
    import aerys.minko.render.shader.part.phong.PhongShaderPart;
    import aerys.minko.type.enum.Blending;

    public class AmbientShader extends BasicShader
    {
        private var _phong : PhongShaderPart;

        public function AmbientShader(renderTarget  : RenderTarget  = null,
                                      priority      : Number        = 0.0)
        {
            super(renderTarget, priority);

            _phong = new PhongShaderPart(this);
        }

        override protected function initializeSettings(settings:ShaderSettings):void
        {
            super.initializeSettings(settings);

            settings.blending = Blending.OPAQUE;
        }

        override protected function getPixelColor() : SFloat
        {
            var diffuse : SFloat    = super.getPixelColor();

            return float4(multiply(diffuse.rgb, _phong.getAmbientLighting()), diffuse.a);
        }
    }
}

add missing AmbientShader

add missing AmbientShader


package {

  import flash.display.Stage;
  import flash.display.Sprite;
  import flash.display.LoaderInfo;
  import flash.display.StageScaleMode;
  import flash.events.*;
  import flash.display.StageAlign;
  import flash.display.StageScaleMode;
  import flash.external.ExternalInterface;
  import flash.system.Security;
  import flash.utils.*;
  import flash.system.System;

  public class ZeroClipboard extends Sprite {

    private var button:Sprite;
    private var clipText:String = '';

    public function ZeroClipboard() {
      // constructor, setup event listeners and external interfaces
      stage.align = "TL";
      stage.scaleMode = "noScale";
      flash.system.Security.allowDomain("*");

      // import flashvars
      var flashvars:Object = LoaderInfo( this.root.loaderInfo ).parameters;
      // invisible button covers entire stage
      button = new Sprite();
      button.buttonMode = true;
      button.useHandCursor = true;
      button.graphics.beginFill(0xCCFF00);
      button.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
      button.alpha = 0.0;
      addChild(button);
      button.addEventListener(MouseEvent.CLICK, function(event:Event): void {
        // user click copies text to clipboard
        // as of flash player 10, this MUST happen from an in-movie flash click event
        System.setClipboard( clipText );
        ExternalInterface.call( 'ZeroClipboard.dispatch', 'complete', clipText );
      });

      button.addEventListener(MouseEvent.MOUSE_OVER, function(event:Event): void {
        ExternalInterface.call( 'ZeroClipboard.dispatch', 'mouseOver', null );
      } );
      button.addEventListener(MouseEvent.MOUSE_OUT, function(event:Event): void {
        ExternalInterface.call( 'ZeroClipboard.dispatch', 'mouseOut', null );
      } );
      button.addEventListener(MouseEvent.MOUSE_DOWN, function(event:Event): void {
        ExternalInterface.call( 'ZeroClipboard.dispatch', 'mouseDown', null );
      } );
      button.addEventListener(MouseEvent.MOUSE_UP, function(event:Event): void {
        ExternalInterface.call( 'ZeroClipboard.dispatch', 'mouseUp', null );
      } );

      // external functions
      ExternalInterface.addCallback("setHandCursor", setHandCursor);
      ExternalInterface.addCallback("setText", setText);
      ExternalInterface.addCallback("setSize", setSize);

      // signal to the browser that we are ready
      ExternalInterface.call( 'ZeroClipboard.dispatch', 'load', null );
    }

    public function setText(newText:String): void {
      // set the maximum number of files allowed
      clipText = newText;
    }

    public function setHandCursor(enabled:Boolean): void {
      // control whether the hand cursor is shown on rollover (true)
      // or the default arrow cursor (false)
      button.useHandCursor = enabled;
    }
  }
}

package {

  import flash.display.Stage;
  import flash.display.Sprite;
  import flash.display.LoaderInfo;
  import flash.display.StageScaleMode;
  import flash.events.*;
  import flash.display.StageAlign;
  import flash.display.StageScaleMode;
  import flash.external.ExternalInterface;
  import flash.system.Security;
  import flash.utils.*;
  import flash.system.System;

  public class ZeroClipboard extends Sprite {

    private var button:Sprite;
    private var clipText:String = '';

    public function ZeroClipboard() {
      // constructor, setup event listeners and external interfaces
      stage.align = "TL";
      stage.scaleMode = "noScale";
      flash.system.Security.allowDomain("*");

      // import flashvars
      var flashvars:Object = LoaderInfo( this.root.loaderInfo ).parameters;
      // invisible button covers entire stage
      button = new Sprite();
      button.buttonMode = true;
      button.useHandCursor = true;
      button.graphics.beginFill(0xCCFF00);
      button.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
      button.alpha = 0.0;
      addChild(button);
      button.addEventListener(MouseEvent.CLICK, function(event:Event): void {
        // user click copies text to clipboard
        // as of flash player 10, this MUST happen from an in-movie flash click event
        System.setClipboard( clipText );
        ExternalInterface.call( 'ZeroClipboard.dispatch', 'complete', clipText );
      });

      button.addEventListener(MouseEvent.MOUSE_OVER, function(event:Event): void {
        ExternalInterface.call( 'ZeroClipboard.dispatch', 'mouseOver', null );
      } );
      button.addEventListener(MouseEvent.MOUSE_OUT, function(event:Event): void {
        ExternalInterface.call( 'ZeroClipboard.dispatch', 'mouseOut', null );
      } );
      button.addEventListener(MouseEvent.MOUSE_DOWN, function(event:Event): void {
        ExternalInterface.call( 'ZeroClipboard.dispatch', 'mouseDown', null );
      } );
      button.addEventListener(MouseEvent.MOUSE_UP, function(event:Event): void {
        ExternalInterface.call( 'ZeroClipboard.dispatch', 'mouseUp', null );
      } );

      // external functions
      ExternalInterface.addCallback("setHandCursor", setHandCursor);
      ExternalInterface.addCallback("setText", setText);
      ExternalInterface.addCallback("setSize", setSize);

      // signal to the browser that we are ready
      ExternalInterface.call( 'ZeroClipboard.dispatch', 'load', null );
    }

    public function setText(newText:String): void {
      // set the maximum number of files allowed
      clipText = newText;
    }

    public function setHandCursor(enabled:Boolean): void {
      // control whether the hand cursor is shown on rollover (true)
      // or the default arrow cursor (false)
      button.useHandCursor = enabled;
    }

    public function setSize(width:Number, height:Number): void {
      button.width = width;
      button.height = height;
    }
  }
}

Add a setSize function to the object

Add a setSize function to the object


// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.delegates {

	import com.kaltura.config.IKalturaConfig;
	import com.kaltura.config.KalturaConfig;
	import com.kaltura.core.KClassFactory;
	import com.kaltura.encryption.MD5;
	import com.kaltura.errors.KalturaError;
	import com.kaltura.events.KalturaEvent;
	import com.kaltura.net.KalturaCall;

	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.utils.Timer;
	import flash.utils.getDefinitionByName;

	public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate {

		public static var CONNECT_TIME:int = 60000; //60 secs
		public static var LOAD_TIME:int = 120000; //120 secs

		protected var connectTimer:Timer;
		protected var loadTimer:Timer;

		protected var _call:KalturaCall;
		protected var _config:KalturaConfig;

		protected var loader:URLLoader;
		protected var fileRef:FileReference;

		//Setters & getters
		public function get call():KalturaCall {
			return _call;
		}

		public function set call(newVal:KalturaCall):void {
			_call = newVal;
		}

		public function get config():IKalturaConfig {
			return _config;
		}

		public function set config(newVal:IKalturaConfig):void {
			_config = newVal as KalturaConfig;
		}

		public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) {
			this.call = call;
			this.config = config;
			if (!call)
				return; //maybe a multi request
			if (call.useTimeout) {
				connectTimer = new Timer(CONNECT_TIME, 1);
				connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout);

				loadTimer = new Timer(LOAD_TIME, 1);
				loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut);
			}
			execute();
		}

		public function close():void {
			try {
				loader.close();
			}
			catch (e:*) {
			}

			if (call.useTimeout) {
				connectTimer.stop();
				loadTimer.stop();
			}
		}

		protected function onConnectTimeout(event:TimerEvent):void {
			var kError:KalturaError = new KalturaError();
			kError.errorCode = "CONNECTION_TIMEOUT";
			kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client.";
			_call.handleError(kError);
			dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));

			loadTimer.stop();
			close();
		}

		protected function onLoadTimeOut(event:TimerEvent):void {
			connectTimer.stop();

			close();

			var kError:KalturaError = new KalturaError();
			kError.errorCode = "POST_TIMEOUT";
			kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result.";
			_call.handleError(kError);
			dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
		}

		protected function execute():void {
			if (call == null) {
				throw new Error('No call defined.');
			}
			post(); //post the call
		}

		/**
		* Helper function for sending the call straight to the server
		*/
		protected function post():void {

			addOptionalArguments();

			formatRequest();

			sendRequest();

			if (call.useTimeout) {
				connectTimer.start();
			}
		}

		protected function formatRequest():void {
			//The configuration is stronger then the args
			if (_config.partnerId != null && _call.args["partnerId"] == -1)
				_call.setRequestArgument("partnerId", _config.partnerId);

			if (_config.ks != null)
				_call.setRequestArgument("ks", _config.ks);

			if (_config.clientTag != null)
				_call.setRequestArgument("clientTag", _config.clientTag);

			_call.setRequestArgument("ignoreNull", _config.ignoreNull);

			//Create signature hash.
			//call.setRequestArgument("kalsig", getMD5Checksum(call));
		}

		protected function getMD5Checksum(call:KalturaCall):String {
			var props:Array = new Array();
			for each (var prop:String in call.args)
				props.push(prop);

			props.push("service");
			props.push("action");
			props.sort();

			var s:String;
			for each (prop in props) {
				s += prop;

				if (prop == "service")
					s += call.service;
				else if (prop == "action")
					s += call.action;
				else
					s += call.args[prop];
			}

			return MD5.encrypt(s);
		}

		protected function sendRequest():void {

			//construct the loader
			createURLLoader();

			//Create signature hash.
			var kalsig:String = getMD5Checksum(call);

			//create the service request for normal calls
			var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;;

			if (_call.method == URLRequestMethod.GET)
				url += "&";

			var req:URLRequest = new URLRequest(url);
			req.contentType = "application/x-www-form-urlencoded";
			req.method = call.method;
			req.data = call.args;

			loader.dataFormat = URLLoaderDataFormat.TEXT;
			loader.load(req);
		}

		protected function createURLLoader():void {
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onDataComplete);
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			loader.addEventListener(Event.OPEN, onOpen);
		}

		protected function onHTTPStatus(event:HTTPStatusEvent):void {
		}

		protected function onOpen(event:Event):void {
			if (call.useTimeout) {
				connectTimer.stop();
				loadTimer.start();
			}
		}

		protected function addOptionalArguments():void {
			//add optional args here
		}

		// Event Handlers

		/**
		 * try to process received data.
		 * if procesing failed, let call handle the processing error
		 * @param event load complete event
		 */
		protected function onDataComplete(event:Event):void {
			try {
				handleResult(XML(event.target.data));
			}
			catch (e:Error) {
				var kErr:KalturaError = new KalturaError();
				kErr.errorCode = String(e.errorID);
				kErr.errorMsg = e.message;
				_call.handleError(kErr);
			}
		}

		/**
		 * handle io or security error events from the loader.
		 * create relevant KalturaError, let the call process it.
		 * @param event
		 */
		protected function onError(event:ErrorEvent):void {
			clean();
			var kError:KalturaError = createKalturaError(event, loader.data);

			if (!kError) {
				kError = new KalturaError();
				kError.errorMsg = event.text;
				//kError.errorCode;
			}

			call.handleError(kError);

			dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
		}

		/**
		 * parse the server's response and let the call process it.
		 * @param result  server's response
		 */
		protected function handleResult(result:XML):void {
			clean();

			var error:KalturaError = validateKalturaResponse(result);

			if (error == null) {
				var digestedResult:Object = parse(result);
				call.handleResult(digestedResult);
			}
			else {
				call.handleError(error);
			}
		}

		/**
		* stop timers and clean event listeners
		 */
		protected function clean():void {
			if (call.useTimeout) {
				connectTimer.stop();
				loadTimer.stop();
			}

			if (loader == null) {
				return;
			}

			loader.removeEventListener(Event.COMPLETE, onDataComplete);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			loader.removeEventListener(Event.OPEN, onOpen);
		}

		/**
		* create the correct object and populate it with the given values. if the needed class is not found
		 * in the file, a generic object is created with attributes matching the XML attributes.
		* Override this parssing function in the specific delegate to create the correct object.
		* @param   result      instance attributes
		* @return an instance of the class declared by the given XML.
		* */
		public function parse(result:XML):* {
			//by defualt create the response object
			var cls:Class;
			try {
				cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class;
			}
			catch (e:Error) {
				cls = Object;
			}
			var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result);
			return obj;
		}

		/**
		 * If the result string holds an error, return a KalturaError object with
		 * relevant values. <br/>
		 * Overide this to create validation object and fill it.
		 * @param result  the string returned from the server.
		 * @return  matching error object
		 */
		protected function validateKalturaResponse(result:String):KalturaError {
			var kError:KalturaError = null;
			var xml:XML = XML(result);
			if (xml.result.hasOwnProperty('error')
				&& xml.result.error.hasOwnProperty('code')
				&& xml.result.error.hasOwnProperty('message')) {

				kError = new KalturaError();
				kError.errorCode = String(xml.result.error.code);
				kError.errorMsg = xml.result.error.message;
				dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
			}

			return kError;
		}

		/**
		 * create error object and fill it with relevant details
		 * @param event
		 * @param loaderData
		 * @return detailed KalturaError to be processed
		 */
		protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError {
			var ke:KalturaError = new KalturaError();
			return ke;
		}

		/**
		* create the url that is used for serve actions
		* @param call    the KalturaCall that defines the required parameters
		 * @return URLRequest with relevant parameters
		* */
		public function getServeUrl(call:KalturaCall):URLRequest {
			var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action;
			for (var key:String in call.args) {
				url += "&" + key + "=" + call.args[key];
			}
			var req:URLRequest = new URLRequest(url);
			req.contentType = "application/x-www-form-urlencoded";
			req.method = call.method;
//          req.data = call.args;
			return req;
		}

	}
}

// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.delegates {

	import com.kaltura.config.IKalturaConfig;
	import com.kaltura.config.KalturaConfig;
	import com.kaltura.core.KClassFactory;
	import com.kaltura.encryption.MD5;
	import com.kaltura.errors.KalturaError;
	import com.kaltura.events.KalturaEvent;
	import com.kaltura.net.KalturaCall;

	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.utils.Timer;
	import flash.utils.getDefinitionByName;

	public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate {

		public static var CONNECT_TIME:int = 60000; //60 secs
		public static var LOAD_TIME:int = 120000; //120 secs

		protected var connectTimer:Timer;
		protected var loadTimer:Timer;

		protected var _call:KalturaCall;
		protected var _config:KalturaConfig;

		protected var loader:URLLoader;
		protected var fileRef:FileReference;

		//Setters & getters
		public function get call():KalturaCall {
			return _call;
		}

		public function set call(newVal:KalturaCall):void {
			_call = newVal;
		}

		public function get config():IKalturaConfig {
			return _config;
		}

		public function set config(newVal:IKalturaConfig):void {
			_config = newVal as KalturaConfig;
		}

		public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) {
			this.call = call;
			this.config = config;
			if (!call)
				return; //maybe a multi request
			if (call.useTimeout) {
				connectTimer = new Timer(CONNECT_TIME, 1);
				connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout);

				loadTimer = new Timer(LOAD_TIME, 1);
				loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut);
			}
			execute();
		}

		public function close():void {
			try {
				loader.close();
			}
			catch (e:*) {
			}

			if (call.useTimeout) {
				connectTimer.stop();
				loadTimer.stop();
			}
		}

		protected function onConnectTimeout(event:TimerEvent):void {
			var kError:KalturaError = new KalturaError();
			kError.errorCode = "CONNECTION_TIMEOUT";
			kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client.";
			_call.handleError(kError);
			dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));

			loadTimer.stop();
			close();
		}

		protected function onLoadTimeOut(event:TimerEvent):void {
			connectTimer.stop();

			close();

			var kError:KalturaError = new KalturaError();
			kError.errorCode = "POST_TIMEOUT";
			kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result.";
			_call.handleError(kError);
			dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
		}

		protected function execute():void {
			if (call == null) {
				throw new Error('No call defined.');
			}
			post(); //post the call
		}

		/**
		* Helper function for sending the call straight to the server
		*/
		protected function post():void {

			addOptionalArguments();

			formatRequest();

			sendRequest();

			if (call.useTimeout) {
				connectTimer.start();
			}
		}

		protected function formatRequest():void {
			//The configuration is stronger then the args
			if (_config.partnerId != null && _call.args["partnerId"] == -1)
				_call.setRequestArgument("partnerId", _config.partnerId);

			if (_config.ks != null)
				_call.setRequestArgument("ks", _config.ks);

			if (_config.clientTag != null)
				_call.setRequestArgument("clientTag", _config.clientTag);

			_call.setRequestArgument("ignoreNull", _config.ignoreNull);

			//Create signature hash.
			//call.setRequestArgument("kalsig", getMD5Checksum(call));
		}

		protected function getMD5Checksum(call:KalturaCall):String {
			var props:Array = new Array();
			for each (var prop:String in call.args)
				props.push(prop);

			props.push("service");
			props.push("action");
			props.sort();

			var s:String;
			for each (prop in props) {
				s += prop;

				if (prop == "service")
					s += call.service;
				else if (prop == "action")
					s += call.action;
				else
					s += call.args[prop];
			}

			return MD5.encrypt(s);
		}

		protected function sendRequest():void {

			//construct the loader
			createURLLoader();

			//Create signature hash.
			var kalsig:String = getMD5Checksum(call);

			//create the service request for normal calls
			var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;;

			if (_call.method == URLRequestMethod.GET)
				url += "&";

			var req:URLRequest = new URLRequest(url);
			req.contentType = "application/x-www-form-urlencoded";
			req.method = call.method;
			req.data = call.args;

			loader.dataFormat = URLLoaderDataFormat.TEXT;
			loader.load(req);
		}

		protected function createURLLoader():void {
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onDataComplete);
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			loader.addEventListener(Event.OPEN, onOpen);
		}

		protected function onHTTPStatus(event:HTTPStatusEvent):void {
		}

		protected function onOpen(event:Event):void {
			if (call.useTimeout) {
				connectTimer.stop();
				loadTimer.start();
			}
		}

		protected function addOptionalArguments():void {
			//add optional args here
		}

		// Event Handlers

		/**
		 * try to process received data.
		 * if procesing failed, let call handle the processing error
		 * @param event load complete event
		 */
		protected function onDataComplete(event:Event):void {
			try {
				handleResult(XML(event.target.data));
			}
			catch (e:Error) {
				var kErr:KalturaError = new KalturaError();
				kErr.errorCode = String(e.errorID);
				kErr.errorMsg = e.message;
				_call.handleError(kErr);
			}
		}

		/**
		 * handle io or security error events from the loader.
		 * create relevant KalturaError, let the call process it.
		 * @param event
		 */
		protected function onError(event:ErrorEvent):void {
			clean();
			var kError:KalturaError = createKalturaError(event, loader.data);

			if (!kError) {
				kError = new KalturaError();
				kError.errorMsg = event.text;
				//kError.errorCode;
			}

			call.handleError(kError);

			dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
		}

		/**
		 * parse the server's response and let the call process it.
		 * @param result  server's response
		 */
		protected function handleResult(result:XML):void {
			clean();

			var error:KalturaError = validateKalturaResponse(result);

			if (error == null) {
				var digestedResult:Object = parse(result);
				call.handleResult(digestedResult);
			}
			else {
				call.handleError(error);
			}
		}

		/**
		* stop timers and clean event listeners
		 */
		protected function clean():void {
			if (call.useTimeout) {
				connectTimer.stop();
				loadTimer.stop();
			}

			if (loader == null) {
				return;
			}

			loader.removeEventListener(Event.COMPLETE, onDataComplete);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			loader.removeEventListener(Event.OPEN, onOpen);
		}

		/**
		* create the correct object and populate it with the given values. if the needed class is not found
		 * in the file, a generic object is created with attributes matching the XML attributes.
		* Override this parssing function in the specific delegate to create the correct object.
		* @param   result      instance attributes
		* @return an instance of the class declared by the given XML.
		* */
		public function parse(result:XML):* {
			//by defualt create the response object
			var cls:Class;
			try {
				cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class;
			}
			catch (e:Error) {
				cls = Object;
			}
			var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result);
			return obj;
		}

		/**
		 * If the result string holds an error, return a KalturaError object with
		 * relevant values. <br/>
		 * Overide this to create validation object and fill it.
		 * @param result  the string returned from the server.
		 * @return  matching error object
		 */
		protected function validateKalturaResponse(result:String):KalturaError {
			var kError:KalturaError = null;
			var xml:XML = XML(result);
			if (xml.result.hasOwnProperty('error')
				&& xml.result.error.hasOwnProperty('code')
				&& xml.result.error.hasOwnProperty('message')) {

				kError = new KalturaError();
				kError.errorCode = String(xml.result.error.code);
				kError.errorMsg = xml.result.error.message;
				dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
			}

			return kError;
		}

		/**
		 * create error object and fill it with relevant details
		 * @param event
		 * @param loaderData
		 * @return detailed KalturaError to be processed
		 */
		protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError {
			var ke:KalturaError = new KalturaError();
			ke.errorMsg = event.text;
			return ke;
		}

		/**
		* create the url that is used for serve actions
		* @param call    the KalturaCall that defines the required parameters
		 * @return URLRequest with relevant parameters
		* */
		public function getServeUrl(call:KalturaCall):URLRequest {
			var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action;
			for (var key:String in call.args) {
				url += "&" + key + "=" + call.args[key];
			}
			var req:URLRequest = new URLRequest(url);
			req.contentType = "application/x-www-form-urlencoded";
			req.method = call.method;
//          req.data = call.args;
			return req;
		}

	}
}

qnd: add error event text to the KalturaError

git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@90711 6b8eccd3-e8c5-4e7d-8186-e12b5326b719


////////////////////////////////////////////////////////////////////////////////
// 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.model
{

public interface IConstraints
{
    function get left():String;
    function set left(value:String):void;

    function get top():String;
    function set top(value:String):void;

    function get right():String;
    function set right(value:String):void;

    function get bottom():String;
    function set bottom(value:String):void;
}
}

Add IConstraints.

Add IConstraints.


package server {
    import flash.net.NetConnection;
    import flash.net.Responder;

    public final class FMSConnection extends NetConnection {

        public function FMSConnection(command:String = null, ...rest) {
            command && this.connect.apply(null, [command].concat(rest));
        }

        public function dispose():void {
            this.close();
        }

        override public function connect(command:String, ...rest):void {
            try {
                super.connect.apply(null, [command].concat(rest));
            } catch (error:Error) {
                trace(this.toString(), 'Can\'t connect...the connection name is already being used by another SWF.');
            }
        }

        override public function close():void {
            try {
                super.close();
            } catch (error:Error) {
                trace(this.toString(), error.message);
            }
        }

        override public function call(command:String, responder:Responder, ...rest):void {
            super.call.apply(null, [command, responder].concat(rest));
        }

        override public function toString():String {
            return '[FMSConnection]';
        }
    }
}

Create FMSConnection.as

Create FMSConnection.as


const count = 1024;

function foo() {
  var a = [];
  for (var i = 0; i < count; i++) {
    a.push(i);
  }
  for (var j = 0; j < 1024; j++) {
    for (var i = 2; i < count; i++) {
      a[i] = a[i - 1] + a[i - 2];
    }
  }
  trace(a.length);
}

foo();

const count = 16;

function foo() {
  var a = [];
  for (var i = 0; i < count; i++) {
    a.push(i);
  }
  for (var j = 0; j < 1024; j++) {
    for (var i = 2; i < count; i++) {
      a[i] = a[i - 1] + a[i - 2];
    }
  }
  trace(a.length);
}

foo();

Reduce test running time.

Reduce test running time.


package code
{
    /*****************************************
	 * based on textmate actionscript bundle
	 ****************************************/

	import fl.events.SliderEvent;

	public class Foo extends MovieClip
	{
		//*************************
		// Properties:

		public var activeSwatch:MovieClip;

		// Color offsets
		public var c1:Number = 0;	// R

		//*************************
		// Constructor:

		public function Foo()
		{
			// Respond to mouse events
			swatch1_btn.addEventListener(MouseEvent.CLICK,swatchHandler,false,0,false);
			previewBox_btn.addEventListener(MouseEvent.MOUSE_DOWN,dragPressHandler);

			// Respond to drag events
			red_slider.addEventListener(SliderEvent.THUMB_DRAG,sliderHandler);

			// Draw a frame later
			addEventListener(Event.ENTER_FRAME,draw);
		}

		protected function clickHandler(event:MouseEvent):void
		{
			car.transform.colorTransform = new ColorTransform(0,0,0,1,c1,c2,c3);
		}

		protected function changeRGBHandler(event:Event):void
		{
			c1 = Number(c1_txt.text);

			if(!(c1>=0)){
				c1 = 0;
			}

			updateSliders();
		}
	}
}

Update static/vendors/ace-builds/demo/kitchen-sink/docs/actionscript.as

Signed-off-by: Bernard Ojengwa <fccb4cc00c1ba7e51bf5c2b5f77130b9fe8d917e@gmail.com>


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

	import org.apache.flex.core.BeadViewBase;
	import org.apache.flex.core.IBead;
	import org.apache.flex.core.IBeadView;
	import org.apache.flex.core.ILayoutParent;
	import org.apache.flex.core.IStrand;
    import org.apache.flex.core.IParent;
	import org.apache.flex.core.UIBase;
	import org.apache.flex.core.ValuesManager;
	import org.apache.flex.html.Container;
	import org.apache.flex.html.supportClasses.Border;
	import org.apache.flex.html.supportClasses.ContainerContentArea;
	import org.apache.flex.html.supportClasses.ScrollBar;
    import org.apache.flex.html.beads.models.ScrollBarModel;

    /**
     *  The ContainerView class is the default view for
     *  the org.apache.flex.html.Container class.
     *  It lets you use some CSS styles to manage the border, background
     *  and padding around the content area.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10.2
     *  @playerversion AIR 2.6
     *  @productversion FlexJS 0.0
     */
	public class ScrollingContainerView extends BeadViewBase implements IBeadView, ILayoutParent
	{
        /**
         *  Constructor.
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		public function ScrollingContainerView()
		{
		}

        /**
         *  The actual parent that parents the children.
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		protected var actualParent:DisplayObjectContainer;

        /**
         *  @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;

			var padding:Object = determinePadding();

			if (contentAreaNeeded())
			{
				actualParent = new ContainerContentArea();
				DisplayObjectContainer(value).addChild(actualParent);
				Container(value).setActualParent(actualParent);
				actualParent.x = padding.paddingLeft;
				actualParent.y = padding.paddingTop;
			}
			else
			{
				actualParent = value as UIBase;
			}

			var backgroundColor:Object = ValuesManager.valuesImpl.getValue(value, "background-color");
			var backgroundImage:Object = ValuesManager.valuesImpl.getValue(value, "background-image");
			if (backgroundColor != null || backgroundImage != null)
			{
				if (value.getBeadByType(IBackgroundBead) == null)
					value.addBead(new (ValuesManager.valuesImpl.getValue(value, "iBackgroundBead")) as IBead);
			}

			var borderStyle:String;
			var borderStyles:Object = ValuesManager.valuesImpl.getValue(value, "border");
			if (borderStyles is Array)
			{
				borderStyle = borderStyles[1];
			}
			if (borderStyle == null)
			{
				borderStyle = ValuesManager.valuesImpl.getValue(value, "border-style") as String;
			}
			if (borderStyle != null && borderStyle != "none")
			{
				if (value.getBeadByType(IBorderBead) == null)
					value.addBead(new (ValuesManager.valuesImpl.getValue(value, "iBorderBead")) as IBead);
			}
		}

		/**
		 *  Determines the top and left padding values, if any, as set by
		 *  padding style values. This includes "padding" for all padding values
		 *  as well as "padding-left" and "padding-top".
		 *
		 *  Returns an object with paddingLeft and paddingTop properties.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		protected function determinePadding():Object
		{
			var paddingLeft:Object;
			var paddingTop:Object;
			var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding");
			if (padding is Array)
			{
				if (padding.length == 1)
					paddingLeft = paddingTop = padding[0];
				else if (padding.length <= 3)
				{
					paddingLeft = padding[1];
					paddingTop = padding[0];
				}
				else if (padding.length == 4)
				{
					paddingLeft = padding[3];
					paddingTop = padding[0];
				}
			}
			else if (padding == null)
			{
				paddingLeft = ValuesManager.valuesImpl.getValue(_strand, "padding-left");
				paddingTop = ValuesManager.valuesImpl.getValue(_strand, "padding-top");
			}
			else
			{
				paddingLeft = paddingTop = padding;
			}
			var pl:Number = Number(paddingLeft);
			var pt:Number = Number(paddingTop);

			return {paddingLeft:pl, paddingTop:pt};
		}

		/**
		 *  Returns true if container to create a separate ContainerContentArea.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		protected function contentAreaNeeded():Boolean
		{
			var padding:Object = determinePadding();

			return (!isNaN(padding.paddingLeft) && padding.paddingLeft > 0 ||
				    !isNaN(padding.paddingTop) && padding.paddingTop > 0);
		}

        /**
         *  The parent of the children.
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		public function get contentView():DisplayObjectContainer
		{
			return actualParent;
		}

        /**
         *  The border.
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		public function get border():Border
		{
			return null;
		}

        /**
         *  The host component, which can resize to different slots.
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		public function get resizableView():DisplayObject
		{
			return _strand as DisplayObject;
		}

        private var _vScrollBar:ScrollBar;

        /**
         *  The vertical ScrollBar, if it exists.
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		public function get vScrollBar():ScrollBar
		{
            if (!_vScrollBar)
                _vScrollBar = createScrollBar();
            return _vScrollBar;
		}

        /**
         *  The horizontal ScrollBar, if it exists.
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
		public function get hScrollBar():ScrollBar
		{
			return null;
		}

        /**
         * @private
         */
        private function createScrollBar():ScrollBar
        {
            var vsb:ScrollBar;
            vsb = new ScrollBar();
            var vsbm:ScrollBarModel = new ScrollBarModel();
            vsbm.maximum = 100;
            vsbm.minimum = 0;
            vsbm.pageSize = 10;
            vsbm.pageStepSize = 10;
            vsbm.snapInterval = 1;
            vsbm.stepSize = 1;
            vsbm.value = 0;
            vsb.model = vsbm;
            vsb.width = 16;
            IParent(_strand).addElement(vsb);
            return vsb;
        }

        /**
         *  The position of the vertical scrollbar
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
        public function get verticalScrollPosition():Number
        {
            return ScrollBarModel(vScrollBar.model).value;
        }

        /**
         *  @private
         */
        public function set verticalScrollPosition(value:Number):void
        {
            ScrollBarModel(vScrollBar.model).value = value;
        }

        /**
         *  The maximum position of the vertical scrollbar
         *
         *  @langversion 3.0
         *  @playerversion Flash 10.2
         *  @playerversion AIR 2.6
         *  @productversion FlexJS 0.0
         */
        public function get maxVerticalScrollPosition():Number
        {
            return ScrollBarModel(vScrollBar.model).maximum -
                ScrollBarModel(vScrollBar.model).pageSize;
        }

    }
}

add a scrolling container view

add a scrolling container view


package goplayer
{
	public function debug(message : Object)
  { callJavascript("goplayer.log", message.toString()) }
}

Add debug.as to skin-src.

Add debug.as to skin-src.


package aerys.minko.render.material.vertex
{
	import aerys.minko.render.RenderTarget;
	import aerys.minko.render.material.basic.BasicShader;
	import aerys.minko.render.shader.SFloat;
	import aerys.minko.render.shader.Shader;

	public class VertexTangentShader extends BasicShader
	{
		private var _tangent	: SFloat;

		public function VertexTangentShader(renderTarget 	: RenderTarget	= null,
											priority		: Number		= 0.0)
		{
			super(renderTarget, priority);
		}

		override protected function getVertexPosition() : SFloat
		{
			_tangent = deltaLocalToWorld(vertexAnimation.getAnimatedVertexTangent());
			_tangent = normalize(_tangent);
			_tangent = divide(add(_tangent, 1), 2);

			return super.getVertexPosition();
		}

		override protected function getPixelColor() : SFloat
		{
			return float4(normalize(interpolate(_tangent.xyz)), 1);
		}
	}
}

add VertexTangentShader to display per-pixel tangents


package aerys.minko.scene.controller.debug
{
	import aerys.minko.render.geometry.primitive.CubeGeometry;
	import aerys.minko.render.material.Material;
	import aerys.minko.render.material.basic.BasicMaterial;
	import aerys.minko.scene.controller.AbstractController;
	import aerys.minko.scene.node.Group;
	import aerys.minko.scene.node.Mesh;
	import aerys.minko.type.enum.DepthTest;
	import aerys.minko.type.math.Vector4;

	/**
	 * Add debug meshes to see the joint and the bone described by a Group node.
	 * This controller can be added to every joint of a skeleton to display it:
	 *
	 *

	 * var debugCtrl : JointsDebugController = new JointsDebugController();
	 *
	 * for each (var m : Mesh in result.get('//mesh[hasController(SkinningController)]'))
	 * {
	 *   var skinningCtrl : SkinningController = m.getControllersByType(SkinningController)[0]
	 *     as SkinningController;
	 *
	 *   for each (var joint : Group in skinningCtrl.joints)
	 *     if (joint.getControllersByType(JointsDebugController).length == 0)
	 *       joint.addController(debugCtrl);
	 * }
	 *

	 *
	 * To remove this controller, you can fetch all the group that have it and remove it from
	 * their controllers:
	 *
	 *

	 * for each (var node : ISceneNode in result.get('//group[hasController(JointsDebugController)]'))
	 *   node.removeController(debugCtrl);
	 *

	 *
	 * @author Jean-Marc Le Roux
	 *
	 */
	public final class JointsDebugController extends AbstractController
	{
		private var _jointsMaterial	: Material;
		private var _bonesMaterial	: Material;

		public function JointsDebugController(jointsMaterial	: Material	= null,
											  bonesMaterial		: Material	= null)
		{
			super(Group);

			initialize(jointsMaterial, bonesMaterial);
		}

		private function initialize(jointsMaterial	: Material,
									bonesMaterial	: Material) : void
		{
			_jointsMaterial = jointsMaterial;
			if (!_jointsMaterial)
			{
				var jointsBasicMaterial : BasicMaterial = new BasicMaterial();

				jointsBasicMaterial.diffuseColor = 0xff0000ff;
				jointsBasicMaterial.depthWriteEnabled = false;
				jointsBasicMaterial.depthTest = DepthTest.ALWAYS;
				_jointsMaterial = jointsBasicMaterial;
			}

			_bonesMaterial = bonesMaterial;
			if (!_bonesMaterial)
			{
				var bonesBasicMaterial : BasicMaterial = new BasicMaterial();

				bonesBasicMaterial.diffuseColor = 0x00ff00ff;
				bonesBasicMaterial.depthWriteEnabled = false;
				bonesBasicMaterial.depthTest = DepthTest.ALWAYS;
				_bonesMaterial = bonesBasicMaterial;
			}

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

		private function targetAddedHandler(ctrl	: AbstractController,
											target	: Group) : void
		{
			var numChildren : uint = target.numChildren;

			for (var i : uint = 0; i < numChildren; ++i)
			{
				var child : Group = target.getChildAt(i) as Group;

				if (child != null)
				{
					var nextJointPosition 	: Vector4 	= child.transform.transformVector(
						Vector4.ZERO
					);
					var boneLength 			: Number 	= nextJointPosition.length;
					var boneMesh 			: Mesh 		= new Mesh(
						CubeGeometry.cubeGeometry, _bonesMaterial, '__bone__'
					);
					var jointMesh			: Mesh		= new Mesh(
						CubeGeometry.cubeGeometry, _jointsMaterial, '__joint__'
					);

					jointMesh.transform.appendUniformScale(.08);
					target.addChild(jointMesh);

					if (boneLength != 0.)
					{
						boneMesh.transform
							.lookAt(nextJointPosition)
							.prependTranslation(0, 0, boneLength * .5)
							.prependScale(.02, .02, boneLength);

						target.addChild(boneMesh);
					}
				}
			}
		}

		private function targetRemovedHandler(ctrl 		: AbstractController,
											  target	: Group) : void
		{
			for each (var jointMesh : Mesh in target.get("/mesh[name='__joint__']"))
				jointMesh.parent = null;

			for each (var boneMesh : Mesh in target.get("/mesh[name='__bone__']"))
				boneMesh.parent = null;
		}
	}
}

add JointsDebugController to display a Group as a joint/bone


////////////////////////////////////////////////////////////////////////////////
//
//  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 {

import flash.display.DisplayObject;
import flash.display.InteractiveObject;
import flash.display.Sprite;
import flash.events.FocusEvent;
import flash.events.SoftKeyboardEvent;
import flash.events.SoftKeyboardTrigger;
import flash.geom.Rectangle;
import flash.text.TextField;
import flash.utils.getQualifiedClassName;

import mx.core.mx_internal;

[Mixin]
/**
 *  A hash table of tests not to run.
 */
public class FakeSoftKeyboard
{

	private static var kbdrect:QName = new QName(mx_internal, "_softKeyboardRect");

	public static var portraitHeight:Number = 200;
	public static var landscapeHeight:Number = 150;

	/**
	 *  Mixin callback that checks if we're in the emulator
	 *  and tries to fake what would happen in terms of events
	 *  and sizing if you were on the device.  It doesn't actually
	 *  need a useful UI since to type, you should just use
	 *  DispatchKeyEvent
	 */
	public static function init(root:DisplayObject):void
	{
		if (DeviceNames.getFromOS() == "")
			return;	// not mac or win

		FakeSoftKeyboard.root = root;

		root.addEventListener(FocusEvent.FOCUS_IN, focusInHandler);
		root.addEventListener(FocusEvent.FOCUS_OUT, focusOutHandler);
	}

	public static var kbd:Sprite;
	public static var root:DisplayObject;

	public static function focusInHandler(event:FocusEvent):void
	{
		var comp:Object = event.target;
		if (comp is TextField || comp is InteractiveObject)
		{
			if (!(comp.needsSoftKeyboard || getQualifiedClassName(comp).indexOf("StyleableStageText") > 0))
				return;

			if (!comp.dispatchEvent(new SoftKeyboardEvent(SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATING,
							true, true, event.relatedObject, SoftKeyboardTrigger.USER_TRIGGERED)))
			{
				root.stage.focus = null;
				return;
			}

			if (!kbd)
			{
				kbd = new Sprite();
				kbd.graphics.beginFill(0x808080);
				kbd.graphics.drawRect(0, 0, 10, 10);
				kbd.graphics.endFill();
			}

			// root is actually a systemManager
			root["popUpChildren"].addChild(kbd);
			if (root.stage.stageHeight > root.stage.stageWidth)
			{
				kbd.height = portraitHeight;
				kbd.width = root.stage.stageWidth;
				root["document"][kbdrect] = new Rectangle(0, 0, kbd.width, kbd.height);
				kbd.y = root.stage.stageHeight - portraitHeight;
			}
			else
			{
				kbd.height = landscapeHeight;
				kbd.width = root.stage.stageWidth;
				root["document"][kbdrect] = new Rectangle(0, 0, kbd.width, kbd.height);
				kbd.y = root.stage.stageHeight - landscapeHeight;
			}
			trace("sent softKeyboardActivate from", comp);
			comp.dispatchEvent(new SoftKeyboardEvent(SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE,
							true, false, event.relatedObject, SoftKeyboardTrigger.USER_TRIGGERED));
		}
	}

	public static function focusOutHandler(event:FocusEvent):void
	{
		trace("fakesoftkeyboard focusOut", event.target, event.relatedObject, kbd);
		if (kbd && kbd.parent)
		{
			// root is actually a systemManager
			root["popUpChildren"].removeChild(kbd);
			root["document"][kbdrect] = new Rectangle(0, 0, 0, 0);
			trace("sent softKeyboardDeactivate from", event.target);
			event.target.dispatchEvent(new SoftKeyboardEvent(SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE,
								true, false, event.relatedObject, SoftKeyboardTrigger.USER_TRIGGERED));
		}
	}

}

}

Add helper to fake softkeyboard events on desktop runs.

git-svn-id: f8d5f742b420a6a114b58659a4f85f335318e53c@1436779 13f79535-47bb-0310-9956-ffa450edef68


package dolly {

import dolly.core.dolly_internal;
import dolly.data.CopyableClass;

import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;

use namespace dolly_internal;

public class CopyingOfCopyableClassTest {

	private var copyableClass:CopyableClass;
	private var copyableClassType:Type;

	[Before]
	public function before():void {
		copyableClass = new CopyableClass();
		copyableClass.property1 = "property1 value";
		copyableClass.writableField1 = "writableField1 value";
		copyableClassType = Type.forInstance(copyableClass);
	}

	[After]
	public function after():void {
		copyableClass = null;
		copyableClassType = null;
	}

	[Test]
	public function findingAllCopyableFieldsForType():void {
		const copyableFields:Vector.<Field> = Copier.findCopyableFieldsForType(copyableClassType);
		assertNotNull(copyableFields);
		assertEquals(2, copyableFields.length);
		assertNotNull(copyableFields[0]);
		assertNotNull(copyableFields[1]);
	}

	[Test]
	public function copyingByCopier():void {
		const copyInstance:CopyableClass = Copier.copy(copyableClass);
		assertNotNull(copyInstance);
		assertNotNull(copyInstance.property1);
		assertEquals(copyInstance.property1, copyableClass.property1);
		assertNotNull(copyInstance.writableField1);
		assertEquals(copyInstance.writableField1, copyableClass.writableField1);
	}

	[Test]
	public function copyingByCopyFunction():void {
		const copyInstance:CopyableClass = copy(copyableClass);
		assertNotNull(copyInstance);
		assertNotNull(copyInstance.property1);
		assertEquals(copyInstance.property1, copyableClass.property1);
		assertNotNull(copyInstance.writableField1);
		assertEquals(copyInstance.writableField1, copyableClass.writableField1);
	}
}
}

Create new test class CopyingOfCopyableClassTest for testing of creation copies of CopyableClass.


package avmplus {
  import flash.utils.Dictionary;
  import flash.utils.getQualifiedClassName;

  trace(getQualifiedClassName("Hello"));
  trace(getQualifiedClassName(123));
  trace(getQualifiedClassName(String));

  trace(getQualifiedClassName([]));
  trace(getQualifiedClassName(Array));

  trace(getQualifiedClassName(true));
  trace(getQualifiedClassName(0));

  class A {}
  trace(getQualifiedClassName(A));
  trace(getQualifiedClassName(new A()));

  var values = [1, -1, "1", "-1", true, false, NaN, Infinity, +Infinity, null, undefined, {}, [], Array, Object, Boolean, A];

  values.forEach(function (v) {
    trace(getQualifiedClassName(v));
  });

  trace("--- DONE ---");
}

Add test case.

Add test case.


package com.google.analytics
{
    import core.Logger;
    import core.log;

    public const log:Logger = core.log;

    /* note:
       we use the logd library
       http://code.google.com/p/maashaack/wiki/logd

       Within your IDE when you build locally
       for Flash Builder
       in Project Properties
       then ActionScript Compiler
       under "Additional compiler arguments":
       -locale en_US -load-config build/config-local.xml

       the Ant build will use
       build/config.xml to produce gaforflash.swc
       and
       build/config-debug.xml to produce gaforflash_d.swc

       We use conditional compilation
       see: http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_21.html

       that means everything written within LOG::P{ ... }
       is not included in the final binary
       when LOG::P is set to false
    */
    LOG::P
    {
        var cfg:Object = { sep: " ", //char separator
                           mode: "clean", // "raw", "clean", "data", "short"
                           tag: true, //use tag
                           time: true  //use time
                         };
        log.config( cfg );
        log.level = log.VERBOSE;
    }

}

add log instance for GA

add log instance for GA


// Happy New Year in ActionScript 3. Place code in the first frame Actions.
var t:TextField=new TextField();
t.text="Happy New Year";
addChild(t);

Add Action script

Add Action script


package com.threerings.util {

import flash.display.DisplayObject;

import flash.events.Event;
import flash.events.IOErrorEvent;

import flash.net.URLLoader;
import flash.net.URLRequest;

/**
 * A utility for loading parameters from an XML file when run from
 * the local filesystem.
 *
 * The file "parameters.xml" should reside in the current directory and contains:
 *  <parameters>
 *      <param name="name1" value="val1"/>
 *      <param name="name2" value="val2"/>
 *  </parameters>
 */
public class ParameterUtil
{
    /**
     * Get the parameters.
     * Note: the callback function may be called prior to this method
     * returning.
     */
    public static function getParameters (disp :DisplayObject, callback :Function) :void
    {
        var url :String = disp.root.loaderInfo.url;
        // normal parameters
        if (url == null || 0 != url.indexOf("file:")) {
            callback(disp.root.loaderInfo.parameters);
            return;
        }

        // instead read from XML
        var loader :URLLoader = new URLLoader();
        loader.addEventListener(IOErrorEvent.IO_ERROR,
            function (event :Event) :void {
                trace("Error loading params: " + event);
                callback(disp.root.loaderInfo.parameters);
            }
        );
        loader.addEventListener(Event.COMPLETE,
            function (event :Event) :void  {
                var data :XML = XML(loader.data);
                var params :Object = {};
                for each (var param :XML in data..param) {
                    params[param.@name] = String(param.@value);
                }
                callback(params);
            }
        );
        loader.load(new URLRequest("file:parameters.xml"));
    }
}
}

ParameterUtil: read params from an XML file we're loaded from the file system.

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


/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is [Open Source Virtual Machine.].
 *
 * The Initial Developer of the Original Code is
 * Adobe System Incorporated.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Adobe AS3 Team
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

/* testcases:
 *   master string exposed to heap graph
 */

package {

    import flash.sampler.*
    import avmplus.*

    var SECTION = "Sampling";
    var VERSION = "AS3";
    var TITLE   = "Master String";

    startTest();
    writeHeaderToLog("Sampling master string test");

    var isdebugger=System.isDebugger();

    var helloWorld = "hello, world";
    var hello = helloWorld.substr(0, 5);

    AddTestCase("assert that static string constant does not have a master string",
        null,
        getMasterString(helloWorld));

    AddTestCase("assert that substring has a master string",
        isdebugger ? helloWorld : null,
        getMasterString(hello));

    test();
}

Add this back

Add this back