CombinedText
stringlengths
4
3.42M
package nid.xfl.compiler.swf.data.actions.swf4 { import nid.xfl.compiler.swf.data.actions.*; public class ActionLess extends Action implements IAction { public static const CODE:uint = 0x0f; public function ActionLess(code:uint, length:uint) { super(code, length); } override public function toString(indent:uint = 0):String { return "[ActionLess]"; } } }
package flexUnitTests.as3.mongo.wire.messages { import as3.mongo.db.document.Document; import as3.mongo.wire.messages.MessageFactory; import as3.mongo.wire.messages.client.OpUpdate; import as3.mongo.wire.messages.client.OpUpdateFlags; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertTrue; public class MessageFactory_makeUpdateFirstOpUpdateMessageTests { private var _messageFactory:MessageFactory; private var _testDBName:String = "aDB"; private var _testCollectionName:String = "aCollection"; private var _testFullCollectionName:String = "aDB.aCollection"; private var _testSelector:Document = new Document(); private var _testUpdate:Document = new Document(); private var _opUpdate:OpUpdate; [Before] public function setUp():void { _messageFactory = new MessageFactory(); _opUpdate = _messageFactory.makeUpdateFirstOpUpdateMessage(_testDBName, _testCollectionName, _testSelector, _testUpdate); } [After] public function tearDown():void { _messageFactory = null; } [Test] public function makeUpdateFirstOpUpdateMessage_validInputs_OpUpdateInstanceReturned():void { assertTrue(_opUpdate is OpUpdate); } [Test] public function makeUpdateFirstOpUpdateMessage_validInputs_flagsIsSetToNoFlags():void { assertEquals(OpUpdateFlags.NO_FLAGS, _opUpdate.flags); } [Test] public function makeUpdateFirstOpUpdateMessage_validInputs_fullCollectionNameIsSet():void { assertEquals(_testFullCollectionName, _opUpdate.fullCollectionName); } [Test] public function makeUpdateFirstOpUpdateMessage_validInputs_selectorIsSet():void { assertEquals(_testSelector, _opUpdate.selector); } [Test] public function makeUpdateFirstOpUpdateMessage_validInputs_updateIsSet():void { assertEquals(_testUpdate, _opUpdate.update); } } }
package org.janschaedlich.oauth.util { import flash.net.URLRequest; import flash.net.URLRequestHeader; public class URLRequestUtil { public function URLRequestUtil() { } public static function getAuthorizationRequestHeader(urlRequest:URLRequest):URLRequestHeader { return new URLRequestUtil().internal_getAuthorizationRequestHeader(urlRequest); } public static function authorizationRequestHeaderContainsParam(param:String, authorizationRequestHeader:URLRequestHeader):Boolean { return new URLRequestUtil().internal_authorizationRequestHeaderContainsParam(param, authorizationRequestHeader); } public function internal_getAuthorizationRequestHeader(urlRequest:URLRequest):URLRequestHeader { var authorizationRequestHeader:URLRequestHeader = null; for each (var requestHeader:URLRequestHeader in urlRequest.requestHeaders) { if (requestHeader.name == "Authorization") { authorizationRequestHeader = requestHeader; break; } } return authorizationRequestHeader; } public function internal_authorizationRequestHeaderContainsParam(param:String, authorizationRequestHeader:URLRequestHeader):Boolean { return (authorizationRequestHeader.value.indexOf(param) != -1); } } }
/* Feathers Copyright 2012-2015 Joshua Tynjala. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.layout { import feathers.core.IFeathersControl; import feathers.core.IValidating; import flash.errors.IllegalOperationError; import flash.geom.Point; import starling.display.DisplayObject; import starling.events.Event; import starling.events.EventDispatcher; /** * Dispatched when a property of the layout changes, indicating that a * redraw is probably needed. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>.</td></tr> * <tr><td><code>data</code></td><td>null</td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. Use the * <code>currentTarget</code> property to always access the Object * listening for the event.</td></tr> * </table> * * @eventType starling.events.Event.CHANGE */ [Event(name="change",type="starling.events.Event")] /** * Dispatched when the layout would like to adjust the container's scroll * position. Typically, this is used when the virtual dimensions of an item * differ from its real dimensions. This event allows the container to * adjust scrolling so that it appears smooth, without jarring jumps or * shifts when an item resizes. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>.</td></tr> * <tr><td><code>data</code></td><td>A <code>flash.geom.Point</code> object * representing how much the scroll position should be adjusted in both * horizontal and vertical directions. Measured in pixels.</td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. Use the * <code>currentTarget</code> property to always access the Object * listening for the event.</td></tr> * </table> * * @eventType starling.events.Event.SCROLL */ [Event(name="scroll",type="starling.events.Event")] /** * Positions items from top to bottom in a single column. * * @see ../../../help/vertical-layout.html How to use VerticalLayout with Feathers containers */ public class VerticalLayout extends EventDispatcher implements IVariableVirtualLayout, ITrimmedVirtualLayout { /** * If the total item height is smaller than the height of the bounds, * the items will be aligned to the top. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_TOP:String = "top"; /** * If the total item height is smaller than the height of the bounds, * the items will be aligned to the middle. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_MIDDLE:String = "middle"; /** * If the total item height is smaller than the height of the bounds, * the items will be aligned to the bottom. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_BOTTOM:String = "bottom"; /** * The items will be aligned to the left of the bounds. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_LEFT:String = "left"; /** * The items will be aligned to the center of the bounds. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_CENTER:String = "center"; /** * The items will be aligned to the right of the bounds. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_RIGHT:String = "right"; /** * The items will fill the width of the bounds. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_JUSTIFY:String = "justify"; /** * Constructor. */ public function VerticalLayout() { } /** * @private */ protected var _heightCache:Array = []; /** * @private */ protected var _discoveredItemsCache:Vector.<DisplayObject> = new <DisplayObject>[]; /** * @private */ protected var _gap:Number = 0; /** * The space, in pixels, between items. * * @default 0 */ public function get gap():Number { return this._gap; } /** * @private */ public function set gap(value:Number):void { if(this._gap == value) { return; } this._gap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _firstGap:Number = NaN; /** * The space, in pixels, between the first and second items. If the * value of <code>firstGap</code> is <code>NaN</code>, the value of the * <code>gap</code> property will be used instead. * * @default NaN */ public function get firstGap():Number { return this._firstGap; } /** * @private */ public function set firstGap(value:Number):void { if(this._firstGap == value) { return; } this._firstGap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _lastGap:Number = NaN; /** * The space, in pixels, between the last and second to last items. If * the value of <code>lastGap</code> is <code>NaN</code>, the value of * the <code>gap</code> property will be used instead. * * @default NaN */ public function get lastGap():Number { return this._lastGap; } /** * @private */ public function set lastGap(value:Number):void { if(this._lastGap == value) { return; } this._lastGap = value; this.dispatchEventWith(Event.CHANGE); } /** * Quickly sets all padding properties to the same value. The * <code>padding</code> getter always returns the value of * <code>paddingTop</code>, but the other padding values may be * different. * * @default 0 * * @see #paddingTop * @see #paddingRight * @see #paddingBottom * @see #paddingLeft */ public function get padding():Number { return this._paddingTop; } /** * @private */ public function set padding(value:Number):void { this.paddingTop = value; this.paddingRight = value; this.paddingBottom = value; this.paddingLeft = value; } /** * @private */ protected var _paddingTop:Number = 0; /** * The space, in pixels, that appears on top, before the first item. * * @default 0 */ public function get paddingTop():Number { return this._paddingTop; } /** * @private */ public function set paddingTop(value:Number):void { if(this._paddingTop == value) { return; } this._paddingTop = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingRight:Number = 0; /** * The minimum space, in pixels, to the right of the items. * * @default 0 */ public function get paddingRight():Number { return this._paddingRight; } /** * @private */ public function set paddingRight(value:Number):void { if(this._paddingRight == value) { return; } this._paddingRight = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingBottom:Number = 0; /** * The space, in pixels, that appears on the bottom, after the last * item. * * @default 0 */ public function get paddingBottom():Number { return this._paddingBottom; } /** * @private */ public function set paddingBottom(value:Number):void { if(this._paddingBottom == value) { return; } this._paddingBottom = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingLeft:Number = 0; /** * The minimum space, in pixels, to the left of the items. * * @default 0 */ public function get paddingLeft():Number { return this._paddingLeft; } /** * @private */ public function set paddingLeft(value:Number):void { if(this._paddingLeft == value) { return; } this._paddingLeft = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _verticalAlign:String = VERTICAL_ALIGN_TOP; [Inspectable(type="String",enumeration="top,middle,bottom")] /** * If the total item height is less than the bounds, the positions of * the items can be aligned vertically. * * @default VerticalLayout.VERTICAL_ALIGN_TOP * * @see #VERTICAL_ALIGN_TOP * @see #VERTICAL_ALIGN_MIDDLE * @see #VERTICAL_ALIGN_BOTTOM */ public function get verticalAlign():String { return this._verticalAlign; } /** * @private */ public function set verticalAlign(value:String):void { if(this._verticalAlign == value) { return; } this._verticalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _horizontalAlign:String = HORIZONTAL_ALIGN_LEFT; [Inspectable(type="String",enumeration="left,center,right,justify")] /** * The alignment of the items horizontally, on the x-axis. * * <p>If the <code>horizontalAlign</code> property is set to * <code>VerticalLayout.HORIZONTAL_ALIGN_JUSTIFY</code>, the * <code>width</code>, <code>minWidth</code>, and <code>maxWidth</code> * properties of the items may be changed, and their original values * ignored by the layout. In this situation, if the width needs to be * constrained, the <code>width</code>, <code>minWidth</code>, or * <code>maxWidth</code> properties should instead be set on the parent * container using the layout.</p> * * @default VerticalLayout.HORIZONTAL_ALIGN_LEFT * * @see #HORIZONTAL_ALIGN_LEFT * @see #HORIZONTAL_ALIGN_CENTER * @see #HORIZONTAL_ALIGN_RIGHT * @see #HORIZONTAL_ALIGN_JUSTIFY */ public function get horizontalAlign():String { return this._horizontalAlign; } /** * @private */ public function set horizontalAlign(value:String):void { if(this._horizontalAlign == value) { return; } this._horizontalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _useVirtualLayout:Boolean = true; /** * @inheritDoc * * @default true */ public function get useVirtualLayout():Boolean { return this._useVirtualLayout; } /** * @private */ public function set useVirtualLayout(value:Boolean):void { if(this._useVirtualLayout == value) { return; } this._useVirtualLayout = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _hasVariableItemDimensions:Boolean = false; /** * When the layout is virtualized, and this value is true, the items may * have variable height values. If false, the items will all share the * same height value with the typical item. * * @default false */ public function get hasVariableItemDimensions():Boolean { return this._hasVariableItemDimensions; } /** * @private */ public function set hasVariableItemDimensions(value:Boolean):void { if(this._hasVariableItemDimensions == value) { return; } this._hasVariableItemDimensions = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _distributeHeights:Boolean = false; /** * Distributes the height of the view port equally to each item. If the * view port height needs to be measured, the largest item's height will * be used for all items, subject to any specified minimum and maximum * height values. * * @default false */ public function get distributeHeights():Boolean { return this._distributeHeights; } /** * @private */ public function set distributeHeights(value:Boolean):void { if(this._distributeHeights == value) { return; } this._distributeHeights = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _requestedRowCount:int = 0; /** * Requests that the layout set the view port dimensions to display a * specific number of rows (plus gaps and padding), if possible. If the * explicit height of the view port is set, then this value will be * ignored. If the view port's minimum and/or maximum height are set, * the actual number of visible rows may be adjusted to meet those * requirements. Set this value to <code>0</code> to display as many * rows as possible. * * @default 0 */ public function get requestedRowCount():int { return this._requestedRowCount; } /** * @private */ public function set requestedRowCount(value:int):void { if(value < 0) { throw RangeError("requestedRowCount requires a value >= 0"); } if(this._requestedRowCount == value) { return; } this._requestedRowCount = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _manageVisibility:Boolean = false; /** * Determines if items will be set invisible if they are outside the * view port. If <code>true</code>, you will not be able to manually * change the <code>visible</code> property of any items in the layout. * * <p><strong>DEPRECATION WARNING:</strong> This property is deprecated * starting with Feathers 2.0. It will be removed in a future version of * Feathers according to the standard * <a target="_top" href="../../../help/deprecation-policy.html">Feathers deprecation policy</a>. * Originally, the <code>manageVisibility</code> property could be used * to improve performance of non-virtual layouts by hiding items that * were outside the view port. However, other performance improvements * have made it so that setting <code>manageVisibility</code> can now * sometimes hurt performance instead of improving it.</p> * * @default false */ public function get manageVisibility():Boolean { return this._manageVisibility; } /** * @private */ public function set manageVisibility(value:Boolean):void { if(this._manageVisibility == value) { return; } this._manageVisibility = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _beforeVirtualizedItemCount:int = 0; /** * @inheritDoc */ public function get beforeVirtualizedItemCount():int { return this._beforeVirtualizedItemCount; } /** * @private */ public function set beforeVirtualizedItemCount(value:int):void { if(this._beforeVirtualizedItemCount == value) { return; } this._beforeVirtualizedItemCount = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _afterVirtualizedItemCount:int = 0; /** * @inheritDoc */ public function get afterVirtualizedItemCount():int { return this._afterVirtualizedItemCount; } /** * @private */ public function set afterVirtualizedItemCount(value:int):void { if(this._afterVirtualizedItemCount == value) { return; } this._afterVirtualizedItemCount = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _typicalItem:DisplayObject; /** * @inheritDoc * * @see #resetTypicalItemDimensionsOnMeasure * @see #typicalItemWidth * @see #typicalItemHeight */ public function get typicalItem():DisplayObject { return this._typicalItem; } /** * @private */ public function set typicalItem(value:DisplayObject):void { if(this._typicalItem == value) { return; } this._typicalItem = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _resetTypicalItemDimensionsOnMeasure:Boolean = false; /** * If set to <code>true</code>, the width and height of the * <code>typicalItem</code> will be reset to <code>typicalItemWidth</code> * and <code>typicalItemHeight</code>, respectively, whenever the * typical item needs to be measured. The measured dimensions of the * typical item are used to fill in the blanks of a virtualized layout * for virtual items that don't have their own display objects to * measure yet. * * @default false * * @see #typicalItemWidth * @see #typicalItemHeight * @see #typicalItem */ public function get resetTypicalItemDimensionsOnMeasure():Boolean { return this._resetTypicalItemDimensionsOnMeasure; } /** * @private */ public function set resetTypicalItemDimensionsOnMeasure(value:Boolean):void { if(this._resetTypicalItemDimensionsOnMeasure == value) { return; } this._resetTypicalItemDimensionsOnMeasure = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _typicalItemWidth:Number = NaN; /** * Used to reset the width, in pixels, of the <code>typicalItem</code> * for measurement. The measured dimensions of the typical item are used * to fill in the blanks of a virtualized layout for virtual items that * don't have their own display objects to measure yet. * * <p>This value is only used when <code>resetTypicalItemDimensionsOnMeasure</code> * is set to <code>true</code>. If <code>resetTypicalItemDimensionsOnMeasure</code> * is set to <code>false</code>, this value will be ignored and the * <code>typicalItem</code> dimensions will not be reset before * measurement.</p> * * <p>If <code>typicalItemWidth</code> is set to <code>NaN</code>, the * typical item will auto-size itself to its preferred width. If you * pass a valid <code>Number</code> value, the typical item's width will * be set to a fixed size. May be used in combination with * <code>typicalItemHeight</code>.</p> * * @default NaN * * @see #resetTypicalItemDimensionsOnMeasure * @see #typicalItemHeight * @see #typicalItem */ public function get typicalItemWidth():Number { return this._typicalItemWidth; } /** * @private */ public function set typicalItemWidth(value:Number):void { if(this._typicalItemWidth == value) { return; } this._typicalItemWidth = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _typicalItemHeight:Number = NaN; /** * Used to reset the height, in pixels, of the <code>typicalItem</code> * for measurement. The measured dimensions of the typical item are used * to fill in the blanks of a virtualized layout for virtual items that * don't have their own display objects to measure yet. * * <p>This value is only used when <code>resetTypicalItemDimensionsOnMeasure</code> * is set to <code>true</code>. If <code>resetTypicalItemDimensionsOnMeasure</code> * is set to <code>false</code>, this value will be ignored and the * <code>typicalItem</code> dimensions will not be reset before * measurement.</p> * * <p>If <code>typicalItemHeight</code> is set to <code>NaN</code>, the * typical item will auto-size itself to its preferred height. If you * pass a valid <code>Number</code> value, the typical item's height will * be set to a fixed size. May be used in combination with * <code>typicalItemWidth</code>.</p> * * @default NaN * * @see #resetTypicalItemDimensionsOnMeasure * @see #typicalItemWidth * @see #typicalItem */ public function get typicalItemHeight():Number { return this._typicalItemHeight; } /** * @private */ public function set typicalItemHeight(value:Number):void { if(this._typicalItemHeight == value) { return; } this._typicalItemHeight = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _scrollPositionVerticalAlign:String = VERTICAL_ALIGN_MIDDLE; [Inspectable(type="String",enumeration="top,middle,bottom")] /** * When the scroll position is calculated for an item, an attempt will * be made to align the item to this position. * * @default VerticalLayout.VERTICAL_ALIGN_MIDDLE * * @see #VERTICAL_ALIGN_TOP * @see #VERTICAL_ALIGN_MIDDLE * @see #VERTICAL_ALIGN_BOTTOM */ public function get scrollPositionVerticalAlign():String { return this._scrollPositionVerticalAlign; } /** * @private */ public function set scrollPositionVerticalAlign(value:String):void { this._scrollPositionVerticalAlign = value; } /** * @inheritDoc */ public function get requiresLayoutOnScroll():Boolean { return this._useVirtualLayout || this._manageVisibility; } /** * @inheritDoc */ public function layout(items:Vector.<DisplayObject>, viewPortBounds:ViewPortBounds = null, result:LayoutBoundsResult = null):LayoutBoundsResult { //this function is very long because it may be called every frame, //in some situations. testing revealed that splitting this function //into separate, smaller functions affected performance. //since the SWC compiler cannot inline functions, we can't use that //feature either. //since viewPortBounds can be null, we may need to provide some defaults var scrollX:Number = viewPortBounds ? viewPortBounds.scrollX : 0; var scrollY:Number = viewPortBounds ? viewPortBounds.scrollY : 0; var boundsX:Number = viewPortBounds ? viewPortBounds.x : 0; var boundsY:Number = viewPortBounds ? viewPortBounds.y : 0; var minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0; var minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0; var maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY; var maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY; var explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN; var explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN; if(this._useVirtualLayout) { //if the layout is virtualized, we'll need the dimensions of the //typical item so that we have fallback values when an item is null this.prepareTypicalItem(explicitWidth - this._paddingLeft - this._paddingRight); var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; } if(!this._useVirtualLayout || this._hasVariableItemDimensions || this._distributeHeights || this._horizontalAlign != HORIZONTAL_ALIGN_JUSTIFY || explicitWidth !== explicitWidth) //isNaN { //in some cases, we may need to validate all of the items so //that we can use their dimensions below. this.validateItems(items, explicitWidth - this._paddingLeft - this._paddingRight, minWidth - this._paddingLeft - this._paddingRight, maxWidth - this._paddingLeft - this._paddingRight, explicitHeight); } if(!this._useVirtualLayout) { //handle the percentHeight property from VerticalLayoutData, //if available. this.applyPercentHeights(items, explicitHeight, minHeight, maxHeight); } var distributedHeight:Number; if(this._distributeHeights) { //distribute the height evenly among all items distributedHeight = this.calculateDistributedHeight(items, explicitHeight, minHeight, maxHeight); } var hasDistributedHeight:Boolean = distributedHeight === distributedHeight; //!isNaN //this section prepares some variables needed for the following loop var hasFirstGap:Boolean = this._firstGap === this._firstGap; //!isNaN var hasLastGap:Boolean = this._lastGap === this._lastGap; //!isNaN var maxItemWidth:Number = this._useVirtualLayout ? calculatedTypicalItemWidth : 0; var positionY:Number = boundsY + this._paddingTop; var indexOffset:int = 0; var itemCount:int = items.length; var totalItemCount:int = itemCount; if(this._useVirtualLayout && !this._hasVariableItemDimensions) { //if the layout is virtualized, and the items all have the same //height, we can make our loops smaller by skipping some items //at the beginning and end. this improves performance. totalItemCount += this._beforeVirtualizedItemCount + this._afterVirtualizedItemCount; indexOffset = this._beforeVirtualizedItemCount; positionY += (this._beforeVirtualizedItemCount * (calculatedTypicalItemHeight + this._gap)); if(hasFirstGap && this._beforeVirtualizedItemCount > 0) { positionY = positionY - this._gap + this._firstGap; } } var secondToLastIndex:int = totalItemCount - 2; //this cache is used to save non-null items in virtual layouts. by //using a smaller array, we can improve performance by spending less //time in the upcoming loops. this._discoveredItemsCache.length = 0; var discoveredItemsCacheLastIndex:int = 0; //this first loop sets the y position of items, and it calculates //the total height of all items for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; //if we're trimming some items at the beginning, we need to //adjust i to account for the missing items in the array var iNormalized:int = i + indexOffset; //pick the gap that will follow this item. the first and second //to last items may have different gaps. var gap:Number = this._gap; if(hasFirstGap && iNormalized == 0) { gap = this._firstGap; } else if(hasLastGap && iNormalized > 0 && iNormalized == secondToLastIndex) { gap = this._lastGap; } if(this._useVirtualLayout && this._hasVariableItemDimensions) { var cachedHeight:Number = this._heightCache[iNormalized]; } if(this._useVirtualLayout && !item) { //the item is null, and the layout is virtualized, so we //need to estimate the height of the item. if(!this._hasVariableItemDimensions || cachedHeight !== cachedHeight) //isNaN { //if all items must have the same height, we will //use the height of the typical item (calculatedTypicalItemHeight). //if items may have different heights, we first check //the cache for a height value. if there isn't one, then //we'll use calculatedTypicalItemHeight as a fallback. positionY += calculatedTypicalItemHeight + gap; } else { //if we have variable item heights, we should use a //cached height when there's one available. it will be //more accurate than the typical item's height. positionY += cachedHeight + gap; } } else { //we get here if the item isn't null. it is never null if //the layout isn't virtualized. if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } item.y = item.pivotY + positionY; var itemWidth:Number = item.width; var itemHeight:Number; if(hasDistributedHeight) { item.height = itemHeight = distributedHeight; } else { itemHeight = item.height; } if(this._useVirtualLayout) { if(this._hasVariableItemDimensions) { if(itemHeight != cachedHeight) { //update the cache if needed. this will notify //the container that the virtualized layout has //changed, and it the view port may need to be //re-measured. this._heightCache[iNormalized] = itemHeight; //attempt to adjust the scroll position so that //it looks like we're scrolling smoothly after //this item resizes. if(positionY < scrollY && cachedHeight !== cachedHeight && //isNaN itemHeight != calculatedTypicalItemHeight) { this.dispatchEventWith(Event.SCROLL, false, new Point(0, itemHeight - calculatedTypicalItemHeight)); } this.dispatchEventWith(Event.CHANGE); } } else if(calculatedTypicalItemHeight >= 0) { //if all items must have the same height, we will //use the height of the typical item (calculatedTypicalItemHeight). item.height = itemHeight = calculatedTypicalItemHeight; } } positionY += itemHeight + gap; //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemWidth > maxItemWidth) { //we need to know the maximum width of the items in the //case where the width of the view port needs to be //calculated by the layout. maxItemWidth = itemWidth; } if(this._useVirtualLayout) { this._discoveredItemsCache[discoveredItemsCacheLastIndex] = item; discoveredItemsCacheLastIndex++; } } } if(this._useVirtualLayout && !this._hasVariableItemDimensions) { //finish the final calculation of the y position so that it can //be used for the total height of all items positionY += (this._afterVirtualizedItemCount * (calculatedTypicalItemHeight + this._gap)); if(hasLastGap && this._afterVirtualizedItemCount > 0) { positionY = positionY - this._gap + this._lastGap; } } //this array will contain all items that are not null. see the //comment above where the discoveredItemsCache is initialized for //details about why this is important. var discoveredItems:Vector.<DisplayObject> = this._useVirtualLayout ? this._discoveredItemsCache : items; var discoveredItemCount:int = discoveredItems.length; var totalWidth:Number = maxItemWidth + this._paddingLeft + this._paddingRight; //the available width is the width of the viewport. if the explicit //width is NaN, we need to calculate the viewport width ourselves //based on the total width of all items. var availableWidth:Number = explicitWidth; if(availableWidth !== availableWidth) //isNaN { availableWidth = totalWidth; if(availableWidth < minWidth) { availableWidth = minWidth; } else if(availableWidth > maxWidth) { availableWidth = maxWidth; } } //this is the total height of all items var totalHeight:Number = positionY - this._gap + this._paddingBottom - boundsY; //the available height is the height of the viewport. if the explicit //height is NaN, we need to calculate the viewport height ourselves //based on the total height of all items. var availableHeight:Number = explicitHeight; if(availableHeight !== availableHeight) //isNaN { availableHeight = totalHeight; if(this._requestedRowCount > 0) { availableHeight = this._requestedRowCount * (calculatedTypicalItemHeight + this._gap) - this._gap + this._paddingTop + this._paddingBottom; } else { availableHeight = totalHeight; } if(availableHeight < minHeight) { availableHeight = minHeight; } else if(availableHeight > maxHeight) { availableHeight = maxHeight; } } //in this section, we handle vertical alignment. items will be //aligned vertically if the total height of all items is less than //the available height of the view port. if(totalHeight < availableHeight) { var verticalAlignOffsetY:Number = 0; if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM) { verticalAlignOffsetY = availableHeight - totalHeight; } else if(this._verticalAlign == VERTICAL_ALIGN_MIDDLE) { verticalAlignOffsetY = Math.round((availableHeight - totalHeight) / 2); } if(verticalAlignOffsetY != 0) { for(i = 0; i < discoveredItemCount; i++) { item = discoveredItems[i]; if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } item.y += verticalAlignOffsetY; } } } for(i = 0; i < discoveredItemCount; i++) { item = discoveredItems[i]; var layoutItem:ILayoutDisplayObject = item as ILayoutDisplayObject; if(layoutItem && !layoutItem.includeInLayout) { continue; } //in this section, we handle horizontal alignment and percent //width from VerticalLayoutData if(this._horizontalAlign == HORIZONTAL_ALIGN_JUSTIFY) { //if we justify items horizontally, we can skip percent width item.x = item.pivotX + boundsX + this._paddingLeft; item.width = availableWidth - this._paddingLeft - this._paddingRight; } else { if(layoutItem) { var layoutData:VerticalLayoutData = layoutItem.layoutData as VerticalLayoutData; if(layoutData) { //in this section, we handle percentage width if //VerticalLayoutData is available. var percentWidth:Number = layoutData.percentWidth; if(percentWidth === percentWidth) //!isNaN { if(percentWidth < 0) { percentWidth = 0; } if(percentWidth > 100) { percentWidth = 100; } itemWidth = percentWidth * (availableWidth - this._paddingLeft - this._paddingRight) / 100; if(item is IFeathersControl) { var feathersItem:IFeathersControl = IFeathersControl(item); var itemMinWidth:Number = feathersItem.minWidth; if(itemWidth < itemMinWidth) { itemWidth = itemMinWidth; } else { var itemMaxWidth:Number = feathersItem.maxWidth; if(itemWidth > itemMaxWidth) { itemWidth = itemMaxWidth; } } } item.width = itemWidth; } } } //handle all other horizontal alignment values (we handled //justify already). the x position of all items is set. switch(this._horizontalAlign) { case HORIZONTAL_ALIGN_RIGHT: { item.x = item.pivotX + boundsX + availableWidth - this._paddingRight - item.width; break; } case HORIZONTAL_ALIGN_CENTER: { //round to the nearest pixel when dividing by 2 to //align in the center item.x = item.pivotX + boundsX + this._paddingLeft + Math.round((availableWidth - this._paddingLeft - this._paddingRight - item.width) / 2); break; } default: //left { item.x = item.pivotX + boundsX + this._paddingLeft; } } } if(this._manageVisibility) { item.visible = ((item.y - item.pivotY + item.height) >= (boundsY + scrollY)) && ((item.y - item.pivotY) < (scrollY + availableHeight)); } } //we don't want to keep a reference to any of the items, so clear //this cache this._discoveredItemsCache.length = 0; //finally, we want to calculate the result so that the container //can use it to adjust its viewport and determine the minimum and //maximum scroll positions (if needed) if(!result) { result = new LayoutBoundsResult(); } result.contentX = 0; result.contentWidth = this._horizontalAlign == HORIZONTAL_ALIGN_JUSTIFY ? availableWidth : totalWidth; result.contentY = 0; result.contentHeight = totalHeight; result.viewPortWidth = availableWidth; result.viewPortHeight = availableHeight; return result; } /** * @inheritDoc */ public function measureViewPort(itemCount:int, viewPortBounds:ViewPortBounds = null, result:Point = null):Point { if(!result) { result = new Point(); } if(!this._useVirtualLayout) { throw new IllegalOperationError("measureViewPort() may be called only if useVirtualLayout is true.") } var explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN; var explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN; var needsWidth:Boolean = explicitWidth !== explicitWidth; //isNaN var needsHeight:Boolean = explicitHeight !== explicitHeight; //isNaN if(!needsWidth && !needsHeight) { result.x = explicitWidth; result.y = explicitHeight; return result; } var minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0; var minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0; var maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY; var maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY; this.prepareTypicalItem(explicitWidth - this._paddingLeft - this._paddingRight); var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; var hasFirstGap:Boolean = this._firstGap === this._firstGap; //!isNaN var hasLastGap:Boolean = this._lastGap === this._lastGap; //!isNaN var positionY:Number; if(this._distributeHeights) { positionY = (calculatedTypicalItemHeight + this._gap) * itemCount; } else { positionY = 0; var maxItemWidth:Number = calculatedTypicalItemWidth; if(!this._hasVariableItemDimensions) { positionY += ((calculatedTypicalItemHeight + this._gap) * itemCount); } else { for(var i:int = 0; i < itemCount; i++) { var cachedHeight:Number = this._heightCache[i]; if(cachedHeight !== cachedHeight) //isNaN { positionY += calculatedTypicalItemHeight + this._gap; } else { positionY += cachedHeight + this._gap; } } } } positionY -= this._gap; if(hasFirstGap && itemCount > 1) { positionY = positionY - this._gap + this._firstGap; } if(hasLastGap && itemCount > 2) { positionY = positionY - this._gap + this._lastGap; } if(needsWidth) { var resultWidth:Number = maxItemWidth + this._paddingLeft + this._paddingRight; if(resultWidth < minWidth) { resultWidth = minWidth; } else if(resultWidth > maxWidth) { resultWidth = maxWidth; } result.x = resultWidth; } else { result.x = explicitWidth; } if(needsHeight) { if(this._requestedRowCount > 0) { var resultHeight:Number = (calculatedTypicalItemHeight + this._gap) * this._requestedRowCount - this._gap; } else { resultHeight = positionY; } resultHeight += this._paddingTop + this._paddingBottom; if(resultHeight < minHeight) { resultHeight = minHeight; } else if(resultHeight > maxHeight) { resultHeight = maxHeight; } result.y = resultHeight; } else { result.y = explicitHeight; } return result; } /** * @inheritDoc */ public function resetVariableVirtualCache():void { this._heightCache.length = 0; } /** * @inheritDoc */ public function resetVariableVirtualCacheAtIndex(index:int, item:DisplayObject = null):void { delete this._heightCache[index]; if(item) { this._heightCache[index] = item.height; this.dispatchEventWith(Event.CHANGE); } } /** * @inheritDoc */ public function addToVariableVirtualCacheAtIndex(index:int, item:DisplayObject = null):void { var heightValue:* = item ? item.height : undefined; this._heightCache.splice(index, 0, heightValue); } /** * @inheritDoc */ public function removeFromVariableVirtualCacheAtIndex(index:int):void { this._heightCache.splice(index, 1); } /** * @inheritDoc */ public function getVisibleIndicesAtScrollPosition(scrollX:Number, scrollY:Number, width:Number, height:Number, itemCount:int, result:Vector.<int> = null):Vector.<int> { if(result) { result.length = 0; } else { result = new <int>[]; } if(!this._useVirtualLayout) { throw new IllegalOperationError("getVisibleIndicesAtScrollPosition() may be called only if useVirtualLayout is true.") } this.prepareTypicalItem(width - this._paddingLeft - this._paddingRight); var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; var hasFirstGap:Boolean = this._firstGap === this._firstGap; //!isNaN var hasLastGap:Boolean = this._lastGap === this._lastGap; //!isNaN var resultLastIndex:int = 0; //we add one extra here because the first item renderer in view may //be partially obscured, which would reveal an extra item renderer. var maxVisibleTypicalItemCount:int = Math.ceil(height / (calculatedTypicalItemHeight + this._gap)) + 1; if(!this._hasVariableItemDimensions) { //this case can be optimized because we know that every item has //the same height var totalItemHeight:Number = itemCount * (calculatedTypicalItemHeight + this._gap) - this._gap; if(hasFirstGap && itemCount > 1) { totalItemHeight = totalItemHeight - this._gap + this._firstGap; } if(hasLastGap && itemCount > 2) { totalItemHeight = totalItemHeight - this._gap + this._lastGap; } var indexOffset:int = 0; if(totalItemHeight < height) { if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM) { indexOffset = Math.ceil((height - totalItemHeight) / (calculatedTypicalItemHeight + this._gap)); } else if(this._verticalAlign == VERTICAL_ALIGN_MIDDLE) { indexOffset = Math.ceil(((height - totalItemHeight) / (calculatedTypicalItemHeight + this._gap)) / 2); } } var minimum:int = (scrollY - this._paddingTop) / (calculatedTypicalItemHeight + this._gap); if(minimum < 0) { minimum = 0; } minimum -= indexOffset; //if we're scrolling beyond the final item, we should keep the //indices consistent so that items aren't destroyed and //recreated unnecessarily var maximum:int = minimum + maxVisibleTypicalItemCount; if(maximum >= itemCount) { maximum = itemCount - 1; } minimum = maximum - maxVisibleTypicalItemCount; if(minimum < 0) { minimum = 0; } for(var i:int = minimum; i <= maximum; i++) { if(i >= 0 && i < itemCount) { result[resultLastIndex] = i; } else if(i < 0) { result[resultLastIndex] = itemCount + i; } else if(i >= itemCount) { result[resultLastIndex] = i - itemCount; } resultLastIndex++; } return result; } var secondToLastIndex:int = itemCount - 2; var maxPositionY:Number = scrollY + height; var positionY:Number = this._paddingTop; for(i = 0; i < itemCount; i++) { var gap:Number = this._gap; if(hasFirstGap && i == 0) { gap = this._firstGap; } else if(hasLastGap && i > 0 && i == secondToLastIndex) { gap = this._lastGap; } var cachedHeight:Number = this._heightCache[i]; if(cachedHeight !== cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } var oldPositionY:Number = positionY; positionY += itemHeight + gap; if(positionY > scrollY && oldPositionY < maxPositionY) { result[resultLastIndex] = i; resultLastIndex++; } if(positionY >= maxPositionY) { break; } } //similar to above, in order to avoid costly destruction and //creation of item renderers, we're going to fill in some extra //indices var resultLength:int = result.length; var visibleItemCountDifference:int = maxVisibleTypicalItemCount - resultLength; if(visibleItemCountDifference > 0 && resultLength > 0) { //add extra items before the first index var firstExistingIndex:int = result[0]; var lastIndexToAdd:int = firstExistingIndex - visibleItemCountDifference; if(lastIndexToAdd < 0) { lastIndexToAdd = 0; } for(i = firstExistingIndex - 1; i >= lastIndexToAdd; i--) { result.unshift(i); } } resultLength = result.length; visibleItemCountDifference = maxVisibleTypicalItemCount - resultLength; resultLastIndex = resultLength; if(visibleItemCountDifference > 0) { //add extra items after the last index var startIndex:int = (resultLength > 0) ? (result[resultLength - 1] + 1) : 0; var endIndex:int = startIndex + visibleItemCountDifference; if(endIndex > itemCount) { endIndex = itemCount; } for(i = startIndex; i < endIndex; i++) { result[resultLastIndex] = i; resultLastIndex++; } } return result; } /** * @inheritDoc */ public function getNearestScrollPositionForIndex(index:int, scrollX:Number, scrollY:Number, items:Vector.<DisplayObject>, x:Number, y:Number, width:Number, height:Number, result:Point = null):Point { var maxScrollY:Number = this.calculateMaxScrollYOfIndex(index, items, x, y, width, height); if(this._useVirtualLayout) { if(this._hasVariableItemDimensions) { var itemHeight:Number = this._heightCache[index]; if(itemHeight !== itemHeight) //isNaN { itemHeight = this._typicalItem.height; } } else { itemHeight = this._typicalItem.height; } } else { itemHeight = items[index].height; } if(!result) { result = new Point(); } result.x = 0; var bottomPosition:Number = maxScrollY - (height - itemHeight); if(scrollY >= bottomPosition && scrollY <= maxScrollY) { //keep the current scroll position because the item is already //fully visible result.y = scrollY; } else { var topDifference:Number = Math.abs(maxScrollY - scrollY); var bottomDifference:Number = Math.abs(bottomPosition - scrollY); if(bottomDifference < topDifference) { result.y = bottomPosition; } else { result.y = maxScrollY; } } return result; } /** * @inheritDoc */ public function getScrollPositionForIndex(index:int, items:Vector.<DisplayObject>, x:Number, y:Number, width:Number, height:Number, result:Point = null):Point { var maxScrollY:Number = this.calculateMaxScrollYOfIndex(index, items, x, y, width, height); if(this._useVirtualLayout) { if(this._hasVariableItemDimensions) { var itemHeight:Number = this._heightCache[index]; if(itemHeight !== itemHeight) //isNaN { itemHeight = this._typicalItem.height; } } else { itemHeight = this._typicalItem.height; } } else { itemHeight = items[index].height; } if(!result) { result = new Point(); } result.x = 0; if(this._scrollPositionVerticalAlign == VERTICAL_ALIGN_MIDDLE) { maxScrollY -= Math.round((height - itemHeight) / 2); } else if(this._scrollPositionVerticalAlign == VERTICAL_ALIGN_BOTTOM) { maxScrollY -= (height - itemHeight); } result.y = maxScrollY; return result; } /** * @private */ protected function validateItems(items:Vector.<DisplayObject>, explicitWidth:Number, minWidth:Number, maxWidth:Number, distributedHeight:Number):void { //if the alignment is justified, then we want to set the width of //each item before validating because setting one dimension may //cause the other dimension to change, and that will invalidate the //layout if it happens after validation, causing more invalidation var isJustified:Boolean = this._horizontalAlign == HORIZONTAL_ALIGN_JUSTIFY; var itemCount:int = items.length; for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; if(!item || (item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout)) { continue; } if(isJustified) { //the alignment is justified, but we don't yet have a width //to use, so we need to ensure that we accurately measure //the items instead of using an old justified width that may //be wrong now! item.width = explicitWidth; if(item is IFeathersControl) { var feathersItem:IFeathersControl = IFeathersControl(item); feathersItem.minWidth = minWidth; feathersItem.maxWidth = maxWidth; } } if(this._distributeHeights) { item.height = distributedHeight; } if(item is IValidating) { IValidating(item).validate() } } } /** * @private */ protected function prepareTypicalItem(justifyWidth:Number):void { if(!this._typicalItem) { return; } if(this._horizontalAlign == HORIZONTAL_ALIGN_JUSTIFY && justifyWidth === justifyWidth) //!isNaN { this._typicalItem.width = justifyWidth; } else if(this._resetTypicalItemDimensionsOnMeasure) { this._typicalItem.width = this._typicalItemWidth; } if(this._resetTypicalItemDimensionsOnMeasure) { this._typicalItem.height = this._typicalItemHeight; } if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } } /** * @private */ protected function calculateDistributedHeight(items:Vector.<DisplayObject>, explicitHeight:Number, minHeight:Number, maxHeight:Number):Number { var itemCount:int = items.length; if(explicitHeight !== explicitHeight) //isNaN { var maxItemHeight:Number = 0; for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; var itemHeight:Number = item.height; if(itemHeight > maxItemHeight) { maxItemHeight = itemHeight; } } explicitHeight = maxItemHeight * itemCount + this._paddingTop + this._paddingBottom + this._gap * (itemCount - 1); var needsRecalculation:Boolean = false; if(explicitHeight > maxHeight) { explicitHeight = maxHeight; needsRecalculation = true; } else if(explicitHeight < minHeight) { explicitHeight = minHeight; needsRecalculation = true; } if(!needsRecalculation) { return maxItemHeight; } } var availableSpace:Number = explicitHeight - this._paddingTop - this._paddingBottom - this._gap * (itemCount - 1); if(itemCount > 1 && this._firstGap === this._firstGap) //!isNaN { availableSpace += this._gap - this._firstGap; } if(itemCount > 2 && this._lastGap === this._lastGap) //!isNaN { availableSpace += this._gap - this._lastGap; } return availableSpace / itemCount; } /** * @private */ protected function applyPercentHeights(items:Vector.<DisplayObject>, explicitHeight:Number, minHeight:Number, maxHeight:Number):void { var remainingHeight:Number = explicitHeight; this._discoveredItemsCache.length = 0; var totalExplicitHeight:Number = 0; var totalMinHeight:Number = 0; var totalPercentHeight:Number = 0; var itemCount:int = items.length; var pushIndex:int = 0; for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; if(item is ILayoutDisplayObject) { var layoutItem:ILayoutDisplayObject = ILayoutDisplayObject(item); if(!layoutItem.includeInLayout) { continue; } var layoutData:VerticalLayoutData = layoutItem.layoutData as VerticalLayoutData; if(layoutData) { var percentHeight:Number = layoutData.percentHeight; if(percentHeight === percentHeight) //!isNaN { if(layoutItem is IFeathersControl) { var feathersItem:IFeathersControl = IFeathersControl(layoutItem); totalMinHeight += feathersItem.minHeight; } totalPercentHeight += percentHeight; this._discoveredItemsCache[pushIndex] = item; pushIndex++; continue; } } } totalExplicitHeight += item.height; } totalExplicitHeight += this._gap * (itemCount - 1); if(this._firstGap === this._firstGap && itemCount > 1) { totalExplicitHeight += (this._firstGap - this._gap); } else if(this._lastGap === this._lastGap && itemCount > 2) { totalExplicitHeight += (this._lastGap - this._gap); } totalExplicitHeight += this._paddingTop + this._paddingBottom; if(totalPercentHeight < 100) { totalPercentHeight = 100; } if(remainingHeight !== remainingHeight) //isNaN { remainingHeight = totalExplicitHeight + totalMinHeight; if(remainingHeight < minHeight) { remainingHeight = minHeight; } else if(remainingHeight > maxHeight) { remainingHeight = maxHeight; } } remainingHeight -= totalExplicitHeight; if(remainingHeight < 0) { remainingHeight = 0; } do { var needsAnotherPass:Boolean = false; var percentToPixels:Number = remainingHeight / totalPercentHeight; for(i = 0; i < pushIndex; i++) { layoutItem = ILayoutDisplayObject(this._discoveredItemsCache[i]); if(!layoutItem) { continue; } layoutData = VerticalLayoutData(layoutItem.layoutData); percentHeight = layoutData.percentHeight; var itemHeight:Number = percentToPixels * percentHeight; if(layoutItem is IFeathersControl) { feathersItem = IFeathersControl(layoutItem); var itemMinHeight:Number = feathersItem.minHeight; if(itemHeight < itemMinHeight) { itemHeight = itemMinHeight; remainingHeight -= itemHeight; totalPercentHeight -= percentHeight; this._discoveredItemsCache[i] = null; needsAnotherPass = true; } else { var itemMaxHeight:Number = feathersItem.maxHeight; if(itemHeight > itemMaxHeight) { itemHeight = itemMaxHeight; remainingHeight -= itemHeight; totalPercentHeight -= percentHeight; this._discoveredItemsCache[i] = null; needsAnotherPass = true; } } } layoutItem.height = itemHeight; } } while(needsAnotherPass) this._discoveredItemsCache.length = 0; } /** * @private */ protected function calculateMaxScrollYOfIndex(index:int, items:Vector.<DisplayObject>, x:Number, y:Number, width:Number, height:Number):Number { if(this._useVirtualLayout) { this.prepareTypicalItem(width - this._paddingLeft - this._paddingRight); var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; } var hasFirstGap:Boolean = this._firstGap === this._firstGap; //!isNaN var hasLastGap:Boolean = this._lastGap === this._lastGap; //!isNaN var positionY:Number = y + this._paddingTop; var lastHeight:Number = 0; var gap:Number = this._gap; var startIndexOffset:int = 0; var endIndexOffset:Number = 0; var itemCount:int = items.length; var totalItemCount:int = itemCount; if(this._useVirtualLayout && !this._hasVariableItemDimensions) { totalItemCount += this._beforeVirtualizedItemCount + this._afterVirtualizedItemCount; if(index < this._beforeVirtualizedItemCount) { //this makes it skip the loop below startIndexOffset = index + 1; lastHeight = calculatedTypicalItemHeight; gap = this._gap; } else { startIndexOffset = this._beforeVirtualizedItemCount; endIndexOffset = index - items.length - this._beforeVirtualizedItemCount + 1; if(endIndexOffset < 0) { endIndexOffset = 0; } positionY += (endIndexOffset * (calculatedTypicalItemHeight + this._gap)); } positionY += (startIndexOffset * (calculatedTypicalItemHeight + this._gap)); } index -= (startIndexOffset + endIndexOffset); var secondToLastIndex:int = totalItemCount - 2; for(var i:int = 0; i <= index; i++) { var item:DisplayObject = items[i]; var iNormalized:int = i + startIndexOffset; if(hasFirstGap && iNormalized == 0) { gap = this._firstGap; } else if(hasLastGap && iNormalized > 0 && iNormalized == secondToLastIndex) { gap = this._lastGap; } else { gap = this._gap; } if(this._useVirtualLayout && this._hasVariableItemDimensions) { var cachedHeight:Number = this._heightCache[iNormalized]; } if(this._useVirtualLayout && !item) { if(!this._hasVariableItemDimensions || cachedHeight !== cachedHeight) //isNaN { lastHeight = calculatedTypicalItemHeight; } else { lastHeight = cachedHeight; } } else { var itemHeight:Number = item.height; if(this._useVirtualLayout) { if(this._hasVariableItemDimensions) { if(itemHeight != cachedHeight) { this._heightCache[iNormalized] = itemHeight; this.dispatchEventWith(Event.CHANGE); } } else if(calculatedTypicalItemHeight >= 0) { item.height = itemHeight = calculatedTypicalItemHeight; } } lastHeight = itemHeight; } positionY += lastHeight + gap; } positionY -= (lastHeight + gap); return positionY; } } }
package kabam.rotmg.SkillTree.images.smallSkills { import mx.core.BitmapAsset; [Embed(source="SmallDefSkill.png")] public class SmallDefSkill extends BitmapAsset { public function SmallDefSkill() { super(); } } }
package feathers.tests { import feathers.controls.Button; import feathers.controls.ButtonGroup; import feathers.controls.ToggleButton; import feathers.data.ListCollection; import flash.geom.Point; import org.flexunit.Assert; import org.flexunit.async.Async; import starling.display.DisplayObject; import starling.display.Quad; import starling.events.Event; import starling.events.Touch; import starling.events.TouchEvent; import starling.events.TouchPhase; public class ButtonGroupDataProviderEventsTests { private var _group:ButtonGroup; [Before] public function prepare():void { this._group = new ButtonGroup(); this._group.direction = ButtonGroup.DIRECTION_VERTICAL; TestFeathers.starlingRoot.addChild(this._group); } [After] public function cleanup():void { this._group.removeFromParent(true); this._group = null; Assert.assertStrictlyEquals("Child not removed from Starling root on cleanup.", 0, TestFeathers.starlingRoot.numChildren); } [Test] public function testTriggeredEventInDataProvider():void { var triggeredItem:Object; var hasTriggered:Boolean = false; function triggeredListener(event:Event, data:Object, item:Object):void { hasTriggered = true; triggeredItem = item; } this._group.dataProvider = new ListCollection( [ { label: "One" }, { label: "Two", triggered: triggeredListener }, { label: "Three" }, ]); this._group.buttonFactory = function():Button { var button:Button = new Button(); button.defaultSkin = new Quad(200, 200); return button; } this._group.validate(); var position:Point = new Point(10, 210); var target:DisplayObject = this._group.stage.hitTest(position, true); var touch:Touch = new Touch(0); touch.target = target; touch.phase = TouchPhase.BEGAN; touch.globalX = position.x; touch.globalY = position.y; var touches:Vector.<Touch> = new <Touch>[touch]; target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches)); //this touch does not move at all, so it should result in triggering //the button. touch.phase = TouchPhase.ENDED; target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches)); Assert.assertTrue("Event.TRIGGERED was not dispatched to listener in data provider", hasTriggered); Assert.assertStrictlyEquals("Event.TRIGGERED was not dispatched with correct item to listener in data provider", this._group.dataProvider.getItemAt(1), triggeredItem); } [Test] public function testChangeEventInDataProvider():void { var changedItem:Object; var hasChanged:Boolean = false; function changeListener(event:Event, data:Object, item:Object):void { hasChanged = true; changedItem = item; } this._group.dataProvider = new ListCollection( [ { label: "One" }, { label: "Two", change: changeListener }, { label: "Three" }, ]); this._group.buttonFactory = function():ToggleButton { var button:ToggleButton = new ToggleButton(); button.defaultSkin = new Quad(200, 200); return button; } this._group.validate(); var position:Point = new Point(10, 210); var target:DisplayObject = this._group.stage.hitTest(position, true); var touch:Touch = new Touch(0); touch.target = target; touch.phase = TouchPhase.BEGAN; touch.globalX = position.x; touch.globalY = position.y; var touches:Vector.<Touch> = new <Touch>[touch]; target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches)); //this touch does not move at all, so it should result in triggering //the button. touch.phase = TouchPhase.ENDED; target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches)); Assert.assertTrue("Event.CHANGE was not dispatched to listener in data provider", hasChanged); Assert.assertStrictlyEquals("Event.CHANGE was not dispatched with correct item to listener in data provider", this._group.dataProvider.getItemAt(1), changedItem); } [Test(async)] public function testLongPressEventInDataProvider():void { var longPressItem:Object; var hasLongPressed:Boolean = false; function longPressListener(event:Event, data:Object, item:Object):void { hasLongPressed = true; longPressItem = item; } this._group.dataProvider = new ListCollection( [ { label: "One" }, { label: "Two", isLongPressEnabled: true, longPress: longPressListener }, { label: "Three" }, ]); this._group.buttonFactory = function():ToggleButton { var button:ToggleButton = new ToggleButton(); button.defaultSkin = new Quad(200, 200); return button; } this._group.validate(); var position:Point = new Point(10, 210); var target:DisplayObject = this._group.stage.hitTest(position, true); var touch:Touch = new Touch(0); touch.target = target; touch.phase = TouchPhase.BEGAN; touch.globalX = 10; touch.globalY = 210; var touches:Vector.<Touch> = new <Touch>[touch]; target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches)); Async.delayCall(this, function():void { Assert.assertTrue("FeathersEventType.LONG_PRESS was not dispatched to listener in data provider", hasLongPressed); Assert.assertStrictlyEquals("Event.CHANGE was not dispatched with correct item to listener in data provider", _group.dataProvider.getItemAt(1), longPressItem); }, 600); } } }
package com.company.assembleegameclient.objects.particles { import com.company.assembleegameclient.objects.GameObject; import com.company.assembleegameclient.objects.thrown.BitmapParticle; import flash.display.BitmapData; import kabam.lib.math.easing.Quad; public class HolyBeamParticle extends BitmapParticle { public function HolyBeamParticle(param1:GameObject, param2:Vector.<BitmapData>, param3:Number, param4:int) { this.go = param1; this.images = param2; this.percentDone = 0; this.currentTime = 0; this.lifeTimeMS = param4; super(param2[0], param3); this.startZ = param3; z_ = this.startZ; _rotation = 0; this.percentDone = 0; } private var percentDone:Number; private var startZ:Number; private var lifeTimeMS:int; private var currentTime:int; private var go:GameObject; private var images:Vector.<BitmapData>; override public function update(param1:int, param2:int):Boolean { this.percentDone = this.currentTime / this.lifeTimeMS; var _loc3_:int = 0; _loc3_ = Math.min(Math.max(0, Math.floor(this.images.length * Quad.easeOut(this.percentDone))), this.images.length - 1); _bitmapData = this.images[_loc3_]; y_ = this.go.y_; x_ = this.go.x_; this.currentTime = this.currentTime + param2; return this.percentDone < 1; } } }
package feathers.tests { import feathers.controls.Label; import feathers.tests.supportClasses.DisposeFlagQuad; import org.flexunit.Assert; public class LabelTests { protected var label:Label; [Before] public function prepare():void { this.label = new Label(); TestFeathers.starlingRoot.addChild(this.label); } [After] public function cleanup():void { this.label.removeFromParent(true); this.label = null; Assert.assertStrictlyEquals("Child not removed from Starling root on cleanup.", 0, TestFeathers.starlingRoot.numChildren); } [Test] public function testSkinsDisposed():void { var backgroundSkin:DisposeFlagQuad = new DisposeFlagQuad(); this.label.backgroundSkin = backgroundSkin; var backgroundDisabledSkin:DisposeFlagQuad = new DisposeFlagQuad(); this.label.backgroundDisabledSkin = backgroundDisabledSkin; this.label.validate(); this.label.dispose(); Assert.assertTrue("backgroundSkin not disposed when Label disposed.", backgroundSkin.isDisposed); Assert.assertTrue("backgroundDisabledSkin not disposed when Label disposed.", backgroundDisabledSkin.isDisposed); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.royale.core { import org.apache.royale.events.Event; import org.apache.royale.events.ValueEvent; /** * Indicates that the state change has completed. All properties * that need to change have been changed, and all transitinos * that need to run have completed. However, any deferred work * may not be completed, and the screen may not be updated until * code stops executing. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ [Event(name="stateChangeComplete", type="org.apache.royale.events.Event")] /** * Indicates that the initialization of the container is complete. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ [Event(name="initComplete", type="org.apache.royale.events.Event")] /** * Indicates that the children of the container is have been added. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ [Event(name="childrenAdded", type="org.apache.royale.events.Event")] /** * The ContainerBase class is the base class for most containers * in Royale. It is usable as the root tag of MXML * documents and UI controls and containers are added to it. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public class ContainerBase extends GroupBase implements IContainerBaseStrandChildrenHost { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public function ContainerBase() { super(); } private var _strandChildren:ContainerBaseStrandChildren; /** * @private */ override public function get strandChildren():IParent { if (_strandChildren == null) { _strandChildren = new ContainerBaseStrandChildren(this); } return _strandChildren; } /* * The following functions are for the SWF-side only and re-direct element functions * to the content area, enabling scrolling and clipping which are provided automatically * in the JS-side. GroupBase handles event dispatching if necessary. */ /** * @private */ COMPILE::SWF override public function addElement(c:IChild, dispatchEvent:Boolean = true):void { var contentView:IParent = getLayoutHost().contentView as IParent; contentView.addElement(c, dispatchEvent); if (dispatchEvent) this.dispatchEvent(new ValueEvent("childrenAdded", c)); } /** * @private */ COMPILE::SWF override public function addElementAt(c:IChild, index:int, dispatchEvent:Boolean = true):void { var contentView:IParent = getLayoutHost().contentView as IParent; contentView.addElementAt(c, index, dispatchEvent); if (dispatchEvent) this.dispatchEvent(new ValueEvent("childrenAdded", c)); } /** * @private */ COMPILE::SWF override public function getElementIndex(c:IChild):int { var layoutHost:ILayoutHost = view as ILayoutHost; var contentView:IParent = layoutHost.contentView as IParent; return contentView.getElementIndex(c); } /** * @private */ COMPILE::SWF override public function removeElement(c:IChild, dispatchEvent:Boolean = true):void { var layoutHost:ILayoutHost = view as ILayoutHost; var contentView:IParent = layoutHost.contentView as IParent; contentView.removeElement(c, dispatchEvent); //TODO This should possibly be ultimately refactored to be more PAYG if(dispatchEvent) this.dispatchEvent(new ValueEvent("childrenRemoved", c)); } /** * @private */ COMPILE::SWF override public function get numElements():int { var layoutHost:ILayoutHost = view as ILayoutHost; var contentView:IParent = layoutHost.contentView as IParent; return contentView.numElements; } /** * @private */ COMPILE::SWF override public function getElementAt(index:int):IChild { var layoutHost:ILayoutHost = view as ILayoutHost; var contentView:IParent = layoutHost.contentView as IParent; return contentView.getElementAt(index); } /* * IStrandPrivate * * These "internal" function provide a backdoor way for proxy classes to * operate directly at strand level. While these function are available on * both SWF and JS platforms, they really only have meaning on the SWF-side. * Other subclasses may provide use on the JS-side. * * @see org.apache.royale.core.IContainer#strandChildren */ /** * @private * @suppress {undefinedNames} * Support strandChildren. */ public function get $numElements():int { return super.numElements; } /** * @private * @suppress {undefinedNames} * Support strandChildren. */ public function $addElement(c:IChild, dispatchEvent:Boolean = true):void { super.addElement(c, dispatchEvent); } /** * @private * @suppress {undefinedNames} * Support strandChildren. */ public function $addElementAt(c:IChild, index:int, dispatchEvent:Boolean = true):void { super.addElementAt(c, index, dispatchEvent); } /** * @private * @suppress {undefinedNames} * Support strandChildren. */ public function $removeElement(c:IChild, dispatchEvent:Boolean = true):void { super.removeElement(c, dispatchEvent); } /** * @private * @suppress {undefinedNames} * Support strandChildren. */ public function $getElementIndex(c:IChild):int { return super.getElementIndex(c); } /** * @private * @suppress {undefinedNames} * Support strandChildren. */ public function $getElementAt(index:int):IChild { return super.getElementAt(index); } } }
/* See LICENSE for copyright and terms of use */ import org.actionstep.asml.ASAsmlReader; import org.actionstep.asml.ASParsingUtils; import org.actionstep.asml.ASReferenceProperty; import org.actionstep.asml.ASTagHandler; import org.actionstep.NSObject; /** * <p>This class handles <code>instance</code> tags from the ASML file.</p> * * <p>An instance tag intantiates an instance of a class as specified by the * <code>instanceOf</code> attribute on the tag. This is generally used for * creating controller objects that will talk with views.</p> * * <p>To create a view of an undetermined class, the <code>view</code> tag is * typically used.</p> * * @author Scott Hyndman */ class org.actionstep.asml.ASInstanceTagHandler extends NSObject implements ASTagHandler { private var m_reader:ASAsmlReader; /** * <p>Constructs a new instance of <code>ASInstanceTagHandler</code>.</p> * * <p><code>reader</code> is the {@link ASAsmlReader} using this tag * handler.</p> */ public function ASInstanceTagHandler(reader:ASAsmlReader) { m_reader = reader; } /** * Does nothing. Instances aren't a member of any hierarchy. */ public function addChildToParent(child:NSObject, parent:NSObject, remainingChildAttributes:Object):Void { } /** * // TODO Describes steps taken here. */ public function parseNodeWithClassName(node:XMLNode, className:String) :Object { var atts:Object = node.attributes; // // Store for exception // var clsName:String = atts.instanceOf == null ? className : atts.instanceOf; // // Get view instance // var instance:Object = ASParsingUtils.createInstanceWithClassNameAttributes(className, atts); initializeObject(instance); // // Apply remaining properties. // var refs:Array = ASParsingUtils.applyPropertiesToObjectWithAttributes( instance, atts); // // Set the owner for all the reference properties and add them to the // reader. // var len:Number = refs.length; for (var i:Number = 0; i < len; i++) { ASReferenceProperty(refs[i]).setOwner(instance); m_reader.addReferenceProperty(ASReferenceProperty(refs[i])); } return instance; } /** * Override to provide more specific functionality. */ private function initializeObject(obj:Object, node:XMLNode):Void { } }
/* Copyright 2012-2015 Bowler Hat LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package feathers.themes { import flash.geom.Rectangle; import flash.text.TextFormat; import flash.text.TextFormatAlign; import flash.utils.ByteArray; import feathers.Feather; import feathers.controls.Button; import feathers.controls.ButtonGroup; import feathers.controls.ButtonState; import feathers.controls.Callout; import feathers.controls.Drawers; import feathers.controls.IScrollBar; import feathers.controls.ImageLoader; import feathers.controls.Label; import feathers.controls.LayoutGroup; import feathers.controls.ProgressBar; import feathers.controls.Radio; import feathers.controls.ScrollBar; import feathers.controls.ScrollBarDisplayMode; import feathers.controls.ScrollContainer; import feathers.controls.ScrollInteractionMode; import feathers.controls.ScrollScreen; import feathers.controls.ScrollText; import feathers.controls.Scroller; import feathers.controls.SimpleScrollBar; import feathers.controls.TextArea; import feathers.controls.TextCallout; import feathers.controls.TextInput; import feathers.controls.ToggleButton; import feathers.controls.ToggleSwitch; import feathers.controls.TrackLayoutMode; import feathers.controls.renderers.BaseDefaultItemRenderer; import feathers.controls.renderers.DefaultGroupedListItemRenderer; import feathers.controls.renderers.DefaultListItemRenderer; import feathers.controls.text.TextFieldTextEditor; import feathers.controls.text.TextFieldTextEditorViewPort; import feathers.controls.text.TextFieldTextRenderer; import feathers.core.FeathersControl; import feathers.core.FocusManager; import feathers.core.ITextEditor; import feathers.core.ITextRenderer; import feathers.core.PopUpManager; import feathers.core.ToolTipManager; import feathers.layout.Direction; import feathers.layout.HorizontalAlign; import feathers.layout.HorizontalLayout; import feathers.layout.RelativePosition; import feathers.layout.VerticalAlign; import feathers.skins.ImageSkin; import starling.core.Starling; import starling.display.DisplayObject; import starling.display.Image; import starling.display.Quad; import starling.display.Stage; import starling.textures.Texture; import starling.textures.TextureAtlas; /** * The base class for the "Aeon" theme for desktop Feathers apps. Handles * everything except asset loading, which is left to subclasses. * * @see AeonDesktopTheme * @see AeonDesktopThemeWithAssetManager */ public class GameAeonTheme extends StyleNameFunctionTheme { /** * @private */ [Embed( source = "../../../assets/aeon_desktop.jpeg", mimeType = "application/octet-stream" )] protected static const ATLAS_BITMAP : Class; /** * @private */ [Embed( source = "../../../assets/aeon_desktop.xml", mimeType = "application/octet-stream" )] protected static const ATLAS_XML : Class; /** * @private */ protected static const ATLAS_SCALE_FACTOR : int = 2; /** * @private * The theme's custom style name for the increment button of a horizontal ScrollBar. */ protected static const THEME_STYLE_NAME_HORIZONTAL_SCROLL_BAR_INCREMENT_BUTTON : String = "aeon-horizontal-scroll-bar-increment-button"; /** * @private * The theme's custom style name for the decrement button of a horizontal ScrollBar. */ protected static const THEME_STYLE_NAME_HORIZONTAL_SCROLL_BAR_DECREMENT_BUTTON : String = "aeon-horizontal-scroll-bar-decrement-button"; /** * @private * The theme's custom style name for the thumb of a horizontal ScrollBar. */ protected static const THEME_STYLE_NAME_HORIZONTAL_SCROLL_BAR_THUMB : String = "aeon-horizontal-scroll-bar-thumb"; /** * @private * The theme's custom style name for the minimum track of a horizontal ScrollBar. */ protected static const THEME_STYLE_NAME_HORIZONTAL_SCROLL_BAR_MINIMUM_TRACK : String = "aeon-horizontal-scroll-bar-minimum-track"; /** * @private * The theme's custom style name for the increment button of a vertical ScrollBar. */ protected static const THEME_STYLE_NAME_VERTICAL_SCROLL_BAR_INCREMENT_BUTTON : String = "aeon-vertical-scroll-bar-increment-button"; /** * @private * The theme's custom style name for the decrement button of a vertical ScrollBar. */ protected static const THEME_STYLE_NAME_VERTICAL_SCROLL_BAR_DECREMENT_BUTTON : String = "aeon-vertical-scroll-bar-decrement-button"; /** * @private * The theme's custom style name for the thumb of a vertical ScrollBar. */ protected static const THEME_STYLE_NAME_VERTICAL_SCROLL_BAR_THUMB : String = "aeon-vertical-scroll-bar-thumb"; /** * @private * The theme's custom style name for the minimum track of a vertical ScrollBar. */ protected static const THEME_STYLE_NAME_VERTICAL_SCROLL_BAR_MINIMUM_TRACK : String = "aeon-vertical-scroll-bar-minimum-track"; /** * @private * The theme's custom style name for the thumb of a horizontal SimpleScrollBar. */ protected static const THEME_STYLE_NAME_HORIZONTAL_SIMPLE_SCROLL_BAR_THUMB : String = "aeon-horizontal-simple-scroll-bar-thumb"; /** * @private * The theme's custom style name for the thumb of a vertical SimpleScrollBar. */ protected static const THEME_STYLE_NAME_VERTICAL_SIMPLE_SCROLL_BAR_THUMB : String = "aeon-vertical-simple-scroll-bar-thumb"; /** * @private * The theme's custom style name for the thumb of a horizontal Slider. */ protected static const THEME_STYLE_NAME_HORIZONTAL_SLIDER_THUMB : String = "aeon-horizontal-slider-thumb"; /** * @private * The theme's custom style name for the minimum track of a horizontal Slider. */ protected static const THEME_STYLE_NAME_HORIZONTAL_SLIDER_MINIMUM_TRACK : String = "aeon-horizontal-slider-minimum-track"; /** * @private * The theme's custom style name for the thumb of a vertical Slider. */ protected static const THEME_STYLE_NAME_VERTICAL_SLIDER_THUMB : String = "aeon-vertical-slider-thumb"; /** * @private * The theme's custom style name for the minimum track of a vertical Slider. */ protected static const THEME_STYLE_NAME_VERTICAL_SLIDER_MINIMUM_TRACK : String = "aeon-vertical-slider-minimum-track"; /** * @private * The theme's custom style name for the minimum track of a vertical VolumeSlider. */ protected static const THEME_STYLE_NAME_VERTICAL_VOLUME_SLIDER_MINIMUM_TRACK : String = "aeon-vertical-volume-slider-minimum-track"; /** * @private * The theme's custom style name for the maximum track of a vertical VolumeSlider. */ protected static const THEME_STYLE_NAME_VERTICAL_VOLUME_SLIDER_MAXIMUM_TRACK : String = "aeon-vertical-volume-slider-maximum-track"; /** * @private * The theme's custom style name for the minimum track of a horizontal VolumeSlider. */ protected static const THEME_STYLE_NAME_HORIZONTAL_VOLUME_SLIDER_MINIMUM_TRACK : String = "aeon-horizontal-volume-slider-minimum-track"; /** * @private * The theme's custom style name for the maximum track of a horizontal VolumeSlider. */ protected static const THEME_STYLE_NAME_HORIZONTAL_VOLUME_SLIDER_MAXIMUM_TRACK : String = "aeon-horizontal-volume-slider-maximum-track"; /** * @private * The theme's custom style name for the minimum track of a pop-up VolumeSlider. */ protected static const THEME_STYLE_NAME_POP_UP_VOLUME_SLIDER_MINIMUM_TRACK : String = "aeon-pop-up-volume-slider-minimum-track"; /** * @private * The theme's custom style name for the maximum track of a pop-up VolumeSlider. */ protected static const THEME_STYLE_NAME_POP_UP_VOLUME_SLIDER_MAXIMUM_TRACK : String = "aeon-pop-up-volume-slider-maximum-track"; /** * @private * The theme's custom style name for the item renderer of a SpinnerList in a DateTimeSpinner. */ protected static const THEME_STYLE_NAME_DATE_TIME_SPINNER_LIST_ITEM_RENDERER : String = "aeon-date-time-spinner-list-item-renderer"; /** * @private * The theme's custom style name for the text renderer of a heading Label. */ protected static const THEME_STYLE_NAME_HEADING_LABEL_TEXT_RENDERER : String = "aeon-heading-label-text-renderer"; /** * @private * The theme's custom style name for the text renderer of a detail Label. */ protected static const THEME_STYLE_NAME_DETAIL_LABEL_TEXT_RENDERER : String = "aeon-detail-label-text-renderer"; /** * @private * The theme's custom style name for the text renderer of a tool tip Label. */ protected static const THEME_STYLE_NAME_TOOL_TIP_LABEL_TEXT_RENDERER : String = "aeon-tool-tip-label-text-renderer"; /** * The name of the font used by controls in this theme. This font is not * embedded. It is the default sans-serif system font. */ public static const FONT_NAME : String = "SimSun"; protected static const FOCUS_INDICATOR_SCALE_9_GRID : Rectangle = new Rectangle( 5, 5, 2, 2 ); protected static const TOOL_TIP_SCALE_9_GRID : Rectangle = new Rectangle( 5, 5, 1, 1 ); protected static const BUTTON_SCALE_9_GRID : Rectangle = new Rectangle( 5, 5, 1, 12 ); protected static const TAB_SCALE_9_GRID : Rectangle = new Rectangle( 5, 5, 1, 15 ); protected static const STEPPER_INCREMENT_BUTTON_SCALE_9_GRID : Rectangle = new Rectangle( 1, 9, 15, 1 ); protected static const STEPPER_DECREMENT_BUTTON_SCALE_9_GRID : Rectangle = new Rectangle( 1, 1, 15, 1 ); protected static const HORIZONTAL_SLIDER_TRACK_SCALE_9_GRID : Rectangle = new Rectangle( 3, 0, 1, 4 ); protected static const VERTICAL_SLIDER_TRACK_SCALE_9_GRID : Rectangle = new Rectangle( 0, 3, 4, 1 ); protected static const TEXT_INPUT_SCALE_9_GRID : Rectangle = new Rectangle( 2, 2, 1, 1 ); protected static const VERTICAL_SCROLL_BAR_THUMB_SCALE_9_GRID : Rectangle = new Rectangle( 4, 7, 1, 4 ); protected static const VERTICAL_SCROLL_BAR_TRACK_SCALE_9_GRID : Rectangle = new Rectangle( 6, 6, 2, 2 ); protected static const VERTICAL_SCROLL_BAR_STEP_BUTTON_SCALE_9_GRID : Rectangle = new Rectangle( 2, 2, 2, 2 ); protected static const HORIZONTAL_SCROLL_BAR_THUMB_SCALE_9_GRID : Rectangle = new Rectangle( 5, 2, 42, 6 ); protected static const HORIZONTAL_SCROLL_BAR_TRACK_SCALE_9_GRID : Rectangle = new Rectangle( 1, 2, 2, 11 ); protected static const HORIZONTAL_SCROLL_BAR_STEP_BUTTON_SCALE_9_GRID : Rectangle = new Rectangle( 2, 2, 10, 11 ); protected static const SIMPLE_BORDER_SCALE_9_GRID : Rectangle = new Rectangle( 2, 2, 2, 2 ); protected static const PANEL_BORDER_SCALE_9_GRID : Rectangle = new Rectangle( 5, 5, 1, 1 ); protected static const HEADER_SCALE_9_GRID : Rectangle = new Rectangle( 1, 1, 2, 28 ); // protected static const SEEK_SLIDER_MINIMUM_TRACK_SCALE_9_GRID:Rectangle = new Rectangle(3, 0, 1, 4); // protected static const SEEK_SLIDER_MAXIMUM_TRACK_SCALE_9_GRID:Rectangle = new Rectangle(1, 0, 1, 4); protected static const ITEM_RENDERER_SKIN_TEXTURE_REGION : Rectangle = new Rectangle( 1, 1, 4, 4 ); protected static const PROGRESS_BAR_FILL_TEXTURE_REGION : Rectangle = new Rectangle( 1, 1, 4, 4 ); protected static const BACKGROUND_COLOR : uint = 0x0; protected static const MODAL_OVERLAY_COLOR : uint = 0xDDDDDD; protected static const MODAL_OVERLAY_ALPHA : Number = 0.5; protected static const PRIMARY_TEXT_COLOR : uint = 0x0B333C; protected static const DISABLED_TEXT_COLOR : uint = 0x5B6770; // protected static const VIDEO_OVERLAY_COLOR:uint = 0xc9e0eE; // protected static const VIDEO_OVERLAY_ALPHA:Number = 0.25; protected static const TOOLTIP_TEXT_COLOR : uint = 0x0B333C; /** * The default global text renderer factory for this theme creates a * TextFieldTextRenderer. */ protected static function textRendererFactory() : ITextRenderer { return new TextFieldTextRenderer(); } /** * The default global text editor factory for this theme creates a * TextFieldTextEditor. */ protected static function textEditorFactory() : ITextEditor { return new TextFieldTextEditor(); } /** * This theme's scroll bar type is ScrollBar. */ protected static function scrollBarFactory() : IScrollBar { return new ScrollBar(); } protected static function popUpOverlayFactory() : DisplayObject { var quad : Quad = new Quad( 100, 100, MODAL_OVERLAY_COLOR ); quad.alpha = MODAL_OVERLAY_ALPHA; return quad; } /** * Constructor. */ public function GameAeonTheme() { super(); this.initialize(); } protected var smallScrollBarSize : int; /** * A smaller font size for details. */ protected var smallFontSize : int; /** * A normal font size. */ protected var regularFontSize : int; /** * A larger font size for headers. */ protected var largeFontSize : int; /** * The size, in pixels, of major regions in the grid. Used for sizing * containers and larger UI controls. */ protected var gridSize : int; /** * The size, in pixels, of minor regions in the grid. Used for larger * padding and gaps. */ protected var gutterSize : int; /** * The size, in pixels, of smaller padding and gaps within the major * regions in the grid. */ protected var smallGutterSize : int; /** * The size, in pixels, of very smaller padding and gaps. */ protected var extraSmallGutterSize : int; /** * The minimum width, in pixels, of some types of buttons. */ protected var buttonMinWidth : int; /** * The width, in pixels, of UI controls that span across multiple grid regions. */ protected var wideControlSize : int; /** * The size, in pixels, of a typical UI control. */ protected var controlSize : int; /** * The size, in pixels, of smaller UI controls. */ protected var smallControlSize : int; /** * The size, in pixels, of a border around any control. */ protected var borderSize : int; protected var calloutBackgroundMinSize : int; protected var progressBarFillMinSize : int; protected var popUpSize : int; protected var popUpVolumeSliderPaddingSize : int; protected var bottomDropShadowSize : int; protected var leftAndRightDropShadowSize : int; /** * The texture atlas that contains skins for this theme. This base class * does not initialize this member variable. Subclasses are expected to * load the assets somehow and set the <code>atlas</code> member * variable before calling <code>initialize()</code>. */ protected var atlas : TextureAtlas; /** * A TextFormat for most UI controls and text. */ protected var defaultTextFormat : TextFormat; protected var defaultToolTipTextFormat : TextFormat; protected var defaultScrollTextFormat : TextFormat; /** * A TextFormat for most disabled UI controls and text. */ protected var disabledTextFormat : TextFormat; /** * A TextFormat for larger text. */ protected var headingTextFormat : TextFormat; /** * A TextFormat for larger, disabled text. */ protected var headingDisabledTextFormat : TextFormat; /** * A TextFormat for smaller text. */ protected var detailTextFormat : TextFormat; /** * A TextFormat for smaller, disabled text. */ protected var detailDisabledTextFormat : TextFormat; protected var focusIndicatorSkinTexture : Texture; protected var toolTipBackgroundSkinTexture : Texture; protected var buttonUpSkinTexture : Texture; protected var buttonHoverSkinTexture : Texture; protected var buttonDownSkinTexture : Texture; protected var buttonDisabledSkinTexture : Texture; protected var toggleButtonSelectedUpSkinTexture : Texture; protected var toggleButtonSelectedHoverSkinTexture : Texture; protected var toggleButtonSelectedDownSkinTexture : Texture; protected var toggleButtonSelectedDisabledSkinTexture : Texture; protected var quietButtonHoverSkinTexture : Texture; protected var callToActionButtonUpSkinTexture : Texture; protected var callToActionButtonHoverSkinTexture : Texture; protected var dangerButtonUpSkinTexture : Texture; protected var dangerButtonHoverSkinTexture : Texture; protected var dangerButtonDownSkinTexture : Texture; protected var backButtonUpIconTexture : Texture; protected var backButtonDisabledIconTexture : Texture; protected var forwardButtonUpIconTexture : Texture; protected var forwardButtonDisabledIconTexture : Texture; // protected var tabUpSkinTexture : Texture; // protected var tabHoverSkinTexture : Texture; // protected var tabDownSkinTexture : Texture; // protected var tabDisabledSkinTexture : Texture; // protected var tabSelectedUpSkinTexture : Texture; // protected var tabSelectedDisabledSkinTexture : Texture; // protected var stepperIncrementButtonUpSkinTexture : Texture; // protected var stepperIncrementButtonHoverSkinTexture : Texture; // protected var stepperIncrementButtonDownSkinTexture : Texture; // protected var stepperIncrementButtonDisabledSkinTexture : Texture; // // protected var stepperDecrementButtonUpSkinTexture : Texture; // protected var stepperDecrementButtonHoverSkinTexture : Texture; // protected var stepperDecrementButtonDownSkinTexture : Texture; // protected var stepperDecrementButtonDisabledSkinTexture : Texture; // protected var hSliderThumbUpSkinTexture : Texture; // protected var hSliderThumbHoverSkinTexture : Texture; // protected var hSliderThumbDownSkinTexture : Texture; // protected var hSliderThumbDisabledSkinTexture : Texture; // protected var hSliderTrackEnabledSkinTexture : Texture; // // protected var vSliderThumbUpSkinTexture : Texture; // protected var vSliderThumbHoverSkinTexture : Texture; // protected var vSliderThumbDownSkinTexture : Texture; // protected var vSliderThumbDisabledSkinTexture : Texture; // protected var vSliderTrackEnabledSkinTexture : Texture; protected var itemRendererUpSkinTexture : Texture; protected var itemRendererHoverSkinTexture : Texture; protected var itemRendererSelectedUpSkinTexture : Texture; protected var headerBackgroundSkinTexture : Texture; // protected var groupedListHeaderBackgroundSkinTexture : Texture; // protected var checkUpIconTexture : Texture; // protected var checkHoverIconTexture : Texture; // protected var checkDownIconTexture : Texture; // protected var checkDisabledIconTexture : Texture; // protected var checkSelectedUpIconTexture : Texture; // protected var checkSelectedHoverIconTexture : Texture; // protected var checkSelectedDownIconTexture : Texture; // protected var checkSelectedDisabledIconTexture : Texture; protected var radioUpIconTexture : Texture; protected var radioHoverIconTexture : Texture; protected var radioDownIconTexture : Texture; protected var radioDisabledIconTexture : Texture; protected var radioSelectedUpIconTexture : Texture; protected var radioSelectedHoverIconTexture : Texture; protected var radioSelectedDownIconTexture : Texture; protected var radioSelectedDisabledIconTexture : Texture; // protected var pageIndicatorNormalSkinTexture : Texture; // protected var pageIndicatorSelectedSkinTexture : Texture; protected var pickerListUpIconTexture : Texture; protected var pickerListHoverIconTexture : Texture; protected var pickerListDownIconTexture : Texture; protected var pickerListDisabledIconTexture : Texture; protected var textInputBackgroundEnabledSkinTexture : Texture; protected var textInputBackgroundDisabledSkinTexture : Texture; protected var textInputSearchIconTexture : Texture; protected var textInputSearchIconDisabledTexture : Texture; protected var vScrollBarThumbUpSkinTexture : Texture; protected var vScrollBarThumbHoverSkinTexture : Texture; protected var vScrollBarThumbDownSkinTexture : Texture; protected var vScrollBarTrackSkinTexture : Texture; protected var vScrollBarThumbIconTexture : Texture; protected var vScrollBarStepButtonUpSkinTexture : Texture; protected var vScrollBarStepButtonHoverSkinTexture : Texture; protected var vScrollBarStepButtonDownSkinTexture : Texture; protected var vScrollBarStepButtonDisabledSkinTexture : Texture; protected var vScrollBarDecrementButtonIconTexture : Texture; protected var vScrollBarIncrementButtonIconTexture : Texture; protected var hScrollBarThumbUpSkinTexture : Texture; protected var hScrollBarThumbHoverSkinTexture : Texture; protected var hScrollBarThumbDownSkinTexture : Texture; protected var hScrollBarTrackSkinTexture : Texture; protected var hScrollBarThumbIconTexture : Texture; protected var hScrollBarStepButtonUpSkinTexture : Texture; protected var hScrollBarStepButtonHoverSkinTexture : Texture; protected var hScrollBarStepButtonDownSkinTexture : Texture; protected var hScrollBarStepButtonDisabledSkinTexture : Texture; protected var hScrollBarDecrementButtonIconTexture : Texture; protected var hScrollBarIncrementButtonIconTexture : Texture; protected var simpleBorderBackgroundSkinTexture : Texture; protected var insetBorderBackgroundSkinTexture : Texture; protected var panelBorderBackgroundSkinTexture : Texture; protected var alertBorderBackgroundSkinTexture : Texture; protected var progressBarFillSkinTexture : Texture; protected var listDrillDownAccessoryTexture : Texture; //media textures // protected var playPauseButtonPlayUpIconTexture:Texture; // protected var playPauseButtonPauseUpIconTexture:Texture; // protected var overlayPlayPauseButtonPlayUpIconTexture:Texture; // protected var fullScreenToggleButtonEnterUpIconTexture:Texture; // protected var fullScreenToggleButtonExitUpIconTexture:Texture; // protected var muteToggleButtonLoudUpIconTexture:Texture; // protected var muteToggleButtonMutedUpIconTexture:Texture; // protected var horizontalVolumeSliderMinimumTrackSkinTexture:Texture; // protected var horizontalVolumeSliderMaximumTrackSkinTexture:Texture; // protected var verticalVolumeSliderMinimumTrackSkinTexture:Texture; // protected var verticalVolumeSliderMaximumTrackSkinTexture:Texture; // protected var popUpVolumeSliderMinimumTrackSkinTexture:Texture; // protected var popUpVolumeSliderMaximumTrackSkinTexture:Texture; // protected var seekSliderMinimumTrackSkinTexture:Texture; // protected var seekSliderMaximumTrackSkinTexture:Texture; // protected var seekSliderProgressSkinTexture:Texture; /** * Disposes the texture atlas before calling super.dispose() */ override public function dispose() : void { if ( this.atlas ) { //if anything is keeping a reference to the texture, we don't //want it to keep a reference to the theme too. this.atlas.texture.root.onRestore = null; this.atlas.dispose(); this.atlas = null; } var stage : Stage = Starling.current.stage; FocusManager.setEnabledForStage( stage, false ); ToolTipManager.setEnabledForStage( stage, false ); //don't forget to call super.dispose()! super.dispose(); } /** * Initializes the theme. Expected to be called by subclasses after the * assets have been loaded and the skin texture atlas has been created. */ protected function initialize() : void { this.initializeTextureAtlas(); this.initializeDimensions(); this.initializeFonts(); this.initializeTextures(); this.initializeGlobals(); this.initializeStage(); this.initializeStyleProviders(); } /** * Initializes common values used for setting the dimensions of components. */ protected function initializeDimensions() : void { this.gridSize = 30; this.extraSmallGutterSize = 2; this.smallGutterSize = 6; this.gutterSize = 10; this.borderSize = 1; this.controlSize = 22; this.smallControlSize = 12; this.calloutBackgroundMinSize = 5; this.progressBarFillMinSize = 7; this.buttonMinWidth = 16; this.wideControlSize = 152; this.popUpSize = this.gridSize * 10 + this.smallGutterSize * 9; this.popUpVolumeSliderPaddingSize = 6; this.leftAndRightDropShadowSize = 1; this.bottomDropShadowSize = 3; this.smallScrollBarSize = 16; } /** * Sets the stage background color. */ protected function initializeStage() : void { Starling.current.stage.color = BACKGROUND_COLOR; Starling.current.nativeStage.color = BACKGROUND_COLOR; Feather.scrollTextOverlay = Starling.current.nativeStage; } /** * Initializes global variables (not including global style providers). */ protected function initializeGlobals() : void { var stage : Stage = Starling.current.stage; FocusManager.setEnabledForStage( stage, false ); ToolTipManager.setEnabledForStage( stage, true ); FeathersControl.defaultTextRendererFactory = textRendererFactory; FeathersControl.defaultTextEditorFactory = textEditorFactory; PopUpManager.overlayFactory = popUpOverlayFactory; Callout.stagePadding = this.smallGutterSize; } /** * Initializes font sizes and formats. */ protected function initializeFonts() : void { this.smallFontSize = 11; this.regularFontSize = 12; this.largeFontSize = 14; this.defaultTextFormat = new TextFormat( FONT_NAME, this.regularFontSize, PRIMARY_TEXT_COLOR, false, false, false, null, null, TextFormatAlign.LEFT, 0, 0, 0, 0 ); this.defaultScrollTextFormat = new flash.text.TextFormat( "SimSun", regularFontSize, 0xffffff, false ); this.defaultToolTipTextFormat = new TextFormat( FONT_NAME, this.regularFontSize, TOOLTIP_TEXT_COLOR, false, false, false, null, null, TextFormatAlign.LEFT, 0, 0, 0, 0 ); this.disabledTextFormat = new TextFormat( FONT_NAME, this.regularFontSize, DISABLED_TEXT_COLOR, false, false, false, null, null, TextFormatAlign.LEFT, 0, 0, 0, 0 ); this.headingTextFormat = new TextFormat( FONT_NAME, this.largeFontSize, PRIMARY_TEXT_COLOR, false, false, false, null, null, TextFormatAlign.LEFT, 0, 0, 0, 0 ); this.headingDisabledTextFormat = new TextFormat( FONT_NAME, this.largeFontSize, DISABLED_TEXT_COLOR, false, false, false, null, null, TextFormatAlign.LEFT, 0, 0, 0, 0 ); this.detailTextFormat = new TextFormat( FONT_NAME, this.smallFontSize, PRIMARY_TEXT_COLOR, false, false, false, null, null, TextFormatAlign.LEFT, 0, 0, 0, 0 ); this.detailDisabledTextFormat = new TextFormat( FONT_NAME, this.smallFontSize, DISABLED_TEXT_COLOR, false, false, false, null, null, TextFormatAlign.LEFT, 0, 0, 0, 0 ); } public function getTexture( name : String ) : Texture { return this.atlas.getTexture( name ); } /** * Initializes the textures by extracting them from the atlas and * setting up any scaling grids that are needed. */ protected function initializeTextures() : void { this.focusIndicatorSkinTexture = this.atlas.getTexture( "focus-indicator-skin0000" ); this.toolTipBackgroundSkinTexture = this.atlas.getTexture( "tool-tip-background-skin0000" ); this.buttonUpSkinTexture = this.atlas.getTexture( "button-up-skin0000" ); this.buttonHoverSkinTexture = this.atlas.getTexture( "button-hover-skin0000" ); this.buttonDownSkinTexture = this.atlas.getTexture( "button-down-skin0000" ); this.buttonDisabledSkinTexture = this.atlas.getTexture( "button-disabled-skin0000" ); this.toggleButtonSelectedUpSkinTexture = this.atlas.getTexture( "toggle-button-selected-up-skin0000" ); this.toggleButtonSelectedHoverSkinTexture = this.atlas.getTexture( "toggle-button-selected-hover-skin0000" ); this.toggleButtonSelectedDownSkinTexture = this.atlas.getTexture( "toggle-button-selected-down-skin0000" ); this.toggleButtonSelectedDisabledSkinTexture = this.atlas.getTexture( "toggle-button-selected-disabled-skin0000" ); this.quietButtonHoverSkinTexture = this.atlas.getTexture( "quiet-button-hover-skin0000" ); this.callToActionButtonUpSkinTexture = this.atlas.getTexture( "call-to-action-button-up-skin0000" ); this.callToActionButtonHoverSkinTexture = this.atlas.getTexture( "call-to-action-button-hover-skin0000" ); this.dangerButtonUpSkinTexture = this.atlas.getTexture( "danger-button-up-skin0000" ); this.dangerButtonHoverSkinTexture = this.atlas.getTexture( "danger-button-hover-skin0000" ); this.dangerButtonDownSkinTexture = this.atlas.getTexture( "danger-button-down-skin0000" ); this.backButtonUpIconTexture = this.atlas.getTexture( "back-button-up-icon0000" ); this.backButtonDisabledIconTexture = this.atlas.getTexture( "back-button-disabled-icon0000" ); this.forwardButtonUpIconTexture = this.atlas.getTexture( "forward-button-up-icon0000" ); this.forwardButtonDisabledIconTexture = this.atlas.getTexture( "forward-button-disabled-icon0000" ); // this.tabUpSkinTexture = this.atlas.getTexture( "tab-up-skin0000" ); // this.tabHoverSkinTexture = this.atlas.getTexture( "tab-hover-skin0000" ); // this.tabDownSkinTexture = this.atlas.getTexture( "tab-down-skin0000" ); // this.tabDisabledSkinTexture = this.atlas.getTexture( "tab-disabled-skin0000" ); // this.tabSelectedUpSkinTexture = this.atlas.getTexture( "tab-selected-up-skin0000" ); // this.tabSelectedDisabledSkinTexture = this.atlas.getTexture( "tab-selected-disabled-skin0000" ); // this.stepperIncrementButtonUpSkinTexture = this.atlas.getTexture( "numeric-stepper-increment-button-up-skin0000" ); // this.stepperIncrementButtonHoverSkinTexture = this.atlas.getTexture( "numeric-stepper-increment-button-hover-skin0000" ); // this.stepperIncrementButtonDownSkinTexture = this.atlas.getTexture( "numeric-stepper-increment-button-down-skin0000" ); // this.stepperIncrementButtonDisabledSkinTexture = this.atlas.getTexture( "numeric-stepper-increment-button-disabled-skin0000" ); // // this.stepperDecrementButtonUpSkinTexture = this.atlas.getTexture( "numeric-stepper-decrement-button-up-skin0000" ); // this.stepperDecrementButtonHoverSkinTexture = this.atlas.getTexture( "numeric-stepper-decrement-button-hover-skin0000" ); // this.stepperDecrementButtonDownSkinTexture = this.atlas.getTexture( "numeric-stepper-decrement-button-down-skin0000" ); // this.stepperDecrementButtonDisabledSkinTexture = this.atlas.getTexture( "numeric-stepper-decrement-button-disabled-skin0000" ); // this.hSliderThumbUpSkinTexture = this.atlas.getTexture( "horizontal-slider-thumb-up-skin0000" ); // this.hSliderThumbHoverSkinTexture = this.atlas.getTexture( "horizontal-slider-thumb-hover-skin0000" ); // this.hSliderThumbDownSkinTexture = this.atlas.getTexture( "horizontal-slider-thumb-down-skin0000" ); // this.hSliderThumbDisabledSkinTexture = this.atlas.getTexture( "horizontal-slider-thumb-disabled-skin0000" ); // this.hSliderTrackEnabledSkinTexture = this.atlas.getTexture( "horizontal-slider-track-enabled-skin0000" ); // // this.vSliderThumbUpSkinTexture = this.atlas.getTexture( "vertical-slider-thumb-up-skin0000" ); // this.vSliderThumbHoverSkinTexture = this.atlas.getTexture( "vertical-slider-thumb-hover-skin0000" ); // this.vSliderThumbDownSkinTexture = this.atlas.getTexture( "vertical-slider-thumb-down-skin0000" ); // this.vSliderThumbDisabledSkinTexture = this.atlas.getTexture( "vertical-slider-thumb-disabled-skin0000" ); // this.vSliderTrackEnabledSkinTexture = this.atlas.getTexture( "vertical-slider-track-enabled-skin0000" ); this.itemRendererUpSkinTexture = Texture.fromTexture( this.atlas.getTexture( "item-renderer-up-skin0000" ), ITEM_RENDERER_SKIN_TEXTURE_REGION ); this.itemRendererHoverSkinTexture = Texture.fromTexture( this.atlas.getTexture( "item-renderer-hover-skin0000" ), ITEM_RENDERER_SKIN_TEXTURE_REGION ); this.itemRendererSelectedUpSkinTexture = Texture.fromTexture( this.atlas.getTexture( "item-renderer-selected-up-skin0000" ), ITEM_RENDERER_SKIN_TEXTURE_REGION ); this.headerBackgroundSkinTexture = this.atlas.getTexture( "header-background-skin0000" ); // this.groupedListHeaderBackgroundSkinTexture = this.atlas.getTexture( "grouped-list-header-background-skin0000" ); // this.checkUpIconTexture = this.atlas.getTexture( "check-up-icon0000" ); // this.checkHoverIconTexture = this.atlas.getTexture( "check-hover-icon0000" ); // this.checkDownIconTexture = this.atlas.getTexture( "check-down-icon0000" ); // this.checkDisabledIconTexture = this.atlas.getTexture( "check-disabled-icon0000" ); // this.checkSelectedUpIconTexture = this.atlas.getTexture( "check-selected-up-icon0000" ); // this.checkSelectedHoverIconTexture = this.atlas.getTexture( "check-selected-hover-icon0000" ); // this.checkSelectedDownIconTexture = this.atlas.getTexture( "check-selected-down-icon0000" ); // this.checkSelectedDisabledIconTexture = this.atlas.getTexture( "check-selected-disabled-icon0000" ); // this.radioUpIconTexture = this.atlas.getTexture( "radio-up-icon0000" ); // this.radioHoverIconTexture = this.atlas.getTexture( "radio-hover-icon0000" ); // this.radioDownIconTexture = this.atlas.getTexture( "radio-down-icon0000" ); // this.radioDisabledIconTexture = this.atlas.getTexture( "radio-disabled-icon0000" ); // this.radioSelectedUpIconTexture = this.atlas.getTexture( "radio-selected-up-icon0000" ); // this.radioSelectedHoverIconTexture = this.atlas.getTexture( "radio-selected-hover-icon0000" ); // this.radioSelectedDownIconTexture = this.atlas.getTexture( "radio-selected-down-icon0000" ); // this.radioSelectedDisabledIconTexture = this.atlas.getTexture( "radio-selected-disabled-icon0000" ); // this.pageIndicatorNormalSkinTexture = this.atlas.getTexture( "page-indicator-normal-symbol0000" ); // this.pageIndicatorSelectedSkinTexture = this.atlas.getTexture( "page-indicator-selected-symbol0000" ); // this.pickerListUpIconTexture = this.atlas.getTexture( "picker-list-up-icon0000" ); // this.pickerListHoverIconTexture = this.atlas.getTexture( "picker-list-hover-icon0000" ); // this.pickerListDownIconTexture = this.atlas.getTexture( "picker-list-down-icon0000" ); // this.pickerListDisabledIconTexture = this.atlas.getTexture( "picker-list-disabled-icon0000" ); this.textInputBackgroundEnabledSkinTexture = this.atlas.getTexture( "text-input-background-enabled-skin0000" ); this.textInputBackgroundDisabledSkinTexture = this.atlas.getTexture( "text-input-background-disabled-skin0000" ); this.textInputSearchIconTexture = this.atlas.getTexture( "search-icon0000" ); this.textInputSearchIconDisabledTexture = this.atlas.getTexture( "search-icon-disabled0000" ); this.vScrollBarThumbUpSkinTexture = this.atlas.getTexture( "vertical-scroll-bar-thumb-up-skin0000" ); this.vScrollBarThumbHoverSkinTexture = this.atlas.getTexture( "vertical-scroll-bar-thumb-hover-skin0000" ); this.vScrollBarThumbDownSkinTexture = this.atlas.getTexture( "vertical-scroll-bar-thumb-down-skin0000" ); this.vScrollBarTrackSkinTexture = this.atlas.getTexture( "vertical-scroll-bar-track-skin0000" ); this.vScrollBarThumbIconTexture = this.atlas.getTexture( "vertical-scroll-bar-thumb-icon0000" ); this.vScrollBarStepButtonUpSkinTexture = this.atlas.getTexture( "vertical-scroll-bar-step-button-up-skin0000" ); this.vScrollBarStepButtonHoverSkinTexture = this.atlas.getTexture( "vertical-scroll-bar-step-button-hover-skin0000" ); this.vScrollBarStepButtonDownSkinTexture = this.atlas.getTexture( "vertical-scroll-bar-step-button-down-skin0000" ); this.vScrollBarStepButtonDisabledSkinTexture = this.atlas.getTexture( "vertical-scroll-bar-step-button-disabled-skin0000" ); this.vScrollBarDecrementButtonIconTexture = this.atlas.getTexture( "vertical-scroll-bar-decrement-button-icon0000" ); this.vScrollBarIncrementButtonIconTexture = this.atlas.getTexture( "vertical-scroll-bar-increment-button-icon0000" ); this.hScrollBarThumbUpSkinTexture = this.atlas.getTexture( "horizontal-scroll-bar-thumb-up-skin0000" ); this.hScrollBarThumbHoverSkinTexture = this.atlas.getTexture( "horizontal-scroll-bar-thumb-hover-skin0000" ); this.hScrollBarThumbDownSkinTexture = this.atlas.getTexture( "horizontal-scroll-bar-thumb-down-skin0000" ); this.hScrollBarTrackSkinTexture = this.atlas.getTexture( "horizontal-scroll-bar-track-skin0000" ); this.hScrollBarThumbIconTexture = this.atlas.getTexture( "horizontal-scroll-bar-thumb-icon0000" ); this.hScrollBarStepButtonUpSkinTexture = this.atlas.getTexture( "horizontal-scroll-bar-step-button-up-skin0000" ); this.hScrollBarStepButtonHoverSkinTexture = this.atlas.getTexture( "horizontal-scroll-bar-step-button-hover-skin0000" ); this.hScrollBarStepButtonDownSkinTexture = this.atlas.getTexture( "horizontal-scroll-bar-step-button-down-skin0000" ); this.hScrollBarStepButtonDisabledSkinTexture = this.atlas.getTexture( "horizontal-scroll-bar-step-button-disabled-skin0000" ); this.hScrollBarDecrementButtonIconTexture = this.atlas.getTexture( "horizontal-scroll-bar-decrement-button-icon0000" ); this.hScrollBarIncrementButtonIconTexture = this.atlas.getTexture( "horizontal-scroll-bar-increment-button-icon0000" ); this.simpleBorderBackgroundSkinTexture = this.atlas.getTexture( "simple-border-background-skin0000" ); this.insetBorderBackgroundSkinTexture = this.atlas.getTexture( "inset-border-background-skin0000" ); this.panelBorderBackgroundSkinTexture = this.atlas.getTexture( "panel-background-skin0000" ); this.alertBorderBackgroundSkinTexture = this.atlas.getTexture( "alert-background-skin0000" ); this.progressBarFillSkinTexture = Texture.fromTexture( this.atlas.getTexture( "progress-bar-fill-skin0000" ), PROGRESS_BAR_FILL_TEXTURE_REGION ); // this.playPauseButtonPlayUpIconTexture = this.atlas.getTexture("play-pause-toggle-button-play-up-icon0000"); // this.playPauseButtonPauseUpIconTexture = this.atlas.getTexture("play-pause-toggle-button-pause-up-icon0000"); // this.overlayPlayPauseButtonPlayUpIconTexture = this.atlas.getTexture("overlay-play-pause-toggle-button-play-up-icon0000"); // this.fullScreenToggleButtonEnterUpIconTexture = this.atlas.getTexture("full-screen-toggle-button-enter-up-icon0000"); // this.fullScreenToggleButtonExitUpIconTexture = this.atlas.getTexture("full-screen-toggle-button-exit-up-icon0000"); // this.muteToggleButtonMutedUpIconTexture = this.atlas.getTexture("mute-toggle-button-muted-up-icon0000"); // this.muteToggleButtonLoudUpIconTexture = this.atlas.getTexture("mute-toggle-button-loud-up-icon0000"); // this.horizontalVolumeSliderMinimumTrackSkinTexture = this.atlas.getTexture("horizontal-volume-slider-minimum-track-skin0000"); // this.horizontalVolumeSliderMaximumTrackSkinTexture = this.atlas.getTexture("horizontal-volume-slider-maximum-track-skin0000"); // this.verticalVolumeSliderMinimumTrackSkinTexture = this.atlas.getTexture("vertical-volume-slider-minimum-track-skin0000"); // this.verticalVolumeSliderMaximumTrackSkinTexture = this.atlas.getTexture("vertical-volume-slider-maximum-track-skin0000"); // this.popUpVolumeSliderMinimumTrackSkinTexture = this.atlas.getTexture("pop-up-volume-slider-minimum-track-skin0000"); // this.popUpVolumeSliderMaximumTrackSkinTexture = this.atlas.getTexture("pop-up-volume-slider-maximum-track-skin0000"); // this.seekSliderMinimumTrackSkinTexture = this.atlas.getTexture("seek-slider-minimum-track-skin0000"); // this.seekSliderMaximumTrackSkinTexture = this.atlas.getTexture("seek-slider-maximum-track-skin0000"); // this.seekSliderProgressSkinTexture = this.atlas.getTexture("seek-slider-progress-skin0000"); this.listDrillDownAccessoryTexture = this.atlas.getTexture( "drill-down-icon0000" ); } /** * Sets global style providers for all components. */ protected function initializeStyleProviders() : void { //alert // this.getStyleProviderForClass( Alert ).defaultStyleFunction = this.setAlertStyles; // this.getStyleProviderForClass( Header ).setFunctionForStyleName( Alert.DEFAULT_CHILD_STYLE_NAME_HEADER, this.setPanelHeaderStyles ); // this.getStyleProviderForClass( ButtonGroup ).setFunctionForStyleName( Alert.DEFAULT_CHILD_STYLE_NAME_BUTTON_GROUP, this.setAlertButtonGroupStyles ); // this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( Alert.DEFAULT_CHILD_STYLE_NAME_MESSAGE, this.setAlertMessageTextRendererStyles ); //button this.getStyleProviderForClass( Button ).defaultStyleFunction = this.setButtonStyles; this.getStyleProviderForClass( Button ).setFunctionForStyleName( Button.ALTERNATE_STYLE_NAME_QUIET_BUTTON, this.setQuietButtonStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( Button.ALTERNATE_STYLE_NAME_CALL_TO_ACTION_BUTTON, this.setCallToActionButtonStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( Button.ALTERNATE_STYLE_NAME_DANGER_BUTTON, this.setDangerButtonStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( Button.ALTERNATE_STYLE_NAME_BACK_BUTTON, this.setBackButtonStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( Button.ALTERNATE_STYLE_NAME_FORWARD_BUTTON, this.setForwardButtonStyles ); this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( Button.DEFAULT_CHILD_STYLE_NAME_LABEL, this.setButtonLabelStyles ); //button group this.getStyleProviderForClass( ButtonGroup ).defaultStyleFunction = this.setButtonGroupStyles; //callout this.getStyleProviderForClass( Callout ).defaultStyleFunction = this.setCalloutStyles; //date time spinner // this.getStyleProviderForClass( SpinnerList ).setFunctionForStyleName( DateTimeSpinner.DEFAULT_CHILD_STYLE_NAME_LIST, this.setDateTimeSpinnerListStyles ); // this.getStyleProviderForClass( DefaultListItemRenderer ).setFunctionForStyleName( THEME_STYLE_NAME_DATE_TIME_SPINNER_LIST_ITEM_RENDERER, this.setDateTimeSpinnerListItemRendererStyles ); //drawers this.getStyleProviderForClass( Drawers ).defaultStyleFunction = this.setDrawersStyles; //grouped list (see also: item renderers) // this.getStyleProviderForClass( GroupedList ).defaultStyleFunction = this.setGroupedListStyles; // this.getStyleProviderForClass( GroupedList ).setFunctionForStyleName( GroupedList.ALTERNATE_STYLE_NAME_INSET_GROUPED_LIST, this.setInsetGroupedListStyles ); //header // this.getStyleProviderForClass( Header ).defaultStyleFunction = this.setHeaderStyles; // this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( Header.DEFAULT_CHILD_STYLE_NAME_TITLE, this.setHeaderTitleStyles ); //item renderers for lists this.getStyleProviderForClass( DefaultListItemRenderer ).defaultStyleFunction = this.setItemRendererStyles; this.getStyleProviderForClass( DefaultListItemRenderer ).setFunctionForStyleName( DefaultListItemRenderer.ALTERNATE_STYLE_NAME_DRILL_DOWN, this.setDrillDownItemRendererStyles ); // this.getStyleProviderForClass( DefaultListItemRenderer ).setFunctionForStyleName( DefaultListItemRenderer.ALTERNATE_STYLE_NAME_CHECK, this.setCheckItemRendererStyles ); this.getStyleProviderForClass( DefaultGroupedListItemRenderer ).defaultStyleFunction = this.setItemRendererStyles; this.getStyleProviderForClass( DefaultGroupedListItemRenderer ).setFunctionForStyleName( DefaultGroupedListItemRenderer.ALTERNATE_STYLE_NAME_DRILL_DOWN, this.setDrillDownItemRendererStyles ); // this.getStyleProviderForClass( DefaultGroupedListItemRenderer ).setFunctionForStyleName( DefaultGroupedListItemRenderer.ALTERNATE_STYLE_NAME_CHECK, this.setCheckItemRendererStyles ); // this.getStyleProviderForClass( DefaultGroupedListItemRenderer ).setFunctionForStyleName( GroupedList.ALTERNATE_CHILD_STYLE_NAME_INSET_ITEM_RENDERER, this.setInsetGroupedListItemRendererStyles ); this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( BaseDefaultItemRenderer.DEFAULT_CHILD_STYLE_NAME_ACCESSORY_LABEL, this.setItemRendererAccessoryLabelStyles ); this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( BaseDefaultItemRenderer.DEFAULT_CHILD_STYLE_NAME_ICON_LABEL, this.setItemRendererIconLabelStyles ); this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( BaseDefaultItemRenderer.DEFAULT_CHILD_STYLE_NAME_LABEL, this.setItemRendererLabelStyles ); //header and footer renderers for grouped list // this.getStyleProviderForClass( DefaultGroupedListHeaderOrFooterRenderer ).defaultStyleFunction = this.setGroupedListHeaderOrFooterRendererStyles; // this.getStyleProviderForClass( DefaultGroupedListHeaderOrFooterRenderer ).setFunctionForStyleName( GroupedList.ALTERNATE_CHILD_STYLE_NAME_INSET_HEADER_RENDERER, this.setInsetGroupedListHeaderRendererStyles ); // this.getStyleProviderForClass( DefaultGroupedListHeaderOrFooterRenderer ).setFunctionForStyleName( GroupedList.ALTERNATE_CHILD_STYLE_NAME_INSET_FOOTER_RENDERER, this.setInsetGroupedListFooterRendererStyles ); // this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( DefaultGroupedListHeaderOrFooterRenderer.DEFAULT_CHILD_STYLE_NAME_CONTENT_LABEL, this.setGroupedListHeaderOrFooterRendererContentLabelStyles ); //label this.getStyleProviderForClass( Label ).setFunctionForStyleName( Label.ALTERNATE_STYLE_NAME_HEADING, this.setHeadingLabelStyles ); this.getStyleProviderForClass( Label ).setFunctionForStyleName( Label.ALTERNATE_STYLE_NAME_DETAIL, this.setDetailLabelStyles ); this.getStyleProviderForClass( Label ).setFunctionForStyleName( Label.ALTERNATE_STYLE_NAME_TOOL_TIP, this.setToolTipLabelStyles ); this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( Label.DEFAULT_CHILD_STYLE_NAME_TEXT_RENDERER, this.setLabelTextRendererStyles ); this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( THEME_STYLE_NAME_HEADING_LABEL_TEXT_RENDERER, this.setHeadingLabelTextRendererStyles ); this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( THEME_STYLE_NAME_DETAIL_LABEL_TEXT_RENDERER, this.setDetailLabelTextRendererStyles ); //layout group this.getStyleProviderForClass( LayoutGroup ).setFunctionForStyleName( LayoutGroup.ALTERNATE_STYLE_NAME_TOOLBAR, this.setToolbarLayoutGroupStyles ); //list (see also: item renderers) // this.getStyleProviderForClass( List ).defaultStyleFunction = this.setListStyles; //numeric stepper // this.getStyleProviderForClass( NumericStepper ).defaultStyleFunction = this.setNumericStepperStyles; // this.getStyleProviderForClass( TextInput ).setFunctionForStyleName( NumericStepper.DEFAULT_CHILD_STYLE_NAME_TEXT_INPUT, this.setNumericStepperTextInputStyles ); // this.getStyleProviderForClass( Button ).setFunctionForStyleName( NumericStepper.DEFAULT_CHILD_STYLE_NAME_INCREMENT_BUTTON, this.setNumericStepperIncrementButtonStyles ); // this.getStyleProviderForClass( Button ).setFunctionForStyleName( NumericStepper.DEFAULT_CHILD_STYLE_NAME_DECREMENT_BUTTON, this.setNumericStepperDecrementButtonStyles ); //panel // this.getStyleProviderForClass( Panel ).defaultStyleFunction = this.setPanelStyles; // this.getStyleProviderForClass( Header ).setFunctionForStyleName( Panel.DEFAULT_CHILD_STYLE_NAME_HEADER, this.setPanelHeaderStyles ); //panel screen // this.getStyleProviderForClass( PanelScreen ).defaultStyleFunction = this.setPanelScreenStyles; //page indicator // this.getStyleProviderForClass( PageIndicator ).defaultStyleFunction = this.setPageIndicatorStyles; //picker list (see also: item renderers) // this.getStyleProviderForClass( PickerList ).defaultStyleFunction = this.setPickerListStyles; // this.getStyleProviderForClass( List ).setFunctionForStyleName( PickerList.DEFAULT_CHILD_STYLE_NAME_LIST, this.setDropDownListStyles ); // this.getStyleProviderForClass( Button ).setFunctionForStyleName( PickerList.DEFAULT_CHILD_STYLE_NAME_BUTTON, this.setPickerListButtonStyles ); // this.getStyleProviderForClass( ToggleButton ).setFunctionForStyleName( PickerList.DEFAULT_CHILD_STYLE_NAME_BUTTON, this.setPickerListButtonStyles ); //progress bar this.getStyleProviderForClass( ProgressBar ).defaultStyleFunction = this.setProgressBarStyles; //radio this.getStyleProviderForClass( Radio ).defaultStyleFunction = this.setRadioStyles; this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( Radio.DEFAULT_CHILD_STYLE_NAME_LABEL, this.setRadioLabelStyles ); //scroll bar this.getStyleProviderForClass( ScrollBar ).setFunctionForStyleName( Scroller.DEFAULT_CHILD_STYLE_NAME_HORIZONTAL_SCROLL_BAR, this.setHorizontalScrollBarStyles ); this.getStyleProviderForClass( ScrollBar ).setFunctionForStyleName( Scroller.DEFAULT_CHILD_STYLE_NAME_VERTICAL_SCROLL_BAR, this.setVerticalScrollBarStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_HORIZONTAL_SCROLL_BAR_INCREMENT_BUTTON, this.setHorizontalScrollBarIncrementButtonStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_HORIZONTAL_SCROLL_BAR_DECREMENT_BUTTON, this.setHorizontalScrollBarDecrementButtonStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_HORIZONTAL_SCROLL_BAR_THUMB, this.setHorizontalScrollBarThumbStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_HORIZONTAL_SCROLL_BAR_MINIMUM_TRACK, this.setHorizontalScrollBarMinimumTrackStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_VERTICAL_SCROLL_BAR_INCREMENT_BUTTON, this.setVerticalScrollBarIncrementButtonStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_VERTICAL_SCROLL_BAR_DECREMENT_BUTTON, this.setVerticalScrollBarDecrementButtonStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_VERTICAL_SCROLL_BAR_THUMB, this.setVerticalScrollBarThumbStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_VERTICAL_SCROLL_BAR_MINIMUM_TRACK, this.setVerticalScrollBarMinimumTrackStyles ); //scroll container this.getStyleProviderForClass( ScrollContainer ).defaultStyleFunction = this.setScrollContainerStyles; this.getStyleProviderForClass( ScrollContainer ).setFunctionForStyleName( ScrollContainer.ALTERNATE_STYLE_NAME_TOOLBAR, this.setToolbarScrollContainerStyles ); //scroll screen this.getStyleProviderForClass( ScrollScreen ).defaultStyleFunction = this.setScrollScreenStyles; //scroll text //this.getStyleProviderForClass(ScrollText).defaultStyleFunction = this.setScrollTextStyles; //simple scroll bar this.getStyleProviderForClass( SimpleScrollBar ).setFunctionForStyleName( Scroller.DEFAULT_CHILD_STYLE_NAME_HORIZONTAL_SCROLL_BAR, this.setHorizontalSimpleScrollBarStyles ); this.getStyleProviderForClass( SimpleScrollBar ).setFunctionForStyleName( Scroller.DEFAULT_CHILD_STYLE_NAME_VERTICAL_SCROLL_BAR, this.setVerticalSimpleScrollBarStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_HORIZONTAL_SIMPLE_SCROLL_BAR_THUMB, this.setHorizontalSimpleScrollBarThumbStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_VERTICAL_SIMPLE_SCROLL_BAR_THUMB, this.setVerticalSimpleScrollBarThumbStyles ); //slider // this.getStyleProviderForClass( Slider ).defaultStyleFunction = this.setSliderStyles; // this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_HORIZONTAL_SLIDER_THUMB, this.setHorizontalSliderThumbStyles ); // this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_HORIZONTAL_SLIDER_MINIMUM_TRACK, this.setHorizontalSliderMinimumTrackStyles ); // this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_VERTICAL_SLIDER_THUMB, this.setVerticalSliderThumbStyles ); // this.getStyleProviderForClass( Button ).setFunctionForStyleName( THEME_STYLE_NAME_VERTICAL_SLIDER_MINIMUM_TRACK, this.setVerticalSliderMinimumTrackStyles ); //spinner list // this.getStyleProviderForClass( SpinnerList ).defaultStyleFunction = this.setSpinnerListStyles; //tab bar // this.getStyleProviderForClass( TabBar ).defaultStyleFunction = this.setTabBarStyles; // this.getStyleProviderForClass( ToggleButton ).setFunctionForStyleName( TabBar.DEFAULT_CHILD_STYLE_NAME_TAB, this.setTabStyles ); //text area this.getStyleProviderForClass( TextArea ).defaultStyleFunction = this.setTextAreaStyles; this.getStyleProviderForClass( TextFieldTextEditorViewPort ).setFunctionForStyleName( TextArea.DEFAULT_CHILD_STYLE_NAME_TEXT_EDITOR, this.setTextAreaTextEditorStyles ); //text callout this.getStyleProviderForClass( TextCallout ).defaultStyleFunction = this.setTextCalloutStyles; this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( TextCallout.DEFAULT_CHILD_STYLE_NAME_TEXT_RENDERER, this.setTextCalloutTextRendererStyles ); //text input this.getStyleProviderForClass( TextInput ).defaultStyleFunction = this.setTextInputStyles; this.getStyleProviderForClass( TextInput ).setFunctionForStyleName( TextInput.ALTERNATE_STYLE_NAME_SEARCH_TEXT_INPUT, this.setSearchTextInputStyles ); this.getStyleProviderForClass( TextFieldTextEditor ).setFunctionForStyleName( TextInput.DEFAULT_CHILD_STYLE_NAME_TEXT_EDITOR, this.setTextInputTextEditorStyles ); this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( TextInput.DEFAULT_CHILD_STYLE_NAME_PROMPT, this.setTextInputPromptStyles ); //toggle button this.getStyleProviderForClass( ToggleButton ).defaultStyleFunction = this.setButtonStyles; this.getStyleProviderForClass( ToggleButton ).setFunctionForStyleName( Button.ALTERNATE_STYLE_NAME_QUIET_BUTTON, this.setQuietButtonStyles ); //toggle switch this.getStyleProviderForClass( ToggleSwitch ).defaultStyleFunction = this.setToggleSwitchStyles; this.getStyleProviderForClass( Button ).setFunctionForStyleName( ToggleSwitch.DEFAULT_CHILD_STYLE_NAME_ON_TRACK, this.setToggleSwitchOnTrackStyles ); this.getStyleProviderForClass( Button ).setFunctionForStyleName( ToggleSwitch.DEFAULT_CHILD_STYLE_NAME_THUMB, this.setToggleSwitchThumbStyles ); this.getStyleProviderForClass( ToggleButton ).setFunctionForStyleName( ToggleSwitch.DEFAULT_CHILD_STYLE_NAME_THUMB, this.setToggleSwitchThumbStyles ); this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( ToggleSwitch.DEFAULT_CHILD_STYLE_NAME_ON_LABEL, this.setToggleSwitchOnLabelStyles ); this.getStyleProviderForClass( TextFieldTextRenderer ).setFunctionForStyleName( ToggleSwitch.DEFAULT_CHILD_STYLE_NAME_OFF_LABEL, this.setToggleSwitchOffLabelStyles ); } // protected function pageIndicatorNormalSymbolFactory() : Image // { // return new Image( this.pageIndicatorNormalSkinTexture ); // } // // protected function pageIndicatorSelectedSymbolFactory() : Image // { // return new Image( this.pageIndicatorSelectedSkinTexture ); // } //------------------------- // Shared //------------------------- protected function setScrollerStyles( scroller : Scroller ) : void { scroller.clipContent = true; scroller.horizontalScrollBarFactory = scrollBarFactory; scroller.verticalScrollBarFactory = scrollBarFactory; scroller.interactionMode = ScrollInteractionMode.MOUSE; scroller.scrollBarDisplayMode = ScrollBarDisplayMode.FIXED; var focusIndicatorSkin : Image = new Image( this.focusIndicatorSkinTexture ); focusIndicatorSkin.scale9Grid = FOCUS_INDICATOR_SCALE_9_GRID; scroller.focusIndicatorSkin = focusIndicatorSkin; scroller.focusPadding = 0; } // protected function setDropDownListStyles( list : List ) : void // { // this.setListStyles( list ); // list.maxHeight = this.wideControlSize; // } //------------------------- // Button //------------------------- protected function setBaseButtonStyles( button : Button ) : void { var focusIndicatorSkin : Image = new Image( this.focusIndicatorSkinTexture ); focusIndicatorSkin.scale9Grid = FOCUS_INDICATOR_SCALE_9_GRID; button.focusIndicatorSkin = focusIndicatorSkin; button.focusPadding = -1; button.paddingTop = this.extraSmallGutterSize; button.paddingBottom = this.extraSmallGutterSize; button.paddingLeft = this.smallGutterSize; button.paddingRight = this.smallGutterSize; button.gap = this.smallGutterSize; button.minGap = this.smallGutterSize; button.minWidth = this.smallControlSize; button.minHeight = this.smallControlSize; } protected function setButtonStyles( button : Button ) : void { var skin : ImageSkin = new ImageSkin( this.buttonUpSkinTexture ); skin.setTextureForState( ButtonState.HOVER, this.buttonHoverSkinTexture ); skin.setTextureForState( ButtonState.DOWN, this.buttonDownSkinTexture ); skin.setTextureForState( ButtonState.DISABLED, this.buttonDisabledSkinTexture ); if ( button is ToggleButton ) { //for convenience, this function can style both a regular button //and a toggle button skin.selectedTexture = this.toggleButtonSelectedUpSkinTexture; skin.setTextureForState( ButtonState.HOVER_AND_SELECTED, this.toggleButtonSelectedHoverSkinTexture ); skin.setTextureForState( ButtonState.DOWN_AND_SELECTED, this.toggleButtonSelectedDownSkinTexture ); skin.setTextureForState( ButtonState.DISABLED_AND_SELECTED, this.toggleButtonSelectedDisabledSkinTexture ); } skin.scale9Grid = BUTTON_SCALE_9_GRID; button.defaultSkin = skin; this.setBaseButtonStyles( button ); button.minWidth = this.buttonMinWidth; button.minHeight = this.controlSize; } protected function setQuietButtonStyles( button : Button ) : void { var defaultSkin : Quad = new Quad( this.controlSize, this.controlSize, 0xff00ff ); defaultSkin.alpha = 0; button.defaultSkin = defaultSkin; var otherSkin : ImageSkin = new ImageSkin( null ); otherSkin.setTextureForState( ButtonState.HOVER, this.quietButtonHoverSkinTexture ); otherSkin.setTextureForState( ButtonState.DOWN, this.buttonDownSkinTexture ); button.setSkinForState( ButtonState.HOVER, otherSkin ); button.setSkinForState( ButtonState.DOWN, otherSkin ); if ( button is ToggleButton ) { //for convenience, this function can style both a regular button //and a toggle button otherSkin.selectedTexture = this.toggleButtonSelectedUpSkinTexture; otherSkin.setTextureForState( ButtonState.HOVER_AND_SELECTED, this.toggleButtonSelectedHoverSkinTexture ); otherSkin.setTextureForState( ButtonState.DOWN_AND_SELECTED, this.toggleButtonSelectedDownSkinTexture ); otherSkin.setTextureForState( ButtonState.DISABLED_AND_SELECTED, this.toggleButtonSelectedDisabledSkinTexture ); ToggleButton( button ).defaultSelectedSkin = otherSkin; } otherSkin.scale9Grid = BUTTON_SCALE_9_GRID; otherSkin.width = this.controlSize; otherSkin.height = this.controlSize; this.setBaseButtonStyles( button ); button.minWidth = this.controlSize; button.minHeight = this.controlSize; } protected function setCallToActionButtonStyles( button : Button ) : void { var skin : ImageSkin = new ImageSkin( this.callToActionButtonUpSkinTexture ); skin.setTextureForState( ButtonState.HOVER, this.callToActionButtonHoverSkinTexture ); skin.setTextureForState( ButtonState.DOWN, this.buttonDownSkinTexture ); skin.scale9Grid = BUTTON_SCALE_9_GRID; skin.width = this.controlSize; skin.height = this.controlSize; button.defaultSkin = skin; this.setBaseButtonStyles( button ); button.minWidth = this.controlSize; button.minHeight = this.controlSize; } protected function setDangerButtonStyles( button : Button ) : void { var skin : ImageSkin = new ImageSkin( this.dangerButtonUpSkinTexture ); skin.setTextureForState( ButtonState.HOVER, this.dangerButtonHoverSkinTexture ); skin.setTextureForState( ButtonState.DOWN, this.dangerButtonDownSkinTexture ); skin.scale9Grid = BUTTON_SCALE_9_GRID; skin.width = this.controlSize; skin.height = this.controlSize; button.defaultSkin = skin; this.setBaseButtonStyles( button ); button.minWidth = this.controlSize; button.minHeight = this.controlSize; } protected function setBackButtonStyles( button : Button ) : void { this.setButtonStyles( button ); var icon : ImageSkin = new ImageSkin( this.backButtonUpIconTexture ); icon.disabledTexture = this.backButtonDisabledIconTexture; button.defaultIcon = icon; button.iconPosition = RelativePosition.LEFT_BASELINE; } protected function setForwardButtonStyles( button : Button ) : void { this.setButtonStyles( button ); var icon : ImageSkin = new ImageSkin( this.forwardButtonUpIconTexture ); icon.disabledTexture = this.forwardButtonDisabledIconTexture; button.defaultIcon = icon; button.iconPosition = RelativePosition.RIGHT_BASELINE; } protected function setButtonLabelStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.defaultTextFormat; textRenderer.disabledTextFormat = this.disabledTextFormat; } //------------------------- // ButtonGroup //------------------------- protected function setButtonGroupStyles( group : ButtonGroup ) : void { group.gap = this.smallGutterSize; } //------------------------- // Callout //------------------------- protected function setCalloutStyles( callout : Callout ) : void { var backgroundSkin : Image = new Image( this.panelBorderBackgroundSkinTexture ); backgroundSkin.scale9Grid = PANEL_BORDER_SCALE_9_GRID; callout.backgroundSkin = backgroundSkin; var arrowSkin : Quad = new Quad( this.gutterSize, this.gutterSize, 0xff00ff ); arrowSkin.alpha = 0; callout.topArrowSkin = callout.rightArrowSkin = callout.bottomArrowSkin = callout.leftArrowSkin = arrowSkin; callout.paddingTop = this.smallGutterSize; callout.paddingBottom = this.smallGutterSize; callout.paddingRight = this.gutterSize; callout.paddingLeft = this.gutterSize; } //------------------------- // Drawers //------------------------- protected function setDrawersStyles( drawers : Drawers ) : void { var overlaySkin : Quad = new Quad( 10, 10, MODAL_OVERLAY_COLOR ); overlaySkin.alpha = MODAL_OVERLAY_ALPHA; drawers.overlaySkin = overlaySkin; } //------------------------- // Label //------------------------- protected function setLabelTextRendererStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.defaultTextFormat; textRenderer.disabledTextFormat = this.disabledTextFormat; } protected function setHeadingLabelStyles( label : Label ) : void { label.customTextRendererStyleName = THEME_STYLE_NAME_HEADING_LABEL_TEXT_RENDERER; } protected function setHeadingLabelTextRendererStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.headingTextFormat; textRenderer.disabledTextFormat = this.headingDisabledTextFormat; } protected function setDetailLabelStyles( label : Label ) : void { label.customTextRendererStyleName = THEME_STYLE_NAME_DETAIL_LABEL_TEXT_RENDERER; } protected function setDetailLabelTextRendererStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.detailTextFormat; textRenderer.disabledTextFormat = this.detailDisabledTextFormat; } protected function setToolTipLabelStyles( label : Label ) : void { var backgroundSkin : Image = new Image( this.toolTipBackgroundSkinTexture ); backgroundSkin.scale9Grid = TOOL_TIP_SCALE_9_GRID; label.backgroundSkin = backgroundSkin; label.customTextRendererStyleName = THEME_STYLE_NAME_TOOL_TIP_LABEL_TEXT_RENDERER; label.paddingTop = this.extraSmallGutterSize; label.paddingRight = this.smallGutterSize + this.leftAndRightDropShadowSize; label.paddingBottom = this.extraSmallGutterSize + this.bottomDropShadowSize; label.paddingLeft = this.smallGutterSize + this.leftAndRightDropShadowSize; } protected function setToolTipLabelTextRendererStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.defaultTextFormat; textRenderer.disabledTextFormat = this.disabledTextFormat; } //------------------------- // LayoutGroup //------------------------- protected function setToolbarLayoutGroupStyles( group : LayoutGroup ) : void { if ( !group.layout ) { var layout : HorizontalLayout = new HorizontalLayout(); layout.paddingTop = this.extraSmallGutterSize; layout.paddingBottom = this.extraSmallGutterSize; layout.paddingRight = this.smallGutterSize; layout.paddingLeft = this.smallGutterSize; layout.gap = this.smallGutterSize; layout.verticalAlign = VerticalAlign.MIDDLE; group.layout = layout; } group.minHeight = this.gridSize; var backgroundSkin : Image = new Image( this.headerBackgroundSkinTexture ); backgroundSkin.scale9Grid = HEADER_SCALE_9_GRID; group.backgroundSkin = backgroundSkin; } //------------------------- // List //------------------------- // protected function setListStyles( list : List ) : void // { // this.setScrollerStyles( list ); // // list.verticalScrollPolicy = ScrollPolicy.AUTO; // // var backgroundSkin : Image = new Image( this.simpleBorderBackgroundSkinTexture ); // backgroundSkin.scale9Grid = SIMPLE_BORDER_SCALE_9_GRID; // list.backgroundSkin = backgroundSkin; // // list.padding = this.borderSize; // } protected function setItemRendererStyles( itemRenderer : BaseDefaultItemRenderer ) : void { var skin : ImageSkin = new ImageSkin( this.itemRendererUpSkinTexture ); skin.selectedTexture = this.itemRendererSelectedUpSkinTexture; skin.setTextureForState( ButtonState.HOVER, this.itemRendererHoverSkinTexture ); skin.setTextureForState( ButtonState.DOWN, this.itemRendererSelectedUpSkinTexture ); itemRenderer.defaultSkin = skin; itemRenderer.horizontalAlign = HorizontalAlign.LEFT; itemRenderer.iconPosition = RelativePosition.LEFT; itemRenderer.accessoryPosition = RelativePosition.RIGHT; itemRenderer.paddingTop = this.extraSmallGutterSize; itemRenderer.paddingBottom = this.extraSmallGutterSize; itemRenderer.paddingRight = this.smallGutterSize; itemRenderer.paddingLeft = this.smallGutterSize; itemRenderer.gap = this.extraSmallGutterSize; itemRenderer.minGap = this.extraSmallGutterSize; itemRenderer.accessoryGap = Number.POSITIVE_INFINITY; itemRenderer.minAccessoryGap = this.smallGutterSize; itemRenderer.minWidth = this.controlSize; itemRenderer.minHeight = this.controlSize; itemRenderer.useStateDelayTimer = false; } protected function setDrillDownItemRendererStyles( itemRenderer : BaseDefaultItemRenderer ) : void { this.setItemRendererStyles( itemRenderer ); itemRenderer.itemHasAccessory = false; var defaultAccessory : ImageLoader = new ImageLoader(); defaultAccessory.source = this.listDrillDownAccessoryTexture; itemRenderer.defaultAccessory = defaultAccessory; } /* protected function setCheckItemRendererStyles( itemRenderer : BaseDefaultItemRenderer ) : void { itemRenderer.defaultSkin = new Image( this.itemRendererUpSkinTexture ); itemRenderer.itemHasIcon = false; var icon : ImageSkin = new ImageSkin( this.checkUpIconTexture ); icon.selectedTexture = this.checkSelectedUpIconTexture; icon.setTextureForState( ButtonState.HOVER, this.checkHoverIconTexture ); icon.setTextureForState( ButtonState.DOWN, this.checkDownIconTexture ); icon.setTextureForState( ButtonState.DISABLED, this.checkDisabledIconTexture ); icon.setTextureForState( ButtonState.HOVER_AND_SELECTED, this.checkSelectedHoverIconTexture ); icon.setTextureForState( ButtonState.DOWN_AND_SELECTED, this.checkSelectedDownIconTexture ); icon.setTextureForState( ButtonState.DISABLED_AND_SELECTED, this.checkSelectedDisabledIconTexture ); itemRenderer.defaultIcon = icon; itemRenderer.horizontalAlign = HorizontalAlign.LEFT; itemRenderer.iconPosition = RelativePosition.LEFT; itemRenderer.accessoryPosition = RelativePosition.RIGHT; itemRenderer.paddingTop = this.extraSmallGutterSize; itemRenderer.paddingBottom = this.extraSmallGutterSize; itemRenderer.paddingRight = this.smallGutterSize; itemRenderer.paddingLeft = this.smallGutterSize; itemRenderer.gap = this.smallGutterSize; itemRenderer.minGap = this.smallGutterSize; itemRenderer.accessoryGap = Number.POSITIVE_INFINITY; itemRenderer.minAccessoryGap = this.smallGutterSize; itemRenderer.minWidth = this.controlSize; itemRenderer.minHeight = this.controlSize; itemRenderer.useStateDelayTimer = false; } */ protected function setItemRendererLabelStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.defaultTextFormat; textRenderer.disabledTextFormat = this.disabledTextFormat; } protected function setItemRendererAccessoryLabelStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.defaultTextFormat; textRenderer.disabledTextFormat = this.disabledTextFormat; } protected function setItemRendererIconLabelStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.defaultTextFormat; textRenderer.disabledTextFormat = this.disabledTextFormat; } //------------------------- // ProgressBar //------------------------- protected function setProgressBarStyles( progress : ProgressBar ) : void { var backgroundSkin : Image = new Image( this.simpleBorderBackgroundSkinTexture ); backgroundSkin.scale9Grid = SIMPLE_BORDER_SCALE_9_GRID; if ( progress.direction == Direction.VERTICAL ) { backgroundSkin.height = this.wideControlSize; } else { backgroundSkin.width = this.wideControlSize; } progress.backgroundSkin = backgroundSkin; var fillSkin : Image = new Image( this.progressBarFillSkinTexture ); if ( progress.direction == Direction.VERTICAL ) { fillSkin.height = 0; } else { fillSkin.width = 0; } progress.fillSkin = fillSkin; progress.padding = this.borderSize; } //------------------------- // Radio //------------------------- protected function setRadioStyles( radio : Radio ) : void { var icon : ImageSkin = new ImageSkin( this.radioUpIconTexture ); icon.selectedTexture = this.radioSelectedUpIconTexture; icon.setTextureForState( ButtonState.HOVER, this.radioHoverIconTexture ); icon.setTextureForState( ButtonState.DOWN, this.radioDownIconTexture ); icon.setTextureForState( ButtonState.DISABLED, this.radioDisabledIconTexture ); icon.setTextureForState( ButtonState.HOVER_AND_SELECTED, this.radioSelectedHoverIconTexture ); icon.setTextureForState( ButtonState.DOWN_AND_SELECTED, this.radioSelectedDownIconTexture ); icon.setTextureForState( ButtonState.DISABLED_AND_SELECTED, this.radioSelectedDisabledIconTexture ); radio.defaultIcon = icon; var focusIndicatorSkin : Image = new Image( this.focusIndicatorSkinTexture ); focusIndicatorSkin.scale9Grid = FOCUS_INDICATOR_SCALE_9_GRID; radio.focusIndicatorSkin = focusIndicatorSkin; radio.focusPadding = -2; radio.horizontalAlign = HorizontalAlign.LEFT; radio.verticalAlign = VerticalAlign.MIDDLE; radio.gap = this.smallGutterSize; radio.minWidth = this.controlSize; radio.minHeight = this.controlSize; } protected function setRadioLabelStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.defaultTextFormat; textRenderer.disabledTextFormat = this.disabledTextFormat; } //------------------------- // ScrollBar //------------------------- protected function setHorizontalScrollBarStyles( scrollBar : ScrollBar ) : void { scrollBar.trackLayoutMode = TrackLayoutMode.SINGLE; scrollBar.customIncrementButtonStyleName = THEME_STYLE_NAME_HORIZONTAL_SCROLL_BAR_INCREMENT_BUTTON; scrollBar.customDecrementButtonStyleName = THEME_STYLE_NAME_HORIZONTAL_SCROLL_BAR_DECREMENT_BUTTON; scrollBar.customThumbStyleName = THEME_STYLE_NAME_HORIZONTAL_SCROLL_BAR_THUMB; scrollBar.customMinimumTrackStyleName = THEME_STYLE_NAME_HORIZONTAL_SCROLL_BAR_MINIMUM_TRACK; scrollBar.minHeight = smallScrollBarSize; } protected function setVerticalScrollBarStyles( scrollBar : ScrollBar ) : void { scrollBar.trackLayoutMode = TrackLayoutMode.SINGLE; scrollBar.minWidth = smallScrollBarSize; scrollBar.customIncrementButtonStyleName = THEME_STYLE_NAME_VERTICAL_SCROLL_BAR_INCREMENT_BUTTON; scrollBar.customDecrementButtonStyleName = THEME_STYLE_NAME_VERTICAL_SCROLL_BAR_DECREMENT_BUTTON; scrollBar.customThumbStyleName = THEME_STYLE_NAME_VERTICAL_SCROLL_BAR_THUMB; scrollBar.customMinimumTrackStyleName = THEME_STYLE_NAME_VERTICAL_SCROLL_BAR_MINIMUM_TRACK; } protected function setHorizontalScrollBarIncrementButtonStyles( button : Button ) : void { var skin : ImageSkin = new ImageSkin( this.hScrollBarStepButtonUpSkinTexture ); skin.setTextureForState( ButtonState.HOVER, this.hScrollBarStepButtonHoverSkinTexture ); skin.setTextureForState( ButtonState.DOWN, this.hScrollBarStepButtonDownSkinTexture ); skin.setTextureForState( ButtonState.DISABLED, this.hScrollBarStepButtonDisabledSkinTexture ); skin.scale9Grid = HORIZONTAL_SCROLL_BAR_STEP_BUTTON_SCALE_9_GRID; skin.batchable = false; button.defaultSkin = skin; var defaultIcon : Image = new Image( this.hScrollBarIncrementButtonIconTexture ); defaultIcon.batchable = false; button.defaultIcon = defaultIcon; var incrementButtonDisabledIcon : Quad = new Quad( 1, 1, 0xff00ff ); incrementButtonDisabledIcon.alpha = 0; button.disabledIcon = incrementButtonDisabledIcon; button.hasLabelTextRenderer = false; button.minHeight = smallScrollBarSize; } protected function setHorizontalScrollBarDecrementButtonStyles( button : Button ) : void { var skin : ImageSkin = new ImageSkin( hScrollBarStepButtonUpSkinTexture ); skin.setTextureForState( ButtonState.HOVER, this.hScrollBarStepButtonHoverSkinTexture ); skin.setTextureForState( ButtonState.DOWN, this.hScrollBarStepButtonDownSkinTexture ); skin.setTextureForState( ButtonState.DISABLED, this.hScrollBarStepButtonDisabledSkinTexture ); skin.scale9Grid = HORIZONTAL_SCROLL_BAR_STEP_BUTTON_SCALE_9_GRID; skin.batchable = false; button.defaultSkin = skin; var defaultIcon : Image = new Image( this.hScrollBarDecrementButtonIconTexture ); defaultIcon.batchable = false; button.defaultIcon = defaultIcon; var decrementButtonDisabledIcon : Quad = new Quad( 1, 1, 0xff00ff ); decrementButtonDisabledIcon.alpha = 0; button.disabledIcon = decrementButtonDisabledIcon; button.hasLabelTextRenderer = false; button.minHeight = smallScrollBarSize; } protected function setHorizontalScrollBarThumbStyles( thumb : Button ) : void { var skin : ImageSkin = new ImageSkin( this.hScrollBarThumbUpSkinTexture ); skin.setTextureForState( ButtonState.HOVER, this.hScrollBarThumbHoverSkinTexture ); skin.setTextureForState( ButtonState.DOWN, this.hScrollBarThumbDownSkinTexture ); skin.scale9Grid = HORIZONTAL_SCROLL_BAR_THUMB_SCALE_9_GRID; skin.batchable = false; thumb.defaultSkin = skin; thumb.defaultIcon = new Image( this.hScrollBarThumbIconTexture ); thumb.verticalAlign = VerticalAlign.MIDDLE; thumb.paddingBottom = this.extraSmallGutterSize; thumb.hasLabelTextRenderer = false; thumb.minHeight = smallScrollBarSize; } protected function setHorizontalScrollBarMinimumTrackStyles( track : Button ) : void { var defaultSkin : Image = new Image( this.hScrollBarTrackSkinTexture ); defaultSkin.scale9Grid = HORIZONTAL_SCROLL_BAR_TRACK_SCALE_9_GRID; track.defaultSkin = defaultSkin; track.hasLabelTextRenderer = false; track.minHeight = smallScrollBarSize; } protected function setVerticalScrollBarIncrementButtonStyles( button : Button ) : void { var skin : ImageSkin = new ImageSkin( this.vScrollBarStepButtonUpSkinTexture ); skin.setTextureForState( ButtonState.HOVER, this.vScrollBarStepButtonHoverSkinTexture ); skin.setTextureForState( ButtonState.DOWN, this.vScrollBarStepButtonDownSkinTexture ); skin.setTextureForState( ButtonState.DISABLED, this.vScrollBarStepButtonDisabledSkinTexture ); skin.scale9Grid = VERTICAL_SCROLL_BAR_STEP_BUTTON_SCALE_9_GRID; skin.batchable = false; button.defaultSkin = skin; var defaultIcon : Image = new Image( this.vScrollBarIncrementButtonIconTexture ); defaultIcon.batchable = false; button.defaultIcon = defaultIcon; var incrementButtonDisabledIcon : Quad = new Quad( 1, 1, 0xff00ff ); incrementButtonDisabledIcon.alpha = 0; button.disabledIcon = incrementButtonDisabledIcon; button.hasLabelTextRenderer = false; button.minWidth = smallScrollBarSize; } protected function setVerticalScrollBarDecrementButtonStyles( button : Button ) : void { var skin : ImageSkin = new ImageSkin( this.vScrollBarStepButtonUpSkinTexture ); skin.setTextureForState( ButtonState.HOVER, this.vScrollBarStepButtonHoverSkinTexture ); skin.setTextureForState( ButtonState.DOWN, this.vScrollBarStepButtonDownSkinTexture ); skin.setTextureForState( ButtonState.DISABLED, this.vScrollBarStepButtonDisabledSkinTexture ); skin.scale9Grid = VERTICAL_SCROLL_BAR_STEP_BUTTON_SCALE_9_GRID; skin.batchable = false; button.defaultSkin = skin; var defaultIcon : Image = new Image( this.vScrollBarDecrementButtonIconTexture ); defaultIcon.batchable = false; button.defaultIcon = defaultIcon; var decrementButtonDisabledIcon : Quad = new Quad( 1, 1, 0xff00ff ); decrementButtonDisabledIcon.alpha = 0; button.disabledIcon = decrementButtonDisabledIcon; button.hasLabelTextRenderer = false; button.minWidth = smallScrollBarSize; } protected function setVerticalScrollBarThumbStyles( thumb : Button ) : void { var skin : ImageSkin = new ImageSkin( this.vScrollBarThumbUpSkinTexture ); skin.setTextureForState( ButtonState.HOVER, this.vScrollBarThumbUpSkinTexture ); skin.setTextureForState( ButtonState.DOWN, this.vScrollBarThumbUpSkinTexture ); skin.scale9Grid = VERTICAL_SCROLL_BAR_THUMB_SCALE_9_GRID; skin.batchable = false; thumb.defaultSkin = skin; // thumb.defaultIcon = new Image(this.vScrollBarThumbIconTexture); thumb.horizontalAlign = HorizontalAlign.CENTER; thumb.paddingRight = this.extraSmallGutterSize; thumb.hasLabelTextRenderer = false; thumb.minWidth = smallScrollBarSize; } protected function setVerticalScrollBarMinimumTrackStyles( track : Button ) : void { var defaultSkin : Image = new Image( this.vScrollBarTrackSkinTexture ); defaultSkin.scale9Grid = VERTICAL_SCROLL_BAR_TRACK_SCALE_9_GRID; defaultSkin.batchable = false; track.defaultSkin = defaultSkin; track.hasLabelTextRenderer = false; track.minWidth = smallScrollBarSize; } //------------------------- // ScrollContainer //------------------------- protected function setScrollContainerStyles( container : ScrollContainer ) : void { this.setScrollerStyles( container ); } protected function setToolbarScrollContainerStyles( container : ScrollContainer ) : void { this.setScrollerStyles( container ); if ( !container.layout ) { var layout : HorizontalLayout = new HorizontalLayout(); layout.paddingTop = this.extraSmallGutterSize; layout.paddingBottom = this.extraSmallGutterSize; layout.paddingRight = this.smallGutterSize; layout.paddingLeft = this.smallGutterSize; layout.gap = this.extraSmallGutterSize; layout.verticalAlign = VerticalAlign.MIDDLE; container.layout = layout; } var backgroundSkin : Image = new Image( this.headerBackgroundSkinTexture ); backgroundSkin.scale9Grid = HEADER_SCALE_9_GRID; container.backgroundSkin = backgroundSkin; container.minHeight = this.gridSize; } //------------------------- // ScrollScreen //------------------------- protected function setScrollScreenStyles( screen : ScrollScreen ) : void { this.setScrollerStyles( screen ); } //------------------------- // ScrollText //------------------------- protected function setScrollTextStyles( text : ScrollText ) : void { this.setScrollerStyles( text ); text.textFormat = this.defaultScrollTextFormat; text.disabledTextFormat = this.disabledTextFormat; text.padding = this.gutterSize; } //------------------------- // SimpleScrollBar //------------------------- protected function setHorizontalSimpleScrollBarStyles( scrollBar : SimpleScrollBar ) : void { scrollBar.customThumbStyleName = THEME_STYLE_NAME_HORIZONTAL_SIMPLE_SCROLL_BAR_THUMB; } protected function setVerticalSimpleScrollBarStyles( scrollBar : SimpleScrollBar ) : void { scrollBar.customThumbStyleName = THEME_STYLE_NAME_VERTICAL_SIMPLE_SCROLL_BAR_THUMB; } protected function setHorizontalSimpleScrollBarThumbStyles( thumb : Button ) : void { var skin : ImageSkin = new ImageSkin( this.hScrollBarThumbUpSkinTexture ); skin.setTextureForState( ButtonState.HOVER, this.hScrollBarThumbHoverSkinTexture ); skin.setTextureForState( ButtonState.DOWN, this.hScrollBarThumbDownSkinTexture ); skin.scale9Grid = HORIZONTAL_SCROLL_BAR_THUMB_SCALE_9_GRID; thumb.defaultSkin = skin; thumb.defaultIcon = new Image( this.hScrollBarThumbIconTexture ); thumb.verticalAlign = VerticalAlign.TOP; thumb.paddingTop = this.smallGutterSize; thumb.hasLabelTextRenderer = false; } protected function setVerticalSimpleScrollBarThumbStyles( thumb : Button ) : void { var skin : ImageSkin = new ImageSkin( this.vScrollBarThumbUpSkinTexture ); skin.setTextureForState( ButtonState.HOVER, this.vScrollBarThumbHoverSkinTexture ); skin.setTextureForState( ButtonState.DOWN, this.vScrollBarThumbDownSkinTexture ); skin.scale9Grid = VERTICAL_SCROLL_BAR_THUMB_SCALE_9_GRID; thumb.defaultSkin = skin; thumb.defaultIcon = new Image( this.vScrollBarThumbIconTexture ); thumb.horizontalAlign = HorizontalAlign.LEFT; thumb.paddingLeft = this.smallGutterSize; thumb.hasLabelTextRenderer = false; } //------------------------- // TextArea //------------------------- protected function setTextAreaStyles( textArea : TextArea ) : void { this.setScrollerStyles( textArea ); textArea.focusPadding = -2; textArea.padding = this.borderSize; // var skin:ImageSkin = new ImageSkin(this.textInputBackgroundEnabledSkinTexture); // skin.disabledTexture = this.textInputBackgroundDisabledSkinTexture; // skin.scale9Grid = TEXT_INPUT_SCALE_9_GRID; // skin.width = this.wideControlSize * 2; // skin.height = this.wideControlSize; // textArea.backgroundSkin = skin; } protected function setTextAreaTextEditorStyles( textEditor : TextFieldTextEditorViewPort ) : void { textEditor.textFormat = this.defaultTextFormat; textEditor.disabledTextFormat = this.disabledTextFormat; textEditor.paddingTop = this.extraSmallGutterSize; textEditor.paddingRight = this.smallGutterSize; textEditor.paddingBottom = this.extraSmallGutterSize; textEditor.paddingLeft = this.smallGutterSize; } //------------------------- // TextCallout //------------------------- protected function setTextCalloutStyles( callout : TextCallout ) : void { this.setCalloutStyles( callout ); } protected function setTextCalloutTextRendererStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.defaultTextFormat; } //------------------------- // TextInput //------------------------- protected function setBaseTextInputStyles( input : TextInput ) : void { var skin : ImageSkin = new ImageSkin( this.textInputBackgroundEnabledSkinTexture ); skin.disabledTexture = this.textInputBackgroundDisabledSkinTexture; skin.scale9Grid = TEXT_INPUT_SCALE_9_GRID; skin.width = this.wideControlSize; skin.height = this.controlSize; input.backgroundSkin = skin; var focusIndicatorSkin : Image = new Image( this.focusIndicatorSkinTexture ); focusIndicatorSkin.scale9Grid = FOCUS_INDICATOR_SCALE_9_GRID; input.focusIndicatorSkin = focusIndicatorSkin; input.focusPadding = -2; input.minWidth = this.controlSize; input.minHeight = this.controlSize; input.gap = this.extraSmallGutterSize; input.paddingTop = this.extraSmallGutterSize; input.paddingBottom = this.extraSmallGutterSize; input.paddingRight = this.smallGutterSize; input.paddingLeft = this.smallGutterSize; } protected function setTextInputStyles( input : TextInput ) : void { this.setBaseTextInputStyles( input ); } protected function setSearchTextInputStyles( input : TextInput ) : void { this.setBaseTextInputStyles( input ); var icon : ImageSkin = new ImageSkin( this.textInputSearchIconTexture ); icon.disabledTexture = this.textInputSearchIconDisabledTexture; input.defaultIcon = icon; } protected function setTextInputTextEditorStyles( textEditor : TextFieldTextEditor ) : void { textEditor.textFormat = this.defaultTextFormat; textEditor.disabledTextFormat = this.disabledTextFormat; } protected function setTextInputPromptStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.defaultTextFormat; textRenderer.disabledTextFormat = this.disabledTextFormat; } //------------------------- // ToggleSwitch //------------------------- protected function setToggleSwitchStyles( toggle : ToggleSwitch ) : void { toggle.trackLayoutMode = TrackLayoutMode.SINGLE; toggle.labelAlign = ToggleSwitch.LABEL_ALIGN_MIDDLE; var focusIndicatorSkin : Image = new Image( this.focusIndicatorSkinTexture ); focusIndicatorSkin.scale9Grid = FOCUS_INDICATOR_SCALE_9_GRID; toggle.focusIndicatorSkin = focusIndicatorSkin; toggle.focusPadding = -1; } protected function setToggleSwitchOnLabelStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.defaultTextFormat; textRenderer.disabledTextFormat = this.disabledTextFormat; } protected function setToggleSwitchOffLabelStyles( textRenderer : TextFieldTextRenderer ) : void { textRenderer.textFormat = this.defaultTextFormat; textRenderer.disabledTextFormat = this.disabledTextFormat; } protected function setToggleSwitchOnTrackStyles( track : Button ) : void { var defaultSkin : Image = new Image( this.toggleButtonSelectedUpSkinTexture ); defaultSkin.scale9Grid = BUTTON_SCALE_9_GRID; defaultSkin.width = 2 * this.controlSize + this.smallControlSize; track.defaultSkin = defaultSkin; track.hasLabelTextRenderer = false; } protected function setToggleSwitchThumbStyles( thumb : Button ) : void { this.setButtonStyles( thumb ); thumb.width = this.controlSize; thumb.height = this.controlSize; thumb.hasLabelTextRenderer = false; } /** * @private */ protected function initializeTextureAtlas() : void { var atlasBitmapData : ByteArray = new ATLAS_BITMAP(); var atlasTexture : Texture = Texture.fromAtfData( atlasBitmapData, ATLAS_SCALE_FACTOR, false ); atlasTexture.root.onRestore = this.atlasTexture_onRestore; this.atlas = new TextureAtlas( atlasTexture, XML( new ATLAS_XML())); } /** * @private */ protected function atlasTexture_onRestore() : void { var atlasBitmapData : ByteArray = new ATLAS_BITMAP(); this.atlas.texture.root.uploadAtfData( atlasBitmapData ); } } }
goto *skip_module ;----------------------------------------------------------------- #deffunc gppost_setup int _p1 ; ポストエフェクト初期化 postid = _p1 postid_max = 10 postname="None" post_prmsub = *setup_postsub sx=ginfo_sx:sy=ginfo_sy if postid=0 : gosub *setup_none if postid=1 : gosub *setup_crt if postid=2 : gosub *setup_contrast if postid=3 : gosub *setup_blur2 if postid=4 : gosub *setup_mosaic if postid=5 : gosub *setup_sobel if postid=6 : gosub *setup_oldfilm if postid=7 : gosub *setup_glow if postid=8 : gosub *setup_sepia if postid=9 : gosub *setup_gray gsel 0 return #deffunc gppost_exec ; ポストエフェクト実行 ; gosub post_prmsub ; ポストエフェクト描画開始 return *setup_postsub return *exec_copybuf ; buffer1 -> メイン画面にシェーダー描画 gsel 0 redraw 0 ; 描画開始 pos 0,0:gmode 0 celput 1 return *setup_none ; フィルターなし buffer 1,sx,sy,screen_offscreen post_prmsub = *exec_copybuf return *setup_sepia ; セピアフィルター postname="Sepia Filter" gpusershader "res/shaders/sprite.vert", "res/shaders/p_sepia.frag", "" buffer 1,sx,sy,screen_offscreen + screen_usergcopy post_prmsub = *exec_copybuf return *setup_gray ; 白黒フィルター postname="Gray Filter" gpusershader "res/shaders/sprite.vert", "res/shaders/p_grayscale.frag", "" buffer 1,sx,sy,screen_offscreen + screen_usergcopy post_prmsub = *exec_copybuf return *setup_crt ; ブラウン管フィルター postname="CRT Filter" celload "res/crtmask.png",4 ; オーバーレイ画像 gpusershader "res/shaders/sprite.vert", "res/shaders/p_crtmonitor.frag", "" buffer 1,sx/2,sy/2,screen_offscreen + screen_usergcopy post_prmsub = *exec_crt gpgetmat crt_mat, 1, GPGETMAT_OPT_SCRMAT crt_curvex=0.5 ; X方向の湾曲率 crt_curvey=0.4 ; Y方向の湾曲率 gpmatprm1 crt_mat, "u_curvex", crt_curvex gpmatprm1 crt_mat, "u_curvey", crt_curvey return *exec_crt ; buffer1 -> メイン画面にシェーダー描画 gsel 0 redraw 0 ; 描画開始 pos 0,0:gmode 0 gzoom sx,sy,1,0,0,sx/2,sy/2 ;gosub *exec_copybuf ; オーバーレイを描画 pos 0,0:gmode 1 celput 4 return *setup_contrast ; コントラストフィルター postname="Contrast Filter" gpusershader "res/shaders/sprite.vert", "res/shaders/p_contrast.frag", "" buffer 1,sx,sy,screen_offscreen + screen_usergcopy post_prmsub = *exec_copybuf gpgetmat cont_mat, 1, GPGETMAT_OPT_SCRMAT contrast_level=2.0 contrast_bright=-0.2 gpmatprm1 cont_mat, "u_contrast", contrast_level gpmatprm1 cont_mat, "u_brightness", contrast_bright return *setup_blur2 ; ガウスぼかしフィルター postname="Blur Filter" gpusershader "res/shaders/p_blur2.vert", "res/shaders/p_blur2.frag", "" buffer 1,sx,sy,screen_offscreen + screen_usergcopy gpusershader "res/shaders/p_blur2.vert", "res/shaders/p_blur2.frag", "" ;gpusershader "res/shaders/sprite.vert", "res/shaders/p_blur.frag", "" buffer 2,sx,sy,screen_offscreen + screen_usergcopy post_prmsub = *exec_blur2 gpgetmat blur_mat, 1, GPGETMAT_OPT_SCRMAT gpgetmat blur_mat2, 2, GPGETMAT_OPT_SCRMAT blur_level=6.0 ; ぼかし強度(1.0~10.0程度) blur_stepx=1.0/sx blur_stepy=1.0/sy gpmatprm1 blur_mat2, "u_length", 0.0 gpmatprm1 blur_mat2, "u_length2", blur_level return *exec_blur2 ; パラメーター更新 dd=blur_level *exec_blur_loop ; buffer1 -> buffer2にコピー gpmatprm1 blur_mat, "u_length", blur_stepx*dd gpmatprm1 blur_mat, "u_length2", 0.0 gsel 2:redraw 0:pos 0,0:gmode 0:celput 1:redraw 1 dd-=1.0 if dd<=1.0 : goto *exec_blur_done ; buffer2 -> buffer1にコピー gpmatprm1 blur_mat2, "u_length", 0.0 gpmatprm1 blur_mat2, "u_length2", blur_stepy*dd gsel 1:redraw 0:pos 0,0:gmode 0:celput 2:redraw 1 dd-=1.0 if dd<=1.0 : goto *exec_blur_done2 goto *exec_blur_loop *exec_blur_done2 ; buffer1 -> buffer0にコピー gpmatprm1 blur_mat, "u_length", blur_stepx*dd gpmatprm1 blur_mat, "u_length2", 0.0 gsel 0:redraw 0:pos 0,0:gmode 0:celput 1 return *exec_blur_done ; buffer2 -> buffer0にコピー gpmatprm1 blur_mat2, "u_length", 0.0 gpmatprm1 blur_mat2, "u_length2", blur_stepy*dd gsel 0:redraw 0:pos 0,0:gmode 0:celput 2 return *setup_mosaic ; モザイクフィルター postname="Mosaic Filter" gpusershader "res/shaders/sprite.vert", "res/shaders/p_mosaic.frag", "" buffer 1,sx,sy,screen_offscreen + screen_usergcopy post_prmsub = *exec_copybuf return *setup_sobel ; 輪郭抽出フィルター postname="Sobel Filter" gpusershader "res/shaders/sprite.vert", "res/shaders/p_sobel.frag", "" buffer 1,sx,sy,screen_offscreen + screen_usergcopy post_prmsub = *exec_copybuf gpgetmat sobel_mat, 1, GPGETMAT_OPT_SCRMAT gpmatprm1 sobel_mat, "u_width", 1.0/sx/2 gpmatprm1 sobel_mat, "u_height", 1.0/sy/2 return *setup_oldfilm ; 古いフィルムフィルター postname="Old Film Filter" gpusershader "res/shaders/sprite.vert", "res/shaders/p_oldfilm.frag", "" buffer 1,sx,sy,screen_offscreen + screen_usergcopy post_prmsub = *exec_oldfilm gpgetmat oldfilm_mat, 1, GPGETMAT_OPT_SCRMAT gpmatprm1 oldfilm_mat, "u_sepiaValue", 0.8 gpmatprm1 oldfilm_mat, "u_noiseValue", 0.4 gpmatprm1 oldfilm_mat, "u_scratchValue", 0.4 gpmatprm1 oldfilm_mat, "u_innerVignetting", 0.9 gpmatprm1 oldfilm_mat, "u_outerVignetting", 0.9 return *exec_oldfilm ; パラメーター更新 getreq etime,SYSREQ_TIMER gpmatprm1 oldfilm_mat, "u_elapsedTime", etime dd=double(rnd(32768)) gpmatprm1 oldfilm_mat, "u_random", dd / 32768 gosub *exec_copybuf return *setup_glow ; グローフィルター postname="Glow Filter" buffer 1,sx,sy,screen_offscreen gpusershader "res/shaders/sprite.vert", "res/shaders/p_blur.frag", "" buffer 2,sx/2,sy/2,screen_offscreen + screen_usergcopy post_prmsub = *exec_glow gpgetmat glow_mat, 2, GPGETMAT_OPT_SCRMAT glow_base=1.0/sx*2 gpmatprm1 glow_mat, "u_length", glow_base return *exec_glow ; buffer1 -> buffer2に縮小してコピー gsel 2 redraw 0 pos 0,0:gmode 0 gzoom sx/2,sy/2, 1, 0,0, sx,sy redraw 1 ; buffer1と2を合成して描画 gsel 0 redraw 0 ; 描画開始 pos 0,0:gmode 1,,,128 gzoom sx,sy, 2, 0,0, sx/2,sy/2 pos 0,0:gmode 5,,,128 celput 1 return ;----------------------------------------------------------------- *skip_module
package org.ffilmation.engine.events { // Imports import flash.events.* /** * <p>The fProcessEvent event class stores information about a process event.</p> * * <p>Several processes in the filmation engine involve more than one subprocess, * and this class stores info about the overall task that is being monitored as * well as the status of the current subtask.</p> * * <p>This allows to have progress bars that go something like:</p> * * Loading media file A. 20% done<br> * Overall loading process: 12% done * */ public class fProcessEvent extends Event { // Public /** * Overall process completion status, from 0 to 100 */ public var overall:Number /** * Overall process description */ public var overallDescription:String /** * Current process completion status, from 0 to 100 */ public var current:Number /** * Current process description */ public var currentDescription:String /** * A boolean value indicating if the overall process is considered done ( same as checking overall = 100 ) */ public var complete:Boolean // Constructor /** * Constructor for the fProcessEvent class. * * @param type The type of the event. Event listeners can access this information through the inherited type property. * * @param overall Overall process completion status, from 0 to 100 * * @param overallDescription Overall process desccription * * @param current Cverall process completion status, from 0 to 100 * * @param currentDescription Cverall process desccription * */ function fProcessEvent(type:String,overall:Number,overallDescription:String,current:Number,currentDescription:String):void { super(type) this.overall = overall this.overallDescription = overallDescription this.current = current this.currentDescription = currentDescription this.complete = overall == 100 } } }
package kabam.rotmg.death.view { import flash.display.BitmapData; import kabam.rotmg.death.control.HandleNormalDeathSignal; import kabam.rotmg.death.model.DeathModel; import kabam.rotmg.dialogs.control.CloseDialogsSignal; import robotlegs.bender.bundles.mvcs.Mediator; public class ZombifyDialogMediator extends Mediator { public function ZombifyDialogMediator() { super(); } [Inject] public var view:ZombifyDialog; [Inject] public var closeDialogs:CloseDialogsSignal; [Inject] public var handleDeath:HandleNormalDeathSignal; [Inject] public var death:DeathModel; override public function initialize():void { this.view.closed.addOnce(this.onClosed); } private function onClosed():void { var _local1:* = null; _local1 = this.death.getLastDeath(); var _local2:BitmapData = new BitmapData(this.view.stage.width, this.view.stage.height, true, 0); _local2.draw(this.view.stage); _local1.background = _local2; this.closeDialogs.dispatch(); this.handleDeath.dispatch(_local1); } } }
package org.w3c.css.sac { // http://www.w3.org/Style/CSS/SAC/doc/org/w3c/css/sac/SelectorFactory.html /** * @see SelectorTypes * @see ISelector */ public interface ISelectorFactory { /** * Creates an any node selector. * @throws ICSSException If this selector is not supported. * @returns the any node selector. * @see SelectorTypes#SAC_ANY_NODE_SELECTOR */ function createAnyNodeSelector():ISimpleSelector; /** * Creates a cdata section node selector. * @param data the data * @throws ICSSException If this selector is not supported. * @returns the cdata section node selector * @see SelectorTypes#SAC_CDATA_SECTION_NODE_SELECTOR */ function createCDataSectionSelector( data:String ):ICharacterDataSelector; /** * Creates a child selector. * @param parent the parent selector * @param child the child selector * @throws ICSSException If this selector is not supported. * @returns the combinator selector. * @see SelectorTypes#SAC_CHILD_SELECTOR */ function createChildSelector( parent:ISelector, child:ISimpleSelector ):IDescendantSelector; /** * Creates a comment node selector. * @param data the data * @throws ICSSException If this selector is not supported. * @returns the comment node selector * @see SelectorTypes#SAC_COMMENT_NODE_SELECTOR */ function createCommentSelector( data:String ):ICharacterDataSelector; /** * Creates a conditional selector. * @param selector a selector. * @param condition a condition * @throws ICSSException If this selector is not supported. * @returns the conditional selector. * @see SelectorTypes#SAC_CONDITIONAL_SELECTOR */ function createConditionalSelector( selector:ISimpleSelector, condition:ICondition ):IConditionalSelector; /** * Creates a descendant selector. * @param parent the parent selector * @param descendant the descendant selector * @throws ICSSException If this selector is not supported. * @returns the combinator selector. * @see SelectorTypes#SAC_DESCENDANT_SELECTOR */ function createDescendantSelector( parent:ISelector, descendant:ISimpleSelector ):IDescendantSelector; /** * Creates a sibling selector. * @param nodeType the type of nodes in the siblings list. * @param child the child selector * @param adjacent the direct adjacent selector * @throws ICSSException If this selector is not supported. * @returns the sibling selector with nodeType equals to org.w3c.dom.Node.ELEMENT_NODE * @see SelectorTypes#SAC_DIRECT_ADJACENT_SELECTOR */ function createDirectAdjacentSelector( nodeType:uint, child:ISelector, directAdjacent:ISimpleSelector ):ISiblingSelector; /** * Creates an element selector. * @param namespaceURI the namespace URI of the element selector. * @param tagName the local part of the element name. NULL if this element selector can match any element. * @throws ICSSException If this selector is not supported. * @returns the element selector * @see SelectorTypes#SAC_ELEMENT_NODE_SELECTOR */ function createElementSelector( namespaceURI:String, tagName:String ):IElementSelector; /** * Creates an negative selector. * @param selector a selector. * @throws ICSSException If this selector is not supported. * @returns the negative selector. * @see SelectorTypes#SAC_NEGATIVE_SELECTOR */ function createNegativeSelector( selector:ISimpleSelector ):INegativeSelector; /** * Creates a processing instruction node selector. * @param target the target * @param data the data * @throws ICSSException If this selector is not supported. * @returns the processing instruction node selector * @see SelectorTypes#SAC_PROCESSING_INSTRUCTION_NODE_SELECTOR */ function createProcessingInstructionSelector( target:String, data:String ):IProcessingInstructionSelector; /** * Creates a pseudo element selector. * @param pseudoName the pseudo element name. NULL if this element selector can match any pseudo element. * @throws ICSSException If this selector is not supported. * @returns the element selector * @see SelectorTypes#SAC_PSEUDO_ELEMENT_SELECTOR */ function createPseudoElementSelector( namespaceURI:String, pseudoName:String ):IElementSelector; /** * Creates an root node selector. * @throws ICSSException If this selector is not supported. * @returns the root node selector. * @see SelectorTypes#SAC_ROOT_NODE_SELECTOR */ function createRootNodeSelector():ISimpleSelector; /** * Creates a text node selector. * @param data the data * @throws ICSSException If this selector is not supported. * @returns the text node selector * @see SelectorTypes#SAC_TEXT_NODE_SELECTOR */ function createTextNodeSelector( data:String ):ICharacterDataSelector; } }
package sabelas.nodes { import sabelas.components.Motion; import sabelas.components.Position; import ash.core.Node; /** * Node for moving object * @author Abiyasa */ public class MotionNode extends Node { public var position:Position; public var motion:Motion; } }
package recastnavigation.detour.navmesh { import recastnavigation.core.RNBase; import recastnavigation.core.rn_internal; import recastnavigation.core.utils.offsetBytes; import recastnavigation.internal_api.CModule; use namespace rn_internal; /** * Defines an navigation mesh off-mesh connection within a dtMeshTile * object. An off-mesh connection is a user defined traversable * connection made up to two vertices. */ public class DTOffMeshConnection extends RNBase { rn_internal static var SIZE:int = 0; rn_internal static const OFFSET_POS:int = offsetBytes(4 * 6, DTOffMeshConnection); rn_internal static const OFFSET_RAD:int = offsetBytes(4, DTOffMeshConnection); rn_internal static const OFFSET_POLY:int = offsetBytes(2, DTOffMeshConnection); rn_internal static const OFFSET_FLAGS:int = offsetBytes(1, DTOffMeshConnection); rn_internal static const OFFSET_SIDE:int = offsetBytes(1, DTOffMeshConnection); rn_internal static const OFFSET_USER_ID:int = offsetBytes(4, DTOffMeshConnection); /** The endpoints of the connection. Component ax. [(ax, ay, az, bx, by, bz)] */ public function get posAX():Number { return CModule.readFloat(ptr + OFFSET_POS); } public function set posAX(value:Number):void { CModule.writeFloat(ptr + OFFSET_POS, value); } /** The endpoints of the connection. Component ay. [(ax, ay, az, bx, by, bz)] */ public function get posAY():Number { return CModule.readFloat(ptr + OFFSET_POS + 4); } public function set posAY(value:Number):void { CModule.writeFloat(ptr + OFFSET_POS + 4, value); } /** The endpoints of the connection. Component az. [(ax, ay, az, bx, by, bz)] */ public function get posAZ():Number { return CModule.readFloat(ptr + OFFSET_POS + 8); } public function set posAZ(value:Number):void { CModule.writeFloat(ptr + OFFSET_POS + 8, value); } /** The endpoints of the connection. Component bx. [(ax, ay, az, bx, by, bz)] */ public function get posBX():Number { return CModule.readFloat(ptr + OFFSET_POS + 12); } public function set posBX(value:Number):void { CModule.writeFloat(ptr + OFFSET_POS + 12, value); } /** The endpoints of the connection. Component by. [(ax, ay, az, bx, by, bz)] */ public function get posBY():Number { return CModule.readFloat(ptr + OFFSET_POS + 16); } public function set posBY(value:Number):void { CModule.writeFloat(ptr + OFFSET_POS + 16, value); } /** The endpoints of the connection. Component bz. [(ax, ay, az, bx, by, bz)] */ public function get posBZ():Number { return CModule.readFloat(ptr + OFFSET_POS + 20); } public function set posBZ(value:Number):void { CModule.writeFloat(ptr + OFFSET_POS + 20, value); } /** The radius of the endpoints. [Limit: >= 0] */ public function get rad():Number { return CModule.readFloat(ptr + OFFSET_RAD); } public function set rad(value:Number):void { CModule.writeFloat(ptr + OFFSET_RAD, value); } /** The polygon reference of the connection within the tile. */ public function get poly():int { return CModule.read16(ptr + OFFSET_POLY); } public function set poly(value:int):void { CModule.write16(ptr + OFFSET_POLY, value); } /** * Link flags. These are not the connection's user defined flags. * Those are assigned via the connection's dtPoly definition. * These are link flags used for internal purposes. */ public function get flags():int { return CModule.read8(ptr + OFFSET_FLAGS); } public function set flags(value:int):void { CModule.write8(ptr + OFFSET_FLAGS, value); } /** End point side. */ public function get side():int { return CModule.read8(ptr + OFFSET_SIDE); } public function set side(value:int):void { CModule.write8(ptr + OFFSET_SIDE, value); } /** The id of the offmesh connection. (User assigned when the navigation mesh is built.) */ public function get userId():int { return CModule.read32(ptr + OFFSET_USER_ID); } public function set userId(value:int):void { CModule.write32(ptr + OFFSET_USER_ID, value); } } }
// Urho2D particle example. // This sample demonstrates: // - Creating a 2D scene with particle // - Displaying the scene using the Renderer subsystem // - Handling mouse move to move particle #include "Scripts/Utilities/Sample.as" Node@ particleNode; void Start() { // Execute the common startup for samples SampleStart(); // Set mouse visible input.mouseVisible = true; // Create the scene content CreateScene(); // Create the UI content CreateInstructions(); // Setup the viewport for displaying the scene SetupViewport(); // Hook up to the frame update events SubscribeToEvents(); } void CreateScene() { scene_ = Scene(); // Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will // show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it // is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically // optimizing manner scene_.CreateComponent("Octree"); // Create a scene node for the camera, which we will move around // The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically) cameraNode = scene_.CreateChild("Camera"); // Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0f, 0.0f, -10.0f); Camera@ camera = cameraNode.CreateComponent("Camera"); camera.orthographic = true; camera.orthoSize = graphics.height * PIXEL_SIZE; ParticleEffect2D@ particleEffect = cache.GetResource("ParticleEffect2D", "Urho2D/sun.pex"); if (particleEffect is null) return; particleNode = scene_.CreateChild("ParticleEmitter2D"); ParticleEmitter2D@ particleEmitter = particleNode.CreateComponent("ParticleEmitter2D"); particleEmitter.effect = particleEffect; ParticleEffect2D@ greenSpiralEffect = cache.GetResource("ParticleEffect2D", "Urho2D/greenspiral.pex"); if (greenSpiralEffect is null) return; Node@ greenSpiralNode = scene_.CreateChild("GreenSpiral"); ParticleEmitter2D@ greenSpiralEmitter = greenSpiralNode.CreateComponent("ParticleEmitter2D"); greenSpiralEmitter.effect = greenSpiralEffect; } void CreateInstructions() { // Construct new Text object, set string to display and font to use Text@ instructionText = ui.root.CreateChild("Text"); instructionText.text = "Use mouse to move the particle."; instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15); // Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER; instructionText.verticalAlignment = VA_CENTER; instructionText.SetPosition(0, ui.root.height / 4); } void SetupViewport() { // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera // at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to // use, but now we just use full screen and default render path configured in the engine command line options Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera")); renderer.viewports[0] = viewport; } void SubscribeToEvents() { // Subscribe HandleMouseMove() function for tracking mouse/touch move events SubscribeToEvent("MouseMove", "HandleMouseMove"); if (touchEnabled) SubscribeToEvent("TouchMove", "HandleMouseMove"); // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample UnsubscribeFromEvent("SceneUpdate"); } void HandleMouseMove(StringHash eventType, VariantMap& eventData) { if (particleNode !is null) { float x = eventData["x"].GetInt(); float y = eventData["y"].GetInt(); Camera@ camera = cameraNode.GetComponent("Camera"); particleNode.position = camera.ScreenToWorldPoint(Vector3(x / graphics.width, y / graphics.height, 10.0f)); } } // Create XML patch instructions for screen joystick layout specific to this sample app String patchInstructions = "<patch>" + " <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" + " <attribute name=\"Is Visible\" value=\"false\" />" + " </add>" + "</patch>";
function isPalindrome(str:String):Boolean { for(var first:uint = 0, second:uint = str.length - 1; first < second; first++, second--) if(str.charAt(first) != str.charAt(second)) return false; return true; }
package starline.player.panels.audio { import flash.display.*; import flash.events.*; import starline.ui.list.ListBox; /* * Guzhva Andrey * http://starline-studio.com * 07.01.2011 * MusicBox player | radio */ public class AudioList extends Sprite { public var _root:*; public var _parent:*; // Interface public var menu_mc:AudioMenu; public var list_mc:ListBox; public var in_arr:Array; public var sort_lines_arr:Array; public var lines_arr:Array; public var search_key:String = ''; // Positiun public var prev_click:int; public var cur_click:int; public var prev_dclick:int; public var cur_dclick:int; // Flag public var random_flag:Boolean = false; public var round_flag:Boolean = false; // Vars private var cur_drag:uint; private var start_drag:uint; private var n_del:uint; public function AudioList(_root:*, _parent:*) :void { this._root = _root; this._parent = _parent; menu_mc = new AudioMenu(_root, this); addChild(menu_mc); list_mc = new ListBox(0, 45, 630, 10); addChild(list_mc); } public function onList(arr:Array):void { in_arr = new Array(); lines_arr = new Array(); sort_lines_arr = new Array(); if (arr) { in_arr = arr; if (in_arr.length>0) { // если есть удиозаписи for (var i:int = 0; i < in_arr.length; ++i) { var p:* = in_arr[i]; var line:AudioLine = new AudioLine(this, i, p); line.del_btn.visible = (line.oid == _root.flashVars.viewer_id)?true:false; line.add_btn.visible = (line.oid != _root.flashVars.viewer_id)?true:false; lines_arr.push(line); // создаем массив с аудиозаписями } } } cur_dclick = -1 cur_click = -1; audioListSortByKey(); } private function refreshN():void { for (var i:uint = 0; i < lines_arr.length; i++) { lines_arr.n = i; } } ////////////////////////////////////////////////////////////////////////////////////////////////// ////----------------------------------------------------------------------------------- Фильтровка ////////////////////////////////////////////////////////////////////////////////////////////////// public function audioListSortByKey(search_key:String = '', resetScroll:Boolean = true):void { // фильтровка аудиозаписей по слову if (cur_dclick != -1) { sort_lines_arr[cur_dclick].unDclick(); cur_dclick = -1; } if (cur_click != -1) { sort_lines_arr[cur_click].unClick(); cur_click = -1; } this.search_key = search_key; sort_lines_arr = new Array(); if (search_key == "") { sort_lines_arr = lines_arr; } else { for (var i:uint = 0; i < lines_arr.length; i++) { var search_name:String = lines_arr[i].artist+' '+lines_arr[i].title; search_name = search_name.toLowerCase(); if (search_name.indexOf(search_key)!= -1) { sort_lines_arr.push(lines_arr[i]); } } } list_mc.clear(); if (resetScroll) list_mc.resetScrollBar(); list_mc.addItemsArray( sort_lines_arr ); } //////////////////////////////////////////////////////////////////////////////////////// ////------------------------------------------------------------------------- ADD DELETE //////////////////////////////////////////////////////////////////////////////////////// public function onAdd(aid:uint, oid:uint, n:uint):void { _root.loaderBar_spr.visible = true; _root.VK.api('audio.add', {aid:aid, oid:oid}, _root.vkApiRequest.fetchAudioAdd, _root.vkApiRequest.requestFail); } public function onDel(aid:uint, oid:uint, n:uint):void { n_del = n; _root.loaderBar_spr.visible = true; _root.VK.api('audio.delete', {aid:aid, oid:oid}, _root.vkApiRequest.fetchAudioDelete, _root.vkApiRequest.requestFail); } public function audioDelete():void { lines_arr.splice(n_del, 1); refreshN(); audioListSortByKey(search_key, false); } //////////////////////////////////////////////////////////////////////////////////////// ////----------------------------------------------------------------------------- SELECT //////////////////////////////////////////////////////////////////////////////////////// public function onClick(n:int):void { if (n != cur_click) { prev_click = cur_click; cur_click = n; sort_lines_arr[cur_click].onClick(); if (prev_click >= 0) { sort_lines_arr[prev_click].unClick(); } } } public function onDclick(n:int):void { if(n != cur_dclick){ prev_dclick = cur_dclick; cur_dclick = n; if (prev_dclick >= 0) {sort_lines_arr[prev_dclick].unDclick();} sort_lines_arr[cur_dclick].onDclick() } _parent.audio_flag = true; _parent.setLastAudio(sort_lines_arr[cur_dclick].artist+' - '+sort_lines_arr[cur_dclick].title); _parent.onNewPlay(sort_lines_arr[cur_dclick].url); } public function onNext():void { if (cur_dclick < sort_lines_arr.length-1) { if (random_flag) { onDclick(Math.random()*sort_lines_arr.length); } else { onDclick(cur_dclick+1); } } else { onDclick(0); } } public function onPrev():void { if (cur_dclick > 0) { if (random_flag) { onDclick(Math.random()*sort_lines_arr.length); } else { onDclick(cur_dclick-1); } } } //////////////////////////////////////////////////////////////////////////////////////// ////--------------------------------------------------------------------- Перетаскивание //////////////////////////////////////////////////////////////////////////////////////// public function startDragLine(target:Sprite):void { start_drag = target['idx']; //idx взятой пролосы addEventListener( MouseEvent.MOUSE_MOVE, mouseMove ); target.y = mouseY-10; addChild(target); target.startDrag(); } public function stopDragLine(target:Sprite):void { removeEventListener(MouseEvent.MOUSE_MOVE, mouseMove); stopDrag(); target.x = 0; target.y = (start_drag - list_mc.sb.scrollPosition) * 32; list_mc.addChild(target); var after:uint = (start_drag - 1) < 0 ? 0 : sort_lines_arr[start_drag - 1].aid; var before:uint = (start_drag + 1) > sort_lines_arr.length - 1 ? 0 : sort_lines_arr[start_drag + 1].aid; if (_root.flashVars.viewer_id == sort_lines_arr[start_drag].oid && search_key == '') { _root.VK.api('audio.reorder', { aid:sort_lines_arr[start_drag].aid, after: after, before: before}, _root.vkApiRequest.fetchAudioReorder, _root.vkApiRequest.requestFail); } refreshN(); } private function mouseMove(e:MouseEvent):void { cur_drag = list_mc.sb.scrollPosition + int(list_mc.mouseY / 32); //idx наведенной var cur_line:Sprite = sort_lines_arr[cur_drag]; var start_line:Sprite = sort_lines_arr[start_drag]; if ((start_drag - cur_drag > 0 && cur_drag >= 0) || (start_drag - cur_drag < 0 && cur_drag < sort_lines_arr.length)) { setLine(cur_drag, start_drag); sort_lines_arr.splice(cur_drag, 1, start_line); sort_lines_arr.splice(start_drag, 1, cur_line); list_mc.items.splice(cur_drag, 1, start_line); list_mc.items.splice(start_drag, 1, cur_line); start_drag = cur_drag; } // скролл листа при перетаскивании //if (scroll_mc.mouseY < 0) { //scroll_mc.scrollWhell(3); //} //if (scroll_mc.mouseY > 320) { //scroll_mc.scrollWhell(-3); //} } // устанока новых параметров после перетаскивания private function setLine(_cur:uint, _new:uint):void { sort_lines_arr[_cur].y = (_new - list_mc.sb.scrollPosition)* 32; sort_lines_arr[_cur].idx = _new; sort_lines_arr[_cur].n_txt.text = _new + 1; sort_lines_arr[_new].idx = _cur; sort_lines_arr[_new].n_txt.text = _cur + 1; if (_cur == cur_click || _new == cur_click) { cur_click = _new; } if ( _new == cur_dclick) { cur_dclick = _cur; }else if (_cur == cur_dclick) { cur_dclick = _new; } } } }
package com.ankamagames.dofus.logic.game.fight.steps { import com.ankamagames.dofus.datacenter.spells.Spell; import com.ankamagames.dofus.datacenter.spells.SpellLevel; import com.ankamagames.dofus.kernel.Kernel; import com.ankamagames.dofus.logic.game.fight.fightEvents.FightEventsHelper; import com.ankamagames.dofus.logic.game.fight.frames.FightTurnFrame; import com.ankamagames.dofus.logic.game.fight.managers.MarkedCellsManager; import com.ankamagames.dofus.logic.game.fight.types.FightEventEnum; import com.ankamagames.dofus.logic.game.fight.types.MarkInstance; import com.ankamagames.dofus.network.types.game.actions.fight.GameActionMarkedCell; import com.ankamagames.dofus.types.sequences.AddGlyphGfxStep; import com.ankamagames.jerakine.sequencer.AbstractSequencable; import com.ankamagames.jerakine.types.positions.PathElement; import com.ankamagames.jerakine.utils.display.spellZone.SpellShapeEnum; import tools.enumeration.GameActionMarkTypeEnum; public class FightMarkCellsStep extends AbstractSequencable implements IFightStep { private var _markCasterId:Number; private var _markId:int; private var _markType:int; private var _markSpellGrade:int; private var _cells:Vector.<GameActionMarkedCell>; private var _markSpellId:int; private var _markTeamId:int; private var _markImpactCell:int; private var _markActive:Boolean; public function FightMarkCellsStep(markId:int, markType:int, cells:Vector.<GameActionMarkedCell>, markSpellId:int, markSpellGrade:int, markTeamId:int, markImpactCell:int, markCasterId:Number, markActive:Boolean = true) { super(); this._markCasterId = markCasterId; this._markId = markId; this._markType = markType; this._cells = cells; this._markSpellId = markSpellId; this._markSpellGrade = markSpellGrade; this._markTeamId = markTeamId; this._markImpactCell = markImpactCell; this._markActive = markActive; } public function get stepType() : String { return "markCells"; } override public function start() : void { var cellZone:GameActionMarkedCell = null; var step:AddGlyphGfxStep = null; var evt:String = null; var ftf:FightTurnFrame = null; var pe:PathElement = null; var updatePath:Boolean = false; var spell:Spell = Spell.getSpellById(this._markSpellId); var originMarkSpellLevel:SpellLevel = spell.getSpellLevel(this._markSpellGrade); if(this._markType == GameActionMarkTypeEnum.WALL || originMarkSpellLevel.hasZoneShape(SpellShapeEnum.semicolon)) { if(spell.getParamByName("glyphGfxId") || true) { for each(cellZone in this._cells) { step = new AddGlyphGfxStep(spell.getParamByName("glyphGfxId"),cellZone.cellId,this._markId,this._markType,this._markTeamId); step.start(); } } } else if(spell.getParamByName("glyphGfxId") && !MarkedCellsManager.getInstance().getGlyph(this._markId) && this._markImpactCell != -1) { step = new AddGlyphGfxStep(spell.getParamByName("glyphGfxId"),this._markImpactCell,this._markId,this._markType,this._markTeamId); step.start(); } MarkedCellsManager.getInstance().addMark(this._markCasterId,this._markId,this._markType,spell,originMarkSpellLevel,this._cells,this._markTeamId,this._markActive,this._markImpactCell); var mi:MarkInstance = MarkedCellsManager.getInstance().getMarkDatas(this._markId); if(mi) { evt = FightEventEnum.UNKNOWN_FIGHT_EVENT; switch(mi.markType) { case GameActionMarkTypeEnum.GLYPH: evt = FightEventEnum.GLYPH_APPEARED; break; case GameActionMarkTypeEnum.TRAP: evt = FightEventEnum.TRAP_APPEARED; break; case GameActionMarkTypeEnum.PORTAL: evt = FightEventEnum.PORTAL_APPEARED; break; case GameActionMarkTypeEnum.RUNE: evt = FightEventEnum.RUNE_APPEARED; break; default: _log.warn("Unknown mark type (" + mi.markType + ")."); } FightEventsHelper.sendFightEvent(evt,[mi.associatedSpell.id],0,castingSpellId); ftf = Kernel.getWorker().getFrame(FightTurnFrame) as FightTurnFrame; if(ftf && ftf.myTurn && ftf.lastPath) { for each(pe in ftf.lastPath.path) { if(mi.cells.indexOf(pe.cellId) != -1) { updatePath = true; break; } } if(updatePath) { ftf.updatePath(); } } } executeCallbacks(); } public function get targets() : Vector.<Number> { return new <Number>[this._markId as Number]; } } }
package framework.util { /** * @author melody */ public class TimerUtil { public function TimerUtil() { } public static function getCountDownStr(second:Number):String { second=Math.max(0,second); var txt:String = ""; var n:uint = 0; var minute:uint = 60; var hour:uint = 3600; if (second >= hour) { var h:uint = Math.floor(second / hour); var hStr:String = h + ":"; txt += hStr; second = second - h * hour; n++; }else{ n++; hStr="00" + ":"; txt += hStr; } if (second > minute) { var m:uint = Math.floor(second / minute); var mStr:String = (m < 10 ? "0" + m : m) + ":"; txt += mStr; second = second - m * minute; n++; } else { txt += ("00" + ":"); n++; } //Math.round(ms) var s:uint = Math.round(second); var sStr:String = s < 10 ? "0" + s : s + ""; txt += sStr; return txt; } } }
/* * Copyright (C) 2013 max.rozdobudko@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Created with IntelliJ IDEA. * User: max * Date: 18.02.13 * Time: 08:39 * To change this template use File | Settings | File Templates. */ package com.backendless.examples.flex.todo.application.messages { import com.backendless.examples.flex.todo.domain.Todo; public class CheckTodoMessage { public function CheckTodoMessage(todo:Todo) { super(); this.todo = todo; } public var todo:Todo; } }
package com.tonybeltramelli.airkinect.userAction.event { import flash.events.Event; /** * @author Tony Beltramelli - www.tonybeltramelli.com */ public class KinectMovementEvent extends Event { public static const BEND_DOWN_MOVEMENT : String = "bend_down_movement"; public static const JUMP_MOVEMENT : String = "jump_movement"; public function KinectMovementEvent(type : String, bubbles : Boolean = false, cancelable : Boolean = false) { super(type, bubbles, cancelable); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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 mx.controls.dataGridClasses { import mx.containers.beads.AdvancedDataGridHeaderLayout; import org.apache.royale.html.DataGridButtonBar; /** * The mx DataGridButtonBar class extends DataGridButtonBar to allow some specialized css * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.7 * @royalesuppresspublicvarwarning */ public class DataGridButtonBar extends org.apache.royale.html.DataGridButtonBar { public function DataGridButtonBar() { super(); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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 mx.charts.chartClasses { import mx.core.UIComponent; import org.apache.royale.geom.Rectangle; import mx.core.IFlexDisplayObject; /** * IChartElement defines the base set of properties and methods * required by a UIComponent to be representable in the data space of a chart. * Any component assigned to the series, backgroundElements, * or annotationElements Arrays of a chart must implement this interface. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public interface IChartElement extends IFlexDisplayObject { //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // chartDataProvider //---------------------------------- /** * The data provider assigned to the enclosing chart. * Element types can choose to inherit the data provider * from the enclosing chart if necessary, or allow developers * to assign data providers specifically to the element. * Not all elements are necessarily driven by a data provider. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function set chartDataProvider(value:Object):void; //---------------------------------- // dataTransform //---------------------------------- /** * The DataTransform object that the element uses * to map between data and screen coordinates. * This property is assigned by the enclosing chart. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function set dataTransform(value:DataTransform):void; //---------------------------------- // labelContainer //---------------------------------- /** * The DisplayObject that displays labels rendered by this element. * In most cases, labels displayed in the data area of a chart * are rendered on top of all elements * rather than interleaved with the data. * If an implementing Element has labels to display, * it can place them in a Sprite object * and return it as the value of the <code>labelContainer</code> property. * Enclosing charts will render labelContainers * from all enclosed elements and place them * in the data area above all other elements. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get labelContainer():UIComponent; //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Called by the governing DataTransform to obtain a description * of the data represented by this IChartElement. * Implementors fill out and return an Array of * mx.charts.chartClasses.DataDescription objects * to guarantee that their data is correctly accounted for * by any axes that are autogenerating values * from the displayed data (such as minimum, maximum, * interval, and unitSize). * Most element types return an Array * containing a single DataDescription. * Aggregate elements, such as BarSet and ColumnSet, * might return multiple DataDescription instances * that describe the data displayed by their subelements. * When called, the implementor describes the data * along the axis indicated by the <code>dimension</code> argument. * This function might be called for each axis * supported by the containing chart. * * @param dimension Determines the axis to get data descriptions of. * * @param requiredFields A bitfield that indicates which values * of the DataDescription object the particular axis cares about. * Implementors can optimize by only calculating the necessary fields. * * @return An Array containing the DataDescription instances that describe * the data that is displayed. * * @see mx.charts.chartClasses.DataDescription * @see mx.charts.chartClasses.DataTransform * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function describeData(dimension:String, requiredFields:uint):Array /* of DataDescription */; /** * Returns a HitData object describing the nearest data point * to the coordinates passed to the method. * The <code>x</code> and <code>y</code> arguments * should be values in the Element's coordinate system. * This method aheres to the limits specified by the * <code>sensitivity2</code> parameter * when looking for nearby data points. * * @param x The x coordinate relative to the ChartBase object. * * @param y The y coordinate relative to the ChartBase object. * * @param sensitivity2 The maximum distance from the data point that the * x/y coordinate location can be. * * @return A HitData object describing the nearest data point * within <code>sensitivity2</code> pixels. * * @see mx.charts.HitData * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function findDataPoints(x:Number, y:Number,sensitivity2:Number):Array /* of HitData */; /** * Indicates to the element that the data mapping * of the associated axes has changed. * Implementors should dispose of cached data * and re-render appropriately. * This function is called automatically * by the associated DataTransform when necessary. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function mappingChanged():void; /** * Called by the enclosing chart to indicate that the current state * of the chart has changed. * Implementing elements should respond to this method * in order to synchronize changes to the data displayed by the element. * * @param oldState An integer representing the previous state. * * @param v An integer representing the new state. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function chartStateChanged(oldState:uint,v:uint):void; /** * Called by the enclosing chart to collect any transitions * a particular element might play when the chart changes state. * The chart collects transitions from all elements * and ensures that they play in parallel. * It waits until all transitions have completed * before advancing to another state. * Implementors should append any necessary transitions * to the transitions Array parameter. * * @param chartState The state at which the chart plays * the new transitions. * * @param transitions An Array of transition to add * to the chart's list of transitions to play. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function collectTransitions(chartState:Number,transitions:Array /* of IEffectInstance */):void; /** * Called by the chart to allow associated elements * to claim style selectors from its chartSeriesStyles Array. * Each chart has an associated set of selectors that are * implicitly assigned to contained elements that require them. * Implementing this function gives an element a chance to 'claim' * elements out of that set, as necessary. * An element that requires <i>N</i> style selectors claims the values * from <code>styles[firstAvailable]</code> to * <code>styles[firstAvailable + <i>N</i> - 1]</code>. * * @param styles An Array of styles to claim. * * @param firstAvailable The first style selector in the Array to claim. * * @return The new value for <code>firstAvailable</code> * after claiming any styles (for example, * <code>firstAvailable</code> + <i>N</i>). * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function claimStyles(styles:Array /* of Object */,firstAvailable:uint):uint; } }
package openfl.display { /** * @externs * The JointStyle class is an enumeration of constant values that specify the * joint style to use in drawing lines. These constants are provided for use * as values in the `joints` parameter of the * `openfl.display.Graphics.lineStyle()` method. The method supports * three types of joints: miter, round, and bevel, as the following example * shows: */ public class JointStyle { /** * Specifies beveled joints in the `joints` parameter of the * `openfl.display.Graphics.lineStyle()` method. */ public static const BEVEL:String = "bevel"; /** * Specifies mitered joints in the `joints` parameter of the * `openfl.display.Graphics.lineStyle()` method. */ public static const MITER:String = "miter"; /** * Specifies round joints in the `joints` parameter of the * `openfl.display.Graphics.lineStyle()` method. */ public static const ROUND:String = "round"; } }
/** * LineChart.as * Keith Peters * version 0.9.9 * * A chart component for graphing an array of numeric data as a line graph. * * Copyright (c) 2011 Keith Peters * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.bit101.charts { import flash.display.DisplayObjectContainer; public class LineChart extends Chart { protected var _lineWidth:Number = 1; protected var _lineColor:uint = 0x999999; /** * Constructor * @param parent The parent DisplayObjectContainer on which to add this Label. * @param xpos The x position to place this component. * @param ypos The y position to place this component. * @param data The array of numeric values to graph. */ public function LineChart(parent:DisplayObjectContainer=null, xpos:Number=0, ypos:Number=0, data:Array=null) { super(parent, xpos, ypos, data); } /** * Graphs the numeric data in the chart. */ protected override function drawChart():void { var border:Number = 2; var lineWidth:Number = (_width - border) / (_data.length - 1); var chartHeight:Number = _height - border; _chartHolder.x = 0; _chartHolder.y = _height; var xpos:Number = border; var max:Number = getMaxValue(); var min:Number = getMinValue(); var scale:Number = chartHeight / (max - min); _chartHolder.graphics.lineStyle(_lineWidth, _lineColor); _chartHolder.graphics.moveTo(xpos, (_data[0] - min) * -scale); xpos += lineWidth; for(var i:int = 1; i < _data.length; i++) { if(_data[i] != null) { _chartHolder.graphics.lineTo(xpos, (_data[i] - min) * -scale); } xpos += lineWidth; } } /////////////////////////////////// // getter/setters /////////////////////////////////// /** * Sets/gets the width of the line in the graph. */ public function set lineWidth(value:Number):void { _lineWidth = value; invalidate(); } public function get lineWidth():Number { return _lineWidth; } /** * Sets/gets the color of the line in the graph. */ public function set lineColor(value:uint):void { _lineColor = value; invalidate(); } public function get lineColor():uint { return _lineColor; } } }
package { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Sprite; import specification.expect; public class ExpectToContainDisplayObject { private var container:DisplayObjectContainer; private var child:DisplayObject; public function ExpectToContainDisplayObject() { } [Before] public function setUp():void { container = new Sprite(); child = new Sprite(); } [After] public function tearDown():void { container = null; child = null; } [Test] public function expectContainerToContainChild():void { container.addChild(child); expect(container).to.contain(child); } [Test] public function expectContainerNotToContainChild():void { expect(container).not.to.contain(child); } [Test(expects="specification.core.ExpectationError")] public function expectContainerNotToContainIncorrectChild():void { expect(container).to.contain(child); } } }
package fl.controls { import fl.core.InvalidationType; import fl.core.UIComponent; import fl.managers.IFocusManagerComponent; import flash.display.DisplayObject; public class Button extends LabelButton implements IFocusManagerComponent { private static var defaultStyles:Object = { "emphasizedSkin":"Button_emphasizedSkin", "emphasizedPadding":2 }; public static var createAccessibilityImplementation:Function; protected var _emphasized:Boolean = false; protected var emphasizedBorder:DisplayObject; public function Button() { super(); } public static function getStyleDefinition() : Object { return UIComponent.mergeStyles(LabelButton.getStyleDefinition(),defaultStyles); } public function get emphasized() : Boolean { return _emphasized; } public function set emphasized(param1:Boolean) : void { _emphasized = param1; invalidate(InvalidationType.STYLES); } override protected function draw() : void { if(isInvalid(InvalidationType.STYLES) || isInvalid(InvalidationType.SIZE)) { drawEmphasized(); } super.draw(); if(emphasizedBorder != null) { setChildIndex(emphasizedBorder,numChildren - 1); } } protected function drawEmphasized() : void { var _loc2_:Number = NaN; if(emphasizedBorder != null) { removeChild(emphasizedBorder); } emphasizedBorder = null; if(!_emphasized) { return; } var _loc1_:Object = getStyleValue("emphasizedSkin"); if(_loc1_ != null) { emphasizedBorder = getDisplayObjectInstance(_loc1_); } if(emphasizedBorder != null) { addChildAt(emphasizedBorder,0); _loc2_ = Number(getStyleValue("emphasizedPadding")); emphasizedBorder.x = emphasizedBorder.y = -_loc2_; emphasizedBorder.width = width + _loc2_ * 2; emphasizedBorder.height = height + _loc2_ * 2; } } override public function drawFocus(param1:Boolean) : void { var _loc2_:Number = NaN; var _loc3_:* = undefined; super.drawFocus(param1); if(param1) { _loc2_ = Number(getStyleValue("emphasizedPadding")); if(_loc2_ < 0 || !_emphasized) { _loc2_ = 0; } _loc3_ = getStyleValue("focusRectPadding"); _loc3_ = _loc3_ == null?2:_loc3_; _loc3_ = _loc3_ + _loc2_; uiFocusRect.x = -_loc3_; uiFocusRect.y = -_loc3_; uiFocusRect.width = width + _loc3_ * 2; uiFocusRect.height = height + _loc3_ * 2; } } override protected function initializeAccessibility() : void { if(Button.createAccessibilityImplementation != null) { Button.createAccessibilityImplementation(this); } } } }
package com.ankamagames.dofus.logic.game.fight.steps { import com.ankamagames.dofus.logic.common.managers.StatsManager; import com.ankamagames.dofus.network.types.game.character.characteristic.CharacterCharacteristic; import com.ankamagames.jerakine.sequencer.AbstractSequencable; import com.ankamagames.jerakine.utils.display.EnterFrameDispatcher; public class FightUpdateStatStep extends AbstractSequencable implements IFightStep { public const STEP_TYPE:String = "updateStats"; private var _entityId:Number = NaN; private var _newStats:Vector.<CharacterCharacteristic> = null; private var _targets:Vector.<Number> = null; public function FightUpdateStatStep(entityId:Number, newStats:Vector.<CharacterCharacteristic>) { super(); this._entityId = entityId; this._newStats = newStats; this._targets = new <Number>[this._entityId]; } public function get stepType() : String { return this.STEP_TYPE; } public function get targets() : Vector.<Number> { return this._targets; } override public function start() : void { EnterFrameDispatcher.worker.addSingleTreatment(StatsManager.getInstance(),StatsManager.getInstance().addRawStats,[this._entityId,this._newStats]); super.start(); executeCallbacks(); } } }
package cmodule.lua_wrapper { const __2E_str156317:int = gstaticInitter.alloc(28,1); }
package { import net.flashpunk.Entity; import net.flashpunk.graphics.Image; import net.flashpunk.Mask; import net.flashpunk.masks.Pixelmask; public class Barb extends Entity { private var injured:Boolean = false; public function Barb() { type = "barb"; } override public function update():void { var p:Player = collide("player", x, y) as Player; if (p) { if (!injured) { trace("injury!"); injured = true; p.health -= 25; } } } } }
package game.view { import ddt.events.CrazyTankSocketEvent; import ddt.manager.SocketManager; import flash.display.BitmapData; import flash.utils.ByteArray; import game.model.WindPowerImgData; import road7th.comm.PackageIn; public class WindPowerManager { private static var _instance:WindPowerManager; private var _windPicMode:WindPowerImgData; public function WindPowerManager() { super(); } public static function get Instance() : WindPowerManager { if(_instance == null) { _instance = new WindPowerManager(); } return _instance; } public function init() : void { this._windPicMode = new WindPowerImgData(); SocketManager.Instance.addEventListener(CrazyTankSocketEvent.WINDPIC,this._windPicCome); } private function _windPicCome(param1:CrazyTankSocketEvent) : void { var _loc2_:PackageIn = param1.pkg; var _loc3_:int = _loc2_.readByte(); var _loc4_:ByteArray = _loc2_.readByteArray(); this._windPicMode.refeshData(_loc4_,_loc3_); } public function getWindPic(param1:Array) : BitmapData { return this._windPicMode.getImgBmp(param1); } public function getWindPicById(param1:int) : BitmapData { return this._windPicMode.getImgBmpById(param1); } } }
package example.ui { import UI.abstract.component.control.mc.Animation; import UI.abstract.resources.AnCategory; import UI.abstract.resources.ResourceUtil; import UI.theme.defaulttheme.text.TextInput; import flash.display.Sprite; import flash.events.FocusEvent; public class AnimationE extends Sprite { private var ui:Animation; private var ui1:Animation; private var ui2:Animation; public function AnimationE() { super(); ui1 = new Animation(AnCategory.MOUNTS,"601200001",21,true,1.0,5); ui1.x = 300; ui1.dir = 4; ui1.y = 300; addChild(ui1); ui = new Animation(AnCategory.USER,"100012003",21,true,1.0,5); ui.x = 300; ui.dir = 4; ui.y = 300; addChild(ui); ui2 = new Animation(AnCategory.USER,"100022002_12",21,true,1.0,5); ui2.x = 300; ui2.dir = 4; ui2.y = 300; addChild(ui2); var textInput:TextInput = new TextInput(); textInput.name = "url"; textInput.addEventListener(FocusEvent.FOCUS_IN,onFocusIn); textInput.addEventListener(FocusEvent.FOCUS_OUT,onFocusOut); textInput.x = 500; textInput.y = 0; textInput.width = 100; textInput.height = 20; addChild(textInput); var textInput:TextInput = new TextInput(); textInput.name = "currentFrame"; textInput.addEventListener(FocusEvent.FOCUS_IN,onFocusIn); textInput.addEventListener(FocusEvent.FOCUS_OUT,onFocusOut); textInput.x = 500; textInput.y = 30; textInput.width = 100; textInput.height = 20; addChild(textInput); var textInput:TextInput = new TextInput(); textInput.name = "dir"; textInput.addEventListener(FocusEvent.FOCUS_IN,onFocusIn); textInput.addEventListener(FocusEvent.FOCUS_OUT,onFocusOut); textInput.x = 500; textInput.y = 60; textInput.width = 100; textInput.height = 20; addChild(textInput); var textInput:TextInput = new TextInput(); textInput.name = "action"; textInput.addEventListener(FocusEvent.FOCUS_IN,onFocusIn); textInput.addEventListener(FocusEvent.FOCUS_OUT,onFocusOut); textInput.x = 500; textInput.y = 90; textInput.width = 100; textInput.height = 20; addChild(textInput); } private function onFocusIn(event:FocusEvent):void{ if(event.currentTarget.name == "setSkin"){ event.currentTarget.text = ""; } } private function onFocusOut(event:FocusEvent):void{ if(event.currentTarget.name == "gapH" || event.currentTarget.name == "gapW"){ //ui.set9Gap(int((getChildByName("gapW") as TextInput).text),int((getChildByName("gapH") as TextInput).text)); }else if(event.currentTarget.name == "setSkin"){ //ui.setSkin((getChildByName("setSkin") as TextInput).text); } else{ ui[event.currentTarget.name] = (getChildByName(event.currentTarget.name) as TextInput).text; ui1[event.currentTarget.name] = (getChildByName(event.currentTarget.name) as TextInput).text; ui2[event.currentTarget.name] = (getChildByName(event.currentTarget.name) as TextInput).text; } } } }
package com.emmanouil.managers { import com.greensock.TweenLite; import com.greensock.easing.Expo; import com.emmanouil.ui.UIView; import com.emmanouil.ui.types.UIViewTransitionAnimation; import com.emmanouil.core.Capabilities; public class ViewManager { private static var changingView:Boolean; public static var activeView:UIView; public static var lastView:UIView; private static var viewsArray:Array = new Array(); public static var preventChange:Boolean = false; public static function AddViews(view:UIView, id:String):void { if(viewsArray.length < 1){ activeView = view; activeView.Start(); } else{ view.visible = false; } view.id = id; viewsArray.push(view); trace("[View Manager] - Add - " + id); } public static function ChangeViewTo(id:String, animation:String = "rightToLeft"):void { if(!preventChange){ goToView(ViewWithID(id), animation); } //volta para o default preventChange = false; } private static function goToView(_activeView:UIView, _animationType:String):void { if(!changingView){ changingView = true; lastView = activeView; activeView = _activeView; activeView.visible = true; //Se não repetir a tela if(lastView != activeView){ switch(_animationType){ case UIViewTransitionAnimation.FADE_OUT: activeView.alpha = 0; TweenLite.to(activeView, 0.5, {alpha: 1, onStart: onStart, onComplete: onComplete}); break; case UIViewTransitionAnimation.PAGED: //se a tela anterior estiver na esquerda - animar da direita p/ esquerda const factor:Number = (lastView.page > activeView.page) ? -1.5 : 1.5; _activeView.x = Capabilities.GetWidth() * factor; lastView.visible = false; TweenLite.to(activeView, 0.5, {x: 0, alpha: 1, ease: Expo.easeOut, onStart: onStart, onComplete: onComplete}); break; case UIViewTransitionAnimation.RIGTH_TO_LEFT: _activeView.x = Capabilities.GetWidth() * 1.5; lastView.visible = false; TweenLite.to(activeView, 0.5, {x: 0, alpha: 1, ease: Expo.easeOut, onStart: onStart, onComplete: onComplete}); break; case UIViewTransitionAnimation.LEFT_TO_RIGTH: _activeView.x = Capabilities.GetWidth() * -1.5; lastView.visible = false; TweenLite.to(activeView, 0.5, {x: 0, alpha: 1, ease: Expo.easeOut, onStart: onStart, onComplete: onComplete}); break; } } else{ changingView = false; activeView.GoHome(); } } } private static function onStart():void { lastView.StopAwake(); activeView.StartAwake(); //verifica orientação da tela //DeviceScreenManager.CheckViewOrientation(activeView); checkAwakeViews(); } private static function onComplete():void { trace("[View Manager] - Navegated - " + activeView.name); changingView = false; lastView.alpha = 1; lastView.visible = false; checkViews(); lastView.Stop(); activeView.Start(); } private static function checkAwakeViews():void { } private static function checkViews():void { } private static function ViewWithID(id:String):UIView { for(var i:int = 0; i < viewsArray.length; i++){ if(viewsArray[i].id == id){ return viewsArray[i]; } } throw new Error("Não achou o item: " + id); return viewsArray[0]; } } }
package org.flexlite.domUI.collections { import flash.events.IEventDispatcher; /** * 列表的集合类数据源对象接口 * @author DOM */ public interface ICollection extends IEventDispatcher { /** * 此集合中的项目数。0 表示不包含项目,而 -1 表示长度未知。 */ function get length():int; /** * 获取指定索引处的项目。 * @throws RangeError 如果索引小于 0 或大于长度。 */ function getItemAt(index:int):Object; /** * 如果项目位于列表中,返回该项目的索引。否则返回-1。 */ function getItemIndex(item:Object):int; } }
package devoron.aslc.moduls.output { import devoron.file.FileInfo; import devoron.sdk.runtime.errors.ErrorValue; import flash.events.MouseEvent; import flash.filesystem.File; import net.kawa.tween.easing.Linear; import net.kawa.tween.KTween; import org.aswing.AbstractListCell; import org.aswing.ASColor; import org.aswing.Component; import org.aswing.decorators.ColorDecorator; import org.aswing.ext.Form; import org.aswing.JLabel; import org.aswing.JList; public class StackTraceListCellRenderer extends AbstractListCell { protected var selectedColor:ASColor = new ASColor(0XFFFFFF, 0.15); protected var unselectedColor:ASColor = new ASColor(0xFFFFFF, 0.14); protected var comp:Form; protected var pathLB:JLabel; protected var descriptionLB:JLabel; //protected var lineLB:JLabel; protected var positionLB:JLabel; protected var citatLB:JLabel; private var rootDirectory:FileInfo; private var clb:ColorDecorator; private var isSelected:Boolean; private var errorValue:ErrorValue; public function StackTraceListCellRenderer() { comp = new Form(); //comp.addEventListener(MouseEvent.MOUSE_OUT, onMOut); //comp.addEventListener(MouseEvent.MOUSE_OVER, onMOver); //pathLB.setSelectable(true); pathLB = new JLabel(); pathLB.setForeground(new ASColor(0XFFFFFF, 0.6)); pathLB.setOpaque(false); descriptionLB = new JLabel(); descriptionLB.setForeground(new ASColor(0XFFFFFF, 0.6)); descriptionLB.setOpaque(false); /*lineLB = new JLabel(); lineLB.setForeground(new ASColor(0XFFFFFF, 0.6)); lineLB.setOpaque(false);*/ positionLB = new JLabel(); positionLB.setForeground(new ASColor(0XFFFFFF, 0.6)); positionLB.setOpaque(false); citatLB = new JLabel(); citatLB.setForeground(new ASColor(0XFFFFFF, 0.6)); citatLB.setOpaque(false); comp.addLeftHoldRow(0, positionLB, descriptionLB); //comp.addLeftHoldRow(0, /*lineLB,*/ positionLB, pathLB); //pathLB //pathLB.setBackground(new ASColor(0x000000, 0.4)); clb = new ColorDecorator(new ASColor(0x000000, 0), null, 2); comp.setBackgroundDecorator(clb); //comp.addLeftHoldRow(0, 5, pathLB); comp.buttonMode = true; comp.addEventListener(MouseEvent.ROLL_OVER, onRollOver); comp.addEventListener(MouseEvent.ROLL_OUT, onRollOut); comp.doubleClickEnabled = true; comp.mouseChildren = false; comp.addEventListener(MouseEvent.DOUBLE_CLICK, onDoubleClick); comp.alpha = 0.54; } private function onDoubleClick(e:MouseEvent):void { trace("даблик " + value.path); //pathLB.setForeground(new ASColor(0xC93C18, 0.4)); //clb.setColor(new ASColor(0xE2130E, 1)); //if(e (new File(value.path)).openWithDefaultApplication(); // временно !! var fi:File = new File(value.path); if (fi.extension == "as") { /*var editosFactory:StudioDataProcessorsProvider = new StudioDataProcessorsProvider(); var editor:IDataProcessor = editosFactory.getDataProcessor(fi.name, AS3Editor, fi.nativePath, false); StudioWorkspace.instance.append(editor.getView(), { layout: StudioWorkspaceLayout.TAB, icon: null, title: fi.name + "." + fi.extension } ); StudioWorkspace.instance.tabs.setSelectedIndex(StudioWorkspace.instance.tabs.getTabCount()-1);*/ //trace("DBBBBB " + editor.getView()) } //comp.alpha = 0.04; } private function onRollOut(e:MouseEvent):void { if (isSelected) comp.alpha = 1; else KTween.to(comp, 0.15, {alpha: 0.54}, Linear.easeIn).init(); /*if (v) { alpha = 0; super.setVisible(true); KTween.to(this, 0.15, {alpha: 1}, Linear.easeIn).init(); } else { //super.setVisible(false); KTween.to(this, 0.08, {alpha: 0}, Linear.easeIn, onAlphaReduceComplete).init(); }*/ } private function onRollOver(e:MouseEvent):void { KTween.to(comp, 0.15, {alpha: 1}, Linear.easeIn).init(); } private function onMOver(e:MouseEvent):void { //KTween.to(clb, 0.15, {alpha: 1}, Linear.easeIn).init(); pathLB.setForeground(new ASColor(0XFFFFFF, 0.6)); clb.setColor(new ASColor(0x000000, 0.14)); } private function onMOut(e:MouseEvent):void { clb.setColor(new ASColor(0x000000, 0)); pathLB.setForeground(new ASColor(0XFFFFFF, 0.4)); } public override function getCellComponent():Component { return comp; } public override function getCellValue():* { return errorValue; } public override function setCellValue(value:*):void { this.value = value; //if (!value) //return; //rootDirectory = FileInfo(value); /** * Было !! * * pathLB.setText(value.text); */ if (value is ErrorValue) { //va var errorValue:ErrorValue = value as ErrorValue; descriptionLB.setText(errorValue.description); positionLB.setText("["+errorValue.line + ":" + errorValue.position+"]"); } else { descriptionLB.setText( (value as Object).codePath); //pathLB.setText( (value as Object).filePath); //positionLB.setText( (value as Object).line); positionLB.setText( "#" + (value as Object).messageNum + " : " + (value as Object).line); } //errorValue = value as ErrorValue; //pathLB.setText(errorValue.path); //lineLB.setText(errorValue.line); //positionLB.setText("[" + errorValue.line + " : " + errorValue.position + "]"); //pathLB.setText(rootDirectory.name); //var bi:Bitmap = new Bitmap(rootDirectory.icons[1]); //bi.filters = [new ColorMatrixFilter([0.3086, 0.6094, 0.0820, 0, 0, 0.3086, 0.6094, 0.0820, 0, 0, 0.3086, 0.6094, 0.0820, 0, 0, 0, 0, 0, 1, 0])]; //pathLB.setIcon(new AssetIcon(bi)); } public function setListCellStatus2(list:JList, isSelected:Boolean, index:int):void { //clb.setColor( isSelected ? selectedColor : unselectedColor); pathLB.setForeground(isSelected ? list.getSelectionForeground() : list.getForeground()); //comp.setBorder(new LineBorder(null, isSelected ? selectedColor : unselectedColor, 1, 2)); } public override function setListCellStatus(list:JList, isSelected:Boolean, index:int):void { this.isSelected = isSelected; //var com:Component = getCellComponent(); if (isSelected) { /*pathLB.setBackground(list.getSelectionBackground()); pathLB.setForeground(list.getSelectionForeground());*/ //pathLB.setForeground(new ASColor(0xFFFFFF, 0.4)); clb.setColor(new ASColor(0x000000, 0.14)); } else { pathLB.setBackground(list.getBackground()); //pathLB.setForeground(list.getForeground()); //pathLB.setForeground(new ASColor(0xFFFFFF, 0.4)); clb.setColor(new ASColor(0x000000, 0)); } pathLB.setFont(list.getFont()); } } }
package com.traffic.util.uiCleaner { import com.adobe.cairngorm.contract.Contract; import mx.core.UIComponent; import mx.logging.Log; import mx.states.State; public class StatesCleaner implements IDisplayObjectCleaner { public function canCleanDisplayObject(object:Object):Boolean { return object is UIComponent; } public function cleanDisplayObject(object:Object):void { Contract.precondition(object is UIComponent); const component:UIComponent = UIComponent(object); try { // Iterate through the component's states and clean them up // in preparation for garbage collection. while ( component.states && component.states.length > 0 ) { var state : State = component.states.pop() as State; while ( state.overrides && state.overrides.length > 0 ) { var stateOverride: Object = state.overrides.pop(); if ( stateOverride.hasOwnProperty( "target" ) ) { stateOverride.target = null; } } } } catch( e : Error ) { Log.getLogger("com.sohnar.traffic.util.StatesCleaner").warn( "Error in cleanStates: " + e.message ); } } } }
package game.actions { import com.pickgliss.utils.ClassUtils; import ddt.data.PathInfo; import ddt.events.CrazyTankSocketEvent; import ddt.manager.SoundManager; import flash.display.MovieClip; import flash.geom.Point; import game.GameManager; import game.model.Living; import game.model.LocalPlayer; import game.model.TurnedLiving; import game.objects.GameLiving; import game.objects.SimpleBox; import game.view.map.MapView; import org.aswing.KeyboardManager; import road7th.comm.PackageIn; import road7th.utils.MovieClipWrapper; import room.RoomManager; public class ChangePlayerAction extends BaseAction { private var _map:MapView; private var _info:Living; private var _count:int; private var _changed:Boolean; private var _pkg:PackageIn; private var _event:CrazyTankSocketEvent; public function ChangePlayerAction(param1:MapView, param2:Living, param3:CrazyTankSocketEvent, param4:PackageIn, param5:Number = 200) { super(); this._event = param3; this._event.executed = false; this._pkg = param4; this._map = param1; this._info = param2; this._count = param5 / 40; } private function syncMap() : void { var _loc7_:LocalPlayer = null; var _loc12_:int = 0; var _loc13_:int = 0; var _loc14_:int = 0; var _loc15_:int = 0; var _loc16_:SimpleBox = null; var _loc17_:int = 0; var _loc18_:Boolean = false; var _loc19_:int = 0; var _loc20_:int = 0; var _loc21_:int = 0; var _loc22_:Boolean = false; var _loc23_:int = 0; var _loc24_:int = 0; var _loc25_:int = 0; var _loc26_:int = 0; var _loc27_:int = 0; var _loc28_:int = 0; var _loc29_:int = 0; var _loc30_:Living = null; var _loc1_:Boolean = this._pkg.readBoolean(); var _loc2_:int = this._pkg.readByte(); var _loc3_:int = this._pkg.readByte(); var _loc4_:int = this._pkg.readByte(); var _loc5_:Array = new Array(); _loc5_ = [_loc1_,_loc2_,_loc3_,_loc4_]; GameManager.Instance.Current.setWind(GameManager.Instance.Current.wind,this._info.LivingID == GameManager.Instance.Current.selfGamePlayer.LivingID,_loc5_); this._info.isHidden = this._pkg.readBoolean(); var _loc6_:int = this._pkg.readInt(); if(this._info is LocalPlayer) { _loc7_ = LocalPlayer(this._info); if(_loc6_ > 0) { _loc7_.turnTime = _loc6_; } else { _loc7_.turnTime = RoomManager.getTurnTimeByType(RoomManager.Instance.current.timeType); } if(_loc6_ != RoomManager.getTurnTimeByType(RoomManager.Instance.current.timeType)) { } } var _loc8_:int = this._pkg.readInt(); var _loc9_:uint = 0; while(_loc9_ < _loc8_) { _loc12_ = this._pkg.readInt(); _loc13_ = this._pkg.readInt(); _loc14_ = this._pkg.readInt(); _loc15_ = this._pkg.readInt(); _loc16_ = new SimpleBox(_loc12_,String(PathInfo.GAME_BOXPIC),_loc15_); _loc16_.x = _loc13_; _loc16_.y = _loc14_; this._map.addPhysical(_loc16_); _loc9_++; } var _loc10_:int = this._pkg.readInt(); var _loc11_:int = 0; while(_loc11_ < _loc10_) { _loc17_ = this._pkg.readInt(); _loc18_ = this._pkg.readBoolean(); _loc19_ = this._pkg.readInt(); _loc20_ = this._pkg.readInt(); _loc21_ = this._pkg.readInt(); _loc22_ = this._pkg.readBoolean(); _loc23_ = this._pkg.readInt(); _loc24_ = this._pkg.readInt(); _loc25_ = this._pkg.readInt(); _loc26_ = this._pkg.readInt(); _loc27_ = this._pkg.readInt(); _loc28_ = this._pkg.readInt(); _loc29_ = this._pkg.readInt(); _loc30_ = GameManager.Instance.Current.livings[_loc17_]; if(_loc30_) { _loc30_.updateBlood(_loc21_,5); _loc30_.isNoNole = _loc22_; _loc30_.maxEnergy = _loc23_; _loc30_.psychic = _loc24_; if(_loc30_.isSelf) { _loc7_ = LocalPlayer(_loc30_); _loc7_.energy = _loc30_.maxEnergy; _loc7_.shootCount = _loc28_; _loc7_.dander = _loc25_; if(_loc7_.currentPet) { _loc7_.currentPet.MaxMP = _loc26_; _loc7_.currentPet.MP = _loc27_; } _loc7_.soulPropCount = 0; _loc7_.flyCount = _loc29_; } if(!_loc18_) { _loc30_.die(); } else { _loc30_.onChange = false; _loc30_.pos = new Point(_loc19_,_loc20_); _loc30_.onChange = true; } } _loc11_++; } this._map.currentTurn = this._pkg.readInt(); } override public function execute() : void { if(!this._changed) { if(this._map.hasSomethingMoving() == false && (this._map.currentPlayer == null || this._map.currentPlayer.actionCount == 0)) { this.executeImp(false); } } else { this._count--; if(this._count <= 0) { this.changePlayer(); } } } private function changePlayer() : void { if(this._info is TurnedLiving) { TurnedLiving(this._info).isAttacking = true; } this._map.gameView.updateControlBarState(this._info); _isFinished = true; } override public function cancel() : void { this._event.executed = true; } private function executeImp(param1:Boolean) : void { var _loc2_:Living = null; var _loc3_:MovieClipWrapper = null; if(!this._info.isExist) { _isFinished = true; this._map.gameView.updateControlBarState(null); return; } if(!this._changed) { this._event.executed = true; this._changed = true; if(this._pkg) { this.syncMap(); } for each(_loc2_ in GameManager.Instance.Current.livings) { _loc2_.beginNewTurn(); } this._map.gameView.setCurrentPlayer(this._info); (this._map.getPhysical(this._info.LivingID) as GameLiving).needFocus(0,0,{"priority":3}); this._info.gemDefense = false; if(this._info is LocalPlayer && !param1) { KeyboardManager.getInstance().reset(); SoundManager.instance.play("016"); _loc3_ = new MovieClipWrapper(MovieClip(ClassUtils.CreatInstance("asset.game.TurnAsset")),true,true); _loc3_.repeat = false; _loc3_.movie.mouseChildren = _loc3_.movie.mouseEnabled = false; _loc3_.movie.x = 440; _loc3_.movie.y = 180; this._map.gameView.addChild(_loc3_.movie); } else { SoundManager.instance.play("038"); this.changePlayer(); } } } override public function executeAtOnce() : void { super.executeAtOnce(); this.executeImp(true); } } }
package com.huawei.overte.view.node { import flash.display.BitmapData; import flash.display.GradientType; import flash.display.Sprite; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import com.huawei.overte.view.common.attachment.ReflectorAttachment import mx.states.OverrideBase; import twaver.Consts; import twaver.IImageAsset; import twaver.Node; import twaver.Styles; import twaver.Utils; import twaver.networkx.IGraphics; import twaver.networkx.NetworkX; import twaver.networkx.ui.NodeUI; public class RefNodeUI extends NodeUI { public function RefNodeUI(network:NetworkX, node:Node) { super(network, node); } override public function updateProperties():void { super.updateProperties(); } override protected function createUnionBounds():Rectangle { var result:Rectangle = super.createUnionBounds(); result.height += 1 + this.node.height; return result; } private var __reflectorAttachment:ReflectorAttachment; override public function checkAttachments():void { super.checkAttachments(); if(!__reflectorAttachment) { __reflectorAttachment = new ReflectorAttachment(this); this.addAttachment(__reflectorAttachment); } } override protected function drawContent(graphics:IGraphics):void { super.drawContent(graphics); var image:IImageAsset = Utils.getImageAsset(this.node.image); if(image == null){ return; } var rect:Rectangle = this.bodyRect; var bitmapData:BitmapData = new BitmapData(rect.width, rect.height, true, 0x00000000); var color:* = element.getStyle(Styles.INNER_STYLE) == Consts.INNER_STYLE_DYE ? innerColor : null; var matrix:Matrix = new Matrix(rect.width/image.width, 0, 0, rect.height/image.height, 0, 0); bitmapData.draw(image.getBitmapData(color), matrix); var resultBitmapData:BitmapData = new BitmapData(rect.width, rect.height, true, 0x00000000); resultBitmapData.copyPixels(bitmapData, new Rectangle(0, 0, rect.width, rect.height), new Point(), this.createAlphaGradientBitmap()); graphics.drawBitmapData(resultBitmapData, rect.x, rect.bottom + 1, rect.width, rect.height, "rectangle", "fill", 180); } private function createAlphaGradientBitmap():BitmapData { var rect:Rectangle = this.bodyRect; var alphaGradientBitmap:BitmapData = new BitmapData(rect.width, rect.height, true, 0x00000000); var gradientMatrix:Matrix = new Matrix(); var gradientSprite:Sprite = new Sprite(); gradientMatrix.createGradientBox(rect.width, rect.height * 0.4, Math.PI/2, 0, rect.height * (1.0 - 0.4)); gradientSprite.graphics.beginGradientFill(GradientType.LINEAR, [0xFFFFFF, 0xFFFFFF], [0, 0.4], [0, 255], gradientMatrix); gradientSprite.graphics.drawRect(0, rect.height * (1.0 - 0.4), rect.width, rect.height * 1); gradientSprite.graphics.endFill(); alphaGradientBitmap.draw(gradientSprite); return alphaGradientBitmap; } } }
package flash.text { /** * @externs * The TextFieldType class is an enumeration of constant values used in * setting the `type` property of the TextField class. */ final public class TextFieldType { /** * Used to specify a `dynamic` TextField. */ public static const DYNAMIC:String = "dynamic"; /** * Used to specify an `input` TextField. */ public static const INPUT:String = "input"; } }
import org.caleb.core.CoreInterface; import org.caleb.util.ObjectUtil; import org.caleb.Configuration; /** * * @see CoreInterface */ class org.caleb.core.CoreObject implements CoreInterface { private var $instanceDescription:String; /* * Sole Constructor */ public function CoreObject(Void) { this.setClassDescription('org.caleb.core.CoreObject'); } /** * Returns a reference to internal $instanceDescription var */ public function toString(Void):String{ return this.$instanceDescription; } private function setClassDescription(d:String):Void { if(org.caleb.util.ObjectUtil.isExplicitInstanceOf(this, eval(d)) == false) { d = 'subclass of ' + d; } this.$instanceDescription = d; } public function get classType():String { return this.$instanceDescription.toString().substring(this.$instanceDescription.toString().lastIndexOf('.') + 1); } }
package com.ankamagames.dofus.logic.game.common.frames { import com.ankamagames.dofus.kernel.Kernel; import com.ankamagames.dofus.kernel.net.ConnectionType; import com.ankamagames.dofus.kernel.net.ConnectionsHandler; import com.ankamagames.dofus.logic.common.managers.NotificationManager; import com.ankamagames.dofus.logic.common.managers.PlayerManager; import com.ankamagames.dofus.logic.connection.managers.AuthentificationManager; import com.ankamagames.dofus.logic.game.common.managers.PlayedCharacterManager; import com.ankamagames.dofus.logic.game.common.misc.KoliseumMessageRouter; import com.ankamagames.dofus.network.messages.game.approach.AuthenticationTicketAcceptedMessage; import com.ankamagames.dofus.network.messages.game.approach.AuthenticationTicketMessage; import com.ankamagames.dofus.network.messages.game.approach.HelloGameMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharacterSelectedForceMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharacterSelectedForceReadyMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharacterSelectedSuccessMessage; import com.ankamagames.dofus.network.messages.game.character.choice.CharactersListRequestMessage; import com.ankamagames.dofus.network.messages.game.context.GameContextCreateRequestMessage; import com.ankamagames.dofus.network.messages.game.context.fight.GameFightEndMessage; import com.ankamagames.dofus.network.messages.game.context.roleplay.fight.arena.GameRolePlayArenaSwitchToFightServerMessage; import com.ankamagames.dofus.network.messages.game.context.roleplay.fight.arena.GameRolePlayArenaSwitchToGameServerMessage; import com.ankamagames.dofus.network.messages.game.initialization.CharacterLoadingCompleteMessage; import com.ankamagames.jerakine.data.XmlConfig; import com.ankamagames.jerakine.logger.Log; import com.ankamagames.jerakine.logger.Logger; import com.ankamagames.jerakine.messages.Message; import com.ankamagames.jerakine.messages.RegisteringFrame; import com.ankamagames.jerakine.network.messages.ServerConnectionFailedMessage; import com.ankamagames.jerakine.types.enums.Priority; import flash.utils.getQualifiedClassName; public class ServerTransferFrame extends RegisteringFrame { protected static const _log:Logger = Log.getLogger(getQualifiedClassName(ServerTransferFrame)); private var _newServerLoginTicket:String; private var _originePlayerId:Number; private var _lastResultMsg:GameFightEndMessage; private var _connexionPorts:Array; public function ServerTransferFrame() { super(); _priority = Priority.HIGHEST; } override public function pushed() : Boolean { return true; } override public function pulled() : Boolean { return true; } override protected function registerMessages() : void { register(HelloGameMessage,this.onHelloGameMessage); register(AuthenticationTicketAcceptedMessage,this.onAuthenticationTicketAcceptedMessage); register(CharacterSelectedForceMessage,this.onCharacterSelectedForceMessage); register(CharacterSelectedSuccessMessage,this.onCharacterSelectedSuccessMessage); register(CharacterLoadingCompleteMessage,this.onCharacterLoadingCompleteMessage); register(GameRolePlayArenaSwitchToFightServerMessage,this.onGameRolePlayArenaSwitchToFightServerMessage); register(GameRolePlayArenaSwitchToGameServerMessage,this.onGameRolePlayArenaSwitchToGameServerMessage); register(GameFightEndMessage,this.onGameFightEndMessage); register(ServerConnectionFailedMessage,this.onServerConnectionFailedMessage); } protected function getConnectionType(msg:Message) : String { return ConnectionsHandler.getConnection().getConnectionId(msg); } private function onCharacterSelectedForceMessage(msg:CharacterSelectedForceMessage) : void { ConnectionsHandler.getConnection().send(new CharacterSelectedForceReadyMessage()); } private function onCharacterSelectedSuccessMessage(msg:CharacterSelectedSuccessMessage) : void { PlayedCharacterManager.getInstance().infos = msg.infos; } private function onHelloGameMessage(msg:HelloGameMessage) : Boolean { var lang:String = XmlConfig.getInstance().getEntry("config.lang.current"); var authMsg:AuthenticationTicketMessage = new AuthenticationTicketMessage(); authMsg.initAuthenticationTicketMessage(lang,this._newServerLoginTicket); switch(this.getConnectionType(msg)) { case ConnectionType.TO_KOLI_SERVER: ConnectionsHandler.getConnection().messageRouter = new KoliseumMessageRouter(); break; case ConnectionType.TO_GAME_SERVER: ConnectionsHandler.getConnection().messageRouter = null; } ConnectionsHandler.getConnection().send(authMsg); return true; } private function onAuthenticationTicketAcceptedMessage(msg:AuthenticationTicketAcceptedMessage) : Boolean { var clr:CharactersListRequestMessage = null; switch(this.getConnectionType(msg)) { case ConnectionType.TO_KOLI_SERVER: clr = new CharactersListRequestMessage(); clr.initCharactersListRequestMessage(); ConnectionsHandler.getConnection().send(clr); return true; default: return false; } } private function onCharacterLoadingCompleteMessage(msg:CharacterLoadingCompleteMessage) : Boolean { var gccrm:GameContextCreateRequestMessage = null; switch(this.getConnectionType(msg)) { case ConnectionType.TO_KOLI_SERVER: gccrm = new GameContextCreateRequestMessage(); gccrm.initGameContextCreateRequestMessage(); ConnectionsHandler.getConnection().send(gccrm); return true; default: return false; } } private function onGameRolePlayArenaSwitchToFightServerMessage(msg:GameRolePlayArenaSwitchToFightServerMessage) : Boolean { var port:uint = 0; this._connexionPorts = new Array(); for each(port in msg.ports) { this._connexionPorts.push(port); } _log.debug("Switch to fight server using ports : " + this._connexionPorts); if(!ConnectionsHandler.getConnection().getSubConnection(ConnectionType.TO_KOLI_SERVER)) { this._originePlayerId = PlayedCharacterManager.getInstance().id; } this._newServerLoginTicket = AuthentificationManager.getInstance().decodeWithAES(msg.ticket).toString(); ConnectionsHandler.connectToKoliServer(msg.address,msg.ports[0]); return true; } private function onGameRolePlayArenaSwitchToGameServerMessage(msg:GameRolePlayArenaSwitchToGameServerMessage) : Boolean { var synchronisationFrameInstance:SynchronisationFrame = Kernel.getWorker().getFrame(SynchronisationFrame) as SynchronisationFrame; synchronisationFrameInstance.resetSynchroStepByServer(ConnectionType.TO_KOLI_SERVER); ConnectionsHandler.getConnection().close(ConnectionType.TO_KOLI_SERVER); ConnectionsHandler.getConnection().messageRouter = null; PlayerManager.getInstance().kisServerPort = 0; NotificationManager.getInstance().sendNotification(); return true; } private function onGameFightEndMessage(msg:GameFightEndMessage) : void { this._lastResultMsg = msg; } private function onServerConnectionFailedMessage(msg:ServerConnectionFailedMessage) : Boolean { var newPort:uint = 0; var formerPort:uint = msg.failedConnection.port; _log.debug("Connection failed using port " + formerPort); if(this._connexionPorts && this._connexionPorts.length) { this._connexionPorts.splice(this._connexionPorts.indexOf(formerPort),1); if(this._connexionPorts.length) { newPort = this._connexionPorts[0]; _log.debug("Connection new attempt, port " + this._connexionPorts); msg.failedConnection.tryConnectingOnAnotherPort(newPort); } return true; } return true; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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. // //////////////////////////////////////////////////////////////////////////////// /*** * Based on the * Swiz Framework library by Chris Scott, Ben Clinkinbeard, Sönke Rohde, John Yanarella, Ryan Campbell, and others https://github.com/swiz/swiz-framework */ package org.apache.royale.crux.utils.view { import org.apache.royale.core.UIBase; import org.apache.royale.core.IFlexInfo; COMPILE::SWF{ import flash.display.DisplayObjectContainer; import flash.display.DisplayObject; } COMPILE::JS{ import org.apache.royale.core.HTMLElementWrapper; } /** * A utility function to check whether a content item has a container in its parent chain * * @param container * @param content * @return true if the content is present in the child hierarchy of the container * * @royaleignorecoercion org.apache.royale.core.HTMLElementWrapper */ public function applicationContains(container:IFlexInfo, content:UIBase):Boolean { if (!content) return false; if (!container) return false; COMPILE::SWF{ return DisplayObjectContainer(container).contains(DisplayObject(content)); } COMPILE::JS{ return HTMLElementWrapper(container).element.contains(content.element) } } }
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2009 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package mx.collections { /** * The SummaryField class represents a single property in a SummaryRow instance. * Each SummaryRow instance specifies one or more SummayField instances * that are used to create a data summary. * * <p>Use the <code>dataField</code> property to specify the data field used to generate the summary, * the <code>label</code> property to specify the name of the data field created to hold the summary data, * and the <code>operation</code> property to specify how to create the summary for numeric fields. * You can specify one of the following values: * <code>SUM</code>, <code>MIN</code>, <code>MAX</code>, <code>AVG</code>, or <code>COUNT</code>.</p> * * <p>The following example creates summary rows based on two fields of the data provider * of the AdvancedDataGrid control:</p> * * <pre> * &lt;mx:AdvancedDataGrid id=&quot;myADG&quot; * initialize=&quot;gc.refresh();&quot;&gt; * &lt;mx:dataProvider&gt; * &lt;mx:GroupingCollection id=&quot;gc&quot; source=&quot;{dpFlat}&quot;&gt; * &lt;mx:Grouping&gt; * &lt;mx:GroupingField name=&quot;Region&quot;&gt; * &lt;mx:summaries&gt; * &lt;mx:SummaryRow summaryPlacement=&quot;group&quot;&gt; * &lt;mx:fields&gt; * &lt;mx:SummaryField dataField=&quot;Actual&quot; * label=&quot;Min Actual&quot; operation=&quot;MIN&quot;/&gt; * &lt;mx:SummaryField dataField=&quot;Actual&quot; * label=&quot;Max Actual&quot; operation=&quot;MAX&quot;/&gt; * &lt;/mx:fields&gt; * &lt;/mx:SummaryRow&gt; * &lt;/mx:summaries&gt; * &lt;/mx:GroupingField&gt; * &lt;mx:GroupingField name=&quot;Territory&quot;&gt; * &lt;mx:summaries&gt; * &lt;mx:SummaryRow summaryPlacement=&quot;group&quot;&gt; * &lt;mx:fields&gt; * &lt;mx:SummaryField dataField=&quot;Actual&quot; * label=&quot;Min Actual&quot; operation=&quot;MIN&quot;/&gt; * &lt;mx:SummaryField dataField=&quot;Actual&quot; * label=&quot;Max Actual&quot; operation=&quot;MAX&quot;/&gt; * &lt;/mx:fields&gt; * &lt;/mx:SummaryRow&gt; * &lt;/mx:summaries&gt; * &lt;/mx:GroupingField&gt; * &lt;/mx:Grouping&gt; * &lt;/mx:GroupingCollection&gt; * &lt;/mx:dataProvider&gt; * * &lt;mx:columns&gt; * &lt;mx:AdvancedDataGridColumn dataField=&quot;Region&quot;/&gt; * &lt;mx:AdvancedDataGridColumn dataField=&quot;Territory_Rep&quot; * headerText=&quot;Territory Rep&quot;/&gt; * &lt;mx:AdvancedDataGridColumn dataField=&quot;Actual&quot;/&gt; * &lt;mx:AdvancedDataGridColumn dataField=&quot;Estimate&quot;/&gt; * &lt;mx:AdvancedDataGridColumn dataField=&quot;Min Actual&quot;/&gt; * &lt;mx:AdvancedDataGridColumn dataField=&quot;Max Actual&quot;/&gt; * &lt;/mx:columns&gt; * &lt;/mx:AdvancedDataGrid&gt; * </pre> * * <p>This Class has been deprecated and replaced by a new Class * <code>SummaryField2</code>. * Properties <code>operation</code> and <code>summaryFunction</code> are * not present in the Class <code>SummaryField2</code>. * A new property <code>summaryOperation</code> is introduced in * <code>SummaryField2</code>.</p> * * @see mx.controls.AdvancedDataGrid * @see mx.collections.GroupingField * @see mx.collections.SummaryRow * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Deprecated(replacement="SummaryField2", since="4.0")] public class SummaryField { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param dataField Data field for which the summary is computed. * * @param operation The function that should be performed on the children. * You can specify one of the following values for numeric fields: * <code>SUM</code>, <code>MIN</code>, <code>MAX</code>, <code>AVG</code>, or <code>COUNT</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function SummaryField(dataField:String = null, operation:String = "SUM") { super(); this.dataField = dataField; this.operation = operation; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // dataField //---------------------------------- /** * Data field for which the summary is computed. * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var dataField:String; //---------------------------------- // label //---------------------------------- /** * The property used inside the summary object, * an instance of the SummaryObject class, to * hold summary information. * * <p>For example, if you set the <code>label</code> property to "Summary", * then the computed summary is placed in a property named "Summary" * in the summary object. The property of the SummaryObject instance * containing the summary data will appear as below:</p> * * <pre>{Summary:1000}</pre> * * @see mx.collections.SummaryObject * @see mx.collections.SummaryRow#summaryObjectFunction * @see #summaryFunction * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var label:String; //---------------------------------- // operation //---------------------------------- /** * The function that should be performed on the children. * * You can specify one of the following values for numeric fields: * <code>SUM</code>, <code>MIN</code>, <code>MAX</code>, <code>AVG</code>, or <code>COUNT</code>. * * @default SUM * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var operation:String = "SUM"; //---------------------------------- // summaryFunction //---------------------------------- /** * Specifies a callback function to compute a custom data summary. * * <p>You use this property with the <code>SummaryRow.summaryObjectFunction</code> property, * which defines an instance of the SummaryObject class used * to collect summary data for display in the AdvancedDataGrid control.</p> * * <p>The function signature should be as follows:</p> * * <pre> * function mySummaryFunction(iterator:IViewCursor, dataField:String, operation:String):Object</pre> * * <p>The built-in summary functions for <code>SUM</code>, <code>MIN</code>, * <code>MAX</code>, <code>AVG</code>, and <code>COUNT</code> all return a Number containing * the summary data. </p> * * @see mx.collections.SummaryObject * @see mx.collections.SummaryRow#summaryObjectFunction * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var summaryFunction:Function; } }
/** @file mesh_render.as */ #include "assets.as" #include "icomponent.as" /** * @addtogroup Components * @{ **/ /** * @class MeshRender * @brief Mesh render component which can be attached to an entity * @author Hilze Vonck **/ class MeshRender : IComponent { void Initialize() final { Violet_Components_MeshRender::Create(GetId()); } void Destroy() final { Violet_Components_MeshRender::Destroy(GetId()); } /** * @brief Attaches a mesh to this mesh render. Will create child entities for all sub meshes * @param mesh (const Asset::Mesh&) The mesh that needs to be attached * @public **/ void Attach(const Asset::Mesh&in mesh) { Violet_Components_MeshRender::Attach(GetId(), mesh.GetId()); } /** * @brief Sets the mesh that will be used * @param mesh (const Asset::Mesh&) The mesh that will be used * @public **/ void SetMesh(const Asset::Mesh&in mesh) { Violet_Components_MeshRender::SetMesh(GetId(), mesh.GetId()); } /** * @brief Sets the sub mesh that will be used * @param sub_mesh (const uint16) The sub mesh that will be used * @public **/ void SetSubMesh(const uint16&in sub_mesh) { Violet_Components_MeshRender::SetSubMesh(GetId(), sub_mesh); } void SetAlbedoTexture(const Asset::Texture&in texture) { Violet_Components_MeshRender::SetAlbedoTexture(GetId(), texture.GetId()); } void SetNormalTexture(const Asset::Texture&in texture) { Violet_Components_MeshRender::SetNormalTexture(GetId(), texture.GetId()); } void SetMetallicRoughnessTexture(const Asset::Texture&in texture) { Violet_Components_MeshRender::SetMetallicRoughnessTexture(GetId(), texture.GetId()); } void MakeStatic() { Violet_Components_MeshRender::MakeStatic(GetId()); } void MakeStaticRecursive() { Violet_Components_MeshRender::MakeStaticRecursive(GetId()); } void MakeDynamic() { Violet_Components_MeshRender::MakeDynamic(GetId()); } void MakeDynamicRecursive() { Violet_Components_MeshRender::MakeDynamicRecursive(GetId()); } } /** * @} **/
package org.axgl.util.debug { import org.axgl.Ax; import org.axgl.AxGroup; import org.axgl.AxSprite; import org.axgl.resource.AxResource; import org.axgl.text.AxText; import org.axgl.text.AxTextLimitStrategy; import org.axgl.util.AxLogger; /** * A debug console that contains all the log messages on screen. You can adjust the layout of * the debug console via Ax.options, or by calling Ax.debugger.customReflow passing in your own * custom debug window layout. */ public class AxDebugConsole extends AxGroup { /** Lays the debug console on the bottom left in a small window. */ public static const BOTTOM_LEFT_LAYOUT:uint = 0; /** Lays the debug console on the left side of the screen, full height. */ public static const LEFT_SIDE_LAYOUT:uint = 1; /** Lays the debug console on the entire screen between the two debug bars. */ public static const FULL_SCREEN_LAYOUT:uint = 2; public static const CONSOLE_COLOR:uint = 0x77000000; public static const PADDING:uint = 6; public var background:AxSprite; public var text:AxText; public var messages:Vector.<String> = new Vector.<String>; public function AxDebugConsole() { this.add(background = new AxSprite(0, 0)); this.add(text = new AxText(5, 5, AxResource.font, "", Ax.viewWidth - 20)); background.scroll.x = background.scroll.y = 0; text.scroll.x = text.scroll.y = 0; background.zooms = text.zooms = false; visible = false; text.limitStrategy = new AxTextLimitStrategy(3, AxTextLimitStrategy.END); reflow(BOTTOM_LEFT_LAYOUT); } /** * Reflows the debug window based on a built in layout. * * @param layout The layout to use when reflowing the debug console. */ public function reflow(layout:uint):void { switch (layout) { case BOTTOM_LEFT_LAYOUT: customReflow(new AxDebugBottomLeftLayout); break; case LEFT_SIDE_LAYOUT: customReflow(new AxDebugLeftSideLayout); break; case FULL_SCREEN_LAYOUT: customReflow(new AxDebugFullScreenLayout); break; } } /** * Reflows the debug window based on an AxDebugLayout. You can call this to reflow * based on a custom debug layout. */ public function customReflow(layout:AxDebugLayout):void { layout.flow(this); } /** * Logs a message to the debug console. Unless necessary, you should typically be calling * functions on Ax.logger rather than this class directly. * * @param level The log level to use. * @param message The message to log. */ public function log(level:String, message:String):void { visible = true; messages.push(getDateTag() + " " + getLogTag(level) + " " + message); if (messages.length > text.limitStrategy.limit) { messages.splice(0, messages.length - text.limitStrategy.limit); } text.text = messages.join("\n"); } private static const INFO_TAG:String = "@[ffffff][@[89ee9c]INFO@[ffffff]]"; private static const WARN_TAG:String = "@[ffffff][@[ffb93f]WARN@[ffffff]]"; private static const ERROR_TAG:String = "@[ffffff][@[ff3f3f]ERROR@[ffffff]]"; private function getLogTag(level:String):String { switch (level) { case AxLogger.ERROR: return ERROR_TAG; case AxLogger.WARN: return WARN_TAG; default: return INFO_TAG; } } private function getDateTag():String { var date:Date = new Date; var dateString:String = date.hours + "@[ffffff]:@[aaaaaa]" + (date.minutes < 10 ? "0" + date.minutes : date.minutes) + "@[ffffff]:@[aaaaaa]" + (date.seconds < 10 ? "0" + date.seconds : date.seconds); return "@[ffffff][@[aaaaaa]" + dateString + "@[ffffff]]"; } } }
/* Copyright (c) 2010 Maxim Kachurovskiy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.cgpClient.mail.mime { public class MIMEReport { public function MIMEReport(xml:XML = null) { if (xml) update(xml); } private function update(xml:XML):void {} } }
import skyui.components.list.BasicList; import skyui.components.list.IListProcessor; import skyui.defines.Actor; import skyui.defines.Magic; import skyui.defines.Inventory; class MagicIconSetter implements IListProcessor { /* PRIVATE VARIABLES */ private var _noIconColors: Boolean; /* INITIALIZATION */ public function MagicIconSetter(a_configAppearance: Object) { _noIconColors = a_configAppearance.icons.item.noColor; } /* PUBLIC FUNCTIONS */ // @override IListProcessor public function processList(a_list: BasicList): Void { var entryList: Array = a_list.entryList; for (var i: Number = 0; i < entryList.length; i++) processEntry(entryList[i]); } /* PRIVATE FUNCTIONS */ private function processEntry(a_entryObject: Object): Void { switch (a_entryObject.type) { case Inventory.ICT_SPELL: processSpellIcon(a_entryObject); break; case Inventory.ICT_SHOUT: a_entryObject.iconLabel = "default_shout"; break; case Inventory.ICT_ACTIVE_EFFECT: a_entryObject.iconLabel = "default_effect"; break; case Inventory.ICT_SPELL_DEFAULT: a_entryObject.iconLabel = "default_power"; break; default: break; } if (_noIconColors && a_entryObject.iconColor != undefined) delete(a_entryObject.iconColor); } private function processSpellIcon(a_entryObject: Object): Void { a_entryObject.iconLabel = "default_power"; // fire rune, actorValue = Health, school = Destruction, resistance = Fire, effectFlags = hostile+detrimental switch(a_entryObject.school) { case Actor.AV_ALTERATION: a_entryObject.iconLabel = "default_alteration"; break; case Actor.AV_CONJURATION: a_entryObject.iconLabel = "default_conjuration"; break; case Actor.AV_DESTRUCTION: a_entryObject.iconLabel = "default_destruction"; processResist(a_entryObject); break; case Actor.AV_ILLUSION: a_entryObject.iconLabel = "default_illusion"; break; case Actor.AV_RESTORATION: a_entryObject.iconLabel = "default_restoration"; break; } } private function processResist(a_entryObject: Object): Void { if (a_entryObject.resistance == undefined || a_entryObject.resistance == Actor.AV_NONE) return; switch(a_entryObject.resistance) { case Actor.AV_FIRERESIST: a_entryObject.iconLabel = "magic_fire"; a_entryObject.iconColor = 0xC73636; break; case Actor.AV_ELECTRICRESIST: a_entryObject.iconLabel = "magic_shock"; a_entryObject.iconColor = 0xEAAB00; break; case Actor.AV_FROSTRESIST: a_entryObject.iconLabel = "magic_frost"; a_entryObject.iconColor = 0x1FFBFF; break; } } }
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2005-2007 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package spark.effects { import flash.display.DisplayObjectContainer; import mx.core.IVisualElement; import mx.core.IVisualElementContainer; import mx.core.mx_internal; import spark.effects.supportClasses.AddActionInstance; import mx.effects.IEffectInstance; import mx.effects.Effect; import mx.effects.effectClasses.PropertyChanges; use namespace mx_internal; //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name="duration", kind="property")] /** * The AddAction class defines an action effect that corresponds * to the <code>AddChild</code> property of a view state definition. * You use an AddAction effect within a transition definition * to control when the view state change defined by an AddChild property * occurs during the transition. * * @mxml * * <p>The <code>&lt;s:AddAction&gt;</code> tag * inherits all of the tag attributes of its superclass, * and adds the following tag attributes:</p> * * <pre> * &lt;s:AddAction * <b>Properties</b> * id="ID" * index="-1" * position="index" * relativeTo="" * /&gt; * </pre> * * @see spark.effects.supportClasses.AddActionInstance * @see mx.states.AddChild * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public class AddAction extends Effect { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @private */ private static var AFFECTED_PROPERTIES:Array = [ "parent", "index" ]; /** * Constant used to specify the position to add the item relative to the * object specified by the <code>relativeTo</code> property. * * @see #position * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public static const BEFORE:String = "before"; /** * Constant used to specify the position to add the item relative to the * object specified by the <code>relativeTo</code> property. * * @see #position * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public static const AFTER:String = "after"; /** * Constant used to specify the position to add the item relative to the * object specified by the <code>relativeTo</code> property. * * @see #position * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public static const FIRST_CHILD:String = "firstChild"; /** * Constant used to specify the position to add the item relative to the * object specified by the <code>relativeTo</code> property. * * @see #position * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public static const LAST_CHILD:String = "lastChild"; /** * Constant used to specify the position to add the item relative to the * object specified by the <code>relativeTo</code> property. * * @see #position * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public static const INDEX:String = "index"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param target The Object to animate with this effect. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function AddAction(target:Object = null) { super(target); duration = 0; instanceClass = AddActionInstance; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** * @private */ private var localPropertyChanges:Array; //---------------------------------- // index //---------------------------------- [Inspectable(category="General", minValue="-1")] /** * The index of the child within the parent. * A value of -1 means add the child as the last child of the parent. * * @default -1 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public var index:int = -1; //---------------------------------- // relativeTo //---------------------------------- [Inspectable(category="General")] /** * The location where the child component is added. * By default, Flex determines this value from the <code>AddChild</code> * property definition in the view state definition. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public var relativeTo:DisplayObjectContainer; //---------------------------------- // position //---------------------------------- [Inspectable(category="General")] /** * The position of the child in the display list, relative to the * object specified by the <code>relativeTo</code> property. * Valid values are <code>AddAction.BEFORE</code>, <code>AddAction.AFTER</code>, * <code>AddAction.FIRST_CHILD</code>, <code>AddAction.LAST_CHILD</code>, * and <code>AddAction.INDEX</code>, where <code>AddAction.INDEX</code> * specifies the use of the <code>index</code> property * to determine the position of the child. * * @default AddAction.INDEX * @see #BEFORE * @see #AFTER * @see #FIRST_CHILD * @see #LAST_CHILD * @see #INDEX * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public var position:String = INDEX; //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ override public function getAffectedProperties():Array /* of String */ { return AFFECTED_PROPERTIES; } /** * @private */ private function getPropertyChanges(target:Object):PropertyChanges { for (var i:int = 0; i < localPropertyChanges.length; i++) { if (localPropertyChanges[i].target == target) return localPropertyChanges[i]; } return null; } /** * @private */ private function targetSortHandler(first:Object, second:Object):Number { var p1:PropertyChanges = getPropertyChanges(first); var p2:PropertyChanges = getPropertyChanges(second); if (p1 && p2) { if (p1.start.index > p2.start.index) return 1; else if (p1.start.index < p2.start.index) return -1; } return 0; } /** * @private */ override public function createInstances(targets:Array = null):Array /* of EffectInstance */ { if (!targets) targets = this.targets; if (targets && propertyChangesArray) { localPropertyChanges = propertyChangesArray; targets.sort(targetSortHandler); } return super.createInstances(targets); } /** * @private */ override protected function initInstance(instance:IEffectInstance):void { super.initInstance(instance); var actionInstance:AddActionInstance = AddActionInstance(instance); actionInstance.relativeTo = relativeTo; actionInstance.index = index; actionInstance.position = position; } /** * @private */ override protected function getValueFromTarget(target:Object, property:String):* { var container:* = target.parent; if (property == "index") return container ? ((container is IVisualElementContainer) ? IVisualElementContainer(container).getElementIndex(target as IVisualElement) : container.getChildIndex(target)) : 0; return super.getValueFromTarget(target, property); } /** * @private */ override protected function applyValueToTarget(target:Object, property:String, value:*, props:Object):void { if (property == "parent" && value == undefined) { if (target.parent) { if (target.parent is IVisualElementContainer) IVisualElementContainer(target.parent).removeElement(target as IVisualElement); else target.parent.removeChild(target); } } // Ignore index - it's applied along with parent } } }
package feathers.examples.componentsExplorer.screens { import feathers.controls.Button; import feathers.controls.GroupedList; import feathers.controls.Header; import feathers.controls.Screen; import feathers.data.HierarchicalCollection; import feathers.examples.componentsExplorer.data.GroupedListSettings; import starling.display.DisplayObject; import starling.events.Event; [Event(name="complete",type="starling.events.Event")] [Event(name="showSettings",type="starling.events.Event")] public class GroupedListScreen extends Screen { public static const SHOW_SETTINGS:String = "showSettings"; public function GroupedListScreen() { super(); } public var settings:GroupedListSettings; private var _list:GroupedList; private var _header:Header; private var _backButton:Button; private var _settingsButton:Button; override protected function initialize():void { var groups:Array = [ { header: "A", children: [ { text: "Aardvark" }, { text: "Alligator" }, { text: "Alpaca" }, { text: "Anteater" }, ] }, { header: "B", children: [ { text: "Baboon" }, { text: "Bear" }, { text: "Beaver" }, ] }, { header: "C", children: [ { text: "Canary" }, { text: "Cat" }, ] }, { header: "D", children: [ { text: "Deer" }, { text: "Dingo" }, { text: "Dog" }, { text: "Dolphin" }, { text: "Donkey" }, { text: "Dragonfly" }, { text: "Duck" }, { text: "Dung Beetle" }, ] }, { header: "E", children: [ { text: "Eagle" }, { text: "Earthworm" }, { text: "Eel" }, { text: "Elk" }, ] } ]; groups.fixed = true; this._list = new GroupedList(); if(this.settings.style == GroupedListSettings.STYLE_INSET) { this._list.nameList.add(GroupedList.ALTERNATE_NAME_INSET_GROUPED_LIST); } this._list.dataProvider = new HierarchicalCollection(groups); this._list.typicalItem = { text: "Item 1000" }; this._list.typicalHeader = "Group 10"; this._list.typicalFooter = "Footer 10"; this._list.isSelectable = this.settings.isSelectable; this._list.scrollerProperties.hasElasticEdges = this.settings.hasElasticEdges; this._list.itemRendererProperties.labelField = "text"; this._list.addEventListener(Event.CHANGE, list_changeHandler); this.addChildAt(this._list, 0); this._backButton = new Button(); this._backButton.label = "Back"; this._backButton.addEventListener(Event.TRIGGERED, backButtontriggeredHandler); this._settingsButton = new Button(); this._settingsButton.label = "Settings"; this._settingsButton.addEventListener(Event.TRIGGERED, settingsButtontriggeredHandler); this._header = new Header(); this._header.title = "Grouped List"; this.addChild(this._header); this._header.leftItems = new <DisplayObject> [ this._backButton ]; this._header.rightItems = new <DisplayObject> [ this._settingsButton ]; // handles the back hardware key on android this.backButtonHandler = this.onBackButton; } override protected function draw():void { this._header.width = this.actualWidth; this._header.validate(); this._list.y = this._header.height; this._list.width = this.actualWidth; this._list.height = this.actualHeight - this._list.y; this._list.validate(); } private function onBackButton():void { this.dispatchEventWith(Event.COMPLETE); } private function backButtontriggeredHandler(event:Event):void { this.onBackButton(); } private function settingsButtontriggeredHandler(event:Event):void { this.dispatchEventWith(SHOW_SETTINGS); } private function list_changeHandler(event:Event):void { trace("GroupedList onChange:", this._list.selectedGroupIndex, this._list.selectedItemIndex); } } }
package { import flash.display.Bitmap; import flash.display.BitmapData; import flash.filesystem.File; import flash.geom.Point; import net.flashpunk.Entity; import net.flashpunk.Graphic; import net.flashpunk.graphics.Image; import net.flashpunk.Mask; import net.flashpunk.utils.Input; /** * ... * @author jjp */ public class Factory extends EntitySidebarImg { private var bmp: BitmapData; private var urpf: String; private var filewatcher: FileWatcher; public function Factory(sidebar: Sidebar, urpf: String, bmp:BitmapData) { super(sidebar, bmp, sidebar.width); this.bmp = bmp; this.urpf = urpf; } override public function added():void { super.added(); var stage: WorldStage = WorldStage(world); filewatcher = FileWatcher.Get(stage.UabFromUrf(stage.UrfFromUrp(urpf))); filewatcher.Register(function(bmpNew:BitmapData, file:File):void { bmp = bmpNew; OnImgReload(bmpNew, file); }, this); } override public function removed():void { super.removed(); filewatcher.Unregister(this); } override public function OnClick():void { var worldStage: WorldStage = WorldStage(world); var posMouseReal: Point = worldStage.PointRealFromScreen(new Point(Input.mouseX, Input.mouseY)); var urffBmp: String = worldStage.UrfFromUrp(urpf); var tok: Token = new Token(bmp, urffBmp, posMouseReal.x - this.bmp.width / 2, posMouseReal.y - this.bmp.height / 2); world.add(tok); worldStage.tokSelected = tok; } } }
package serverProto.rolePromote { import com.netease.protobuf.Message; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_MESSAGE; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_SINT32; import com.netease.protobuf.WireType; import serverProto.inc.ProtoRetInfo; import com.netease.protobuf.WritingBuffer; import com.netease.protobuf.WriteUtils; import flash.utils.IDataInput; import com.netease.protobuf.ReadUtils; import flash.errors.IOError; public final class ProtoGetRolePromoteInfoResponse extends Message { public static const RET:FieldDescriptor$TYPE_MESSAGE = new FieldDescriptor$TYPE_MESSAGE("serverProto.rolePromote.ProtoGetRolePromoteInfoResponse.ret","ret",1 << 3 | WireType.LENGTH_DELIMITED,ProtoRetInfo); public static const REMAIN_STAR:FieldDescriptor$TYPE_SINT32 = new FieldDescriptor$TYPE_SINT32("serverProto.rolePromote.ProtoGetRolePromoteInfoResponse.remain_star","remainStar",2 << 3 | WireType.VARINT); public static const PREV_START:FieldDescriptor$TYPE_SINT32 = new FieldDescriptor$TYPE_SINT32("serverProto.rolePromote.ProtoGetRolePromoteInfoResponse.prev_start","prevStart",3 << 3 | WireType.VARINT); public static const ATTR_INFO:FieldDescriptor$TYPE_MESSAGE = new FieldDescriptor$TYPE_MESSAGE("serverProto.rolePromote.ProtoGetRolePromoteInfoResponse.attr_info","attrInfo",4 << 3 | WireType.LENGTH_DELIMITED,ProtoPromoteAttrInfo); public var ret:ProtoRetInfo; private var remain_star$field:int; private var hasField$0:uint = 0; private var prev_start$field:int; private var attr_info$field:serverProto.rolePromote.ProtoPromoteAttrInfo; public function ProtoGetRolePromoteInfoResponse() { super(); } public function clearRemainStar() : void { this.hasField$0 = this.hasField$0 & 4.294967294E9; this.remain_star$field = new int(); } public function get hasRemainStar() : Boolean { return (this.hasField$0 & 1) != 0; } public function set remainStar(param1:int) : void { this.hasField$0 = this.hasField$0 | 1; this.remain_star$field = param1; } public function get remainStar() : int { return this.remain_star$field; } public function clearPrevStart() : void { this.hasField$0 = this.hasField$0 & 4.294967293E9; this.prev_start$field = new int(); } public function get hasPrevStart() : Boolean { return (this.hasField$0 & 2) != 0; } public function set prevStart(param1:int) : void { this.hasField$0 = this.hasField$0 | 2; this.prev_start$field = param1; } public function get prevStart() : int { return this.prev_start$field; } public function clearAttrInfo() : void { this.attr_info$field = null; } public function get hasAttrInfo() : Boolean { return this.attr_info$field != null; } public function set attrInfo(param1:serverProto.rolePromote.ProtoPromoteAttrInfo) : void { this.attr_info$field = param1; } public function get attrInfo() : serverProto.rolePromote.ProtoPromoteAttrInfo { return this.attr_info$field; } override final function writeToBuffer(param1:WritingBuffer) : void { var _loc2_:* = undefined; WriteUtils.writeTag(param1,WireType.LENGTH_DELIMITED,1); WriteUtils.write$TYPE_MESSAGE(param1,this.ret); if(this.hasRemainStar) { WriteUtils.writeTag(param1,WireType.VARINT,2); WriteUtils.write$TYPE_SINT32(param1,this.remain_star$field); } if(this.hasPrevStart) { WriteUtils.writeTag(param1,WireType.VARINT,3); WriteUtils.write$TYPE_SINT32(param1,this.prev_start$field); } if(this.hasAttrInfo) { WriteUtils.writeTag(param1,WireType.LENGTH_DELIMITED,4); WriteUtils.write$TYPE_MESSAGE(param1,this.attr_info$field); } for(_loc2_ in this) { super.writeUnknown(param1,_loc2_); } } override final function readFromSlice(param1:IDataInput, param2:uint) : void { /* * Decompilation error * Code may be obfuscated * Tip: You can try enabling "Automatic deobfuscation" in Settings * Error type: IndexOutOfBoundsException (Index: 4, Size: 4) */ throw new flash.errors.IllegalOperationError("Not decompiled due to error"); } } }
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2009 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package mx.olap { import flash.utils.Dictionary; import mx.collections.ArrayCollection; import mx.collections.IList; import mx.core.mx_internal; /** * The OLAPMember class represents a member of an OLAP dimension. * * @mxml * <p> * The <code>&lt;mx:OLAPMember&gt;</code> tag inherits all of the tag attributes * of its superclass, and adds the following tag attributes: * </p> * <pre> * &lt;mx:OLAPMember * <b>Properties</b> * /&gt; * * @see mx.olap.IOLAPMember * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class OLAPMember extends OLAPElement implements IOLAPMember { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor * * @param name The name of the OLAP element that includes the OLAP schema hierarchy of the element. * For example, "Time_Year", where "Year" is a level of the "Time" dimension in an OLAP schema. * * @param displayName The name of the OLAP member, as a String, which can be used for display. * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function OLAPMember(name:String=null, displayName:String=null) { OLAPTrace.traceMsg("Creating member: " + name, OLAPTrace.TRACE_LEVEL_3); super(name, displayName); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * A child members map based on their name */ private var _childrenMap:Dictionary = new Dictionary(true); //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- //---------------------------------- // dimension //---------------------------------- /** * The dimension to which this member belongs. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function get dimension():IOLAPDimension { if (level && level.hierarchy) return level.hierarchy.dimension; return null; } //---------------------------------- // uniqueName //---------------------------------- /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function get uniqueName():String { var list:Array = []; list.push(this); var parent:IOLAPMember = this.parent; // if the member is from a OLAPAttribute then // we only need to push the hierarchy name if (hierarchy is OLAPAttribute) { list.push(hierarchy); } else { // if the member is from a OLAPHierarchy then we need to traverse // its parents till we reach the top level. while (parent && parent.parent) { list.push(parent); parent = parent.parent; } list.push(hierarchy.levels.getItemAt(0)); list.push(hierarchy); } list.push(dimension); var uName:String = ""; var n:int = list.length; for (var i:int = n - 1; i > -1; --i) uName += "[" + list[i].name + "]."; uName = uName.substring(0, uName.length-1); return uName; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // children //---------------------------------- private var _children:IList = new ArrayCollection; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get children():IList { return _children; } //---------------------------------- // dataField //---------------------------------- private var _dataField:String; /** * The field of the input data set that provides * the data for this OLAPMember instance. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get dataField():String { return _dataField; } /** * @private */ public function set dataField(field:String):void { _dataField = field; } //---------------------------------- // hierarchy //---------------------------------- /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get hierarchy():IOLAPHierarchy { return level.hierarchy; } //---------------------------------- // isAll //---------------------------------- private var _all:Boolean = false; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get isAll():Boolean { return _all; } //---------------------------------- // isMeasure //---------------------------------- /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get isMeasure():Boolean { return false; } //---------------------------------- // level //---------------------------------- private var _level:IOLAPLevel; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get level():IOLAPLevel { return _level; } /** * @private */ public function set level(level:IOLAPLevel):void { _level = level; } //---------------------------------- // parent //---------------------------------- private var _parent:IOLAPMember; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get parent():IOLAPMember { return _parent; } /** * @private */ public function set parent(p:IOLAPMember):void { _parent = p; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function findChildMember(name:String):IOLAPMember { return _childrenMap[name]; } /** * Sets this member as the all member. * By default, the member is not the all member. * * @param value <code>true</code> to make this member the all member. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function setIsAll(value:Boolean):void { _all = value; } /** * @private * * Adds a child member to this member. * * @param m The child member to add. */ mx_internal function addChild(m:IOLAPMember):void { _children.addItem(m); _childrenMap[m.name] = m; } } }
// // $Id$ package com.threerings.msoy.notify.data { import com.threerings.io.ObjectInputStream; import com.threerings.util.MessageBundle; import com.threerings.util.Name; import com.threerings.orth.notify.data.Notification; import com.threerings.msoy.data.all.MemberName; /** * Notifies a user that an invitation was accepted */ public class InviteAcceptedNotification extends Notification { // from Notification override public function getAnnouncement () :String { return MessageBundle.tcompose( "m.invite_accepted", _inviteeEmail, _invitee, _invitee.getId()); } // from Notification override public function getCategory () :int { return PERSONAL; } // from Notification override public function getSender () :Name { return _invitee; } override public function readObject (ins :ObjectInputStream) :void { super.readObject(ins); _invitee = MemberName(ins.readObject()); _inviteeEmail = ins.readField(String) as String; } protected var _invitee :MemberName; protected var _inviteeEmail :String; } }
/** * ... * @author Default * @version 0.1 */ package org.papervision3d.core.effects { import flash.filters.ColorMatrixFilter; import flash.geom.Point; import org.papervision3d.view.layer.BitmapEffectLayer; public class BitmapColorEffect extends AbstractEffect{ private var layer:BitmapEffectLayer; private var filter:ColorMatrixFilter; public function BitmapColorEffect(r:Number = 1, g:Number = 1, b:Number = 1, a:Number= 1){ filter = new ColorMatrixFilter( [r,0,0,0,0, 0,g,0,0,0, 0,0,b,0,0, 0,0,0,a,0] ); } public function updateEffect(r:Number = 1, g:Number = 1, b:Number = 1, a:Number= 1):void{ filter = new ColorMatrixFilter( [r,0,0,0,0, 0,g,0,0,0, 0,0,b,0,0, 0,0,0,a,0] ); } public override function attachEffect(layer:BitmapEffectLayer):void{ this.layer = BitmapEffectLayer(layer); } public override function postRender():void{ layer.canvas.applyFilter(layer.canvas, layer.canvas.rect, new Point(), filter); } } }
package assets { import assets.xml.AtlasXML; import assets.xml.FontXML; import flash.ui.Keyboard; import native_controls.ProgressBar; import starling.text.BitmapFont; import starling.text.TextField; import starling.textures.TextureAtlas; import starling.utils.AssetManager; public class AssetLoader { [Embed(source = "../../res/fonts/unispace/tt/unispace bd.ttf", embedAsCFF = "false", fontFamily = "Unispace", unicodeRange = "U+0020-U+007e")] private static const Unispace:Class; private var boss:Main; private var assetManager:AssetManager; private var progressBar:ProgressBar; public function AssetLoader(boss:Main) { this.progressBar = new ProgressBar(); boss.addChild(this.progressBar); this.boss = boss; this.assetManager = new AssetManager(); this.assetManager.verbose = true; this.assetManager.enqueue(EmbeddedAssets); this.assetManager.loadQueue(this.assetsProgress); } private function assetsProgress(ratio:Number):void { this.progressBar.redraw(ratio); if (ratio == 1.0) { this.removeAll(); initializeAtlasMakerAtlases(this.assetManager, AtlasXML.getOne()); var atlas:TextureAtlas = this.assetManager.getTextureAtlas(View.MAIN_ATLAS); this.addFonts(atlas); validateTheMap(); this.boss.initializeEverything(this.assetManager); } } private function removeAll():void { this.boss.removeChild(this.progressBar); this.progressBar = null; } private function addFonts(atlas:TextureAtlas):void { var bbxml:XML = FontXML.getBananaBrickXML(); for each (var char:XML in bbxml.chars.char) { if (parseInt(char.@id) != Keyboard.SPACE) char.@xadvance = (parseInt(char.@xoffset) + parseInt(char.@width)); } TextField.registerBitmapFont(new BitmapFont( atlas.getTexture("BananaBrick"), bbxml), "BananaBrick"); } } }
package feathers.examples.video { import feathers.controls.ImageLoader; import feathers.controls.LayoutGroup; import feathers.events.MediaPlayerEventType; import feathers.layout.AnchorLayout; import feathers.layout.AnchorLayoutData; import feathers.layout.HorizontalLayoutData; import feathers.media.FullScreenToggleButton; import feathers.media.MuteToggleButton; import feathers.media.PlayPauseToggleButton; import feathers.media.SeekSlider; import feathers.media.VideoPlayer; import feathers.themes.MetalWorksDesktopTheme; import flash.desktop.NativeApplication; import flash.display.NativeMenu; import flash.display.NativeMenuItem; import flash.events.ContextMenuEvent; import flash.filesystem.File; import flash.net.FileFilter; import starling.core.Starling; import starling.display.Sprite; import starling.events.Event; public class Main extends Sprite { public function Main() { new MetalWorksDesktopTheme(); super(); this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler); } protected var _videoPlayer:VideoPlayer protected var _controls:LayoutGroup; protected var _playPauseButton:PlayPauseToggleButton; protected var _seekSlider:SeekSlider; protected var _muteButton:MuteToggleButton; protected var _fullScreenButton:FullScreenToggleButton; protected var _view:ImageLoader; protected var _fullScreenItem:NativeMenuItem; protected var _fileToOpen:File; private function addedToStageHandler(event:starling.events.Event):void { this.createMenu(); this._videoPlayer = new VideoPlayer(); this._videoPlayer.autoSizeMode = LayoutGroup.AUTO_SIZE_MODE_STAGE; this._videoPlayer.layout = new AnchorLayout(); this._videoPlayer.addEventListener(Event.READY, videoPlayer_readyHandler); this._videoPlayer.addEventListener(MediaPlayerEventType.DISPLAY_STATE_CHANGE, videoPlayer_displayStateChangeHandler); this.addChild(this._videoPlayer); this._view = new ImageLoader(); this._videoPlayer.addChild(this._view); this._controls = new LayoutGroup(); this._controls.touchable = false; this._controls.styleNameList.add(LayoutGroup.ALTERNATE_STYLE_NAME_TOOLBAR); this._videoPlayer.addChild(this._controls); this._playPauseButton = new PlayPauseToggleButton(); this._controls.addChild(this._playPauseButton); this._seekSlider = new SeekSlider(); this._seekSlider.layoutData = new HorizontalLayoutData(100); this._controls.addChild(this._seekSlider); this._muteButton = new MuteToggleButton(); this._controls.addChild(this._muteButton); this._fullScreenButton = new FullScreenToggleButton(); this._controls.addChild(this._fullScreenButton); var controlsLayoutData:AnchorLayoutData = new AnchorLayoutData(); controlsLayoutData.left = 0; controlsLayoutData.right = 0; controlsLayoutData.bottom = 0; this._controls.layoutData = controlsLayoutData; var viewLayoutData:AnchorLayoutData = new AnchorLayoutData(0, 0, 0, 0); viewLayoutData.bottomAnchorDisplayObject = this._controls; this._view.layoutData = viewLayoutData; } protected function createMenu():void { var menu:NativeMenu; if(NativeApplication.supportsMenu) { menu = NativeApplication.nativeApplication.menu; var applicationMenuItem:NativeMenuItem = menu.getItemAt(0); menu.removeAllItems(); menu.addItem(applicationMenuItem); } else { menu = new NativeMenu(); Starling.current.nativeStage.nativeWindow.menu = menu; } var fileMenuItem:NativeMenuItem = new NativeMenuItem("File"); var fileMenu:NativeMenu = new NativeMenu(); fileMenuItem.submenu = fileMenu; menu.addItem(fileMenuItem); var openItem:NativeMenuItem = new NativeMenuItem("Open"); openItem.keyEquivalent = "o"; openItem.addEventListener(flash.events.Event.SELECT, openItem_selectHandler); fileMenu.addItem(openItem); var closeItem:NativeMenuItem = new NativeMenuItem("Close"); closeItem.keyEquivalent = "w"; closeItem.addEventListener(flash.events.Event.SELECT, closeItem_selectHandler); fileMenu.addItem(closeItem); var viewMenuItem:NativeMenuItem = new NativeMenuItem("View"); var viewMenu:NativeMenu = new NativeMenu(); viewMenuItem.submenu = viewMenu; menu.addItem(viewMenuItem); this._fullScreenItem = new NativeMenuItem("Enter Full Screen"); this._fullScreenItem.keyEquivalent = "f"; this._fullScreenItem.addEventListener(flash.events.Event.SELECT, fullScreenItem_selectHandler); viewMenu.addItem(this._fullScreenItem); if(NativeApplication.supportsMenu) { var windowMenuItem:NativeMenuItem = new NativeMenuItem("Window"); var windowMenu:NativeMenu = new NativeMenu(); windowMenuItem.submenu = windowMenu; menu.addItem(windowMenuItem); var minimizeItem:NativeMenuItem = new NativeMenuItem("Minimize"); minimizeItem.keyEquivalent = "m"; minimizeItem.addEventListener(flash.events.Event.SELECT, minimizeItem_selectHandler); windowMenu.addItem(minimizeItem); var zoomItem:NativeMenuItem = new NativeMenuItem("Zoom"); zoomItem.addEventListener(flash.events.Event.SELECT, zoomItem_selectHandler); windowMenu.addItem(zoomItem); } } protected function videoPlayer_readyHandler(event:Event):void { this._view.source = this._videoPlayer.texture; this._controls.touchable = true; } protected function videoPlayer_displayStateChangeHandler(event:Event):void { this._fullScreenItem.label = this._videoPlayer.isFullScreen ? "Exit Full Screen" : "Enter Full Screen"; } protected function openItem_selectHandler(event:flash.events.Event):void { this._fileToOpen = new File(); this._fileToOpen.addEventListener(flash.events.Event.SELECT, fileToOpen_selectHandler); this._fileToOpen.addEventListener(flash.events.Event.CANCEL, fileToOpen_cancelHandler); this._fileToOpen.browseForOpen("Select video file", [ new FileFilter("Video files", "*.m4v;*.mp4;*.f4v;*.flv;*.mov") ]); } protected function closeItem_selectHandler(event:flash.events.Event):void { //we don't need to dispose the texture here. the VideoPlayer will //do it automatically when videoSource is changed. this._view.source = null; this._videoPlayer.videoSource = null; this._controls.touchable = false; } protected function fileToOpen_cancelHandler(event:flash.events.Event):void { this._fileToOpen.removeEventListener(flash.events.Event.SELECT, fileToOpen_selectHandler); this._fileToOpen.removeEventListener(flash.events.Event.CANCEL, fileToOpen_cancelHandler); this._fileToOpen = null; } protected function fileToOpen_selectHandler(event:flash.events.Event):void { if(this._videoPlayer.videoSource === this._fileToOpen.url) { //it's the same file, so just start it over instead of trying //to load it again! this._videoPlayer.stop(); this._videoPlayer.play(); return; } this._controls.touchable = false; this._videoPlayer.videoSource = this._fileToOpen.url; this._fileToOpen.removeEventListener(flash.events.Event.SELECT, fileToOpen_selectHandler); this._fileToOpen.removeEventListener(flash.events.Event.CANCEL, fileToOpen_cancelHandler); this._fileToOpen = null; } protected function fullScreenItem_selectHandler(event:flash.events.Event):void { this._videoPlayer.toggleFullScreen(); } protected function minimizeItem_selectHandler(event:flash.events.Event):void { Starling.current.nativeStage.nativeWindow.minimize(); } protected function zoomItem_selectHandler(event:flash.events.Event):void { Starling.current.nativeStage.nativeWindow.maximize(); } } }
package com.ankamagames.dofus.network.messages.game.inventory.storage { import com.ankamagames.jerakine.network.CustomDataWrapper; import com.ankamagames.jerakine.network.ICustomDataInput; import com.ankamagames.jerakine.network.ICustomDataOutput; import com.ankamagames.jerakine.network.INetworkMessage; import com.ankamagames.jerakine.network.NetworkMessage; import com.ankamagames.jerakine.network.utils.FuncTree; import flash.utils.ByteArray; public class StorageObjectsRemoveMessage extends NetworkMessage implements INetworkMessage { public static const protocolId:uint = 7279; private var _isInitialized:Boolean = false; public var objectUIDList:Vector.<uint>; private var _objectUIDListtree:FuncTree; public function StorageObjectsRemoveMessage() { this.objectUIDList = new Vector.<uint>(); super(); } override public function get isInitialized() : Boolean { return this._isInitialized; } override public function getMessageId() : uint { return 7279; } public function initStorageObjectsRemoveMessage(objectUIDList:Vector.<uint> = null) : StorageObjectsRemoveMessage { this.objectUIDList = objectUIDList; this._isInitialized = true; return this; } override public function reset() : void { this.objectUIDList = new Vector.<uint>(); this._isInitialized = false; } override public function pack(output:ICustomDataOutput) : void { var data:ByteArray = new ByteArray(); this.serialize(new CustomDataWrapper(data)); writePacket(output,this.getMessageId(),data); } override public function unpack(input:ICustomDataInput, length:uint) : void { this.deserialize(input); } override public function unpackAsync(input:ICustomDataInput, length:uint) : FuncTree { var tree:FuncTree = new FuncTree(); tree.setRoot(input); this.deserializeAsync(tree); return tree; } public function serialize(output:ICustomDataOutput) : void { this.serializeAs_StorageObjectsRemoveMessage(output); } public function serializeAs_StorageObjectsRemoveMessage(output:ICustomDataOutput) : void { output.writeShort(this.objectUIDList.length); for(var _i1:uint = 0; _i1 < this.objectUIDList.length; _i1++) { if(this.objectUIDList[_i1] < 0) { throw new Error("Forbidden value (" + this.objectUIDList[_i1] + ") on element 1 (starting at 1) of objectUIDList."); } output.writeVarInt(this.objectUIDList[_i1]); } } public function deserialize(input:ICustomDataInput) : void { this.deserializeAs_StorageObjectsRemoveMessage(input); } public function deserializeAs_StorageObjectsRemoveMessage(input:ICustomDataInput) : void { var _val1:uint = 0; var _objectUIDListLen:uint = input.readUnsignedShort(); for(var _i1:uint = 0; _i1 < _objectUIDListLen; _i1++) { _val1 = input.readVarUhInt(); if(_val1 < 0) { throw new Error("Forbidden value (" + _val1 + ") on elements of objectUIDList."); } this.objectUIDList.push(_val1); } } public function deserializeAsync(tree:FuncTree) : void { this.deserializeAsyncAs_StorageObjectsRemoveMessage(tree); } public function deserializeAsyncAs_StorageObjectsRemoveMessage(tree:FuncTree) : void { this._objectUIDListtree = tree.addChild(this._objectUIDListtreeFunc); } private function _objectUIDListtreeFunc(input:ICustomDataInput) : void { var length:uint = input.readUnsignedShort(); for(var i:uint = 0; i < length; i++) { this._objectUIDListtree.addChild(this._objectUIDListFunc); } } private function _objectUIDListFunc(input:ICustomDataInput) : void { var _val:uint = input.readVarUhInt(); if(_val < 0) { throw new Error("Forbidden value (" + _val + ") on elements of objectUIDList."); } this.objectUIDList.push(_val); } } }
/* Copyright (C) 2012 John Nesky Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package beepbox.synth { public class BarPattern { public var notes: Array; public var instrument: int; public function BarPattern() { notes = []; instrument = 0; //notes = [new Note(12, 0, 8)]; //notes[0].pins = [new NotePin(0, 0), new NotePin(0, 3), new NotePin(2, 4), new NotePin(2, 8)]; } public function cloneNotes(): Array { var result: Array = []; for each (var oldNote: Note in notes) { var newNote: Note = new Note(-1, oldNote.start, oldNote.end, 3); newNote.pitches = oldNote.pitches.concat(); newNote.pins = []; for each (var oldPin: NotePin in oldNote.pins) { newNote.pins.push(new NotePin(oldPin.interval, oldPin.time, oldPin.volume)); } result.push(newNote); } return result; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.royale.html.beads.controllers { COMPILE::JS { import org.apache.royale.html.Spinner; import org.apache.royale.html.supportClasses.SpinnerButton; import goog.events; import goog.events.EventType; } import org.apache.royale.core.IBeadController; import org.apache.royale.core.IRangeModel; import org.apache.royale.core.IStrand; import org.apache.royale.core.UIBase; import org.apache.royale.events.Event; import org.apache.royale.events.IEventDispatcher; import org.apache.royale.events.MouseEvent; import org.apache.royale.events.ValueChangeEvent; import org.apache.royale.html.TextButton; import org.apache.royale.html.beads.ISpinnerView; import org.apache.royale.utils.sendStrandEvent; import org.apache.royale.core.Bead; /** * The SpinnerMouseController class bead handles mouse events on the * org.apache.royale.html.Spinner's component buttons, changing the * value of the Spinner. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9 */ public class SpinnerMouseController extends Bead implements IBeadController { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9 */ public function SpinnerMouseController() { } private var rangeModel:IRangeModel; /** * @copy org.apache.royale.core.IBead#strand * * @royaleignorecoercion org.apache.royale.html.Spinner * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9 * @royaleignorecoercion org.apache.royale.html.beads.ISpinnerView * @royaleignorecoercion org.apache.royale.core.UIBase * @royaleignorecoercion org.apache.royale.core.IRangeModel */ override public function set strand(value:IStrand):void { _strand = value; rangeModel = UIBase(value).model as IRangeModel; COMPILE::SWF { var spinnerBead:ISpinnerView = value.getBeadByType(ISpinnerView) as ISpinnerView; spinnerBead.decrement.addEventListener(MouseEvent.CLICK, decrementClickHandler); spinnerBead.decrement.addEventListener("buttonRepeat", decrementClickHandler); spinnerBead.increment.addEventListener(MouseEvent.CLICK, incrementClickHandler); spinnerBead.increment.addEventListener("buttonRepeat", incrementClickHandler); } COMPILE::JS { var spinnerBead:ISpinnerView = value.getBeadByType(ISpinnerView) as ISpinnerView; var incrementButton:SpinnerButton = spinnerBead.increment; var decrementButton:SpinnerButton = spinnerBead.decrement; goog.events.listen(incrementButton.element, goog.events.EventType.CLICK, incrementClickHandler); goog.events.listen(decrementButton.element, goog.events.EventType.CLICK, decrementClickHandler); } } /** * @private * @royaleignorecoercion org.apache.royale.events.IEventDispatcher */ private function decrementClickHandler( event:org.apache.royale.events.MouseEvent ) : void { var oldValue:Number = rangeModel.value; rangeModel.value = Math.max(rangeModel.minimum, rangeModel.value - rangeModel.stepSize); var vce:ValueChangeEvent = ValueChangeEvent.createUpdateEvent(_strand, "value", oldValue, rangeModel.value); sendStrandEvent(_strand,vce); } /** * @private * @royaleignorecoercion org.apache.royale.events.IEventDispatcher */ private function incrementClickHandler( event:org.apache.royale.events.MouseEvent ) : void { var oldValue:Number = rangeModel.value; rangeModel.value = Math.min(rangeModel.maximum, rangeModel.value + rangeModel.stepSize); var vce:ValueChangeEvent = ValueChangeEvent.createUpdateEvent(_strand, "value", oldValue, rangeModel.value); sendStrandEvent(_strand,vce); } } }
package kabam.lib.net.impl { import com.company.assembleegameclient.parameters.Parameters; import com.hurlant.crypto.symmetric.ICipher; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.events.TimerEvent; import flash.net.Socket; import flash.utils.ByteArray; import flash.utils.Timer; import kabam.lib.net.api.MessageProvider; import org.osflash.signals.Signal; public class SocketServer { public static const MESSAGE_LENGTH_SIZE_IN_BYTES:int = 4; public const connected:Signal = new Signal(); public const closed:Signal = new Signal(); public const error:Signal = new Signal(String); private const unsentPlaceholder:Message = new Message(0); private const data:ByteArray = new ByteArray(); [Inject] public var messages:MessageProvider; [Inject] public var socket:Socket; [Inject] public var socketServerModel:SocketServerModel; public var delayTimer:Timer; private var head:Message; private var tail:Message; private var messageLen:int = -1; private var outgoingCipher:ICipher; private var incomingCipher:ICipher; private var server:String; private var port:int; public function SocketServer() { this.head = this.unsentPlaceholder; this.tail = this.unsentPlaceholder; super(); } public function setOutgoingCipher(cipher:ICipher):SocketServer { this.outgoingCipher = cipher; return this; } public function setIncomingCipher(cipher:ICipher):SocketServer { this.incomingCipher = cipher; return this; } public function connect(address:String, port:int):void { this.server = address; this.port = port; this.addListeners(); this.messageLen = -1; if (this.socketServerModel.connectDelayMS) { this.connectWithDelay(); } else { this.socket.connect(address, port); } } private function addListeners():void { this.socket.addEventListener(Event.CONNECT, this.onConnect); this.socket.addEventListener(Event.CLOSE, this.onClose); this.socket.addEventListener(ProgressEvent.SOCKET_DATA, this.onSocketData); this.socket.addEventListener(IOErrorEvent.IO_ERROR, this.onIOError); this.socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onSecurityError); } private function connectWithDelay():void { this.delayTimer = new Timer(this.socketServerModel.connectDelayMS, 1); this.delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE, this.onTimerComplete); this.delayTimer.start(); } private function onTimerComplete(_arg1:TimerEvent):void { this.delayTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, this.onTimerComplete); this.socket.connect(this.server, this.port); } public function disconnect():void { try { this.socket.close(); } catch (error:Error) { } this.removeListeners(); this.closed.dispatch(); } private function removeListeners():void { this.socket.removeEventListener(Event.CONNECT, this.onConnect); this.socket.removeEventListener(Event.CLOSE, this.onClose); this.socket.removeEventListener(ProgressEvent.SOCKET_DATA, this.onSocketData); this.socket.removeEventListener(IOErrorEvent.IO_ERROR, this.onIOError); this.socket.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onSecurityError); } public function sendMessage(msg:Message):void { this.tail.next = msg; this.tail = msg; this.socket.connected && this.sendPendingMessages(); } public function queueMessage(msg:Message):void { this.tail.next = msg; this.tail = msg; } private function sendPendingMessages():void { var temp:Message = this.head.next; var msg:Message = temp; if (!this.socket.connected) { return; } var i:int = 0; while (msg) { this.data.position = 0; this.data.length = 0; msg.writeToOutput(this.data); this.data.position = 0; if (this.outgoingCipher != null) { this.outgoingCipher.encrypt(this.data); this.data.position = 0; } this.socket.writeInt(this.data.bytesAvailable + 5); this.socket.writeByte(msg.id); this.socket.writeBytes(this.data); temp = msg; msg = msg.next; temp.consume(); i++; } if (i > 0) { this.socket.flush(); } this.unsentPlaceholder.next = null; this.unsentPlaceholder.prev = null; this.head = (this.tail = this.unsentPlaceholder); } private function onConnect(evt:Event):void { this.connected.dispatch(); } private function onClose(evt:Event):void { this.closed.dispatch(); } private function onIOError(evt:IOErrorEvent):void { var errMsg:String = this.parseString("Socket-Server IO Error: {0}", [evt.text]); this.error.dispatch(errMsg); this.closed.dispatch(); } private function onSecurityError(evt:SecurityErrorEvent):void { var errMsg:String = this.parseString( "Socket-Server Security: {0}. Please open port " + Parameters.PORT + " in your firewall and/or router settings and try again", [evt.text]); this.error.dispatch(errMsg); this.closed.dispatch(); } private function onSocketData(_:ProgressEvent = null):void { var messageId:uint; var message:Message; var errorMessage:String; while (true) { if (this.socket == null || !this.socket.connected) break; if (this.messageLen == -1) { if (this.socket.bytesAvailable < 4) break; try { this.messageLen = this.socket.readInt(); } catch (e:Error) { errorMessage = parseString("Socket-Server Data Error: {0}: {1}", [e.name, e.message]); error.dispatch(errorMessage); messageLen = -1; return; } } if (this.socket.bytesAvailable < this.messageLen - MESSAGE_LENGTH_SIZE_IN_BYTES) break; messageId = this.socket.readUnsignedByte(); message = this.messages.require(messageId); data.position = 0; data.length = 0; if (this.messageLen - 5 > 0) { this.socket.readBytes(data, 0, this.messageLen - 5); } data.position = 0; if (this.incomingCipher != null) { this.incomingCipher.decrypt(data); data.position = 0; } this.messageLen = -1; if (message == null) { this.logErrorAndClose("Socket-Server Protocol Error: Unknown message"); return; } try { message.parseFromInput(data); } catch (error:Error) { logErrorAndClose("Socket-Server Protocol Error: {0}", [error.toString()]); return; } message.consume(); sendPendingMessages(); } } private function logErrorAndClose(errorPrefix:String, errMsgs:Array = null):void { this.error.dispatch(this.parseString(errorPrefix, errMsgs)); this.disconnect(); } private function parseString(msgTemplate:String, msgs:Array):String { var numMsgs:int = msgs.length; for (var i:int = 0; i < numMsgs; i++) { msgTemplate = msgTemplate.replace("{" + i + "}", msgs[i]); i++; } return msgTemplate; } public function isConnected():Boolean { return this.socket.connected; } } }
package flare.animate.interpolate { import flash.geom.Point; /** * Interpolator for <code>flash.geom.Point</code> values. */ public class PointInterpolator extends Interpolator { private var _startX:Number, _startY:Number; private var _rangeX:Number, _rangeY:Number; private var _cur:Point; /** * Creates a new PointInterpolator. * @param target the object whose property is being interpolated * @param property the property to interpolate * @param start the starting point value to interpolate from * @param end the target point value to interpolate to */ public function PointInterpolator(target:Object, property:String, start:Object, end:Object) { super(target, property, start, end); } /** * Initializes this interpolator. * @param start the starting value of the interpolation * @param end the target value of the interpolation */ protected override function init(start:Object, end:Object) : void { var e:Point = Point(end), s:Point = Point(start); _cur = _prop.getValue(_target) as Point; if (_cur == null || _cur == s || _cur == e) _cur = e.clone(); _startX = s.x; _startY = s.y; _rangeX = e.x - _startX; _rangeY = e.y - _startY; } /** * Calculate and set an interpolated property value. * @param f the interpolation fraction (typically between 0 and 1) */ public override function interpolate(f:Number) : void { _cur.x = _startX + f*_rangeX; _cur.y = _startY + f*_rangeY; _prop.setValue(_target, _cur); } } // end of class PointInterpolator }
package asunit.framework { import asunit.errors.AssertionFailedError; import asunit.util.ArrayIterator; import asunit.util.Iterator; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.errors.IllegalOperationError; import flash.events.Event; import flash.events.TimerEvent; import flash.utils.Timer; import flash.utils.describeType; import flash.utils.getDefinitionByName; import flash.utils.setTimeout; /** * A test case defines the fixture to run multiple tests. To define a test case<br> * 1) implement a subclass of TestCase<br> * 2) define instance variables that store the state of the fixture<br> * 3) initialize the fixture state by overriding <code>setUp</code><br> * 4) clean-up after a test by overriding <code>tearDown</code>.<br> * Each test runs in its own fixture so there * can be no side effects among test runs. * Here is an example: * <pre> * public class MathTest extends TestCase { * protected double fValue1; * protected double fValue2; * * protected void setUp() { * fValue1= 2.0; * fValue2= 3.0; * } * } * </pre> * * For each test implement a method which interacts * with the fixture. Verify the expected results with assertions specified * by calling <code>assertTrue</code> with a boolean. * <pre> * public void testAdd() { * double result= fValue1 + fValue2; * assertTrue(result == 5.0); * } * </pre> * Once the methods are defined you can run them. The framework supports * both a static type safe and more dynamic way to run a test. * In the static way you override the runTest method and define the method to * be invoked. A convenient way to do so is with an anonymous inner class. * <pre> * TestCase test= new MathTest("add") { * public void runTest() { * testAdd(); * } * }; * test.run(); * </pre> * The dynamic way uses reflection to implement <code>runTest</code>. It dynamically finds * and invokes a method. * In this case the name of the test case has to correspond to the test method * to be run. * <pre> * TestCase= new MathTest("testAdd"); * test.run(); * </pre> * The tests to be run can be collected into a TestSuite. JUnit provides * different <i>test runners</i> which can run a test suite and collect the results. * A test runner either expects a static method <code>suite</code> as the entry * point to get a test to run or it will extract the suite automatically. * <pre> * public static Test suite() { * suite.addTest(new MathTest("testAdd")); * suite.addTest(new MathTest("testDivideByZero")); * return suite; * } * </pre> * @see TestResult * @see TestSuite */ public class TestCase extends Assert implements Test { protected static const PRE_SET_UP:int = 0; protected static const SET_UP:int = 1; protected static const RUN_METHOD:int = 2; protected static const TEAR_DOWN:int = 3; protected static const DEFAULT_TIMEOUT:int = 1000; protected var fName:String; protected var result:TestListener; protected var testMethods:Array; protected var isComplete:Boolean; protected var context:DisplayObjectContainer; protected var methodIsAsynchronous:Boolean; protected var timeout:Timer; private var setUpIsAsynchronous:Boolean; private var currentMethod:String; private var runSingle:Boolean; private var methodIterator:Iterator; private var layoutManager:Object; private var currentState:int; /** * Constructs a test case with the given name. */ public function TestCase(testMethod:String = null) { var description:XML = describeType(this); var className:Object = description.@name; var methods:XMLList = description..method.(@name.match("^test")); if(testMethod != null) { testMethods = testMethod.split(", ").join(",").split(","); if(testMethods.length == 1) { runSingle = true; } } else { setTestMethods(methods); } setName(className.toString()); resolveLayoutManager(); } private function resolveLayoutManager():void { // Avoid creating import dependencies on flex framework // If you have the framework.swc in your classpath, // the layout manager will be found, if not, a mcok // will be used. try { var manager:Class = getDefinitionByName("mx.managers.LayoutManager") as Class; layoutManager = manager["getInstance"](); if(!layoutManager.hasOwnProperty("resetAll")) { throw new Error("TestCase :: mx.managers.LayoutManager missing resetAll method"); } } catch(e:Error) { layoutManager = new Object(); layoutManager.resetAll = function():void { } } } /** * Sets the name of a TestCase * @param name The name to set */ public function setName(name:String):void { fName = name; } protected function setTestMethods(methodNodes:XMLList):void { testMethods = new Array(); var methodNames:Object = methodNodes.@name; var name:String; for each(var item:Object in methodNames) { name = item.toString(); testMethods.push(name); } } public function getTestMethods():Array { return testMethods; } /** * Counts the number of test cases executed by run(TestResult result). */ public function countTestCases():int { return testMethods.length; } /** * Creates a default TestResult object * * @see TestResult */ protected function createResult():TestResult { return new TestResult(); } /** * A convenience method to run this test, collecting the results with * either the TestResult provided or a default, new TestResult object. * Expects either: * run():void // will return the newly created TestResult * run(result:TestResult):TestResult // will use the TestResult * that was passed in. * * @see TestResult */ public function run():void { getResult().run(this); } public function setResult(result:TestListener):void { this.result = result; } protected function getResult():TestListener { return (result == null) ? createResult() : result; } /** * Runs the bare test sequence. * @exception Error if any exception is thrown * throws Error */ public function runBare():void { if(isComplete) { return; } var name:String; var itr:Iterator = getMethodIterator(); if(itr.hasNext()) { name = String(itr.next()); currentState = PRE_SET_UP; runMethod(name); } else { cleanUp(); getResult().endTest(this); isComplete = true; dispatchEvent(new Event(Event.COMPLETE)); } } private function getMethodIterator():Iterator { if(methodIterator == null) { methodIterator = new ArrayIterator(testMethods); } return methodIterator; } // Override this method in Asynchronous test cases // or any other time you want to perform additional // member cleanup after all test methods have run protected function cleanUp():void { } private function runMethod(methodName:String):void { try { methodIsAsynchronous = false; if(currentState == PRE_SET_UP) { currentState = SET_UP; getResult().startTestMethod(this, methodName); setUp(); // setUp may be async and change the state of methodIsAsynchronous } currentMethod = methodName; if(!methodIsAsynchronous) { currentState = RUN_METHOD; this[methodName](); } else { setUpIsAsynchronous = true; } } catch(assertionFailedError:AssertionFailedError) { getResult().addFailure(this, assertionFailedError); } catch(unknownError:Error) { getResult().addError(this, unknownError); } finally { if(!methodIsAsynchronous) { runTearDown(); } } } /** * Sets up the fixture, for example, instantiate a mock object. * This method is called before each test is executed. * throws Exception on error */ protected function setUp():void { } /** * Tears down the fixture, for example, delete mock object. * This method is called after a test is executed. * throws Exception on error */ protected function tearDown():void { } /** * Returns a string representation of the test case */ override public function toString():String { if(getCurrentMethod()) { return getName() + "." + getCurrentMethod() + "()"; } else { return getName(); } } /** * Gets the name of a TestCase * @return returns a String */ public function getName():String { return fName; } public function getCurrentMethod():String { return currentMethod; } public function getIsComplete():Boolean { return isComplete; } public function setContext(context:DisplayObjectContainer):void { this.context = context; } public function getContext():DisplayObjectContainer { return context; } protected function addAsync(handler:Function = null, duration:Number=DEFAULT_TIMEOUT):Function { if(handler == null) { handler = function(args:*):* {}; } methodIsAsynchronous = true; timeout = new Timer(duration, 1); timeout.addEventListener(TimerEvent.TIMER_COMPLETE, getTimeoutComplete(duration)); timeout.start(); // try ..args var context:TestCase = this; return function(args:*):* { context.timeout.stop(); try { handler.apply(context, arguments); } catch(e:AssertionFailedError) { context.getResult().addFailure(context, e); } catch(ioe:IllegalOperationError) { context.getResult().addError(context, ioe); } finally { context.asyncMethodComplete(); } } } private function getTimeoutComplete(duration:Number):Function { var context:TestCase = this; return function(event:Event):void { context.getResult().addError(context, new IllegalOperationError("TestCase.timeout (" + duration + "ms) exceeded on an asynchronous test method.")); context.asyncMethodComplete(); } } protected function asyncMethodComplete():void { if(currentState == SET_UP) { runMethod(currentMethod); } else if(currentState == RUN_METHOD) { runTearDown(); } } protected function runTearDown():void { currentState = TEAR_DOWN; if(isComplete) { return; } if(!runSingle) { getResult().endTestMethod(this, currentMethod); tearDown(); layoutManager.resetAll(); } setTimeout(runBare, 5); } protected function addChild(child:DisplayObject):DisplayObject { return getContext().addChild(child); } protected function removeChild(child:DisplayObject):DisplayObject { if(child == null) { throw new IllegalOperationError("TestCase.removeChild must have non-null parameter child"); } return getContext().removeChild(child); } // public function fail(message:String):void { // result.addFailure(this, new AssertionFailedError(message)); // } } }
/** * Copyright (c) 2010 Doug Koellmer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package quickb2.thirdparty.flash { import flash.display.Graphics; import quickb2.display.immediate.color.qb2E_ColorChannel; import quickb2.display.immediate.color.qb2S_Color; import quickb2.display.immediate.color.qb2U_Color; import quickb2.display.immediate.graphics.*; import quickb2.display.immediate.graphics.qb2E_DrawParam; import quickb2.math.geo.coords.qb2GeoPoint; import quickb2.math.qb2S_Math; /** * Wraps the Flash Graphics object in order to implement qb2I_Graphics2d * * @author Doug Koellmer */ public class qb2FlashVectorGraphics2d extends qb2A_GraphicsContext implements qb2I_Graphics2d { private static const s_utilPoint1:qb2GeoPoint = new qb2GeoPoint(); private static const s_utilPoint2:qb2GeoPoint = new qb2GeoPoint(); private static const s_utilPoint3:qb2GeoPoint = new qb2GeoPoint(); private static const NORMAL_SCALE_MODE:String = "normal"; private static const CAPS_STYLE:String = "none"; private var m_flashGraphicsObject:Graphics = null; private var m_needsEndFill:Boolean = false; public function qb2FlashVectorGraphics2d(flashGraphicsObject_nullable:Graphics = null):void { setFlashGraphicsObject(flashGraphicsObject_nullable); } public function fill():void { m_flashGraphicsObject.endFill(); } public function getFlashGraphicsObject():Graphics { return m_flashGraphicsObject; } public function setFlashGraphicsObject(flashGraphicsObject:Graphics, copyData:Boolean = true):void { if ( flashGraphicsObject != null && m_flashGraphicsObject != null && copyData ) { flashGraphicsObject.clear(); flashGraphicsObject.copyFrom(m_flashGraphicsObject); } m_flashGraphicsObject = flashGraphicsObject; if ( m_flashGraphicsObject != null ) { setFill(null); setLineStyle(); } } public function clearBuffer():void { m_flashGraphicsObject.clear(); } public override function pushParam(param:qb2E_DrawParam, value_copied:* ):void { var oldValue:* = super.getParam(param); super.pushParam(param, value_copied); updateGraphics(param, oldValue); } public override function popParam(param:qb2E_DrawParam):void { var oldValue:* = super.getParam(param); super.popParam(param); updateGraphics(param, oldValue); } private function updateGraphics(param:qb2E_DrawParam, oldValue:*):void { if ( m_flashGraphicsObject == null ) return; switch(param) { case qb2E_DrawParam.FILL_COLOR: { setFill(oldValue); break; } case qb2E_DrawParam.LINE_THICKNESS: case qb2E_DrawParam.LINE_COLOR: { setLineStyle(); break; } } } private function isColorDefined(param:qb2E_DrawParam):Boolean { if ( super.getParam(param) == null ) { return false; } var currentColor:int = getParam(param); if ( (currentColor & qb2S_Color.ALPHA_MASK) == 0 ) { return param == qb2E_DrawParam.FILL_COLOR; // fill color of alpha 0 is still valid, but for lines it's meaningless. } return true; } private function setFill(oldValue:*):void { var newValue:* = super.getParam(qb2E_DrawParam.FILL_COLOR); if ( oldValue == null ) { if ( newValue != null ) { this.beginFill(); } } else { if ( newValue != null ) { m_flashGraphicsObject.endFill(); this.beginFill(); } else { m_flashGraphicsObject.endFill(); } } } private function beginFill():void { var color:int = super.getParam(qb2E_DrawParam.FILL_COLOR); var rgbColor:int = color & qb2S_Color.COLOR_MASK; var alpha:Number = qb2U_Color.channelMantissa(qb2E_ColorChannel.ALPHA, color); m_flashGraphicsObject.beginFill(rgbColor, alpha); } private function setLineStyle():void { if ( !isColorDefined(qb2E_DrawParam.LINE_COLOR) ) { m_flashGraphicsObject.lineStyle(); return; } var color:int = super.getParam(qb2E_DrawParam.LINE_COLOR); var rgbColor:int = color & qb2S_Color.COLOR_MASK; var alpha:Number = qb2U_Color.channelMantissa(qb2E_ColorChannel.ALPHA, color); m_flashGraphicsObject.lineStyle(getParam(qb2E_DrawParam.LINE_THICKNESS), rgbColor, alpha, false, NORMAL_SCALE_MODE, CAPS_STYLE); } public function moveTo(point:qb2I_DrawPoint):void { this.calcTransformedPoint(point, s_utilPoint1); m_flashGraphicsObject.moveTo(s_utilPoint1.getX(), s_utilPoint1.getY()); } public function drawLineTo(point:qb2I_DrawPoint):void { this.calcTransformedPoint(point, s_utilPoint1); m_flashGraphicsObject.lineTo(s_utilPoint1.getX(), s_utilPoint1.getY()); } public function drawCubicCurveTo(controlPoint1:qb2I_DrawPoint, controlPoint2:qb2I_DrawPoint, anchorPoint:qb2I_DrawPoint):void { this.calcTransformedPoint(controlPoint1, s_utilPoint1); this.calcTransformedPoint(controlPoint2, s_utilPoint2); this.calcTransformedPoint(anchorPoint, s_utilPoint3); m_flashGraphicsObject.cubicCurveTo(s_utilPoint1.getX(), s_utilPoint1.getY(), s_utilPoint2.getX(), s_utilPoint2.getY(), s_utilPoint3.getX(), s_utilPoint3.getY()); } public function drawQuadCurveTo(controlPoint:qb2I_DrawPoint, anchorPoint:qb2I_DrawPoint):void { this.calcTransformedPoint(controlPoint, s_utilPoint1); this.calcTransformedPoint(anchorPoint, s_utilPoint2); m_flashGraphicsObject.curveTo(s_utilPoint1.getX(), s_utilPoint1.getY(), s_utilPoint2.getX(), s_utilPoint2.getY()); } public function drawCircle(point_nullable:qb2I_DrawPoint, radius:Number):void { point_nullable = point_nullable != null ? point_nullable : qb2S_Math.ORIGIN; this.calcTransformedPoint(point_nullable, s_utilPoint1); m_flashGraphicsObject.drawCircle(s_utilPoint1.getX(), s_utilPoint1.getY(), radius); } public function drawLine(point1:qb2I_DrawPoint, point2:qb2I_DrawPoint):void { this.moveTo(point1); this.drawLineTo(point2); } } }
/** * @exampleText * * <a name="CacheLoader"></a> * <h1>CacheLoader</h1> * * <p>This is an example of the <a href="http://templelibrary.googlecode.com/svn/trunk/modules/data/doc/temple/data/cache/CacheLoader.html">CacheLoader</a>. * The CacheLoader stores the data (as ByteArray) in the <a href="http://templelibrary.googlecode.com/svn/trunk/doc/temple/data/cache/LoaderCache.html" name="doc">LoaderCache</a> with the url as key. * The next time a CacheLoader needs to load the same url it gets the data directly from the LoaderCache.</p> * * <p><a href="http://templelibrary.googlecode.com/svn/trunk/modules/data/examples/temple/data/cache/CacheLoaderExample.swf" target="_blank">View this example</a></p> * * <p><a href="http://templelibrary.googlecode.com/svn/trunk/modules/data/examples/temple/data/cache/CacheLoaderExample.as" target="_blank">View source</a></p> */ package { import temple.data.cache.CacheLoader; import flash.net.URLRequest; // This class extends the DocumentClassExample, which handles some default Temple settings. This class can be found in directory '/examples/templates/' public class CacheLoaderExample extends DocumentClassExample { private static const _URL:String = "image.jpg"; public function CacheLoaderExample() { super("Temple - CacheLoaderExample"); // create a new CacheLoader var loader:CacheLoader = new CacheLoader(); addChild(loader); loader.scale = .2; loader.load(new URLRequest(_URL)); // create an other CacheLoader and load the same URL. The image is only loaded once. loader = new CacheLoader(); addChild(loader); loader.scale = .2; loader.x = 300; loader.load(new URLRequest(_URL)); } } }
/** * <p>Original Author: jessefreeman</p> * <p>Class File: IStyle.as</p> * * <p>Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions:</p> * * <p>The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software.</p> * * <p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE.</p> * * <p>Licensed under The MIT License</p> * <p>Redistributions of files must retain the above copyright notice.</p> * * <p>Revisions<br/> * 1.0.0 Initial version Feb 11, 2010</p> * */ package com.flashartofwar.fcss.styles { /** * @author jessefreeman */ public interface IStyle { function set styleName(value:String):void; function get styleName():String; function merge(object:Object):void; function toString():String; function clone():IStyle; } }
package me.shunia.xsqst_helper.utils { import flash.filesystem.File; import air.update.ApplicationUpdater; import air.update.events.UpdateEvent; /** * 最简化的自动更新器. * * @author qingfenghuang */ public class Updater { private var _u:ApplicationUpdater = null; public function Updater(updateConfUrl:String) { _u = new ApplicationUpdater(); _u.configurationFile = new File(updateConfUrl); _u.addEventListener(UpdateEvent.INITIALIZED, onInit); _u.initialize(); } protected function onInit(e:UpdateEvent):void { _u.checkNow(); } } }
package com.ankamagames.berilia.types.uiDefinition { import flash.utils.Dictionary; public class UiDefinition { public static var MEMORY_LOG:Dictionary = new Dictionary(true); public var name:String; public var debug:Boolean = false; public var graphicTree:Array; public var kernelEvents:Array; public var constants:Array; public var className:String; public var useCache:Boolean = true; public var usePropertiesCache:Boolean = true; public var modal:Boolean = false; public var giveFocus:Boolean = true; public var transmitFocus:Boolean = true; public var scalable:Boolean = true; public var labelDebug:Boolean = false; public var fullscreen:Boolean = false; public var setOnTopOnClick:Boolean = true; public function UiDefinition() { super(); this.graphicTree = new Array(); this.kernelEvents = new Array(); this.constants = new Array(); MEMORY_LOG[this] = 1; } } }
package kabam.rotmg.assets { import mx.core.*; [Embed(source="EmbeddedAssets_lofiEnvironment2Embed_.png")] public class EmbeddedAssets_lofiEnvironment2Embed_ extends BitmapAsset { public function EmbeddedAssets_lofiEnvironment2Embed_() { super(); } } }
package laya.debug.tools { import laya.utils.Byte; /** * base64编码解码类 * @author ww */ public class Base64Tool { public function Base64Tool() { } public static var chars:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // Use a lookup table to find the index. public static var lookup:Uint8Array = null; public static function init():void { if (lookup) return; lookup = new Uint8Array(256) for (var i:int = 0; i < chars.length; i++) { lookup[chars.charCodeAt(i)] = i; } } /** * 编码ArrayBuffer * @param arraybuffer * @return * */ public static function encode(arraybuffer:ArrayBuffer):String { var bytes:Uint8Array = new Uint8Array(arraybuffer), i:int, len:int = bytes.length, base64:String = ""; for (i = 0; i < len; i += 3) { base64 += chars[bytes[i] >> 2]; base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64 += chars[bytes[i + 2] & 63]; } if ((len % 3) === 2) { base64 = base64.substring(0, base64.length - 1) + "="; } else if (len % 3 === 1) { base64 = base64.substring(0, base64.length - 2) + "=="; } return base64; } /** * 编码字符串 * @param str * @return * */ public static function encodeStr(str:String):String { var byte:Byte; byte = new Byte(); byte.writeUTFString(str); return encodeByte(byte); } /** * 编码Byte * @param byte * @param start * @param end * @return * */ public static function encodeByte(byte:Byte, start:int = 0, end:int = -1):String { if (end < 0) { end = byte.length; } return encode(byte.buffer.slice(start,end)); } /** * 解码成Byte * @param base64 * @return * */ public static function decodeToByte(base64:String):Byte { return new Byte(decode(base64)); } /** * 解码成ArrayBuffer * @param base64 * @return * */ public static function decode(base64:String):ArrayBuffer { init(); var bufferLength:int = base64.length * 0.75, len:int = base64.length, i:int, p:int = 0, encoded1:int, encoded2:int, encoded3:int, encoded4:int; if (base64[base64.length - 1] === "=") { bufferLength--; if (base64[base64.length - 2] === "=") { bufferLength--; } } var arraybuffer:ArrayBuffer = new ArrayBuffer(bufferLength), bytes:Uint8Array = new Uint8Array(arraybuffer); for (i = 0; i < len; i += 4) { encoded1 = lookup[base64.charCodeAt(i)]; encoded2 = lookup[base64.charCodeAt(i + 1)]; encoded3 = lookup[base64.charCodeAt(i + 2)]; encoded4 = lookup[base64.charCodeAt(i + 3)]; bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return arraybuffer; } ; } }
 /* AS3 Copyright 2008 */ package com.neopets.games.inhouse.suteksTomb.game.extendedMenus { import com.neopets.projects.gameEngine.gui.AbsMenu; import com.neopets.projects.gameEngine.gui.buttons.SelectedButton; import com.neopets.util.button.NeopetsButton; import com.neopets.util.sound.GameSoundManager; import com.neopets.games.inhouse.suteksTomb.game.Sounds; import flash.display.MovieClip; import flash.events.Event; import flash.events.MouseEvent; import flash.text.TextField; /** * This is a Simple Menu for the Opening Screen * The Button Click Commands are not handled at this level but at the Insatiation of this Class. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @NP9 Game System * * @author Clive Henrick * @since 7.08.2009 */ public class ExtInstructionScreen extends AbsMenu { //-------------------------------------- // CLASS CONSTANTS //-------------------------------------- //-------------------------------------- // VARIABLES //-------------------------------------- public var returnBtn:NeopetsButton; //On Stage //public var introText_txt:TextField; //On Stage public var longText_txt:TextField; //On Stage public var longText2_txt:TextField; //On Stage public var longText3_txt:TextField; //On Stage public var longText4_txt:TextField; //On Stage public var longText5_txt:TextField; //On Stage public var hourglass:MovieClip; public var toggleButton:MovieClip; public var soundToggleBtn:SelectedButton; //On Stage //-------------------------------------- // CONSTRUCTOR //-------------------------------------- /** * @Constructor */ public function ExtInstructionScreen():void { super(); setupVars(); } //-------------------------------------- // GETTER/SETTERS //-------------------------------------- //-------------------------------------- // PUBLIC METHODS //-------------------------------------- /** * The toggle button's display will be set based on GameSoundManager's music and sound setting (on or off) * This public function should be called whenever memuManager is showing the instructions page in SuteksTombEngine class **/ public function matchSoundSetting ():void { if (GameSoundManager.musicOn && GameSoundManager.soundOn) { toggleButton.gotoAndStop("on") } else if (!GameSoundManager.musicOn && GameSoundManager.soundOn) { toggleButton.gotoAndStop("sound") } else if (!GameSoundManager.musicOn && !GameSoundManager.soundOn) { toggleButton.gotoAndStop("off") } } //-------------------------------------- // EVENT HANDLERS //-------------------------------------- //-------------------------------------- // PRIVATE & PROTECTED INSTANCE METHODS //-------------------------------------- /** * @Note: Setups Variables */ private function setupVars():void { returnBtn.addEventListener(MouseEvent.MOUSE_UP,MouseClicked,false,0,true); //soundToggleBtn.addEventListener(MouseEvent.MOUSE_UP,MouseClicked,false,0,true); toggleButton.addEventListener(MouseEvent.MOUSE_DOWN, toggleButtonClicked, false, 0, true); mID = "GameScene"; hourglass.gotoAndStop(1) //toggleButton.gotoAndStop("on") } private function toggleButtonClicked (evt:MouseEvent):void { trace ("clicked") if (GameSoundManager.musicOn && GameSoundManager.soundOn) { GameSoundManager.musicOn = false GameSoundManager.stopSound(Sounds.SND_LOOP); toggleButton.gotoAndStop("sound") } else if (!GameSoundManager.musicOn && GameSoundManager.soundOn) { GameSoundManager.soundOn = false toggleButton.gotoAndStop("off") } else if (!GameSoundManager.musicOn && !GameSoundManager.soundOn) { GameSoundManager.soundOn = true GameSoundManager.musicOn = true GameSoundManager.soundPlay(GameSoundManager.musicOn, Sounds.SND_LOOP, true); toggleButton.gotoAndStop("on") } } } }
/** * <p>Original Author: toddanderson</p> * <p>Class File: ScrollMark.as</p> * <p>Version: 0.3</p> * * <p>Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions:</p> * * <p>The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software.</p> * * <p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE.</p> * * <p>Licensed under The MIT License</p> * <p>Redistributions of files must retain the above copyright notice.</p> */ package com.custardbelly.as3flobile.model { import flash.utils.Dictionary; /** * ScrollMark is a model class representing a point in time at which a scroll action has occured. * @author toddanderson */ public class ScrollMark { public var x:Number; public var y:Number; public var time:Number; private static var KEY_INCREMENT:uint = 0; /** * @private * * Internally managed pool of ScrollMark instances. */ private static var _pool:Dictionary; /** * Constructor * @param x Number The position along the x axis that the scroll action occured. * @param y Number The position along the y axis that the scroll action occured. * @param time Number The time at which the scroll action occured. */ public function ScrollMark( x:Number = 0, y:Number = 0, time:Number = 0 ) { this.x = x; this.y = y; this.time = time; } /** * @private * * Fail safe method to retrieve the mark list related to the unique key in the pool. * @param key uint * @return Vector.<ScrollMark> */ static private function getMarksFromKey( key:uint ):Vector.<ScrollMark> { // If pool not created, create it. if( _pool == null ) _pool = new Dictionary( true ); // If associated list of marks not available, create it. if( _pool[key] == null ) _pool[key] = new Vector.<ScrollMark>(); // Return list based on key. return _pool[key]; } /** * Generates and returns a unique key to use when working with mark pools. * @return uint */ static public function generateKey():uint { // Simple, simple increment. We're not doing web security here, people. We just playing. return ScrollMark.KEY_INCREMENT++; } /** * Utility factory method to access a ScrollMark instance. Checks if ScrollMark is available in pool of instances. If not creates a new one. * @param key uint The unique key associated with the pool request. Keys can first be obtained using ScrollMark#generateKey(). * @param x Number The position along the x axis that the scroll action occured. * @param y Number The position along the y axis that the scroll action occured. * @param time Number The time at which the scroll action occured. * @return ScrollMark */ static public function getScrollMark( key:uint, x:Number, y:Number, time:Number ):ScrollMark { var marks:Vector.<ScrollMark> = ScrollMark.getMarksFromKey( key ); if( marks.length == 0 ) marks[0] = new ScrollMark(); var mark:ScrollMark = marks.shift(); mark.x = x; mark.y = y; mark.time = time; return mark; } /** * Utility method to return a ScrollMark instance to the internally managed pool of ScrollMarks. * @param key uint * @param mark ScrollMark */ static public function returnScrollMark( key:uint, mark:ScrollMark ):void { var marks:Vector.<ScrollMark> = ScrollMark.getMarksFromKey( key ); mark.x = mark.y = mark.time = 0; marks[marks.length] = mark; } /** * Utility method to flush the internally managed pool of ScrollMark references. * @param key uint The unique key to the mark pool. */ static public function flush( key:uint ):void { if( _pool == null ) return; var marks:Vector.<ScrollMark> = ScrollMark.getMarksFromKey( key ); while( marks.length > 0 ) marks.shift(); } /** * Utility method to flush all internally managed pools of ScrollMark references. */ static public function flushAll():void { if( _pool == null ) return; var key:uint; for each( key in _pool ) { ScrollMark.flush( key ); } } } }
package com.degrafa.geometry { import com.degrafa.geometry.command.CommandStackItem; import com.degrafa.geometry.RoundedRectangleComplex; [Bindable] /** * CalloutBalloon is the Geometry used to render the default Axiis data tip. */ public class CalloutBalloon extends RoundedRectangleComplex { private var _calloutY:Number; /** * The Y position of the callout relative to its 0,0 location **/ public function get calloutY():Number { if(!_calloutY){return 0;} return _calloutY; } public function set calloutY(value:Number):void{ if(_calloutY != value){ _calloutY = value; invalidated = true; } } private var _calloutX:Number; /** * The X position of the callout relative to its 0,0 location **/ public function get calloutX():Number{ if(!_calloutX){return 0;} return _calloutX; } public function set calloutX(value:Number):void{ if(_calloutX != value){ _calloutX = value; invalidated = true; } } private var _calloutWidthRatio:Number=.3; /** * How wide the base of the callout triangle is where it intersects with the side of the callout **/ public function get calloutWidthRatio():Number{ if(!_calloutWidthRatio){return 0;} return _calloutWidthRatio; } public function set calloutWidthRatio(value:Number):void{ if(_calloutWidthRatio != value){ _calloutWidthRatio = value; invalidated = true; } } /** * Constructor. */ public function CalloutBalloon() { super(); } override public function preDraw():void { commandStack.source.length=0; super.preDraw(); createCallout(); } private function getAngle(x:Number, y:Number):Number { var xpos:Number = x - (this.x + width/2); var ypos:Number = y - (this.y + height/2); var radius:Number = Math.sqrt( xpos*xpos + ypos*ypos ); var radianSin:Number = 0; var radianCos:Number = 0; if( radius > 0 ) { radianCos = Math.acos( ypos/radius ); radianSin = Math.asin( xpos/radius ); } var angle:Number = radianCos*180/Math.PI; if( radianSin > 0 ) angle = 360 - angle; return angle; } private function createCallout():void { //Find the lines in the commandStack //Assume lines are found in this order (clockwise) TOP, RIGHT, BOTTOM, LEFT /** Determine which side of the rectangle to draw the callout on * 1. Determine the angles of each corner * 2. Determine the angle of the callout x,y * 3. Map the callout x,y within the bounds of arc created by two corners of the rectangle */ if ( ((calloutX > this.x) && (calloutX < this.x+width)) && ( (calloutY > this.y) && (calloutY < this.y+height))) return; var calloutAngle:Number=getAngle(calloutX,calloutY); var topLeftAngle:Number=getAngle(this.x,this.y); var topRightAngle:Number=getAngle(this.x+width,this.y+0); var bottomRightAngle:Number=getAngle(this.x + width,this.y+height); var bottomLeftAngle:Number=getAngle(this.x,this.y+height); var angleRatio:Number; var line:CommandStackItem; var w:Number; if (calloutAngle<=bottomRightAngle && calloutAngle>=topRightAngle) { //trace("RIGHT SIDE"); line=this.rightLine; w=height-topRightRadius-bottomRightRadius; angleRatio=(bottomRightAngle-calloutAngle)/(bottomRightAngle-topRightAngle); } else if (calloutAngle<=topRightAngle && calloutAngle>=topLeftAngle) { //trace("TOP SIDE"); line=this.topLine; w=width-topRightRadius-topLeftRadius; angleRatio=(topRightAngle-calloutAngle)/(topRightAngle-topLeftAngle); } else if (calloutAngle<=topLeftAngle && calloutAngle >=bottomLeftAngle) { //trace("LEFT SIDE"); line=this.leftLine; w=height-this.topLeftRadius-this.bottomRightRadius; angleRatio=(topLeftAngle-calloutAngle)/(topLeftAngle-bottomLeftAngle); } else { //trace("BOTTOM SIDE"); line=this.bottomLine; w=width-this.bottomLeftRadius-this.bottomRightRadius; var ca:Number= (calloutAngle>=bottomRightAngle) ? calloutAngle-bottomRightAngle: (360-bottomRightAngle) + calloutAngle; angleRatio= 1-(ca/((360-bottomRightAngle)+bottomLeftAngle)) } //trace("topLeftAngle=" + topLeftAngle + " topRightAngle=" + topRightAngle + " bottomRightAngle=" + bottomRightAngle + " bottomLeftAngle=" + bottomLeftAngle + " calloutAngle=" + calloutAngle + " angleRatio=" + angleRatio); var i:int=0; var previousItem:CommandStackItem; var o:Number=w*(1-calloutWidthRatio)*(1-angleRatio)*.9; w=w*calloutWidthRatio; if (o+w > this.width) o=this.width-w; for each (var item:CommandStackItem in this.commandStack.source) { if (item == line ) { var oldX:int=item.x; var px:Number=(isNaN(previousItem.x)) ? previousItem.x1 : previousItem.x; var py:Number=(isNaN(previousItem.y)) ? previousItem.y1 : previousItem.y; //Create first edge of triangle var line0:CommandStackItem; var line1:CommandStackItem; var line2:CommandStackItem; var line3:CommandStackItem; if (line==this.topLine) { line0 = new CommandStackItem(CommandStackItem.LINE_TO,px+o,item.y); line1 = new CommandStackItem(CommandStackItem.LINE_TO,calloutX,calloutY); line2 = new CommandStackItem(CommandStackItem.LINE_TO,px+o+w,item.y); line3 = new CommandStackItem(CommandStackItem.LINE_TO,item.x,item.y); } else if (line==this.rightLine) { line0 = new CommandStackItem(CommandStackItem.LINE_TO,item.x,py+o); line1 = new CommandStackItem(CommandStackItem.LINE_TO,calloutX,calloutY); line2 = new CommandStackItem(CommandStackItem.LINE_TO,item.x,py+o+w); line3 = new CommandStackItem(CommandStackItem.LINE_TO,item.x,item.y); } if (line==this.bottomLine) { line0 = new CommandStackItem(CommandStackItem.LINE_TO,px-o,item.y); line1 = new CommandStackItem(CommandStackItem.LINE_TO,calloutX,calloutY); line2 = new CommandStackItem(CommandStackItem.LINE_TO,px-o-w,item.y); line3 = new CommandStackItem(CommandStackItem.LINE_TO,item.x,item.y); } else if (line==this.leftLine) { line0 = new CommandStackItem(CommandStackItem.LINE_TO,item.x,py-o); line1 = new CommandStackItem(CommandStackItem.LINE_TO,calloutX,calloutY); line2 = new CommandStackItem(CommandStackItem.LINE_TO,item.x,py-o-w); line3 = new CommandStackItem(CommandStackItem.LINE_TO,item.x,item.y); } commandStack.addItemAt(line0,i+1); commandStack.addItemAt(line1,i+2); commandStack.addItemAt(line2,i+3); commandStack.addItemAt(line3,i+4); //remove original line commandStack.source.splice(i,1); //commandStack.source[i]=item; break; } previousItem=item; i++; } } } }
/* Copyright aswing.org, see the LICENCE.txt. */ import GUI.fox.aswing.ASColor; import GUI.fox.aswing.ASFont; import GUI.fox.aswing.ASTextExtent; import GUI.fox.aswing.ASTextFormat; import GUI.fox.aswing.ASWingConstants; import GUI.fox.aswing.Component; import GUI.fox.aswing.Container; import GUI.fox.aswing.geom.Point; import GUI.fox.aswing.geom.Rectangle; import GUI.fox.aswing.Icon; import GUI.fox.aswing.JPanel; import GUI.fox.aswing.JPopup; import GUI.fox.aswing.JWindow; import GUI.fox.aswing.LayoutManager; import GUI.fox.aswing.MCPanel; import GUI.fox.aswing.util.HashMap; class GUI.fox.aswing.ASWingUtils{ /** * A fast access to ASWingConstants Constant * @see GUI.fox.aswing.ASWingConstants */ public static var CENTER:Number = ASWingConstants.CENTER; /** * A fast access to ASWingConstants Constant * @see GUI.fox.aswing.ASWingConstants */ public static var TOP:Number = ASWingConstants.TOP; /** * A fast access to ASWingConstants Constant * @see GUI.fox.aswing.ASWingConstants */ public static var LEFT:Number = ASWingConstants.LEFT; /** * A fast access to ASWingConstants Constant * @see GUI.fox.aswing.ASWingConstants */ public static var BOTTOM:Number = ASWingConstants.BOTTOM; /** * A fast access to ASWingConstants Constant * @see GUI.fox.aswing.ASWingConstants */ public static var RIGHT:Number = ASWingConstants.RIGHT; /** * A fast access to ASWingConstants Constant * @see GUI.fox.aswing.ASWingConstants */ public static var HORIZONTAL:Number = ASWingConstants.HORIZONTAL; /** * A fast access to ASWingConstants Constant * @see GUI.fox.aswing.ASWingConstants */ public static var VERTICAL:Number = ASWingConstants.VERTICAL; private static var ROOT:MovieClip; private static var displayableComponents:HashMap; private static var initialStageWidth:Number = Stage.width; private static var initialStageHeight:Number = Stage.height; /** * Returns the center position in the stage. */ public static function getScreenCenterPosition():Point{ var r:Rectangle = getVisibleMaximizedBounds(); return new Point(r.x + r.width/2, r.y + r.height/2); } /** * getVisibleMaximizedBounds(mc:MovieClip)<br> * getVisibleMaximizedBounds() default to return the visible bounds in stage. * Returns the currently visible maximized bounds in a MovieClip(viewable the stage area). */ public static function getVisibleMaximizedBounds(mc:MovieClip):Rectangle{ var sw:Number = Stage.width; var sh:Number = Stage.height; var sa:String = Stage.align; var dw:Number = sw - initialStageWidth; var dh:Number = sh - initialStageHeight; var b:Rectangle = new Rectangle(0, 0, sw, sh); if(mc != undefined){ mc.globalToLocal(b); } switch(sa){ case "T": b.x -= dw/2; break; case "B": b.x -= dw/2; b.y -= dh; break; case "L": b.y -= dh/2; break; case "R": b.x -= dw; b.y -= dh/2; break; case "LT": case "TL": break; case "RT": case "TR": b.x -= dw; break; case "LB": case "BL": b.y -= dh; break; case "RB": case "BR": b.x -= dw; b.y -= dh; break; default: b.x -= dw/2; b.y -= dh/2; break; } b.x = Math.ceil(b.x); b.y = Math.ceil(b.y); b.width = Math.floor(b.width); b.height = Math.floor(b.height); return b; } /** * Registers a displayable component.<br> * You should not call this method at your application programs. * @param com the displayable component */ public static function addDisplayableComponent(com:Component):Void{ if(displayableComponents == undefined){ displayableComponents = new HashMap(); } displayableComponents.put(com.getID(), com); } /** * Removes a registered displayable component when it became not displayable.<br> * You should not call this method at your application programs generally with AsWing standard component, * But if you created your custom component extension, you should note that you must call the destroy method * when it was destroied, then it will be automaticlly removed here, but if you did not call destroy or * overrided destroy method, you must call this method manually when it become undisplayable. * @param com the de-displayableed component * @see Component#destroy() */ public static function removeDisplayableComponent(com:Component):Void{ displayableComponents.remove(com.getID(), com); } /** * Gets the displayable component for it's id. * @param id the id of the component * @return the displayable component owned the id * @see Component#getID() */ public static function getDisplayableComponent(id):Component{ return displayableComponents.get(id); } /** * Sets the root movieclip for components base on. * Default is _root. */ public static function setRootMovieClip(root:MovieClip):Void{ ROOT = root; } /** * Returns the root movieclip which components base on. or symbol libraray located in. * @return _root if you have not set it or you set it with null/undefined, the mc you'v set before. * @see #setRootMovieClip() */ public static function getRootMovieClip():MovieClip{ if(ROOT == undefined){ return _root; } return ROOT; } /** * Creates and return a pane to hold the component with specified layout manager and constraints. */ public static function createPaneToHold(com:Component, layout:LayoutManager, constraints:Object):Container{ var p:JPanel = new JPanel(layout); p.setOpaque(false); p.append(com, constraints); return p; } /** * Returns the first Window ancestor of c, or null if component is not contained inside a window * @return the first Window ancestor of c, or null if component is not contained inside a window */ public static function getWindowAncestor(c:Component):JWindow{ while(c != null){ if(c instanceof JWindow){ return JWindow(c); } c = c.getParent(); } return null; } /** * Returns the first Popup ancestor of c, or null if component is not contained inside a popup * @return the first Popup ancestor of c, or null if component is not contained inside a popup */ public static function getPopupAncestor(c:Component):JPopup{ while(c != null){ if(c instanceof JPopup){ return JPopup(c); } c = c.getParent(); } return null; } /** * Returns the first popup ancestor or movieclip root of c, or null if can't find the ancestor * @return the first popup ancestor or movieclip root of c, or null if can't find the ancestor */ public static function getOwnerAncestor(c:Component){ var popup:JPopup = getPopupAncestor(c); if(popup == null){ return c.getComponentRootAncestorMovieClip(); } return popup; } /** * Returns the MCPanel ancestor of c, or null if it is not contained inside a mcpanel yet * @return the first MCPanel ancestor of c, or null. */ public static function getAncestorComponent(c:Component):Container{ while(c != null){ if(c instanceof MCPanel){ return Container(c); } c = c.getParent(); } return null; } /** * When call <code>setLookAndFeel</code> it will not change the UIs at created components. * Call this method to update all existing component's UIs. * @see #updateComponentTreeUI() * @see GUI.fox.aswing.Component#updateUI() */ public static function updateAllComponentUI():Void{ var mcps:Array = MCPanel.getMCPanels(); var n:Number = mcps.length; for(var i:Number=0; i<n; i++){ updateComponentTreeUI(MCPanel(mcps[i])); } } /** * A simple minded look and feel change: ask each node in the tree to updateUI() -- that is, * to initialize its UI property with the current look and feel. * @see GUI.fox.aswing.Component#updateUI() */ public static function updateComponentTreeUI(com:Component):Void{ var rootc:Component = getRoot(com); updateChildrenUI(rootc); } private static function updateChildrenUI(c:Component):Void{ c.updateUI(); //trace("UI updated : " + c); if(c instanceof Container){ var con:Container = Container(c); for(var i:Number = con.getComponentCount()-1; i>=0; i--){ updateChildrenUI(con.getComponent(i)); } } } /** * Returns the root component for the current component tree. * @return the first ancestor of c that's ordinaryly a MCPanel or a JPopup(or JWindow, JFrame). */ public static function getRoot(c:Component):Component{ var maxLoop:Number = 10000; //max search depth 1000 while(c.getParent() != null && maxLoop>0){ c = c.getParent(); maxLoop--; } return c; } //Don't call this method currently, it has some problem cause text shake public static function boundsTextField(tf:TextField, r:Rectangle):Void{ tf._x = r.x; tf._y = r.y; tf._width = r.width; tf._height = r.height; } /** * Apply the font and color to the textfield. * @param text * @param font * @param color */ public static function applyTextFontAndColor(text:TextField, font:ASFont, color:ASColor):Void{ var tf:ASTextFormat = font.getASTextFormat(); applyTextFormatAndColor(text, tf, color); } public static function applyTextFont(text:TextField, font:ASFont):Void{ font.getASTextFormat().applyToTextCurrentAndNew(text); } public static function applyTextFormat(text:TextField, textFormat:ASTextFormat):Void{ textFormat.applyToTextCurrentAndNew(text); } public static function applyTextColor(text:TextField, color:ASColor):Void{ if(text.textColor != color.getRGB()){ text.textColor = color.getRGB(); } if(text._alpha != color.getAlpha()){ text._alpha = color.getAlpha(); } } /** * Apply the textformat and color to the textfield. * @param text * @param textFormat * @param color */ public static function applyTextFormatAndColor(text:TextField, textFormat:ASTextFormat, color:ASColor):Void{ applyTextFormat(text, textFormat); applyTextColor(text, color); } /** * Compute and return the location of the icons origin, the * location of origin of the text baseline, and a possibly clipped * version of the compound labels string. Locations are computed * relative to the viewR rectangle. */ public static function layoutCompoundLabel( f:ASFont, text:String, icon:Icon, verticalAlignment:Number, horizontalAlignment:Number, verticalTextPosition:Number, horizontalTextPosition:Number, viewR:Rectangle, iconR:Rectangle, textR:Rectangle, textIconGap:Number):String { if (icon != null) { iconR.width = icon.getIconWidth(); iconR.height = icon.getIconHeight(); }else { iconR.width = iconR.height = 0; } var tf:ASTextFormat = f.getASTextFormat(); var textIsEmpty:Boolean = (text==null || text==""); if(textIsEmpty){ textR.width = textR.height = 0; }else{ var ts:ASTextExtent = tf.getTextExtent(text); textR.width = Math.ceil(ts.getTextFieldWidth()); textR.height = Math.ceil(ts.getTextFieldHeight()); } /* Unless both text and icon are non-null, we effectively ignore * the value of textIconGap. The code that follows uses the * value of gap instead of textIconGap. */ var gap:Number = (textIsEmpty || (icon == null)) ? 0 : textIconGap; if(!textIsEmpty){ /* If the label text string is too wide to fit within the available * space "..." and as many characters as will fit will be * displayed instead. */ var availTextWidth:Number; if (horizontalTextPosition == CENTER) { availTextWidth = viewR.width; }else { availTextWidth = viewR.width - (iconR.width + gap); } if (textR.width > availTextWidth) { text = layoutTextWidth(text, textR, availTextWidth, tf); } } /* Compute textR.x,y given the verticalTextPosition and * horizontalTextPosition properties */ if (verticalTextPosition == TOP) { if (horizontalTextPosition != CENTER) { textR.y = 0; }else { textR.y = -(textR.height + gap); } }else if (verticalTextPosition == CENTER) { textR.y = (iconR.height / 2) - (textR.height / 2); }else { // (verticalTextPosition == BOTTOM) if (horizontalTextPosition != CENTER) { textR.y = iconR.height - textR.height; }else { textR.y = (iconR.height + gap); } } if (horizontalTextPosition == LEFT) { textR.x = -(textR.width + gap); }else if (horizontalTextPosition == CENTER) { textR.x = (iconR.width / 2) - (textR.width / 2); }else { // (horizontalTextPosition == RIGHT) textR.x = (iconR.width + gap); } //trace("textR : " + textR); //trace("iconR : " + iconR); //trace("viewR : " + viewR); /* labelR is the rectangle that contains iconR and textR. * Move it to its proper position given the labelAlignment * properties. * * To avoid actually allocating a Rectangle, Rectangle.union * has been inlined below. */ var labelR_x:Number = Math.min(iconR.x, textR.x); var labelR_width:Number = Math.max(iconR.x + iconR.width, textR.x + textR.width) - labelR_x; var labelR_y:Number = Math.min(iconR.y, textR.y); var labelR_height:Number = Math.max(iconR.y + iconR.height, textR.y + textR.height) - labelR_y; //trace("labelR_x : " + labelR_x); //trace("labelR_width : " + labelR_width); //trace("labelR_y : " + labelR_y); //trace("labelR_height : " + labelR_height); var dx:Number = 0; var dy:Number = 0; if (verticalAlignment == TOP) { dy = viewR.y - labelR_y; } else if (verticalAlignment == CENTER) { dy = (viewR.y + (viewR.height/2)) - (labelR_y + (labelR_height/2)); } else { // (verticalAlignment == BOTTOM) dy = (viewR.y + viewR.height) - (labelR_y + labelR_height); } if (horizontalAlignment == LEFT) { dx = viewR.x - labelR_x; } else if (horizontalAlignment == RIGHT) { dx = (viewR.x + viewR.width) - (labelR_x + labelR_width); } else { // (horizontalAlignment == CENTER) dx = (viewR.x + (viewR.width/2)) - (labelR_x + (labelR_width/2)); } /* Translate textR and glypyR by dx,dy. */ //trace("dx : " + dx); //trace("dy : " + dy); textR.x += dx; textR.y += dy; iconR.x += dx; iconR.y += dy; //trace("tf = " + tf); //trace("textR : " + textR); //trace("iconR : " + iconR); return text; } private static function charWidth(atf:ASTextFormat, ch:String):Number{ return atf.getTextExtent(ch).getWidth(); } public static function computeStringWidth(atf:ASTextFormat, str:String):Number{ return atf.getTextExtent(str).getTextFieldWidth(); } public static function computeStringHeight(atf:ASTextFormat, str:String):Number{ return atf.getTextExtent(str).getTextFieldHeight(); } /** * before call this method textR.width must be filled with correct value of whole text. */ public static function layoutTextWidth(text:String, textR:Rectangle, availTextWidth:Number, tf:ASTextFormat):String{ if (textR.width <= availTextWidth) { return text; } var clipString:String = "..."; var totalWidth:Number = Math.round(computeStringWidth(tf, clipString)); if(totalWidth > availTextWidth){ totalWidth = Math.round(computeStringWidth(tf, "..")); if(totalWidth > availTextWidth){ text = "."; textR.width = Math.round(computeStringWidth(tf, ".")); if(textR.width > availTextWidth){ textR.width = 0; text = ""; } }else{ text = ".."; textR.width = totalWidth; } return text; }else{ var nChars:Number; var lastWidth:Number = totalWidth; //begin binary search var num:Number = text.length; var li:Number = 0; //binary search of left index var ri:Number = num; //binary search of right index while(li<ri){ var i:Number = li + Math.floor((ri - li)/2); var subText:String = text.substring(0, i); var length:Number = Math.ceil(lastWidth + computeStringWidth(tf, subText)); if((li == i - 1) && li>0){ if(length > availTextWidth){ subText = text.substring(0, li); textR.width = Math.ceil(lastWidth + computeStringWidth(tf, text.substring(0, li))); }else{ textR.width = length; } return subText + clipString; }else if(i <= 1){ if(length <= availTextWidth){ textR.width = length; return subText + clipString; }else{ textR.width = lastWidth; return clipString; } } if(length < availTextWidth){ li = i; }else if(length > availTextWidth){ ri = i; }else{ text = subText + clipString; textR.width = length; return text; } } //end binary search textR.width = lastWidth; return ""; /* //the old arithmetic var mCharWidth:Number = charWidth(tf, "i"); for(nChars = 0; nChars < text.length; nChars++) { lastWidth = totalWidth; totalWidth += charWidth(tf, text.charAt(nChars)); if (totalWidth > availTextWidth) { break; } } if(nChars > 0){ text = text.substring(0, nChars) + clipString; }else{ text = clipString; } textR.width = lastWidth; return text; */ } } /** * Compute and return the location of origin of the text baseline, and a possibly clipped * version of the text string. Locations are computed * relative to the viewR rectangle. */ public static function layoutText( f:ASFont, text:String, verticalAlignment:Number, horizontalAlignment:Number, viewR:Rectangle, textR:Rectangle):String { var tf:ASTextFormat = f.getASTextFormat(); var textIsEmpty:Boolean = (text==null || text==""); if(textIsEmpty){ textR.width = textR.height = 0; }else{ var ts:ASTextExtent = tf.getTextExtent(text); textR.width = Math.ceil(ts.getTextFieldWidth()); textR.height = Math.ceil(ts.getTextFieldHeight()); } if(!textIsEmpty){ /* If the label text string is too wide to fit within the available * space "..." and as many characters as will fit will be * displayed instead. */ var availTextWidth:Number = viewR.width; if (textR.width > availTextWidth) { text = layoutTextWidth(text, textR, availTextWidth, tf); } } if(horizontalAlignment == CENTER){ textR.x = viewR.x + (viewR.width - textR.width)/2; }else if(horizontalAlignment == RIGHT){ textR.x = viewR.x + (viewR.width - textR.width); }else{ textR.x = viewR.x; } if(verticalAlignment == CENTER){ textR.y = viewR.y + (viewR.height - textR.height)/2; }else if(verticalAlignment == BOTTOM){ textR.y = viewR.y + (viewR.height - textR.height); }else{ textR.y = viewR.y; } return text; } /** * Fixes inheritance chain for Container's childs to make AsWing MMC-compatible */ public static function fixContainerInheritance(instance:Container):Void { var proto:Object = instance; while (proto.__proto__.__proto__ != null) { if (proto.__proto__ instanceof Container) return; proto = proto.__proto__; } proto.__proto__ = Container.prototype; } }
package net.guttershark.managers { import flash.display.InteractiveObject; import flash.display.LoaderInfo; import flash.events.ActivityEvent; import flash.events.DataEvent; import flash.events.Event; import flash.events.FocusEvent; import flash.events.IEventDispatcher; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.ProgressEvent; import flash.events.StatusEvent; import flash.events.TextEvent; import flash.events.TimerEvent; import flash.media.Camera; import flash.media.Microphone; import flash.media.Sound; import flash.net.FileReference; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.Socket; import flash.net.URLLoader; import flash.text.TextField; import flash.utils.Dictionary; import flash.utils.Timer; import net.guttershark.control.PreloadController; import net.guttershark.display.FLV; import net.guttershark.support.events.FLVEvent; import net.guttershark.support.preloading.events.AssetCompleteEvent; import net.guttershark.support.preloading.events.AssetErrorEvent; import net.guttershark.support.preloading.events.PreloadProgressEvent; import net.guttershark.util.Bandwidth; import net.guttershark.util.Tracking; import net.guttershark.util.XMLLoader; /** * The EventManager class simplifies events and provides shortcuts for event listeners * for AS3 top level classes, guttershark classes, and component events on * an opt-in basis. Depending on the callbacks you have defined in your callback delegate, * event listeners will be added to the object. So this means that not all events will * be listened for, only ones with callback functions defined. * * <p>Events can also be cycled through the javascript tracking framework. You can * send all events that exist for an object through the tracking framework, or - (by * default), only send the events through tracking that you have callbacks defined for.</p> * * @example Using EventManager with a MovieClip. * <listing> * import net.guttershark.managers.EventManager; * * public class Main extends Sprite * { * * private var em:EventManager; * private var mc:MovieClip; * * public function Main() * { * super(); * em = EventManager.gi(); * mc = new MovieClip(); * mc.graphics.beginFill(0xFF0066); * mc.graphics.drawCircle(200, 200, 100); * mc.graphics.endFill(); * em.handleEvents(mc,this,"onCircle"); * addChild(mc); * } * * public function onCircleClick():void * { * trace("circle click"); * } * * public function onCircleAddedToStage():void * { * trace("my circle was added to stage"); * } * } * </listing> * * <p>Callback methods are defined by the prefix you give to the <em><code>handleEvents</code></em> * method, plus the event name.</p> * * @example How callbacks must be defined: * <listing> * import net.guttershark.managers.EventManager; * * var em:EventManager = EventManager.gi(); * var mc:MovieClip = new MovieClip(); * * em.handleEvents(mc,this,"onMyMC",false,true); //onMyMC is the "prefix" * * function onMyMCClick():void{} //Click is the Event -> so the callback must be defined like prefix+event -> onMyMCClick * * //to define a handler for MouseMove, the prefix is "onMyMC" the event is "MouseMove". * function onMyMCMouseMove():void{} * </listing> * * <p>Passing the originating event object back to your callback is optional, but there are a few * events that are not optional, because they contain information you probably need. * The non-negotiable events are listed below.</p> * * <p>EventManager also supports adding your own EventListenerDelegate, this is how * component support is available. There are custom EventListenerDelegates for * components so you don't have to compile every one into your swf. This also * allows you to extend the EventManager to support your own classes that dispatch events.</p> * * @example Adding support for event handler delegate of an FLVPlayback component: * <listing> * import net.guttershark.managers.EventManager; * import net.guttershark.support.eventmanager.FLVPlaybackEventListenerDelegate; * var em:EventManager = EventManager.gi(); * em.addEventListenerDelegate(FLVPlayback,FLVPlaybackEventListenerDelegate); * em.handleEvents(myFLVPlayback,this,"onMyFLVPlayback"); * </listing> * * @example Adding support for tracking (only the click event will go through tracking): * <listing> * import net.guttershark.managers.EventManager; * var em:EventManager = EventManager.gi(); * var mc:MovieClip = new MovieClip(); * em.handleEvents(mc,this,"onMyMC",false,true); * function onMyMCClick(){} * </listing> * * @example Adding support for tracking (all events cycle through tracking): * <listing> * import net.guttershark.managers.EventManager; * var em:EventManager = EventManager.gi(); * var mc:MovieClip = new MovieClip(); * em.handleEvents(mc,this,"onMyMC",false,false,<strong>true</strong>); * function onMyMCClick(){} * </listing> * * <p>In the above example, even though a callback is only defined for the click event, * all events from the object will be fire through tracking - with the usual prefix+eventName * as the id for the tracking call.</p> * * @example Using the EventManager in a loop situation for unique tracking: * <listing> * import net.guttershark.managers.EventManager; * var em:EventManager = EventManager.gi(); * for(var i:int = 0; i < myClips.length; i++) * { * em.handleEvents(myClips[i],this,"onClip",false,true,false,"onClip"+i.toString()); * } * function onClipClick() * { * } * </listing> * * @example Tracking xml file example for the above example. * <listing> * &lt;tracking&gt; * &lt;track id="onClipClick0"&gt; * &lt;atlas&gt;...&lt;/atlas&gt; * &lt;webtrends&gt;...&lt;/webtrends&gt; * &lt;/track&gt; * &lt;track id="onClipClick1"&gt; * &lt;atlas&gt;...&lt;/atlas&gt; * &lt;webtrends&gt;...&lt;/webtrends&gt; * &lt;/track&gt; * &lt;/tracking&gt; * </listing> * * <p>Supported TopLevel Flashplayer Objects and Events:</p> * <table border='1'> * <tr bgcolor="#999999"><td width="200"><strong>Object</strong></td><td><strong>Events</strong></td></tr> * <tr><td>DisplayObject</td><td>Added,AddedToStage,Activate,Deactivate,Removed,RemovedFromStage</td> * <tr><td>InteractiveObject</td><td>Click,DoubleClick,MouseUp,MouseDown,MouseMove,MouseOver,MouseWheel,MouseOut,FocusIn,<br/> * FocusOut,KeyFocusChange,MouseFocusChange,TabChildrenChange,TabIndexChange,TabEnabledChange</td></tr> * <tr><td>Stage</td><td>Resize,Fullscreen,MouseLeave</td></tr> * <tr><td>TextField</td><td>Change,Link</td></tr> * <tr><td>Timer</td><td>Timer,TimerComplete</td></tr> * <tr><td>Socket</td><td>Connect,Close,SocketData</td></tr> * <tr><td>LoaderInfo</td><td>Complete,Unload,Init,Open,Progress</td></tr> * <tr><td>Camera</td><td>Activity,Status</td></tr> * <tr><td>Microphone</td><td>Activity,Status</td></tr> * <tr><td>NetConnection</td><td>Status</td></tr> * <tr><td>NetStream</td><td>Status</td></tr> * <tr><td>FileReference</td><td>Cancel,Complete,Open,Select,UploadCompleteData</td></tr> * <tr><td>Sound</td><td>Progress,Complete,ID3,Open</td></tr> * </table> * * <p>Supported Guttershark Classes:</p> * <table border='1'> * <tr bgcolor="#999999"><td width="200"><strong>Object</strong></td><td width="200"><strong>EventListenerDelegate</strong></td><td><strong>Events</strong></td></tr> * <tr><td>PreloadController</td><td>NA</td><td>Complete,Progress,AssetComplete,AssetError</td></tr> * <tr><td>XMLLoader</td><td>NA</td><td>Complete</td></tr> * <tr><td>SoundManager</td><td>NA</td><td>Change</td></tr> * <tr><td>FLV</td><td>NA</td><td>Start,Stop,BufferFull,BufferEmpty,BufferFlush,SeekNotify,SeekInvalidTime, * Meta,CuePoint,Progress,StreamNotFound</td></tr> * </table> * * <p>Supported Components:</p> * <table border='1'> * <tr bgcolor="#999999"><td width="200"><strong>Component</strong></td><td width="200"><strong>EventHandlerDelegate</strong></td><td><strong>Events</strong></td></tr> * <tr><td>FLVPlayback</td><td>FLVPlaybackEventDelegate</td><td>Play,Pause,Stopped,PlayheadUpdate,StateChange,AutoRewound,Close,Complete,FastForward,Rewind,<br/> * SkinLoaded,Seeked,ScrubStart,ScrubFinish,Ready,BufferState</td></tr> * <tr><td>Button (Inherits Events)</td><td>Change,LabelChange,ButtonDown</td><td></td></tr> * </table> * * <p>To support any of those components, you need to add the EventListenerDelegate for the * target component to the event manager. See the example above for using the FLVPlaybackEventDelegate</p> * * <p>Non-negotiable event types that always pass event objects to your callbacks:</p> * <ul> * <li>AssetErrorEvent.ERROR</li> * <li>AssetCompleteEvent.COMPLETE</li> * <li>ActivityEvent.ACTIVITY</li> * <li>ColorPickerEvent.CHANGE</li> * <li>ComponentEvent.LABEL_CHANGE</li> * <li>DataEvent.UPLOAD_COMPLETE_DATA</li> * <li>KeyboardEvent.KEY_UP</li> * <li>KeyboardEvent.KEY_DOWN</li> * <li>MouseEvent.MOUSE_WHEEL</li> * <li>PreloadProgressEvent.PROGRESS</li> * <li>ScrollEvent.SCROLL</li> * <li>StatusEvent.STATUS</li> * <li>TextEvent.LINK</li> * <li>VideoEvent.PLAYHEAD_UPDATE</li> * <li>FLVEvent.PROGRESS</li> * <li>FLVEvent.META_DATA</li> * <li>FLVEvent.CUE_POINT</li> * <li>FLVEvent.STREAM_NOT_FOUND</li> * </ul> */ final public class EventManager { /** * singleton instance */ private static var instance:EventManager; /** * Stores info about objects. */ private var edinfo:Dictionary; /** * Custom handlers. */ private var handlers:Dictionary; private var h:Dictionary; /** * Custom handler instances. */ private var instances:Dictionary; /** * lookup for interactive objects events. */ private var eventsByObject:Dictionary; /** * Singleton access. */ public static function gi():EventManager { if(instance == null) instance = new EventManager(); return instance; } /** * @private * Constructor for EventListenersDelegate instances. */ public function EventManager() { if(EventManager.instance) throw new Error("EventManager is a singleton, see EventManager.gi()"); instances = new Dictionary(); handlers = new Dictionary(); edinfo = new Dictionary(); eventsByObject = new Dictionary(); h = new Dictionary(); } /** * Add a custom EventListenerDelegate - the class must be * an implementation of EventListenerDelegate. */ public function addEventListenerDelegate(klassOfObject:Class, klassHandler:Class):void { handlers[klassHandler] = klassOfObject; h[klassOfObject] = klassHandler; } /** * A shortcut for the <em><code>handleEvents</em></code> method. * * @see #handleEvents() */ public function he(obj:IEventDispatcher, callbackDelegate:*, callbackPrefix:String, returnEventObjects:Boolean = false, cycleThroughTracking:Boolean = false, cycleAllThroughTracking:Boolean = false, trackingID:String = null):void { handleEvents(obj,callbackDelegate,callbackPrefix,returnEventObjects,cycleThroughTracking,cycleAllThroughTracking,trackingID); } /** * Add auto event handling for the target object. * * @param obj The object to add event listeners to. * @param callbackDelegate The object in which your callback methods are defined. * @param callbackPrefix A prefix for all callback function definitions. * @param returnEventObjects Whether or not to pass the origin event objects back to your callbacks (with exception of non-negotiable event types). * @param cycleThroughTracking For every event that is handled, pass the same event through the tracking framework. Only events that have callbacks will be passed through tracking. * @param cycleAllThroughTracking Automatically adds listeners for every event that the target object dispatches, in order to grab every * event and pass to tracking, without requiring you to have a callback method defined on your callbackDelegate. * @param trackingID Define a custom trackingID to pass through the tracking framework. For events dispatched from the provided object. The id * is made up your tracking id + the acual event. */ public function handleEvents(obj:IEventDispatcher, callbackDelegate:*, callbackPrefix:String, returnEventObjects:Boolean = false, cycleThroughTracking:Boolean = false, cycleAllThroughTracking:Boolean = false, trackingID:String = null):void { if(edinfo[obj]) disposeEventsForObject(obj); edinfo[obj] = {}; edinfo[obj].callbackDelegate = callbackDelegate; edinfo[obj].callbackPrefix = callbackPrefix; edinfo[obj].passEventObjects = returnEventObjects; edinfo[obj].passThroughTracking = cycleThroughTracking; edinfo[obj].trackingID = trackingID; edinfo[obj].cycleAllThroughTracking = cycleAllThroughTracking; if(obj is InteractiveObject) { if((callbackPrefix + "Resize") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.RESIZE, onStageResize,false,0,true); if((callbackPrefix + "Fullscreen") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.FULLSCREEN, onStageFullscreen,false,0,true); if((callbackPrefix + "Added") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.ADDED,onDOAdded,false,0,true); if((callbackPrefix + "AddedToStage") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.ADDED_TO_STAGE,onDOAddedToStage,false,0,true); if((callbackPrefix + "Activate") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.ACTIVATE,onDOActivate,false,0,true); if((callbackPrefix + "Deactivate") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.DEACTIVATE,onDODeactivate,false,0,true); if((callbackPrefix + "Removed") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.REMOVED,onDORemoved,false,0,true); if((callbackPrefix + "RemovedFromStage") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.REMOVED_FROM_STAGE,onDORemovedFromStage,false,0,true); if((callbackPrefix + "MouseLeave") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.MOUSE_LEAVE, onStageMouseLeave,false,0,true); if((callbackPrefix + "Click") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(MouseEvent.CLICK,onIOClick,false,0,true); if((callbackPrefix + "DoubleClick") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(MouseEvent.DOUBLE_CLICK,onIODoubleClick,false,0,true); if((callbackPrefix + "MouseDown") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(MouseEvent.MOUSE_DOWN,onIOMouseDown,false,0,true); if((callbackPrefix + "MouseMove") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(MouseEvent.MOUSE_MOVE,onIOMouseMove,false,0,true); if((callbackPrefix + "MouseUp") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(MouseEvent.MOUSE_UP,onIOMouseUp,false,0,true); if((callbackPrefix + "MouseOut") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(MouseEvent.MOUSE_OUT,onIOMouseOut,false,0,true); if((callbackPrefix + "MouseOver") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(MouseEvent.MOUSE_OVER,onIOMouseOver,false,0,true); if((callbackPrefix + "MouseWheel") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(MouseEvent.MOUSE_WHEEL,onIOMouseWheel,false,0,true); if((callbackPrefix + "RollOut") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(MouseEvent.ROLL_OUT, onIORollOut,false,0,true); if((callbackPrefix + "RollOver") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(MouseEvent.ROLL_OVER,onIORollOver,false,0,true); if((callbackPrefix + "FocusIn") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(FocusEvent.FOCUS_IN,onIOFocusIn,false,0,true); if((callbackPrefix + "FocusOut") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(FocusEvent.FOCUS_OUT,onIOFocusOut,false,0,true); if((callbackPrefix + "KeyFocusChange") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(FocusEvent.KEY_FOCUS_CHANGE,onIOKeyFocusChange,false,0,true); if((callbackPrefix + "MouseFocusChange") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(FocusEvent.MOUSE_FOCUS_CHANGE,onIOMouseFocusChange,false,0,true); if((callbackPrefix + "TabChildrenChange") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.TAB_CHILDREN_CHANGE, onTabChildrenChange,false,0,true); if((callbackPrefix + "TabEnabledChange") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.TAB_ENABLED_CHANGE, onTabEnabledChange,false,0,true); if((callbackPrefix + "TabIndexChange") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.TAB_INDEX_CHANGE,onTabIndexChange,false,0,true); if((callbackPrefix + "KeyDown") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown,false,0,true); if((callbackPrefix + "KeyUp") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(KeyboardEvent.KEY_UP, onKeyUp,false,0,true); } if(obj is FLV) { if(((callbackPrefix + "Progress") in callbackDelegate)) obj.addEventListener(FLVEvent.PROGRESS,onFLVProgress,false,0,true); if(((callbackPrefix + "Start") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(FLVEvent.START,onFLVStart,false,0,true); if(((callbackPrefix + "Stop") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(FLVEvent.STOP,onFLVStop,false,0,true); if(((callbackPrefix + "SeekNotify") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(FLVEvent.SEEK_NOTIFY,onFLVSeekNotify,false,0,true); if(((callbackPrefix + "SeekInvalidTime") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(FLVEvent.SEEK_INVALID_TIME,onFLVSeekInvalidTime,false,0,true); if(((callbackPrefix + "StreamNotFound") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(FLVEvent.STREAM_NOT_FOUND,onFLVStreamNotFound,false,0,true); if(((callbackPrefix + "BufferFlush") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(FLVEvent.BUFFER_FLUSH,onFLVBufferFlush,false,0,true); if(((callbackPrefix + "BufferEmpty") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(FLVEvent.BUFFER_EMPTY,onFLVBufferEmpty,false,0,true); if(((callbackPrefix + "BufferFull") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(FLVEvent.BUFFER_FULL,onFLVBufferFull,false,0,true); if(((callbackPrefix + "CuePoint") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(FLVEvent.CUE_POINT,onFLVCuePoint,false,0,true); if(((callbackPrefix + "Meta") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(FLVEvent.METADATA,onFLVMetaData,false,0,true); } if(obj is PreloadController) { if(((callbackPrefix + "Progress") in callbackDelegate)) obj.addEventListener(PreloadProgressEvent.PROGRESS,onProgress,false,0,true); if(((callbackPrefix + "Complete") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(Event.COMPLETE, onComplete, false, 0, true); if(((callbackPrefix + "AssetComplete") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(AssetCompleteEvent.COMPLETE, onAssetComplete, false, 0, true); if(((callbackPrefix + "AssetError") in callbackDelegate) || cycleAllThroughTracking) obj.addEventListener(AssetErrorEvent.ERROR,onAssetError, false, 0, true); return; } if(obj is TextField) { if((callbackPrefix + "Change") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.CHANGE, onTextFieldChange,false,0,true); if((callbackPrefix + "Link") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(TextEvent.LINK, onTextFieldLink,false,0,true); return; } if(obj is XMLLoader) { var x:XMLLoader = XMLLoader(obj); edinfo[x.contentLoader] = edinfo[obj]; if((callbackPrefix + "Complete") in callbackDelegate || cycleAllThroughTracking) x.contentLoader.addEventListener(Event.COMPLETE,onXMLLoaderComplete,false,0,true); return; } if(obj is Bandwidth) { var b:Bandwidth = Bandwidth(obj); edinfo[b.contentLoader] = edinfo[obj]; if(callbackPrefix + "Complete" in callbackDelegate || cycleAllThroughTracking) b.contentLoader.addEventListener(Event.COMPLETE, onBandwidthComplete,false,0,true); return; } if(obj is SoundManager) { if((callbackPrefix + "Change") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.CHANGE,onSoundChange,false,0,true); return; } for each(var objType:Class in handlers) { if(obj is objType) { var i:* = new h[objType](); i.eventHandlerFunction = this.handleEvent; i.callbackPrefix = callbackPrefix; i.callbackDelegate = callbackDelegate; i.cycleAllThroughTracking = cycleAllThroughTracking; instances[obj] = i; i.addListeners(obj); } } if(obj is Sound) { if((callbackPrefix + "Complete") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.COMPLETE,onSoundComplete,false,0,true); if((callbackPrefix + "Progress") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(ProgressEvent.PROGRESS,onSoundProgress,false,0,true); if((callbackPrefix + "Open") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.OPEN,onSoundOpen,false,0,true); if((callbackPrefix + "ID3") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.ID3,onSoundID3,false,0,true); } if(obj is LoaderInfo || obj is URLLoader) { if((callbackPrefix + "Complete") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.COMPLETE, onLIComplete,false,0,true); if((callbackPrefix + "Open") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.OPEN, onLIOpen,false,0,true); if((callbackPrefix + "Unload") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.UNLOAD, onLIUnload,false,0,true); if((callbackPrefix + "Init") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.INIT, onLIInit,false,0,true); if((callbackPrefix + "Progress") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(ProgressEvent.PROGRESS, onLIProgress,false,0,true); return; } if(obj is Timer) { if((callbackPrefix + "Timer") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(TimerEvent.TIMER, onTimer,false,0,true); if((callbackPrefix + "TimerComplete") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete,false,0,true); return; } if(obj is Camera || obj is Microphone) { if((callbackPrefix + "Activity") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(ActivityEvent.ACTIVITY, onCameraActivity,false,0,true); if((callbackPrefix + "Status") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(StatusEvent.STATUS, onCameraStatus,false,0,true); return; } if(obj is Socket) { if((callbackPrefix + "Close") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.CLOSE, onSocketClose,false,0,true); if((callbackPrefix + "Connect") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.CONNECT, onSocketConnect,false,0,true); if((callbackPrefix + "SocketData") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData,false,0,true); return; } if(obj is NetConnection) { if((callbackPrefix + "Status") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(StatusEvent.STATUS, onCameraStatus,false,0,true); return; } if(obj is NetStream) { if((callbackPrefix + "Status") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(StatusEvent.STATUS, onCameraStatus,false,0,true); return; } if(obj is FileReference) { if((callbackPrefix + "Cancel") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.CANCEL, onFRCancel,false,0,true); if((callbackPrefix + "Complete") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.COMPLETE, onFRComplete,false,0,true); if((callbackPrefix + "Open") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.OPEN,onFROpen,false,0,true); if((callbackPrefix + "Select") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(Event.SELECT, onFRSelect,false,0,true); if((callbackPrefix + "UploadCompleteData") in callbackDelegate || cycleAllThroughTracking) obj.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onFRUploadCompleteData,false,0,true); return; } } private function onFLVSeekNotify(fe:FLVEvent):void { handleEvent(fe,"Seek"); } private function onFLVSeekInvalidTime(fe:FLVEvent):void { handleEvent(fe,"InvalidTime"); } private function onFLVStreamNotFound(fe:FLVEvent):void { handleEvent(fe,"StreamNotFound",true); } private function onFLVBufferFlush(fe:FLVEvent):void { handleEvent(fe,"BufferFlush"); } private function onFLVBufferFull(fe:FLVEvent):void { handleEvent(fe,"BufferFull"); } private function onFLVBufferEmpty(fe:FLVEvent):void { handleEvent(fe,"BufferEmpty"); } private function onFLVCuePoint(fe:FLVEvent):void { handleEvent(fe,"CuePoint",true); } private function onFLVMetaData(fe:FLVEvent):void { handleEvent(fe,"Meta",true); } private function onFLVStop(fe:FLVEvent):void { handleEvent(fe,"Stop"); } private function onFLVStart(fe:FLVEvent):void { handleEvent(fe,"Start"); } private function onFLVProgress(fe:FLVEvent):void { handleEvent(fe,"Progress",true); } private function onSoundID3(e:Event):void { handleEvent(e,"ID3"); } private function onSoundProgress(pe:ProgressEvent):void { trace("progress"); handleEvent(pe,"Progress",true); } private function onSoundComplete(e:Event):void { handleEvent(e,"Complete"); } private function onSoundOpen(e:Event):void { handleEvent(e,"Open"); } public function handleEventsForObjects(callbackDelegate:*, objects:Array,prefixes:Array,returnEventObjects:Boolean = false,cycleThroughTracking:Boolean = false):void { var ol:int = objects.length; var pl:int = prefixes.length; if(ol != pl) throw new Error("The objects and prefixes must be a 1 to 1 relationship."); var i:int = 0; for(i;i<ol;i++) handleEvents(objects[i],callbackDelegate,prefixes[i],returnEventObjects,cycleThroughTracking); } private function onSoundChange(e:Event):void { handleEvent(e,"Change"); } private function onBandwidthComplete(e:Event):void { handleEvent(e,"Complete"); } private function onAssetComplete(ace:AssetCompleteEvent):void { handleEvent(ace,"AssetComplete",true); } private function onAssetError(aee:AssetErrorEvent):void { handleEvent(aee,"AssetError",true); } private function onProgress(pe:PreloadProgressEvent):void { handleEvent(pe,"Progress",true); } private function onComplete(e:*):void { handleEvent(e,"Complete"); } private function onXMLLoaderComplete(e:Event):void { handleEvent(e,"Complete"); } private function onFRCancel(e:Event):void { handleEvent(e, "Cancel"); } private function onFRComplete(e:Event):void { handleEvent(e,"Complete"); } private function onFROpen(e:Event):void { handleEvent(e,"Open"); } private function onFRSelect(e:Event):void { handleEvent(e,"Select"); } private function onFRUploadCompleteData(de:DataEvent):void { handleEvent(de,"UploadCompleteData",true); } private function onSocketClose(e:Event):void { handleEvent(e, "Close"); } private function onSocketConnect(e:Event):void { handleEvent(e, "Connect"); } private function onSocketData(pe:ProgressEvent):void { handleEvent(pe, "SocketData"); } private function onCameraActivity(ae:ActivityEvent):void { handleEvent(ae, "Activity"); } private function onCameraStatus(ae:StatusEvent):void { handleEvent(ae, "Status", true); } private function onLIProgress(pe:ProgressEvent):void { handleEvent(pe, "Progress"); } private function onLIInit(e:Event):void { handleEvent(e, "Init"); } private function onLIUnload(e:Event):void { handleEvent(e, "Unload"); } private function onLIOpen(e:Event):void { handleEvent(e, "Open"); } private function onLIComplete(e:Event):void { handleEvent(e, "Complete"); } private function onKeyDown(e:KeyboardEvent):void { handleEvent(e,"KeyDown",true); } private function onKeyUp(e:KeyboardEvent):void { handleEvent(e,"KeyUp",true); } private function onTabChildrenChange(e:Event):void { handleEvent(e,"TabChildrenChange"); } private function onTabEnabledChange(e:Event):void { handleEvent(e,"TabEnabledChange"); } private function onTabIndexChange(e:Event):void { handleEvent(e,"TabIndexChange"); } private function onTextFieldChange(e:Event):void { handleEvent(e,"Change"); } private function onTextFieldLink(e:TextEvent):void { handleEvent(e,"Link",true); } private function onStageFullscreen(e:Event):void { handleEvent(e,"Fullscreen"); } private function onStageResize(e:Event):void { handleEvent(e,"Resize"); } private function onStageMouseLeave(e:Event):void { handleEvent(e,"MouseLeave"); } private function onTimer(e:Event):void { handleEvent(e,"Timer"); } private function onTimerComplete(e:Event):void { handleEvent(e,"TimerComplete"); } private function onIORollOver(e:MouseEvent):void { handleEvent(e,"RollOver"); } private function onIORollOut(e:MouseEvent):void { handleEvent(e,"RollOut"); } private function onIOFocusIn(e:Event):void { handleEvent(e,"FocusIn"); } private function onIOFocusOut(e:Event):void { handleEvent(e,"FocusOut"); } private function onIOKeyFocusChange(e:Event):void { handleEvent(e,"KeyFocusChange"); } private function onIOMouseFocusChange(e:Event):void { handleEvent(e,"MouseFocusChange"); } private function onDOAdded(e:Event):void { handleEvent(e,"Added"); } private function onDOAddedToStage(e:Event):void { handleEvent(e,"AddedToStage"); } private function onDOActivate(e:Event):void { handleEvent(e,"Activate"); } private function onDODeactivate(e:Event):void { handleEvent(e,"Deactivate"); } private function onDORemoved(e:Event):void { handleEvent(e,"Removed"); } private function onDORemovedFromStage(e:Event):void { handleEvent(e,"RemovedFromStage"); } private function onIOClick(e:MouseEvent):void { handleEvent(e,"Click"); } private function onIODoubleClick(e:MouseEvent):void { handleEvent(e,"DoubleClick"); } private function onIOMouseDown(e:MouseEvent):void { handleEvent(e,"MouseDown"); } private function onIOMouseMove(e:MouseEvent):void { handleEvent(e,"MouseMove"); } private function onIOMouseOver(e:MouseEvent):void { handleEvent(e,"MouseOver"); } private function onIOMouseOut(e:MouseEvent):void { handleEvent(e,"MouseOut"); } private function onIOMouseUp(e:MouseEvent):void { handleEvent(e,"MouseUp"); } private function onIOMouseWheel(e:MouseEvent):void { handleEvent(e,"MouseWheel",true); } /** * Generic method used to handle all events, and possibly call * the callback on the defined callback delegate. */ private function handleEvent(e:*, func:String, forceEventObjectPass:Boolean = false):void { var obj:IEventDispatcher = IEventDispatcher(e.currentTarget || e.target); if(!edinfo[obj]) return; var info:Object = Object(edinfo[obj]); var f:String = info.callbackPrefix + func; if(info.passThroughTracking && !info.trackingID) Tracking.track(f); else if(info.passThroughTracking && info.trackingID) { f = info.trackingID + func; Tracking.track(f); } if(!(f in info.callbackDelegate)) return; if(info.passEventObjects || forceEventObjectPass) info.callbackDelegate[f](e); else info.callbackDelegate[f](); } /** * A shorcut for the disposeEventsForObject method, this will used * in favor of the latter in 1.0. * * @param obj The object in which events are being managed. */ public function disposeEvents(obj:IEventDispatcher):void { disposeEventsForObject(obj); } /** * Dispose of events for an object that was being managed by this event manager. * * @param obj The object in which events are being managed. */ public function disposeEventsForObject(obj:IEventDispatcher):void { if(!edinfo[obj]) return; if(edinfo[obj]) edinfo[obj] = null; if(obj is XMLLoader) { var x:XMLLoader = XMLLoader(obj); edinfo[x.contentLoader] = null; x.contentLoader.removeEventListener(Event.COMPLETE,onXMLLoaderComplete); return; } if(obj is Bandwidth) { var b:Bandwidth = Bandwidth(obj); edinfo[b.contentLoader] = null; b.contentLoader.removeEventListener(Event.COMPLETE, onBandwidthComplete); return; } if(obj is Timer) { obj.removeEventListener(TimerEvent.TIMER, onTimer); obj.removeEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete); return; } if(obj is LoaderInfo || obj is URLLoader) { obj.removeEventListener(Event.COMPLETE, onLIComplete); obj.removeEventListener(Event.OPEN, onLIOpen); obj.removeEventListener(Event.UNLOAD, onLIUnload); obj.removeEventListener(Event.INIT, onLIInit); obj.removeEventListener(ProgressEvent.PROGRESS, onLIProgress); return; } if(obj is Camera || obj is Microphone) { obj.removeEventListener(ActivityEvent.ACTIVITY, onCameraActivity); obj.removeEventListener(StatusEvent.STATUS, onCameraStatus); return; } if(obj is Socket) { obj.removeEventListener(Event.CLOSE, onSocketClose); obj.removeEventListener(Event.CONNECT, onSocketConnect); obj.removeEventListener(ProgressEvent.SOCKET_DATA, onSocketData); return; } if(obj is NetConnection) { obj.removeEventListener(StatusEvent.STATUS, onCameraStatus); return; } if(obj is NetStream) { obj.removeEventListener(StatusEvent.STATUS, onCameraStatus); return; } if(obj is FileReference) { obj.removeEventListener(Event.CANCEL, onFRCancel); obj.removeEventListener(Event.COMPLETE, onFRComplete); obj.removeEventListener(Event.OPEN,onFROpen); obj.removeEventListener(Event.SELECT, onFRSelect); obj.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onFRUploadCompleteData); return; } if(obj is TextField) { obj.removeEventListener(Event.CHANGE, onTextFieldChange); obj.removeEventListener(TextEvent.LINK, onTextFieldLink); return; } if(obj is PreloadController) { obj.removeEventListener(PreloadProgressEvent.PROGRESS, onProgress); obj.removeEventListener(Event.COMPLETE, onComplete); obj.removeEventListener(AssetCompleteEvent.COMPLETE, onAssetComplete); obj.removeEventListener(AssetErrorEvent.ERROR,onAssetError); } if(obj is InteractiveObject) { obj.removeEventListener(Event.RESIZE, onStageResize); obj.removeEventListener(Event.FULLSCREEN, onStageFullscreen); obj.removeEventListener(Event.ADDED,onDOAdded); obj.removeEventListener(Event.ADDED_TO_STAGE,onDOAddedToStage); obj.removeEventListener(Event.ACTIVATE,onDOActivate); obj.removeEventListener(Event.DEACTIVATE,onDODeactivate); obj.removeEventListener(Event.REMOVED,onDORemoved); obj.removeEventListener(Event.REMOVED_FROM_STAGE,onDORemovedFromStage); obj.removeEventListener(Event.MOUSE_LEAVE, onStageMouseLeave); obj.removeEventListener(MouseEvent.CLICK,onIOClick); obj.removeEventListener(MouseEvent.DOUBLE_CLICK,onIODoubleClick); obj.removeEventListener(MouseEvent.MOUSE_DOWN,onIOMouseDown); obj.removeEventListener(MouseEvent.MOUSE_MOVE,onIOMouseMove); obj.removeEventListener(MouseEvent.MOUSE_UP,onIOMouseUp); obj.removeEventListener(MouseEvent.MOUSE_OUT,onIOMouseOut); obj.removeEventListener(MouseEvent.MOUSE_OVER,onIOMouseOver); obj.removeEventListener(MouseEvent.MOUSE_WHEEL,onIOMouseWheel); obj.removeEventListener(MouseEvent.ROLL_OUT, onIORollOut); obj.removeEventListener(MouseEvent.ROLL_OVER,onIORollOver); obj.removeEventListener(FocusEvent.FOCUS_IN,onIOFocusIn); obj.removeEventListener(FocusEvent.FOCUS_OUT,onIOFocusOut); obj.removeEventListener(FocusEvent.KEY_FOCUS_CHANGE,onIOKeyFocusChange); obj.removeEventListener(FocusEvent.MOUSE_FOCUS_CHANGE,onIOMouseFocusChange); obj.removeEventListener(Event.TAB_CHILDREN_CHANGE, onTabChildrenChange); obj.removeEventListener(Event.TAB_ENABLED_CHANGE, onTabEnabledChange); obj.removeEventListener(Event.TAB_INDEX_CHANGE,onTabIndexChange); obj.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown); obj.removeEventListener(KeyboardEvent.KEY_UP, onKeyUp); } if(instances[obj]) { instances[obj].dispose(); instances[obj] = null; } } /** * Dispose of events for multiple objects. * @param objects An array of objects whose events should be disposed of. */ public function disposeEventsForObjects(...objects:Array):void { for each(var obj:* in objects) disposeEventsForObject(obj); } } }
/** * __ __ __ * ____/ /_ ____/ /______ _ ___ / /_ * / __ / / ___/ __/ ___/ / __ `/ __/ * / /_/ / (__ ) / / / / / /_/ / / * \__,_/_/____/_/ /_/ /_/\__, /_/ * / / * \/ * http://distriqt.com * * @author Michael (https://github.com/marchbold) * @created 18/5/21 */ package com.apm.client.commands.general { import com.apm.client.APM; import com.apm.client.commands.Command; import com.apm.client.events.CommandEvent; import com.apm.client.logging.Log; import com.apm.data.user.UserSettings; import flash.events.EventDispatcher; import flash.filesystem.File; public class ConfigCommand extends EventDispatcher implements Command { //////////////////////////////////////////////////////// // CONSTANTS // private static const TAG:String = "ConfigCommand"; public static const NAME:String = "config"; //////////////////////////////////////////////////////// // VARIABLES // private var _parameters:Array; //////////////////////////////////////////////////////// // FUNCTIONALITY // public function ConfigCommand() { super(); _parameters = []; } public function setParameters( parameters:Array ):void { _parameters = parameters; } public function get name():String { return NAME; } public function get category():String { return ""; } public function get requiresNetwork():Boolean { return false; } public function get requiresProject():Boolean { return false; } public function get description():String { return "controls the configuration parameters saved in the global user configuration"; } public function get usage():String { return description + "\n" + "\n" + "apm config set <param> <value> Sets a <param> user configuration parameter to the specified <value> \n" + "apm config get <param> Prints the user configuration parameter value for the <param> parameter \n"; } public function execute():void { Log.d( TAG, "execute(): " + (_parameters.length > 0 ? _parameters[ 0 ] : "...") + "\n" ); try { for (var i:int = 0; i < _parameters.length; i++) { var arg:String = _parameters[ i ]; switch (arg) { case "set": { if (_parameters.length < 3) { dispatchEvent( new CommandEvent( CommandEvent.PRINT_USAGE, name )); dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_ERROR )); return; } var set_param:String = _parameters[ ++i ]; var set_value:String = _parameters.slice( ++i ).join( " " ); switch (set_param) { case "publisher_token": { APM.config.user.publisherToken = set_value; break; } case "github_token": { APM.config.user.githubToken = set_value; break; } case "disable_terminal_control_sequences": { APM.config.user.disableTerminalControlSequences = (set_value == "true" || set_value == "1"); break; } } APM.config.user.save(); dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_OK )); return; } case "get": { if (_parameters.length >= 2) { var param:String = _parameters[ ++i ]; var value:String = "unknown"; switch (param) { case "publisher_token": { value = APM.config.user.publisherToken; break; } case "github_token": { value = APM.config.user.githubToken; break; } case "disable_terminal_control_sequences": { value = APM.config.user.disableTerminalControlSequences ? "true" : "false"; break; } } APM.io.writeLine( param + "=" + (value == null ? "null" : value) ); dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_OK )); return; } else { dispatchEvent( new CommandEvent( CommandEvent.PRINT_USAGE, name )); dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_ERROR )); return; } break; } } } dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_OK )); } catch (e:Error) { APM.io.error( e ); dispatchEvent( new CommandEvent( CommandEvent.COMPLETE, APM.CODE_ERROR )); } } } }
package com.tencent.morefun.naruto.plugin.exui.teammate { import flash.display.MovieClip; public dynamic class TeammateTalkUI extends MovieClip { public var context:MovieClip; public function TeammateTalkUI() { super(); addFrameScript(0,this.frame1,23,this.frame24,27,this.frame28); } function frame1() : * { stop(); } function frame24() : * { stop(); } function frame28() : * { stop(); } } }
import empire_ai.weasel.WeaselAI; import empire_ai.weasel.race.Race; import empire_ai.weasel.Development; import empire_ai.weasel.Planets; import empire_ai.weasel.Budget; import resources; import buildings; import attributes; class Devout : Race, RaceDevelopment { IDevelopment@ development; // [[ MODIFY BASE GAME ]] Planets@ planets; Budget@ budget; const ResourceType@ altarResource; const BuildingType@ altar; int coverAttrib = -1; BuildingRequest@ altarBuild; Planet@ focusAltar; double considerTimer = 0.0; void save(SaveFile& file) { planets.saveBuildingRequest(file, altarBuild); file << focusAltar; file << considerTimer; } void load(SaveFile& file) { @altarBuild = planets.loadBuildingRequest(file); file >> focusAltar; file >> considerTimer; } void create() { @planets = cast<Planets>(ai.planets); @development = cast<IDevelopment>(ai.development); // [[ MODIFY BASE GAME ]] @budget = cast<Budget>(ai.budget); @altarResource = getResource("Altar"); @altar = getBuildingType("Altar"); coverAttrib = getEmpAttribute("AltarSupportedPopulation"); } void start() { auto@ data = ai.empire.getPlanets(); Object@ obj; while(receive(data, obj)) { Planet@ pl = cast<Planet>(obj); if(pl !is null){ if(pl.primaryResourceType == altarResource.id) { @focusAltar = pl; break; } } } } bool shouldBeFocus(Planet& pl, const ResourceType@ resource) override { if(resource is altarResource) return true; return false; } void focusTick(double time) override { //Handle our current altar build if(altarBuild !is null) { if(altarBuild.built) { @focusAltar = altarBuild.plAI.obj; @altarBuild = null; } else if(altarBuild.canceled) { @altarBuild = null; } } //Handle our focused altar if(focusAltar !is null) { if(!focusAltar.valid || focusAltar.owner !is ai.empire || focusAltar.primaryResourceType != altarResource.id) { @focusAltar = null; } } //If we aren't covering our entire population, find new planets to make into altars double coverage = ai.empire.getAttribute(coverAttrib); double population = ai.empire.TotalPopulation; if(coverage >= population || altarBuild !is null) return; bool makeNewAltar = true; if(focusAltar !is null) { auto@ foc = development.getFocus(focusAltar); if(foc !is null && int(foc.obj.level) >= foc.targetLevel) { foc.targetLevel += 1; considerTimer = gameTime + 180.0; makeNewAltar = false; } else { makeNewAltar = gameTime > considerTimer; } } if(makeNewAltar) { if(budget.canSpend(BT_Development, 300)) { //Turn our most suitable planet into an altar PlanetAI@ bestBuild; double bestWeight = 0.0; for(uint i = 0, cnt = planets.planets.length; i < cnt; ++i) { auto@ plAI = planets.planets[i]; double w = randomd(0.9, 1.1); if(plAI.resources !is null && plAI.resources.length != 0) { auto@ res = plAI.resources[0].resource; if(res.level == 0 && !res.limitlessLevel) w *= 5.0; if(res.cls !is null) w *= 0.5; if(res.level > 0) w /= pow(2.0, res.level); } else { w *= 100.0; } if(w > bestWeight) { bestWeight = w; @bestBuild = plAI; } } if(bestBuild !is null) { @altarBuild = planets.requestBuilding(bestBuild, altar, expire=60.0); considerTimer = gameTime + 120.0; } } } } }; AIComponent@ createDevout() { return Devout(); }
package away3d.entities { import away3d.animators.ParticleAnimator; import away3d.animators.nodes.ParticleFollowNode; import away3d.animators.states.ParticleFollowState; import away3d.arcane; import away3d.bounds.BoundingSphere; import away3d.containers.ObjectContainer3D; import flash.geom.Matrix3D; import flash.geom.Vector3D; use namespace arcane; public class FollowParticleContainer extends ObjectContainer3D { private var _identityTransform:Matrix3D = new Matrix3D; private var _followTarget:TargetObject3D; private var _updateBoundMeshes:Vector.<Mesh> = new Vector.<Mesh>; private var _updatePositionMeshes:Vector.<Mesh> = new Vector.<Mesh>; private var _tempCenter:Vector3D = new Vector3D; public function FollowParticleContainer() { _followTarget = new TargetObject3D(this); addChild(_followTarget); } public function addFollowParticle(mesh:Mesh):void { var animator:ParticleAnimator = mesh.animator as ParticleAnimator; if (!animator) throw(new Error("not a particle mesh")); var followState:ParticleFollowState = animator.getAnimationStateByName("ParticleFollowLocalDynamic") as ParticleFollowState; if (!followState) throw(new Error("not a follow particle")); followState.followTarget = _followTarget; addChild(mesh); if ((animator.animationSet.getAnimation("ParticleFollowLocalDynamic") as ParticleFollowNode)._usesPosition) { _updateBoundMeshes.push(mesh); } else { _updatePositionMeshes.push(mesh); } } public function removeFollowParticle(mesh:Mesh):void { var animator:ParticleAnimator = mesh.animator as ParticleAnimator; if (!animator) throw(new Error("not a particle mesh")); var followState:ParticleFollowState = animator.getAnimationStateByName("ParticleFollowLocalDynamic") as ParticleFollowState; if (!followState) throw(new Error("not a follow particle")); followState.followTarget = null; removeChild(mesh); var index:int = _updateBoundMeshes.indexOf(mesh); if (index != -1) _updateBoundMeshes.splice(index, 1); else _updatePositionMeshes.splice(_updatePositionMeshes.indexOf(mesh), 1); } public function get originalSceneTransform():Matrix3D { return super.sceneTransform; } override public function get sceneTransform():Matrix3D { if (_sceneTransformDirty) { var comps:Vector.<Vector3D> = super.sceneTransform.decompose(); var rawData:Vector.<Number> = _identityTransform.rawData; rawData[0] = comps[2].x; rawData[5] = comps[2].y; rawData[10] = comps[2].z; _identityTransform.copyRawDataFrom(rawData); } if (_followTarget.sceneTransformDirty) updateBounds(_followTarget.position); return _identityTransform; } private function updateBounds(center:Vector3D):void { var mesh:Mesh; for each (mesh in _updateBoundMeshes) { _tempCenter.copyFrom(center); _tempCenter.x /= mesh.scaleX; _tempCenter.y /= mesh.scaleY; _tempCenter.z /= mesh.scaleZ; var bounds:BoundingSphere = mesh.bounds as BoundingSphere; bounds.fromSphere(_tempCenter, bounds.radius); } for each (mesh in _updatePositionMeshes) { mesh.position = _followTarget.specificPos; } } } } import away3d.containers.ObjectContainer3D; import away3d.entities.FollowParticleContainer; import flash.geom.Matrix3D; import flash.geom.Vector3D; class TargetObject3D extends ObjectContainer3D { private var _container:FollowParticleContainer; private var _helpTransform:Matrix3D = new Matrix3D; public var specificPos:Vector3D = new Vector3D; private var specificEulers:Vector3D = new Vector3D; public function TargetObject3D(container:FollowParticleContainer) { _container = container; } public function get sceneTransformDirty():Boolean { return _sceneTransformDirty; } private function validateTransform():void { if (_sceneTransformDirty) { _helpTransform.copyFrom(_container.originalSceneTransform); var comps:Vector.<Vector3D> = _helpTransform.decompose(); this.specificPos = comps[0]; specificPos.x /= comps[2].x; specificPos.y /= comps[2].y; specificPos.z /= comps[2].z; //TODO: find a better way to implement it specificEulers.x = 0; specificEulers.y = 0; specificEulers.z = 0; var parent:ObjectContainer3D = _container; while (parent) { specificEulers.x += parent.rotationX; specificEulers.y += parent.rotationY; specificEulers.z += parent.rotationZ; parent = parent.parent; } _sceneTransformDirty = false; } } override public function get x():Number { if (_sceneTransformDirty) validateTransform(); return specificPos.x; } override public function get y():Number { if (_sceneTransformDirty) validateTransform(); return specificPos.y; } override public function get z():Number { if (_sceneTransformDirty) validateTransform(); return specificPos.z; } override public function get position():Vector3D { if (_sceneTransformDirty) validateTransform(); return specificPos; } override public function get rotationX():Number { if (_sceneTransformDirty) validateTransform(); return specificEulers.x; } override public function get rotationY():Number { if (_sceneTransformDirty) validateTransform(); return specificEulers.y; } override public function get rotationZ():Number { if (_sceneTransformDirty) validateTransform(); return specificEulers.z; } }
//////////////////////////////////////////////////////////////////////////////// // // 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 spark.components { import org.apache.royale.events.Event; import spark.layouts.TileLayout; import spark.layouts.supportClasses.LayoutBase; //[IconFile("TileGroup.png")] [Exclude(name="layout", kind="property")] /** * The TileGroup container is an instance of the Group container * that uses the TileLayout class. * Do not modify the <code>layout</code> property. * Instead, use the properties of the TileGroup class to modify the * characteristics of the TileLayout class. * * <p>The TileGroup container has the following default characteristics:</p> * <table class="innertable"> * <tr><th>Characteristic</th><th>Description</th></tr> * <tr><td>Default size</td><td>Large enough to display its children</td></tr> * <tr><td>Minimum size</td><td>0 pixels</td></tr> * <tr><td>Maximum size</td><td>10000 pixels wide and 10000 pixels high</td></tr> * </table> * * @mxml * * <p>The <code>&lt;s:TileGroup&gt;</code> tag inherits all of the tag * attributes of its superclass and adds the following tag attributes:</p> * * <pre> * &lt;s:TileGroup * <strong>Properties</strong> * columnAlign="left" * columnCount="-1" * columnWidth="0" * horizontalAlign="justify" * horizontalGap="6" * orientation="rows" * padding="0" * paddingBottom="0" * paddingLeft="0" * paddingRight="0" * paddingTop="0" * requestedColumnCount"-1" * requestedRowCount="-1" * rowAlign="top" * rowCount="-1" * rowHeight="0" * verticalAlign="justify" * verticalGap="6" * /&gt; * </pre> * * @see spark.layouts.TileLayout * @includeExample examples/TileGroupExample.mxml * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public class TileGroup extends Group { // include "../core/Version.as"; /** * Constructor. * Initializes the <code>layout</code> property to an instance of * the TileLayout class. * * @see spark.layouts.TileLayout * @see spark.components.HGroup * @see spark.components.VGroup * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function TileGroup():void { super(); super.layout = new TileLayout(); } private function get tileLayout():TileLayout { return TileLayout(layout); } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // columnAlign //---------------------------------- [Inspectable(category="General", enumeration="left,justifyUsingGap,justifyUsingWidth", defaultValue="left")] /** * @copy spark.layouts.TileLayout#columnAlign * * @default "left" * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get columnAlign():String { return tileLayout.columnAlign; } /** * @private */ public function set columnAlign(value:String):void { tileLayout.columnAlign = value; } //---------------------------------- // columnCount //---------------------------------- [Bindable("propertyChange")] [Inspectable(category="General")] /** * @copy spark.layouts.TileLayout#columnCount * * @default -1 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get columnCount():int { return tileLayout.columnCount; } //---------------------------------- // columnWidth //---------------------------------- [Bindable("propertyChange")] [Inspectable(category="General", minValue="0.0")] /** * @copy spark.layouts.TileLayout#columnWidth * * @default 0 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get columnWidth():int { return tileLayout.columnWidth; } /** * @private */ public function set columnWidth(value:int):void { tileLayout.columnWidth = value; } //---------------------------------- // horizontalAlign //---------------------------------- [Inspectable(category="General", enumeration="left,right,center,justify", defaultValue="justify")] /** * @copy spark.layouts.TileLayout#horizontalAlign * * @default "justify" * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get horizontalAlign():String { return tileLayout.horizontalAlign; } /** * @private */ public function set horizontalAlign(value:String):void { tileLayout.horizontalAlign = value; } //---------------------------------- // horizontalGap //---------------------------------- [Bindable("propertyChange")] [Inspectable(category="General", defaultValue="6")] /** * @copy spark.layouts.TileLayout#horizontalGap * * @default 6 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get horizontalGap():int { return tileLayout.horizontalGap; } /** * @private */ public function set horizontalGap(value:int):void { tileLayout.horizontalGap = value; } //---------------------------------- // orientation //---------------------------------- [Inspectable(category="General", enumeration="rows,columns", defaultValue="rows")] /** * @copy spark.layouts.TileLayout#orientation * * @default "rows" * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get orientation():String { return tileLayout.orientation; } /** * @private */ public function set orientation(value:String):void { tileLayout.orientation = value; } //---------------------------------- // padding //---------------------------------- [Inspectable(category="General", defaultValue="0.0")] /** * @copy spark.layouts.TileLayout#padding * * @default 0 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get padding():Number { return tileLayout.padding; } /** * @private */ public function set padding(value:Number):void { tileLayout.padding = value; } //---------------------------------- // paddingLeft //---------------------------------- [Inspectable(category="General", defaultValue="0.0")] /** * @copy spark.layouts.TileLayout#paddingLeft * * @default 0 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override public function get paddingLeft():Number { return tileLayout.paddingLeft; } /** * @private */ override public function set paddingLeft(value:Number):void { tileLayout.paddingLeft = value; } //---------------------------------- // paddingRight //---------------------------------- [Inspectable(category="General", defaultValue="0.0")] /** * @copy spark.layouts.TileLayout#paddingRight * * @default 0 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override public function get paddingRight():Number { return tileLayout.paddingRight; } /** * @private */ override public function set paddingRight(value:Number):void { tileLayout.paddingRight = value; } //---------------------------------- // paddingTop //---------------------------------- [Inspectable(category="General", defaultValue="0.0")] /** * @copy spark.layouts.TileLayout#paddingTop * * @default 0 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override public function get paddingTop():Number { return tileLayout.paddingTop; } /** * @private */ override public function set paddingTop(value:Number):void { tileLayout.paddingTop = value; } //---------------------------------- // paddingBottom //---------------------------------- [Inspectable(category="General", defaultValue="0.0")] /** * @copy spark.layouts.TileLayout#paddingBottom * * @default 0 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override public function get paddingBottom():Number { return tileLayout.paddingBottom; } /** * @private */ override public function set paddingBottom(value:Number):void { tileLayout.paddingBottom = value; } //---------------------------------- // requestedColumnCount //---------------------------------- [Inspectable(category="General", minValue="-1")] /** * @copy spark.layouts.TileLayout#requestedColumnCount * * @default -1 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get requestedColumnCount():int { return tileLayout.requestedColumnCount; } /** * @private */ public function set requestedColumnCount(value:int):void { tileLayout.requestedColumnCount = value; } //---------------------------------- // requestedRowCount //---------------------------------- [Inspectable(category="General", minValue="-1")] /** * @copy spark.layouts.TileLayout#requestedRowCount * * @default -1 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get requestedRowCount():int { return tileLayout.requestedRowCount; } /** * @private */ public function set requestedRowCount(value:int):void { tileLayout.requestedRowCount = value; } //---------------------------------- // rowAlign //---------------------------------- [Inspectable(category="General", enumeration="top,justifyUsingGap,justifyUsingHeight", defaultValue="top")] /** * @copy spark.layouts.TileLayout#rowAlign * * @default "top" * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get rowAlign():String { return tileLayout.rowAlign; } /** * @private */ public function set rowAlign(value:String):void { tileLayout.rowAlign = value; } //---------------------------------- // rowCount //---------------------------------- [Bindable("propertyChange")] [Inspectable(category="General")] /** * @copy spark.layouts.TileLayout#rowCount * * @default -1 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get rowCount():int { return tileLayout.rowCount; } //---------------------------------- // rowHeight //---------------------------------- [Bindable("propertyChange")] [Inspectable(category="General", minValue="0.0")] /** * @copy spark.layouts.TileLayout#rowHeight * * @default 0 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get rowHeight():int { return tileLayout.rowHeight; } /** * @private */ public function set rowHeight(value:int):void { tileLayout.rowHeight = value; } //---------------------------------- // verticalAlign //---------------------------------- [Inspectable(category="General", enumeration="top,bottom,middle,justify", defaultValue="justify")] /** * @copy spark.layouts.TileLayout#verticalAlign * * @default "justify" * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get verticalAlign():String { return tileLayout.verticalAlign; } /** * @private */ public function set verticalAlign(value:String):void { tileLayout.verticalAlign = value; } //---------------------------------- // verticalGap //---------------------------------- [Bindable("propertyChange")] [Inspectable(category="General", defaultValue="6")] /** * @copy spark.layouts.TileLayout#verticalGap * * @default 6 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get verticalGap():int { return tileLayout.verticalGap; } /** * @private */ public function set verticalGap(value:int):void { tileLayout.verticalGap = value; } //-------------------------------------------------------------------------- // // Overridden Properties // //-------------------------------------------------------------------------- //---------------------------------- // layout //---------------------------------- /** * @private override public function set layout(value:LayoutBase):void { throw(new Error(resourceManager.getString("components", "layoutReadOnly"))); } */ //-------------------------------------------------------------------------- // // Event Handlers // //-------------------------------------------------------------------------- /** * @private override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { if (type == "propertyChange") { if (!hasEventListener(type)) tileLayout.addEventListener(type, redispatchHandler); } super.addEventListener(type, listener, useCapture, priority, useWeakReference) } */ /** * @private override public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { super.removeEventListener(type, listener, useCapture); if (type == "propertyChange") { if (!hasEventListener(type)) tileLayout.removeEventListener(type, redispatchHandler); } } */ private function redispatchHandler(event:Event):void { dispatchEvent(event); } } }
#include "ParticleCommon.as" #include "Map.as" #include "Camera.as" shared class Particle { Vec3f position; Vec3f velocity; SColor color = color_white; u16 timeToLive = 2 * getTicksASecond(); bool dieOnCollide = false; float gravity = 0.0f; float elasticity = 0.0f; float friction = 1.0f; } shared class ParticleManager { private uint count = 0; private uint maxParticles = 300; private float maxDistance = 30.0f; private Vec3f[] position; private Vec3f[] oldPosition; private Vec3f[] velocity; private SColor[] color; private bool[] static; private uint[] spawnTime; private u16[] timeToLive; private bool[] dieOnCollide; private float[] gravity; private float[] elasticity; private float[] friction; private float maxScale = 0.0625f; private float[] matrix; private CRules@ rules = getRules(); private Map@ map = Map::getMap(); private Camera@ camera = Camera::getCamera(); ParticleManager() { Matrix::MakeIdentity(matrix); position.reserve(maxParticles); oldPosition.reserve(maxParticles); velocity.reserve(maxParticles); color.reserve(maxParticles); static.reserve(maxParticles); spawnTime.reserve(maxParticles); timeToLive.reserve(maxParticles); dieOnCollide.reserve(maxParticles); gravity.reserve(maxParticles); elasticity.reserve(maxParticles); friction.reserve(maxParticles); } void Update() { if (v_fastrender) { ClearParticles(); return; } uint gameTime = getGameTime(); for (int i = count - 1; i >= 0; i--) { float dist = (camera.position - position[i]).magSquared(); if (position[i].y <= -10 || dist >= maxDistance * maxDistance || gameTime >= spawnTime[i] + timeToLive[i]) { RemoveParticle(i); continue; } oldPosition[i] = position[i]; if (static[i]) continue; velocity[i].y = Maths::Clamp(velocity[i].y + gravity[i], -1, 1); position[i] += velocity[i]; Vec3f opf = oldPosition[i].floor(); Vec3f pf = position[i].floor(); if (opf != pf && map.isSolid(map.getBlockSafe(pf))) { if (dieOnCollide[i]) { RemoveParticle(i); continue; } if (opf.y != pf.y) { //prevent particle from phasing through voxel if (velocity[i].y < 0) { position[i].y = Maths::Ceil(position[i].y); velocity[i].x *= friction[i]; velocity[i].z *= friction[i]; if ((velocity[i] - Vec3f(0, gravity[i], 0)).magSquared() < 0.001f) { static[i] = true; velocity[i].Clear(); continue; } } else if (velocity[i].y > 0) { position[i].y = Maths::Floor(position[i].y); } velocity[i].y *= -elasticity[i]; } if (opf.x != pf.x) { if (velocity[i].x < 0) { position[i].x = Maths::Ceil(position[i].x); } else if (velocity[i].x > 0) { position[i].x = Maths::Floor(position[i].x); } velocity[i].x *= -elasticity[i]; } if (opf.z != pf.z) { if (velocity[i].z < 0) { position[i].z = Maths::Ceil(position[i].z); } else if (velocity[i].x > 0) { position[i].z = Maths::Floor(position[i].z); } velocity[i].z *= -elasticity[i]; } } } } void AddParticle(Particle particle) { if (v_fastrender) return; float dist = (camera.position - particle.position).magSquared(); if (dist >= maxDistance * maxDistance) return; if (count >= maxParticles) { RemoveParticle(0); } position.push_back(particle.position); oldPosition.push_back(particle.position); velocity.push_back(particle.velocity); color.push_back(particle.color); spawnTime.push_back(getGameTime()); timeToLive.push_back(particle.timeToLive); dieOnCollide.push_back(particle.dieOnCollide); gravity.push_back(particle.gravity); elasticity.push_back(particle.elasticity); friction.push_back(particle.friction); static.push_back(particle.velocity.magSquared() == 0 && particle.gravity == 0); count++; } void RemoveParticle(uint index) { position.removeAt(index); oldPosition.removeAt(index); velocity.removeAt(index); color.removeAt(index); static.removeAt(index); spawnTime.removeAt(index); timeToLive.removeAt(index); dieOnCollide.removeAt(index); gravity.removeAt(index); elasticity.removeAt(index); friction.removeAt(index); count--; } void ClearParticles() { if (count == 0) return; position.clear(); oldPosition.clear(); velocity.clear(); color.clear(); static.clear(); spawnTime.clear(); timeToLive.clear(); dieOnCollide.clear(); gravity.clear(); elasticity.clear(); friction.clear(); count = 0; } void Render() { if (count == 0) return; Render::SetModelTransform(matrix); float t = Interpolation::getFrameTime(); float gt = Interpolation::getGameTime(); float yRotationRadians = Maths::toRadians(camera.interRotation.y); Vec3f vec(Maths::FastCos(yRotationRadians), 1, Maths::FastSin(yRotationRadians)); Vertex[] vertices = array<Vertex>(count * 4); for (uint i = 0; i < count; i++) { uint index = i * 4; Vec3f pos = static[i] ? position[i] : oldPosition[i].lerp(position[i], t); SColor col = color[i]; float time = (gt - spawnTime[i]) / timeToLive[i]; float scale = maxScale * (1 - Maths::Pow(time, 10)); vertices[index + 0] = Vertex(pos.x - scale * vec.x, pos.y - scale * vec.y, pos.z - scale * vec.z, 0, 1, col); vertices[index + 1] = Vertex(pos.x - scale * vec.x, pos.y + scale * vec.y, pos.z - scale * vec.z, 0, 0, col); vertices[index + 2] = Vertex(pos.x + scale * vec.x, pos.y + scale * vec.y, pos.z + scale * vec.z, 1, 0, col); vertices[index + 3] = Vertex(pos.x + scale * vec.x, pos.y - scale * vec.y, pos.z + scale * vec.z, 1, 1, col); } Render::RawQuads("pixel", vertices); } void CheckStaticParticles() { for (uint i = 0; i < count; i++) { if (!static[i] || gravity[i] == 0.0f) continue; Vec3f pos = position[i] - Vec3f(0, gravity[i], 0); if (!map.isSolid(map.getBlockSafe(pos))) { static[i] = false; } } } uint getParticleCount() { return count; } }
package com.adobe.dashboard.model.chart { public class SaleOportunityModel { private var _companyName:String; public function get companyName():String { return _companyName; } public function set companyName(value:String):void { _companyName=value; } private var _expectedCloseDate:Date; public function get expectedCloseDate():Date { return _expectedCloseDate; } public function set expectedCloseDate(value:Date):void { _expectedCloseDate=value; } private var _expectedGross:Number public function get expectedGross():Number { return _expectedGross; } public function set expectedGross(value:Number):void { _expectedGross=value; } public function SaleOportunityModel() { } } }
/** * * ADOBE SYSTEMS INCORPORATED * Copyright 2012 Adobe Systems Incorporated * All Rights Reserved. * * NOTICE: Adobe permits you to use, modify, and distribute this file * in accordance with the terms of the license agreement accompanying it. * * Author: Jozsef Vass * * Documentation: http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm * */ package com.icecastplayer { import flash.utils.ByteArray; public class MpegHeader { public static const VERSION_25:int = 0; public static const VERSION_2:int = 2; public static const VERSION_1:int = 3; public static const LAYER_1:int = 3; public static const LAYER_2:int = 2; public static const LAYER_3:int = 1; public static const CHANNEL_STEREO:int = 0; public static const CHANNEL_JOINT_STEREO:int = 1; public static const CHANNEL_DUAL:int = 2; public static const CHANNEL_MONO:int = 3; private static const FrameSyncMask:uint = 0xffe00000; private static const AudioVersionIdMask:uint = 0x180000; private static const LayerMask:uint = 0x60000; private static const ProtectionMask:uint = 0x10000; private static const BitrateMask:uint = 0xf000; private static const SamplingRateMask:uint = 0xc00; private static const PaddingMask:uint = 0x200; private static const ChannelModeMask:uint = 0xc0; private static const CopyrightMask:uint = 0x8; private static const OriginalMask:uint = 0x4; private static const BitRateV1L1:Array = [0, 32000, 64000, 96000, 128000, 160000, 192000, 224000, 256000, 288000, 320000, 352000, 384000, 416000, 448000, -1]; private static const BitRateV1L2:Array = [0, 32000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000, 384000, -1]; private static const BitRateV1L3:Array = [0, 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000, -1]; private static const BitRateV2L1:Array = [0, 32000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 144000, 160000, 176000, 192000, 224000, 256000, -1]; private static const BitRateV2L2L3:Array = [0, 8000, 16000, 24000, 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 144000, 160000, -1]; /** * Constructor. */ public function MpegHeader() { reset(); } /** * Reset. */ public function reset():void { header = 0; } /** * MPEG header parser. Performs minimal validation of header. */ public function parse(stream:ByteArray):Boolean { if (stream.bytesAvailable < 4) { return false; } header = stream.readUnsignedInt(); if ((header & FrameSyncMask) ^ FrameSyncMask) { return false; } version = (header & AudioVersionIdMask) >> 19; if (1 == version) { return false; } layer = (header & LayerMask) >> 17; if (0 == layer) { return false; } if (LAYER_1 == layer) { samplesPerFrame = 384; } else if (LAYER_2 == layer || LAYER_3 == layer) { samplesPerFrame = 1152; } protection = (header & ProtectionMask) >> 16; var bitrateIndex:uint = (header & BitrateMask) >> 12; if (15 == bitrateIndex) { return false; } if (VERSION_1 == version) { switch (layer) { case LAYER_1: bitrate = BitRateV1L1[bitrateIndex]; break; case LAYER_2: bitrate = BitRateV1L2[bitrateIndex]; break; case LAYER_3: bitrate = BitRateV1L3[bitrateIndex]; break; } } else if (VERSION_2 == version) { switch (layer) { case LAYER_1: bitrate = BitRateV2L1[bitrateIndex]; break; case LAYER_2: case LAYER_3: bitrate = BitRateV2L2L3[bitrateIndex]; break; } } var samplingRateIndex:uint = (header & SamplingRateMask) >> 10; if (3 == samplingRateIndex) { return false; } switch (version) { case VERSION_1: switch (samplingRateIndex) { case 0: samplingRate = 44100; break; case 1: samplingRate = 48000; break; case 2: samplingRate = 32000; break; } break; case VERSION_2: switch (samplingRateIndex) { case 0: samplingRate = 22050; break; case 1: samplingRate = 24000; break; case 2: samplingRate = 16000; break; } break; case VERSION_25: switch (samplingRateIndex) { case 0: samplingRate = 11025; break; case 1: samplingRate = 12000; break; case 2: samplingRate = 8000; break; } break; } padding = (header & PaddingMask) >> 9; if (LAYER_1 == layer) { frameLengthBytes = (12 * bitrate / samplingRate + padding) * 4; } else if (LAYER_2 == layer || LAYER_3 == layer) { frameLengthBytes = 144 * bitrate / samplingRate + padding; } duration = 1000 * samplesPerFrame / samplingRate; channelMode = (header & ChannelModeMask) >> 6; copyright = (header & CopyrightMask) >> 3; original = (header & OriginalMask) >> 2; return true; } public var version:int = -1; public var layer:int = -1; public var protection:int = -1; public var bitrate:int = -1; public var samplingRate:int = -1; public var padding:int = -1; public var channelMode:int = -1; public var frameLengthBytes:int = -1; public var samplesPerFrame:int = -1; public var copyright:int = -1; public var original:int = -1; public var duration:int = -1; public var header:uint = 0; } }
/* * =BEGIN CLOSED LICENSE * * Copyright (c) 2013-2014 Andras Csizmadia * http://www.vpmedia.eu * * For information about the licensing and copyright please * contact Andras Csizmadia at andras@vpmedia.eu * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * =END CLOSED LICENSE */ package hu.vpmedia.assets.parsers { import flash.net.URLLoaderDataFormat; import hu.vpmedia.assets.loaders.AssetLoaderType; /** * The SWCParser class is an SWC parser. * * @see BaseAssetParser * @see AssetParserType */ public class SWCParser extends BaseAssetParser { //---------------------------------- // Constructor //---------------------------------- /** * Constructor */ public function SWCParser() { super(); _type = AssetParserType.SWC_PARSER; _pattern = /^.+\.((swc))/i; _loaderType = AssetLoaderType.BINARY_LOADER; _dataType = URLLoaderDataFormat.BINARY; } //---------------------------------- // API //---------------------------------- // TODO: implement } }
/* * BetweenAS3 * * Licensed under the MIT License * * Copyright (c) 2009 BeInteractive! (www.be-interactive.org) and * Spark project (www.libspark.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package org.libspark.betweenas3.core.easing { /** * Quadratic.easeInOut. * * @author yossy:beinteractive */ public class QuadraticEaseInOut implements IEasing { /** * @inheritDoc */ public function calculate(t:Number, b:Number, c:Number, d:Number):Number { if ((t /= d / 2) < 1) { return c / 2 * t * t + b; } return -c / 2 * ((--t) * (t - 2) - 1) + b; } } }
package fl.events { import flash.events.Event; import fl.events.ListEvent; public class DataGridEvent extends ListEvent { public static const COLUMN_STRETCH : String; public static const HEADER_RELEASE : String; public static const ITEM_EDIT_BEGINNING : String; public static const ITEM_EDIT_BEGIN : String; public static const ITEM_EDIT_END : String; public static const ITEM_FOCUS_IN : String; public static const ITEM_FOCUS_OUT : String; protected var _dataField : String; protected var _itemRenderer : Object; protected var _reason : String; public function get itemRenderer () : Object; public function get dataField () : String; public function set dataField (value:String) : Void; public function get reason () : String; public function DataGridEvent (type:String, bubbles:Boolean =false, cancelable:Boolean =false, columnIndex:int =-1, rowIndex:int =-1, itemRenderer:Object =null, dataField:String =null, reason:String =null); public function toString () : String; public function clone () : Event; } }
/* Feathers Copyright 2012-2014 Joshua Tynjala. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.controls.supportClasses { import feathers.core.FeathersControl; import feathers.utils.geom.matrixToRotation; import feathers.utils.geom.matrixToScaleX; import feathers.utils.geom.matrixToScaleY; import flash.display.Sprite; import flash.events.TextEvent; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.text.AntiAliasType; import flash.text.GridFitType; import flash.text.StyleSheet; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import starling.core.RenderSupport; import starling.core.Starling; import starling.events.Event; import starling.utils.MatrixUtil; /** * @private */ public class TextFieldViewPort extends FeathersControl implements IViewPort { private static const HELPER_MATRIX:Matrix = new Matrix(); private static const HELPER_POINT:Point = new Point(); public function TextFieldViewPort() { super(); this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler); this.addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler); } private var _textFieldContainer:Sprite; private var _textField:TextField; /** * @private */ private var _text:String = ""; /** * @see feathers.controls.ScrollText#text */ public function get text():String { return this._text; } /** * @private */ public function set text(value:String):void { if(!value) { value = ""; } if(this._text == value) { return; } this._text = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ private var _isHTML:Boolean = false; /** * @see feathers.controls.ScrollText#isHTML */ public function get isHTML():Boolean { return this._isHTML; } /** * @private */ public function set isHTML(value:Boolean):void { if(this._isHTML == value) { return; } this._isHTML = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ private var _textFormat:TextFormat; /** * @see feathers.controls.ScrollText#textFormat */ public function get textFormat():TextFormat { return this._textFormat; } /** * @private */ public function set textFormat(value:TextFormat):void { if(this._textFormat == value) { return; } this._textFormat = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _disabledTextFormat:TextFormat; /** * @see feathers.controls.ScrollText#disabledTextFormat */ public function get disabledTextFormat():TextFormat { return this._disabledTextFormat; } /** * @private */ public function set disabledTextFormat(value:TextFormat):void { if(this._disabledTextFormat == value) { return; } this._disabledTextFormat = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _styleSheet:StyleSheet; /** * @see feathers.controls.ScrollText#styleSheet */ public function get styleSheet():StyleSheet { return this._styleSheet; } /** * @private */ public function set styleSheet(value:StyleSheet):void { if(this._styleSheet == value) { return; } this._styleSheet = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _embedFonts:Boolean = false; /** * @see feathers.controls.ScrollText#embedFonts */ public function get embedFonts():Boolean { return this._embedFonts; } /** * @private */ public function set embedFonts(value:Boolean):void { if(this._embedFonts == value) { return; } this._embedFonts = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _antiAliasType:String = AntiAliasType.ADVANCED; /** * @see feathers.controls.ScrollText#antiAliasType */ public function get antiAliasType():String { return this._antiAliasType; } /** * @private */ public function set antiAliasType(value:String):void { if(this._antiAliasType == value) { return; } this._antiAliasType = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _background:Boolean = false; /** * @see feathers.controls.ScrollText#background */ public function get background():Boolean { return this._background; } /** * @private */ public function set background(value:Boolean):void { if(this._background == value) { return; } this._background = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _backgroundColor:uint = 0xffffff; /** * @see feathers.controls.ScrollText#backgroundColor */ public function get backgroundColor():uint { return this._backgroundColor; } /** * @private */ public function set backgroundColor(value:uint):void { if(this._backgroundColor == value) { return; } this._backgroundColor = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _border:Boolean = false; /** * @see feathers.controls.ScrollText#border */ public function get border():Boolean { return this._border; } /** * @private */ public function set border(value:Boolean):void { if(this._border == value) { return; } this._border = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _borderColor:uint = 0x000000; /** * @see feathers.controls.ScrollText#borderColor */ public function get borderColor():uint { return this._borderColor; } /** * @private */ public function set borderColor(value:uint):void { if(this._borderColor == value) { return; } this._borderColor = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _condenseWhite:Boolean = false; /** * @see feathers.controls.ScrollText#condenseWhite */ public function get condenseWhite():Boolean { return this._condenseWhite; } /** * @private */ public function set condenseWhite(value:Boolean):void { if(this._condenseWhite == value) { return; } this._condenseWhite = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _displayAsPassword:Boolean = false; /** * @see feathers.controls.ScrollText#displayAsPassword */ public function get displayAsPassword():Boolean { return this._displayAsPassword; } /** * @private */ public function set displayAsPassword(value:Boolean):void { if(this._displayAsPassword == value) { return; } this._displayAsPassword = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _gridFitType:String = GridFitType.PIXEL; /** * @see feathers.controls.ScrollText#gridFitType */ public function get gridFitType():String { return this._gridFitType; } /** * @private */ public function set gridFitType(value:String):void { if(this._gridFitType == value) { return; } this._gridFitType = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _sharpness:Number = 0; /** * @see feathers.controls.ScrollText#sharpness */ public function get sharpness():Number { return this._sharpness; } /** * @private */ public function set sharpness(value:Number):void { if(this._sharpness == value) { return; } this._sharpness = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ private var _thickness:Number = 0; /** * @see feathers.controls.ScrollText#thickness */ public function get thickness():Number { return this._thickness; } /** * @private */ public function set thickness(value:Number):void { if(this._thickness == value) { return; } this._thickness = value; this.invalidate(INVALIDATION_FLAG_DATA); } private var _minVisibleWidth:Number = 0; public function get minVisibleWidth():Number { return this._minVisibleWidth; } public function set minVisibleWidth(value:Number):void { if(this._minVisibleWidth == value) { return; } if(value != value) //isNaN { throw new ArgumentError("minVisibleWidth cannot be NaN"); } this._minVisibleWidth = value; this.invalidate(INVALIDATION_FLAG_SIZE); } private var _maxVisibleWidth:Number = Number.POSITIVE_INFINITY; public function get maxVisibleWidth():Number { return this._maxVisibleWidth; } public function set maxVisibleWidth(value:Number):void { if(this._maxVisibleWidth == value) { return; } if(value != value) //isNaN { throw new ArgumentError("maxVisibleWidth cannot be NaN"); } this._maxVisibleWidth = value; this.invalidate(INVALIDATION_FLAG_SIZE); } private var _visibleWidth:Number = NaN; public function get visibleWidth():Number { return this._visibleWidth; } public function set visibleWidth(value:Number):void { if(this._visibleWidth == value || (value != value && this._visibleWidth != this._visibleWidth)) //isNaN { return; } this._visibleWidth = value; this.invalidate(INVALIDATION_FLAG_SIZE); } private var _minVisibleHeight:Number = 0; public function get minVisibleHeight():Number { return this._minVisibleHeight; } public function set minVisibleHeight(value:Number):void { if(this._minVisibleHeight == value) { return; } if(value != value) //isNaN { throw new ArgumentError("minVisibleHeight cannot be NaN"); } this._minVisibleHeight = value; this.invalidate(INVALIDATION_FLAG_SIZE); } private var _maxVisibleHeight:Number = Number.POSITIVE_INFINITY; public function get maxVisibleHeight():Number { return this._maxVisibleHeight; } public function set maxVisibleHeight(value:Number):void { if(this._maxVisibleHeight == value) { return; } if(value != value) //isNaN { throw new ArgumentError("maxVisibleHeight cannot be NaN"); } this._maxVisibleHeight = value; this.invalidate(INVALIDATION_FLAG_SIZE); } private var _visibleHeight:Number = NaN; public function get visibleHeight():Number { return this._visibleHeight; } public function set visibleHeight(value:Number):void { if(this._visibleHeight == value || (value != value && this._visibleHeight != this._visibleHeight)) //isNaN { return; } this._visibleHeight = value; this.invalidate(INVALIDATION_FLAG_SIZE); } public function get contentX():Number { return 0; } public function get contentY():Number { return 0; } private var _scrollStep:Number; public function get horizontalScrollStep():Number { return this._scrollStep; } public function get verticalScrollStep():Number { return this._scrollStep; } private var _horizontalScrollPosition:Number = 0; public function get horizontalScrollPosition():Number { return this._horizontalScrollPosition; } public function set horizontalScrollPosition(value:Number):void { if(this._horizontalScrollPosition == value) { return; } this._horizontalScrollPosition = value; this.invalidate(INVALIDATION_FLAG_SCROLL); } private var _verticalScrollPosition:Number = 0; public function get verticalScrollPosition():Number { return this._verticalScrollPosition; } public function set verticalScrollPosition(value:Number):void { if(this._verticalScrollPosition == value) { return; } this._verticalScrollPosition = value; this.invalidate(INVALIDATION_FLAG_SCROLL); } private var _paddingTop:Number = 0; public function get paddingTop():Number { return this._paddingTop; } public function set paddingTop(value:Number):void { if(this._paddingTop == value) { return; } this._paddingTop = value; this.invalidate(INVALIDATION_FLAG_STYLES); } private var _paddingRight:Number = 0; public function get paddingRight():Number { return this._paddingRight; } public function set paddingRight(value:Number):void { if(this._paddingRight == value) { return; } this._paddingRight = value; this.invalidate(INVALIDATION_FLAG_STYLES); } private var _paddingBottom:Number = 0; public function get paddingBottom():Number { return this._paddingBottom; } public function set paddingBottom(value:Number):void { if(this._paddingBottom == value) { return; } this._paddingBottom = value; this.invalidate(INVALIDATION_FLAG_STYLES); } private var _paddingLeft:Number = 0; public function get paddingLeft():Number { return this._paddingLeft; } public function set paddingLeft(value:Number):void { if(this._paddingLeft == value) { return; } this._paddingLeft = value; this.invalidate(INVALIDATION_FLAG_STYLES); } override public function set visible(value:Boolean):void { if(super.visible == value) { return; } super.visible = value; this._hasPendingRenderChange = true; } override public function set alpha(value:Number):void { if(super.alpha == value) { return; } super.alpha = value; this._hasPendingRenderChange = true; } private var _hasPendingRenderChange:Boolean = false; override public function get hasVisibleArea():Boolean { if(this._hasPendingRenderChange) { return true; } return super.hasVisibleArea; } override public function render(support:RenderSupport, parentAlpha:Number):void { var starlingViewPort:Rectangle = Starling.current.viewPort; HELPER_POINT.x = HELPER_POINT.y = 0; this.parent.getTransformationMatrix(this.stage, HELPER_MATRIX); MatrixUtil.transformCoords(HELPER_MATRIX, 0, 0, HELPER_POINT); var nativeScaleFactor:Number = 1; if(Starling.current.supportHighResolutions) { nativeScaleFactor = Starling.current.nativeStage.contentsScaleFactor; } var scaleFactor:Number = Starling.contentScaleFactor / nativeScaleFactor; this._textFieldContainer.x = starlingViewPort.x + HELPER_POINT.x * scaleFactor; this._textFieldContainer.y = starlingViewPort.y + HELPER_POINT.y * scaleFactor; this._textFieldContainer.scaleX = matrixToScaleX(HELPER_MATRIX) * scaleFactor; this._textFieldContainer.scaleY = matrixToScaleY(HELPER_MATRIX) * scaleFactor; this._textFieldContainer.rotation = matrixToRotation(HELPER_MATRIX) * 180 / Math.PI; this._textFieldContainer.visible = true; this._textFieldContainer.alpha = parentAlpha * this.alpha; this._textFieldContainer.visible = this.visible; this._hasPendingRenderChange = false; super.render(support, parentAlpha); } override protected function initialize():void { this._textFieldContainer = new Sprite(); this._textFieldContainer.visible = false; this._textField = new TextField(); this._textField.autoSize = TextFieldAutoSize.LEFT; this._textField.selectable = false; this._textField.mouseWheelEnabled = false; this._textField.wordWrap = true; this._textField.multiline = true; this._textField.addEventListener(TextEvent.LINK, textField_linkHandler); this._textFieldContainer.addChild(this._textField); } override protected function draw():void { var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); var sizeInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SIZE); var scrollInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SCROLL); var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); if(stylesInvalid) { this._textField.antiAliasType = this._antiAliasType; this._textField.background = this._background; this._textField.backgroundColor = this._backgroundColor; this._textField.border = this._border; this._textField.borderColor = this._borderColor; this._textField.condenseWhite = this._condenseWhite; this._textField.displayAsPassword = this._displayAsPassword; this._textField.embedFonts = this._embedFonts; this._textField.gridFitType = this._gridFitType; this._textField.sharpness = this._sharpness; this._textField.thickness = this._thickness; this._textField.x = this._paddingLeft; this._textField.y = this._paddingTop; } if(dataInvalid || stylesInvalid) { if(this._styleSheet) { this._textField.styleSheet = this._styleSheet; } else { this._textField.styleSheet = null; if(!this._isEnabled && this._disabledTextFormat) { this._textField.defaultTextFormat = this._disabledTextFormat; } else if(this._textFormat) { this._textField.defaultTextFormat = this._textFormat; } } if(this._isHTML) { this._textField.htmlText = this._text; } else { this._textField.text = this._text; } this._scrollStep = this._textField.getLineMetrics(0).height * Starling.contentScaleFactor; } var calculatedVisibleWidth:Number = this._visibleWidth; if(calculatedVisibleWidth != calculatedVisibleWidth) { if(this.stage) { calculatedVisibleWidth = this.stage.stageWidth; } else { calculatedVisibleWidth = Starling.current.stage.stageWidth; } if(calculatedVisibleWidth < this._minVisibleWidth) { calculatedVisibleWidth = this._minVisibleWidth; } else if(calculatedVisibleWidth > this._maxVisibleWidth) { calculatedVisibleWidth = this._maxVisibleWidth; } } this._textField.width = calculatedVisibleWidth - this._paddingLeft - this._paddingRight; var totalContentHeight:Number = this._textField.height + this._paddingTop + this._paddingBottom; var calculatedVisibleHeight:Number = this._visibleHeight; if(calculatedVisibleHeight != calculatedVisibleHeight) { calculatedVisibleHeight = totalContentHeight; if(calculatedVisibleHeight < this._minVisibleHeight) { calculatedVisibleHeight = this._minVisibleHeight; } else if(calculatedVisibleHeight > this._maxVisibleHeight) { calculatedVisibleHeight = this._maxVisibleHeight; } } sizeInvalid = this.setSizeInternal(calculatedVisibleWidth, totalContentHeight, false) || sizeInvalid; if(sizeInvalid || scrollInvalid) { var scrollRect:Rectangle = this._textFieldContainer.scrollRect; if(!scrollRect) { scrollRect = new Rectangle(); } scrollRect.width = calculatedVisibleWidth; scrollRect.height = calculatedVisibleHeight; scrollRect.x = this._horizontalScrollPosition; scrollRect.y = this._verticalScrollPosition; this._textFieldContainer.scrollRect = scrollRect; } } private function addedToStageHandler(event:Event):void { Starling.current.nativeStage.addChild(this._textFieldContainer); } private function removedFromStageHandler(event:Event):void { Starling.current.nativeStage.removeChild(this._textFieldContainer); } protected function textField_linkHandler(event:TextEvent):void { this.dispatchEventWith(Event.TRIGGERED, false, event.text); } } }
/** * VERSION: 1.0 * DATE: 2012-03-22 * AS3 (AS2 and JS versions are also available) * UPDATES AND DOCS AT: http://www.greensock.com **/ import com.greensock.easing.Ease; /** * See AS3 files for full ASDocs * * <p><strong>Copyright 2008-2014, GreenSock. All rights reserved.</strong> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for <a href="http://www.greensock.com/club/">Club GreenSock</a> members, the software agreement that was issued with the membership.</p> * * @author Jack Doyle, jack@greensock.com */ class com.greensock.easing.BackInOut extends Ease { public static var ease:BackInOut = new BackInOut(); public function BackInOut(overshoot:Number) { _p1 = (overshoot || overshoot == 0) ? overshoot : 1.70158; _p2 = _p1 * 1.525; } public function getRatio(p:Number):Number { return ((p*=2) < 1) ? 0.5 * p * p * ((_p2 + 1) * p - _p2) : 0.5 * ((p -= 2) * p * ((_p2 + 1) * p + _p2) + 2); } public function config(overshoot:Number):BackInOut { return new BackInOut(overshoot); } }
//////////////////////////////////////////////////////////////////////////////// // // 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 // // No warranty of merchantability or fitness of any kind. // Use this software at your own risk. // //////////////////////////////////////////////////////////////////////////////// package actionScripts.plugin.splashscreen { import flash.events.Event; import flash.events.EventDispatcher; import mx.collections.ArrayCollection; import mx.resources.ResourceManager; import actionScripts.events.GlobalEventDispatcher; import actionScripts.events.MenuEvent; import actionScripts.plugin.IMenuPlugin; import actionScripts.plugin.PluginBase; import actionScripts.plugin.settings.ISettingsProvider; import actionScripts.plugin.settings.vo.BooleanSetting; import actionScripts.plugin.settings.vo.ISetting; import actionScripts.ui.IContentWindow; import actionScripts.ui.menu.vo.MenuItem; import actionScripts.utils.UtilsCore; import actionScripts.valueObjects.ConstantsCoreVO; import actionScripts.valueObjects.ProjectReferenceVO; import actionScripts.valueObjects.TemplateVO; import components.views.splashscreen.SplashScreen; public class SplashScreenPlugin extends PluginBase implements IMenuPlugin, ISettingsProvider { override public function get name():String { return "Splash Screen Plugin"; } override public function get author():String { return ConstantsCoreVO.MOONSHINE_IDE_LABEL +" Project Team"; } override public function get description():String { return "Shows artsy splashscreen"; } public static const EVENT_SHOW_SPLASH:String = "showSplashEvent"; [Bindable] public var showSplash:Boolean = true; [Bindable] public var projectsTemplates:ArrayCollection = new ArrayCollection(); override public function activate():void { super.activate(); if (showSplash) { showSplashScreen(); } dispatcher.addEventListener(EVENT_SHOW_SPLASH, handleShowSplash); } override public function deactivate():void { super.deactivate(); dispatcher.removeEventListener(EVENT_SHOW_SPLASH, handleShowSplash); } public function getMenu():MenuItem { // Since plugin will be activated if needed we can return null to block menu if( !_activated ) return null; return UtilsCore.getRecentProjectsMenu(); } public function getSettingsList():Vector.<ISetting> { return Vector.<ISetting>([ new BooleanSetting(this, 'showSplash', 'Show splashscreen at startup') ]) } protected function handleShowSplash(event:Event):void { showSplashScreen(); } private function showSplashScreen():void { // Don't add another splash if one is up already for each (var tab:IContentWindow in model.editors) { if (tab is SplashScreen) return; } var splashScreen:SplashScreen = new SplashScreen(); splashScreen.plugin = this; model.editors.addItem(splashScreen); // following will load template data from local for desktop if (ConstantsCoreVO.IS_AIR) { projectsTemplates = getProjectsTemplatesForSpashScreen(); } } private function getProjectsTemplatesForSpashScreen():ArrayCollection { var templates:Array = ConstantsCoreVO.TEMPLATES_PROJECTS.source.filter(filterProjectsTemplates); var specialTemplates:Array = ConstantsCoreVO.TEMPLATES_PROJECTS_SPECIALS.source.filter(filterProjectsTemplates); return new ArrayCollection(templates.concat(specialTemplates)); } private function filterProjectsTemplates(item:TemplateVO, index:int, arr:Array):Boolean { return item.displayHome; } } }
package away3d.core.partition { import away3d.core.base.IRenderable; import away3d.core.traverse.PartitionTraverser; import away3d.entities.Entity; /** * RenderableNode is a space partitioning leaf node that contains any Entity that is itself a IRenderable * object. This excludes Mesh (since the renderable objects are its SubMesh children). */ public class RenderableNode extends EntityNode { private var _renderable : IRenderable; /** * Creates a new RenderableNode object. * @param mesh The mesh to be contained in the node. */ public function RenderableNode(renderable : IRenderable) { super(Entity(renderable)); _renderable = renderable; // also keep a stronger typed reference } /** * @inheritDoc */ override public function acceptTraverser(traverser : PartitionTraverser) : void { if (traverser.enterNode(this)) { super.acceptTraverser(traverser); traverser.applyRenderable(_renderable); } } } }
package ddt.view.tips { import com.pickgliss.ui.ComponentFactory; import com.pickgliss.ui.core.Disposeable; import com.pickgliss.ui.text.FilterFrameText; import com.pickgliss.utils.ObjectUtils; import ddt.manager.SocketManager; import flash.display.Bitmap; import flash.display.Sprite; import flash.events.MouseEvent; import im.info.CustomInfo; public class FriendGroupTItem extends Sprite implements Disposeable { private var _text:FilterFrameText; private var _bg:Bitmap; private var _info:CustomInfo; private var _nickName:String; public function FriendGroupTItem() { super(); this.initView(); } private function initView() : void { this._bg = ComponentFactory.Instance.creatBitmap("asset.FriendGroupTItem.bg"); this._text = ComponentFactory.Instance.creatComponentByStylename("GroupTItem.text"); addChild(this._bg); addChild(this._text); this._bg.visible = false; addEventListener(MouseEvent.MOUSE_OVER,this.__overHandler); addEventListener(MouseEvent.MOUSE_OUT,this.__outHandler); addEventListener(MouseEvent.CLICK,this.__clickHandler); } public function set info(param1:CustomInfo) : void { this._info = param1; this._text.text = this._info.Name; } public function set NickName(param1:String) : void { this._nickName = param1; } protected function __overHandler(param1:MouseEvent) : void { this._bg.visible = true; } protected function __outHandler(param1:MouseEvent) : void { this._bg.visible = false; } protected function __clickHandler(param1:MouseEvent) : void { SocketManager.Instance.out.sendAddFriend(this._nickName,this._info.ID); } override public function get height() : Number { return this._bg.height; } public function dispose() : void { removeEventListener(MouseEvent.MOUSE_OVER,this.__overHandler); removeEventListener(MouseEvent.MOUSE_OUT,this.__outHandler); removeEventListener(MouseEvent.CLICK,this.__clickHandler); if(this._bg) { ObjectUtils.disposeObject(this._bg); } this._bg = null; if(this._text) { ObjectUtils.disposeObject(this._text); } this._text = null; if(parent) { parent.removeChild(this); } } } }
package swift.core.shell.sbin { import org.ais.system.Memory; import swift.core.shell.Shell; public class Shell_mcl extends Shell { public function Shell_mcl() { name = command = "mcl"; callback = __exec; description = "清空内存\n" + "0 智能清空内存\n" + "1 立即清空内存,但不更新清空条件\n" + "2 立即清空内存,同时更新清空条件"; } protected function __exec(str:String):Object { Memory.clear(parseInt(str)); str = null; return null; } } }
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright {yyyy} {name of copyright owner} * * 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.deleidos.rtws.alertcontroller.events { import com.deleidos.rtws.commons.event.TrackableOperationStatusEvent; import flash.events.Event; import flash.utils.getQualifiedClassName; public class JsonEvent extends TrackableOperationStatusEvent { public static const VALIDATE_JSON:String = getQualifiedClassName(JsonEvent) + ".VALIDATE_JSON"; public static const VALIDATE_JSON_STATUS:String = getQualifiedClassName(JsonEvent) + ".VALIDATE_JSON_STATUS"; public static const FORMAT_JSON:String = getQualifiedClassName(JsonEvent) + ".FORMAT_JSON"; public static const FORMAT_JSON_STATUS:String = getQualifiedClassName(JsonEvent) + ".FORMAT_JSON_STATUS"; private var _jsonStrToProcess:String; private var _formattedJson:String; public function JsonEvent(type:String, subType:String, trackingToken:Object, userMsg:String=null, timestamp:Number=NaN, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, subType, trackingToken, userMsg, timestamp, bubbles, cancelable); } public function get jsonStrToProcess():String { return _jsonStrToProcess; } public function set jsonStrToProcess(value:String):void { _jsonStrToProcess = value; } public function get formattedJson():String { return _formattedJson; } public function set formattedJson(value:String):void { _formattedJson = value; } override public function clone():Event { var result:JsonEvent = new JsonEvent(type, subType, trackingToken, userMsg, timestamp, bubbles, cancelable); result.jsonStrToProcess = this.jsonStrToProcess; result.formattedJson = this.formattedJson; return result; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.automation.tool { import flash.display.DisplayObject; import flash.events.Event; import flash.events.IEventDispatcher; import flash.events.TimerEvent; import flash.geom.Point; import flash.utils.Timer; import flash.utils.getQualifiedClassName; import mx.automation.Automation; import mx.automation.AutomationClass; import mx.automation.AutomationConstants; import mx.automation.AutomationError; import mx.automation.AutomationHelper; import mx.automation.AutomationID; import mx.automation.AutomationIDPart; import mx.automation.IAutomationClass; import mx.automation.IAutomationEventDescriptor; import mx.automation.IAutomationManager2; import mx.automation.IAutomationMethodDescriptor; import mx.automation.IAutomationObject; import mx.automation.IAutomationPropertyDescriptor; import mx.automation.IAutomationTabularData; import mx.automation.codec.AdvancedDataGridSelectedCellCodec; import mx.automation.codec.ArrayPropertyCodec; import mx.automation.codec.AssetPropertyCodec; import mx.automation.codec.AutomationObjectPropertyCodec; import mx.automation.codec.ChartItemCodec; import mx.automation.codec.ColorPropertyCodec; import mx.automation.codec.DatePropertyCodec; import mx.automation.codec.DateRangePropertyCodec; import mx.automation.codec.DateScrollDetailPropertyCodec; import mx.automation.codec.DefaultPropertyCodec; import mx.automation.codec.FilePropertyCodec; import mx.automation.codec.HitDataCodec; import mx.automation.codec.IAutomationPropertyCodec; import mx.automation.codec.KeyCodePropertyCodec; import mx.automation.codec.KeyModifierPropertyCodec; import mx.automation.codec.ListDataObjectCodec; import mx.automation.codec.RendererPropertyCodec; import mx.automation.codec.ScrollDetailPropertyCodec; import mx.automation.codec.ScrollDirectionPropertyCodec; import mx.automation.codec.TabObjectCodec; import mx.automation.codec.TriggerEventPropertyCodec; import mx.automation.events.AutomationAirEvent; import mx.automation.events.AutomationCustomReplayEvent; import mx.automation.events.AutomationRecordEvent; import mx.automation.events.EventDetails; import mx.controls.Alert; import mx.controls.Image; import mx.controls.SWFLoader; import mx.core.EventPriority; import mx.core.FlexGlobals; import mx.core.mx_internal; import mx.managers.IMarshalSystemManager; import mx.managers.ISystemManager; import mx.managers.PopUpManager; import mx.managers.SystemManager; import mx.resources.IResourceManager; import mx.resources.ResourceManager; import spark.automation.codec.SparkDropDownListBaseSelectedItemCodec; use namespace mx_internal; [ResourceBundle("automation_agent")] [ResourceBundle("tool_air")] /** * @private */ public class ToolAdapter implements IToolCodecHelper { include "../../core/Version.as"; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * Captures all properties of all objects in the application's active * window/dialog box/Web page in the Active Screen of each step. * This means that all objects can be added to object repository / * added checkpoints, etc. * @private */ public static const COMPLETE:uint = 0; /** * (Default). Captures all properties of all objects in the application's * active window/dialog box/Web page in the Active Screen of the first * step performed in an application's window, plus all properties * of the recorded object in subsequent steps in the same window * (it is an optimization of Complete mode). * As in Complete mode, in this mode, all objects can be added to object * repository / added checkpoints, etc. * @private */ public static const PARTIAL:uint = 1; /** * Captures properties only for the recorded object and its parent in the * Active Screen of each step. * This means that only the recorded objects and its parents can be added * to object repository / added checkpoints, etc. * @private */ public static const MINIMUM:uint = 2; /** * Disables capturing of Active Screen files for all applications * and Web pages. * This means no Active Screen will be shown. * @private */ public static const NONE:uint = 3; // indicates what type of application is being automation currently. /** * @private */ public static const ApplicationType_Flex:int = 0; /** * @private */ public static const ApplicationType_AIR:int = 1; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- /** * @private */ private static var isInitialized:Boolean = false; /** * @private */ private static var qtpCodecHelper:IToolCodecHelper; /** * @private */ public static var _applicationType:int = -1; /** * @private */ public static var _applicationId:String; /** * @private */ //private var sandboxRoot:IEventDispatcher; /** * @private * The highest place we can listen for events in our DOM */ private static var mainListenerObj:IEventDispatcher; /** * @private */ private var lastApplicationName:String; /** * @private */ private var lastRequestName:String; /** * @private */ private var requestPending:Boolean; /** * @private */ private var requestResultObjArray:Array; /** * @private */ private var resultRecieved:Boolean; /** * @private */ private var sm:ISystemManager; /** * @private */ // private var _smMSm:IMarshalSystemManager; /* public function get smMSm():IMarshalSystemManager { if(!_smMSm) _smMSm = IMarshalSystemManager(sm.getImplementation("mx.managers::IMarshalSystemManager")); return _smMSm; } */ //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 4 */ public function ToolAdapter() { super(); sm = FlexGlobals.topLevelApplication.systemManager; //smMSm = sm as IMarshalSystemManager; //_smMSm = IMarshalSystemManager((FlexGlobals.topLevelApplication.systemManager as SystemManager).getImplementation("max.manager::IMarshalSystemManager")); //_smMSm = IMarshalSystemManager((Automation.getMainApplication().systemManager as SystemManager).getImplementation("max.manager::IMarshalSystemManager")); // working line _smMSm = IMarshalSystemManager(sm.getImplementation("mx.managers::IMarshalSystemManager")); // the following code is to take care of Marshalling in Automation // we need to handle all the methods which can reach Tool (which will be a part of // main applicaiton. We need to send the information about this function call to other applications. //sandboxRoot = sm.getSandboxRoot(); // these events are coming from the main application and the children are listening to the main application if(sm.isTopLevelRoot() == false) { var eventDetailsToListenFromParent:Array = new Array(); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.FIND_OBJECTIDS, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.RUN, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.GET_ACTIVESCREEN, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.GET_PARENT, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.GET_RECTANGLE, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.GET_ELEMENT_FROM_POINT, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.GET_ELEMENT_TYPE, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.GET_DISPLAY_NAME, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.GET_PROPERTIES, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.BUILD_DESCRIPTION, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.GET_CHILDREN, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.LEARN_CHILD_OBJECTS, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.GET_LAST_ERROR, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.SET_LAST_ERROR, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.GET_TABULAR_ATTRIBUTES, interAppRequestHandler)); eventDetailsToListenFromParent.push(new EventDetails(ToolMarshallingEvent.GET_TABULAR_DATA, interAppRequestHandler)); automationManager.addEventListenersToAllParentApplications(eventDetailsToListenFromParent); //addEventListenersToAllParentApplications(eventDetailsToListenFromParent); } var eventDetailsToListenFromChildren:Array = new Array(); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.FIND_OBJECTIDS_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.RUN_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.GET_ACTIVESCREEN_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.GET_PARENT_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.GET_RECTANGLE_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.GET_ELEMENT_FROM_POINT_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.GET_ELEMENT_TYPE_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.GET_DISPLAY_NAME_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.GET_PROPERTIES_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.BUILD_DESCRIPTION_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.GET_CHILDREN_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.LEARN_CHILD_OBJECTS_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.GET_LAST_ERROR_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.GET_TABULAR_ATTRIBUTES_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.GET_TABULAR_DATA_REPLY, interAppReplyHandler)); eventDetailsToListenFromChildren.push(new EventDetails(ToolMarshallingEvent.RECORD, marhsalledRecordHandler)); automationManager.addEventListenersToAllChildApplications(eventDetailsToListenFromChildren); automationManager.addEventListener(AutomationRecordEvent.RECORD,recordHandler, false, EventPriority.DEFAULT_HANDLER, true); automationManager.addEventListener(AutomationAirEvent.NEW_AIR_WINDOW,newWindowHandler); if (!isInitialized) { isInitialized = true; qtpCodecHelper = this; // Add the default serializers. addPropertyCodec( "object", new DefaultPropertyCodec()); addPropertyCodec( "keyCode", new KeyCodePropertyCodec()); addPropertyCodec( "keyModifier", new KeyModifierPropertyCodec()); addPropertyCodec( "object[]", new ArrayPropertyCodec(new DefaultPropertyCodec())); addPropertyCodec( "color", new ColorPropertyCodec()); addPropertyCodec( "color[]", new ArrayPropertyCodec(new ColorPropertyCodec())); addPropertyCodec( "automationObject", new AutomationObjectPropertyCodec()); addPropertyCodec( "automationObject[]", new ArrayPropertyCodec(new AutomationObjectPropertyCodec())); addPropertyCodec( "asset", new AssetPropertyCodec()); addPropertyCodec( "asset[]", new ArrayPropertyCodec(new AssetPropertyCodec())); addPropertyCodec( "listDataObject", new ListDataObjectCodec()); addPropertyCodec( "listDataObject[]", new ArrayPropertyCodec(new ListDataObjectCodec())); addPropertyCodec( "rendererObject", new RendererPropertyCodec()); addPropertyCodec( "dateRange", new DateRangePropertyCodec()); addPropertyCodec( "dateObject", new DatePropertyCodec()); addPropertyCodec( "dateRange[]", new ArrayPropertyCodec(new DateRangePropertyCodec())); addPropertyCodec( "event", new TriggerEventPropertyCodec()); addPropertyCodec( "tab", new TabObjectCodec()); addPropertyCodec( "scrollDetail", new ScrollDetailPropertyCodec()); addPropertyCodec( "dateScrollDetail", new DateScrollDetailPropertyCodec()); addPropertyCodec( "scrollDirection", new ScrollDirectionPropertyCodec()); addPropertyCodec( "AdvancedDataGridSelectedCell[]", new ArrayPropertyCodec(new AdvancedDataGridSelectedCellCodec())); addPropertyCodec( "ChartItemCodec", new ChartItemCodec()); addPropertyCodec( "ChartItemCodec[]", new ArrayPropertyCodec(new ChartItemCodec())); addPropertyCodec( "hitDataCodec[]", new ArrayPropertyCodec(new HitDataCodec())); addPropertyCodec( "fileCodec", new FilePropertyCodec()); addPropertyCodec( "SparkDropDownListBaseSelectedItem", new SparkDropDownListBaseSelectedItemCodec()); /* This portion of the code is removed to make the automation_dmv source compilable in Flex Builder source. Why this code was used : To make the application which does not need the datavisuaalisation components, not including these codes The required codecs were supposed to be present in the automation_dmv swc and hence only if the user provides this swc, these classes would have been loaded. But to make these classes under the automation_dmv , we bring the dependancy of qtp and automation source as the codecs use IToolProper.... class. Hence we cannot compile them independantly try { // check for availability of chart codec. // it may not be available if user has not included chart delegates var codec:Object = getDefinitionByName("mx.automation.codec.HitDataCodec"); addPropertyCodec( "hitDataCodec[]", new ArrayPropertyCodec(new codec())); } catch(e:Error) { } */ var message:String; /* if (Capabilities.playerType != "ActiveX") { message = resourceManager.getString( "automation_agent", "notActiveX"); trace(message); return; } if (! Capabilities.os.match(/^Windows/)) { message = resourceManager.getString( "automation_agent", "notWindows", [Capabilities.os]); trace(message); return; } if (!ExternalInterface.available) { message = resourceManager.getString( "automation_agent", "noExternalInterface"); trace(message); return; } if (!playerID || playerID.length == 0) { message = resourceManager.getString( "automation_agent", "noPlayerID"); trace(message); return; } if (playerID.match(/[\.-]/)) { message = resourceManager.getString( "automation_agent", "invalidPlayerID", [playerID]); trace(message); return; } */ try { //ToolAgent.initSocket(); //beginRecording(); /* // for js driver ExternalInterface.addCallback("SetTestingEnvironment", setTestingEnvironment); // Add QTP callbacks ExternalInterface.addCallback("GetParent", getParent); ExternalInterface.addCallback("GetChildren", getChildren); ExternalInterface.addCallback("BuildDescription", buildDescription); ExternalInterface.addCallback("FindObjectId", findObjectID); ExternalInterface.addCallback("FindObjectId2", findObjectIDs); ExternalInterface.addCallback("GetDisplayName", getDisplayName); ExternalInterface.addCallback("GetElementType", getElementType); ExternalInterface.addCallback("GetProperties", getProperties); ExternalInterface.addCallback("GetTabularData", getTabularData); ExternalInterface.addCallback("GetTabularAttributes", getTabularAttributes); ExternalInterface.addCallback("Run", run); ExternalInterface.addCallback("GetLastError", getLastError); ExternalInterface.addCallback("SetLastError", setLastError); ExternalInterface.addCallback("BeginRecording", beginRecording); ExternalInterface.addCallback("EndRecording", endRecording); ExternalInterface.addCallback("GetElementFromPoint", getElementFromPoint); ExternalInterface.addCallback("GetRectangle", getRectangle); ExternalInterface.addCallback("GetActiveScreen", getActiveScreen); ExternalInterface.addCallback("LearnChildObjects", learnChildObjects); // Register ActiveX plugin ExternalInterface.call("eval", "try { window._mx_testing_plugin_" + playerID + " = new ActiveXObject('TEAPluginIE.TEAFlexAgentIE'); }" + "catch(e) { document.getElementById('" + playerID + "').SetLastError(e.message); } "); if (lastError) { message = resourceManager.getString( "automation_agent", "unableToLoadPluginGeneric", [lastError.message]); trace(message); return; } ExternalInterface.call("eval", "if (!window._mx_testing_plugin_" + playerID + ".RegisterPluginWithTool(self, " + "'" + playerID + "')) {" + "document.getElementById('" + playerID + "').SetLastError('TEAPluginIE.TEAFlexAgentIE is not scriptable'); }"); if (lastError) { message = resourceManager.getString( "automation_agent", "unableToLoadPluginGeneric", [lastError.message]); trace(message); return; } // Load environment XML var te:String = ExternalInterface.call("window._mx_testing_plugin_" + playerID + ".GetTestingEnvironment"); setTestingEnvironment(te); */ } catch (se:SecurityError) { message = resourceManager.getString( "automation_agent", "unableToLoadPluginGeneric", [se.message]); Automation.automationDebugTracer.traceMessage("ToolAdapter","ToolAdapter()",message); } } } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private */ private var lastError:Error; /** * @private */ private var propertyCodecMap:Object = []; /** * @private * Used for accessing localized Error messages. */ private static var resourceManager:IResourceManager = ResourceManager.getInstance(); /** * @private * Used for accessing localized Error messages. */ private var detailsSentToTool :Boolean = false; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // automationManager //---------------------------------- /** * @private */ private function get automationManager():IAutomationManager2 { //return Automation.automationManager ; return Automation.automationManager2 as IAutomationManager2; } //---------------------------------- // playerID //---------------------------------- /** * @private */ private function get playerID():String { return FlexGlobals.topLevelApplication.id; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * Registers a custom codec to encoding an decoding of object properties and * event properties to and from a testing tool. For example, ColorPicker * events can contain the selected color. A special color codec is provided * to encode and decode colors from their native number format to hex. * * Predefined codecs include: * "" - The default codec that supports basic types such as String, Number, int and uint. * "color" - Converts a number to hex. * "keyCode" - Converts a keyCode number to a human readable string * "keyState" - Converts ctrlKey, shiftKey and altKey booleans to a human * readable bitfield string. * "skin" - Converts a skin asset class name to closely resemble it's * original asset name. Path separators and periods in the orignal * path name will be converted to underscores. This is only available * on readonly properties. * "automationObject" - Converts an object to it's automationName. * * @param codecName the name of the codec. * * @param codec the implementation of the codec. */ private function addPropertyCodec(codecName:String, codec:IAutomationPropertyCodec):void { propertyCodecMap[codecName] = codec; } /** * @private */ public function setTestingEnvironment(te:String):void { //trace (te); automationManager.automationEnvironment = new ToolEnvironment(new XML(te)); // For supportig Marshalling we need the env information as string and // the name of the class which interprets the information // this information will be used by the Automation Manger in each of the AppDomain // to intialise the class with the details. // #IMP: MARSHALLING NOTE#: The name of the class needs to be maintained across versions // However the implementation of the class can be different in each version. automationManager.automationEnvironmentString = te; automationManager.automationEnvironmentHandlingClassName = "mx.automation.tool.ToolEnvironment"; } /** * Encodes a single value to a testing tool value. Unlike encodeProperties which * takes an object which contains all the properties to encode, this method * takes the actual value to encode. This is useful for encoding return values. * * @param obj the value to be encoded. * * @param propertyDescriptor the property descriptor that describes this value. * * @param relativeParent the IAutomationObject that is related to this value. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 4 */ public function encodeValue(value:Object, testingToolType:String, codecName:String, relativeParent:IAutomationObject):Object { //setup a fake descriptor and object to send to the codec var pd:ToolPropertyDescriptor = new ToolPropertyDescriptor("value", false, false, testingToolType, codecName); var obj:Object = {value:value}; return getPropertyValue(obj, pd, relativeParent); } public function getPropertyValue(obj:Object, pd:ToolPropertyDescriptor, relativeParent:IAutomationObject = null):Object { var codec:IAutomationPropertyCodec = propertyCodecMap[pd.codecName]; if (codec == null) codec = propertyCodecMap["object"]; if (relativeParent == null) relativeParent = obj as IAutomationObject; return codec.encode(automationManager, obj, pd, relativeParent); } /** * Encodes properties in an AS object to an array of values for a testing tool * using the codecs. Since the object being passed in may not be an IAutomationObject * (it could be an event class) and some of the properties require the * IAutomationObject to be transcoded (such as the item renderers in * a list event), relativeParent should always be set to the relevant * IAutomationObject. * * @param obj the object that contains the properties to be encoded. * * @param propertyDescriptors the property descriptors that describes the properties for this object. * * @param relativeParent the IAutomationObject that is related to this object. * * @return the encoded property value. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 4 */ public function encodeProperties(obj:Object, propertyDescriptors:Array, interactionReplayer:IAutomationObject):Array { var result:Array = []; var consecutiveDefaultValueCount:Number = 0; for (var i:int = 0; i < propertyDescriptors.length; i++) { var val:Object = getPropertyValue(obj, propertyDescriptors[i], interactionReplayer); var isDefaultValueNull:Boolean = propertyDescriptors[i].defaultValue == "null"; consecutiveDefaultValueCount = (!(val == null && isDefaultValueNull) && (propertyDescriptors[i].defaultValue == null || val == null || propertyDescriptors[i].defaultValue != val.toString()) ? 0 : consecutiveDefaultValueCount + 1); result.push(val); } result.splice(result.length - consecutiveDefaultValueCount, consecutiveDefaultValueCount); return result; } /** * @private */ private function getValuesWithTypeInformation(elemetnsArray:Array):Array { var count:int = elemetnsArray.length; var index:int = 0; var currentArgsArray:Array= new Array(); while(index < count) { var currentObject:Object = elemetnsArray[index]; var currentObjectType:String = getQualifiedClassName(currentObject); var currentobjString:String; if(currentObject == null) currentobjString = ClientSocketHandler.nullValueIndicator; else currentobjString = currentObject.toString(); var currentArgString:String = currentObjectType+ ClientSocketHandler.typeValueSeparator + currentobjString; currentArgsArray.push(currentArgString); index++; } return currentArgsArray; } /** * @private */ private function handleIncompleteRecord(event:Event):void { if (!automationManager.isSynchronized(null)) { var myTimer:Timer = new Timer(1000,1); myTimer.addEventListener("timer", handleIncompleteRecord); myTimer.start(); } else { var objectId2Object:Object = findObjectIDs(currentDescriptionXMLString); var objectId2Array:Array = (objectId2Object["result"] as Array); var objectId2String:String =""; if(objectId2Array) { var completeString:String; objectId2String = objectId2Array.join(ClientSocketHandler.objectIdSeparators); objectId2String = objectId2Array.join(ClientSocketHandler.objectIdSeparators); completeString = recordInfoString+ objectId2String + ClientSocketHandler.recordInfoSeparator; var request1:RequestData = new RequestData(); request1.requestID = ClientSocketHandler.activeScreenDataStoreRequestString; request1.requestData = activeScreenString; var request2:RequestData = new RequestData(); request2.requestID = ClientSocketHandler.recordRequestString; request2.requestData = completeString; if(sm.isTopLevelRoot() == false) { // send the event to the root applicaiton and let it take care of the socket communication. var marshalledEvent:ToolMarshallingEvent = new ToolMarshallingEvent( ToolMarshallingEvent.RECORD); // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var recordDetails:Array = new Array(); recordDetails.push(request1); recordDetails.push(request2); marshalledEvent.interAppDataToMainApp = recordDetails; dispatchEventToParent(marshalledEvent); } else { if(ToolAgent.clientSocketHandler) { (ToolAgent.clientSocketHandler).addToRecordRequestQueue(request1); (ToolAgent.clientSocketHandler).addToRecordRequestQueue(request2); //trace ("calling processQueuedRecordRequests ToolAgent"); (ToolAgent.clientSocketHandler).processQueuedRecordRequests(true); } } /* Application.application.alpha= appAlpha; Application.application.enabled = true; */ ClientSocketHandler.enableApplication(); } } } private var recordInfoString:String; private var activeScreenString:String; private var currentDescriptionXMLString:String; private var appAlpha:int = -1; private function recordHandler(event:AutomationRecordEvent):void { if(event.isDefaultPrevented()) return; automationManager.incrementCacheCounter(); try { var obj:IAutomationObject = event.automationObject ; var rid:AutomationID = automationManager.createID(obj); var descriptionXML:XML = getDescriptionXML(rid, obj); // We are storing the actual pretty printing value so that we can // reset it back when we are done with our operation. // Ref: http://bugs.adobe.com/jira/browse/FLEXENT-1140 var actualPrettyPrinting:Boolean = XML.prettyPrinting; XML.prettyPrinting = false; var parentRids:Array = []; while (obj) { rid = automationManager.createID(obj); parentRids.push(rid.toString()); obj = automationManager.getParent(obj); } // the last rid corresponds to the highest parent // get the window id for this obejct // clone the automationID var rid1:AutomationID = rid.clone(); //get the first part var objectIdPart:AutomationIDPart = rid1.removeFirst(); var windowId:String = automationManager.getAIRWindowUniqueIDFromAutomationIDPart(objectIdPart); var completeString:String = parentRids.join(":|:"); completeString=completeString.concat(ClientSocketHandler.recordInfoSeparator,descriptionXML.toXMLString(),ClientSocketHandler.recordInfoSeparator,event.name); // now we have parentRids | descriptionXML | event name in the complete string // for the argument arrays var argsArray:Array = event.args as Array; if(argsArray) { var argLength:int = argsArray.length; if(argLength != 0) { var argString :String = (getValuesWithTypeInformation(event.args as Array)).join(ClientSocketHandler.eventArgsSeparator) ; //completeString=completeString.concat(ClientSocketHandler.recordInfoSeparator,event.args.join(ClientSocketHandler.eventArgsSeparator),ClientSocketHandler.recordInfoSeparator); completeString=completeString.concat(ClientSocketHandler.recordInfoSeparator,argString,ClientSocketHandler.recordInfoSeparator); } else completeString=completeString.concat(ClientSocketHandler.recordInfoSeparator,ClientSocketHandler.recordNoArgIndicator,ClientSocketHandler.recordInfoSeparator); } else completeString=completeString.concat(ClientSocketHandler.recordInfoSeparator,ClientSocketHandler.recordNoArgIndicator,ClientSocketHandler.recordInfoSeparator); // now we have the argument details also in the complete string // get the active screen details // before sending the record details , capture the active screen details and send // for the time being we dont have the player coordinates in screen coordinates // we need the top offset and left offset of the player // we need the stage start points //get the point for sub apps using automation manager's API, that returns main //air app's start point. Retuns null if this is main air app var stageStartCoordinate:Point = automationManager.getStartPointInScreenCoordinates(windowId); if(!stageStartCoordinate) //null if this is main air app stageStartCoordinate = getStageStartPointInScreenCoords(windowId); if(!stageStartCoordinate) stageStartCoordinate = new Point(0,0); // we would have got the message for this. so the user is not expected to proceed. // the above is done to avoid the null obejct access. var resultObj:Object = getActiveScreen(0,parentRids[0],stageStartCoordinate.x,stageStartCoordinate.y); // var activeScreenData:String = resultObj.result; activeScreenString = resultObj.result; // calculate object ID string var objectId2Object:Object = findObjectIDs(descriptionXML.toXMLString()); var objectId2Array:Array = (objectId2Object["result"] as Array); var objectId2String:String =""; if(objectId2Array) { objectId2String = objectId2Array.join(ClientSocketHandler.objectIdSeparators); completeString = completeString+ objectId2String + ClientSocketHandler.recordInfoSeparator; var request1:RequestData = new RequestData(); request1.requestID = ClientSocketHandler.activeScreenDataStoreRequestString; request1.requestData = activeScreenString; var request2:RequestData = new RequestData(); request2.requestID = ClientSocketHandler.recordRequestString; request2.requestData = completeString; if(sm.isTopLevelRoot() == false) { // send the event to the root applicaiton and let it take care of the socket communication. var marshalledEvent:ToolMarshallingEvent = new ToolMarshallingEvent( ToolMarshallingEvent.RECORD); // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var recordDetails:Array = new Array(); recordDetails.push(request1); recordDetails.push(request2); marshalledEvent.interAppDataToMainApp = recordDetails; dispatchEventToParent(marshalledEvent); } else { if(ToolAgent.clientSocketHandler) { (ToolAgent.clientSocketHandler).addToRecordRequestQueue(request1); (ToolAgent.clientSocketHandler).addToRecordRequestQueue(request2); //trace ("calling processQueuedRecordRequests ToolAgent"); (ToolAgent.clientSocketHandler).processQueuedRecordRequests(true); } } } else { /* appAlpha = Application.application.alpha; Application.application.alpha= .4; Application.application.enabled = false; */ ClientSocketHandler.disableApplication(); currentDescriptionXMLString = descriptionXML.toXMLString(); recordInfoString = completeString; var myTimer:Timer = new Timer(1000,1); myTimer.addEventListener("timer", handleIncompleteRecord); myTimer.start(); } //rani /* ExternalInterface.call("window._mx_testing_plugin_" + playerID + ".Record", parentRids, descriptionXML.toXMLString(), event.name, event.args);*/ XML.prettyPrinting = actualPrettyPrinting; } catch (e:Error) { lastError = e; Automation.automationDebugTracer.traceMessage("ToolAdapter","recordHandler()",e.message); } automationManager.decrementCacheCounter(); } private function marhsalledRecordHandler(event:Event):void { // Marshalling events are needeed across applicaiton domain // so this conversion shall fail in the same domain // i.e the above check is to avoid the echoing if(event is ToolMarshallingEvent) return; // this handler is only for the main app. so if we are not the main app root // application, we should not handle it, we should just pass to our parent. //if(smMSm && (smMSm.useSWFBridge() == true)) if(sm.isTopLevelRoot() == false) { var event1:ToolMarshallingEvent = ToolMarshallingEvent.marshal(event); dispatchEventToParent(event1); } else { // i.e take the deta send from the sub app and call the external interface call. // #IMP: MARSHALLING NOTE#: var recordDetails:Array = event["interAppDataToMainApp"]; if(recordDetails && recordDetails.length == 2) { /* ExternalInterface.call("window._mx_testing_plugin_" + playerID + ".Record", recordDetails[0], //parentRids, recordDetails[1], //descriptionXML.toXMLString(), recordDetails[2], //event.name, recordDetails[3]); // event.args); */ if(ToolAgent.clientSocketHandler) { (ToolAgent.clientSocketHandler).addToRecordRequestQueue(recordDetails[0]); (ToolAgent.clientSocketHandler).addToRecordRequestQueue(recordDetails[1]); //trace ("calling processQueuedRecordRequests ToolAgent"); (ToolAgent.clientSocketHandler).processQueuedRecordRequests(true); } } } } /** * @private */ public function beginRecording():Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; automationManager.addEventListener(AutomationRecordEvent.RECORD, recordHandler, false, EventPriority.DEFAULT_HANDLER, true); automationManager.beginRecording(); return o; }); } /** * @private */ public function endRecording():Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; automationManager.endRecording(); automationManager.removeEventListener(AutomationRecordEvent.RECORD, recordHandler); return o; }); } /** * @private */ public function getElementType(objID:String, fromTool:Boolean = true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try{ var rid:AutomationID = AutomationID.parse(objID); var requiredApplicationName:String = getApplicationNameFromAutomationID(rid); var currentApplicationName:String = getApplicationName(); if(requiredApplicationName == currentApplicationName) { if (fromTool == true) detailsSentToTool = true; var target:IAutomationObject = automationManager.resolveIDToSingleObject(rid); o.result = automationManager.getAutomationClassName(target); } else { // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(objID); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.GET_ELEMENT_TYPE,details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to QTP o = requestResultObjArray[0] as Object; detailsSentToTool = true; } } } catch (e:Error) { throw e; } return o; }); } /** * @private */ public function getDisplayName(objID:String, fromTool:Boolean = true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try { var rid:AutomationID = AutomationID.parse(objID); // we need to find out whether the current app and the // reuired app are the same. var requiredApplicationName:String = getApplicationNameFromAutomationID(rid); var currentApplicationName:String = getApplicationName(); if(requiredApplicationName == currentApplicationName) { if (fromTool == true) detailsSentToTool = true; var target:IAutomationObject = automationManager.resolveIDToSingleObject(rid); o.result = automationManager.getAutomationName(target); } else { // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(objID); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.GET_DISPLAY_NAME,details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to QTP o = requestResultObjArray[0] as Object; detailsSentToTool = true; } } } catch(e:Error) { throw e; } return o; }); } private function replayEvent(target:IAutomationObject, eventName:String, args:Array):Object { var automationClass:IAutomationClass = automationManager.automationEnvironment.getAutomationClassByInstance(target); var message:String; // try to find the automation class if (! automationClass) { message = resourceManager.getString( "automation_agent", "classNotFound", [AutomationClass.getClassName(target)]); throw new Error(message); } var eventDescriptor:IAutomationEventDescriptor = automationClass.getDescriptorForEventByName(eventName); if (!eventDescriptor) { message = resourceManager.getString( "automation_agent", "methodNotFound", [eventName, automationClass]); throw new Error(message); } var retValue:Object = eventDescriptor.replay(target, args); return {value:retValue, type:null}; } private function replayMethod(target:IAutomationObject, method:String, args:Array):Object { var automationClass:IAutomationClass = automationManager.automationEnvironment.getAutomationClassByInstance(target); var message:String; // try to find the automation class if (! automationClass) { message = resourceManager.getString( "automation_agent", "classNotFound", [AutomationClass.getClassName(target)]); throw new Error(message); } var methodDescriptor:IAutomationMethodDescriptor = automationClass.getDescriptorForMethodByName(method); if (!methodDescriptor) { message = resourceManager.getString( "automation_agent", "methodNotFound", [method, automationClass]); throw new Error(message); } var retValue:Object = methodDescriptor.replay(target, args); if(retValue is IAutomationObject) retValue = automationManager.createID(IAutomationObject(retValue)).toString(); return {value:retValue, type:methodDescriptor.returnType}; } private var replayResultObj:Object = null; private function replayDefaultHandler(event:AutomationCustomReplayEvent):void { replayResultObj = { result:null, error:0 }; if(event.isDefaultPrevented()) return; automationManager.removeEventListener(AutomationCustomReplayEvent.CUSTOM_REPLAY,replayDefaultHandler); if((event.type != AutomationCustomReplayEvent.CUSTOM_REPLAY) || (event.automationObject == null )|| (event.name == null)) return; //var o:Object = { result:null, error:0 }; try { replayResultObj.result = replayMethod(event.automationObject, event.name, event.args); } catch(e:Error) { try { //replayResultObj.result = replayEvent(target, method, args); replayResultObj.result = replayEvent(event.automationObject, event.name, event.args); } catch(e:Error) { automationManager.decrementCacheCounter(); throw e; } } } /** * @private */ public function replay(target:IAutomationObject, method:String, args:Array):Object { // first let us dispatch the custom replay event. replayResultObj = null; // create the custom replay event and dispatch the same var customReplayEventObj:AutomationCustomReplayEvent = new AutomationCustomReplayEvent(AutomationCustomReplayEvent.CUSTOM_REPLAY,false,true); //customReplayEventObj.cancelable should be true. We need to make this true as the default handler can prevent the default. customReplayEventObj.automationObject = target; customReplayEventObj.name = method; customReplayEventObj.args = args; // dispatch the event from the automation manager. automationManager.addEventListener(AutomationCustomReplayEvent.CUSTOM_REPLAY,replayDefaultHandler,false, EventPriority.DEFAULT_HANDLER,false); automationManager.dispatchEvent(customReplayEventObj); return replayResultObj; } /** * @private */ public function run(objID:String, method:String, args:String, fromTool:Boolean = true):Object { return useErrorHandler(function():Object { var resultObj:Object; try { var rid:AutomationID = AutomationID.parse(objID); var requiredApplicationName:String = getApplicationNameFromAutomationID(rid); var currentAppName:String = getApplicationName(); if(requiredApplicationName != currentAppName) { // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(objID); details.push(method); details.push(args); if(fromTool == true) { requestPending = false; resultRecieved = false; } resultObj = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.RUN,details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to QTP resultObj = requestResultObjArray[0]; detailsSentToTool = true; } } else { if (fromTool == true) detailsSentToTool = true; // *************************************** var target:IAutomationObject = automationManager.resolveIDToSingleObject(rid); resultObj = replay(target, method, convertArrayFromCrazyToAs(args)); } // if we have not sent the request to QTP, we need to send the error message that we are not yet synchronised // we need this message only if the request to this method has come from QTP if((detailsSentToTool == false)&&(fromTool == true)) { // we dont expect this case to happen. But just to be on the // safe side we are keeping this error var message:String = resourceManager.getString( "automation_agent", "notSynchronized"); throw new AutomationError(message, AutomationError.OBJECT_NOT_VISIBLE); } } catch(e:Error) { throw e; } return resultObj; }); } /** * @private */ public function findObjectID(descriptionXML:String):Object { // this method is not used in 3 onwards // hence this method is modified to support Marshalling return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try { var rid:AutomationID = new AutomationID(); var x:XML = new XML(descriptionXML); while (x) { var part:AutomationIDPart = new AutomationIDPart(); part.automationClassName = x.@type.toString(); var automationClass:IToolAutomationClass = automationManager.automationEnvironment.getAutomationClassByName(part.automationClassName) as IToolAutomationClass; var propertyCaseRemapping:Object = automationClass.propertyLowerCaseMap; for (var property:Object in x.Property) { var propertyName:String = x.Property[property].@name.toString().toLowerCase(); if (propertyName in propertyCaseRemapping) { var propertyDescriptor:ToolPropertyDescriptor = propertyCaseRemapping[propertyName]; propertyName = propertyDescriptor.name; var regEx:String = x.Property[property].@regExp; var value:String = x.Property[property].@value; if (regEx == "true" || regEx == "t") part[propertyName] = new RegExp(value); else part[propertyName] = value; } } rid.addLast(part); x = x.Element.length() == 1 ? x.Element[0] : null; } var message:String; if (!automationManager.isSynchronized(null)) { message = resourceManager.getString( "automation_agent", "notSynchronized"); throw new AutomationError(message, AutomationError.OBJECT_NOT_VISIBLE); } var obj:IAutomationObject = automationManager.resolveIDToSingleObject(rid); if (!automationManager.isSynchronized(obj)) { message = resourceManager.getString( "automation_agent", "notSynchronized"); throw new AutomationError(message, AutomationError.OBJECT_NOT_VISIBLE); } if (!automationManager.isVisible(obj as DisplayObject)) { message = resourceManager.getString( "automation_agent", "invisible"); throw new AutomationError(message, AutomationError.OBJECT_NOT_VISIBLE); } o.result = automationManager.createID(obj).toString(); } catch(e:Error) { throw e; } return o; }); } /** * @private */ public function findObjectIDs(descriptionXML:String, fromTool :Boolean = true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; var message:String; try { var rid:AutomationID = new AutomationID(); var x:XML = new XML(descriptionXML); var partIndex:int = 0; var sameApplication:Boolean = true; var requiredApplicationName :String ; while (x && sameApplication) { var part:AutomationIDPart = new AutomationIDPart(); part.automationClassName = x.@type.toString(); var automationClass:IToolAutomationClass = automationManager.automationEnvironment.getAutomationClassByName(part.automationClassName) as IToolAutomationClass; var propertyCaseRemapping:Object = automationClass.propertyLowerCaseMap; for (var property:Object in x.Property) { var propertyName:String = x.Property[property].@name.toString().toLowerCase(); if (propertyName in propertyCaseRemapping) { var propertyDescriptor:ToolPropertyDescriptor = propertyCaseRemapping[propertyName]; propertyName = propertyDescriptor.name; var regEx:String = x.Property[property].@regExp; var value:String = x.Property[property].@value; if (regEx == "true" || regEx == "t") part[propertyName] = new RegExp(value); else part[propertyName] = value; } } rid.addLast(part); // we need to decide whehter we are in the correct application if((partIndex == 0) && (fromTool == true)) { requiredApplicationName = automationManager.getApplicationNameFromAutomationIDPart(part); //requiredApplicationName = part["automationName"][0].toString(); var currentAppName:String = getApplicationName(); // we need to check whether this request is for the // root application or sub application. // if it is for the sub applicaiton, we need to send the information as event to the other // applications and wait for the result. if(requiredApplicationName != currentAppName ) sameApplication = false; } partIndex++; x = x.Element.length() == 1 ? x.Element[0] : null; } if (!automationManager.isSynchronized(null)) { message = resourceManager.getString( "automation_agent", "notSynchronized"); throw new AutomationError(message, AutomationError.OBJECT_NOT_VISIBLE); } // before we call methods on the automation manger, whether this request is for the // root application or sub application. // if it is for the sub applicaiton, we need to send the information as event to the other // applications and wait for the result. if(sameApplication == true ) { if (fromTool == true) detailsSentToTool = true; //here we can proceed with the root applicaiton. var autObjects:Array = automationManager.resolveID(rid); for (var i:int = 0; i < autObjects.length; ++i) { autObjects[i] = automationManager.createID(autObjects[i]).toString(); } o.result = autObjects; detailsSentToTool = true; } else { // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(descriptionXML); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.FIND_OBJECTIDS , details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to Tool o.result = requestResultObjArray[0]; detailsSentToTool = true; } } // if we have not sent the request to QTP, we need to send the error message that we are not yet synchronised // we need this message only if the request to this method has come from QTP if((detailsSentToTool == false)&&(fromTool == true)) { // we dont expect this case to happen. But just to be on the // safe side we are keeping this error var message1:String = resourceManager.getString( "automation_agent", "notSynchronized"); throw new AutomationError(message1, AutomationError.OBJECT_NOT_VISIBLE); } } catch(e:Error) { throw e; } return o; }); } /** * @private */ public function buildDescription(objID:String, fromTool:Boolean = true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try { var rid:AutomationID = AutomationID.parse(objID); // we need to find out whether the current app and the // reuired app are the same. var requiredApplicationName:String = getApplicationNameFromAutomationID(rid); var currentApplicationName:String = getApplicationName(); if(requiredApplicationName == currentApplicationName) { if (fromTool == true) detailsSentToTool = true; var obj:IAutomationObject = automationManager.resolveIDToSingleObject(rid); //Don't use getDescriptionXML because it uses the attributes //that were sent into us, and in theory those attributes could //be regular expressions used to find the item //var result:XML = getDescriptionXML(rid, obj); //XML.prettyPrinting = false; //o.result = stripSlashRHack(result.toXMLString()); o.result = getActiveOrLearnXMLTree(objID, false).learnChildrenXML; } else { // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(objID); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.BUILD_DESCRIPTION , details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to Tool o = requestResultObjArray[0]; detailsSentToTool = true; } } // if we have not sent the request to QTP, we need to send the error message that we are not yet synchronised // we need this message only if the request to this method has come from QTP if((detailsSentToTool == false)&&(fromTool == true)) { // we dont expect this case to happen. But just to be on the // safe side we are keeping this error var message:String = resourceManager.getString( "automation_agent", "notSynchronized"); throw new AutomationError(message, AutomationError.OBJECT_NOT_VISIBLE); } } catch (e:Error) { throw e; } return o; }); } /** * @private */ public function getPropertyDescriptors(obj:IAutomationObject, names:Array = null, forVerification:Boolean = true, forDescription:Boolean = true):Array { if (!obj) return null; try { automationManager.incrementCacheCounter(); var automationClass:IToolAutomationClass = automationManager.automationEnvironment.getAutomationClassByInstance(obj) as IToolAutomationClass; var i:int; var propertyCaseRemapping:Object = automationClass.propertyLowerCaseMap; var result:Array = []; if (!names) { var propertyDescriptors:Array = automationClass.getPropertyDescriptors(obj, forVerification, forDescription); names = []; for (i = 0; i < propertyDescriptors.length; i++) { names[i] = propertyDescriptors[i].name; } } for (i = 0; i < names.length; i++) { var lowerCaseName:String = names[i].toLowerCase(); var propertyDescriptor:ToolPropertyDescriptor = propertyCaseRemapping[lowerCaseName]; result.push(propertyDescriptor); } automationManager.decrementCacheCounter(); } catch(e:Error) { automationManager.decrementCacheCounter(); throw e; } return result; } private function encodeValues(obj:IAutomationObject, values:Array, descriptors:Array):Array { var result:Array = []; for (var i:int = 0; i < values.length; ++i) { var descriptor:ToolPropertyDescriptor = descriptors[i]; var codec:IAutomationPropertyCodec = propertyCodecMap[descriptor.codecName]; if (codec == null) codec = propertyCodecMap["object"]; var relativeParent:IAutomationObject = obj; var retValue:Object = codec.encode(automationManager, obj, descriptor, relativeParent); result.push({value:retValue, descriptor:descriptor}); } return result; } /** * @private */ public function getProperties(objID:String, names:String, fromTool:Boolean = true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try { var rid:AutomationID = AutomationID.parse(objID); // we need to find out whether the current app and the // reuired app are the same. var requiredApplicationName:String = getApplicationNameFromAutomationID(rid); var currentApplicationName:String = getApplicationName(); if(requiredApplicationName == currentApplicationName) { if (fromTool == true) detailsSentToTool = true; // we are in the same applicaiton, and hence we can proceed. var obj:IAutomationObject = automationManager.resolveIDToSingleObject(rid); var asNames:Array = convertArrayFromCrazyToAs(names); var descriptors:Array = []; if(asNames && asNames.length) { //trace("getProperties 1- Lenght of Name"+ asNames.length); var automationClass:IToolAutomationClass = automationManager.automationEnvironment.getAutomationClassByInstance(obj) as IToolAutomationClass;; var propertyCaseRemapping:Object = automationClass.propertyLowerCaseMap; for (var i:int = 0; i < asNames.length; i++) { var lowerCaseName:String = asNames[i].toLowerCase(); var propertyDescriptor:IAutomationPropertyDescriptor = propertyCaseRemapping[lowerCaseName]; // trace("getProperties 2 + Name - "+ lowerCaseName); if(propertyDescriptor) { asNames[i] = propertyDescriptor.name; descriptors.push(propertyDescriptor); //trace("getProperties 3 + Name - found"+ lowerCaseName); } else { // descriptor was not found delete the entry. asNames.splice(i, 1); //trace("getProperties 3 + Name - Not found"+ lowerCaseName); } } } var values:Array = automationManager.getProperties(obj, asNames); var x:Array = encodeValues(obj, values, descriptors); //trace("getProperties 4 + found values"+ x.length); for (var no:int = 0; no < x.length; ++no) { x[no] = x[no].value; } o.result = getValuesWithTypeInformation(x); } else { // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(objID); details.push(names); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.GET_PROPERTIES,details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to QTP o = requestResultObjArray[0] as Object; detailsSentToTool = true; } } } catch (e:Error) { throw e; } return o; }); } /** * @private */ public function getParent(objID:String, fromTool:Boolean = true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try { var rid:AutomationID = AutomationID.parse(objID); // we need to find out whether the current app and the // reuired app are the same. var requiredApplicationName:String = getApplicationNameFromAutomationID(rid); var currentApplicationName:String = getApplicationName(); if(requiredApplicationName == currentApplicationName) { if (fromTool == true) detailsSentToTool = true; var obj:IAutomationObject = automationManager.resolveIDToSingleObject(rid); obj = automationManager.getParent(obj); o.result = (obj ? automationManager.createID(obj).toString() : null); } else { // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(objID); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.GET_PARENT,details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to QTP o = requestResultObjArray[0] as Object; detailsSentToTool = true; } } // if we have not sent the request to QTP, we need to send the error message that we are not yet synchronised // we need this message only if the request to this method has come from QTP if((detailsSentToTool == false)&&(fromTool == true)) { // we dont expect this case to happen. But just to be on the // safe side we are keeping this error var message:String = resourceManager.getString( "automation_agent", "notSynchronized"); throw new AutomationError(message, AutomationError.OBJECT_NOT_VISIBLE); } } catch(e:Error) { throw e; } return o; }); } /** * @private */ public function getChildren(objID:String, filterXMLString:String = null, fromTool:Boolean = true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try { var rid:AutomationID = AutomationID.parse(objID); // we need to find out whether the current app and the // reuired app are the same. var requiredApplicationName:String = getApplicationNameFromAutomationID(rid); var currentApplicationName:String = getApplicationName(); if(requiredApplicationName == currentApplicationName) { if (fromTool == true) detailsSentToTool = true; var autObject:IAutomationObject = automationManager.resolveIDToSingleObject(rid); var children:Array; if (autObject.numAutomationChildren > 0) { var part:AutomationIDPart = createPartFromFilterXML(filterXMLString); children = automationManager.getChildrenFromIDPart(autObject, part); for (var i:int = 0; i < children.length; ++i) { children[i] = automationManager.createID(children[i]).toString(); } } else children = [automationManager.createID(autObject).toString()]; o.result = children; } else { // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(objID); details.push(filterXMLString); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.GET_CHILDREN,details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to QTP o = requestResultObjArray[0] as Object; detailsSentToTool = true; } } } catch (e:Error) { throw e; } return o; }); } /** * @private */ public function setLastError(message:String, fromTool:Boolean = true):void { // we need to find out which was the last responded application. var currentAppname:String = getApplicationName(); if ((fromTool == false) || (currentAppname == lastResponseRecievedApplicationName)) { lastError = new Error(message); } else { // this will be called if the fromTool == true and currentAppname != lastResponseRecievedApplicationName // we need to dispatch the event and get the error details from the appropriate application // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(message); handleRequestToDifferentApplication(lastResponseRecievedApplicationName, ToolMarshallingEvent.SET_LAST_ERROR,details); } } /** * @private */ public function getLastError(fromTool:Boolean = true):Object { // we need to find out which was the last responded application. var currentAppname:String = getApplicationName(); if ((fromTool == false) || (currentAppname == lastResponseRecievedApplicationName)) { detailsSentToTool = true; return { result: (lastError ? lastError.message.substr(0, 1 << 9) : null), error: 0 }; } else { var o:Object = { result:null, error:0 }; // we will reach this condition only when fromTool == true and // currentAppname != lastResponseRecievedApplicationName // we need to dispatch the event and get the error details from the appropriate application // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); //details.push(lastResponseRecievedApplicationName); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(lastResponseRecievedApplicationName, ToolMarshallingEvent.GET_LAST_ERROR,details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to QTP o = requestResultObjArray[0] as Object; detailsSentToTool = true; } return o; } } /** * @private */ protected function getRectangle(objID:String, fromTool:Boolean = true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try { var rid:AutomationID = AutomationID.parse(objID); // we need to find out whether the current app and the // reuired app are the same. var requiredApplicationName:String = getApplicationNameFromObjectIDString(objID); var currentApplicationName:String = getApplicationName(); if(requiredApplicationName == currentApplicationName) { if (fromTool == true) detailsSentToTool = true; var obj:IAutomationObject = automationManager.resolveIDToSingleObject(rid); o.result = automationManager.getRectangle(obj as DisplayObject); } else { // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(objID); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.GET_RECTANGLE,details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to QTP o = requestResultObjArray[0] as Object; detailsSentToTool = true; } } } catch(e:Error) { throw e; } return o; }); } public function getRectangleInScreenCoordinates(objID:String):Array { // for AIR, we need to add the chromeHeight and Chrome width to get the screen coordinates // as the app 0,0 does not include the chrome details. var boundarObj:Object = getRectangle(objID); var objBoundaryInAppCoordinates:Array = boundarObj["result"] as Array; var objBoundaryInScreenCoordinates:Array = new Array(); var windowId:String = automationManager.getAIRWindowUniqueIDFromObjectIDString(objID); if(objBoundaryInAppCoordinates.length == 4) { var stageStartScreenCoordinate:Point = getStageStartPointInScreenCoords(windowId); if(!stageStartScreenCoordinate) stageStartScreenCoordinate = new Point(0,0); // we would have got the message for this. so the user is not expected to proceed. // the above is done to avoid the null obejct access. //var chromeHeight:int = getChromeHeight(); // for flex this will return 0 //var chromeWidth:int = getChromeWidth(); // for flex this will return 0 var chromeHeight:int = 0; // for flex this will return 0 var chromeWidth:int = 0; // for flex this will return 0 objBoundaryInScreenCoordinates.push(objBoundaryInAppCoordinates[0] + stageStartScreenCoordinate.x+chromeWidth); objBoundaryInScreenCoordinates.push(objBoundaryInAppCoordinates[1] + stageStartScreenCoordinate.y+chromeHeight); objBoundaryInScreenCoordinates.push(objBoundaryInAppCoordinates[2] + stageStartScreenCoordinate.x+chromeWidth); objBoundaryInScreenCoordinates.push(objBoundaryInAppCoordinates[3] + stageStartScreenCoordinate.y+chromeHeight); /*trace (String(objBoundaryInScreenCoordinates[0]) + String(objBoundaryInScreenCoordinates[1]) + String( objBoundaryInScreenCoordinates[2] ) + String( objBoundaryInScreenCoordinates[3]) );*/ } return objBoundaryInScreenCoordinates; } /** * @private */ public function getElementFromPoint(x:int, y:int, windowId:String, fromTool:Boolean= true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try { var details:Array = new Array(); details.push(x); details.push(y); details.push(windowId); // here the handling is different from the other methods // here we need just let the sub application handle the point // first. if no sub application handles the point, then the main application needs to handle the same if(fromTool == true) { // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. if(fromTool == true) { requestPending = false; resultRecieved = false; } // in the case of this method, we need to let all application process // the request. If the application is able to process the details, we need to // get the details. If we get a Popup or Alerts we need to give the importance of the same. // secondly we need to give priority of a non SWFLoader object. // first let us call from the main applicaiton var appWindow:DisplayObject = automationManager.getAIRWindow(windowId); //Application.application as DisplayObject; var appPoint:Point = convertScreenPointToStagePoint(new Point(x,y),windowId); var appGlobalPoint:Point = appWindow.localToGlobal(appPoint); var obj:IAutomationObject = automationManager.getElementFromPoint2(appGlobalPoint.x, appGlobalPoint.y,windowId); var result:AutomationID; var mainAppObj:Object = null; // add the result to the resultObejct array if the result is not a SWFLoader // Note: we need to check how the object is to be handled when the // application is loaded using Loader if((obj != null) && (!(isObjectSWFLoader(obj1)))) { var currentAppName1:String = getApplicationName(); // we dont need to find out if the object belong to popup // if we dont get a pop up from child, and if we got and // object from main application, main application object has the // preference. var isPopup1:Boolean = automationManager.isObjectPopUp(obj); mainAppObj = { result:null, applicationName:currentAppName1, isPopup:isPopup1, error:0 }; var resultY:AutomationID = automationManager.createID(obj); mainAppObj.result = resultY.toString(); } // irrespective of the result from the main application we // to check what is the object at this point by other application. handleRequestToDifferentApplication(null, ToolMarshallingEvent.GET_ELEMENT_FROM_POINT,details); if(mainAppObj) { var tempArray:Array = new Array(); tempArray.push(mainAppObj); requestResultObjArray = tempArray.concat(requestResultObjArray); } // we would have got replies from all applicaitons which could process the object var count:int = requestResultObjArray.length; if(count != 0) { var index:int = 0; var requiredObjectIdentified:Boolean = false; // process each object var currentObj:Object = null; while((!requiredObjectIdentified) && (index < count)) { currentObj = requestResultObjArray[index]; if(currentObj["isPopup"] == true) { // NOTE: TBD: we need to handle the case of other objects which can be // hosted by the PopupManager requiredObjectIdentified = true; } index++; } if(requiredObjectIdentified == true) { lastApplicationName = currentObj["applicationName" ]; o.result = currentObj.result; } else { // the last loaded application need not be the application on the top. // this depends on the order of the swfloader in an application. // so we need to get the index of the last application. var lastRequiredObjectIndex:int = automationManager.getTopApplicationIndex(requestResultObjArray); //var lastRequiredObjectIndex:int = requestResultObjArray.length - 1; if(lastRequiredObjectIndex != -1) { currentObj = requestResultObjArray[lastRequiredObjectIndex]; lastApplicationName = currentObj["applicationName" ]; o.result = currentObj.result; } } } detailsSentToTool = true; } else { appWindow = FlexGlobals.topLevelApplication as DisplayObject; appPoint = convertScreenPointToStagePoint(new Point(x,y),windowId); if(appPoint) { appGlobalPoint = appWindow.localToGlobal(appPoint); var obj1:IAutomationObject = automationManager.getElementFromPoint(appGlobalPoint.x, appGlobalPoint.y); // check whether the object is a child of system manager // we expect the Alerts and object hosted by the PopupManager // only to get a special treatment if((obj1 != null) && (!isObjectSWFLoader(obj1))) { var isPopup:Boolean = automationManager.isObjectPopUp(obj1); var result1:AutomationID = automationManager.createID(obj1); var currentAppName:String = getApplicationName(); var o2:Object = { result:null, applicationName:currentAppName, isPopup:isPopup, error:0 }; o2.result = result1.toString(); return o2; } } } } catch (e:Error) { throw e; } return o; }); } private function isObjectSWFLoader(obj:Object):Boolean { var retValue:Boolean = false; if(obj is SWFLoader) { // Image is also a SWFLoader. But we should not ignore that. if(!(obj is Image)) retValue = true; } return retValue } /** * @private */ public function getActiveScreen(level:uint, objID:String, leftOffset:int, topOffset:int, fromTool:Boolean = true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try { // we need to find out whether the current app and the // reuired app are the same. var requiredApplicationName:String = getApplicationNameFromObjectIDString(objID); var currentApplicationName:String = getApplicationName(); if(requiredApplicationName == currentApplicationName) { if (fromTool == true) detailsSentToTool = true; //we could make the 2nd parameter true if we wanted to support //the complete level o.result = getActiveOrLearnXMLTree(objID, false, "", true, leftOffset, topOffset).learnChildrenXML; } else { // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(level); details.push(objID); details.push(leftOffset); details.push(topOffset); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.GET_ACTIVESCREEN,details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to QTP o = requestResultObjArray[0] as Object; detailsSentToTool = true; } } } catch(e:Error) { throw e; } return o; }); } /** * @private */ public function learnChildObjects(objID:String, filterXMLString:String, fromTool:Boolean = true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try { // we need to find out whether the current app and the // reuired app are the same. var requiredApplicationName:String = getApplicationNameFromObjectIDString(objID); var currentApplicationName:String = getApplicationName(); if(requiredApplicationName == currentApplicationName) { if (fromTool == true) detailsSentToTool = true; //we could make the 2nd parameter true if we wanted to support //the complete level o.result = getActiveOrLearnXMLTree(objID, true, filterXMLString); } else { // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(objID); details.push(filterXMLString); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.LEARN_CHILD_OBJECTS,details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to QTP o = requestResultObjArray[0] as Object; detailsSentToTool = true; } } } catch(e:Error) { throw e; } return o; }); } /** * @private */ public function getTabularData(objID:String, begin:uint = 0, end:uint = 0, fromTool:Boolean = true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try { var rid:AutomationID = AutomationID.parse(objID); // we need to find out whether the current app and the // reuired app are the same. var requiredApplicationName:String = getApplicationNameFromAutomationID(rid); var currentApplicationName:String = getApplicationName(); if(requiredApplicationName == currentApplicationName) { if (fromTool == true) detailsSentToTool = true; var obj:IAutomationObject = automationManager.resolveIDToSingleObject(rid); var td:IAutomationTabularData = automationManager.getTabularData(obj); o.result = { columnTitles: td ? td.columnNames : [], tableData: (td ? td.getValues(begin, end) : [[]]) }; } else { // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(objID); details.push(begin); details.push(end); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.GET_TABULAR_DATA,details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to QTP o = requestResultObjArray[0] as Object; detailsSentToTool = true; } } } catch(e:Error) { throw e; } return o; }); } public function getTabularAttributes(objID:String, fromTool:Boolean = true):Object { return useErrorHandler(function():Object { var o:Object = { result:null, error:0 }; try { var rid:AutomationID = AutomationID.parse(objID); // we need to find out whether the current app and the // reuired app are the same. var requiredApplicationName:String = getApplicationNameFromAutomationID(rid); var currentApplicationName:String = getApplicationName(); if(requiredApplicationName == currentApplicationName) { if (fromTool == true) detailsSentToTool = true; var obj:IAutomationObject = automationManager.resolveIDToSingleObject(rid); var td:IAutomationTabularData = automationManager.getTabularData(obj); o.result = { minVisibleRow: td ? td.firstVisibleRow : [], maxVisibleRow: td ? td.lastVisibleRow : [], fullSize: td ? td.numRows : [] }; } else { // we need to send this as information to the other application // and let the appropriate application handle it. // #IMP: MARSHALLING NOTE#: This order of ariguments should not be changed // across versions. If any new arguements is needed in new versions // add them to the end of the list and handle appropriately in the // handler of this event. var details:Array = new Array(); details.push(objID); if(fromTool == true) { requestPending = false; resultRecieved = false; } o.result = handleRequestToDifferentApplication(requiredApplicationName, ToolMarshallingEvent.GET_TABULAR_ATTRIBUTES,details); if((resultRecieved == true)&&(fromTool == true)) { // since we have recieved the result, we can send the information back to QTP o = requestResultObjArray[0] as Object; detailsSentToTool = true; } } } catch(e:Error) { throw e; } return o; }); } /** * @private */ private function useErrorHandler(f:Function):Object { var o:Object = { result:null, error:0 }; try { o = f(); } catch (e:Error) { lastError = e; o.error = (e is AutomationError ? AutomationError(e).code : AutomationError.ILLEGAL_OPERATION); Automation.automationDebugTracer.traceMessage("ToolAdapter","setErrorHandler()",e.message); } return o; } /** * @private */ private function getDescriptionXML(rid:AutomationID, target:IAutomationObject):XML { var obj:IAutomationObject = target; var result:XML; while (obj) { var part:AutomationIDPart = rid.removeLast(); if (automationManager.showInHierarchy(obj) || target == obj) { var automationClass:String = automationManager.getAutomationClassName(obj); var automationName:String = part.automationName; //build description xml - probably could use the same methods //that learn and activescreen use, but those were added later //and this has been working so don't fix it var x:XML = (<Element type={automationClass} name={automationName}/>); for (var i:String in part) x.appendChild(<Property name={i} value={part[i] != null ? part[i] : ""}/>); if (result) x.appendChild(result); result = x; } obj = automationManager.getParent(obj); } return new XML(result); } /** * @private */ private function createPartFromFilterXML(filterXMLString:String):AutomationIDPart { var part:AutomationIDPart = new AutomationIDPart(); var filterXML:XML = new XML(filterXMLString); for (var o:Object in filterXML.Property) { var propertyNode:XML = filterXML.Property[o]; var name:String = propertyNode.@Name.toString(); var value:String = propertyNode.@Value.toString(); if(name.toLowerCase() == "automationname") name = "automationName"; else if(name.toLowerCase() == "automationindex") name = "automationIndex"; else if(name.toLowerCase() == "classname") name = "className"; else if(name.toLowerCase() == "id") name = "id"; if (propertyNode.@RegExp.toString() == "true") part[name] = new RegExp(value); else part[name] = value; } if (filterXML.@Type && filterXML.@Type.toString().length != 0) part["automationClassName"] = filterXML.@Type.toString(); return part; } /** * @private */ private function getActiveOrLearnXMLTree(objID:String, addChildren:Boolean, filterXML:String = "", addActiveInfo:Boolean = false, leftOffset:int = -1, topOffset:int = -1):Object { var rid:AutomationID = AutomationID.parse(objID); var activeAO:IAutomationObject = automationManager.resolveIDToSingleObject(rid); var rids:Array = addActiveInfo ? null : []; //add the current item var activeNode:XML = getActiveOrLearnScreenXML(rids, activeAO, true, addActiveInfo, leftOffset, topOffset); //add the children if (addChildren) getActiveOrLearnChildrenXML(rids, activeAO, filterXML, activeNode, addActiveInfo, leftOffset, topOffset); //add the parents var result:XML = getActiveOrLearnParentsXML(rids, automationManager.getParent(activeAO), activeNode, addActiveInfo, leftOffset, topOffset); // We are storing the actual pretty printing value so that we can // reset it back when we are done with our operation. // Ref: http://bugs.adobe.com/jira/browse/FLEXENT-1140 var actualPrettyPrinting:Boolean = XML.prettyPrinting; XML.prettyPrinting = false; var resultXMLString:String; var objectIdPart:AutomationIDPart = rid.removeFirst(); var windowId:String = automationManager.getAIRWindowUniqueIDFromAutomationIDPart(objectIdPart); // using the check to see if we are requesting activeScreen XML or learn XML // activeScreenXML requires the outermost element to contain the bounding rectangle // learn XML doesnot require this. // We are using activeWindow API in order to get the rectangle corresponding to // the active window instead of getting the top level application's always. // http://bugs.adobe.com/jira/browse/FLEXENT-1123 var appObj:Object = AutomationHelper.getActiveWindow(windowId); var rect:Array = automationManager.getRectangle(appObj as DisplayObject); if(leftOffset != -1) { var wrapper:XML = <Element> <Rectangle left={leftOffset} top={topOffset} right={leftOffset + rect[0] + appObj.screen.right} bottom = {topOffset + rect[1] + appObj.screen.bottom}/> </Element>; wrapper.appendChild(result); resultXMLString = String(wrapper.toXMLString()); } else resultXMLString = String(result.toXMLString()); XML.prettyPrinting = actualPrettyPrinting; return {learnChildrenXML: resultXMLString, childrenIDs: rids}; } /** * @private */ private function getActiveOrLearnParentsXML(rids:Array, currentAO:IAutomationObject, currentNode:XML = null, addActiveInfo:Boolean = false, leftOffset:int = -1, topOffset:int = -1):XML { while (currentAO != null) { var newNode:XML = getActiveOrLearnScreenXML(rids, currentAO, false, addActiveInfo, leftOffset, topOffset); newNode.appendChild(currentNode); currentNode = newNode; currentAO = automationManager.getParent(currentAO); } return currentNode; } /** * @private */ private function getActiveOrLearnChildrenXML(rids:Array, parentAO:IAutomationObject, filterXMLString:String, parentNode:XML, addActiveInfo:Boolean = false, leftOffset:int = -1, topOffset:int = -1):void { if (parentAO.numAutomationChildren == 0) return; //convert the XML filter to a part - note QTP hasn't implemented the filter part yet var part:AutomationIDPart = createPartFromFilterXML(filterXMLString); var children:Array = automationManager.getChildrenFromIDPart(parentAO, part); for (var i:int = 0; i < children.length; ++i) { var childAO:IAutomationObject = children[i]; //we probably can skip anything that doesn't show in the hieararchy //remove this if this assumption turns out to be untrue (but comment as to why) if (!automationManager.showInHierarchy(childAO)) continue; var childNode:XML = getActiveOrLearnScreenXML(rids, childAO, false, addActiveInfo, leftOffset, topOffset); parentNode.appendChild(childNode); getActiveOrLearnChildrenXML(rids, childAO, filterXMLString, childNode, false, leftOffset, topOffset); } } /** * @private * Prepares the XML description of the component along with bounding rectangle. * This function is used for active screen recording as well as returning information * for learning objects. * * @param leftOffset left coordinate of the player * * @param topOffset top coordinate of player */ private function getActiveOrLearnScreenXML(rids:Array, currentAO:IAutomationObject, isActiveAO:Boolean = false, addActiveInfo:Boolean = false, leftOffset:int = -1, topOffset:int= -1):XML { var automationClass:String = automationManager.getAutomationClassName(currentAO); var automationName:String = automationManager.getAutomationName(currentAO); if (rids != null) rids.push(automationManager.createID(currentAO).toString()); // build description xml var result:XML = (addActiveInfo ? (<Element type={automationClass} name={automationName} isActiveElement={isActiveAO}> </Element>) : (<Element type={automationClass} name={automationName} index={rids != null ? rids.length - 1 : 0}> </Element>) ); //add properties var values:Array = automationManager.getProperties(currentAO, null, addActiveInfo, true); var descriptors:Array = getPropertyDescriptors(currentAO, null, addActiveInfo, true); var properties:Array = encodeValues(currentAO, values, descriptors); for (var i:uint = 0; i < properties.length; i++) { var name:String = properties[i].descriptor.name; var value:String = properties[i].value != null ? properties[i].value : ""; var forDescription:Boolean = properties[i].descriptor.forDescription; var childXML:XML = (addActiveInfo ? <Property name={name} value={value} forDescription={forDescription}/> : <Property name={name} value={value}/>); result.appendChild(childXML); } //add screen coordinates if (addActiveInfo) { var rect:Array = automationManager.getRectangle(currentAO as DisplayObject); result.appendChild(<Rectangle left={leftOffset + rect[0]} top={topOffset + rect[1]} right={leftOffset + rect[2]} bottom={topOffset + rect[3]} />); } return result; } /** * @private * Converts Tool specific strings to proper values. */ private function convertArrayFromCrazyToAs(a:String):Array { var result:Array = a.split("__MX_ARG_SEP__"); for (var i:uint = 0; i < result.length; i++) { if (result[i] == "__MX_NULL__") result[i] = null; } return result; } /** * Decodes an array of properties from a testing tool into an AS object. * using the codecs. * * @param obj the object that contains the properties to be encoded. * * @param args the property values to transcode. * * @param propertyDescriptors the property descriptors that describes the properties for this object. * * @param relativeParent the IAutomationObject that is related to this object. * * @return the decoded property value. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 4 */ public function decodeProperties(obj:Object, args:Array, propertyDescriptors:Array, interactionReplayer:IAutomationObject):void { for (var i:int = 0; i < propertyDescriptors.length; i++) { var value:String = null; if (args != null && i < args.length && args[i] == "null" && propertyDescriptors[i].defaultValue == "null") args[i] = null; if (args != null && i < args.length && ((args[i] != null && args[i] != "") || propertyDescriptors[i].defaultValue == null)) setPropertyValue(obj, args[i], propertyDescriptors[i], interactionReplayer); else if (propertyDescriptors[i].defaultValue != null) setPropertyValue(obj, (propertyDescriptors[i].defaultValue == "null" ? null : propertyDescriptors[i].defaultValue), propertyDescriptors[i], interactionReplayer); else { var message:String = resourceManager.getString( "automation_agent", "missingArgument", [propertyDescriptors[i].name]); throw new Error(message); } } } /** * @private */ public function setPropertyValue(obj:Object, value:Object, pd:ToolPropertyDescriptor, relativeParent:IAutomationObject = null):void { var codec:IAutomationPropertyCodec = propertyCodecMap[pd.codecName]; if (codec == null) codec = propertyCodecMap["object"]; if (relativeParent == null) relativeParent = obj as IAutomationObject; codec.decode(automationManager, obj, value, pd, relativeParent); } /** * @private */ public static function getCodecHelper():IToolCodecHelper { return qtpCodecHelper; } public static function set applicationType( appType:int):void { _applicationType = appType; } public static function get applicationType():int { return _applicationType; } public static function set applicationId( appId:String):void { _applicationId = appId; } public static function get applicationId():String { return _applicationId; } /* // this will give the stage boundary for AIR apps. public static function getStageBoundaryInScreenCoords(applicationId:String):Rectangle { var stageBoundary:Rectangle; var stageHeight:int; var stageWidth:int; var allPropFound:Boolean= false; // get the application start cooridnate in screen points //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& var stageStartPointInScreenCoordinates:Point; // get the type of the application. if(_applicationType == ToolAdapter.ApplicationType_AIR) { var airFunctionHandler:Class = null; try { allPropFound = true; airFunctionHandler = getAirFunctionHelperClass("stageHeight,stageWidth,stageStartCoordinates"); if(airFunctionHandler) { var obj:Object = new airFunctionHandler(applicationId); if(obj.hasOwnProperty("stageStartCoordinates")) stageStartPointInScreenCoordinates = obj["stageStartCoordinates"]; else allPropFound = false; if(obj.hasOwnProperty("stageWidth")) stageWidth = obj["stageWidth"]; else allPropFound = false; if(obj.hasOwnProperty("stageHeight")) stageHeight = obj["stageHeight"]; else allPropFound = false; } } catch(e:Error) { trace("stageHeight,stageWidth, stageStartCoordinates - In AIR we are supposed to have class 'mx.automation.air.AirFunctionsHelper'."); // TBD. Converting this as user message and adding this in the locales. } if(allPropFound == false) { trace("stageHeight - In AIR we are supposed to have class 'mx.automation.air.AirFunctionsHelper' with stageHeight,stageWidth, stageStartCoordinates as properties."); // TBD. Converting this as user message and adding this in the locales. } } else // we are in flex app { // get the application start coordinate from the browsers //stageStartPointInScreenCoordinates = ExternalInterfaceMethods_AS.getApplicationStartPointInScreenCoordinates(_applicationId); stageHeight = Application.application.height; stageWidth = Application.application.width; stageStartPointInScreenCoordinates = new Point(0, 0); //stageStartPointInScreenCoordinates = (Automation.automationManager2 as IAutomationManager2).getStartPoint(); } //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& if(stageStartPointInScreenCoordinates) { // get the application boudary Array in screen cooridnates. stageBoundary = new Rectangle(stageStartPointInScreenCoordinates.x, stageStartPointInScreenCoordinates.y, stageWidth, stageHeight); } return stageBoundary; } */ public static function getStageStartPointInScreenCoords(windowId:String ):Point { var stageStartPoint:Point = new Point(0,0) try { stageStartPoint = AutomationHelper.getStageStartPointInScreenCoords(windowId); } catch(e:Error) { showAirHelperNotFoundMessage(); Automation.automationDebugTracer.traceMessage("ToolAdapter","stageStartCoordinates()", AutomationConstants.missingAIRClass); } return stageStartPoint; } public function convertScreenPointToStagePoint(screenPoint:Point, applicationId:String):Point { var stageStartPoint:Point = getStageStartPointInScreenCoords(applicationId) var stagePoint:Point; // convert the point to app cooridnates stagePoint = new Point(screenPoint.x-stageStartPoint.x, screenPoint.y-stageStartPoint.y); return stagePoint; } public function getAppTitle():String { var title:String = ""; try { title = AutomationHelper.getAppTitle(); } catch(e:Error) { showAirHelperNotFoundMessage(); Automation.automationDebugTracer.traceMessage("ToolAdapter","appTitle()", AutomationConstants.missingAIRClass); // TBD. Converting this as user message and adding this in the locales. } return title; } /*public function getChromeHeight():int { var chromeHeight:int = 0; // default for flex = 0; var allPropFound:Boolean= false; // get the type of the application. if(_applicationType == ToolAdapter.ApplicationType_AIR) { var airFunctionHandler:Class = null; try { airFunctionHandler = getAirFunctionHelperClass("chromeHeight"); if(airFunctionHandler) { var obj:Object = new airFunctionHandler(null); if(obj.hasOwnProperty("chromeHeight")) { chromeHeight = obj["chromeHeight"]; allPropFound = true; } } } catch(e:Error) { trace("chromeHeight - In AIR we are supposed to have class 'mx.automation.air.AirFunctionsHelper'."); // TBD. Converting this as user message and adding this in the locales. } if(allPropFound == false) { trace("chromeHeight - In AIR we are supposed to have class 'mx.automation.air.AirFunctionsHelper' with chromeHeight property."); // TBD. Converting this as user message and adding this in the locales. } } return chromeHeight; } private static var classLoadingFailed:Boolean = false; public function isAirClassLoaded():Boolean { return !classLoadingFailed; } private static function getAirFunctionHelperClass(prpertyName:String):Class { if(!classLoadingFailed) { try { return Class(getDefinitionByName("mx.automation.air.AirFunctionsHelper")); } catch (e:Error) { var message:String = showAirHelperNotFoundMessage(); classLoadingFailed = true; throw new Error(message); } } return null; } public function getChromeWidth():int { var chromeWidth:int = 0; // default for flex = 0; var allPropFound:Boolean= false; // get the type of the application. if(_applicationType == ToolAdapter.ApplicationType_AIR) { var airFunctionHandler:Class = null; try { airFunctionHandler = getAirFunctionHelperClass("chromeWidth"); if(airFunctionHandler) { var obj:Object = new airFunctionHandler(null); if(obj.hasOwnProperty("chromeWidth")) { chromeWidth = obj["chromeWidth"]; allPropFound = true; } } } catch(e:Error) { trace("chromeWidth - In AIR we are supposed to have class 'mx.automation.air.AirFunctionsHelper'."); // TBD. Converting this as user message and adding this in the locales. } if(allPropFound == false) { trace("chromeWidth - - In AIR we are supposed to have class 'mx.automation.air.AirFunctionsHelper' with chromeWidth property."); // TBD. Converting this as user message and adding this in the locales. } } return chromeWidth; }*/ private function getApplicationName():String { return automationManager.getUniqueApplicationID(); } private function getApplicationNameFromObjectIDString(objectID:String):String { var rid:AutomationID = AutomationID.parse(objectID); return getApplicationNameFromAutomationID(rid); } private function getApplicationNameFromAutomationID(objectID:AutomationID):String { // clone the automationID var rid:AutomationID = objectID.clone(); //remove the application var part:AutomationIDPart = rid.removeFirst(); return automationManager.getApplicationNameFromAutomationIDPart (part); /* // check whether the current class is an AIR window as it is the another object // which can be the first level // we have added a property by name 'applicationName' which is applicable only // for the top level windows for AIR if (part.hasOwnProperty("applicationName")) return (part["applicationName"].toString()); // if we reach here we are not the AIR top level window // hence we can use the automationName to get the automation class name return (part["automationName"].toString()); */ } public function dispatchMarshalledEvent(type:String, applicationName:String , details1:Array):void { // This method is called to send all events from the root Automation Manager to the sub applicaitons. // we need to store the information that the we have sent the information and we are waiting // for the reply lastApplicationName = applicationName; lastRequestName = type; requestPending = true; var marshalledEvent:ToolMarshallingEvent = new ToolMarshallingEvent(type); marshalledEvent.applicationName = applicationName; marshalledEvent.interAppDataToSubApp = details1; dispatchEventToChildren(marshalledEvent); } public function dispatchMarshalledReplyEvent(type:String, applicationName:String , details:Array):void { var marshalledEvent:ToolMarshallingEvent = new ToolMarshallingEvent(type); marshalledEvent.applicationName = applicationName; marshalledEvent.interAppDataToMainApp = details; dispatchEventToParent(marshalledEvent); } private function dispatchEventToParent(event:Event):void { automationManager.dispatchToParent(event); } private function dispatchEventToChildren(event:Event):void { automationManager.dispatchToAllChildren(event); } private function handleRequestToDifferentApplication(requiredApplicationName:String, requestType:String , details:Array):Array { // clear the result object array so that we have only the result of the // current request requestResultObjArray = new Array(); dispatchMarshalledEvent( requestType,requiredApplicationName,details ); return null; } /** * @private */ private var lastResponseRecievedApplicationName:String; /** * @private */ private var inReplySendingToParent:Boolean = false; private function interAppReplyHandler(eventObj:Event) :void { // Marshalling events are needeed across applicaiton domain // so this conversion shall fail in the same domain // i.e the above check is to avoid the echoing if(eventObj is ToolMarshallingEvent) return; if(inReplySendingToParent) return; // if we are not the root application we need not handle the reply, just pass it to the parent //if(smMSm && (smMSm.useSWFBridge() == true)) if(sm.isTopLevelRoot() == false) { inReplySendingToParent = true; var eventObj1:ToolMarshallingEvent = ToolMarshallingEvent.marshal(eventObj); dispatchEventToParent(eventObj1); inReplySendingToParent = false; } else { // we got the last event details resultRecieved = true; // this handler happens in the root application // so we need to find out which was the application last responded to the last request // we need this information to get the last error. // the only case where we recieve reply from a non relevant application also // is for the getElementFromPoint. However for this case, we dont expect // a last error. and the final handling of the getElement from happens in the // main application, hence we will handle this variable appropriately in that // method separately. lastResponseRecievedApplicationName = (eventObj["applicationName"]); // we need a special handling if the event was // get element from point as we expect results from different applicaiton // so we need to add them to the array instead of storing in the result object. if(eventObj.type == ToolMarshallingEvent.GET_ELEMENT_FROM_POINT_REPLY) { // dont assign the value to the array, instead add to the array requestResultObjArray.push(eventObj["interAppDataToMainApp"][0]); } else requestResultObjArray= (eventObj["interAppDataToMainApp"]); } } private var inRequestSendingToChildren:Boolean = false; /** * @private */ private function interAppRequestHandler(eventObj:Event) :void { // Marshalling events are needeed across applicaiton domain // so this conversion shall fail in the same domain // i.e the above check is to avoid the echoing if(eventObj is ToolMarshallingEvent) return; if(inRequestSendingToChildren) return; var appName:String = getApplicationName(); var details:Array = new Array(); var type:String; var resultObj:Object; var objectID:String; var filterXML:String; if((eventObj["applicationName"] == appName)||(eventObj["applicationName"] == null)) { var dispatchEvent:Boolean = true; if(eventObj.type == ToolMarshallingEvent.FIND_OBJECTIDS) { var descriptionXML:String = eventObj["interAppDataToSubApp"][0] as String; resultObj = findObjectIDs(descriptionXML, false)["result"]; details.push(resultObj); type = ToolMarshallingEvent.FIND_OBJECTIDS_REPLY; } else if (eventObj.type == ToolMarshallingEvent.RUN) { //run(objID:String, method:String, args:String):Object objectID = eventObj["interAppDataToSubApp"][0]; var method:String = eventObj["interAppDataToSubApp"][1]; var args:String = eventObj["interAppDataToSubApp"][2]; resultObj = run(objectID,method,args,false); details.push(resultObj); type = ToolMarshallingEvent.RUN_REPLY; } else if (eventObj.type == ToolMarshallingEvent.GET_ACTIVESCREEN) { //run(objID:String, method:String, args:String):Object var level:int = eventObj["interAppDataToSubApp"][0]; objectID = eventObj["interAppDataToSubApp"][1]; var leftOffset:int = eventObj["interAppDataToSubApp"][2]; var topOffset:int = eventObj["interAppDataToSubApp"][3]; resultObj = getActiveScreen(level,objectID,leftOffset,topOffset,false); details.push(resultObj); type = ToolMarshallingEvent.GET_ACTIVESCREEN_REPLY; } else if (eventObj.type == ToolMarshallingEvent.GET_PARENT) { objectID = eventObj["interAppDataToSubApp"][0]; resultObj = getParent(objectID,false); details.push(resultObj); type = ToolMarshallingEvent.GET_RECTANGLE_REPLY; } else if (eventObj.type == ToolMarshallingEvent.GET_RECTANGLE) { objectID = eventObj["interAppDataToSubApp"][0]; resultObj = getRectangle(objectID,false); details.push(resultObj); type = ToolMarshallingEvent.GET_RECTANGLE_REPLY; } else if (eventObj.type == ToolMarshallingEvent.GET_ELEMENT_FROM_POINT) { var x:int = eventObj["interAppDataToSubApp"][0]; var y:int = eventObj["interAppDataToSubApp"][1]; var appId:String = eventObj["interAppDataToSubApp"][2] as String; resultObj = getElementFromPoint(x,y,appId,false); if((resultObj["result"] == "" )||(resultObj["result"] == null)) dispatchEvent = false; else { details.push(resultObj); type = ToolMarshallingEvent.GET_ELEMENT_FROM_POINT_REPLY; } } else if (eventObj.type == ToolMarshallingEvent.GET_ELEMENT_TYPE) { objectID = eventObj["interAppDataToSubApp"][0]; resultObj = getElementType(objectID,false); details.push(resultObj); type = ToolMarshallingEvent.GET_ELEMENT_TYPE_REPLY; } else if (eventObj.type == ToolMarshallingEvent.GET_DISPLAY_NAME) { objectID = eventObj["interAppDataToSubApp"][0]; resultObj = getDisplayName(objectID,false); details.push(resultObj); type = ToolMarshallingEvent.GET_DISPLAY_NAME_REPLY; } else if (eventObj.type == ToolMarshallingEvent.GET_PROPERTIES) { objectID = eventObj["interAppDataToSubApp"][0]; var names:String = eventObj["interAppDataToSubApp"][1]; resultObj = getProperties(objectID,names,false); details.push(resultObj); type = ToolMarshallingEvent.GET_PROPERTIES_REPLY; } else if (eventObj.type == ToolMarshallingEvent.BUILD_DESCRIPTION) { objectID = eventObj["interAppDataToSubApp"][0]; resultObj = buildDescription(objectID,false); details.push(resultObj); type = ToolMarshallingEvent.BUILD_DESCRIPTION_REPLY; } else if (eventObj.type == ToolMarshallingEvent.GET_CHILDREN) { objectID = eventObj["interAppDataToSubApp"][0]; filterXML = eventObj["interAppDataToSubApp"][1]; resultObj = getChildren(objectID,filterXML,false); details.push(resultObj); type = ToolMarshallingEvent.GET_CHILDREN_REPLY; } else if (eventObj.type == ToolMarshallingEvent.LEARN_CHILD_OBJECTS) { objectID = eventObj["interAppDataToSubApp"][0]; var filterXML1:String = eventObj["interAppDataToSubApp"][1]; resultObj = learnChildObjects(objectID,filterXML1,false); details.push(resultObj); type = ToolMarshallingEvent.LEARN_CHILD_OBJECTS_REPLY; } else if (eventObj.type == ToolMarshallingEvent.GET_LAST_ERROR) { resultObj = getLastError(false); details.push(resultObj); type = ToolMarshallingEvent.GET_LAST_ERROR_REPLY; } else if (eventObj.type == ToolMarshallingEvent.SET_LAST_ERROR) { var message:String = eventObj["interAppDataToSubApp"][0]; setLastError(message,false); dispatchEvent = false; // there is no reply for the setLast error } else if (eventObj.type == ToolMarshallingEvent.GET_TABULAR_ATTRIBUTES) { objectID = eventObj["interAppDataToSubApp"][0]; resultObj = getTabularAttributes(objectID,false); details.push(resultObj); type = ToolMarshallingEvent.GET_TABULAR_ATTRIBUTES_REPLY; } else if (eventObj.type == ToolMarshallingEvent.GET_TABULAR_DATA) { objectID = eventObj["interAppDataToSubApp"][0]; var begin:int = eventObj["interAppDataToSubApp"][1]; var end:int = eventObj["interAppDataToSubApp"][2]; resultObj = getTabularData(objectID,begin,end,false); details.push(resultObj); type = ToolMarshallingEvent.GET_TABULAR_DATA_REPLY; } if (dispatchEvent == true) dispatchMarshalledReplyEvent(type,appName,details); if(eventObj.type == ToolMarshallingEvent.GET_ELEMENT_FROM_POINT) { inRequestSendingToChildren = true; var eventObj1:ToolMarshallingEvent = ToolMarshallingEvent.marshal(eventObj); dispatchEventToChildren(eventObj1); inRequestSendingToChildren = false; } } else { inRequestSendingToChildren = true; var eventObj2:ToolMarshallingEvent = ToolMarshallingEvent.marshal(eventObj); dispatchEventToChildren(eventObj2); inRequestSendingToChildren = false; } } private function newWindowHandler(event:AutomationAirEvent):void { // we need to inform the socket handler to communicate to the plugin // to get the hwnd for this new window. if(ToolAgent.clientSocketHandler) (ToolAgent.clientSocketHandler).processNewWindowInformation(event.windowId); } private static var connectionAttemptAlert:Alert; private static var successMessageAlert:Alert; public static function showConnectionAttemptMessage():String { var message:String = resourceManager.getString("tool_air","qtpConnectionAttempt"); connectionAttemptAlert = Alert.show( message); return message; } public static function showConnectionSuccessMessage():String { if(connectionAttemptAlert) PopUpManager.removePopUp(connectionAttemptAlert); var message:String = resourceManager.getString("tool_air","qtpConnectionSuccess"); successMessageAlert = Alert.show(message); removeSuccessMessageAlert(); // let us close this return message; } // we need only one type of error message. private static var errorMessageDisplayed:Boolean = false; public static function showioErrorMessage(eventString:String):String { if(connectionAttemptAlert) PopUpManager.removePopUp(connectionAttemptAlert); var message :String = resourceManager.getString( "tool_air", "noConnectionToTool"); message = message + "\n" + resourceManager.getString( "tool_air", "noConnectionToTool_Recommendation"); if(!errorMessageDisplayed) Alert.show(message); errorMessageDisplayed = true; return message; } public static function showSecurityErrorMessage(eventString:String):String { if(connectionAttemptAlert) PopUpManager.removePopUp(connectionAttemptAlert); var message :String = resourceManager.getString( "tool_air", "securityError"); message = message + "\n" + "\n"; message = message + "securityErrorHandler: " + eventString; //trace (message); if(!errorMessageDisplayed) Alert.show(message); errorMessageDisplayed = true; return message; } public static function showConnectionFailureMessage():String { if(connectionAttemptAlert) PopUpManager.removePopUp(connectionAttemptAlert); // we wait for 3000 milliseconds 3 times to check whether we // could connect to QTP. var message:String = resourceManager.getString("tool_air","qtpConnectionFailed"); if(!errorMessageDisplayed) Alert.show(message); errorMessageDisplayed = true; ClientSocketHandler.enableApplication(); return message; } public static function showAirHelperNotFoundMessage():String { if(connectionAttemptAlert) PopUpManager.removePopUp(connectionAttemptAlert); var message:String = resourceManager.getString("tool_air", "airHelperClassNotFound"); if(!errorMessageDisplayed) Alert.show(message); errorMessageDisplayed = true; return message; } public static function removeSuccessMessageAlert():void { var tempTimer:Timer = new Timer(3000,1); tempTimer.addEventListener(TimerEvent.TIMER,removeSuccessMessageAlertTimerHandler); tempTimer.start(); } public static function removeSuccessMessageAlertTimerHandler(event:Event):void { if(successMessageAlert) PopUpManager.removePopUp(successMessageAlert); } } }
package org.as3.serializer.enums { /** * * Enumarations used over the serialization * * @author Mario Vieira * */ public class SerializerEnums { public function SerializerEnums(){} public static const S_ERIALIZE:String = 'Serialize'; public static const SERIALIZER:String = 'serializer'; //xml element names for an object properties (vars or accessor pairs) returned by the global member describeType(object:Object):XML public static const VARIABLE:String = 'variable'; public static const ACCESSOR:String = 'accessor'; public static const ITERATIVE:String = 'iterative'; //to check if the iterative item is IList public static const ADD_ITEM:String = 'addItem'; //to cast bolleans check public static const FALSE:String = 'false'; public static const XML_VERSION:String = '<?xml version="1.0"?>\n'; } }
package laya.ui { import laya.events.Event; import laya.utils.Handler; /** * 实例的 <code>selectedIndex</code> 属性发生变化时调度。 * @eventType laya.events.Event */ [Event(name = "change", type = "laya.events.Event")] /** * 节点打开关闭时触发。 * @eventType laya.events.Event */ [Event(name = "open", type = "laya.events.Event")] /** * <code>Tree</code> 控件使用户可以查看排列为可扩展树的层次结构数据。 * * @example * package * { * import laya.ui.Tree; * import laya.utils.Browser; * import laya.utils.Handler; * public class Tree_Example * { * public function Tree_Example() * { * Laya.init(640, 800); * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/vscroll.png", "resource/ui/vscroll$bar.png", "resource/ui/vscroll$down.png", "resource/ui/vscroll$up.png", "resource/ui/clip_selectBox.png", "resource/ui/clip_tree_folder.png", "resource/ui/clip_tree_arrow.png"], Handler.create(this, onLoadComplete)); * } * private function onLoadComplete():void * { * var xmlString:String;//创建一个xml字符串,用于存储树结构数据。 * xmlString = "&lt;root&gt;&lt;item label='box1'&gt;&lt;abc label='child1'/&gt;&lt;abc label='child2'/&gt;&lt;abc label='child3'/&gt;&lt;abc label='child4'/&gt;&lt;abc label='child5'/&gt;&lt;/item&gt;&lt;item label='box2'&gt;&lt;abc label='child1'/&gt;&lt;abc label='child2'/&gt;&lt;abc label='child3'/&gt;&lt;abc label='child4'/&gt;&lt;/item&gt;&lt;/root&gt;"; * var domParser:* = new Browser.window.DOMParser();//创建一个DOMParser实例domParser。 * var xml:* = domParser.parseFromString(xmlString, "text/xml");//解析xml字符。 * var tree:Tree = new Tree();//创建一个 Tree 类的实例对象 tree 。 * tree.scrollBarSkin = "resource/ui/vscroll.png";//设置 tree 的皮肤。 * tree.itemRender = Item;//设置 tree 的项渲染器。 * tree.xml = xml;//设置 tree 的树结构数据。 * tree.x = 100;//设置 tree 对象的属性 x 的值,用于控制 tree 对象的显示位置。 * tree.y = 100;//设置 tree 对象的属性 y 的值,用于控制 tree 对象的显示位置。 * tree.width = 200;//设置 tree 的宽度。 * tree.height = 100;//设置 tree 的高度。 * Laya.stage.addChild(tree);//将 tree 添加到显示列表。 * } * } * } * import laya.ui.Box; * import laya.ui.Clip; * import laya.ui.Label; * class Item extends Box * { * public function Item() * { * this.name = "render"; * this.right = 0; * this.left = 0; * var selectBox:Clip = new Clip("resource/ui/clip_selectBox.png", 1, 2); * selectBox.name = "selectBox"; * selectBox.height = 24; * selectBox.x = 13; * selectBox.y = 0; * selectBox.left = 12; * addChild(selectBox); * var folder:Clip = new Clip("resource/ui/clip_tree_folder.png", 1, 3); * folder.name = "folder"; * folder.x = 14; * folder.y = 4; * addChild(folder); * var label:Label = new Label("treeItem"); * label.name = "label"; * label.color = "#ffff00"; * label.width = 150; * label.height = 22; * label.x = 33; * label.y = 1; * label.left = 33; * label.right = 0; * addChild(label); * var arrow:Clip = new Clip("resource/ui/clip_tree_arrow.png", 1, 2); * arrow.name = "arrow"; * arrow.x = 0; * arrow.y = 5; * addChild(arrow); * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高、渲染模式 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * var res = ["resource/ui/vscroll.png", "resource/ui/vscroll$bar.png", "resource/ui/vscroll$down.png", "resource/ui/vscroll$up.png", "resource/ui/clip_selectBox.png", "resource/ui/clip_tree_folder.png", "resource/ui/clip_tree_arrow.png"]; * Laya.loader.load(res, new laya.utils.Handler(this, onLoadComplete)); * function onLoadComplete() { * var xmlString;//创建一个xml字符串,用于存储树结构数据。 * xmlString = "&lt;root&gt;&lt;item label='box1'&gt;&lt;abc label='child1'/&gt;&lt;abc label='child2'/&gt;&lt;abc label='child3'/&gt;&lt;abc label='child4'/&gt;&lt;abc label='child5'/&gt;&lt;/item&gt;&lt;item label='box2'&gt;&lt;abc label='child1'/&gt;&lt;abc label='child2'/&gt;&lt;abc label='child3'/&gt;&lt;abc label='child4'/&gt;&lt;/item&gt;&lt;/root&gt;"; * var domParser = new laya.utils.Browser.window.DOMParser();//创建一个DOMParser实例domParser。 * var xml = domParser.parseFromString(xmlString, "text/xml");//解析xml字符。 * var tree = new laya.ui.Tree();//创建一个 Tree 类的实例对象 tree 。 * tree.scrollBarSkin = "resource/ui/vscroll.png";//设置 tree 的皮肤。 * tree.itemRender = mypackage.treeExample.Item;//设置 tree 的项渲染器。 * tree.xml = xml;//设置 tree 的树结构数据。 * tree.x = 100;//设置 tree 对象的属性 x 的值,用于控制 tree 对象的显示位置。 * tree.y = 100;//设置 tree 对象的属性 y 的值,用于控制 tree 对象的显示位置。 * tree.width = 200;//设置 tree 的宽度。 * tree.height = 100;//设置 tree 的高度。 * Laya.stage.addChild(tree);//将 tree 添加到显示列表。 * } * (function (_super) { * function Item() { * Item.__super.call(this);//初始化父类。 * this.right = 0; * this.left = 0; * var selectBox = new laya.ui.Clip("resource/ui/clip_selectBox.png", 1, 2); * selectBox.name = "selectBox";//设置 selectBox 的name 为“selectBox”时,将被识别为树结构的项的背景。2帧:悬停时背景、选中时背景。 * selectBox.height = 24; * selectBox.x = 13; * selectBox.y = 0; * selectBox.left = 12; * this.addChild(selectBox);//需要使用this.访问父类的属性或方法。 * var folder = new laya.ui.Clip("resource/ui/clip_tree_folder.png", 1, 3); * folder.name = "folder";//设置 folder 的name 为“folder”时,将被识别为树结构的文件夹开启状态图表。2帧:折叠状态、打开状态。 * folder.x = 14; * folder.y = 4; * this.addChild(folder); * var label = new laya.ui.Label("treeItem"); * label.name = "label";//设置 label 的name 为“label”时,此值将用于树结构数据赋值。 * label.color = "#ffff00"; * label.width = 150; * label.height = 22; * label.x = 33; * label.y = 1; * label.left = 33; * label.right = 0; * this.addChild(label); * var arrow = new laya.ui.Clip("resource/ui/clip_tree_arrow.png", 1, 2); * arrow.name = "arrow";//设置 arrow 的name 为“arrow”时,将被识别为树结构的文件夹开启状态图表。2帧:折叠状态、打开状态。 * arrow.x = 0; * arrow.y = 5; * this.addChild(arrow); * }; * Laya.class(Item,"mypackage.treeExample.Item",_super);//注册类 Item 。 * })(laya.ui.Box); * @example * import Tree = laya.ui.Tree; * import Browser = laya.utils.Browser; * import Handler = laya.utils.Handler; * class Tree_Example { * constructor() { * Laya.init(640, 800); * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/vscroll.png", "resource/ui/vscroll$bar.png", "resource/ui/vscroll$down.png", "resource/ui/vscroll$up.png", "resource/ui/vscroll$up.png", "resource/ui/clip_selectBox.png", "resource/ui/clip_tree_folder * . * png", "resource/ui/clip_tree_arrow.png"], Handler.create(this, this.onLoadComplete)); * } * private onLoadComplete(): void { * var xmlString: String;//创建一个xml字符串,用于存储树结构数据。 * xmlString = "&lt;root&gt;&lt;item label='box1'&gt;&lt;abc label='child1'/&gt;&lt;abc label='child2'/&gt;&lt;abc label='child3'/&gt;&lt;abc label='child4'/&gt;&lt;abc label='child5'/&gt;&lt;/item&gt;&lt;item label='box2'&gt;&lt;abc * label='child1'/&gt;&lt;abc label='child2'/&gt;&lt;abc label='child3'/&gt;&lt;abc label='child4'/&gt;&lt;/item&gt;&lt;/root&gt;"; * var domParser: any = new Browser.window.DOMParser();//创建一个DOMParser实例domParser。 * var xml: any = domParser.parseFromString(xmlString, "text/xml");//解析xml字符。 * var tree: Tree = new Tree();//创建一个 Tree 类的实例对象 tree 。 * tree.scrollBarSkin = "resource/ui/vscroll.png";//设置 tree 的皮肤。 * tree.itemRender = Item;//设置 tree 的项渲染器。 * tree.xml = xml;//设置 tree 的树结构数据。 * tree.x = 100;//设置 tree 对象的属性 x 的值,用于控制 tree 对象的显示位置。 * tree.y = 100;//设置 tree 对象的属性 y 的值,用于控制 tree 对象的显示位置。 * tree.width = 200;//设置 tree 的宽度。 * tree.height = 100;//设置 tree 的高度。 * Laya.stage.addChild(tree);//将 tree 添加到显示列表。 * } * } * import Box = laya.ui.Box; * import Clip = laya.ui.Clip; * import Label = laya.ui.Label; * class Item extends Box { * constructor() { * super(); * this.name = "render"; * this.right = 0; * this.left = 0; * var selectBox: Clip = new Clip("resource/ui/clip_selectBox.png", 1, 2); * selectBox.name = "selectBox"; * selectBox.height = 24; * selectBox.x = 13; * selectBox.y = 0; * selectBox.left = 12; * this.addChild(selectBox); * var folder: Clip = new Clip("resource/ui/clip_tree_folder.png", 1, 3); * folder.name = "folder"; * folder.x = 14; * folder.y = 4; * this.addChild(folder); * var label: Label = new Label("treeItem"); * label.name = "label"; * label.color = "#ffff00"; * label.width = 150; * label.height = 22; * label.x = 33; * label.y = 1; * label.left = 33; * label.right = 0; * this.addChild(label); * var arrow: Clip = new Clip("resource/ui/clip_tree_arrow.png", 1, 2); * arrow.name = "arrow"; * arrow.x = 0; * arrow.y = 5; * this.addChild(arrow); * } * } */ public class Tree extends Box implements IRender { /**@private */ protected var _list:List; /**@private */ protected var _source:Array; /**@private */ protected var _renderHandler:Handler; /**@private */ protected var _spaceLeft:Number = 10; /**@private */ protected var _spaceBottom:Number = 0; /**@private */ protected var _keepStatus:Boolean = true; /** * 创建一个新的 <code>Tree</code> 类实例。 * <p>在 <code>Tree</code> 构造函数中设置属性width、height的值都为200。</p> */ public function Tree() { width = height = 200; } /**@inheritDoc */ override public function destroy(destroyChild:Boolean = true):void { super.destroy(destroyChild); _list && _list.destroy(destroyChild); _list = null; _source = null; _renderHandler = null; } /**@inheritDoc */ override protected function createChildren():void { addChild(_list = new List()); _list.renderHandler = Handler.create(this, renderItem, null, false); _list.repeatX = 1; _list.on(Event.CHANGE, this, onListChange); } /** * @private * 此对象包含的<code>List</code>实例的<code>Event.CHANGE</code>事件侦听处理函数。 */ protected function onListChange(e:Event=null):void { event(Event.CHANGE); } /** * 数据源发生变化后,是否保持之前打开状态,默认为true。 * <p><b>取值:</b> * <li>true:保持之前打开状态。</li> * <li>false:不保持之前打开状态。</li> * </p> */ public function get keepStatus():Boolean { return _keepStatus; } public function set keepStatus(value:Boolean):void { _keepStatus = value; } /** * 列表数据源,只包含当前可视节点数据。 */ public function get array():Array { return _list.array; } public function set array(value:Array):void { if (_keepStatus && _list.array && value) { parseOpenStatus(_list.array, value); } _source = value; _list.array = getArray(); } /** * 数据源,全部节点数据。 */ public function get source():Array { return _source; } /** * 此对象包含的<code>List</code>实例对象。 */ public function get list():List { return _list; } /** * 此对象包含的<code>List</code>实例的单元格渲染器。 * <p><b>取值:</b> * <ol> * <li>单元格类对象。</li> * <li> UI 的 JSON 描述。</li> * </ol></p> */ public function get itemRender():* { return _list.itemRender; } public function set itemRender(value:*):void { _list.itemRender = value; } /** * 滚动条皮肤。 */ public function get scrollBarSkin():String { return _list.vScrollBarSkin; } public function set scrollBarSkin(value:String):void { _list.vScrollBarSkin = value; } /**滚动条*/ public function get scrollBar():ScrollBar { return _list.scrollBar; } /** * 单元格鼠标事件处理器。 * <p>默认返回参数(e:Event,index:int)。</p> */ public function get mouseHandler():Handler { return _list.mouseHandler; } public function set mouseHandler(value:Handler):void { _list.mouseHandler = value; } /** * <code>Tree</code> 实例的渲染处理器。 */ public function get renderHandler():Handler { return _renderHandler; } public function set renderHandler(value:Handler):void { _renderHandler = value; } /** * 左侧缩进距离(以像素为单位)。 */ public function get spaceLeft():Number { return _spaceLeft; } public function set spaceLeft(value:Number):void { _spaceLeft = value; } /** * 每一项之间的间隔距离(以像素为单位)。 */ public function get spaceBottom():Number { return _list.spaceY; } public function set spaceBottom(value:Number):void { _list.spaceY = value; } /** * 表示当前选择的项索引。 */ public function get selectedIndex():int { return _list.selectedIndex; } public function set selectedIndex(value:int):void { _list.selectedIndex = value; } /** * 当前选中的项对象的数据源。 */ public function get selectedItem():Object { return _list.selectedItem; } public function set selectedItem(value:Object):void { _list.selectedItem = value; } /** * @inheritDoc */ override public function set width(value:Number):void { super.width = value; _list.width = value; } /**@inheritDoc */ override public function set height(value:Number):void { super.height = value; _list.height = value; } /** * @private * 获取数据源集合。 */ protected function getArray():Array { var arr:Array = []; for each (var item:Object in _source) { if (getParentOpenStatus(item)) { item.x = _spaceLeft * getDepth(item); arr.push(item); } } return arr; } /** * @private * 获取项对象的深度。 */ protected function getDepth(item:Object, num:int = 0):int { if (item.nodeParent == null) return num; else return getDepth(item.nodeParent, num + 1); } /** * @private * 获取项对象的上一级的打开状态。 */ protected function getParentOpenStatus(item:Object):Boolean { var parent:Object = item.nodeParent; if (parent == null) { return true; } else { if (parent.isOpen) { if (parent.nodeParent != null) return getParentOpenStatus(parent); else return true; } else { return false; } } } /** * @private * 渲染一个项对象。 * @param cell 一个项对象。 * @param index 项的索引。 */ protected function renderItem(cell:Box, index:int):void { var item:Object = cell.dataSource; if (item) { cell.left = item.x; var arrow:Clip = cell.getChildByName("arrow") as Clip; if (arrow) { if (item.hasChild) { arrow.visible = true; arrow.index = item.isOpen ? 1 : 0; arrow.tag = index; arrow.off(Event.CLICK, this, onArrowClick); arrow.on(Event.CLICK, this, onArrowClick); } else { arrow.visible = false; } } var folder:Clip = cell.getChildByName("folder") as Clip; if (folder) { if (folder.clipY == 2) { folder.index = item.isDirectory ? 0 : 1; } else { folder.index = item.isDirectory ? item.isOpen ? 1 : 0 : 2; } } _renderHandler && _renderHandler.runWith([cell, index]); } } /** * @private */ private function onArrowClick(e:Event):void { var arrow:Clip = e.currentTarget as Clip; var index:int = arrow.tag; _list.array[index].isOpen = !_list.array[index].isOpen; event(Event.OPEN); _list.array = getArray(); } /** * 设置指定项索引的项对象的打开状态。 * @param index 项索引。 * @param isOpen 是否处于打开状态。 */ public function setItemState(index:int, isOpen:Boolean):void { if (!_list.array[index]) return; _list.array[index].isOpen = isOpen; _list.array = getArray(); } /** * 刷新项列表。 */ public function fresh():void { _list.array = getArray(); repaint(); } /**@inheritDoc */ override public function set dataSource(value:*):void { _dataSource = value; //if (value is XmlDom) xml = value as XmlDom; super.dataSource = value; } /** * xml结构的数据源。 */ public function set xml(value:XmlDom):void { var arr:Array = []; parseXml(value.childNodes[0], arr, null, true); array = arr; } /** * @private * 解析并处理XML类型的数据源。 */ protected function parseXml(xml:XmlDom, source:Array, nodeParent:Object, isRoot:Boolean):void { var obj:Object; var list:Array = xml.childNodes; var childCount:int = list.length; if (!isRoot) { obj = {}; var list2:Object = xml.attributes; for each (var attrs:XmlDom in list2) { var prop:String = attrs.nodeName; var value:String = attrs.nodeValue; obj[prop] = value == "true" ? true : value == "false" ? false : value; } obj.nodeParent = nodeParent; if (childCount > 0) obj.isDirectory = true; obj.hasChild = childCount > 0; source.push(obj); } for (var i:int = 0; i < childCount; i++) { var node:XmlDom = list[i]; parseXml(node, source, obj, false); } } /** * @private * 处理数据项的打开状态。 */ protected function parseOpenStatus(oldSource:Array, newSource:Array):void { for (var i:int = 0, n:int = newSource.length; i < n; i++) { var newItem:Object = newSource[i]; if (newItem.isDirectory) { for (var j:int = 0, m:int = oldSource.length; j < m; j++) { var oldItem:Object = oldSource[j]; if (oldItem.isDirectory && isSameParent(oldItem, newItem) && newItem.label == oldItem.label) { newItem.isOpen = oldItem.isOpen; break; } } } } } /** * @private * 判断两个项对象在树结构中的父节点是否相同。 * @param item1 项对象。 * @param item2 项对象。 * @return 如果父节点相同值为true,否则值为false。 */ protected function isSameParent(item1:Object, item2:Object):Boolean { if (item1.nodeParent == null && item2.nodeParent == null) return true; else if (item1.nodeParent == null || item2.nodeParent == null) return false else { if (item1.nodeParent.label == item2.nodeParent.label) return isSameParent(item1.nodeParent, item2.nodeParent); else return false; } } /** * 表示选择的树节点项的<code>path</code>属性值。 */ public function get selectedPath():String { if (_list.selectedItem) { return _list.selectedItem.path; } return null; } /** * 更新项列表,显示指定键名的数据项。 * @param key 键名。 */ public function filter(key:String):void { if (Boolean(key)) { var result:Array = []; getFilterSource(_source, result, key); _list.array = result; } else { _list.array = getArray(); } } /** * @private * 获取数据源中指定键名的值。 */ private function getFilterSource(array:Array, result:Array, key:String):void { key = key.toLocaleLowerCase(); for each (var item:Object in array) { if (!item.isDirectory && String(item.label).toLowerCase().indexOf(key) > -1) { item.x = 0; result.push(item); } if (item.child && item.child.length > 0) { getFilterSource(item.child, result, key); } } } } }
// Decompiled by AS3 Sorcerer 6.08 // www.as3sorcerer.com //kabam.rotmg.ui.view.NewCharacterMediator package kabam.rotmg.ui.view { import robotlegs.bender.bundles.mvcs.Mediator; import com.company.assembleegameclient.screens.NewCharacterScreen; import kabam.rotmg.core.model.PlayerModel; import kabam.rotmg.core.signals.SetScreenSignal; import kabam.rotmg.game.signals.PlayGameSignal; import kabam.rotmg.core.signals.ShowTooltipSignal; import kabam.rotmg.core.signals.HideTooltipsSignal; import kabam.rotmg.core.signals.UpdateNewCharacterScreenSignal; import kabam.rotmg.core.signals.BuyCharacterPendingSignal; import kabam.rotmg.classes.model.ClassesModel; import kabam.rotmg.dialogs.control.OpenDialogSignal; import kabam.rotmg.account.securityQuestions.data.SecurityQuestionsModel; import kabam.rotmg.account.securityQuestions.view.SecurityQuestionsInfoDialog; import com.company.assembleegameclient.screens.CharacterSelectionAndNewsScreen; import kabam.rotmg.classes.view.CharacterSkinView; import flash.display.Sprite; public class NewCharacterMediator extends Mediator { [Inject] public var view:NewCharacterScreen; [Inject] public var playerModel:PlayerModel; [Inject] public var setScreen:SetScreenSignal; [Inject] public var playGame:PlayGameSignal; [Inject] public var showTooltip:ShowTooltipSignal; [Inject] public var hideTooltips:HideTooltipsSignal; [Inject] public var updateNewCharacterScreen:UpdateNewCharacterScreenSignal; [Inject] public var buyCharacterPending:BuyCharacterPendingSignal; [Inject] public var classesModel:ClassesModel; [Inject] public var openDialog:OpenDialogSignal; [Inject] public var securityQuestionsModel:SecurityQuestionsModel; override public function initialize():void { this.view.selected.add(this.onSelected); this.view.close.add(this.onClose); this.view.tooltip.add(this.onTooltip); this.updateNewCharacterScreen.add(this.onUpdate); this.buyCharacterPending.add(this.onBuyCharacterPending); this.view.initialize(this.playerModel); if (this.securityQuestionsModel.showSecurityQuestionsOnStartup) { this.openDialog.dispatch(new SecurityQuestionsInfoDialog()); } } private function onBuyCharacterPending(_arg_1:int):void { this.view.updateCreditsAndFame(this.playerModel.getCredits(), this.playerModel.getFame()); } override public function destroy():void { this.view.selected.remove(this.onSelected); this.view.close.remove(this.onClose); this.view.tooltip.remove(this.onTooltip); this.buyCharacterPending.remove(this.onBuyCharacterPending); this.updateNewCharacterScreen.remove(this.onUpdate); } private function onClose():void { this.setScreen.dispatch(new CharacterSelectionAndNewsScreen()); } private function onSelected(_arg_1:int):void { this.classesModel.getCharacterClass(_arg_1).setIsSelected(true); this.setScreen.dispatch(new CharacterSkinView()); } private function onTooltip(_arg_1:Sprite):void { if (_arg_1) { this.showTooltip.dispatch(_arg_1); } else { this.hideTooltips.dispatch(); } } private function onUpdate():void { this.view.update(this.playerModel); } } }//package kabam.rotmg.ui.view
// 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/. function testFunction() { var sum:int = 10; for (var i:int = 0; i < 10; i++) { i += sum; } var i:int; print(i); } testFunction();