CombinedText
stringlengths
4
3.42M
package io.arkeus.ouya.control { import flash.events.Event; import flash.ui.GameInputControl; import io.arkeus.ouya.ControllerInput; import io.arkeus.ouya.controller.GameController; public class ButtonControl extends GameControl { private var changed:Boolean = false; private var minimum:Number; private var maximum:Number; public function ButtonControl(device:GameController, control:GameInputControl, minimum:Number = 0.5, maximum:Number = 1) { super(device, control); this.minimum = minimum; this.maximum = maximum; } public function get pressed():Boolean { return updatedAt >= ControllerInput.previous && held && changed; } public function get released():Boolean { return updatedAt >= ControllerInput.previous && !held && changed; } public function get held():Boolean { return value >= minimum && value <= maximum; } override protected function onChange(event:Event):void { var beforeHeld:Boolean = held; super.onChange(event); changed = held != beforeHeld; } } }
package com.bit101.components { import flash.display.Sprite; import flash.events.MouseEvent; import flash.display.DisplayObjectContainer; public class PushButton extends Component { protected var _back:Sprite; protected var _face:Sprite; protected var _label:com.bit101.components.Label; protected var _labelText:String = ""; protected var _over:Boolean = false; protected var _down:Boolean = false; protected var _selected:Boolean = false; protected var _toggle:Boolean = false; public function PushButton(param1:DisplayObjectContainer = null, param2:Number = 0, param3:Number = 0, param4:String = "", param5:Function = null) { super(param1,param2,param3); if(param5 != null) { addEventListener(MouseEvent.CLICK,param5); } this.label = param4; } override protected function init() : void { super.init(); buttonMode = true; useHandCursor = true; setSize(100,20); } override protected function addChildren() : void { this._back = new Sprite(); this._back.filters = [getShadow(2,true)]; this._back.mouseEnabled = false; addChild(this._back); this._face = new Sprite(); this._face.mouseEnabled = false; this._face.filters = [getShadow(1)]; this._face.x = 1; this._face.y = 1; addChild(this._face); this._label = new com.bit101.components.Label(); addChild(this._label); addEventListener(MouseEvent.MOUSE_DOWN,this.onMouseGoDown); addEventListener(MouseEvent.ROLL_OVER,this.onMouseOver); } protected function drawFace() : void { this._face.graphics.clear(); if(this._down) { this._face.graphics.beginFill(Style.BUTTON_DOWN); } else { this._face.graphics.beginFill(Style.BUTTON_FACE); } this._face.graphics.drawRect(0,0,_width - 2,_height - 2); this._face.graphics.endFill(); } override public function draw() : void { super.draw(); this._back.graphics.clear(); this._back.graphics.beginFill(Style.BACKGROUND); this._back.graphics.drawRect(0,0,_width,_height); this._back.graphics.endFill(); this.drawFace(); this._label.text = this._labelText; this._label.autoSize = true; this._label.draw(); if(this._label.width > _width - 4) { this._label.autoSize = false; this._label.width = _width - 4; } else { this._label.autoSize = true; } this._label.draw(); this._label.move(_width / 2 - this._label.width / 2,_height / 2 - this._label.height / 2); } protected function onMouseOver(param1:MouseEvent) : void { this._over = true; addEventListener(MouseEvent.ROLL_OUT,this.onMouseOut); } protected function onMouseOut(param1:MouseEvent) : void { this._over = false; if(!this._down) { this._face.filters = [getShadow(1)]; } removeEventListener(MouseEvent.ROLL_OUT,this.onMouseOut); } protected function onMouseGoDown(param1:MouseEvent) : void { this._down = true; this.drawFace(); this._face.filters = [getShadow(1,true)]; stage.addEventListener(MouseEvent.MOUSE_UP,this.onMouseGoUp); } protected function onMouseGoUp(param1:MouseEvent) : void { if(this._toggle && this._over) { this._selected = !this._selected; } this._down = this._selected; this.drawFace(); this._face.filters = [getShadow(1,this._selected)]; stage.removeEventListener(MouseEvent.MOUSE_UP,this.onMouseGoUp); } public function set label(param1:String) : void { this._labelText = param1; this.draw(); } public function get label() : String { return this._labelText; } public function set selected(param1:Boolean) : void { if(!this._toggle) { var param1:* = false; } this._selected = param1; this._down = this._selected; this._face.filters = [getShadow(1,this._selected)]; this.drawFace(); } public function get selected() : Boolean { return this._selected; } public function set toggle(param1:Boolean) : void { this._toggle = param1; } public function get toggle() : Boolean { return this._toggle; } } }
package game.view.viewBase { import starling.display.Image; import game.manager.AssetMgr; import starling.display.Sprite; import starling.textures.Texture; import starling.text.TextField; import starling.display.Button; import flash.geom.Rectangle; import com.utils.Constants; import feathers.controls.TextInput; import feathers.controls.List; import feathers.display.Scale9Image; import feathers.textures.Scale9Textures; import game.view.goodsGuide.view.GoodsGuideGrid; import com.view.View; public class GoodsGuideForgeViewBase extends View { public var ui_Setup_button_switch31529:Scale9Image; public var grid:GoodsGuideGrid; public var btn_ok:Button; public var list_equip:List; public var view_drop:Sprite; public var list_drop:List; public function GoodsGuideForgeViewBase() { super(false); var texture:Texture; var textField:TextField; var input_txt:TextInput; var image:Image; var button:Button; var assetMgr:AssetMgr = AssetMgr.instance; texture =assetMgr.getTexture('ui_wudixingyunxing_xingxing_goumaikuang1'); image = new Image(texture); image.width = 102; image.height = 446; image.smoothing= Constants.NONE; this.addQuiackChild(image); texture =assetMgr.getTexture('ui_wudixingyunxing_xingxing_goumaikuang2'); image = new Image(texture); image.x = 79; image.width = 216; image.height = 446; image.smoothing= Constants.NONE; this.addQuiackChild(image); texture =assetMgr.getTexture('ui_wudixingyunxing_xingxing_goumaikuang1'); image = new Image(texture); image.x = 350; image.width = 102; image.height = 446; image.scaleX = -1; image.smoothing= Constants.NONE; this.addQuiackChild(image); texture = assetMgr.getTexture('ui_Setup_button_switch3'); var ui_Setup_button_switch31529Rect:Rectangle = new Rectangle(54,26,107,52); var ui_Setup_button_switch315299ScaleTexture:Scale9Textures = new Scale9Textures(texture,ui_Setup_button_switch31529Rect); ui_Setup_button_switch31529 = new Scale9Image(ui_Setup_button_switch315299ScaleTexture); ui_Setup_button_switch31529.x = 15; ui_Setup_button_switch31529.y = 29; ui_Setup_button_switch31529.width = 318; ui_Setup_button_switch31529.height = 400; this.addQuiackChild(ui_Setup_button_switch31529); grid = new GoodsGuideGrid(); grid.x = 127; grid.y = 42; this.addQuiackChild(grid); texture = assetMgr.getTexture('ui_button_gongyong_big'); btn_ok = new Button(texture); btn_ok.name= 'btn_ok'; btn_ok.x = 25; btn_ok.y = 375; btn_ok.width = 305; btn_ok.height = 57; this.addQuiackChild(btn_ok); btn_ok.text= '合成'; btn_ok.fontColor= 0xFF9900; btn_ok.fontSize= 24; list_equip = new List(); list_equip.x = 21; list_equip.y = 198; list_equip.width = 310; list_equip.height = 100; this.addQuiackChild(list_equip); view_drop = new Sprite(); view_drop.x = 21; view_drop.y = 129; view_drop.width = 317; view_drop.height = 294; this.addQuiackChild(view_drop); view_drop.name= 'view_drop'; texture = assetMgr.getTexture('ui_gongyong_hero_pub_9gongge_article'); var bg_listRect:Rectangle = new Rectangle(17,19,27,22); var bg_list9ScaleTexture:Scale9Textures = new Scale9Textures(texture,bg_listRect); var bg_list : Scale9Image = new Scale9Image(bg_list9ScaleTexture); bg_list.y = 19; bg_list.width = 312; bg_list.height = 275; view_drop.addQuiackChild(bg_list); texture = assetMgr.getTexture('ui_gongyong_hero_pub_9gongge_article1') image = new Image(texture); image.name= 'tag'; image.x = 177; image.width = 42; image.height = 19; view_drop.addQuiackChild(image); image.touchable = false; list_drop = new List(); list_drop.x = -5; list_drop.y = 25; list_drop.width = 310; list_drop.height = 258; view_drop.addQuiackChild(list_drop); init(); } override public function dispose():void { grid.dispose(); btn_ok.dispose(); list_equip.dispose(); list_drop.dispose(); view_drop.dispose(); super.dispose(); } } }
// // $Id$ package com.threerings.msoy.data.all { import com.threerings.msoy.client.DeploymentConfig; /** * Utility routines relating to a member's email address. */ public class MemberMailUtil { public static function isPermaguest (email :String) :Boolean { //Check if the person has the anon and @whirled.com strings in their emails return (email.indexOf("anon") >= 0) && (email.indexOf("@www.whirled.com") >= 0) } } }
package com.conceptualideas.compression.tar { /** * Copyright (c) <2011> Keyston Clay <http://ihaveinternet.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. */ /** * ... * @author Conceptual Ideas */ public class TarConstants{ public static const RECORD_SIZE:int = 512; public static const NAME_SIZE:int = 100; public function TarConstants() { } } }
// Decompiled by AS3 Sorcerer 6.08 // www.as3sorcerer.com //kabam.rotmg.characters.reskin.ReskinConfig package kabam.rotmg.characters.reskin { import robotlegs.bender.framework.api.IConfig; import robotlegs.bender.framework.api.IContext; import org.swiftsuspenders.Injector; import robotlegs.bender.extensions.mediatorMap.api.IMediatorMap; import robotlegs.bender.extensions.signalCommandMap.api.ISignalCommandMap; import kabam.lib.net.api.MessageMap; import kabam.rotmg.characters.reskin.view.ReskinCharacterView; import kabam.rotmg.characters.reskin.view.ReskinCharacterMediator; import kabam.rotmg.characters.reskin.view.ReskinPanel; import kabam.rotmg.characters.reskin.view.ReskinPanelMediator; import kabam.rotmg.characters.reskin.control.AddReskinConsoleActionSignal; import kabam.rotmg.characters.reskin.control.AddReskinConsoleActionCommand; import kabam.rotmg.characters.reskin.control.OpenReskinDialogSignal; import kabam.rotmg.characters.reskin.control.OpenReskinDialogCommand; import kabam.rotmg.characters.reskin.control.ReskinCharacterSignal; import kabam.rotmg.characters.reskin.control.ReskinCharacterCommand; import kabam.rotmg.messaging.impl.GameServerConnection; import kabam.rotmg.messaging.impl.outgoing.Reskin; import kabam.rotmg.characters.reskin.control.ReskinHandler; public class ReskinConfig implements IConfig { [Inject] public var context:IContext; [Inject] public var injector:Injector; [Inject] public var mediatorMap:IMediatorMap; [Inject] public var commandMap:ISignalCommandMap; [Inject] public var messageMap:MessageMap; public function configure():void { this.mediatorMap.map(ReskinCharacterView).toMediator(ReskinCharacterMediator); this.mediatorMap.map(ReskinPanel).toMediator(ReskinPanelMediator); this.commandMap.map(AddReskinConsoleActionSignal).toCommand(AddReskinConsoleActionCommand); this.commandMap.map(OpenReskinDialogSignal).toCommand(OpenReskinDialogCommand); this.commandMap.map(ReskinCharacterSignal).toCommand(ReskinCharacterCommand); this.messageMap.map(GameServerConnection.RESKIN).toMessage(Reskin).toHandler(ReskinHandler); this.context.lifecycle.afterInitializing(this.onInit); } private function onInit():void { this.injector.getInstance(AddReskinConsoleActionSignal).dispatch(); } } }//package kabam.rotmg.characters.reskin
package kabam.rotmg.assets.EmbeddedAssets { import kabam.rotmg.assets.*; import mx.core.*; [Embed(source="dats/EmbeddedAssets_particlesEmbed.dat", mimeType="application/octet-stream")] public class EmbeddedAssets_particlesEmbed extends ByteArrayAsset { public function EmbeddedAssets_particlesEmbed() { super(); return; } } }
package com.playfab.ClientModels { public class GetCharacterStatisticsResult { public var CharacterStatistics:Object; public function GetCharacterStatisticsResult(data:Object=null) { if(data == null) return; CharacterStatistics = data.CharacterStatistics; } } }
/** * Created by Administator on 21.10.14. */ package { public class CssCompile { public function CssCompile() { } } }
package dragonBones.display { import flash.display.BlendMode; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import dragonBones.core.dragonBones_internal; import dragonBones.fast.FastSlot; use namespace dragonBones_internal; public class NativeFastSlot extends FastSlot { private var _nativeDisplay:DisplayObject; public function NativeFastSlot() { super(this); _nativeDisplay = null; } override public function dispose():void { super.dispose(); _nativeDisplay = null; } //Abstract method /** @private */ override dragonBones_internal function updateDisplay(value:Object):void { _nativeDisplay = value as DisplayObject; } /** @private */ override dragonBones_internal function getDisplayIndex():int { if(_nativeDisplay && _nativeDisplay.parent) { return _nativeDisplay.parent.getChildIndex(_nativeDisplay); } return -1; } /** @private */ override dragonBones_internal function addDisplayToContainer(container:Object, index:int = -1):void { var nativeContainer:DisplayObjectContainer = container as DisplayObjectContainer; if(_nativeDisplay && nativeContainer) { if (index < 0) { nativeContainer.addChild(_nativeDisplay); } else { nativeContainer.addChildAt(_nativeDisplay, Math.min(index, nativeContainer.numChildren)); } } } /** @private */ override dragonBones_internal function removeDisplayFromContainer():void { if(_nativeDisplay && _nativeDisplay.parent) { _nativeDisplay.parent.removeChild(_nativeDisplay); } } /** @private */ override dragonBones_internal function updateTransform():void { if(_nativeDisplay) { _nativeDisplay.transform.matrix = this._globalTransformMatrix; } } /** @private */ override dragonBones_internal function updateDisplayVisible(value:Boolean):void { //if(_nativeDisplay) //{ //_nativeDisplay.visible = this._parent.visible && this._visible && value; //} } /** @private */ override dragonBones_internal function updateDisplayColor( aOffset:Number, rOffset:Number, gOffset:Number, bOffset:Number, aMultiplier:Number, rMultiplier:Number, gMultiplier:Number, bMultiplier:Number, colorChanged:Boolean = false):void { if(_nativeDisplay) { super.updateDisplayColor(aOffset, rOffset, gOffset, bOffset, aMultiplier, rMultiplier, gMultiplier, bMultiplier,colorChanged); _nativeDisplay.transform.colorTransform = _colorTransform; } } /** @private */ override dragonBones_internal function updateDisplayBlendMode(value:String):void { if(_nativeDisplay) { switch(blendMode) { case BlendMode.ADD: case BlendMode.ALPHA: case BlendMode.DARKEN: case BlendMode.DIFFERENCE: case BlendMode.ERASE: case BlendMode.HARDLIGHT: case BlendMode.INVERT: case BlendMode.LAYER: case BlendMode.LIGHTEN: case BlendMode.MULTIPLY: case BlendMode.NORMAL: case BlendMode.OVERLAY: case BlendMode.SCREEN: case BlendMode.SHADER: case BlendMode.SUBTRACT: _nativeDisplay.blendMode = blendMode; break; default: //_nativeDisplay.blendMode = BlendMode.NORMAL; break; } } } } }
package com.playfab.ProfilesModels { public class GetGlobalPolicyResponse { public var Permissions:Vector.<EntityPermissionStatement>; public function GetGlobalPolicyResponse(data:Object=null) { if(data == null) return; if(data.Permissions) { Permissions = new Vector.<EntityPermissionStatement>(); for(var Permissions_iter:int = 0; Permissions_iter < data.Permissions.length; Permissions_iter++) { Permissions[Permissions_iter] = new EntityPermissionStatement(data.Permissions[Permissions_iter]); }} } } }
package com.ankamagames.dofus.logic.game.common.actions.party { import com.ankamagames.dofus.misc.utils.AbstractAction; import com.ankamagames.jerakine.handlers.messages.Action; public class DungeonPartyFinderRegisterAction extends AbstractAction implements Action { public var dungeons:Array; public function DungeonPartyFinderRegisterAction(params:Array = null) { super(params); } public static function create(dungeons:Array) : DungeonPartyFinderRegisterAction { var a:DungeonPartyFinderRegisterAction = new DungeonPartyFinderRegisterAction(); a.dungeons = dungeons; return a; } } }
package org.superkaka.KLib.behavior { import flash.display.DisplayObject; import flash.events.Event; import flash.events.TimerEvent; import flash.utils.Timer; import org.superkaka.KLib.interfaces.IActiveSleep; /** * 为目标添加被加入显示列表时激活和移出显示列表时休眠的行为 * 解决了使用传统的 REMOVED_FROM_STAGE 事件时如果目标从一个容器添加进另一个容器但实际并没有离开舞台的情况下会意外触发事件的问题 * @author kaka */ public class ActiveSleepBehavior extends DisplayObjectBehavior { protected var isSleep:Boolean; protected var asTarget:IActiveSleep; public function ActiveSleepBehavior(target:IActiveSleep):void { super(target as DisplayObject); } override protected function init():void { asTarget = target as IActiveSleep; } override public function start():void { isSleep = displayObject.stage == null; if (isSleep) asTarget.sleep(); else asTarget.active(); displayObject.addEventListener(Event.ADDED_TO_STAGE, showHandler); displayObject.addEventListener(Event.REMOVED_FROM_STAGE, hideHandler); } override public function stop():void { displayObject.removeEventListener(Event.ADDED_TO_STAGE, showHandler); displayObject.removeEventListener(Event.REMOVED_FROM_STAGE, hideHandler); } /** * 添加到显示列表 * @param evt */ private function showHandler(evt:Event):void { displayObject.removeEventListener(Event.EXIT_FRAME, doSleep); if (!isSleep) return; isSleep = false; asTarget.active(); } /** * 从显示列表移除 * @param evt */ private function hideHandler(evt:Event):void { displayObject.addEventListener(Event.EXIT_FRAME, doSleep); } private function doSleep(evt:Event):void { displayObject.removeEventListener(Event.EXIT_FRAME, doSleep); if (isSleep) return; isSleep = true; if (displayObject.stage != null) throw new Error();//本行在测试一段时间没问题之后删除 asTarget.sleep(); } } }
package serverProto.team { import com.netease.protobuf.Message; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_UINT64; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_ENUM; import com.netease.protobuf.WireType; import com.netease.protobuf.UInt64; 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 ProtoJoinTeamRequest extends Message { public static const TEAM_ID:FieldDescriptor$TYPE_UINT64 = new FieldDescriptor$TYPE_UINT64("serverProto.team.ProtoJoinTeamRequest.team_id","teamId",2 << 3 | WireType.VARINT); public static const JOIN_TYPE:FieldDescriptor$TYPE_ENUM = new FieldDescriptor$TYPE_ENUM("serverProto.team.ProtoJoinTeamRequest.join_type","joinType",3 << 3 | WireType.VARINT,ProtoJoinType); public var teamId:UInt64; private var join_type$field:int; private var hasField$0:uint = 0; public function ProtoJoinTeamRequest() { super(); } public function clearJoinType() : void { this.hasField$0 = this.hasField$0 & 4.294967294E9; this.join_type$field = new int(); } public function get hasJoinType() : Boolean { return (this.hasField$0 & 1) != 0; } public function set joinType(param1:int) : void { this.hasField$0 = this.hasField$0 | 1; this.join_type$field = param1; } public function get joinType() : int { return this.join_type$field; } override final function writeToBuffer(param1:WritingBuffer) : void { var _loc2_:* = undefined; WriteUtils.writeTag(param1,WireType.VARINT,2); WriteUtils.write$TYPE_UINT64(param1,this.teamId); if(this.hasJoinType) { WriteUtils.writeTag(param1,WireType.VARINT,3); WriteUtils.write$TYPE_ENUM(param1,this.join_type$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: 2, Size: 2) */ throw new flash.errors.IllegalOperationError("Not decompiled due to error"); } } }
/** * ]~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~._ * ]~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~._ * * Class : Derivative.as * Version : 1.0 * * Author : Matt Holcombe (gullinbursti) * Created : 12-23-09 * * Purpose : Provides operations related to derivitve calculus. * * ]~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~·¯ * ]~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~·¯ **/ /* Licensed under the MIT License Copyright (c) 2009 Matt Holcombe (matt@gullinbursti.cc) 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 AUTHOR 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. http://code.gullinbursti.cc/ http://en.wikipedia.org/wiki/MIT_license/ []~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~:~~[]. */ package cc.gullinbursti.math.calculus { //] includes [!]> //]=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~. //]~=~=~=~=~=~=~=~=~=~=~=~=~=~[]~=~=~=~=~=~=~=~=~=~=~=~=~=~[ /** * * @author Gullinbursti */ // <[!] class delaration [¡]> public class Derivative extends BasicCalc { //]~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~._ //TODO: define & implement some derivative operations public function Derivative() {/* …\(^_^)/… */} //]~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~~*~._ //]~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=[> //]~=~=~=~=~=~=~=~=~=[> } }
package widgets.Interrupciones.servicios.interrupciones { import com.esri.ags.FeatureSet; import com.esri.ags.Graphic; import com.esri.ags.SpatialReference; import com.esri.ags.tasks.QueryTask; import com.esri.ags.tasks.supportClasses.Query; import mx.collections.ArrayCollection; import mx.rpc.AsyncResponder; import widgets.Interrupciones.servicios.UtilWhere; import widgets.Interrupciones.urls.Urls; public class BusquedaClientePorInterrupcion { public var callBackOk:Function; public var callBackError:Function; public var resultado:ArrayCollection; public function BusquedaInterrupciones() { } public function buscar(callBackOk:Function,callBackError:Function,idInterrupcion:String):void{ this.callBackError=callBackError; this.callBackOk=callBackOk; var propiedades:Array = new Array(); propiedades.push("interrupcion_id"); propiedades.push("vl_clientes_afectados"); propiedades.push("vl_duracion"); var query:Query = new Query(); query.outFields=propiedades; //TODO: hardcodeado por ahora query.outSpatialReference= new SpatialReference(102100); var condicionPeriodo:String=UtilWhere.periodoAWhereInterrupcion(arrayPeriodo); // TODO: ACA PONER EL IN de los ids.... query.where=condicionPeriodo; query.returnGeometry = false; //query.orderByFields = new Array("nombre asc"); var queryTask:QueryTask = new QueryTask(); queryTask.showBusyCursor = true; queryTask.url=Urls.URL_INTERRUPCIONES; // queryTask.token="_zmYF3PlUzzAtyzA9TggDvN6vBP9vX558R7uqN3ajG3sQTevsamsvf3eNFpe47TY"; queryTask.useAMF=false; queryTask.execute(query, new AsyncResponder(onResult, onFault)); } private function onResult(featureSet:FeatureSet, token:Object = null):void { resultado=new ArrayCollection; if (featureSet.features.length == 0){ callBackOk(resultado); return; } for (var i:Number=0;i<featureSet.features.length;i++){ var g:Graphic = featureSet.features[i] as Graphic; var idInterrupcion:String=g.attributes["interrupcion_id"]; var afectados:Number=Number(g.attributes["vl_clientes_afectados"]); var duracion:Number=Number(g.attributes["vl_duracion"]); var dtoInterrupcion:DtoInterrupcion=new DtoInterrupcion; dtoInterrupcion.idInterrupcion=idInterrupcion; dtoInterrupcion.afectados=afectados; dtoInterrupcion.duracion=duracion; resultado.addItem(dtoInterrupcion); } callBackOk(resultado); } private function onFault(info:Object, token:Object = null):void { callBackError("error" +info); } } }
/** * 개발자 : refracta * 날짜 : 2014-08-15 오전 12:55 */ package com.wg.ga.missile.manager { import com.wg.ga.framework.entity.Entity; import com.wg.ga.framework.fm.FitnessMeasurement; import com.wg.ga.framework.gene.Gene; import com.wg.ga.framework.logic.interfaces.CrossoverLogic; import com.wg.ga.framework.logic.interfaces.MutationLogic; import com.wg.ga.framework.manager.GeneManager; import com.wg.ga.framework.util.Random; import com.wg.ga.missile.entity.MissileTargetEntity; import com.wg.ga.framework.gene.DirectionGene; import flash.system.System; public class MissileTargetGeneManager implements GeneManager { private var originalPoolAmount:int ; private var mutationRatio:int ; public function MissileTargetGeneManager(originalPoolAmount:int, mutationRatio:int) { this.originalPoolAmount = originalPoolAmount; this.mutationRatio = mutationRatio; } public function getRandomIndexCrossoverEntities(crossoverLogic:CrossoverLogic, entities:Vector.<MissileTargetEntity>):Vector.<MissileTargetEntity> { var childEntities:Vector.<MissileTargetEntity> = new Vector.<MissileTargetEntity>(); var size:int = entities.length; if (size < 2) { try { throw new Error("MissileTargetEntity list size is small"); } catch (e:Error) { trace(e.getStackTrace()); System.exit(1); } } for (var i:int = 0; i <originalPoolAmount; i++) { var randomIndex1:int = Random.nextInt(size); var randomIndex2:int = Random.nextInt(size); for (; randomIndex1 == randomIndex2; randomIndex1 = Random.nextInt(size)) ; var source1:MissileTargetEntity = entities[randomIndex1]; var source2:MissileTargetEntity = entities[randomIndex2]; var reproductionEntity:MissileTargetEntity = MissileTargetEntity(crossoverLogic.createCrossoverEntity(source1, source2)); childEntities.push(reproductionEntity); } return childEntities; } public function setMutateEntity(mutateLogic:MutationLogic, targetEntities:Vector.<MissileTargetEntity>):void { for (var i:int = 0; i < targetEntities.length; i++) { if (Random.nextProbability(mutationRatio)) { var mutation:Entity = mutateLogic.createMutation(targetEntities[i]); targetEntities[i] = MissileTargetEntity(mutation); } } } public function makeRandomUnlimitedGeneList():Vector.<Gene> { return null; } public function makeRandomLimitGeneList(limit:int):Vector.<Gene> { var geneInformation:Vector.<DirectionGene> = new Vector.<DirectionGene>(); for (var i:int = 0; i < limit; i++) { geneInformation.push(DirectionGene.GENE_LIST[Random.nextInt(DirectionGene.GENE_LIST.length)]); } return Vector.<Gene>(geneInformation); } public function getFirstLimitBinaryEntitys(fitnessMeasurement:FitnessMeasurement, numOfGene:int, numOfEntity:int):Vector.<MissileTargetEntity> { var entityList:Vector.<MissileTargetEntity> = new Vector.<MissileTargetEntity>(); for (var i:int = 0; i < numOfEntity; i++) { entityList.push(getLimitMissileTargetEntity(fitnessMeasurement,numOfGene)); } return entityList; } public function getLimitMissileTargetEntity(fitnessMeasurement:FitnessMeasurement, numOfGene:int):MissileTargetEntity{ var genes:Vector.<DirectionGene> = Vector.<DirectionGene> (makeRandomLimitGeneList(numOfGene)); var returnEntity:MissileTargetEntity = new MissileTargetEntity(genes,fitnessMeasurement); return returnEntity; } } }
package dagd.powers.scripts { import flash.display.MovieClip; import flash.events.MouseEvent; public class Multi extends MovieClip { private var velocityX: Number = 0; //X velocity private var velocityY: Number = 0; //Y velocity private var velocityA: Number = 0; //angular velocity var sideTest: Number = 1; public var isDead: Boolean = false; public var points = 0; public var damage = 0; public function Multi() { // constructor code sideTest = Math.random(); if (sideTest >= 0.5) x = -50; else x = 850; y = Math.random() * 300 + 600; if (sideTest >= 0.5) velocityX = (Math.random() * 2) + 2; // Makes the spear fly across the screen from left to right else velocityX = (Math.random() * -2) - 2; // Makes the spear fly across the screen from right to left velocityY = (Math.random() * 0.5) + 0.5; //Makes object shoot slowly fall down if (sideTest >= 0.5) velocityA = (Math.random() * 4) - 2; //Velocity for the rotation of the object else velocityA = (Math.random() * -4) + 2; //Velocity for the rotation of the object addEventListener(MouseEvent.CLICK, handleClick); } public function update() { var gravity: Number = -0.05; velocityY += gravity; x += velocityX; y += velocityY; rotation += velocityA; if (y < -50) isDead = true; //kill the object } private function handleClick(e: MouseEvent) { isDead = true; //kill this object points = 200; //give the player points damage = -10; //damage the player } //this function is used for cleanup, ensuring no memory leaks public function dispose(): void { removeEventListener(MouseEvent.CLICK, handleClick); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.ICollectionView; import mx.collections.IList; import mx.collections.IViewCursor; import mx.core.mx_internal; import mx.resources.ResourceManager; use namespace mx_internal; //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name="dimension", kind="property")] //-------------------------------------- // metadata //-------------------------------------- [DefaultProperty("elements")] /** * The OLAPDimension class represents a dimension of an OLAP cube. * * @mxml * <p> * The <code>&lt;mx:OLAPDimension&gt;</code> tag inherits all of the tag attributes * of its superclass, and adds the following tag attributes: * </p> * <pre> * &lt;mx:OLAPDimension * <b>Properties</b> * attributes="" * elements="" * hierarchies="" * /&gt; * * @see mx.olap.IOLAPDimension * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class OLAPDimension extends OLAPElement implements IOLAPDimension { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor * * @param name The name of the OLAP dimension that includes the OLAP schema hierarchy of the element. * * @param displayName The name of the OLAP dimension, as a String, which can be used for display. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function OLAPDimension(name:String=null, displayName:String=null) { OLAPTrace.traceMsg("Creating dimension: " + name, OLAPTrace.TRACE_LEVEL_3); super(name, displayName); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- //map of attributes using name as the key private var attributeMap:Dictionary = new Dictionary(true); //map of hierarchies using name as the key private var _hierarchiesMap:Dictionary = new Dictionary(true); //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // attributes //---------------------------------- private var _attributes:IList = new ArrayCollection; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get attributes():IList { return _attributes; } /** * @private */ public function set attributes(value:IList):void { _attributes = value; var n:int = value.length; for (var attrIndex:int = 0; attrIndex < n; ++attrIndex) { var attr:OLAPAttribute = value.getItemAt(attrIndex) as OLAPAttribute; attr.dimension = this; attributeMap[attr.name] = attr; } } //---------------------------------- // cube //---------------------------------- private var _cube:IOLAPCube; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get cube():IOLAPCube { return _cube; } /** * @private */ public function set cube(value:IOLAPCube):void { _cube = value; } //---------------------------------- // dataProvider //---------------------------------- mx_internal function get dataProvider():ICollectionView { return OLAPCube(cube).dataProvider; } //---------------------------------- // defaultMember //---------------------------------- /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get defaultMember():IOLAPMember { // get the default hierarchy here if ((hierarchies.length + attributes.length) > 1) { var message:String = ResourceManager.getInstance().getString( "olap", "multipleHierarchies"); throw Error(message); } return hierarchies[0].defaultMember; } //---------------------------------- // elements //---------------------------------- /** * Processes the input Array and initializes the <code>attributes</code> * and <code>hierarchies</code> properties based on the elements of the Array. * Attributes are represented in the Array by instances of the OLAPAttribute class, * and hierarchies are represented by instances of the OLAPHierarchy class. * * <p>Use this property to define the attributes and hierarchies of a cube in a single Array.</p> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function set elements(value:Array):void { var attrs:ArrayCollection = new ArrayCollection(); var userHierarchies:ArrayCollection = new ArrayCollection(); for each (var element:Object in value) { if (element is OLAPAttribute) attrs.addItem(element); else if (element is OLAPHierarchy) userHierarchies.addItem(element); else OLAPTrace.traceMsg("Invalid element specified for dimension elements"); } attributes = attrs; hierarchies = userHierarchies; } //---------------------------------- // hierarchies //---------------------------------- private var _hierarchies:IList = new ArrayCollection; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get hierarchies():IList { return _hierarchies; } /** * @private */ public function set hierarchies(value:IList):void { //limitation till we support multiple hierarchies. if (value.length > 1) { var message:String = ResourceManager.getInstance().getString( "olap", "multipleHierarchiesNotSupported", [name]); throw Error(message); } _hierarchies = value; for (var i:int = 0; i < value.length; ++i) { var h:OLAPHierarchy = value.getItemAt(i) as OLAPHierarchy; h.dimension = this; _hierarchiesMap[h.name] = h; } } //---------------------------------- // isMeasure //---------------------------------- private var _isMeasureDimension:Boolean = false; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get isMeasure():Boolean { return _isMeasureDimension; } /** * @private */ mx_internal function setAsMeasure(value:Boolean):void { _isMeasureDimension = value; } //---------------------------------- // members //---------------------------------- /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get members():IList { var temp:Array = []; for (var i:int = 0; i < hierarchies.length; ++i) temp = temp.concat(hierarchies.getItemAt(i).members.toArray()); return new ArrayCollection(temp); } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function findHierarchy(name:String):IOLAPHierarchy { return _hierarchiesMap[name]; } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function findAttribute(name:String):IOLAPAttribute { return attributeMap[name]; } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function findMember(name:String):IOLAPMember { var member:IOLAPMember; var i:int = 0; var h:OLAPHierarchy; for (i = 0; i < attributes.length; ++i) { h = attributes.getItemAt(i) as OLAPHierarchy; member = h.findMember(name); if (member) break; } if (!member) { for (i = 0; i < hierarchies.length; ++i) { h = hierarchies.getItemAt(i) as OLAPHierarchy; member = h.findMember(name); if (member) break; } } return member; } /** * @private * Creates a hierarchy of the dimension. * * @param name The name of the hierarchy. * * @return An OLAPHierarchy instance that represents the new hierarchy. */ mx_internal function createHierarchy(name:String):OLAPHierarchy { var h:OLAPHierarchy = new OLAPHierarchy(name); h.dimension = this; _hierarchies.addItem(h); _hierarchiesMap[h.name] = h; return h; } /** * @private */ mx_internal function refresh():void { //if dimension is of measure type we have nothing to do. if (isMeasure) return; var temp:Object; var dataHandlers:Array =[]; var i:int = 0; var n:int = attributes.length; for (i = 0; i < n; ++i) { temp = attributes.getItemAt(i); dataHandlers.push(temp); } n = hierarchies.length; for (i = 0; i < n; ++i) { temp = hierarchies.getItemAt(i); temp.refresh(); dataHandlers.push(temp); } for (i = 0; i < n; ++i) { var h:OLAPHierarchy = hierarchies.getItemAt(i) as OLAPHierarchy; var levels:IList = h.levels; var m:int = levels.length; for (var j:int = 0; j < m; ++j) { var level:OLAPLevel = levels[j]; //levels doesn't include allLevel //if (level == h.allLevel) // continue; var a:OLAPAttribute = findAttribute(level.name) as OLAPAttribute; a.userHierarchy = level.hierarchy; a.userHierarchyLevel = level; } } // we need to refresh attributes here because we need the userHierarchy // userLevels to be set before refresh can happen. n = attributes.length; for (i = 0; i < n; ++i) { temp = attributes.getItemAt(i); temp.refresh(); } var iterator:IViewCursor = dataProvider.createCursor(); while (!iterator.afterLast) { var currentData:Object = iterator.current; for each (temp in dataHandlers) temp.processData(currentData); iterator.moveNext(); } } /** * @private */ mx_internal function addAttribute(name:String, dataField:String):IOLAPAttribute { var attrHierarchy:OLAPAttribute = attributeMap[name]; if (!attrHierarchy) { attrHierarchy = new OLAPAttribute(name); attrHierarchy.dataField = dataField; attrHierarchy.dimension = this; attributeMap[name] = attrHierarchy; _attributes.addItem(attrHierarchy); } return attrHierarchy; } } }
package org.openapitools.client.api { import org.openapitools.common.ApiInvoker; import org.openapitools.exception.ApiErrorCodes; import org.openapitools.exception.ApiError; import org.openapitools.common.ApiUserCredentials; import org.openapitools.event.Response; import org.openapitools.common.OpenApi; import mx.rpc.AsyncToken; import mx.utils.UIDUtil; import flash.utils.Dictionary; import flash.events.EventDispatcher; public class CqApi extends OpenApi { /** * Constructor for the CqApi api client * @param apiCredentials Wrapper object for tokens and hostName required towards authentication * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response */ public function CqApi(apiCredentials: ApiUserCredentials, eventDispatcher: EventDispatcher = null) { super(apiCredentials, eventDispatcher); } public static const event_get_login_page: String = "get_login_page"; public static const event_post_cq_actions: String = "post_cq_actions"; /* * Returns String */ public function get_login_page (): String { // create path and map variables var path: String = "/libs/granite/core/content/login.html".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "get_login_page"; token.returnType = String; return requestId; } /* * Returns void */ public function post_cq_actions (authorizableId: String, changelog: String): String { // create path and map variables var path: String = "/.cqactions.html".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); var headerParams: Dictionary = new Dictionary(); // verify required params are set if( // verify required params are set if() { throw new ApiError(400, "missing required params"); } ) { throw new ApiError(400, "missing required params"); } if("null" != String(authorizableId)) queryParams["authorizableId"] = toPathValue(authorizableId); if("null" != String(changelog)) queryParams["changelog"] = toPathValue(changelog); var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, null, headerParams); var requestId: String = getUniqueId(); token.requestId = requestId; token.completionEventType = "post_cq_actions"; token.returnType = null ; return requestId; } } }
package tests.weapon { import org.flixel.*; import org.flixel.plugin.photonstorm.*; import tests.TestsHeader; public class WeaponTest4 extends FlxState { // Common variables public static var title:String = "Weapon 4"; public static var description:String = "Bullet Acceleration Example"; private var instructions:String = "LEFT / RIGHT to Move. Space to Fire."; private var header:TestsHeader; // Test specific variables private var controls:FlxControlHandler; private var player:FlxSprite; private var lazer:FlxWeapon; public function WeaponTest4() { } override public function create():void { header = new TestsHeader(instructions); add(header); // Test specific header.showDarkBackground(); // Our players space ship player = new FlxSprite(160, 200, AssetsRegistry.invaderPNG); // Creates our weapon. We'll call it "lazer" and link it to the x/y coordinates of the player sprite lazer = new FlxWeapon("lazer", player, "x", "y"); // Tell the weapon to create 50 bullets using the bulletPNG image. // The 5 value is the x offset, which makes the bullet fire from the tip of the players ship. lazer.makeImageBullet(40, AssetsRegistry.bulletPNG, 5); // Sets the direction and speed the bullets will be fired in lazer.setBulletAcceleration(0, -60, 200, 200); // The following are controls for the player, note that the "setFireButton" controls the speed at which bullets are fired, not the Weapon class itself // Enable the plugin - you only need do this once (unless you destroy the plugin) if (FlxG.getPlugin(FlxControl) == null) { FlxG.addPlugin(new FlxControl); } FlxControl.create(player, FlxControlHandler.MOVEMENT_INSTANT, FlxControlHandler.STOPPING_INSTANT, 1, false, false); FlxControl.player1.setMovementSpeed(200, 0, 200, 0); FlxControl.player1.setCursorControl(false, false, true, true); FlxControl.player1.setBounds(16, 200, 280, 16); // This is what fires the actual bullets (pressing SPACE) at a rate of 1 bullet per 150 ms, hooked to the lazer.fire method FlxControl.player1.setFireButton("SPACE", FlxControlHandler.KEYMODE_PRESSED, 150, lazer.fire); // The group which contains all of the bullets should be added so it is displayed add(lazer.group); add(player); // Header overlay add(header.overlay); } override public function update():void { super.update(); } override public function destroy():void { // Important! Clear out the plugin otherwise resources will get messed right up after a while FlxControl.clear(); super.destroy(); } } }
package { import flash.display.Sprite; import mx.core.IFlexModuleFactory; import mx.core.mx_internal; import mx.styles.CSSStyleDeclaration; import mx.styles.StyleManager; [ExcludeClass] public class _comboDropDownStyle { public static function init(fbs:IFlexModuleFactory):void { var style:CSSStyleDeclaration = StyleManager.getStyleDeclaration(".comboDropDown"); if (!style) { style = new CSSStyleDeclaration(); StyleManager.setStyleDeclaration(".comboDropDown", style, false); } if (style.defaultFactory == null) { style.defaultFactory = function():void { this.fontWeight = "normal"; this.cornerRadius = 0; this.dropShadowEnabled = true; this.shadowDirection = "center"; this.borderThickness = 0; this.shadowDistance = 1; this.backgroundColor = 0xffffff; }; } } } }
package { public class Main { public function Main() { var vector:Vector.<*> = new <*>[] } } }
package laya.html.dom { /** * @private */ public class HTMLBrElement extends HTMLElement { public function HTMLBrElement() { super(); style.lineElement = true; style.block = true; } } }
package net.guttershark.util.filters { import flash.display.DisplayObject; import flash.filters.BevelFilter; import flash.filters.BitmapFilter; import flash.filters.BlurFilter; import flash.filters.ColorMatrixFilter; import flash.filters.DropShadowFilter; import flash.filters.GlowFilter; import flash.filters.GradientBevelFilter; import flash.filters.GradientGlowFilter; import net.guttershark.util.Singleton; /** * The FilterUtilities class is a singleton that * provides common filter generation and filter * management for a display object. * * @see net.guttershark.util.Utilities Utilities class. */ public class FilterUtils { /** * Singleton instance. */ private static var inst:FilterUtils; /** * Singleton access. */ public static function gi():FilterUtils { if(!inst) inst = Singleton.gi(FilterUtils); return inst; } /** * @private */ public function FilterUtils() { Singleton.assertSingle(FilterUtils); } /** * Return a default <code>DropShadowFilter</code>. * <ul> * <li>length:0</li> * <li>direction:45</li> * <li>alpha:100</li> * <li>blurX:10</li> * <li>blurY:10</li> * <li>strength:0.5</li> * <li>quality:HIGH</li> * </ul> */ public function getSoftShadowFilter():DropShadowFilter { return new DropShadowFilter(0,45,0x000000,100,10,10,0.50,FilterQuality.HIGH); } /** * Returns a predefined greyscale color matrix. */ public function luminanceTransform():ColorMatrixFilter { var rwgt:Number = .3086; var gwgt:Number = .6094; var bwgt:Number = .0820; var lumTransform:ColorMatrixFilter = new ColorMatrixFilter(new Array(rwgt,gwgt,bwgt,0.0,0.0,rwgt,gwgt,bwgt,0.0,0.0,rwgt,gwgt,bwgt,0.0,0.0,0.0,0.0,0.0,1.0,0.0)); return lumTransform; } /** * Clears any current shadow filters, and applies a new one. * * @param target The target display object. * @param filter A drop shadow filter. */ public function setShadow(target:DisplayObject,filter:DropShadowFilter):DropShadowFilter { clearFilterType(target,DropShadowFilter); return addShadow(target,filter); } /** * Adds a new shadow filter to the display object. * * @param target The target display object. * @param filter A drop shadow filter. */ public function addShadow(target:DisplayObject,filter:DropShadowFilter):DropShadowFilter { addFilter(target,filter); return filter; } /** * Remove all shadow filters. * * @param The target display object. */ public function cleanShadow(target:DisplayObject):void { clearFilterType(target,DropShadowFilter); } /** * Clears any current glow filters, and applies a new one. * * @param target The target display object. * @param filter A glow filter. */ public function setGlow(target:DisplayObject,filter:GlowFilter):GlowFilter { clearFilterType(target,GlowFilter); return addGlow(target,filter); } /** * Adds a new glow filter to the display object. * * @param target The target display object. * @param filter A glow filter. */ public function addGlow(target:DisplayObject,filter:GlowFilter):GlowFilter { addFilter(target,filter); return filter; } /** * Remove all glow filters. * * @param target The target display object. */ public function cleanGlow(target:DisplayObject):void { clearFilterType(target,GlowFilter); } /** * Clears any current bevel filters, and applies a new one. * * @param target The target display object. * @param filter A bevel filter. */ public function setBevel(target:DisplayObject,filter:BevelFilter):BevelFilter { clearFilterType(target,BevelFilter); return addBevel(target,filter); } /** * Adds a new bevel filter to the display object. * * @param target The target display object. * @param filter A bevel filter. */ public function addBevel(target:DisplayObject,filter:BevelFilter):BevelFilter { addFilter(target,filter); return filter; } /** * Remove all bevel filters. * * @param target The target display object. */ public function cleanBevel(target:DisplayObject):void { clearFilterType(target,BevelFilter); } /** * Clears any current color filters, and applies a new one. * * @param target The target display object. * @param filter A color matrix filter. */ public function setColorMatrix(target:DisplayObject,filter:ColorMatrixFilter):ColorMatrixFilter { clearFilterType(target,ColorMatrixFilter); return addColorMatrix(target,filter); } /** * Adds a new color matrix filter to the display object. * * @param target The target display object. * @param filter A color matrix filter. */ public function addColorMatrix(target:DisplayObject,filter:ColorMatrixFilter):ColorMatrixFilter { addFilter(target,filter); return filter; } /** * Clears any gradient glow filters, and applies a new one. * * @param target The target display object. * @param filter A gradient glow filter. */ public function setGradientGlow(target:DisplayObject,filter:GradientGlowFilter):GradientGlowFilter { clearFilterType(target,GradientGlowFilter); return addGradientGlow(target,filter); } /** * Adds a new gradient glow filter to the display object. * * @param target The target display object. * @param filter A gradient glow filter. */ public function addGradientGlow(target:DisplayObject,filter:GradientGlowFilter):GradientGlowFilter { addFilter(target,filter); return filter; } /** * Remove all gradient glow filters. * * @param target The target display object. */ public function cleanGradientGlow(target:DisplayObject):void { clearFilterType(target,GradientGlowFilter); } /** * Clears any gradient bevel filters, and applies a new one. * * @param target The target display object. * @param filter A gradient bevel filter. */ public function setGradientBevel(target:DisplayObject,filter:GradientBevelFilter):GradientBevelFilter { clearFilterType(target,GradientBevelFilter); return addGradientBevel(target,filter); } /** * Adds a new gradient bevel filter to the display object. * * @param target The target display object. * @param filter A gradient bevel filter. */ public function addGradientBevel(target:DisplayObject,filter:GradientBevelFilter):GradientBevelFilter { addFilter(target,filter); return filter; } /** * Remove all gradient bevel filters. * * @param target The target display object. */ public function cleanGradientBevel(target:DisplayObject):void { clearFilterType(target,GradientBevelFilter); } /** * Clears any blur filters, and applies a new one. * * @param target The taget display object. * @param filter A blur filter. */ public function setBlur(target:DisplayObject,filter:BlurFilter):BlurFilter { clearFilterType(target,BlurFilter); return addBlur(target,filter); } /** * Adds a new blur filter the the display object. * * @param target The target display object. * @param filter A blur filter. */ public function addBlur(target:DisplayObject,filter:BlurFilter):BlurFilter { addFilter(target,filter); return filter; } /** * Remove all blur filters. * * @param target The target display object. */ public function cleanBlur(target:DisplayObject):void { clearFilterType(target,BlurFilter); } /** * Add a filter of any type, to the target display object. * * @param taget The target display object. * @param filter A bitmap filter. */ public function addFilter(target:DisplayObject=null,filter:BitmapFilter=null):void { if(target == null||filter == null) return; var tmp:Array = target.filters; tmp.push(filter); target.filters = tmp; } /** * Remove a filter of any type. * * @param target The target display object. * @param filter A bitmap filter. */ public function removeFilter(target:DisplayObject=null,filter:BitmapFilter=null):void { if(target == null||filter == null ) return; var tmp:Array = target.filters; var index:int = getFilterIndex(target,filter); if(index > -1) { tmp.splice(index,1); target.filters = tmp; } } /** * Remove all filters from a target display object. * * @param target The target display object. */ public function clean(target:DisplayObject):void { target.filters = []; } /** * Removes all filters of a certain type. * * @param target The target display object. * @param filterType The class type of the filters to remove. */ public function clearFilterType(target:DisplayObject=null,filterType:Class=null):void { if(target == null||filterType == null) return; var len:int = target.filters.length; var tmp:Array = new Array(); var i:int = 0; for(i;i<len;i++) { var f:BitmapFilter = target.filters[i]; if(!(f is filterType)) tmp.push(f); } target.filters = tmp; } /** * Finds the last index of a filter and returns that index, or -1 if not found. * * @param target The target display object. * @param filter A bitmap filter. */ public function getFilterIndex(target:DisplayObject=null,filter:BitmapFilter=null):int { if(target == null) return -1; var pos:int = target.filters.length; while(pos--) { var f:BitmapFilter = target.filters[pos]; if(f == filter) return pos; } return -1; } /** * Finds the last index of a filter type, and returns that index, or -1 if not found. * * @param target The target display object. * @param filterType The class type of the filter to find. */ public function getFilterTypeIndex(target:DisplayObject=null,filterType:Class=null):int { if(target == null) return -1; var pos:int = target.filters.length; while(pos--) { var f:BitmapFilter = target.filters[pos]; if(f is filterType) return pos; } return -1; } } }
package feathers.examples.componentsExplorer.screens { import feathers.controls.Button; import feathers.controls.GroupedList; import feathers.controls.PanelScreen; import feathers.controls.renderers.DefaultGroupedListItemRenderer; import feathers.controls.renderers.IGroupedListItemRenderer; import feathers.data.HierarchicalCollection; import feathers.events.FeathersEventType; import feathers.examples.componentsExplorer.data.GroupedListSettings; import feathers.layout.AnchorLayout; import feathers.layout.AnchorLayoutData; import feathers.system.DeviceCapabilities; import starling.core.Starling; 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 PanelScreen { public static const SHOW_SETTINGS:String = "showSettings"; public function GroupedListScreen() { super(); } public var settings:GroupedListSettings; private var _list:GroupedList; private var _backButton:Button; private var _settingsButton:Button; override protected function initialize():void { //never forget to call super.initialize() super.initialize(); this.layout = new AnchorLayout(); 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" }, ] }, { header: "F", children: [ { text: "Fox" }, ] } ]; groups.fixed = true; this._list = new GroupedList(); if(this.settings.style == GroupedListSettings.STYLE_INSET) { this._list.styleNameList.add(GroupedList.ALTERNATE_NAME_INSET_GROUPED_LIST); } this._list.dataProvider = new HierarchicalCollection(groups); this._list.typicalItem = { text: "Item 1000" }; this._list.isSelectable = this.settings.isSelectable; this._list.hasElasticEdges = this.settings.hasElasticEdges; this._list.clipContent = false; this._list.autoHideBackground = true; this._list.itemRendererFactory = function():IGroupedListItemRenderer { var renderer:DefaultGroupedListItemRenderer = new DefaultGroupedListItemRenderer(); //enable the quick hit area to optimize hit tests when an item //is only selectable and doesn't have interactive children. renderer.isQuickHitAreaEnabled = true; renderer.labelField = "text"; return renderer; }; this._list.addEventListener(Event.CHANGE, list_changeHandler); this._list.layoutData = new AnchorLayoutData(0, 0, 0, 0); this.addChildAt(this._list, 0); this.headerProperties.title = "Grouped List"; if(!DeviceCapabilities.isTablet(Starling.current.nativeStage)) { this._backButton = new Button(); this._backButton.styleNameList.add(Button.ALTERNATE_NAME_BACK_BUTTON); this._backButton.label = "Back"; this._backButton.addEventListener(Event.TRIGGERED, backButton_triggeredHandler); this.headerProperties.leftItems = new <DisplayObject> [ this._backButton ]; this.backButtonHandler = this.onBackButton; } this._settingsButton = new Button(); this._settingsButton.label = "Settings"; this._settingsButton.addEventListener(Event.TRIGGERED, settingsButton_triggeredHandler); this.headerProperties.rightItems = new <DisplayObject> [ this._settingsButton ]; this.owner.addEventListener(FeathersEventType.TRANSITION_COMPLETE, owner_transitionCompleteHandler); } private function onBackButton():void { this.dispatchEventWith(Event.COMPLETE); } private function backButton_triggeredHandler(event:Event):void { this.onBackButton(); } private function settingsButton_triggeredHandler(event:Event):void { this.dispatchEventWith(SHOW_SETTINGS); } private function list_changeHandler(event:Event):void { trace("GroupedList onChange:", this._list.selectedGroupIndex, this._list.selectedItemIndex); } private function owner_transitionCompleteHandler(event:Event):void { this.owner.removeEventListener(FeathersEventType.TRANSITION_COMPLETE, owner_transitionCompleteHandler); this._list.revealScrollBars(); } } }
package roomList.pvpRoomList { import com.pickgliss.ui.ComponentFactory; import com.pickgliss.ui.controls.cell.IListCell; import com.pickgliss.ui.controls.list.List; import com.pickgliss.ui.core.Disposeable; import com.pickgliss.ui.text.FilterFrameText; import com.pickgliss.ui.text.GradientText; import com.pickgliss.utils.DisplayUtils; import com.pickgliss.utils.ObjectUtils; import ddt.data.player.PlayerInfo; import ddt.manager.PlayerTipManager; import ddt.view.common.LevelIcon; import ddt.view.common.SexIcon; import flash.display.Bitmap; import flash.display.DisplayObject; import flash.display.Sprite; import flash.events.MouseEvent; import flash.geom.Point; import vip.VipController; public class RoomListPlayerItem extends Sprite implements Disposeable, IListCell { private var _info:PlayerInfo; private var _levelIcon:LevelIcon; private var _sexIcon:SexIcon; private var _name:FilterFrameText; private var _BG:Bitmap; private var _isSelected:Boolean; private var _vipName:GradientText; public function RoomListPlayerItem() { super(); this.init(); } private function init() : void { this._BG = ComponentFactory.Instance.creatBitmap("asset.roomList.playerItemBG"); this._BG.visible = false; this._BG.y = 2; addChild(this._BG); this._name = ComponentFactory.Instance.creat("roomList.pvpRoomList.playerItemName"); this._name.isAutoFitLength = true; this._levelIcon = new LevelIcon(); this._levelIcon.setSize(LevelIcon.SIZE_SMALL); addChild(this._levelIcon); this._sexIcon = ComponentFactory.Instance.creatCustomObject("roomList.roomPlayerItem.SexIcon"); addChild(this._sexIcon); addEventListener(MouseEvent.CLICK,this.itemClick); } private function itemClick(param1:MouseEvent) : void { PlayerTipManager.show(this._info,localToGlobal(new Point(0,0)).y); } public function setListCellStatus(param1:List, param2:Boolean, param3:int) : void { this._isSelected = param2; if(this._BG) { this._BG.visible = this._isSelected; } } public function getCellValue() : * { return this._info; } public function setCellValue(param1:*) : void { this._info = param1; this.update(); } public function get isSelected() : Boolean { return this._isSelected; } private function update() : void { this._name.text = this._info.NickName; if(this._info.IsVIP) { if(this._vipName) { ObjectUtils.disposeObject(this._vipName); } this._vipName = VipController.instance.getVipNameTxt(120,this._info.typeVIP); this._vipName.x = this._name.x; this._vipName.y = this._name.y; this._vipName.text = this._name.text; addChild(this._vipName); DisplayUtils.removeDisplay(this._name); } else { addChild(this._name); DisplayUtils.removeDisplay(this._vipName); } this._sexIcon.setSex(this._info.Sex); this._levelIcon.setInfo(this._info.Grade,this._info.Repute,this._info.WinCount,this._info.TotalCount,this._info.FightPower,this._info.Offer,true,false); } public function asDisplayObject() : DisplayObject { return this; } public function dispose() : void { removeEventListener(MouseEvent.CLICK,this.itemClick); if(this._vipName) { this._vipName.dispose(); } this._vipName = null; if(this._name) { this._name.dispose(); this._name = null; } if(this._levelIcon) { this._levelIcon.dispose(); this._levelIcon = null; } if(this._sexIcon) { this._sexIcon.dispose(); this._sexIcon = null; } if(this._BG) { ObjectUtils.disposeObject(this._BG); this._BG = null; } } } }
package factories { import mx.core.FlexGlobals; public class SpyProbeFactory extends ResourceFactory { /* Constructor is not used... */ public function SpyProbeFactory():* { } [Bindable] public static var name:String = 'SpyProbe'; private static var level_rates:Array = [ 100, 500, 2500, ]; private static var level_costs:Array = [ 300, 1500, 7500, ]; private static var __current_level__:int = 0; public static function get current_level():int { return __current_level__; } public static function set current_level(level:int):void { if (__current_level__ != level) { __current_level__ = level; } } public static function next_level():void { __current_level__++; var app:GalaxyWars = FlexGlobals.topLevelApplication as GalaxyWars; app.mySO.data.__solar_resource_level__ = __current_level__; app.mySO.flush(); } public static function get current_level_production_rate():Number { try { return level_rates[current_level]; } catch (err:Error) {} return -1; } public static function get current_level_upgrade_cost():Number { try { return level_costs[current_level]; } catch (err:Error) {} return -1; } public static function get current_level_upgrade_time():Number { return ResourceFactory.current_level_upgrade_time(current_level); } } }
package com.ankamagames.dofus.network.messages.game.inventory.exchanges { import com.ankamagames.dofus.network.types.game.mount.MountClientData; 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.utils.FuncTree; import flash.utils.ByteArray; public class ExchangeMountsStableBornAddMessage extends ExchangeMountsStableAddMessage implements INetworkMessage { public static const protocolId:uint = 1340; private var _isInitialized:Boolean = false; public function ExchangeMountsStableBornAddMessage() { super(); } override public function get isInitialized() : Boolean { return super.isInitialized && this._isInitialized; } override public function getMessageId() : uint { return 1340; } public function initExchangeMountsStableBornAddMessage(mountDescription:Vector.<MountClientData> = null) : ExchangeMountsStableBornAddMessage { super.initExchangeMountsStableAddMessage(mountDescription); this._isInitialized = true; return this; } override public function reset() : void { super.reset(); 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; } override public function serialize(output:ICustomDataOutput) : void { this.serializeAs_ExchangeMountsStableBornAddMessage(output); } public function serializeAs_ExchangeMountsStableBornAddMessage(output:ICustomDataOutput) : void { super.serializeAs_ExchangeMountsStableAddMessage(output); } override public function deserialize(input:ICustomDataInput) : void { this.deserializeAs_ExchangeMountsStableBornAddMessage(input); } public function deserializeAs_ExchangeMountsStableBornAddMessage(input:ICustomDataInput) : void { super.deserialize(input); } override public function deserializeAsync(tree:FuncTree) : void { this.deserializeAsyncAs_ExchangeMountsStableBornAddMessage(tree); } public function deserializeAsyncAs_ExchangeMountsStableBornAddMessage(tree:FuncTree) : void { super.deserializeAsync(tree); } } }
package com.ankamagames.jerakine.utils.errors { public class SignatureError extends Error { public static const INVALID_HEADER:uint = 1; public static const INVALID_SIGNATURE:uint = 2; public function SignatureError(message:* = "", id:* = 0) { super(message,id); } } }
package net.nobien.utils { /** * The StringUtil class contains static utility methods for manipulating Strings. */ public class StringUtil { /** * Removes whitespace from the front and the end of the specified string. * @param input The String whose beginning and ending whitespace will will be removed. * @return A String with whitespace removed from the begining and end */ public static function trim( input:String ):String { return StringUtil.ltrim( StringUtil.rtrim( input ) ); } /** * Removes whitespace from the front of the specified string. * @param input The String whose beginning whitespace will will be removed. * @return A String with whitespace removed from the begining */ public static function ltrim( input:String ):String { var size:Number = input.length; for ( var i:Number = 0; i < size; i++ ) { if( input.charCodeAt( i ) > 32 ) { return input.substring( i ); } } return ""; } /** * Removes whitespace from the end of the specified string. * @param input The String whose ending whitespace will will be removed. * @return A String with whitespace removed from the end */ public static function rtrim( input:String ):String { var size:Number = input.length; for ( var i:Number = size; i > 0; i--) { if( input.charCodeAt( i - 1 ) > 32 ) { return input.substring( 0, i ); } } return ""; } /** * Removes all instances of the remove string in the input string. * @param input The string that will be checked for instances of remove string. * @param remove The string that will be removed from the input string. * @return A String with the remove string removed. */ public static function remove( input:String, remove:String ):String { return StringUtil.replace( input, remove, "" ); } /** * Removes all hidden line breaks from the content string. * @param str The string that will have the line breaks removed. * @return A String with line breaks removed. */ static public function removeLineBreaks( str:String ):String { var pcLB:RegExp = /\r\n/g; var macLB:RegExp = /\r/g; var linuxLB:RegExp = /\n/g; str = str.replace( pcLB, "" ); str = str.replace( macLB, "" ); str = str.replace( linuxLB, "" ); return str; } /** * Replaces all instances of the replace string in the input string with the replaceWith string. * @param input The string that instances of replace string will be replaces with removeWith string. * @param replace The string that will be replaced by instances of the replaceWith string. * @param replaceWith The string that will replace instances of replace string. * @return A new String with the replace string replaced with the replaceWith string. */ public static function replace( input:String, replace:String, replaceWith:String ):String { var sb:String = new String(); var found:Boolean = false; var sLen:Number = input.length; var rLen:Number = replace.length; for ( var i:Number = 0; i < sLen; i++ ) { if ( input.charAt( i ) == replace.charAt( 0 ) ) { found = true; for ( var j:Number = 0; j < rLen; j++ ) { if ( !( input.charAt( i + j ) == replace.charAt( j ) ) ) { found = false; break; } } if ( found ) { sb += replaceWith; i = i + ( rLen - 1 ); continue; } } sb += input.charAt( i ); } return sb; } } }
/* * Temple Library for ActionScript 3.0 * Copyright © MediaMonks B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by MediaMonks B.V. * 4. Neither the name of MediaMonks B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY MEDIAMONKS B.V. ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL MEDIAMONKS B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Note: This license does not apply to 3rd party classes inside the Temple * repository with their own license! */ package temple.ui.buttons { import temple.core.debug.IDebuggable; import temple.core.display.CoreMovieClip; import temple.ui.buttons.behaviors.ButtonStateBehavior; import temple.ui.buttons.behaviors.ButtonTimelineBehavior; import temple.ui.buttons.behaviors.ButtonTimelinePlayMode; /** * A MultiStateElement can be used inside a <code>MultiStateButton</code>. Is will automatically respond to the * state of the <code>MultiStateButton</code> and will show the same state. * * <p>A MultiStateElement can be nested inside objects which has a <code>ButtonBehavior</code>. Nesting means that * it is placed on the timeline of an object. But also on the timeline of a child or grand-child of the object. * There can be an unlimited amount of sub-children between the object and the MultiStateElement.</p> * * <p>The Temple knows different kinds of buttons. Check out the * <a href="http://templelibrary.googlecode.com/svn/trunk/modules/ui/readme.html" target="_blank">button schema</a> * in the UI Module of the Temple for a list of all available buttons which their features. </p> * * @see temple.ui.buttons.behaviors.ButtonBehavior * @see ../../../../readme.html * * @author Thijs Broerse */ public class MultiStateElement extends CoreMovieClip implements IDebuggable { private var _timelineBehavior:ButtonTimelineBehavior; private var _stateBehavior:ButtonStateBehavior; public function MultiStateElement() { super(); stop(); if (totalFrames > 1) _timelineBehavior = new ButtonTimelineBehavior(this); _stateBehavior = new ButtonStateBehavior(this); } /** * Returns a reference to the ButtonTimelineBehavior */ public function get buttonTimelineBehavior():ButtonTimelineBehavior { return _timelineBehavior; } /** * Returns a reference to the ButtonTimelineBehavior */ public function get buttonStateBehavior():ButtonStateBehavior { return _stateBehavior; } /** * Define how the timeline should be played when the ButtonTimelineBehavior must go to an other label. * More specific playModes for every state can be set on the buttonTimelineBehavior * * @see temple.ui.buttons.behaviors.ButtonTimelinePlayMode * @see temple.ui.buttons.behaviors.ButtonTimelineBehavior */ public function get playMode():ButtonTimelinePlayMode { return _timelineBehavior ? _timelineBehavior.playMode : null; } /** * @private */ [Inspectable(name="PlayMode", type="String", defaultValue="reversed", enumeration="reversed,continue,immediately")] public function set playMode(value:*):void { if (_timelineBehavior) _timelineBehavior.playMode = value; } /** * @inheritDoc */ override public function destruct():void { _timelineBehavior = null; _stateBehavior = null; super.destruct(); } } }
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2003-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 mx.containers { import flash.display.DisplayObject; import flash.events.Event; import flash.events.FocusEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.geom.Rectangle; import flash.ui.Keyboard; import mx.automation.IAutomationObject; import mx.containers.accordionClasses.AccordionHeader; import mx.controls.Button; import mx.core.ClassFactory; import mx.core.ComponentDescriptor; import mx.core.Container; import mx.core.ContainerCreationPolicy; import mx.core.EdgeMetrics; import mx.core.IDataRenderer; import mx.core.IDeferredContentOwner; import mx.core.IFactory; import mx.core.IInvalidating; import mx.core.INavigatorContent; import mx.core.IUIComponent; import mx.core.ScrollPolicy; import mx.core.UIComponent; import mx.core.mx_internal; import mx.effects.Effect; import mx.effects.Tween; import mx.events.ChildExistenceChangedEvent; import mx.events.FlexEvent; import mx.events.IndexChangedEvent; import mx.geom.RoundedRectangle; import mx.managers.HistoryManager; import mx.managers.IFocusManagerComponent; import mx.managers.IHistoryManagerClient; import mx.styles.CSSStyleDeclaration; use namespace mx_internal; [RequiresDataBinding(true)] [IconFile("Accordion.png")] /** * Dispatched when the selected child container changes. * * @eventType mx.events.IndexChangedEvent.CHANGE * @helpid 3012 * @tiptext change event * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name="change", type="mx.events.IndexChangedEvent")] //-------------------------------------- // Styles //-------------------------------------- /** * Name of the CSS style declaration that specifies styles for the accordion * headers (tabs). * * <p>You can use this class selector to set the values of all the style properties * of the AccordionHeader class, including <code>fillAlphas</code>, <code>fillColors</code>, * <code>focusAlpha</code>, <code>focusRounderCorners</code>, * <code>focusSkin</code>, <code>focusThickness</code>, and <code>selectedFillColors</code>.</p> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="headerStyleName", type="String", inherit="no")] /** * Number of pixels between children in the horizontal direction. * The default value is 8. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="horizontalGap", type="Number", format="Length", inherit="no")] /** * Height of each accordion header, in pixels. * The default value is automatically calculated based on the font styles for * the header. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="headerHeight", type="Number", format="Length", inherit="no")] /** * Duration, in milliseconds, of the animation from one child to another. * * The default value for the Halo theme is 250. * The default value for the Spark theme is 0. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="openDuration", type="Number", format="Time", inherit="no")] /** * Tweening function used by the animation from one child to another. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="openEasingFunction", type="Function", inherit="no")] /** * Number of pixels between the container's bottom border and its content area. * The default value is -1, so the bottom border of the last header * overlaps the Accordion container's bottom border. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="paddingBottom", type="Number", format="Length", inherit="no")] /** * Number of pixels between the container's top border and its content area. * The default value is -1, so the top border of the first header * overlaps the Accordion container's top border. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="paddingTop", type="Number", format="Length", inherit="no")] /** * Color of header text when rolled over. * * The default value for the Halo theme is <code>0x2B333C</code>. * The default value for the Spark theme is <code>0x000000</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="textRollOverColor", type="uint", format="Color", inherit="yes")] /** * Color of selected text. * * The default value for the Halo theme is <code>0x2B333C</code>. * The default value for the Spark theme is <code>0x000000</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="textSelectedColor", type="uint", format="Color", inherit="yes")] /** * Number of pixels between children in the vertical direction. * The default value is -1, so the top and bottom borders * of adjacent headers overlap. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="verticalGap", type="Number", format="Length", inherit="no")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name="autoLayout", kind="property")] [Exclude(name="clipContent", kind="property")] [Exclude(name="defaultButton", kind="property")] [Exclude(name="horizontalLineScrollSize", kind="property")] [Exclude(name="horizontalPageScrollSize", kind="property")] [Exclude(name="horizontalScrollBar", kind="property")] [Exclude(name="horizontalScrollPolicy", kind="property")] [Exclude(name="horizontalScrollPosition", kind="property")] [Exclude(name="maxHorizontalScrollPosition", kind="property")] [Exclude(name="maxVerticalScrollPosition", kind="property")] [Exclude(name="verticalLineScrollSize", kind="property")] [Exclude(name="verticalPageScrollSize", kind="property")] [Exclude(name="verticalScrollBar", kind="property")] [Exclude(name="verticalScrollPolicy", kind="property")] [Exclude(name="verticalScrollPosition", kind="property")] [Exclude(name="scroll", kind="event")] /* [Exclude(name="focusBlendMode", kind="style")] */ [Exclude(name="horizontalScrollBarStyleName", kind="style")] [Exclude(name="verticalScrollBarStyleName", kind="style")] [Exclude(name="focusSkin", kind="style")] [Exclude(name="focusThickness", kind="style")] //-------------------------------------- // Other metadata //-------------------------------------- [DefaultBindingProperty(source="selectedIndex", destination="selectedIndex")] [DefaultTriggerEvent("change")] /** * An MX Accordion navigator container has a collection of child MX containers * or Spark NavigatorContent containers, but only one of them at a time is visible. * It creates and manages navigator buttons (accordion headers), which you use * to navigate between the children. * There is one navigator button associated with each child container, * and each navigator button belongs to the Accordion container, not to the child. * When the user clicks a navigator button, the associated child container * is displayed. * The transition to the new child uses an animation to make it clear to * the user that one child is disappearing and a different one is appearing. * * <p><b>Note:</b> The direct children of an MX navigator container must be * MX containers, either MX layout or MX navigator containers, * or the Spark NavigatorContent container. * You cannot directly nest a control or a Spark container * other than the Spark NavigatorContent container within a navigator; * they must be children of an child MX container.</p> * * <p>The Accordion container does not extend the ViewStack container, * but it implements all the properties, methods, styles, and events * of the ViewStack container, such as <code>selectedIndex</code> * and <code>selectedChild</code>.</p> * * <p>An Accordion container has the following default sizing characteristics:</p> * <table class="innertable"> * <tr> * <th>Characteristic</th> * <th>Description</th> * </tr> * <tr> * <td>Default size</td> * <td>The width and height of the currently active child.</td> * </tr> * <tr> * <td>Container resizing rules</td> * <td>Accordion containers are only sized once to fit the size of the first child container by default. * They do not resize when you navigate to other child containers by default. * To force Accordion containers to resize when you navigate to a different child container, * set the resizeToContent property to true.</td> * </tr> * <tr> * <td>Child sizing rules</td> * <td>Children are sized to their default size. The child is clipped if it is larger than the Accordion container. * If the child is smaller than the Accordion container, it is aligned to the upper-left corner of the * Accordion container.</td> * </tr> * <tr> * <td>Default padding</td> * <td>-1 pixel for the top, bottom, left, and right values.</td> * </tr> * </table> * * @mxml * * <p>The <code>&lt;mx:Accordion&gt;</code> tag inherits all of the * tag attributes of its superclass, with the exception of scrolling-related * attributes, and adds the following tag attributes:</p> * * <pre> * &lt;mx:Accordion * <strong>Properties</strong> * headerRenderer="<i>IFactory</i>" * historyManagementEnabled="true|false" * resizeToContent="false|true" * selectedChild"<i>A reference to the first child</i>" * selectedIndex="undefined" * * <strong>Styles</strong> * headerHeight="depends on header font styles" * headerStyleName="<i>No default</i>" * horizontalGap="8" * openDuration="250" * openEasingFunction="undefined" * paddingBottom="-1" * paddingTop="-1" * textRollOverColor="0xB333C" * textSelectedColor="0xB333C" * verticalGap="-1" * * <strong>Events</strong> * change="<i>No default</i>" * &gt; * ... * <i>child tags</i> * ... * &lt;/mx:Accordion&gt; * </pre> * * @includeExample examples/AccordionExample.mxml * * @see mx.containers.accordionClasses.AccordionHeader * * @tiptext Accordion allows for navigation between different child views * @helpid 3013 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class Accordion extends Container implements IHistoryManagerClient, IFocusManagerComponent { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @private * Base for all header names (_header0 - _headerN). */ private static const HEADER_NAME_BASE:String = "_header"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function Accordion() { super(); headerRenderer = new ClassFactory(AccordionHeader); // Most views can't take focus, but an accordion can. // However, it draws its own focus indicator on the // header for the currently selected child view. // Container() has set tabEnabled false, so we // have to set it back to true. tabEnabled = true; tabFocusEnabled = true; hasFocusableChildren = true; // Accordion always clips content, it just handles it by itself super.clipContent = false; addEventListener(ChildExistenceChangedEvent.CHILD_ADD, childAddHandler); addEventListener(ChildExistenceChangedEvent.CHILD_REMOVE, childRemoveHandler); showInAutomationHierarchy = true; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Is the accordian currently sliding between views? */ private var bSliding:Boolean = false; /** * @private */ private var initialSelectedIndex:int = -1; /** * @private * If true, call HistoryManager.save() when setting currentIndex. */ private var bSaveState:Boolean = false; /** * @private */ private var bInLoadState:Boolean = false; /** * @private */ private var firstTime:Boolean = true; /** * @private */ private var showFocusIndicator:Boolean = false; /** * @private * Cached tween properties to speed up tweening calculations. */ private var tweenViewMetrics:EdgeMetrics; private var tweenContentWidth:Number; private var tweenContentHeight:Number; private var tweenOldSelectedIndex:int; private var tweenNewSelectedIndex:int; private var tween:Tween; /** * @private * We'll measure ourselves once and then store the results here * for the lifetime of the ViewStack. */ private var accMinWidth:Number; private var accMinHeight:Number; private var accPreferredWidth:Number; private var accPreferredHeight:Number; /** * @private * When a child is added or removed, this flag is set true * and it causes a re-measure. */ private var childAddedOrRemoved:Boolean = false; /** * @private * Remember which child has an overlay mask, if any. */ private var overlayChild:IUIComponent; /** * @private * Keep track of the overlay's targetArea */ private var overlayTargetArea:RoundedRectangle; /** * @private */ private var layoutStyleChanged:Boolean = false; /** * @private */ private var currentDissolveEffect:Effect; //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- //---------------------------------- // autoLayout //---------------------------------- // Don't allow user to set autoLayout because // there are problems if deferred instantiation // runs at the same time as an effect. (Bug 79174) [Inspectable(environment="none")] /** * @private */ override public function get autoLayout():Boolean { return true; } /** * @private */ override public function set autoLayout(value:Boolean):void { } //---------------------------------- // baselinePosition //---------------------------------- /** * @private * The baselinePosition of an Accordion is calculated * for the label of the first header. * If there are no children, a child is temporarily added * to do the computation. */ override public function get baselinePosition():Number { if (!validateBaselinePosition()) return NaN; var isEmpty:Boolean = numChildren == 0; if (isEmpty) { var child0:Container = new Container(); addChild(child0); validateNow(); } var header0:Button = getHeaderAt(0); var result:Number = header0.y + header0.baselinePosition; if (isEmpty) { removeChildAt(0); validateNow(); } return result; } //---------------------------------- // clipContent //---------------------------------- // We still need to ensure the clip mask is *never* created for an // Accordion. [Inspectable(environment="none")] /** * @private */ override public function get clipContent():Boolean { return true; // Accordion does clip, it just does it itself } /** * @private */ override public function set clipContent(value:Boolean):void { } //---------------------------------- // horizontalScrollPolicy //---------------------------------- [Inspectable(environment="none")] /** * @private */ override public function get horizontalScrollPolicy():String { return ScrollPolicy.OFF; } /** * @private */ override public function set horizontalScrollPolicy(value:String):void { } //---------------------------------- // verticalScrollPolicy //---------------------------------- [Inspectable(environment="none")] /** * @private */ override public function get verticalScrollPolicy():String { return ScrollPolicy.OFF; } /** * @private */ override public function set verticalScrollPolicy(value:String):void { } //-------------------------------------------------------------------------- // // Public properties // //-------------------------------------------------------------------------- /** * @private */ private var _focusedIndex:int = -1; /** * @private */ mx_internal function get focusedIndex():int { return _focusedIndex; } //---------------------------------- // contentHeight //---------------------------------- /** * The height of the area, in pixels, in which content is displayed. * You can override this getter if your content * does not occupy the entire area of the container. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get contentHeight():Number { // Start with the height of the entire accordion. var contentHeight:Number = unscaledHeight; // Subtract the heights of the top and bottom borders. var vm:EdgeMetrics = viewMetricsAndPadding; contentHeight -= vm.top + vm.bottom; // Subtract the header heights. var verticalGap:Number = getStyle("verticalGap"); var n:int = numChildren; for (var i:int = 0; i < n; i++) { contentHeight -= getHeaderAt(i).height; if (i > 0) contentHeight -= verticalGap; } return contentHeight; } //---------------------------------- // contentWidth //---------------------------------- /** * The width of the area, in pixels, in which content is displayed. * You can override this getter if your content * does not occupy the entire area of the container. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get contentWidth():Number { // Start with the width of the entire accordion. var contentWidth:Number = unscaledWidth; // Subtract the widths of the left and right borders. var vm:EdgeMetrics = viewMetricsAndPadding; contentWidth -= vm.left + vm.right; contentWidth -= getStyle("paddingLeft") + getStyle("paddingRight"); return contentWidth; } //---------------------------------- // headerRenderer //---------------------------------- /** * @private * Storage for the headerRenderer property. */ private var _headerRenderer:IFactory; [Bindable("headerRendererChanged")] /** * A factory used to create the navigation buttons for each child. * The default value is a factory which creates a * <code>mx.containers.accordionClasses.AccordionHeader</code>. The * created object must be a subclass of Button and implement the * <code>mx.core.IDataRenderer</code> interface. The <code>data</code> * property is set to the content associated with the header. * * @see mx.containers.accordionClasses.AccordionHeader * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get headerRenderer():IFactory { return _headerRenderer; } /** * @private */ public function set headerRenderer(value:IFactory):void { _headerRenderer = value; dispatchEvent(new Event("headerRendererChanged")); } //---------------------------------- // historyManagementEnabled //---------------------------------- /** * @private * Storage for historyManagementEnabled property. */ private var _historyManagementEnabled:Boolean = true; /** * @private */ private var historyManagementEnabledChanged:Boolean = false; [Inspectable(defaultValue="true")] /** * If set to <code>true</code>, this property enables history management * within this Accordion container. * As the user navigates from one child to another, * the browser remembers which children were visited. * The user can then click the browser's Back and Forward buttons * to move through this navigation history. * * @default true * * @see mx.managers.HistoryManager * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get historyManagementEnabled():Boolean { return _historyManagementEnabled; } /** * @private */ public function set historyManagementEnabled(value:Boolean):void { if (value != _historyManagementEnabled) { _historyManagementEnabled = value; historyManagementEnabledChanged = true; invalidateProperties(); } } //---------------------------------- // resizeToContent //---------------------------------- /** * @private * Storage for the resizeToContent property. */ private var _resizeToContent:Boolean = false; [Inspectable(defaultValue="false")] /** * If set to <code>true</code>, this Accordion automatically resizes to * the size of its current child. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get resizeToContent():Boolean { return _resizeToContent; } /** * @private */ public function set resizeToContent(value:Boolean):void { if (value != _resizeToContent) { _resizeToContent = value; if (value) invalidateSize(); } } //---------------------------------- // selectedChild //---------------------------------- [Bindable("valueCommit")] /** * A reference to the currently visible child container. * The default value is a reference to the first child. * If there are no children, this property is <code>null</code>. * * <p><b>Note:</b> You can only set this property in an ActionScript statement, * not in MXML.</p> * * @tiptext Specifies the child view that is currently displayed * @helpid 3401 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectedChild():INavigatorContent { if (selectedIndex == -1) return null; return INavigatorContent(getChildAt(selectedIndex)); } /** * @private */ public function set selectedChild(value:INavigatorContent):void { var newIndex:int = getChildIndex(DisplayObject(value)); if (newIndex >= 0 && newIndex < numChildren) selectedIndex = newIndex; } //---------------------------------- // selectedIndex //---------------------------------- /** * @private * Storage for the selectedIndex and selectedChild properties. */ private var _selectedIndex:int = -1; /** * @private */ private var proposedSelectedIndex:int = -1; [Bindable("valueCommit")] [Inspectable(category="General", defaultValue="0")] /** * The zero-based index of the currently visible child container. * Child indexes are in the range 0, 1, 2, ..., n - 1, where n is the number * of children. * The default value is 0, corresponding to the first child. * If there are no children, this property is <code>-1</code>. * * @default 0 * * @tiptext Specifies the index of the child view that is currently displayed * @helpid 3402 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectedIndex():int { if (proposedSelectedIndex != -1) return proposedSelectedIndex; return _selectedIndex; } /** * @private */ public function set selectedIndex(value:int):void { // Bail if new index isn't a number. if (value == -1) return; // Bail if the index isn't changing. if (value == _selectedIndex) return; // Propose the specified value as the new value for selectedIndex. // It gets applied later when commitProperties() calls commitSelectedIndex(). // The proposed value can be "out of range", because the children // may not have been created yet, so the range check is handled // in commitSelectedIndex(), not here. Other calls to this setter // can change the proposed index before it is committed. Also, // childAddHandler() proposes a value of 0 when it creates the first // child, if no value has yet been proposed. proposedSelectedIndex = value; invalidateProperties(); // Set a flag which will cause the History Manager to save state // the next time measure() is called. if (historyManagementEnabled && _selectedIndex != -1 && !bInLoadState) bSaveState = true; dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ override public function createComponentsFromDescriptors( recurse:Boolean = true):void { // The easiest way to handle the ContainerCreationPolicy.ALL policy is to let // Container's implementation of createComponents handle it. if (actualCreationPolicy == ContainerCreationPolicy.ALL) { super.createComponentsFromDescriptors(); return; } // If the policy is ContainerCreationPolicy.AUTO, Accordion instantiates its children // immediately, but not any grandchildren. The children of // the selected child will get created in instantiateSelectedChild(). // Why not create the grandchildren of the selected child by calling // createComponentFromDescriptor(childDescriptors[i], i == selectedIndex); // in the loop below? Because one of this Accordion's childDescriptors // may be for a Repeater, in which case the following loop over the // childDescriptors is not the same as a loop over the children. // In particular, selectedIndex is supposed to specify the nth // child, not the nth childDescriptor, and the 2nd parameter of // createComponentFromDescriptor() should make the recursion happen // on the nth child, not the nth childDescriptor. var numChildrenBefore:int = numChildren; if (childDescriptors) { var n:int = childDescriptors.length; for (var i:int = 0; i < n; i++) { var descriptor:ComponentDescriptor = ComponentDescriptor(childDescriptors[i]); createComponentFromDescriptor(descriptor, false); } } numChildrenCreated = numChildren - numChildrenBefore; processedDescriptors = true; } /** * @private */ override public function setChildIndex(child:DisplayObject, newIndex:int):void { var oldIndex:int = getChildIndex(child); // Check boundary conditions first if (oldIndex == -1 || newIndex < 0) return; var nChildren:int = numChildren; if (newIndex >= nChildren) newIndex = nChildren - 1; // Next, check for no move if (newIndex == oldIndex) return; // De-select the old selected index header var oldSelectedHeader:Button = getHeaderAt(selectedIndex); if (oldSelectedHeader) { oldSelectedHeader.selected = false; drawHeaderFocus(_focusedIndex, false); } // Adjust the depths and _childN references of the affected children. super.setChildIndex(child, newIndex); // Shuffle the headers shuffleHeaders(oldIndex, newIndex); // Select the new selected index header var newSelectedHeader:Button = getHeaderAt(selectedIndex); if (newSelectedHeader) { newSelectedHeader.selected = true; drawHeaderFocus(_focusedIndex, showFocusIndicator); } // Make sure the new selected child is instantiated instantiateChild(selectedChild); } /** * @private */ private function shuffleHeaders(oldIndex:int, newIndex:int):void { var i:int; // Adjust the _headerN references of the affected headers. // Note: Algorithm is the same as Container.setChildIndex(). var header:Button = getHeaderAt(oldIndex); if (newIndex < oldIndex) { for (i = oldIndex; i > newIndex; i--) { getHeaderAt(i - 1).name = HEADER_NAME_BASE + i; } } else { for (i = oldIndex; i < newIndex; i++) { getHeaderAt(i + 1).name = HEADER_NAME_BASE + i; } } header.name = HEADER_NAME_BASE + newIndex; } /** * @private */ override protected function commitProperties():void { super.commitProperties(); if (historyManagementEnabledChanged) { if (historyManagementEnabled) HistoryManager.register(this); else HistoryManager.unregister(this); historyManagementEnabledChanged = false; } commitSelectedIndex(); if (firstTime) { firstTime = false; // Add "addedToStage" and "removedFromStage" listeners so we can // register/un-register from the history manager when this component // is added or removed from the display list. addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler, false, 0, true); addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler, false, 0, true); } } /** * @private */ override protected function measure():void { super.measure(); var minWidth:Number = 0; var minHeight:Number = 0; var preferredWidth:Number = 0; var preferredHeight:Number = 0; var paddingLeft:Number = getStyle("paddingLeft"); var paddingRight:Number = getStyle("paddingRight"); var headerHeight:Number = getHeaderHeight(); // In general, we only measure once and thereafter use cached values. // There are three exceptions: when resizeToContent is true, // when a layout style like headerHeight changes, // and when a child is added or removed. // // We need to copy the cached values into the measured fields // again to handle the case where scaleX or scaleY is not 1.0. // When the Accordion is zoomed, code in UIComponent.measureSizes // scales the measuredWidth/Height values every time that // measureSizes is called. (bug 100749) if (accPreferredWidth && !_resizeToContent && !layoutStyleChanged && !childAddedOrRemoved) { measuredMinWidth = accMinWidth; measuredMinHeight = accMinHeight; measuredWidth = accPreferredWidth; measuredHeight = accPreferredHeight; return; } layoutStyleChanged = false; childAddedOrRemoved = false; var n:int = numChildren; for (var i:int = 0; i < n; i++) { var button:Button = getHeaderAt(i); var child:IUIComponent = getLayoutChildAt(i); minWidth = Math.max(minWidth, button.minWidth); minHeight += headerHeight; preferredWidth = Math.max(preferredWidth, minWidth); preferredHeight += headerHeight; // The headers preferredWidth is messing up the accordion measurement. This may not // be needed anyway because we're still using the headers minWidth to determine our overall // minWidth. if (i == selectedIndex) { preferredWidth = Math.max(preferredWidth, child.getExplicitOrMeasuredWidth()); preferredHeight += child.getExplicitOrMeasuredHeight(); minWidth = Math.max(minWidth, child.minWidth); minHeight += child.minHeight; } } // Add space for borders and margins var vm:EdgeMetrics = viewMetricsAndPadding; var widthPadding:Number = vm.left + vm.right; var heightPadding:Number = vm.top + vm.bottom; // Need to adjust the widthPadding if paddingLeft and paddingRight are negative numbers // (see explanation in updateDisplayList()) if (paddingLeft < 0) widthPadding -= paddingLeft; if (paddingRight < 0) widthPadding -= paddingRight; minWidth += widthPadding; preferredWidth += widthPadding; minHeight += heightPadding; preferredHeight += heightPadding; measuredMinWidth = minWidth; measuredMinHeight = minHeight; measuredWidth = preferredWidth; measuredHeight = preferredHeight; // If we're called before instantiateSelectedChild, then bail. // We'll be called again later (instantiateSelectedChild calls // invalidateSize), and we don't want to load values into the // cache until we're fully initialized. (bug 102639) // This check was moved from the beginning of this function to // here to fix bugs 103665/104213. if (selectedChild && INavigatorContent(selectedChild).deferredContentCreated == false) return; // Don't remember sizes if we don't have any children if (numChildren == 0) return; accMinWidth = minWidth; accMinHeight = minHeight; accPreferredWidth = preferredWidth; accPreferredHeight = preferredHeight; } /** * @private * Arranges the layout of the accordion contents. * * @tiptext Arranges the layout of the Accordion's contents * @helpid 3017 */ override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); // Don't do layout if we're tweening because the tweening // code is handling it. if (tween) return; // Measure the border. var bm:EdgeMetrics = borderMetrics; var paddingLeft:Number = getStyle("paddingLeft"); var paddingRight:Number = getStyle("paddingRight"); var paddingTop:Number = getStyle("paddingTop"); var verticalGap:Number = getStyle("verticalGap"); // Determine the width and height of the content area. var localContentWidth:Number = calcContentWidth(); var localContentHeight:Number = calcContentHeight(); // Arrange the headers, the content clips, // based on selectedIndex. var x:Number = bm.left + paddingLeft; var y:Number = bm.top + paddingTop; // Adjustments. These are required since the default halo // appearance has verticalGap and all margins set to -1 // so the edges of the headers overlap each other and the // border of the accordion. These overlaps cause problems with // the content area clipping, so we adjust for them here. var contentX:Number = x; var adjContentWidth:Number = localContentWidth; var headerHeight:Number = getHeaderHeight(); if (paddingLeft < 0) { contentX -= paddingLeft; adjContentWidth += paddingLeft; } if (paddingRight < 0) adjContentWidth += paddingRight; var n:int = numChildren; for (var i:int = 0; i < n; i++) { var header:Button = getHeaderAt(i); var content:IUIComponent = getLayoutChildAt(i); header.move(x, y); header.setActualSize(localContentWidth, headerHeight); y += headerHeight; if (i == selectedIndex) { content.move(contentX, y); content.visible = true; var contentW:Number = adjContentWidth; var contentH:Number = localContentHeight; if (!isNaN(content.percentWidth)) { if (contentW > content.maxWidth) contentW = content.maxWidth; } else { if (contentW > content.getExplicitOrMeasuredWidth()) contentW = content.getExplicitOrMeasuredWidth(); } if (!isNaN(content.percentHeight)) { if (contentH > content.maxHeight) contentH = content.maxHeight; } else { if (contentH > content.getExplicitOrMeasuredHeight()) contentH = content.getExplicitOrMeasuredHeight(); } if (content.width != contentW || content.height != contentH) { content.setActualSize(contentW, contentH); } y += localContentHeight; } else { content.move(contentX, i < selectedIndex ? y : y - localContentHeight); content.visible = false; } y += verticalGap; } // Make sure blocker is in front if (blocker) rawChildren.setChildIndex(blocker, numChildren - 1); // refresh the focus rect, the dimensions might have changed. drawHeaderFocus(_focusedIndex, showFocusIndicator); } /** * @private */ override mx_internal function setActualCreationPolicies(policy:String):void { super.setActualCreationPolicies(policy); // If the creation policy is switched to ContainerCreationPolicy.ALL and our createComponents // function has already been called (we've created our children but not // all our grandchildren), then create all our grandchildren now (bug 99160). if (policy == ContainerCreationPolicy.ALL && numChildren > 0) { var n:int = numChildren; for (var i:int = 0; i < n; i++) { IDeferredContentOwner(getChildAt(i)).createDeferredContent(); } } } /** * @private */ override protected function focusInHandler(event:FocusEvent):void { super.focusInHandler(event); showFocusIndicator = focusManager.showFocusIndicator; // When the accordion has focus, the Focus Manager // should not treat the Enter key as a click on // the default pushbutton. if (event.target == this) focusManager.defaultButtonEnabled = false; } /** * @private */ override protected function focusOutHandler(event:FocusEvent):void { super.focusOutHandler(event); showFocusIndicator = false; if (focusManager && event.target == this) focusManager.defaultButtonEnabled = true; } /** * @private */ override public function drawFocus(isFocused:Boolean):void { drawHeaderFocus(_focusedIndex, isFocused); } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); if (!styleProp || styleProp == "headerStyleName" || styleProp == "styleName") { var headerStyleName:Object = getStyle("headerStyleName"); var header:Button; if (headerStyleName) { for (var j:int = 0; j < numChildren; j++) { header = getHeaderAt(j); if (header) { header.styleName = headerStyleName; } } } } else if (styleManager.isSizeInvalidatingStyle(styleProp)) { layoutStyleChanged = true; } } /** * @private * When asked to create an overlay mask, create it on the selected child * instead. That way, the chrome around the edge of the Accordion (e.g. the * header buttons) is not occluded by the overlay mask (bug 99029). */ override mx_internal function addOverlay(color:uint, targetArea:RoundedRectangle = null):void { // As we're switching the currently-selected child, don't // allow two children to both have an overlay at the same time. // This is done because it makes accounting a headache. If there's // a legitimate reason why two children both need overlays, this // restriction could be relaxed. if (overlayChild) removeOverlay(); // Remember which child has an overlay, so that we don't inadvertently // create an overlay on one child and later try to remove the overlay // of another child. (bug 100731) overlayChild = selectedChild as IUIComponent; if (!overlayChild) return; effectOverlayColor = color; overlayTargetArea = targetArea; if (selectedChild && selectedChild.deferredContentCreated == false) // No children have been created { // Wait for the childrenCreated event before creating the overlay selectedChild.addEventListener(FlexEvent.INITIALIZE, initializeHandler); } else // Children already exist { initializeHandler(null); } } /** * @private * Called when we are running a Dissolve effect * and the initialize event has been dispatched * or the children already exist */ private function initializeHandler(event:FlexEvent):void { UIComponent(overlayChild).addOverlay(effectOverlayColor, overlayTargetArea); } /** * @private * Handle key down events */ override mx_internal function removeOverlay():void { if (overlayChild) { UIComponent(overlayChild).removeOverlay(); overlayChild = null; } } // ------------------------------------------------------------------------- // StateInterface // ------------------------------------------------------------------------- /** * @copy mx.managers.IHistoryManagerClient#saveState() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function saveState():Object { var index:int = _selectedIndex == -1 ? 0 : _selectedIndex; return { selectedIndex: index }; } /** * @copy mx.managers.IHistoryManagerClient#loadState() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function loadState(state:Object):void { var newIndex:int = state ? int(state.selectedIndex) : 0; if (newIndex == -1) newIndex = initialSelectedIndex; if (newIndex == -1) newIndex = 0; if (newIndex != _selectedIndex) { // When loading a new state, we don't want to // save our current state in the history stack. bInLoadState = true; selectedIndex = newIndex; bInLoadState = false; } } //-------------------------------------------------------------------------- // // Public methods // //-------------------------------------------------------------------------- /** * Returns a reference to the navigator button for a child container. * * @param index Zero-based index of the child. * * @return Button object representing the navigator button. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function getHeaderAt(index:int):Button { return Button(rawChildren.getChildByName(HEADER_NAME_BASE + index)); } /** * @private * Returns the height of the header control. All header controls are the same * height. */ private function getHeaderHeight():Number { var headerHeight:Number = getStyle("headerHeight"); if (isNaN(headerHeight)) { headerHeight = 0; if (numChildren > 0) headerHeight = getHeaderAt(0).measuredHeight; } return headerHeight; } //-------------------------------------------------------------------------- // // Private methods // //-------------------------------------------------------------------------- /** * @private * Utility method to create the segment header */ private function createHeader(content:DisplayObject, i:int):void { // Before creating the header, un-select the currently selected // header. We will be selecting the correct header below. if (selectedIndex != -1 && getHeaderAt(selectedIndex)) getHeaderAt(selectedIndex).selected = false; // Create the header. // Notes: // 1) An accordion maintains a reference to // the header for its Nth child as _headerN. These references are // juggled when children and their headers are re-indexed or // removed, to ensure that _headerN is always a reference the // header for the Nth child. // 2) Always create the header with the index of the last item. // If needed, the headers will be shuffled below. var header:Button = Button(headerRenderer.newInstance()); header.name = HEADER_NAME_BASE + (numChildren - 1); var headerStyleName:String = getStyle("headerStyleName"); if (headerStyleName) { header.styleName = headerStyleName; } header.addEventListener(MouseEvent.CLICK, headerClickHandler); IDataRenderer(header).data = content; if (content is INavigatorContent) { var contentContainer:INavigatorContent = INavigatorContent(content); header.label = contentContainer.label; if (contentContainer.icon) header.setStyle("icon", contentContainer.icon); // If the child has a toolTip, transfer it to the header. var toolTip:String = (contentContainer as UIComponent).toolTip; if (toolTip && toolTip != "") { header.toolTip = toolTip; (contentContainer as UIComponent).toolTip = null; } } rawChildren.addChild(header); // If the newly added child isn't at the end of our child list, shuffle // the headers accordingly. if (i != numChildren - 1) shuffleHeaders(numChildren - 1, i); // Make sure the correct header is selected if (selectedIndex != -1 && getHeaderAt(selectedIndex)) getHeaderAt(selectedIndex).selected = true; } /** * @private */ private function calcContentWidth():Number { // Start with the width of the entire accordion. var contentWidth:Number = unscaledWidth; // Subtract the widths of the left and right borders. var vm:EdgeMetrics = viewMetricsAndPadding; contentWidth -= vm.left + vm.right; return contentWidth; } /** * @private */ private function calcContentHeight():Number { // Start with the height of the entire accordion. var contentHeight:Number = unscaledHeight; // Subtract the heights of the top and bottom borders. var vm:EdgeMetrics = viewMetricsAndPadding; contentHeight -= vm.top + vm.bottom; // Subtract the header heights. var verticalGap:Number = getStyle("verticalGap"); var headerHeight:Number = getHeaderHeight(); var n:int = numChildren; for (var i:int = 0; i < n; i++) { contentHeight -= headerHeight; if (i > 0) contentHeight -= verticalGap; } return contentHeight; } /** * @private */ private function drawHeaderFocus(headerIndex:int, isFocused:Boolean):void { if (headerIndex != -1) getHeaderAt(headerIndex).drawFocus(isFocused); } /** * @private */ private function headerClickHandler(event:Event):void { var header:Button = Button(event.currentTarget); var oldIndex:int = selectedIndex; // content is placed onto the button so we have to access it via [] selectedChild = INavigatorContent(IDataRenderer(header).data); var newIndex:int = selectedIndex; if (oldIndex != newIndex) dispatchChangeEvent(oldIndex, newIndex, event); } /** * @private */ private function commitSelectedIndex():void { if (proposedSelectedIndex == -1) return; var newIndex:int = proposedSelectedIndex; proposedSelectedIndex = -1; // The selectedIndex must be undefined if there are no children, // even if a selectedIndex has been proposed. if (numChildren == 0) { _selectedIndex = -1; return; } // Ensure that the new index is in bounds. if (newIndex < 0) newIndex = 0; else if (newIndex > numChildren - 1) newIndex = numChildren - 1; // Remember the old index. var oldIndex:int = _selectedIndex; // Bail if the index isn't changing. if (newIndex == oldIndex) return; // If we are currently playing a Dissolve effect, end it and restart it again currentDissolveEffect = null; if (isEffectStarted) { var dissolveInstanceClass:Class = Class(systemManager.getDefinitionByName("mx.effects.effectClasses.DissolveInstance")); for (var i:int = 0; i < _effectsStarted.length; i++) { // Avoid referencing the DissolveInstance class directly, so that // we don't create an unwanted linker dependency. if (dissolveInstanceClass && _effectsStarted[i] is dissolveInstanceClass) { // If we find the dissolve, save a pointer to the parent effect and end the instance currentDissolveEffect = _effectsStarted[i].effect; _effectsStarted[i].end(); break; } } } // Unfocus the old header. if (_focusedIndex != newIndex) drawHeaderFocus(_focusedIndex, false); // Deselect the old header. if (oldIndex != -1) getHeaderAt(oldIndex).selected = false; // Commit the new index. _selectedIndex = newIndex; // Remember our initial selected index so we can // restore to our default state when the history // manager requests it. if (initialSelectedIndex == -1) initialSelectedIndex = _selectedIndex; // Select the new header. getHeaderAt(newIndex).selected = true; if (_focusedIndex != newIndex) { // Focus the new header. _focusedIndex = newIndex; drawHeaderFocus(_focusedIndex, showFocusIndicator); } if (bSaveState) { HistoryManager.save(); bSaveState = false; } if (getStyle("openDuration") == 0 || oldIndex == -1) { // Need to set the new index to be visible here // in order for effects to work. IUIComponent(getChildAt(newIndex)).setVisible(true); // Now that the effects have been triggered, we can hide the // current view until it is properly sized and positioned below. IUIComponent(getChildAt(newIndex)).setVisible(false, true); if (oldIndex != -1) IUIComponent(getChildAt(oldIndex)).setVisible(false); instantiateChild(selectedChild); } else { if (tween) tween.endTween(); startTween(oldIndex, newIndex); } } /** * @private */ private function instantiateChild(child:INavigatorContent):void { // fix for bug#137430 // when the selectedChild index is -1 (invalid value due to any reason) // selectedContainer will not be valid. Before we proceed // we need to make sure of its validity. if (!child) return; // Performance optimization: don't call createComponents if we know // that createComponents has already been called. if (child && child.deferredContentCreated == false) child.createDeferredContent(); // Do the initial measurement/layout pass for the newly-instantiated // descendants. invalidateSize(); invalidateDisplayList(); if (child is IInvalidating) IInvalidating(child).invalidateSize(); } /** * @private */ private function dispatchChangeEvent(oldIndex:int, newIndex:int, cause:Event = null):void { var indexChangeEvent:IndexChangedEvent = new IndexChangedEvent(IndexChangedEvent.CHANGE); indexChangeEvent.oldIndex = oldIndex; indexChangeEvent.newIndex = newIndex; indexChangeEvent.relatedObject = getChildAt(newIndex); indexChangeEvent.triggerEvent = cause; dispatchEvent(indexChangeEvent); } /** * @private */ private function startTween(oldSelectedIndex:int, newSelectedIndex:int):void { bSliding = true; // To improve the animation performance, we set up some invariants // used in onTweenUpdate. (Some of these, like contentHeight, are // too slow to recalculate at every tween step.) tweenViewMetrics = viewMetricsAndPadding; tweenContentWidth = calcContentWidth(); tweenContentHeight = calcContentHeight(); tweenOldSelectedIndex = oldSelectedIndex; tweenNewSelectedIndex = newSelectedIndex; // A single instance of Tween drives the animation. var openDuration:Number = getStyle("openDuration"); tween = new Tween(this, 0, tweenContentHeight, openDuration); var easingFunction:Function = getStyle("openEasingFunction") as Function; if (easingFunction != null) tween.easingFunction = easingFunction; // Ideally, all tweening should be managed by the EffectManager. Since // this tween isn't managed by the EffectManager, we need this alternate // mechanism to tell the EffectManager that we're tweening. Otherwise, the // EffectManager might try to play another effect that animates the same // properties. if (oldSelectedIndex != -1) IUIComponent(getChildAt(oldSelectedIndex)).tweeningProperties = ["x", "y", "width", "height"]; IUIComponent(getChildAt(newSelectedIndex)).tweeningProperties = ["x", "y", "width", "height"]; // If the content of the new child hasn't been created yet, set the new child // to the content width/height. This way any background color will show up // properly during the animation. var newSelectedChild:IDeferredContentOwner = IDeferredContentOwner(getChildAt(newSelectedIndex)); if (newSelectedChild.deferredContentCreated == false) { var paddingLeft:Number = getStyle("paddingLeft"); var contentX:Number = borderMetrics.left + (paddingLeft > 0 ? paddingLeft : 0); newSelectedChild.move(contentX, newSelectedChild.y); newSelectedChild.setActualSize(tweenContentWidth, tweenContentHeight); } UIComponent.suspendBackgroundProcessing(); } /** * @private */ mx_internal function onTweenUpdate(value:Number):void { // Fetch the tween invariants we set up in startTween. var vm:EdgeMetrics = tweenViewMetrics; var contentWidth:Number = tweenContentWidth; var contentHeight:Number = tweenContentHeight; var oldSelectedIndex:int = tweenOldSelectedIndex; var newSelectedIndex:int = tweenNewSelectedIndex; // The tweened value is the height of the new content area, which varies // from 0 to the contentHeight. As the new content area grows, the // old content area shrinks. var newContentHeight:Number = value; var oldContentHeight:Number = contentHeight - value; // These offsets for the Y position of the content clips make the content // clips appear to be pushed up and pulled down. var oldOffset:Number = oldSelectedIndex < newSelectedIndex ? -newContentHeight : newContentHeight; var newOffset:Number = newSelectedIndex > oldSelectedIndex ? oldContentHeight : -oldContentHeight; // Loop over all the headers to arrange them vertically. // The loop is intentionally over ALL the headers, not just the ones that // need to move; this makes the animation look equally smooth // regardless of how many headers are moving. // We also reposition the two visible content clips. var y:Number = vm.top; var verticalGap:Number = getStyle("verticalGap"); var n:int = numChildren; for (var i:int = 0; i < n; i++) { var header:Button = getHeaderAt(i); var content:UIComponent = UIComponent(getChildAt(i)); header.$y = y; y += header.height; if (i == oldSelectedIndex) { content.cacheAsBitmap = true; content.scrollRect = new Rectangle(0, -oldOffset, contentWidth, contentHeight); content.visible = true; y += oldContentHeight; } else if (i == newSelectedIndex) { content.cacheAsBitmap = true; content.scrollRect = new Rectangle(0, -newOffset, contentWidth, contentHeight); content.visible = true; y += newContentHeight; } y += verticalGap; } } /** * @private */ mx_internal function onTweenEnd(value:Number):void { bSliding = false; var oldSelectedIndex:int = tweenOldSelectedIndex; var vm:EdgeMetrics = tweenViewMetrics; var verticalGap:Number = getStyle("verticalGap"); var headerHeight:Number = getHeaderHeight(); var localContentWidth:Number = calcContentWidth(); var localContentHeight:Number = calcContentHeight(); var y:Number = vm.top; var content:UIComponent; var n:int = numChildren; for (var i:int = 0; i < n; i++) { var header:Button = getHeaderAt(i); header.$y = y; y += headerHeight; if (i == selectedIndex) { content = UIComponent(getChildAt(i)); content.cacheAsBitmap = false; content.scrollRect = null; content.visible = true; y += localContentHeight; } y += verticalGap; } if (oldSelectedIndex != -1) { content = UIComponent(getChildAt(oldSelectedIndex)); content.cacheAsBitmap = false; content.scrollRect = null; content.visible = false; content.tweeningProperties = null; } // Delete the temporary tween invariants we set up in startTween. tweenViewMetrics = null; tweenContentWidth = NaN; tweenContentHeight = NaN; tweenOldSelectedIndex = 0; tweenNewSelectedIndex = 0; tween = null; UIComponent.resumeBackgroundProcessing(); UIComponent(getChildAt(selectedIndex)).tweeningProperties = null; // If we interrupted a Dissolve effect, restart it here if (currentDissolveEffect) { if (currentDissolveEffect.target != null) { currentDissolveEffect.play(); } else { currentDissolveEffect.play([this]); } } // Let the screen render the last frame of the animation before // we begin instantiating the new child. callLater(instantiateChild, [selectedChild]); } //-------------------------------------------------------------------------- // // Overridden event handlers // //-------------------------------------------------------------------------- /** * @private * Handles "keyDown" event. */ override protected function keyDownHandler(event:KeyboardEvent):void { // Only listen for events that have come from the accordion itself. if (event.target != this) return; var prevValue:int = selectedIndex; // If rtl layout, need to swap LEFT and RIGHT so correct action // is done. var keyCode:uint = mapKeycodeForLayoutDirection(event); switch (keyCode) { case Keyboard.PAGE_DOWN: { drawHeaderFocus(_focusedIndex, false); _focusedIndex = selectedIndex = (selectedIndex < numChildren - 1 ? selectedIndex + 1 : 0); drawHeaderFocus(_focusedIndex, true); event.stopPropagation(); dispatchChangeEvent(prevValue, selectedIndex, event); break; } case Keyboard.PAGE_UP: { drawHeaderFocus(_focusedIndex, false); _focusedIndex = selectedIndex = (selectedIndex > 0 ? selectedIndex - 1 : numChildren - 1); drawHeaderFocus(_focusedIndex, true); event.stopPropagation(); dispatchChangeEvent(prevValue, selectedIndex, event); break; } case Keyboard.HOME: { drawHeaderFocus(_focusedIndex, false); _focusedIndex = selectedIndex = 0; drawHeaderFocus(_focusedIndex, true); event.stopPropagation(); dispatchChangeEvent(prevValue, selectedIndex, event); break; } case Keyboard.END: { drawHeaderFocus(_focusedIndex, false); _focusedIndex = selectedIndex = numChildren - 1; drawHeaderFocus(_focusedIndex, true); event.stopPropagation(); dispatchChangeEvent(prevValue, selectedIndex, event); break; } case Keyboard.DOWN: case Keyboard.RIGHT: { drawHeaderFocus(_focusedIndex, false); _focusedIndex = (_focusedIndex < numChildren - 1 ? _focusedIndex + 1 : 0); drawHeaderFocus(_focusedIndex, true); event.stopPropagation(); break; } case Keyboard.UP: case Keyboard.LEFT: { drawHeaderFocus(_focusedIndex, false); _focusedIndex = (_focusedIndex > 0 ? _focusedIndex - 1 : numChildren - 1); drawHeaderFocus(_focusedIndex, true); event.stopPropagation(); break; } case Keyboard.SPACE: case Keyboard.ENTER: { event.stopPropagation(); if (_focusedIndex != selectedIndex) { selectedIndex = _focusedIndex; dispatchChangeEvent(prevValue, selectedIndex, event); } break; } } } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private * Handles "addedToStage" event */ private function addedToStageHandler(event:Event):void { if (historyManagementEnabled) HistoryManager.register(this); } /** * @private * Handles "removedFromStage" event */ private function removedFromStageHandler(event:Event):void { HistoryManager.unregister(this); } /** * @private */ private function childAddHandler(event:ChildExistenceChangedEvent):void { childAddedOrRemoved = true; var child:DisplayObject = event.relatedObject; // Accordion creates all of its children initially invisible. // They are made as they become the selected child. child.visible = false; // Create the header associated with this child. createHeader(child, getChildIndex(child)); // If the child's label or icon changes, Accordion needs to know so that // the header label can be updated. This event is handled by // labelChanged(). // note: weak listeners child.addEventListener("labelChanged", labelChangedHandler, false, 0, true); child.addEventListener("iconChanged", iconChangedHandler, false, 0, true); // If we just created the first child and no selected index has // been proposed, then propose this child to be selected. if (numChildren == 1 && proposedSelectedIndex == -1) { selectedIndex = 0; // Select the new header. var newHeader:Button = getHeaderAt(0); newHeader.selected = true; // Focus the new header. _focusedIndex = 0; drawHeaderFocus(_focusedIndex, showFocusIndicator); } if (child as IAutomationObject) IAutomationObject(child).showInAutomationHierarchy = true; } /** * @private */ private function childRemoveHandler(event:ChildExistenceChangedEvent):void { childAddedOrRemoved = true; if (numChildren == 0) return; var child:DisplayObject = event.relatedObject; var oldIndex:int = selectedIndex; var newIndex:int; var index:int = getChildIndex(child); // Remove Event Listeners, in case children are referenced elsewhere. child.removeEventListener("labelChanged", labelChangedHandler); child.removeEventListener("iconChanged", iconChangedHandler); var nChildren:int = numChildren - 1; // number of children remaining after child has been removed rawChildren.removeChild(getHeaderAt(index)); // Shuffle all higher numbered headers down. for (var i:int = index; i < nChildren; i++) { getHeaderAt(i + 1).name = HEADER_NAME_BASE + i; } // If we just deleted the only child, the accordion is now empty, // and no child is now selected. if (nChildren == 0) { // There's no need to go through all of commitSelectedIndex(), // and it wouldn't do the right thing, anyway, because // it bails immediately if numChildren is 0. newIndex = _focusedIndex = -1; } else if (index > selectedIndex) { return; } // If we deleted a child before the selected child, the // index of that selected child is now 1 less than it was, // but the selected child itself hasn't changed. else if (index < selectedIndex) { newIndex = oldIndex - 1; } // Now handle the case that we deleted the selected child // and there is another child that we must select. else if (index == selectedIndex) { // If it was the last child, select the previous one. // Otherwise, select the next one. This next child now // has the same index as the one we just deleted, if (index == nChildren) { newIndex = oldIndex - 1; // if something's selected, instantiate it if (newIndex != -1) instantiateChild(INavigatorContent(getChildAt(newIndex))); } else { newIndex = oldIndex; // can't do selectedChild because we need to actually do // newIndex + 1 because currently that's what the index // of the child is (SDK-12622) since this one isn't // actually removed from the display list yet instantiateChild(INavigatorContent(getChildAt(newIndex+1))); } // Select the new selected index header. var newHeader:Button = getHeaderAt(newIndex); newHeader.selected = true; } if (_focusedIndex > index) { _focusedIndex--; drawHeaderFocus(_focusedIndex, showFocusIndicator); } else if (_focusedIndex == index) { if (index == nChildren) _focusedIndex--; drawHeaderFocus(_focusedIndex, showFocusIndicator); } _selectedIndex = newIndex; dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); } /** * @private * Handles "labelChanged" event. */ private function labelChangedHandler(event:Event):void { var child:DisplayObject = DisplayObject(event.target); var childIndex:int = getChildIndex(child); var header:Button = getHeaderAt(childIndex); header.label = INavigatorContent(event.target).label; } /** * @private * Handles "iconChanged" event. */ private function iconChangedHandler(event:Event):void { var child:DisplayObject = DisplayObject(event.target); var childIndex:int = getChildIndex(child); var header:Button = getHeaderAt(childIndex); header.setStyle("icon", INavigatorContent(event.target).icon); //header.icon = Container(event.target).icon; } } }
/** * (c) VARIANTE <http://variante.io> * * This software is released under the MIT License: * http://www.opensource.org/licenses/mit-license.php */ package io.variante.events { import flash.events.IEventDispatcher; /** * Extended flash.events.IEventDispatcher to allow custom event handling. */ public interface IVSEventDispatcher extends IEventDispatcher { /** * Checks if current VSEventDispatcher instance has the specified event type and listener registered. * * @param $type * @param $listener * * @return Boolean value indicating whether listener is registered for the VSEventDispatcher instance. */ function hasEventHandler($type:String, $listener:Function):Boolean; } }
package org.puremvc.as3.multicore.utilities.fabrication.process { import flash.events.Event; public class ProcessEvent extends Event { public static const START:String = 'processStart'; public static const STOP:String = 'processStop'; public static const COMPLETE:String = 'processComplete'; public static const PROGRESS:String = 'processProgress'; public var progress:Number = NaN; public function ProcessEvent(type:String, progress:Number = NaN ) { super(type, bubbles, cancelable); if( type == START || type == STOP ) this.progress = 0; else if( type == COMPLETE ) this.progress = 1; else this.progress = progress; } override public function clone():Event { return new ProcessEvent(type, progress ); } } }
package com.facebook.graph.data.api.status { /** * Status message connections. * @see http://developers.facebook.com/docs/reference/api/status */ public class FacebookStatusMessageConnection { public static const COMMENTS:String = "comments"; public static const LIKES:String = "likes"; } }
//------------------------------------------------------------------------------ // Copyright (c) 2009-2013 the original author or authors. All Rights Reserved. // // NOTICE: You are permitted to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. //------------------------------------------------------------------------------ package robotlegs.bender.extensions.mediatorMap.impl { import flash.display.DisplayObject; import flash.display.MovieClip; import flash.display.Sprite; import flash.geom.Rectangle; import org.flexunit.asserts.assertEqualsVectorsIgnoringOrder; import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import org.hamcrest.object.instanceOf; import org.hamcrest.object.isFalse; import org.hamcrest.object.isTrue; import org.swiftsuspenders.Injector; import robotlegs.bender.extensions.matching.TypeMatcher; import robotlegs.bender.extensions.mediatorMap.api.IMediatorFactory; import robotlegs.bender.extensions.mediatorMap.api.IMediatorViewHandler; import robotlegs.bender.extensions.mediatorMap.impl.support.MediatorWatcher; import robotlegs.bender.extensions.viewManager.api.IViewHandler; import robotlegs.bender.framework.impl.guardSupport.HappyGuard; public class MediatorMapTestPreloaded { /*============================================================================*/ /* Private Properties */ /*============================================================================*/ private var injector:Injector; private var mediatorMap:MediatorMap; private var mediatorWatcher:MediatorWatcher; private var mediatorManager:DefaultMediatorManager; /*============================================================================*/ /* Test Setup and Teardown */ /*============================================================================*/ [Before] public function setUp():void { injector = new Injector(); const factory:IMediatorFactory = new MediatorFactory(injector); const handler:IMediatorViewHandler = new MediatorViewHandler(factory); mediatorMap = new MediatorMap(factory, handler); mediatorManager = new DefaultMediatorManager(factory); mediatorWatcher = new MediatorWatcher(); injector.map(MediatorWatcher).toValue(mediatorWatcher); } [After] public function tearDown():void { mediatorMap = null; mediatorManager = null; } /*============================================================================*/ /* Tests */ /*============================================================================*/ [Test] public function a_hook_runs_and_receives_injections_of_view_and_mediator():void { mediatorMap.map(Sprite).toMediator(RectangleMediator).withHooks(HookWithMediatorAndViewInjectionDrawsRectangle); const view:Sprite = new Sprite(); const expectedViewWidth:Number = 100; const expectedViewHeight:Number = 200; injector.map(Rectangle).toValue(new Rectangle(0, 0, expectedViewWidth, expectedViewHeight)); mediatorMap.handleView(view, null); assertThat(expectedViewWidth, equalTo(view.width)); assertThat(expectedViewHeight, equalTo(view.height)); } [Test] public function can_be_instantiated():void { assertThat(mediatorMap is MediatorMap, isTrue()); } [Test] public function create_mediator_instantiates_mediator_for_view_when_mapped():void { mediatorMap.map(Sprite).toMediator(ExampleMediator); mediatorMap.handleView(new Sprite(), null); const expectedNotifications:Vector.<String> = new <String>['ExampleMediator']; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function doesnt_leave_view_and_mediator_mappings_lying_around():void { mediatorMap.mapMatcher(new TypeMatcher().anyOf(MovieClip, Sprite)).toMediator(ExampleMediator); mediatorMap.handleView(new Sprite(), null); assertThat(injector.satisfiesDirectly(MovieClip), isFalse()); assertThat(injector.satisfiesDirectly(Sprite), isFalse()); assertThat(injector.satisfiesDirectly(ExampleMediator), isFalse()); } [Test] public function handler_creates_mediator_for_view_mapped_by_matcher():void { mediatorMap.mapMatcher(new TypeMatcher().allOf(DisplayObject)).toMediator(ExampleDisplayObjectMediator); mediatorMap.handleView(new Sprite(), null); const expectedNotifications:Vector.<String> = new <String>['ExampleDisplayObjectMediator']; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function handler_doesnt_create_mediator_for_wrong_view_mapped_by_matcher():void { mediatorMap.mapMatcher(new TypeMatcher().allOf(MovieClip)).toMediator(ExampleDisplayObjectMediator); mediatorMap.handleView(new Sprite(), null); const expectedNotifications:Vector.<String> = new <String>[]; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function handler_instantiates_mediator_for_view_mapped_by_type():void { mediatorMap.map(Sprite).toMediator(ExampleMediator); mediatorMap.handleView(new Sprite(), null); const expectedNotifications:Vector.<String> = new <String>['ExampleMediator']; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function implements_IViewHandler():void { assertThat(mediatorMap, instanceOf(IViewHandler)); } [Test] public function mediate_instantiates_mediator_for_view_when_matched_to_mapping():void { mediatorMap.map(Sprite).toMediator(ExampleMediator); mediatorMap.mediate(new Sprite()); const expectedNotifications:Vector.<String> = new <String>['ExampleMediator']; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function mediator_is_created_if_guard_allows_it():void { mediatorMap.map(Sprite).toMediator(ExampleMediator).withGuards(OnlyIfViewHasChildrenGuard); const view:Sprite = new Sprite(); view.addChild(new Sprite()); mediatorMap.mediate(view); const expectedNotifications:Vector.<String> = new <String>['ExampleMediator']; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function no_mediator_is_created_if_guard_prevents_it():void { mediatorMap.map(Sprite).toMediator(ExampleMediator).withGuards(OnlyIfViewHasChildrenGuard); const view:Sprite = new Sprite(); mediatorMap.mediate(view); const expectedNotifications:Vector.<String> = new <String>[]; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function runs_destroy_on_created_mediator_when_unmediate_runs():void { mediatorMap.map(Sprite).toMediator(ExampleMediator); const view:Sprite = new Sprite(); mediatorMap.mediate(view); mediatorMap.unmediate(view); const expectedNotifications:Vector.<String> = new <String>['ExampleMediator', 'ExampleMediator destroy']; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function mediator_is_created_for_non_view_object():void { mediatorMap.map(NotAView).toMediator(NotAViewMediator); const notAView:NotAView = new NotAView(); mediatorMap.mediate(notAView); const expectedNotifications:Vector.<String> = new <String>['NotAViewMediator']; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function non_view_object_injected_into_mediator_correctly():void { mediatorMap.map(NotAView).toMediator(NotAViewMediator); const notAView:NotAView = new NotAView(); mediatorMap.mediate(notAView); assertThat(notAView.mediatorName, equalTo('NotAViewMediator')); } [Test] public function mediator_is_destroyed_for_non_view_object():void { mediatorMap.map(NotAView).toMediator(NotAViewMediator); const notAView:NotAView = new NotAView(); mediatorMap.mediate(notAView); mediatorMap.unmediate(notAView); const expectedNotifications:Vector.<String> = new <String>['NotAViewMediator', 'NotAViewMediator destroy']; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function unmediate_cleans_up_mediators():void { mediatorMap.map(Sprite).toMediator(ExampleMediator); const view:Sprite = new Sprite(); mediatorMap.mediate(view); mediatorMap.unmediate(view); const expectedNotifications:Vector.<String> = new <String>['ExampleMediator', 'ExampleMediator destroy']; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function multiple_mappings_per_matcher_create_mediators():void { mediatorMap.map(Sprite).toMediator(ExampleMediator); mediatorMap.map(Sprite).toMediator(ExampleMediator2); mediatorMap.mediate(new Sprite()); const expectedNotifications:Vector.<String> = new <String>['ExampleMediator', 'ExampleMediator2']; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function multiple_mappings_per_matcher_destroy_mediators():void { mediatorMap.map(Sprite).toMediator(ExampleMediator); mediatorMap.map(Sprite).toMediator(ExampleMediator2); const view:Sprite = new Sprite(); mediatorMap.mediate(view); mediatorMap.unmediate(view); const expectedNotifications:Vector.<String> = new <String>['ExampleMediator', 'ExampleMediator2', 'ExampleMediator destroy', 'ExampleMediator2 destroy']; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function only_one_mediator_created_if_identical_mapping_duplicated():void { mediatorMap.map(Sprite).toMediator(ExampleMediator).withGuards(HappyGuard).withHooks(Alpha50PercentHook); mediatorMap.map(Sprite).toMediator(ExampleMediator).withGuards(HappyGuard).withHooks(Alpha50PercentHook); mediatorMap.mediate(new Sprite()); const expectedNotifications:Vector.<String> = new <String>['ExampleMediator']; assertEqualsVectorsIgnoringOrder(expectedNotifications, mediatorWatcher.notifications); } [Test] public function removing_a_mapping_that_doesnt_exist_doesnt_throw_an_error():void { mediatorMap.unmap(Sprite).fromMediator(ExampleMediator); } } } import flash.display.DisplayObject; import flash.display.Sprite; import flash.geom.Rectangle; import robotlegs.bender.extensions.mediatorMap.impl.support.MediatorWatcher; class ExampleMediator { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ [Inject] public var mediatorWatcher:MediatorWatcher; [Inject] public var view:Sprite; /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function initialize():void { mediatorWatcher.notify('ExampleMediator'); } public function destroy():void { mediatorWatcher.notify('ExampleMediator destroy'); } } class ExampleMediator2 { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ [Inject] public var mediatorWatcher:MediatorWatcher; [Inject] public var view:Sprite; /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function initialize():void { mediatorWatcher.notify('ExampleMediator2'); } public function destroy():void { mediatorWatcher.notify('ExampleMediator2 destroy'); } } class ExampleDisplayObjectMediator { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ [Inject] public var mediatorWatcher:MediatorWatcher; [Inject] public var view:DisplayObject; /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function initialize():void { mediatorWatcher.notify('ExampleDisplayObjectMediator'); } } class RectangleMediator { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ [Inject] public var rectangle:Rectangle; /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function initialize():void { } } class OnlyIfViewHasChildrenGuard { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ [Inject] public var view:Sprite; /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function approve():Boolean { return (view.numChildren > 0); } } class HookWithMediatorAndViewInjectionDrawsRectangle { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ [Inject] public var mediator:RectangleMediator; [Inject] public var view:Sprite; /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function hook():void { const requiredWidth:Number = mediator.rectangle.width; const requiredHeight:Number = mediator.rectangle.height; view.graphics.drawRect(0, 0, requiredWidth, requiredHeight); } } class Alpha50PercentHook { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ [Inject] public var view:Sprite; /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function hook():void { view.alpha = 0.5; } } class HookA { /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function hook():void { } } class NotAView { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ public var mediatorName:String; } class NotAViewMediator { /*============================================================================*/ /* Public Properties */ /*============================================================================*/ [Inject] public var notAView:NotAView; [Inject] public var mediatorWatcher:MediatorWatcher; /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function initialize():void { notAView.mediatorName = 'NotAViewMediator'; mediatorWatcher.notify('NotAViewMediator'); } public function destroy():void { mediatorWatcher.notify('NotAViewMediator destroy'); } }
/* Copyright (c) 2008. Adobe Systems Incorporated. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Adobe Systems Incorporated nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.flexunit.flexui.data { import flash.events.EventDispatcher; import org.flexunit.flexui.data.filter.ITestFunctionStatus; import org.flexunit.flexui.event.TestRunnerBasePresentationModelProperyChangedEvent; import mx.collections.IList; [Event( name="filterChanged", type="flash.events.Event")] public class FilterTestsModel extends EventDispatcher { public var filter : String; private var _selectedTestFunctionStatus : ITestFunctionStatus; public function searchFilterFunc( item : Object ) : Boolean { if ( item is TestCaseData ) { var testClassSum : TestCaseData = item as TestCaseData; testClassSum.filterText = filter; testClassSum.selectedTestFunctionStatus = _selectedTestFunctionStatus; testClassSum.refresh(); var testCaseChildren : IList = testClassSum.children; if ( testCaseChildren && testCaseChildren.length > 0 ) { return true; } } return false; } public function set selectedTestFunctionStatus( value : ITestFunctionStatus ) : void { _selectedTestFunctionStatus = value; dispatchEvent( new TestRunnerBasePresentationModelProperyChangedEvent( TestRunnerBasePresentationModelProperyChangedEvent.FILTER_CHANGED, true ) ); } public function get selectedTestFunctionStatus() : ITestFunctionStatus { return _selectedTestFunctionStatus; } } }
// Billboard example. // This sample demonstrates: // - Populating a 3D scene with billboard sets and several shadow casting spotlights // - Parenting scene nodes to allow more intuitive creation of groups of objects // - Examining rendering performance with a somewhat large object and light count #include "Scripts/Utilities/Sample.as" Scene@ scene_; Node@ cameraNode; float yaw = 0.0f; float pitch = 0.0f; bool drawDebug = false; void Start() { // Execute the common startup for samples SampleStart(); // Create the scene content CreateScene(); // Create the UI content CreateInstructions(); // Setup the viewport for displaying the scene SetupViewport(); // Hook up to the frame update and render post-update events SubscribeToEvents(); } void CreateScene() { scene_ = Scene(); // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) // Also create a DebugRenderer component so that we can draw debug geometry scene_.CreateComponent("Octree"); scene_.CreateComponent("DebugRenderer"); // Create a Zone component for ambient lighting & fog control Node@ zoneNode = scene_.CreateChild("Zone"); Zone@ zone = zoneNode.CreateComponent("Zone"); zone.boundingBox = BoundingBox(-1000.0f, 1000.0f); zone.ambientColor = Color(0.1f, 0.1f, 0.1f); zone.fogStart = 100.0f; zone.fogEnd = 300.0f; // Create a directional light without shadows Node@ lightNode = scene_.CreateChild("DirectionalLight"); lightNode.direction = Vector3(0.5f, -1.0f, 0.5f); Light@ light = lightNode.CreateComponent("Light"); light.lightType = LIGHT_DIRECTIONAL; light.color = Color(0.2f, 0.2f, 0.2f); light.specularIntensity = 1.0f; // Create a "floor" consisting of several tiles for (int y = -5; y <= 5; ++y) { for (int x = -5; x <= 5; ++x) { Node@ floorNode = scene_.CreateChild("FloorTile"); floorNode.position = Vector3(x * 20.5f, -0.5f, y * 20.5f); floorNode.scale = Vector3(20.0f, 1.0f, 20.f); StaticModel@ floorObject = floorNode.CreateComponent("StaticModel"); floorObject.model = cache.GetResource("Model", "Models/Box.mdl"); floorObject.material = cache.GetResource("Material", "Materials/Stone.xml"); } } // Create groups of mushrooms, which act as shadow casters const uint NUM_MUSHROOMGROUPS = 25; const uint NUM_MUSHROOMS = 25; for (uint i = 0; i < NUM_MUSHROOMGROUPS; ++i) { // First create a scene node for the group. The individual mushrooms nodes will be created as children Node@ groupNode = scene_.CreateChild("MushroomGroup"); groupNode.position = Vector3(Random(190.0f) - 95.0f, 0.0f, Random(190.0f) - 95.0f); for (uint j = 0; j < NUM_MUSHROOMS; ++j) { Node@ mushroomNode = groupNode.CreateChild("Mushroom"); mushroomNode.position = Vector3(Random(25.0f) - 12.5f, 0.0f, Random(25.0f) - 12.5f); mushroomNode.rotation = Quaternion(0.0f, Random() * 360.0f, 0.0f); mushroomNode.SetScale(1.0f + Random() * 4.0f); StaticModel@ mushroomObject = mushroomNode.CreateComponent("StaticModel"); mushroomObject.model = cache.GetResource("Model", "Models/Mushroom.mdl"); mushroomObject.material = cache.GetResource("Material", "Materials/Mushroom.xml"); mushroomObject.castShadows = true; } } // Create billboard sets (floating smoke) const uint NUM_BILLBOARDNODES = 25; const uint NUM_BILLBOARDS = 10; for (uint i = 0; i < NUM_BILLBOARDNODES; ++i) { Node@ smokeNode = scene_.CreateChild("Smoke"); smokeNode.position = Vector3(Random(200.0f) - 100.0f, Random(20.0f) + 10.0f, Random(200.0f) - 100.0f); BillboardSet@ billboardObject = smokeNode.CreateComponent("BillboardSet"); billboardObject.numBillboards = NUM_BILLBOARDS; billboardObject.material = cache.GetResource("Material", "Materials/LitSmoke.xml"); billboardObject.sorted = true; for (uint j = 0; j < NUM_BILLBOARDS; ++j) { Billboard@ bb = billboardObject.billboards[j]; bb.position = Vector3(Random(12.0f) - 6.0f, Random(8.0f) - 4.0f, Random(12.0f) - 6.0f); bb.size = Vector2(Random(2.0f) + 3.0f, Random(2.0f) + 3.0f); bb.rotation = Random() * 360.0f; bb.enabled = true; } // After modifying the billboards, they need to be "commited" so that the BillboardSet updates its internals billboardObject.Commit(); } // Create shadow casting spotlights const uint NUM_LIGHTS = 9; for (uint i = 0; i < NUM_LIGHTS; ++i) { Node@ lightNode = scene_.CreateChild("SpotLight"); Light@ light = lightNode.CreateComponent("Light"); float angle = 0.0f; Vector3 position((i % 3) * 60.0f - 60.0f, 45.0f, (i / 3) * 60.0f - 60.0f); Color color(((i + 1) & 1) * 0.5f + 0.5f, (((i + 1) >> 1) & 1) * 0.5f + 0.5f, (((i + 1) >> 2) & 1) * 0.5f + 0.5f); lightNode.position = position; lightNode.direction = Vector3(Sin(angle), -1.5f, Cos(angle)); light.lightType = LIGHT_SPOT; light.range = 90.0f; light.rampTexture = cache.GetResource("Texture2D", "Textures/RampExtreme.png"); light.fov = 45.0f; light.color = color; light.specularIntensity = 1.0f; light.castShadows = true; light.shadowBias = BiasParameters(0.00002f, 0.0f); // Configure shadow fading for the lights. When they are far away enough, the lights eventually become unshadowed for // better GPU performance. Note that we could also set the maximum distance for each object to cast shadows light.shadowFadeDistance = 100.0f; // Fade start distance light.shadowDistance = 125.0f; // Fade end distance, shadows are disabled // Set half resolution for the shadow maps for increased performance light.shadowResolution = 0.5f; // The spot lights will not have anything near them, so move the near plane of the shadow camera farther // for better shadow depth resolution light.shadowNearFarRatio = 0.01f; } // Create the camera. Limit far clip distance to match the fog cameraNode = scene_.CreateChild("Camera"); Camera@ camera = cameraNode.CreateComponent("Camera"); camera.farClip = 300.0f; // Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0f, 5.0f, 0.0f); } void CreateInstructions() { // Construct new Text object, set string to display and font to use Text@ instructionText = ui.root.CreateChild("Text"); instructionText.text = "Use WASD keys and mouse to move\n" "Space to toggle debug geometry"; instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15); // The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER; // 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 Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera")); renderer.viewports[0] = viewport; } void SubscribeToEvents() { // Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate"); // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request // debug geometry SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate"); } void MoveCamera(float timeStep) { // Do not move if the UI has a focused element (the console) if (ui.focusElement !is null) return; // Movement speed as world units per second const float MOVE_SPEED = 20.0f; // Mouse sensitivity as degrees per pixel const float MOUSE_SENSITIVITY = 0.1f; // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees IntVector2 mouseMove = input.mouseMove; yaw += MOUSE_SENSITIVITY * mouseMove.x; pitch += MOUSE_SENSITIVITY * mouseMove.y; pitch = Clamp(pitch, -90.0f, 90.0f); // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0f); // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if (input.keyDown['W']) cameraNode.TranslateRelative(Vector3(0.0f, 0.0f, 1.0f) * MOVE_SPEED * timeStep); if (input.keyDown['S']) cameraNode.TranslateRelative(Vector3(0.0f, 0.0f, -1.0f) * MOVE_SPEED * timeStep); if (input.keyDown['A']) cameraNode.TranslateRelative(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep); if (input.keyDown['D']) cameraNode.TranslateRelative(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep); // Toggle debug geometry with space if (input.keyPress[KEY_SPACE]) drawDebug = !drawDebug; } void AnimateScene(float timeStep) { // Get the light and billboard scene nodes Array<Node@> lightNodes = scene_.GetChildrenWithComponent("Light"); Array<Node@> billboardNodes = scene_.GetChildrenWithComponent("BillboardSet"); const float LIGHT_ROTATION_SPEED = 20.0f; const float BILLBOARD_ROTATION_SPEED = 50.0f; // Rotate the lights around the world Y-axis for (uint i = 0; i < lightNodes.length; ++i) lightNodes[i].Rotate(Quaternion(0.0f, LIGHT_ROTATION_SPEED * timeStep, 0.0f), true); // Rotate the individual billboards within the billboard sets, then recommit to make the changes visible for (uint i = 0; i < billboardNodes.length; ++i) { BillboardSet@ billboardObject = billboardNodes[i].GetComponent("BillboardSet"); for (uint j = 0; j < billboardObject.numBillboards; ++j) { Billboard@ bb = billboardObject.billboards[j]; bb.rotation += BILLBOARD_ROTATION_SPEED * timeStep; } billboardObject.Commit(); } } void HandleUpdate(StringHash eventType, VariantMap& eventData) { // Take the frame time step, which is stored as a float float timeStep = eventData["TimeStep"].GetFloat(); // Move the camera and animate the scene, scale movement with time step MoveCamera(timeStep); AnimateScene(timeStep); } void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData) { // If draw debug mode is enabled, draw viewport debug geometry. This time use depth test, as otherwise the result becomes // hard to interpret due to large object count if (drawDebug) renderer.DrawDebugGeometry(true); }
package starling.utils { import flash.geom.Point; import flash.geom.Vector3D; import starling.errors.AbstractClassError; public class MathUtil { private static const TWO_PI:Number = 6.283185307179586; public function MathUtil() { super(); throw new AbstractClassError(); } public static function intersectLineWithXYPlane(param1:Vector3D, param2:Vector3D, param3:Point = null) : Point { if(param3 == null) { param3 = new Point(); } var _loc7_:Number = param2.x - param1.x; var _loc5_:Number = param2.y - param1.y; var _loc6_:Number = param2.z - param1.z; var _loc4_:Number = -param1.z / _loc6_; param3.x = param1.x + _loc4_ * _loc7_; param3.y = param1.y + _loc4_ * _loc5_; return param3; } public static function isPointInTriangle(param1:Point, param2:Point, param3:Point, param4:Point) : Boolean { var _loc15_:Number = param4.x - param2.x; var _loc13_:Number = param4.y - param2.y; var _loc8_:Number = param3.x - param2.x; var _loc16_:Number = param3.y - param2.y; var _loc12_:Number = param1.x - param2.x; var _loc9_:Number = param1.y - param2.y; var _loc10_:Number = _loc15_ * _loc15_ + _loc13_ * _loc13_; var _loc17_:Number = _loc15_ * _loc8_ + _loc13_ * _loc16_; var _loc14_:Number = _loc15_ * _loc12_ + _loc13_ * _loc9_; var _loc11_:Number = _loc8_ * _loc8_ + _loc16_ * _loc16_; var _loc18_:Number = _loc8_ * _loc12_ + _loc16_ * _loc9_; var _loc5_:Number = 1 / (_loc10_ * _loc11_ - _loc17_ * _loc17_); var _loc6_:Number = (_loc11_ * _loc14_ - _loc17_ * _loc18_) * _loc5_; var _loc7_:Number = (_loc10_ * _loc18_ - _loc17_ * _loc14_) * _loc5_; return _loc6_ >= 0 && _loc7_ >= 0 && _loc6_ + _loc7_ < 1; } public static function normalizeAngle(param1:Number) : Number { param1 = param1 % 6.28318530717959; if(param1 < -3.14159265358979) { param1 = param1 + 6.28318530717959; } if(param1 > 3.14159265358979) { param1 = param1 - 6.28318530717959; } return param1; } public static function getNextPowerOfTwo(param1:Number) : int { var _loc2_:* = 0; if(param1 is int && param1 > 0 && (param1 & param1 - 1) == 0) { return param1; } _loc2_ = 1; param1 = param1 - 1.0e-9; while(_loc2_ < param1) { _loc2_ = _loc2_ << 1; } return _loc2_; } public static function isEquivalent(param1:Number, param2:Number, param3:Number = 1.0E-4) : Boolean { return param1 - param3 < param2 && param1 + param3 > param2; } public static function max(param1:Number, param2:Number) : Number { return param1 > param2?param1:Number(param2); } public static function min(param1:Number, param2:Number) : Number { return param1 < param2?param1:Number(param2); } public static function clamp(param1:Number, param2:Number, param3:Number) : Number { return param1 < param2?param2:Number(param1 > param3?param3:Number(param1)); } } }
package feathers.examples.layoutExplorer.screens { import feathers.controls.Button; import feathers.controls.Header; import feathers.controls.List; import feathers.controls.NumericStepper; import feathers.controls.PanelScreen; import feathers.controls.PickerList; import feathers.data.ArrayCollection; import feathers.data.VectorCollection; import feathers.examples.layoutExplorer.data.TiledRowsLayoutSettings; import feathers.layout.AnchorLayout; import feathers.layout.AnchorLayoutData; import feathers.layout.Direction; import feathers.layout.HorizontalAlign; import feathers.layout.VerticalAlign; import starling.display.DisplayObject; import starling.events.Event; [Event(name="complete",type="starling.events.Event")] public class TiledRowsLayoutSettingsScreen extends PanelScreen { public function TiledRowsLayoutSettingsScreen() { super(); } public var settings:TiledRowsLayoutSettings; private var _list:List; private var _itemCountStepper:NumericStepper; private var _requestedColumnCountStepper:NumericStepper; private var _pagingPicker:PickerList; private var _horizontalGapStepper:NumericStepper; private var _verticalGapStepper:NumericStepper; private var _paddingTopStepper:NumericStepper; private var _paddingRightStepper:NumericStepper; private var _paddingBottomStepper:NumericStepper; private var _paddingLeftStepper:NumericStepper; private var _horizontalAlignPicker:PickerList; private var _verticalAlignPicker:PickerList; private var _tileHorizontalAlignPicker:PickerList; private var _tileVerticalAlignPicker:PickerList; override public function dispose():void { //icon and accessory display objects in the list's data provider //won't be automatically disposed because feathers cannot know if //they need to be used again elsewhere or not. we need to dispose //them manually. this._list.dataProvider.dispose(disposeItemAccessory); //never forget to call super.dispose() because you don't want to //create a memory leak! super.dispose(); } override protected function initialize():void { //never forget to call super.initialize() super.initialize(); this.title = "Tiled Rows Layout Settings"; this.layout = new AnchorLayout(); this._itemCountStepper = new NumericStepper(); this._itemCountStepper.minimum = 1; //the layout can certainly handle more. this value is arbitrary. this._itemCountStepper.maximum = 100; this._itemCountStepper.step = 1; this._itemCountStepper.value = this.settings.itemCount; this._itemCountStepper.addEventListener(Event.CHANGE, itemCountStepper_changeHandler); this._requestedColumnCountStepper = new NumericStepper(); this._requestedColumnCountStepper.minimum = 0; //the layout can certainly handle more. this value is arbitrary. this._requestedColumnCountStepper.maximum = 10; this._requestedColumnCountStepper.step = 1; this._requestedColumnCountStepper.value = this.settings.requestedColumnCount; this._requestedColumnCountStepper.addEventListener(Event.CHANGE, requestedColumnCountStepper_changeHandler); this._pagingPicker = new PickerList(); this._pagingPicker.typicalItem = Direction.HORIZONTAL; this._pagingPicker.dataProvider = new VectorCollection(new <String> [ Direction.NONE, Direction.HORIZONTAL, Direction.VERTICAL ]); this._pagingPicker.selectedItem = this.settings.paging; this._pagingPicker.addEventListener(Event.CHANGE, pagingPicker_changeHandler); this._horizontalAlignPicker = new PickerList(); this._horizontalAlignPicker.typicalItem = HorizontalAlign.CENTER; this._horizontalAlignPicker.dataProvider = new VectorCollection(new <String> [ HorizontalAlign.LEFT, HorizontalAlign.CENTER, HorizontalAlign.RIGHT ]); this._horizontalAlignPicker.selectedItem = this.settings.horizontalAlign; this._horizontalAlignPicker.addEventListener(Event.CHANGE, horizontalAlignPicker_changeHandler); this._verticalAlignPicker = new PickerList(); this._verticalAlignPicker.typicalItem = VerticalAlign.BOTTOM; this._verticalAlignPicker.dataProvider = new VectorCollection(new <String> [ VerticalAlign.TOP, VerticalAlign.MIDDLE, VerticalAlign.BOTTOM ]); this._verticalAlignPicker.selectedItem = this.settings.verticalAlign; this._verticalAlignPicker.addEventListener(Event.CHANGE, verticalAlignPicker_changeHandler); this._tileHorizontalAlignPicker = new PickerList(); this._tileHorizontalAlignPicker.typicalItem = HorizontalAlign.CENTER; this._tileHorizontalAlignPicker.dataProvider = new VectorCollection(new <String> [ HorizontalAlign.LEFT, HorizontalAlign.CENTER, HorizontalAlign.RIGHT, HorizontalAlign.JUSTIFY ]); this._tileHorizontalAlignPicker.selectedItem = this.settings.tileHorizontalAlign; this._tileHorizontalAlignPicker.addEventListener(Event.CHANGE, tileHorizontalAlignPicker_changeHandler); this._tileVerticalAlignPicker = new PickerList(); this._tileVerticalAlignPicker.typicalItem = VerticalAlign.BOTTOM; this._tileVerticalAlignPicker.dataProvider = new VectorCollection(new <String> [ VerticalAlign.TOP, VerticalAlign.MIDDLE, VerticalAlign.BOTTOM, VerticalAlign.JUSTIFY ]); this._tileVerticalAlignPicker.selectedItem = this.settings.tileVerticalAlign; this._tileVerticalAlignPicker.addEventListener(Event.CHANGE, tileVerticalAlignPicker_changeHandler); this._horizontalGapStepper = new NumericStepper(); this._horizontalGapStepper.minimum = 0; //these maximum values are completely arbitrary this._horizontalGapStepper.maximum = 100; this._horizontalGapStepper.step = 1; this._horizontalGapStepper.value = this.settings.horizontalGap; this._horizontalGapStepper.addEventListener(Event.CHANGE, horizontalGapStepper_changeHandler); this._verticalGapStepper = new NumericStepper(); this._verticalGapStepper.minimum = 0; this._verticalGapStepper.maximum = 100; this._verticalGapStepper.step = 1; this._verticalGapStepper.value = this.settings.verticalGap; this._verticalGapStepper.addEventListener(Event.CHANGE, verticalGapStepper_changeHandler); this._paddingTopStepper = new NumericStepper(); this._paddingTopStepper.minimum = 0; this._paddingTopStepper.maximum = 100; this._paddingTopStepper.step = 1; this._paddingTopStepper.value = this.settings.paddingTop; this._paddingTopStepper.addEventListener(Event.CHANGE, paddingTopStepper_changeHandler); this._paddingRightStepper = new NumericStepper(); this._paddingRightStepper.minimum = 0; this._paddingRightStepper.maximum = 100; this._paddingRightStepper.step = 1; this._paddingRightStepper.value = this.settings.paddingRight; this._paddingRightStepper.addEventListener(Event.CHANGE, paddingRightStepper_changeHandler); this._paddingBottomStepper = new NumericStepper(); this._paddingBottomStepper.minimum = 0; this._paddingBottomStepper.maximum = 100; this._paddingBottomStepper.step = 1; this._paddingBottomStepper.value = this.settings.paddingBottom; this._paddingBottomStepper.addEventListener(Event.CHANGE, paddingBottomStepper_changeHandler); this._paddingLeftStepper = new NumericStepper(); this._paddingLeftStepper.minimum = 0; this._paddingLeftStepper.maximum = 100; this._paddingLeftStepper.step = 1; this._paddingLeftStepper.value = this.settings.paddingLeft; this._paddingLeftStepper.addEventListener(Event.CHANGE, paddingLeftStepper_changeHandler); this._list = new List(); this._list.isSelectable = false; this._list.dataProvider = new ArrayCollection( [ { label: "Item Count", accessory: this._itemCountStepper }, { label: "Requested Column Count", accessory: this._requestedColumnCountStepper }, { label: "Paging", accessory: this._pagingPicker }, { label: "horizontalAlign", accessory: this._horizontalAlignPicker }, { label: "verticalAlign", accessory: this._verticalAlignPicker }, { label: "tileHorizontalAlign", accessory: this._tileHorizontalAlignPicker }, { label: "tileVerticalAlign", accessory: this._tileVerticalAlignPicker }, { label: "horizontalGap", accessory: this._horizontalGapStepper }, { label: "verticalGap", accessory: this._verticalGapStepper }, { label: "paddingTop", accessory: this._paddingTopStepper }, { label: "paddingRight", accessory: this._paddingRightStepper }, { label: "paddingBottom", accessory: this._paddingBottomStepper }, { label: "paddingLeft", accessory: this._paddingLeftStepper }, ]); this._list.layoutData = new AnchorLayoutData(0, 0, 0, 0); this.addChild(this._list); this.headerFactory = this.customHeaderFactory; this.backButtonHandler = this.onBackButton; } private function customHeaderFactory():Header { var header:Header = new Header(); var doneButton:Button = new Button(); doneButton.label = "Done"; doneButton.addEventListener(Event.TRIGGERED, doneButton_triggeredHandler); header.rightItems = new <DisplayObject> [ doneButton ]; return header; } private function disposeItemAccessory(item:Object):void { DisplayObject(item.accessory).dispose(); } private function onBackButton():void { this.dispatchEventWith(Event.COMPLETE); } private function doneButton_triggeredHandler(event:Event):void { this.onBackButton(); } private function itemCountStepper_changeHandler(event:Event):void { this.settings.itemCount = this._itemCountStepper.value; } private function requestedColumnCountStepper_changeHandler(event:Event):void { this.settings.requestedColumnCount = this._requestedColumnCountStepper.value; } private function pagingPicker_changeHandler(event:Event):void { this.settings.paging = this._pagingPicker.selectedItem as String; } private function horizontalAlignPicker_changeHandler(event:Event):void { this.settings.horizontalAlign = this._horizontalAlignPicker.selectedItem as String; } private function verticalAlignPicker_changeHandler(event:Event):void { this.settings.verticalAlign = this._verticalAlignPicker.selectedItem as String; } private function tileHorizontalAlignPicker_changeHandler(event:Event):void { this.settings.tileHorizontalAlign = this._tileHorizontalAlignPicker.selectedItem as String; } private function tileVerticalAlignPicker_changeHandler(event:Event):void { this.settings.tileVerticalAlign = this._tileVerticalAlignPicker.selectedItem as String; } private function horizontalGapStepper_changeHandler(event:Event):void { this.settings.horizontalGap = this._horizontalGapStepper.value; } private function verticalGapStepper_changeHandler(event:Event):void { this.settings.verticalGap = this._verticalGapStepper.value; } private function paddingTopStepper_changeHandler(event:Event):void { this.settings.paddingTop = this._paddingTopStepper.value; } private function paddingRightStepper_changeHandler(event:Event):void { this.settings.paddingRight = this._paddingRightStepper.value; } private function paddingBottomStepper_changeHandler(event:Event):void { this.settings.paddingBottom = this._paddingBottomStepper.value; } private function paddingLeftStepper_changeHandler(event:Event):void { this.settings.paddingLeft = this._paddingLeftStepper.value; } } }
//Marks the right margin of code ******************************************************************* package com.neopets.games.inhouse.shenkuuwarrior2.elements { import com.neopets.games.inhouse.shenkuuwarrior2.gamedata.GameInfo; import com.neopets.util.collision.geometry.RectangleArea; import com.neopets.util.collision.objects.CollisionProxy; import flash.display.MovieClip; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; /** * public class Ledge extends Sprite * * <p><u>REVISIONS</u>:<br> * <table width="500" cellpadding="0"> * <tr><th>Date</th><th>Author</th><th>Description</th></tr> * <tr><td>06/09/2009</td><td>baldarev</td><td>Class created.</td></tr> * <tr><td>MM/DD/YYYY</td><td>AUTHOR</td><td>DESCRIPTION.</td></tr> * </table> * </p> */ public class Ledge extends MovieClip { //-------------------------------------------------------------------------- // Costants //-------------------------------------------------------------------------- /** * var description */ //-------------------------------------------------------------------------- //Public properties //-------------------------------------------------------------------------- /** * var description */ public var ledge:MovieClip; //-------------------------------------------------------------------------- //Private properties //-------------------------------------------------------------------------- /** * var description */ //protected var _hookX:Number; old collision system - delete protected var _proxy:CollisionProxy; protected var _proxiinit:Boolean = false; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Creates a new public class Ledge extends Sprite instance. * * <span class="hide">Any hidden comments go here.</span> * * */ public function Ledge() { super(); gotoAndStop(1); // initialize our collision proxy [OLD: when we're added to the stage] when the ledge enter the game area _proxy = new CollisionProxy(this); //addEventListener(Event.ADDED_TO_STAGE,onProxyInit); } //-------------------------------------------------------------------------- // Public Methods //-------------------------------------------------------------------------- /** * Description * @param value of type <code>CustomClass</code> */ public function update():void { //adding to the collision space if (y > -50 && !_proxiinit){ onProxyInit(); _proxiinit = true; } } //-------------------------------------------------------------------------- // Protected Methods //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Private Methods //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Event Handlers //-------------------------------------------------------------------------- /** * Handler for CustomEvent. * * @param event The <code>CustomEvent</code> * */ protected function onProxyInit(ev:Event=null):void { if(stage != null) { _proxy.area = new RectangleArea(ledge); _proxy.addTo(GameInfo.COLLISION_SPACE); removeEventListener(Event.ADDED_TO_STAGE,onProxyInit); } } //-------------------------------------------------------------------------- // Getters/Setters //-------------------------------------------------------------------------- /*public function get hookX ():Number{ return _hookX; } public function set hookX (value:Number):void { _hookX = value; }*/ public function get proxy ():CollisionProxy{ return _proxy; } //do I need this? /*public function set hooked(value:Boolean):void { //trace ("ledge is hooked!"); }*/ } }
/* * 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.flexunit.internals.runners.statements { import flash.events.Event; import flash.net.Responder; import flash.utils.Dictionary; import mx.events.PropertyChangeEvent; import mx.rpc.IResponder; import org.flexunit.Assert; import org.flexunit.AssertionError; import org.flexunit.async.AsyncHandler; import org.flexunit.async.AsyncLocator; import org.flexunit.async.AsyncNativeTestResponder; import org.flexunit.async.AsyncTestResponder; import org.flexunit.async.IAsyncTestResponder; import org.flexunit.async.ITestResponder; import org.flexunit.constants.AnnotationArgumentConstants; import org.flexunit.constants.AnnotationConstants; import org.flexunit.events.AsyncEvent; import org.flexunit.events.AsyncResponseEvent; import org.flexunit.internals.flexunit_internal; import org.flexunit.runners.model.FrameworkMethod; import org.flexunit.runners.model.TestClass; import org.flexunit.token.AsyncTestToken; import org.flexunit.token.ChildResult; import org.flexunit.utils.ClassNameUtil; import org.fluint.sequence.SequenceBindingWaiter; import org.fluint.sequence.SequenceRunner; use namespace flexunit_internal; /** * The <code>ExpectAsync</code> is a decorator that is responsible for determing * whether a specific test method is expecting an asynchronous response. As this * infrastructure carries overhead, we only create it when the user specifics a * given test is asynchronous. The class implements <code>IAsyncHandlingStatement</code> * and works with the <code>Async</code> class.<br/> * * In order to expect an asynchronous response, a test method must include metadata indicating * it is expecting asynchronous functionality.<br/> * * <pre><code> * [Test(async)] * public function asyncTest():void { * //Test with asynchronous functionality * } * </code></pre> * * @see org.flexunit.async.Async */ public class ExpectAsync extends AsyncStatementBase implements IAsyncStatement, IAsyncHandlingStatement { /** * @private */ private var objectUnderTest:Object; /** * @private */ private var statement:IAsyncStatement; /** * @private */ private var returnMessageSent:Boolean = false; /** * @private */ private var testComplete:Boolean; /** * @private */ private var pendingAsyncCalls:Array; /** * @private */ private var asyncFailureConditions:Dictionary; /** * @private */ private var methodBodyExecuting:Boolean = false; /** * Returns a Boolean value indicating whether the test method is current executing. */ public function get bodyExecuting():Boolean { return methodBodyExecuting; } /** * Returns a Boolean value indicating whether there are still any pending asynchronous calls. */ public function get hasPendingAsync():Boolean { return ( pendingAsyncCalls.length > 0 ); } /** * Attempts to call the provided <code>method</code> with the provided <code>rest</code> parameters. * * @param method The Function to call with the provided <code>rest</code> parameters. * @param rest The parameters supplied to the <code>method</code>. */ protected function protect( method:Function, ... rest ):void { try { if ( rest && rest.length>0 ) { method.apply( this, rest ); } else { method(); } if ( hasPendingAsync ) { startAsyncTimers(); } } catch (error:Error) { sendComplete( error ); } } /** * Removes asynchronous event listeners from the provided <code>asyncHandler</code>. * * @param asyncHandler The <code>AsyncHandler</code> from which to remove the event listeners. */ private function removeAsyncEventListeners( asyncHandler:AsyncHandler ):void { asyncHandler.removeEventListener( AsyncHandler.EVENT_FIRED, handleAsyncEventFired, false ); asyncHandler.removeEventListener( AsyncHandler.TIMER_EXPIRED, handleAsyncTimeOut, false ); } /** * Removes asynchronous error event listeners from the provided <code>asyncHandler</code>. * * @param asyncHandler The <code>AsyncHandler</code> from which to remove the error event listeners. */ private function removeAsyncErrorEventListeners( asyncHandler:AsyncHandler ):void { asyncHandler.removeEventListener( AsyncHandler.EVENT_FIRED, handleAsyncErrorFired, false ); asyncHandler.removeEventListener( AsyncHandler.TIMER_EXPIRED, handleAsyncTimeOut, false ); } /** * * * * @internal TODO:: This needs to be cleaned up and revised... just a prototype * @param eventHandler * @param timeout * @param passThroughData * @param timeoutHandler * * @throws Error Test Completed, but additional async event added * * @return * */ public function asyncErrorConditionHandler( eventHandler:Function ):Function { if ( testComplete ) { sendComplete( new Error("Test Completed, but additional async event added") ); } var asyncHandler:AsyncHandler = new AsyncHandler( eventHandler ) asyncHandler.addEventListener( AsyncHandler.EVENT_FIRED, handleAsyncErrorFired, false, 0, true ); //asyncHandler.addEventListener( AsyncHandler.TIMER_EXPIRED, handleAsyncTimeOut, false, 0, true ); asyncFailureConditions[ asyncHandler ] = true; return asyncHandler.handleEvent; } /** * Creates an <code>AsyncHandler</code> that pend and either call the <code>eventHandler</code> or the * <code>timeoutHandler</code>, passing the <code>passThroughData</code>, depending on whether the * <code>timeout</code> period has been reached. * * @param eventHandler The Function that will be executed if the handler is called before * the <code>timeout</code> has expired. * @param timeout The length of time, in milliseconds, before the <code>timeoutHandler</code> will be executed. * @param passThroughData An Object that can be given information about the current test; this information will * be available for both the <code>eventHandler</code> and the <code>timeoutHandler</code>. * @param timeoutHandler The Function that will be executed if the <code>timeout</code> time is reached prior to * the expected event being dispatched. * * @return an event handler Function that will determine whether the <code>timeout</code> has been reached. */ public function asyncHandler( eventHandler:Function, timeout:int, passThroughData:Object = null, timeoutHandler:Function = null ):Function { if ( testComplete ) { sendComplete( new Error("Test Completed, but additional async event added") ); } var asyncHandler:AsyncHandler = new AsyncHandler( eventHandler, timeout, passThroughData, timeoutHandler ) asyncHandler.addEventListener( AsyncHandler.EVENT_FIRED, handleAsyncEventFired, false, 0, true ); asyncHandler.addEventListener( AsyncHandler.TIMER_EXPIRED, handleAsyncTimeOut, false, 0, true ); pendingAsyncCalls.push( asyncHandler ); return asyncHandler.handleEvent; } // We have a toggle in the compiler arguments so that we can choose whether or not the flex classes should // be compiled into the FlexUnit swc. For actionscript only projects we do not want to compile the // flex classes since it will cause errors. /** * Creates an <code>IAsyncTestResponder</code> that pend and either call the <code>eventHandler</code> or the * <code>timeoutHandler</code>, passing the <code>passThroughData</code>, depending on whether the * <code>timeout</code> period has been reached. * * @param responder The responder that will be executed if the <code>IResponder</code> is called before * the <code>timeout</code> has expired. * @param timeout The length of time, in milliseconds, before the <code>timeoutHandler</code> will be executed. * @param passThroughData An Object that can be given information about the current test; this information will * be available for both the <code>eventHandler</code> and the <code>timeoutHandler</code>. * @param timeoutHandler The Function that will be executed if the <code>timeout</code> time is reached prior to * the expected event being dispatched. * * @return an <code>IResponder</code> that will determine whether the <code>timeout</code> has been reached. */ CONFIG::useFlexClasses public function asyncResponder( responder:*, timeout:int, passThroughData:Object = null, timeoutHandler:Function = null ):IResponder { var asyncResponder:IAsyncTestResponder; if ( !( ( responder is IResponder ) || ( responder is ITestResponder ) ) ) { throw new Error( "Object provided to responder parameter of asyncResponder is not a IResponder or ITestResponder" ); } /**If the user passes use an IAsyncTestResponder of their own, then we do not need to wrap it in our own AsyncTestResponder class * This allows the use of a different type of responder than our standard, however, it is the responsibility of the IAsyncTestResponder * we are passed to dispatch the requisite AsyncResponseEvent events in response to a result or fault. * * In your own code, you can therefore do something like: * * asyncResponder( IResponder, timeout ); * * OR * * asyncResponder( mySpecialResponder implements IAsyncTestResponder, timeout ); * * */ if ( responder is IAsyncTestResponder ) { asyncResponder = responder; } else { asyncResponder = new AsyncTestResponder( responder ); } var asyncHandler:AsyncHandler = new AsyncHandler( handleAsyncTestResponderEvent, timeout, passThroughData, timeoutHandler ) asyncHandler.addEventListener( AsyncHandler.EVENT_FIRED, handleAsyncEventFired, false, 0, true ); asyncHandler.addEventListener( AsyncHandler.TIMER_EXPIRED, handleAsyncTimeOut, false, 0, true ); pendingAsyncCalls.push( asyncHandler ); asyncResponder.addEventListener( AsyncResponseEvent.RESPONDER_FIRED, asyncHandler.handleEvent, false, 0, true ); return asyncResponder; } /** * Removes all asynchronous event listeners for each pending asynchronous call. */ private function removeAllAsyncEventListeners():void { for ( var i:int=0; i<pendingAsyncCalls.length; i++ ) { removeAsyncEventListeners( pendingAsyncCalls[ i ] as AsyncHandler ); } pendingAsyncCalls = new Array(); for ( var handler:* in asyncFailureConditions ) { removeAsyncErrorEventListeners( handler as AsyncHandler ); } asyncFailureConditions = new Dictionary( true ); } /** * Called when the asynchronous timeout has been reached for a given test. This method attempts to * call a timeout handler that has been associated with the asychronous test. If no handler has * been specified, an error will be generated and the <code>ExpectAsync</code> statement finishes. * * @param event The event associated with the asynchronous timeout. */ private function handleAsyncTimeOut( event:Event ):void { var asyncHandler:AsyncHandler = event.target as AsyncHandler; var failure:Boolean = false; removeAsyncEventListeners( asyncHandler ); //Run the timeout handler if one exists; otherwise, send an error if ( asyncHandler.timeoutHandler != null ) { protect( asyncHandler.timeoutHandler, asyncHandler.passThroughData ); } else { failure = true; sendComplete( new AssertionError( "Timeout Occurred before expected event" ) ); //protect( Assert.fail, "Timeout Occurred before expected event" ); } //Remove all future pending items removeAllAsyncEventListeners(); /** var methodResult:TestMethodResult = testMonitor.getTestMethodResult( registeredMethod ); if ( methodResult && ( !methodResult.traceInformation ) ) { methodResult.executed = true; methodResult.testDuration = getTimer()-tickCountOnStart; methodResult.traceInformation = "Test completed via Async TimeOut in " + methodResult.testDuration + "ms"; } **/ //Our timeout has failed, declare this specific test complete and move along sendComplete(); } /** * Handles the AsyncResponseEvent that is thrown by the asyncResponder. * It sends data to the original responder based on if it is a result or fault status. * * If the original responder is of type ITestResponder, then the passThroughData is passed to it. * * @param event * @param passThroughData * */ protected function handleAsyncTestResponderEvent( event:AsyncResponseEvent, passThroughData:Object=null ):void { var originalResponder:* = event.originalResponder; var isTestResponder:Boolean = false; if ( originalResponder is ITestResponder ) { isTestResponder = true; } if ( event.status == 'result' ) { if ( isTestResponder ) { originalResponder.result( event.data, passThroughData ); } else { originalResponder.result( event.data ); } } else { if ( isTestResponder ) { originalResponder.fault( event.data, passThroughData ); } else { originalResponder.fault( event.data ); } } } private function handleAsyncErrorFired( event:AsyncEvent ):void { var message:String = "Failing due to Async Event "; if ( event && event.originalEvent ) { message += String( event.originalEvent ); } sendComplete( new AssertionError( message ) ); } /** * Called when the asynchronous event has been fired prior to the timeout being reached. This method attempts to * call event handler that has been associated with the asychronous test. If no handler has * been specified, an error will be generated and the <code>ExpectAsync</code> statement finishes. * * @param event The <code>AsyncEvent</code> event that has been dispatched. */ private function handleAsyncEventFired( event:AsyncEvent ):void { //Receiving this event is a good things... IF it is the first one we are waiting for //If it is not the first one on the stack though, we still need to fail. var asyncHandler:AsyncHandler = event.target as AsyncHandler; var firstPendingAsync:AsyncHandler; var failure:Boolean = false; removeAsyncEventListeners( asyncHandler ); //Determine if any async calls remain if ( hasPendingAsync ) { //Get the first async call firstPendingAsync = pendingAsyncCalls.shift() as AsyncHandler; //Determine if this was the expected async handler if ( firstPendingAsync === asyncHandler ) { if ( asyncHandler.eventHandler != null ) { //this actually needs to be the event object from the previous event protect( asyncHandler.eventHandler, event.originalEvent, firstPendingAsync.passThroughData ); } } else { //The first one on the stack is not the one we received. //We received this one out of order, which is a failure condition failure = true; sendComplete( new AssertionError( "Asynchronous Event Received out of Order" ) ); //protect( Assert.fail, "Asynchronous Event Received out of Order" ); } } else { //We received an event, but we were not waiting for one, failure //protect( Assert.fail, "Unexpected Asynchronous Event Occurred" ); failure = true; sendComplete( new AssertionError( "Unexpected Asynchronous Event Occurred" ) ); } if ( !hasPendingAsync && !methodBodyExecuting && !failure ) { //We have no more pending async, *AND* the method body of the function that originated this message //has also finished, then let the test runner know /** var methodResult:TestMethodResult = testMonitor.getTestMethodResult( registeredMethod ); if ( methodResult && ( !methodResult.traceInformation ) ) { methodResult.executed = true; methodResult.testDuration = getTimer()-tickCountOnStart; methodResult.traceInformation = "Test completed via Async Event in " + methodResult.testDuration + "ms"; } **/ sendComplete(); } } /** * Handles the next steps in a <code>SequenceRunner</code>. * * @param event The event boradcast by the last step in the sequence. * @param sequenceRunner The runner responsible for running the steps in the sequence. */ public function handleNextSequence( event:Event, sequenceRunner:SequenceRunner ):void { if ( event && event.target ) { //Remove the listener for this particular item event.currentTarget.removeEventListener(event.type, handleNextSequence ); } sequenceRunner.continueSequence( event ); startAsyncTimers(); } /** * Creates an <code>IAsyncTestResponder</code> that pend and either call the <code>eventHandler</code> or the * <code>timeoutHandler</code>, passing the <code>passThroughData</code>, depending on whether the * <code>timeout</code> period has been reached. * * @param resultHandler The result <code>Function</code> that will be executed if the <code>Responder</code> is called on its result before * the <code>timeout</code> has expired. * @param faultHandler The fault <code>Function</code> that will be executed if the <code>Responder</code> is called on its fault before * the <code>timeout</code> has expired. * @param timeout The length of time, in milliseconds, before the <code>timeoutHandler</code> will be executed. * @param passThroughData An Object that can be given information about the current test; this information will * be available for both the <code>eventHandler</code> and the <code>timeoutHandler</code>. * @param timeoutHandler The Function that will be executed if the <code>timeout</code> time is reached prior to * the expected event being dispatched. * * @return an <code>IResponder</code> that will determine whether the <code>timeout</code> has been reached. */ public function asyncNativeResponder( resultHandler : Function, faultHandler : Function, timeout:int, passThroughData:Object = null, timeoutHandler:Function = null ):Responder { var asyncResponder:AsyncNativeTestResponder; asyncResponder = new AsyncNativeTestResponder( resultHandler, faultHandler ); var asyncHandler:AsyncHandler = new AsyncHandler( handleAsyncNativeTestResponderEvent, timeout, passThroughData, timeoutHandler ) asyncHandler.addEventListener( AsyncHandler.EVENT_FIRED, handleAsyncEventFired, false, 0, true ); asyncHandler.addEventListener( AsyncHandler.TIMER_EXPIRED, handleAsyncTimeOut, false, 0, true ); pendingAsyncCalls.push( asyncHandler ); asyncResponder.addEventListener( AsyncResponseEvent.RESPONDER_FIRED, asyncHandler.handleEvent, false, 0, true ); return asyncResponder; } /** * Handles the AsyncResponseEvent that is thrown by the asyncResponder. * It sends data to the original responder based on if it is a result or fault status. * * @param event * @param passThroughData * */ protected function handleAsyncNativeTestResponderEvent( event:AsyncResponseEvent, passThroughData:Object=null ):void { var methodHandler:Function = event.methodHandler; methodHandler.call(this, event.data); } /** * * @param event * @param sequenceRunner * */ // We have a toggle in the compiler arguments so that we can choose whether or not the flex classes should // be compiled into the FlexUnit swc. For actionscript only projects we do not want to compile the // flex classes since it will cause errors. CONFIG::useFlexClasses public function handleBindableNextSequence( event:Event, sequenceRunner:SequenceRunner ):void { if ( sequenceRunner.getPendingStep() is SequenceBindingWaiter ) { var sequenceBinding:SequenceBindingWaiter = sequenceRunner.getPendingStep() as SequenceBindingWaiter; if (event is PropertyChangeEvent) { var propName:Object = PropertyChangeEvent(event).property if (propName != sequenceBinding.propertyName) { Assert.fail( "Incorrect Property Change Event Received" ); } } if ( event && event.target ) { //Remove the listener for this particular item sequenceBinding.changeWatcher.unwatch(); //event.currentTarget.removeEventListener(event.type, handleBindableNextSequence ); sequenceRunner.continueSequence( event ); startAsyncTimers(); } } else { Assert.fail( "Event Received out of Order" ); } } /** * Starts the timers for each pending asynchronous call. */ private function startAsyncTimers():void { for ( var i:int=0; i<pendingAsyncCalls.length; i++ ) { ( pendingAsyncCalls[ i ] as AsyncHandler ).startTimer(); } } /** * If the test has not yet been marked as complete, mark the <code>ExpectAsync</code> statement as having finished * and notify the parent token. * * @param error The potential error to send to the parent token. */ override protected function sendComplete( error:Error = null ):void { //If the test has not completed, do not notify the parentToken that this statement has finished executing if ( !testComplete ) { methodBodyExecuting = false; testComplete = true; AsyncLocator.cleanUpCallableForTest( getObjectForRegistration( objectUnderTest ) ); removeAllAsyncEventListeners(); parentToken.sendResult( error ); } } /** * Retrieves the object used for registering this <code>ExpectAsync</code> which * implements <code>IAsyncHandlingStatement</code> * * @param obj The object used to obtain the registration object. */ private function getObjectForRegistration( obj:Object ):Object { var registrationObj:Object; if ( obj is TestClass ) { registrationObj = ( obj as TestClass ).asClass; } else { registrationObj = obj; } return registrationObj; } /** * Registers the <code>ExpectAsync</code> statment for the current object being tested and evaluates the object that * implements the <code>IAsyncStatement</code> that was provided to the <code>ExpectAsync</code> class. * * @param parentToken The token to be notified when the potential asynchronous call have finished. */ public function evaluate( parentToken:AsyncTestToken ):void { this.parentToken = parentToken; //Register this statement with the current object that is being tested AsyncLocator.registerStatementForTest( this, getObjectForRegistration( objectUnderTest ) ); methodBodyExecuting = true; statement.evaluate( myToken ); methodBodyExecuting = false; } /** * A handler method that is called in order to wait once an asynchronous event has been dispatched. * * @param event The event that was received. * @param passThroughData An Object that contains information to pass to the handler. */ public function pendUntilComplete( event:Event, passThroughData:Object=null ):void { } /** * A handler method that is called in order to fail for a given asynchronous event once an it * has been dispatched. * * @param event The event that was received. * @param passThroughData An Object that contains information to pass to the handler. */ public function failOnComplete( event:Event, passThroughData:Object ):void { var message:String = "Unexpected event received "; if ( event ) { message += String( event ); } sendComplete( new AssertionError( message ) ); } /** * Determines if there are any more pending asynchronous calls; if there are, keep running the calls if there are * no errors. If all calls have finished or an error was encountered in the <code>result</code>, report the error * to the parent token and stop tracking the asynchronous events. * * @param result The <code>ChildResult</code> to check to see if there is an error. */ public function handleNextExecuteComplete( result:ChildResult ):void { if ( pendingAsyncCalls.length == 0 ) { //we are all done, no more pending asyncs, we can go on and live a good life for the few moments before we are gced sendComplete( result.error ); //parentToken.sendResult( result.error ); } else { if ( result && result.error ) { //If we already have an error, we need to report it now, not coninue sendComplete( result.error ); } else { startAsyncTimers(); } } } /** * Determine if the <code>method</code> is asynchronous for a test method that is of the expected * metadata <code>type</code>. * * @param method The <code>FrameworkMethod</code> that is potentially asynchronous. * @param type The expected metadata type of the test method (ex: "Test", "Before", "After"). * * @return a Boolean value indicating whether the provided <code>method</code> is asynchronous. */ public static function hasAsync( method:FrameworkMethod, type:String=AnnotationConstants.TEST ):Boolean { var async:String = method.getSpecificMetaDataArgValue( type, AnnotationArgumentConstants.ASYNC ); var asyncBool:Boolean = ( async == "true" ); return asyncBool; } /** * Constructor. * * @param objectUnderTest The current object that is being tested. * @param statement The current <code>IAsyncStatement</code> that will be decorated with the * the <code>ExpectAsync</code> class. */ public function ExpectAsync( objectUnderTest:Object, statement:IAsyncStatement ) { this.objectUnderTest = objectUnderTest; this.statement = statement; //Create a new token that will alert this class when the provided statement has completed myToken = new AsyncTestToken( ClassNameUtil.getLoggerFriendlyClassName( this ) ); myToken.addNotificationMethod( handleNextExecuteComplete ); pendingAsyncCalls = new Array(); asyncFailureConditions = new Dictionary( true ); } } }
package awaybuilder.model.vo.scene { [Bindable] public class AnimatorVO extends AssetVO { public var type:String; public var playbackSpeed:Number = 1; public var animationSet:AnimationSetVO; public var skeleton:SkeletonVO; [Transient] public var activeAnimationNode:AnimationNodeVO; public function clone():AnimatorVO { var vo:AnimatorVO = new AnimatorVO(); vo.fillFromAnimator( this ); return vo; } public function fillFromAnimator( asset:AnimatorVO ):void { this.name = asset.name; this.animationSet = asset.animationSet; this.skeleton = asset.skeleton; this.playbackSpeed = asset.playbackSpeed; this.type = asset.type; } } }
package visuals.ui.dialogs { import com.playata.framework.display.Sprite; import com.playata.framework.display.lib.flash.FlashDisplayObjectContainer; import com.playata.framework.display.lib.flash.FlashLabel; import com.playata.framework.display.lib.flash.FlashLabelArea; import com.playata.framework.display.lib.flash.FlashSprite; import com.playata.framework.display.ui.controls.ILabel; import com.playata.framework.display.ui.controls.ILabelArea; import flash.display.MovieClip; import visuals.ui.base.SymbolPlaceholderGeneric; import visuals.ui.base.SymbolUiButtonDefaultGeneric; import visuals.ui.elements.backgrounds.SymbolSlice9BackgroundDialogGeneric; import visuals.ui.elements.conventions.SymbolConventionRewardGeneric; import visuals.ui.elements.icons.SymbolIconCharacterSmallGeneric; import visuals.ui.elements.icons.SymbolIconVisitorsGeneric; import visuals.ui.elements.icons.SymbolIconXpGeneric; import visuals.ui.elements.item.SymbolItemSlotGeneric; import visuals.ui.elements.quest.SymbolNPCPictureGeneric; public class SymbolDialogConventionCompleteGeneric extends Sprite { private var _nativeObject:SymbolDialogConventionComplete = null; public var conventionBannerRight:SymbolPlaceholderGeneric = null; public var conventionBannerLeft:SymbolPlaceholderGeneric = null; public var dialogBackground:SymbolSlice9BackgroundDialogGeneric = null; public var txtDialogTitle:ILabel = null; public var txtNpcName:ILabel = null; public var btnClose:SymbolUiButtonDefaultGeneric = null; public var iconXp:SymbolIconXpGeneric = null; public var txtXp:ILabel = null; public var reward1:SymbolConventionRewardGeneric = null; public var txtRewardsCaption:ILabel = null; public var txtStatisticCaption:ILabel = null; public var txtTopCaption:ILabel = null; public var symbolIconVisitors:SymbolIconVisitorsGeneric = null; public var iconWinningShow:SymbolIconCharacterSmallGeneric = null; public var txtFansTotal:ILabel = null; public var txtShowCountTotal:ILabel = null; public var txtShowCountOwn:ILabel = null; public var txtTopShows:ILabel = null; public var txtWinningShow:ILabel = null; public var itemReward:SymbolItemSlotGeneric = null; public var conventionLogo:SymbolNPCPictureGeneric = null; public var txtFailed:ILabelArea = null; public var txtSuccessful:ILabelArea = null; public var txtNoRewardText:ILabelArea = null; public function SymbolDialogConventionCompleteGeneric(param1:MovieClip = null) { if(param1) { _nativeObject = param1 as SymbolDialogConventionComplete; } else { _nativeObject = new SymbolDialogConventionComplete(); } super(null,FlashSprite.fromNative(_nativeObject)); var _loc2_:FlashDisplayObjectContainer = _sprite as FlashDisplayObjectContainer; conventionBannerRight = new SymbolPlaceholderGeneric(_nativeObject.conventionBannerRight); conventionBannerLeft = new SymbolPlaceholderGeneric(_nativeObject.conventionBannerLeft); dialogBackground = new SymbolSlice9BackgroundDialogGeneric(_nativeObject.dialogBackground); txtDialogTitle = FlashLabel.fromNative(_nativeObject.txtDialogTitle); txtNpcName = FlashLabel.fromNative(_nativeObject.txtNpcName); btnClose = new SymbolUiButtonDefaultGeneric(_nativeObject.btnClose); iconXp = new SymbolIconXpGeneric(_nativeObject.iconXp); txtXp = FlashLabel.fromNative(_nativeObject.txtXp); reward1 = new SymbolConventionRewardGeneric(_nativeObject.reward1); txtRewardsCaption = FlashLabel.fromNative(_nativeObject.txtRewardsCaption); txtStatisticCaption = FlashLabel.fromNative(_nativeObject.txtStatisticCaption); txtTopCaption = FlashLabel.fromNative(_nativeObject.txtTopCaption); symbolIconVisitors = new SymbolIconVisitorsGeneric(_nativeObject.symbolIconVisitors); iconWinningShow = new SymbolIconCharacterSmallGeneric(_nativeObject.iconWinningShow); txtFansTotal = FlashLabel.fromNative(_nativeObject.txtFansTotal); txtShowCountTotal = FlashLabel.fromNative(_nativeObject.txtShowCountTotal); txtShowCountOwn = FlashLabel.fromNative(_nativeObject.txtShowCountOwn); txtTopShows = FlashLabel.fromNative(_nativeObject.txtTopShows); txtWinningShow = FlashLabel.fromNative(_nativeObject.txtWinningShow); itemReward = new SymbolItemSlotGeneric(_nativeObject.itemReward); conventionLogo = new SymbolNPCPictureGeneric(_nativeObject.conventionLogo); txtFailed = FlashLabelArea.fromNative(_nativeObject.txtFailed); txtSuccessful = FlashLabelArea.fromNative(_nativeObject.txtSuccessful); txtNoRewardText = FlashLabelArea.fromNative(_nativeObject.txtNoRewardText); } public function setNativeInstance(param1:SymbolDialogConventionComplete) : void { FlashSprite.setNativeInstance(_sprite,param1); _nativeObject = param1; syncInstances(); } public function syncInstances() : void { if(_nativeObject.conventionBannerRight) { conventionBannerRight.setNativeInstance(_nativeObject.conventionBannerRight); } if(_nativeObject.conventionBannerLeft) { conventionBannerLeft.setNativeInstance(_nativeObject.conventionBannerLeft); } if(_nativeObject.dialogBackground) { dialogBackground.setNativeInstance(_nativeObject.dialogBackground); } FlashLabel.setNativeInstance(txtDialogTitle,_nativeObject.txtDialogTitle); FlashLabel.setNativeInstance(txtNpcName,_nativeObject.txtNpcName); if(_nativeObject.btnClose) { btnClose.setNativeInstance(_nativeObject.btnClose); } if(_nativeObject.iconXp) { iconXp.setNativeInstance(_nativeObject.iconXp); } FlashLabel.setNativeInstance(txtXp,_nativeObject.txtXp); if(_nativeObject.reward1) { reward1.setNativeInstance(_nativeObject.reward1); } FlashLabel.setNativeInstance(txtRewardsCaption,_nativeObject.txtRewardsCaption); FlashLabel.setNativeInstance(txtStatisticCaption,_nativeObject.txtStatisticCaption); FlashLabel.setNativeInstance(txtTopCaption,_nativeObject.txtTopCaption); if(_nativeObject.symbolIconVisitors) { symbolIconVisitors.setNativeInstance(_nativeObject.symbolIconVisitors); } if(_nativeObject.iconWinningShow) { iconWinningShow.setNativeInstance(_nativeObject.iconWinningShow); } FlashLabel.setNativeInstance(txtFansTotal,_nativeObject.txtFansTotal); FlashLabel.setNativeInstance(txtShowCountTotal,_nativeObject.txtShowCountTotal); FlashLabel.setNativeInstance(txtShowCountOwn,_nativeObject.txtShowCountOwn); FlashLabel.setNativeInstance(txtTopShows,_nativeObject.txtTopShows); FlashLabel.setNativeInstance(txtWinningShow,_nativeObject.txtWinningShow); if(_nativeObject.itemReward) { itemReward.setNativeInstance(_nativeObject.itemReward); } if(_nativeObject.conventionLogo) { conventionLogo.setNativeInstance(_nativeObject.conventionLogo); } FlashLabelArea.setNativeInstance(txtFailed,_nativeObject.txtFailed); FlashLabelArea.setNativeInstance(txtSuccessful,_nativeObject.txtSuccessful); FlashLabelArea.setNativeInstance(txtNoRewardText,_nativeObject.txtNoRewardText); } } }
package rumorPlot.extPlot.script { import rumorPlot.plot.script.Script; import rumorPlot.command.PlotActiviteCommand; public class EndPlotScript extends Script { public function EndPlotScript() { super(); } override public function activate() : void { var _loc1_:int = int(scriptInfo.paramArg.paramArgVect[0].value); new PlotActiviteCommand(_loc1_,PlotActiviteCommand.END).call(); super.activate(); } override public function deactivate(param1:Boolean = false) : void { super.deactivate(param1); } } }
package nid.xfl.compiler.swf.tags { import nid.xfl.compiler.swf.SWFData; import nid.xfl.compiler.swf.data.SWFSoundInfo; public class TagStartSound2 implements ITag { public static const TYPE:uint = 89; public var soundClassName:String; public var soundInfo:SWFSoundInfo; public function TagStartSound2() {} public function parse(data:SWFData, length:uint, version:uint, async:Boolean = false):void { soundClassName = data.readString(); soundInfo = data.readSOUNDINFO(); } public function publish(data:SWFData, version:uint):void { var body:SWFData = new SWFData(); body.writeString(soundClassName); body.writeSOUNDINFO(soundInfo); data.writeTagHeader(type, body.length); data.writeBytes(body); } public function get type():uint { return TYPE; } public function get name():String { return "StartSound2"; } public function get version():uint { return 9; } public function get level():uint { return 2; } public function toString(indent:uint = 0):String { var str:String = Tag.toStringCommon(type, name, indent) + "SoundClassName: " + soundClassName + ", " + "SoundInfo: " + soundInfo; return str; } } }
package shop.view { import baglocked.BaglockedManager; import com.pickgliss.events.FrameEvent; import com.pickgliss.ui.ComponentFactory; import com.pickgliss.ui.LayerManager; import com.pickgliss.ui.controls.BaseButton; import com.pickgliss.ui.controls.Frame; import com.pickgliss.ui.controls.ScrollPanel; import com.pickgliss.ui.controls.container.VBox; import com.pickgliss.ui.core.Disposeable; import com.pickgliss.ui.image.Scale9CornerImage; import com.pickgliss.ui.text.FilterFrameText; import com.pickgliss.utils.ObjectUtils; import ddt.data.EquipType; import ddt.data.goods.ShopCarItemInfo; import ddt.manager.LanguageMgr; import ddt.manager.LeavePageManager; import ddt.manager.PlayerManager; import ddt.manager.ShopManager; import ddt.manager.SocketManager; import ddt.manager.SoundManager; import flash.display.Bitmap; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import shop.manager.ShopBuyManager; public class BuyMultiGoodsView extends Sprite implements Disposeable { private var _bg:Scale9CornerImage; private var _commodityNumberText:FilterFrameText; private var _commodityPricesText1:FilterFrameText; private var _commodityPricesText2:FilterFrameText; private var _commodityPricesText3:FilterFrameText; private var _purchaseConfirmationBtn:BaseButton; private var _buyArray:Vector.<ShopCarItemInfo>; private var _cartList:VBox; private var _cartScroll:ScrollPanel; private var _frame:Frame; private var _innerBg1:Bitmap; private var _innerBg:Bitmap; private var _extraTextButton:BaseButton; public var dressing:Boolean = false; public function BuyMultiGoodsView() { super(); this.initView(); this.initEvents(); } private function initView() : void { this._frame = ComponentFactory.Instance.creatComponentByStylename("shop.CheckOutViewFrame"); this._frame.titleText = LanguageMgr.GetTranslation("shop.Shop.car"); addChild(this._frame); this._cartList = new VBox(); this._bg = ComponentFactory.Instance.creatComponentByStylename("shop.CheckOutViewBg"); this._purchaseConfirmationBtn = ComponentFactory.Instance.creatComponentByStylename("shop.PurchaseConfirmation"); this._cartScroll = ComponentFactory.Instance.creatComponentByStylename("shop.CheckOutViewItemList"); this._extraTextButton = ComponentFactory.Instance.creatComponentByStylename("shop.PurchaseConfirmation"); this._cartScroll.setView(this._cartList); this._cartScroll.vScrollProxy = ScrollPanel.ON; this._cartList.spacing = 5; this._cartList.strictSize = 80; this._cartList.isReverAdd = true; this._frame.addToContent(this._bg); this._innerBg1 = ComponentFactory.Instance.creatBitmap("asset.shop.CheckOutViewBg1"); this._frame.addToContent(this._innerBg1); this._commodityNumberText = ComponentFactory.Instance.creatComponentByStylename("shop.CommodityNumberText"); this._frame.addToContent(this._commodityNumberText); this._innerBg = ComponentFactory.Instance.creatBitmap("asset.shop.CheckOutViewBg"); this._commodityPricesText1 = ComponentFactory.Instance.creatComponentByStylename("shop.CommodityPricesText1"); this._commodityPricesText2 = ComponentFactory.Instance.creatComponentByStylename("shop.CommodityPricesText2"); this._commodityPricesText3 = ComponentFactory.Instance.creatComponentByStylename("shop.CommodityPricesText3"); this._frame.addToContent(this._innerBg); this._frame.addToContent(this._commodityPricesText1); this._frame.addToContent(this._commodityPricesText2); this._frame.addToContent(this._commodityPricesText3); this._frame.addToContent(this._cartScroll); this._frame.addToContent(this._purchaseConfirmationBtn); } public function show() : void { LayerManager.Instance.addToLayer(this,LayerManager.GAME_DYNAMIC_LAYER,true,LayerManager.ALPHA_BLOCKGOUND,true); } protected function updateTxt() : void { var _loc1_:Array = ShopBuyManager.calcPrices(this._buyArray); this._commodityNumberText.text = String(this._buyArray.length); this._commodityPricesText1.text = String(_loc1_[1]); this._commodityPricesText2.text = String(_loc1_[2]); this._commodityPricesText3.text = String(_loc1_[3]); } private function initEvents() : void { this._purchaseConfirmationBtn.addEventListener(MouseEvent.CLICK,this.__buyAvatar); this._frame.addEventListener(FrameEvent.RESPONSE,this.__onResponse); } private function removeEvents() : void { this._purchaseConfirmationBtn.removeEventListener(MouseEvent.CLICK,this.__buyAvatar); this._frame.removeEventListener(FrameEvent.RESPONSE,this.__onResponse); } private function __onResponse(param1:FrameEvent) : void { switch(param1.responseCode) { case FrameEvent.CLOSE_CLICK: case FrameEvent.ESC_CLICK: SoundManager.instance.playButtonSound(); this.dispose(); default: SoundManager.instance.playButtonSound(); this.dispose(); } } private function __buyAvatar(param1:MouseEvent) : void { var _loc3_:ShopCarItemInfo = null; var _loc4_:Array = null; var _loc14_:ShopCartItem = null; var _loc15_:ShopCarItemInfo = null; var _loc16_:ShopCarItemInfo = null; SoundManager.instance.play("008"); if(PlayerManager.Instance.Self.bagLocked) { BaglockedManager.Instance.show(); return; } var _loc2_:Array = []; for each(_loc3_ in this._buyArray) { _loc2_.push(_loc3_); } _loc4_ = ShopManager.Instance.buyIt(_loc2_); if(_loc4_.length == 0) { for each(_loc15_ in this._buyArray) { if(_loc15_.getCurrentPrice().moneyValue > 0) { LeavePageManager.showFillFrame(); return; } } } else if(_loc4_.length < this._buyArray.length) { } var _loc5_:Array = new Array(); var _loc6_:Array = new Array(); var _loc7_:Array = new Array(); var _loc8_:Array = new Array(); var _loc9_:Array = new Array(); var _loc10_:Array = []; var _loc11_:int = 0; while(_loc11_ < this._buyArray.length) { _loc16_ = this._buyArray[_loc11_]; _loc5_.push(_loc16_.GoodsID); _loc6_.push(_loc16_.currentBuyType); _loc7_.push(_loc16_.Color); _loc9_.push(_loc16_.place); if(_loc16_.CategoryID == EquipType.FACE) { _loc10_.push(_loc16_.skin); } else { _loc10_.push(""); } _loc8_.push(this.dressing); _loc11_++; } SocketManager.Instance.out.sendBuyGoods(_loc5_,_loc6_,_loc7_,_loc9_,_loc8_,_loc10_); var _loc12_:Array = []; var _loc13_:int = 0; while(_loc13_ < this._cartList.numChildren) { _loc12_.push(this._cartList.getChildAt(_loc13_)); _loc13_++; } for each(_loc14_ in _loc12_) { if(_loc4_.indexOf(_loc14_.shopItemInfo) > -1) { _loc14_.removeEventListener(ShopCartItem.DELETE_ITEM,this.__deleteItem); _loc14_.removeEventListener(ShopCartItem.CONDITION_CHANGE,this.__conditionChange); this._cartList.removeChild(_loc14_); _loc14_.dispose(); this._buyArray.splice(this._buyArray.indexOf(_loc14_.shopItemInfo),1); } } if(this._cartList.numChildren == 0) { this.dispose(); } else { this.updateTxt(); } } public function setGoods(param1:Vector.<ShopCarItemInfo>) : void { var _loc2_:ShopCarItemInfo = null; var _loc3_:ShopCartItem = null; var _loc4_:ShopCartItem = null; while(this._cartList.numChildren > 0) { _loc3_ = this._cartList.getChildAt(this._cartList.numChildren - 1) as ShopCartItem; _loc3_.removeEventListener(ShopCartItem.DELETE_ITEM,this.__deleteItem); _loc3_.removeEventListener(ShopCartItem.CONDITION_CHANGE,this.__conditionChange); this._cartList.removeChild(_loc3_); _loc3_.dispose(); } this._buyArray = param1; for each(_loc2_ in this._buyArray) { _loc4_ = new ShopCartItem(); _loc4_.shopItemInfo = _loc2_; _loc4_.setColor(_loc2_.Color); this._cartList.addChild(_loc4_); _loc4_.addEventListener(ShopCartItem.DELETE_ITEM,this.__deleteItem); _loc4_.addEventListener(ShopCartItem.CONDITION_CHANGE,this.__conditionChange); } this._cartScroll.invalidateViewport(); this.updateTxt(); } private function __conditionChange(param1:Event) : void { this.updateTxt(); } private function __deleteItem(param1:Event) : void { var _loc2_:ShopCartItem = param1.currentTarget as ShopCartItem; var _loc3_:ShopCarItemInfo = _loc2_.shopItemInfo; _loc2_.removeEventListener(ShopCartItem.DELETE_ITEM,this.__deleteItem); _loc2_.removeEventListener(ShopCartItem.CONDITION_CHANGE,this.__conditionChange); this._cartList.removeChild(_loc2_); var _loc4_:int = this._buyArray.indexOf(_loc3_); this._buyArray.splice(_loc4_,1); this.updateTxt(); this._cartScroll.invalidateViewport(); if(this._buyArray.length < 1) { this.dispose(); } } public function dispose() : void { var _loc1_:ShopCartItem = null; this.removeEvents(); while(this._cartList.numChildren > 0) { _loc1_ = this._cartList.getChildAt(this._cartList.numChildren - 1) as ShopCartItem; _loc1_.removeEventListener(ShopCartItem.DELETE_ITEM,this.__deleteItem); _loc1_.removeEventListener(ShopCartItem.CONDITION_CHANGE,this.__conditionChange); this._cartList.removeChild(_loc1_); _loc1_.dispose(); } ObjectUtils.disposeObject(this._bg); this._bg = null; ObjectUtils.disposeObject(this._commodityNumberText); this._commodityNumberText = null; ObjectUtils.disposeObject(this._commodityPricesText1); this._commodityPricesText1 = null; ObjectUtils.disposeObject(this._commodityPricesText2); this._commodityPricesText2 = null; ObjectUtils.disposeObject(this._commodityPricesText3); this._commodityPricesText3 = null; ObjectUtils.disposeObject(this._purchaseConfirmationBtn); this._purchaseConfirmationBtn = null; this._buyArray = null; ObjectUtils.disposeObject(this._cartList); this._cartList = null; ObjectUtils.disposeObject(this._cartScroll); this._cartScroll = null; ObjectUtils.disposeObject(this._frame); this._frame = null; ObjectUtils.disposeObject(this._bg); this._innerBg1 = null; ObjectUtils.disposeObject(this._innerBg1); this._innerBg = null; ObjectUtils.disposeObject(this._extraTextButton); this._extraTextButton = null; if(parent) { parent.removeChild(this); } } } }
package kabam.rotmg.game.view.components { import flash.display.DisplayObjectContainer; public class QueuedStatusTextList { public var target:DisplayObjectContainer; private var head:QueuedStatusText; private var tail:QueuedStatusText; public function shift():void { this.target.removeChild(this.head); this.head = this.head.next; if (this.head) { this.target.addChild(this.head); } else { this.tail = null; } } public function append(_arg1:QueuedStatusText):void { _arg1.list = this; if (this.tail) { this.tail.next = _arg1; this.tail = _arg1; } else { this.head = (this.tail = _arg1); this.target.addChild(_arg1); } } } }
package kabam.rotmg.dialogs.model { import org.osflash.signals.Signal; public class PopupQueueEntry { private var _name:String; private var _signal:Signal; private var _showingPerDay:int; private var _paramObject:Object; public function PopupQueueEntry(param1:String, param2:Signal, param3:int, param4:Object) { super(); this._name = param1; this._signal = param2; this._showingPerDay = param3; this._paramObject = param4; } public function get name() : String { return this._name; } public function set name(param1:String) : void { this._name = param1; } public function get signal() : Signal { return this._signal; } public function set signal(param1:Signal) : void { this._signal = param1; } public function get showingPerDay() : int { return this._showingPerDay; } public function set showingPerDay(param1:int) : void { this._showingPerDay = param1; } public function get paramObject() : Object { return this._paramObject; } public function set paramObject(param1:Object) : void { this._paramObject = param1; } } }
package utils.location { public class locationNames { /** Firefox */ public static const BROWSER_FIREFOX:String = "browserFirefox"; /** Safari */ public static const BROWSER_SAFARI:String = "browserSafari"; /** Internet Explorer */ public static const BROWSER_IE:String = "browserIE"; /** Opera */ public static const BROWSER_OPERA:String = "browserOpera"; /** Undefined browser */ public static const BROWSER_UNDEFINED:String = "browserUndefined"; /** Standalone player */ public static const STANDALONE_PLAYER:String = "standalonePlayer"; } }
package shootemup.gameobject.ui { import flash.display.MovieClip; import flash.display.SimpleButton; import flash.events.MouseEvent; import flash.system.fscommand; import engine.gameobject.Component; import engine.gameobject.GameObject; import engine.locator.Locator; import engine.time.TimeManager; import shootemup.game.ShootEmUp; import shootemup.gameobject.input.InputComponent; // used to display the pause menu public class PauseMenuComponent extends Component { private var shootEmUp_: ShootEmUp = null; private var pauseMenuResumeButton_: SimpleButton = null; private var pauseMenuRestartButton_: SimpleButton = null; private var pauseMenuQuitButton_: SimpleButton = null; private var menuBackground_: MovieClip = null; private var input_: InputComponent = null; private var timeManager_: TimeManager = null; private var cooldownTime_: Number = 0.1; private var lastPressed_: Number = 0; private var isPaused_: Boolean = false; public override function update(): void { var currentInputs = this.input_.getInputs(); if (!currentInputs["pause"]) { return; } var now: Number = this.timeManager_.getRealNow() / 1000; if (now - this.lastPressed_ < this.cooldownTime_) { return; } this.lastPressed_ = now; if (!this.isPaused_) { this.pauseGame(); } else { this.resumeGame(null); } } public override function initialize(descr: Object = null): void { if (descr == null) { throw new Error("Description for menu component cannot be null"); } this.type_ = "pause"; if (descr["shootEmUp"] == null) { throw new Error("Missing mandatory argument: shoot 'em up game"); } this.shootEmUp_ = descr["shootEmUp"] if (descr["pauseMenuResumeButton"] == null) { throw new Error("Missing mandatory argument: resume button"); } this.pauseMenuResumeButton_ = descr["pauseMenuResumeButton"]; if (descr["pauseMenuRestartButton"] == null) { throw new Error("Missing mandatory argument: restart button"); } this.pauseMenuRestartButton_ = descr["pauseMenuRestartButton"]; if (descr["pauseMenuQuitButton"] == null) { throw new Error("Missing mandatory argument: quit button"); } this.pauseMenuQuitButton_ = descr["pauseMenuQuitButton"]; if (descr["menuBackground"] == null) { throw new Error("Missing mandatory argument: menu background"); } this.menuBackground_ = descr["menuBackground"]; this.input_ = Locator.gameObjectManager().getPlayerGameObject().getComponent("input") as InputComponent; if (this.input_ == null) { throw new Error("Game object must have an input component"); } this.shootEmUp_ = Locator.game() as ShootEmUp; this.timeManager_ = Locator.timeManager(); this.pauseMenuResumeButton_.addEventListener(MouseEvent.CLICK, this.resumeGame); this.pauseMenuRestartButton_.addEventListener(MouseEvent.CLICK, this.restartGame); this.pauseMenuQuitButton_.addEventListener(MouseEvent.CLICK, this.quitGame); this.hide(); } public function show(): void { this.pauseMenuResumeButton_.visible = true; this.pauseMenuRestartButton_.visible = true; this.pauseMenuQuitButton_.visible = true; this.menuBackground_.visible = true; } public function hide(): void { this.pauseMenuResumeButton_.visible = false; this.pauseMenuRestartButton_.visible = false; this.pauseMenuQuitButton_.visible = false; this.menuBackground_.visible = false; } private function pauseGame(): void { this.show(); this.isPaused_ = true; this.timeManager_.stop(); } private function resumeGame(mouseEvent: MouseEvent): void { this.hide(); this.isPaused_ = false; this.timeManager_.resume(); } private function restartGame(mouseEvent: MouseEvent): void { this.hide(); this.isPaused_ = false; this.timeManager_.resume(); this.shootEmUp_.start(); } private function quitGame(mouseEvent: MouseEvent): void { fscommand("quit"); } public function PauseMenuComponent(gameObject: GameObject, descr: Object = null) { super(gameObject, descr); } } }
package de.popforge.revive.application { import de.popforge.revive.display.IDrawAble; import de.popforge.revive.forces.FixedSpring; import de.popforge.revive.geom.Vec2D; import de.popforge.revive.member.ImmovableGate; import de.popforge.revive.member.MovableCircle; import de.popforge.revive.member.MovableParticle; import de.popforge.revive.member.Movable; import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; public class SceneContainer extends Sprite { static public function debugStop(): void { instance.simulation.debugStop(); instance.onRemoved( null ); } static private var instance: SceneContainer; static protected const COLOR_FORCE: uint = 0xcc6633; static protected const COLOR_MOVABLE: uint = 0xababab; static protected const COLOR_IMMOVABLE: uint = 0x878787; static protected const WIDTH: uint = 512; static protected const HEIGHT: uint = 512; static private const MOUSE_CATCH_DISTANCE2: Number = 16 * 16; static private const MOUSE_CATCH_STRENGTH: Number = .025; public var simulation: Simulation; protected var iShape: Shape; protected var mShape: Shape; protected var mouseSpring: FixedSpring; public function SceneContainer() { instance = this; //-- DISPLAY --// iShape = new Shape(); mShape = new Shape(); addChild( iShape ); addChild( mShape ); simulation = new Simulation(); addEventListener( Event.ADDED, onAdded ); addEventListener( Event.REMOVED, onRemoved ); } protected function createStageBounds(): void { var immovable: ImmovableGate; immovable = new ImmovableGate( WIDTH, 0, 0, 0 ); simulation.addImmovable( immovable ); immovable = new ImmovableGate( 0, HEIGHT, WIDTH, HEIGHT ); simulation.addImmovable( immovable ); immovable = new ImmovableGate( 0, 0, 0, HEIGHT ); simulation.addImmovable( immovable ); immovable = new ImmovableGate( WIDTH, HEIGHT, WIDTH, 0 ); simulation.addImmovable( immovable ); } protected function drawImmovables(): void { iShape.graphics.lineStyle( 0, COLOR_IMMOVABLE ); var drawAble: IDrawAble; for each( drawAble in simulation.immovables ) { drawAble.draw( iShape.graphics ); } } protected function onAdded( event: Event ): void { stage.addEventListener( Event.ENTER_FRAME, onEnterFrame ); stage.addEventListener( MouseEvent.MOUSE_DOWN, onMouseDown ); stage.addEventListener( MouseEvent.MOUSE_UP, onMouseUp ); } protected function onRemoved( event: Event ): void { stage.removeEventListener( Event.ENTER_FRAME, onEnterFrame ); stage.removeEventListener( MouseEvent.MOUSE_DOWN, onMouseDown ); stage.removeEventListener( MouseEvent.MOUSE_UP, onMouseUp ); } protected function onEnterFrame( event: Event ): void { if (event == null) { simulation.nextFrame(); return; } if( mouseSpring ) { mouseSpring.x = mouseX; mouseSpring.y = mouseY; } simulation.nextFrame(); // simulation.nextFrame(); //-- UPDATE DISPLAY --// var drawAble: IDrawAble; mShape.graphics.clear(); mShape.graphics.lineStyle( 0, COLOR_MOVABLE ); for each( drawAble in simulation.movables ) { drawAble.draw( mShape.graphics ); } mShape.graphics.lineStyle( 0, COLOR_FORCE ); for each( drawAble in simulation.forces ) { drawAble.draw( mShape.graphics ); } } private function onMouseDown( event: MouseEvent ): void { var movable: Movable; var dx: Number; var dy: Number; for each( movable in simulation.movables ) { if( movable is MovableParticle || movable is MovableCircle ) { dx = MovableParticle( movable ).x - mouseX; dy = MovableParticle( movable ).y - mouseY; if( dx * dx + dy * dy < MOUSE_CATCH_DISTANCE2 ) { mouseSpring = new FixedSpring( mouseX, mouseY, MovableParticle( movable ), MOUSE_CATCH_STRENGTH, 0 ); simulation.addForce( mouseSpring ); break; } } } } private function onMouseUp( event: MouseEvent ): void { if( mouseSpring ) { simulation.removeForce( mouseSpring ); mouseSpring = null; } } } }
package im { import bagAndInfo.BagAndGiftFrame; import bagAndInfo.BagAndInfoManager; import com.pickgliss.toplevel.StageReferance; import com.pickgliss.ui.ComponentFactory; import com.pickgliss.ui.ComponentSetting; import com.pickgliss.ui.LayerManager; import com.pickgliss.ui.controls.BaseButton; import com.pickgliss.ui.controls.Frame; import com.pickgliss.ui.controls.SelectedButton; import com.pickgliss.ui.controls.SelectedButtonGroup; import com.pickgliss.ui.controls.TextButton; import com.pickgliss.ui.controls.list.DropList; import com.pickgliss.ui.image.MovieImage; import com.pickgliss.ui.text.FilterFrameText; import com.pickgliss.ui.text.GradientText; import com.pickgliss.utils.ObjectUtils; import ddt.data.player.PlayerInfo; import ddt.data.player.PlayerState; import ddt.data.player.SelfInfo; import ddt.events.PlayerPropertyEvent; import ddt.manager.AcademyFrameManager; import ddt.manager.AcademyManager; import ddt.manager.ChatManager; import ddt.manager.LanguageMgr; import ddt.manager.MessageTipManager; import ddt.manager.PathManager; import ddt.manager.PlayerManager; import ddt.manager.ServerManager; import ddt.manager.SharedManager; import ddt.manager.SoundManager; import ddt.manager.StateManager; import ddt.states.StateType; import ddt.view.PlayerPortraitView; import ddt.view.common.LevelIcon; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.URLVariables; import flash.utils.Dictionary; import road7th.utils.StringHelper; import socialContact.SocialContactManager; import vip.VipController; public class IMView extends Frame { public static var IS_SHOW_SUB:Boolean; private static const ALL_STATE:Array = [new PlayerState(PlayerState.ONLINE,PlayerState.MANUAL),new PlayerState(PlayerState.AWAY,PlayerState.MANUAL),new PlayerState(PlayerState.BUSY,PlayerState.MANUAL),new PlayerState(PlayerState.NO_DISTRUB,PlayerState.MANUAL),new PlayerState(PlayerState.SHOPPING,PlayerState.MANUAL)]; public static const FRIEND_LIST:int = 0; public static const CMFRIEND_LIST:int = 2; public static const CONSORTIA_LIST:int = 1; public static const LIKEFRIEND_LIST:int = 3; private var _CMSelectedBtn:SelectedButton; private var _IMSelectedBtn:SelectedButton; private var _likePersonSelectedBtn:SelectedButton; private var _addBlackFrame:AddBlackFrame; private var _addBleak:BaseButton; private var _addFriend:BaseButton; private var _myAcademyBtn:BaseButton; private var _inviteBtn:TextButton; private var _addFriendFrame:AddFriendFrame; private var _bg:MovieImage; private var _consortiaListBtn:SelectedButton; private var _levelIcon:LevelIcon; private var _selectedButtonGroup:SelectedButtonGroup; private var _currentListType:int; private var _friendList:IMListView; private var _consortiaList:ConsortiaListView; private var _CMfriendList:CMFriendList; private var _likeFriendList:LikeFriendListView; private var _listContent:Sprite; private var _selfName:FilterFrameText; private var _vipName:GradientText; private var _playerPortrait:PlayerPortraitView; private var _imLookupView:IMLookupView; private var _stateSelectBtn:StateIconButton; private var _stateList:DropList; private var _replyInput:AutoReplyInput; private var _state:FilterFrameText; public function IMView() { super(); super.init(); this.initContent(); this.initEvent(); } private function initContent() : void { titleText = LanguageMgr.GetTranslation("tank.game.ToolStripView.friend"); this._bg = ComponentFactory.Instance.creatComponentByStylename("IM.BGMovieImage"); addToContent(this._bg); this._selfName = ComponentFactory.Instance.creatComponentByStylename("IM.IMList.selfName"); this._selfName.text = PlayerManager.Instance.Self.NickName; if(PlayerManager.Instance.Self.IsVIP) { this._vipName = VipController.instance.getVipNameTxt(138,PlayerManager.Instance.Self.typeVIP); this._vipName.textSize = 18; this._vipName.x = this._selfName.x; this._vipName.y = this._selfName.y; this._vipName.text = this._selfName.text; addToContent(this._vipName); } else { addToContent(this._selfName); } this._IMSelectedBtn = ComponentFactory.Instance.creatComponentByStylename("IMView.IMSelectedBtn"); this._IMSelectedBtn.transparentEnable = true; addToContent(this._IMSelectedBtn); if(PathManager.CommnuntyMicroBlog()) { this._CMSelectedBtn = ComponentFactory.Instance.creatComponentByStylename("IMView.MBSelectedBtn"); this._CMSelectedBtn.transparentEnable = true; addToContent(this._CMSelectedBtn); if(SharedManager.Instance.isCommunity && PathManager.CommunityExist()) { this._CMSelectedBtn.visible = true; } else { this._CMSelectedBtn.visible = false; } } else { this._CMSelectedBtn = ComponentFactory.Instance.creatComponentByStylename("IMView.CMSelectedBtn"); this._CMSelectedBtn.transparentEnable = true; if(SharedManager.Instance.isCommunity && PathManager.CommunityExist()) { addToContent(this._CMSelectedBtn); } else { this._CMSelectedBtn.visible = false; } } this._consortiaListBtn = ComponentFactory.Instance.creatComponentByStylename("IMView.consortiaListBtn"); this._consortiaListBtn.transparentEnable = true; addToContent(this._consortiaListBtn); this._likePersonSelectedBtn = ComponentFactory.Instance.creatComponentByStylename("IMView.LikeSelectedBtn"); if(!(SharedManager.Instance.isCommunity && PathManager.CommunityExist())) { this._likePersonSelectedBtn.x = this._CMSelectedBtn.x; } addToContent(this._likePersonSelectedBtn); this._selectedButtonGroup = new SelectedButtonGroup(); this._selectedButtonGroup.addSelectItem(this._IMSelectedBtn); this._selectedButtonGroup.addSelectItem(this._consortiaListBtn); this._selectedButtonGroup.addSelectItem(this._CMSelectedBtn); this._selectedButtonGroup.addSelectItem(this._likePersonSelectedBtn); this._selectedButtonGroup.selectIndex = 0; this._addFriend = ComponentFactory.Instance.creatComponentByStylename("IM.AddFriendBtn"); this._addFriend.tipData = LanguageMgr.GetTranslation("tank.view.im.AddFriendFrame.add"); addToContent(this._addFriend); this._addBleak = ComponentFactory.Instance.creatComponentByStylename("IM.AddBleakBtn"); this._addBleak.tipData = LanguageMgr.GetTranslation("tank.view.im.AddBlackListFrame.btnText"); addToContent(this._addBleak); this._levelIcon = ComponentFactory.Instance.creatCustomObject("IM.imView.LevelIcon"); this._levelIcon.setSize(LevelIcon.SIZE_BIG); addToContent(this._levelIcon); this._listContent = new Sprite(); addToContent(this._listContent); this._imLookupView = new IMLookupView(); var _loc1_:Point = ComponentFactory.Instance.creatCustomObject("IM.IMView.IMLookupViewPos"); this._imLookupView.x = _loc1_.x; this._imLookupView.y = _loc1_.y; addToContent(this._imLookupView); this._myAcademyBtn = ComponentFactory.Instance.creatComponentByStylename("IMView.myAcademyBtn"); this._myAcademyBtn.tipData = LanguageMgr.GetTranslation("im.IMView.myAcademyBtnTips"); addToContent(this._myAcademyBtn); this._stateSelectBtn = ComponentFactory.Instance.creatCustomObject("IM.stateIconButton"); addToContent(this._stateSelectBtn); this._stateList = ComponentFactory.Instance.creatComponentByStylename("IMView.stateList"); this._stateList.targetDisplay = this._stateSelectBtn; this._stateList.showLength = 5; this._state = ComponentFactory.Instance.creatComponentByStylename("IM.stateIconBtn.stateNameTxt"); this._state.text = "[" + PlayerManager.Instance.Self.playerState.convertToString() + "]"; addToContent(this._state); this._replyInput = ComponentFactory.Instance.creatCustomObject("im.autoReplyInput"); addToContent(this._replyInput); var _loc2_:SelfInfo = PlayerManager.Instance.Self; this._levelIcon.setInfo(_loc2_.Grade,_loc2_.Repute,_loc2_.WinCount,_loc2_.TotalCount,_loc2_.FightPower,_loc2_.Offer,true,false); this.showFigure(); this._currentListType = 0; this.setListType(); this.__onStateChange(new PlayerPropertyEvent("*",new Dictionary())); } private function __CMBtnClick(param1:MouseEvent) : void { IMController.Instance.createConsortiaLoader(); IMController.Instance.addEventListener(Event.COMPLETE,this.__CMFriendLoadComplete); SoundManager.instance.play("008"); } private function __CMFriendLoadComplete(param1:Event) : void { IMController.Instance.removeEventListener(Event.COMPLETE,this.__CMFriendLoadComplete); this._currentListType = CMFRIEND_LIST; this.setListType(); } private function __IMBtnClick(param1:MouseEvent) : void { this._currentListType = FRIEND_LIST; this.setListType(); SoundManager.instance.play("008"); } private function __inviteBtnClick(param1:MouseEvent) : void { var _loc2_:URLRequest = null; var _loc3_:URLVariables = null; var _loc4_:URLLoader = null; MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("im.IMView.inviteInfo")); SoundManager.instance.play("008"); if(!StringHelper.isNullOrEmpty(PathManager.CommunityInvite())) { _loc2_ = new URLRequest(PathManager.CommunityInvite()); _loc3_ = new URLVariables(); _loc3_["fuid"] = String(PlayerManager.Instance.Self.LoginName); _loc3_["fnick"] = PlayerManager.Instance.Self.NickName; _loc3_["tuid"] = this._CMfriendList.currentCMFInfo.UserName; _loc3_["serverid"] = String(ServerManager.Instance.AgentID); _loc3_["rnd"] = Math.random(); _loc2_.data = _loc3_; _loc4_ = new URLLoader(_loc2_); _loc4_.load(_loc2_); } } private function __consortiaListBtnClick(param1:MouseEvent) : void { SoundManager.instance.play("008"); if(PlayerManager.Instance.Self.ConsortiaID <= 0) { MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("im.IMView.infoText")); this._selectedButtonGroup.selectIndex = this._currentListType; return; } this._currentListType = CONSORTIA_LIST; this.setListType(); } private function __likeBtnClick(param1:MouseEvent) : void { SoundManager.instance.play("008"); this._currentListType = LIKEFRIEND_LIST; this.setListType(); } private function __addBleakBtnClick(param1:MouseEvent) : void { SoundManager.instance.play("008"); if(this._addFriendFrame && this._addFriendFrame.parent) { this._addFriendFrame.dispose(); this._addFriendFrame = null; } if(this._addBlackFrame && this._addBlackFrame.parent) { this._addBlackFrame.dispose(); this._addBlackFrame = null; return; } this._addBlackFrame = ComponentFactory.Instance.creat("AddBlackFrame"); LayerManager.Instance.addToLayer(this._addBlackFrame,LayerManager.GAME_DYNAMIC_LAYER); if(StateManager.currentStateType == StateType.MAIN) { ChatManager.Instance.lock = false; } if(StateManager.currentStateType == StateType.FIGHTING) { ComponentSetting.SEND_USELOG_ID(127); } } private function __myAcademyClick(param1:MouseEvent) : void { SoundManager.instance.play("008"); if(PlayerManager.Instance.Self.Grade >= AcademyManager.TARGET_PLAYER_MIN_LEVEL) { if(PlayerManager.Instance.Self.apprenticeshipState != AcademyManager.NONE_STATE) { AcademyManager.Instance.myAcademy(); } else { AcademyFrameManager.Instance.showAcademyPreviewFrame(); } } else { MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("im.IMView.academyInfo")); } } private function _socialContactBtClick(param1:MouseEvent) : void { SoundManager.instance.play("008"); SocialContactManager.Instance.showView(); } private function __addFriendBtnClick(param1:MouseEvent) : void { SoundManager.instance.play("008"); if(this._currentListType == FRIEND_LIST || this._currentListType == CONSORTIA_LIST || this._currentListType == LIKEFRIEND_LIST) { if(this._addBlackFrame && this._addBlackFrame.parent) { this._addBlackFrame.dispose(); this._addBlackFrame = null; } if(this._addFriendFrame && this._addFriendFrame.parent) { this._addFriendFrame.dispose(); this._addFriendFrame = null; return; } this._addFriendFrame = ComponentFactory.Instance.creat("AddFriendFrame"); LayerManager.Instance.addToLayer(this._addFriendFrame,LayerManager.GAME_DYNAMIC_LAYER); } else if(this._CMfriendList && this._CMfriendList.currentCMFInfo && this._CMfriendList.currentCMFInfo.IsExist) { IMController.Instance.addFriend(this._CMfriendList.currentCMFInfo.NickName); } if(StateManager.currentStateType == StateType.MAIN) { ChatManager.Instance.lock = false; } if(StateManager.currentStateType == StateType.FIGHTING) { ComponentSetting.SEND_USELOG_ID(126); } } private function showFigure() : void { var _loc1_:PlayerInfo = PlayerManager.Instance.Self; this._playerPortrait = ComponentFactory.Instance.creatCustomObject("im.PlayerPortrait",["right"]); this._playerPortrait.info = _loc1_; addToContent(this._playerPortrait); } private function setListType() : void { if(this._friendList && this._friendList.parent) { this._friendList.parent.removeChild(this._friendList); this._friendList.dispose(); this._friendList = null; } if(this._consortiaList && this._consortiaList.parent) { this._consortiaList.parent.removeChild(this._consortiaList); this._consortiaList.dispose(); this._consortiaList = null; } if(this._CMfriendList && this._CMfriendList.parent) { this._CMfriendList.parent.removeChild(this._CMfriendList); this._CMfriendList.dispose(); this._CMfriendList = null; } if(this._likeFriendList && this._likeFriendList.parent) { this._likeFriendList.parent.removeChild(this._likeFriendList); this._likeFriendList.dispose(); this._likeFriendList = null; } var _loc1_:Point = ComponentFactory.Instance.creatCustomObject("IM.IMList.listPos"); switch(this._currentListType) { case 0: this._friendList = new IMListView(); this._friendList.y = _loc1_.x; this._listContent.addChild(this._friendList); this._addBleak.visible = true; this._addFriend.visible = true; this._myAcademyBtn.visible = true; this._imLookupView.listType = FRIEND_LIST; break; case 1: this._consortiaList = new ConsortiaListView(); this._consortiaList.y = _loc1_.x; this._listContent.addChild(this._consortiaList); this._addBleak.visible = true; this._addFriend.visible = true; this._myAcademyBtn.visible = true; this._imLookupView.listType = FRIEND_LIST; break; case 2: this._CMfriendList = new CMFriendList(); this._CMfriendList.y = _loc1_.y; if(this._listContent) { this._listContent.addChild(this._CMfriendList); } this._addFriend.visible = false; this._addBleak.visible = false; this._myAcademyBtn.visible = false; this._imLookupView.listType = CMFRIEND_LIST; break; case LIKEFRIEND_LIST: this._likeFriendList = new LikeFriendListView(); this._likeFriendList.y = _loc1_.x; if(this._listContent) { this._listContent.addChild(this._likeFriendList); } this._addBleak.visible = true; this._addFriend.visible = true; this._myAcademyBtn.visible = true; this._imLookupView.listType = LIKEFRIEND_LIST; } if(AcademyManager.Instance.isFighting()) { if(this._myAcademyBtn) { this._myAcademyBtn.visible = false; } } } private function initEvent() : void { this._IMSelectedBtn.addEventListener(MouseEvent.CLICK,this.__IMBtnClick); this._CMSelectedBtn.addEventListener(MouseEvent.CLICK,this.__CMBtnClick); this._consortiaListBtn.addEventListener(MouseEvent.CLICK,this.__consortiaListBtnClick); this._likePersonSelectedBtn.addEventListener(MouseEvent.CLICK,this.__likeBtnClick); this._addFriend.addEventListener(MouseEvent.CLICK,this.__addFriendBtnClick); this._addBleak.addEventListener(MouseEvent.CLICK,this.__addBleakBtnClick); if(this._myAcademyBtn) { this._myAcademyBtn.addEventListener(MouseEvent.CLICK,this.__myAcademyClick); } this._stateSelectBtn.addEventListener(MouseEvent.CLICK,this.__stateSelectClick); StageReferance.stage.addEventListener(MouseEvent.CLICK,this.__hideStateList); PlayerManager.Instance.Self.addEventListener(PlayerPropertyEvent.PROPERTY_CHANGE,this.__onStateChange); } private function __giftClick(param1:MouseEvent) : void { SoundManager.instance.play("008"); BagAndInfoManager.Instance.showBagAndInfo(BagAndGiftFrame.GIFTVIEW); } private function __onStateChange(param1:PlayerPropertyEvent) : void { if(PlayerManager.Instance.Self.playerState.StateID == 1) { this._replyInput.visible = false; } else { this._replyInput.visible = true; } if(param1.changedProperties["State"]) { this._state.text = "[" + PlayerManager.Instance.Self.playerState.convertToString() + "]"; this._stateSelectBtn.setFrame(PlayerManager.Instance.Self.playerState.StateID); } } private function __hideStateList(param1:MouseEvent) : void { if(this._stateList.parent) { this._stateList.parent.removeChild(this._stateList); } } private function __stateSelectClick(param1:MouseEvent) : void { SoundManager.instance.play("008"); param1.stopImmediatePropagation(); if(this._stateList.parent == null) { addToContent(this._stateList); } this._stateList.dataList = ALL_STATE; } private function removeEvent() : void { this._IMSelectedBtn.removeEventListener(MouseEvent.CLICK,this.__IMBtnClick); this._CMSelectedBtn.removeEventListener(MouseEvent.CLICK,this.__CMBtnClick); this._consortiaListBtn.removeEventListener(MouseEvent.CLICK,this.__consortiaListBtnClick); this._likePersonSelectedBtn.removeEventListener(MouseEvent.CLICK,this.__likeBtnClick); this._addFriend.removeEventListener(MouseEvent.CLICK,this.__addFriendBtnClick); this._addBleak.removeEventListener(MouseEvent.CLICK,this.__addBleakBtnClick); IMController.Instance.removeEventListener(Event.COMPLETE,this.__CMFriendLoadComplete); if(this._myAcademyBtn) { this._myAcademyBtn.removeEventListener(MouseEvent.CLICK,this.__myAcademyClick); } this._stateSelectBtn.removeEventListener(MouseEvent.CLICK,this.__stateSelectClick); StageReferance.stage.removeEventListener(MouseEvent.CLICK,this.__hideStateList); PlayerManager.Instance.Self.removeEventListener(PlayerPropertyEvent.PROPERTY_CHANGE,this.__onStateChange); } override public function dispose() : void { IMController.Instance.isShow = false; this.removeEvent(); if(this._bg && this._bg.parent) { this._bg.parent.removeChild(this._bg); this._bg.dispose(); this._bg = null; } if(this._listContent && this._listContent.parent) { this._listContent.parent.removeChild(this._listContent); this._listContent = null; } if(this._selfName && this._selfName.parent) { this._selfName.parent.removeChild(this._selfName); this._selfName.dispose(); this._selfName = null; } if(this._levelIcon && this._levelIcon.parent) { this._levelIcon.parent.removeChild(this._levelIcon); this._levelIcon.dispose(); this._levelIcon = null; } if(this._consortiaListBtn && this._consortiaListBtn.parent) { this._consortiaListBtn.parent.removeChild(this._consortiaListBtn); this._consortiaListBtn.dispose(); this._consortiaListBtn = null; } if(this._likePersonSelectedBtn) { ObjectUtils.disposeObject(this._likePersonSelectedBtn); } this._likePersonSelectedBtn = null; if(this._addFriend && this._addFriend.parent) { this._addFriend.parent.removeChild(this._addFriend); this._addFriend.dispose(); this._addFriend = null; } if(this._addBleak && this._addBleak.parent) { this._addBleak.parent.removeChild(this._addBleak); this._addBleak.dispose(); this._addBleak = null; } if(this._IMSelectedBtn && this._IMSelectedBtn.parent) { this._IMSelectedBtn.parent.removeChild(this._IMSelectedBtn); this._IMSelectedBtn.dispose(); this._IMSelectedBtn = null; } if(this._CMSelectedBtn && this._CMSelectedBtn.parent) { this._CMSelectedBtn.parent.removeChild(this._CMSelectedBtn); this._CMSelectedBtn.dispose(); this._CMSelectedBtn = null; } if(this._imLookupView && this._imLookupView.parent) { this._imLookupView.parent.removeChild(this._imLookupView); this._imLookupView.dispose(); this._imLookupView = null; } if(this._friendList && this._friendList.parent) { this._friendList.parent.removeChild(this._friendList); this._friendList.dispose(); this._friendList = null; } if(this._consortiaList && this._consortiaList.parent) { this._consortiaList.parent.removeChild(this._consortiaList); this._consortiaList.dispose(); this._consortiaList = null; } if(this._CMfriendList && this._CMfriendList.parent) { this._CMfriendList.parent.removeChild(this._CMfriendList); this._CMfriendList.dispose(); this._CMfriendList = null; } if(this._addFriendFrame) { this._addFriendFrame.dispose(); this._addFriendFrame = null; } if(this._addBlackFrame) { this._addBlackFrame.dispose(); this._addBlackFrame = null; } if(this._myAcademyBtn) { this._myAcademyBtn.dispose(); this._myAcademyBtn = null; } if(this._stateList) { this._stateList.dispose(); this._stateList = null; } if(this._stateSelectBtn) { this._stateSelectBtn.dispose(); this._stateSelectBtn = null; } if(this._likeFriendList) { this._likeFriendList.dispose(); this._likeFriendList = null; } if(this._vipName) { ObjectUtils.disposeObject(this._vipName); } this._vipName = null; this._selectedButtonGroup.dispose(); this._selectedButtonGroup = null; super.dispose(); if(this.parent) { this.parent.removeChild(this); } } } }
package cmodule.lua_wrapper { public const _luaD_reallocCI:int = regFunc(FSM_luaD_reallocCI.start); }
/// Urho3D editor scene handling #include "Scripts/Editor/EditorHierarchyWindow.as" #include "Scripts/Editor/EditorInspectorWindow.as" #include "Scripts/Editor/EditorCubeCapture.as" const int PICK_GEOMETRIES = 0; const int PICK_LIGHTS = 1; const int PICK_ZONES = 2; const int PICK_RIGIDBODIES = 3; const int PICK_UI_ELEMENTS = 4; const int MAX_PICK_MODES = 5; const int MAX_UNDOSTACK_SIZE = 256; Scene@ editorScene; String instantiateFileName; CreateMode instantiateMode = REPLICATED; bool sceneModified = false; bool runUpdate = false; Array<Node@> selectedNodes; Array<Component@> selectedComponents; Node@ editNode; Array<Node@> editNodes; Array<Component@> editComponents; uint numEditableComponentsPerNode = 1; Array<XMLFile@> sceneCopyBuffer; bool suppressSceneChanges = false; bool inSelectionModify = false; bool skipMruScene = false; Array<EditActionGroup> undoStack; uint undoStackPos = 0; bool revertOnPause = false; XMLFile@ revertData; Vector3 lastOffsetForSmartDuplicate; void ClearSceneSelection() { selectedNodes.Clear(); selectedComponents.Clear(); editNode = null; editNodes.Clear(); editComponents.Clear(); numEditableComponentsPerNode = 1; HideGizmo(); } void CreateScene() { // Create a scene only once here editorScene = Scene(); // Allow access to the scene from the console script.defaultScene = editorScene; // Always pause the scene, and do updates manually editorScene.updateEnabled = false; } bool ResetScene() { ui.cursor.shape = CS_BUSY; if (messageBoxCallback is null && sceneModified) { MessageBox@ messageBox = MessageBox("Scene has been modified.\nContinue to reset?", "Warning"); if (messageBox.window !is null) { Button@ cancelButton = messageBox.window.GetChild("CancelButton", true); cancelButton.visible = true; cancelButton.focus = true; SubscribeToEvent(messageBox, "MessageACK", "HandleMessageAcknowledgement"); messageBoxCallback = @ResetScene; return false; } } else messageBoxCallback = null; suppressSceneChanges = true; // Create a scene with default values, these will be overridden when loading scenes editorScene.Clear(); editorScene.CreateComponent("Octree"); editorScene.CreateComponent("DebugRenderer"); // Release resources that became unused after the scene clear cache.ReleaseAllResources(false); sceneModified = false; revertData = null; StopSceneUpdate(); UpdateWindowTitle(); DisableInspectorLock(); UpdateHierarchyItem(editorScene, true); ClearEditActions(); suppressSceneChanges = false; ResetCamera(); CreateGizmo(); CreateGrid(); SetActiveViewport(viewports[0]); return true; } void SetResourcePath(String newPath, bool usePreferredDir = true, bool additive = false) { if (newPath.empty) return; if (!IsAbsolutePath(newPath)) newPath = fileSystem.currentDir + newPath; if (usePreferredDir) newPath = AddTrailingSlash(cache.GetPreferredResourceDir(newPath)); else newPath = AddTrailingSlash(newPath); if (newPath == sceneResourcePath) return; // Remove the old scene resource path if any. However make sure that the default data paths do not get removed if (!additive) { cache.ReleaseAllResources(false); renderer.ReloadShaders(); String check = AddTrailingSlash(sceneResourcePath); bool isDefaultResourcePath = check.Compare(fileSystem.programDir + "Data/", false) == 0 || check.Compare(fileSystem.programDir + "CoreData/", false) == 0; if (!sceneResourcePath.empty && !isDefaultResourcePath) cache.RemoveResourceDir(sceneResourcePath); } else { // If additive (path of a loaded prefab) check that the new path isn't already part of an old path Array<String>@ resourceDirs = cache.resourceDirs; for (uint i = 0; i < resourceDirs.length; ++i) { if (newPath.StartsWith(resourceDirs[i], false)) return; } } // Add resource path as first priority so that it takes precedence over the default data paths cache.AddResourceDir(newPath, 0); RebuildResourceDatabase(); if (!additive) { sceneResourcePath = newPath; uiScenePath = GetResourceSubPath(newPath, "Scenes"); uiElementPath = GetResourceSubPath(newPath, "UI"); uiNodePath = GetResourceSubPath(newPath, "Objects"); uiScriptPath = GetResourceSubPath(newPath, "Scripts"); uiParticlePath = GetResourceSubPath(newPath, "Particle"); } } String GetResourceSubPath(String basePath, const String&in subPath) { basePath = AddTrailingSlash(basePath); if (fileSystem.DirExists(basePath + subPath)) return AddTrailingSlash(basePath + subPath); else return basePath; } bool LoadScene(const String&in fileName) { if (fileName.empty) return false; ui.cursor.shape = CS_BUSY; // Always load the scene from the filesystem, not from resource paths if (!fileSystem.FileExists(fileName)) { MessageBox("No such scene.\n" + fileName); return false; } File file(fileName, FILE_READ); if (!file.open) { MessageBox("Could not open file.\n" + fileName); return false; } // Add the scene's resource path in case it's necessary String newScenePath = GetPath(fileName); if (!rememberResourcePath || !sceneResourcePath.StartsWith(newScenePath, false)) SetResourcePath(newScenePath); suppressSceneChanges = true; sceneModified = false; revertData = null; StopSceneUpdate(); String extension = GetExtension(fileName); bool loaded; if (extension == ".xml") loaded = editorScene.LoadXML(file); else if (extension == ".json") loaded = editorScene.LoadJSON(file); else loaded = editorScene.Load(file); // Release resources which are not used by the new scene cache.ReleaseAllResources(false); // Always pause the scene, and do updates manually editorScene.updateEnabled = false; UpdateWindowTitle(); DisableInspectorLock(); UpdateHierarchyItem(editorScene, true); CollapseHierarchy(); ClearEditActions(); suppressSceneChanges = false; // global variable to mostly bypass adding mru upon importing tempscene if (!skipMruScene) UpdateSceneMru(fileName); skipMruScene = false; ResetCamera(); CreateGizmo(); CreateGrid(); SetActiveViewport(viewports[0]); return loaded; } bool SaveScene(const String&in fileName) { if (fileName.empty) return false; ui.cursor.shape = CS_BUSY; // Unpause when saving so that the scene will work properly when loaded outside the editor editorScene.updateEnabled = true; MakeBackup(fileName); File file(fileName, FILE_WRITE); String extension = GetExtension(fileName); bool success; if (extension == ".xml") success = editorScene.SaveXML(file); else if (extension == ".json") success = editorScene.SaveJSON(file); else success = editorScene.Save(file); RemoveBackup(success, fileName); editorScene.updateEnabled = false; if (success) { UpdateSceneMru(fileName); sceneModified = false; UpdateWindowTitle(); } else MessageBox("Could not save scene successfully!\nSee Urho3D.log for more detail."); return success; } bool SaveSceneWithExistingName() { if (editorScene.fileName.empty || editorScene.fileName == TEMP_SCENE_NAME) return PickFile(); else return SaveScene(editorScene.fileName); } Node@ CreateNode(CreateMode mode) { Node@ newNode = null; if (editNode !is null) newNode = editNode.CreateChild("", mode); else newNode = editorScene.CreateChild("", mode); newNode.worldPosition = GetNewNodePosition(); // Create an undo action for the create CreateNodeAction action; action.Define(newNode); SaveEditAction(action); SetSceneModified(); FocusNode(newNode); return newNode; } void CreateComponent(const String&in componentType) { // If this is the root node, do not allow to create duplicate scene-global components if (editNode is editorScene && CheckForExistingGlobalComponent(editNode, componentType)) return; // Group for storing undo actions EditActionGroup group; // For now, make a local node's all components local /// \todo Allow to specify the createmode for (uint i = 0; i < editNodes.length; ++i) { Component@ newComponent = editNodes[i].CreateComponent(componentType, editNodes[i].id < FIRST_LOCAL_ID ? REPLICATED : LOCAL); if (newComponent !is null) { // Some components such as CollisionShape do not create their internal object before the first call to ApplyAttributes() // to prevent unnecessary initialization with default values. Call now newComponent.ApplyAttributes(); CreateComponentAction action; action.Define(newComponent); group.actions.Push(action); } } SaveEditActionGroup(group); SetSceneModified(); // Although the edit nodes selection are not changed, call to ensure attribute inspector notices new components of the edit nodes HandleHierarchyListSelectionChange(); } void CreateLoadedComponent(Component@ component) { if (component is null) return; CreateComponentAction action; action.Define(component); SaveEditAction(action); SetSceneModified(); FocusComponent(component); } Node@ LoadNode(const String&in fileName, Node@ parent = null) { if (fileName.empty) return null; if (!fileSystem.FileExists(fileName)) { MessageBox("No such node file.\n" + fileName); return null; } File file(fileName, FILE_READ); if (!file.open) { MessageBox("Could not open file.\n" + fileName); return null; } ui.cursor.shape = CS_BUSY; // Before instantiating, add object's resource path if necessary SetResourcePath(GetPath(fileName), true, true); Ray cameraRay = camera.GetScreenRay(0.5, 0.5); // Get ray at view center Vector3 position, normal; GetSpawnPosition(cameraRay, newNodeDistance, position, normal, 0, true); Node@ newNode = InstantiateNodeFromFile(file, position, Quaternion(), 1, parent, instantiateMode); if (newNode !is null) { FocusNode(newNode); instantiateFileName = fileName; } return newNode; } Node@ InstantiateNodeFromFile(File@ file, const Vector3& position, const Quaternion& rotation, float scaleMod = 1.0f, Node@ parent = null, CreateMode mode = REPLICATED) { if (file is null) return null; Node@ newNode; uint numSceneComponent = editorScene.numComponents; suppressSceneChanges = true; String extension = GetExtension(file.name); if (extension == ".xml") newNode = editorScene.InstantiateXML(file, position, rotation, mode); else if (extension == ".json") newNode = editorScene.InstantiateJSON(file, position, rotation, mode); else newNode = editorScene.Instantiate(file, position, rotation, mode); suppressSceneChanges = false; if (parent !is null) newNode.parent = parent; if (newNode !is null) { newNode.scale = newNode.scale * scaleMod; if (alignToAABBBottom) { Drawable@ drawable = GetFirstDrawable(newNode); if (drawable !is null) { BoundingBox aabb = drawable.worldBoundingBox; Vector3 aabbBottomCenter(aabb.center.x, aabb.min.y, aabb.center.z); Vector3 offset = aabbBottomCenter - newNode.worldPosition; newNode.worldPosition = newNode.worldPosition - offset; } } // Create an undo action for the load CreateNodeAction action; action.Define(newNode); SaveEditAction(action); SetSceneModified(); if (numSceneComponent != editorScene.numComponents) UpdateHierarchyItem(editorScene); else UpdateHierarchyItem(newNode); } return newNode; } bool SaveNode(const String&in fileName) { if (fileName.empty) return false; ui.cursor.shape = CS_BUSY; MakeBackup(fileName); File file(fileName, FILE_WRITE); if (!file.open) { MessageBox("Could not open file.\n" + fileName); return false; } String extension = GetExtension(fileName); bool success; if (extension == ".xml") success = editNode.SaveXML(file); else if (extension == ".json") success = editNode.SaveJSON(file); else success = editNode.Save(file); RemoveBackup(success, fileName); if (success) instantiateFileName = fileName; else MessageBox("Could not save node successfully!\nSee Urho3D.log for more detail."); return success; } void UpdateScene(float timeStep) { if (runUpdate) editorScene.Update(timeStep); } void StopSceneUpdate() { runUpdate = false; audio.Stop(); toolBarDirty = true; // If scene should revert on update stop, load saved data now if (revertOnPause && revertData !is null) { suppressSceneChanges = true; editorScene.Clear(); editorScene.LoadXML(revertData.root); CreateGrid(); UpdateHierarchyItem(editorScene, true); ClearEditActions(); suppressSceneChanges = false; } revertData = null; } void StartSceneUpdate() { runUpdate = true; // Run audio playback only when scene is updating, so that audio components' time-dependent attributes stay constant when // paused (similar to physics) audio.Play(); toolBarDirty = true; // Save scene data for reverting if enabled if (revertOnPause) { revertData = XMLFile(); XMLElement root = revertData.CreateRoot("scene"); editorScene.SaveXML(root); } else revertData = null; } bool ToggleSceneUpdate() { if (!runUpdate) StartSceneUpdate(); else StopSceneUpdate(); return true; } bool ShowLayerMover() { if (ui.focusElement is null) return ShowLayerEditor(); else return false; } void SetSceneModified() { if (!sceneModified) { sceneModified = true; UpdateWindowTitle(); } } bool SceneDelete() { ui.cursor.shape = CS_BUSY; BeginSelectionModify(); // Clear the selection now to prevent repopulation of selectedNodes and selectedComponents combo hierarchyList.ClearSelection(); // Group for storing undo actions EditActionGroup group; // Remove nodes for (uint i = 0; i < selectedNodes.length; ++i) { Node@ node = selectedNodes[i]; if (node.parent is null || node.scene is null) continue; // Root or already deleted uint nodeIndex = GetListIndex(node); // Create undo action DeleteNodeAction action; action.Define(node); group.actions.Push(action); node.Remove(); SetSceneModified(); // If deleting only one node, select the next item in the same index if (selectedNodes.length == 1 && selectedComponents.empty) hierarchyList.selection = nodeIndex; } // Then remove components, if they still remain for (uint i = 0; i < selectedComponents.length; ++i) { Component@ component = selectedComponents[i]; Node@ node = component.node; if (node is null) continue; // Already deleted uint index = GetComponentListIndex(component); uint nodeIndex = GetListIndex(node); if (index == NO_ITEM || nodeIndex == NO_ITEM) continue; // Do not allow to remove the Octree, DebugRenderer or MaterialCache2D or DrawableProxy2D from the root node if (node is editorScene && (component.typeName == "Octree" || component.typeName == "DebugRenderer" || component.typeName == "MaterialCache2D" || component.typeName == "DrawableProxy2D")) continue; // Create undo action DeleteComponentAction action; action.Define(component); group.actions.Push(action); node.RemoveComponent(component); SetSceneModified(); // If deleting only one component, select the next item in the same index if (selectedComponents.length == 1 && selectedNodes.empty) hierarchyList.selection = index; } SaveEditActionGroup(group); EndSelectionModify(); return true; } bool SceneCut() { return SceneCopy() && SceneDelete(); } bool SceneCopy() { ui.cursor.shape = CS_BUSY; sceneCopyBuffer.Clear(); // Copy components if (!selectedComponents.empty) { for (uint i = 0; i < selectedComponents.length; ++i) { XMLFile@ xml = XMLFile(); XMLElement rootElem = xml.CreateRoot("component"); selectedComponents[i].SaveXML(rootElem); rootElem.SetBool("local", selectedComponents[i].id >= FIRST_LOCAL_ID); sceneCopyBuffer.Push(xml); } } // Copy nodes else { for (uint i = 0; i < selectedNodes.length; ++i) { // Skip the root scene node as it cannot be copied if (selectedNodes[i] is editorScene) continue; XMLFile@ xml = XMLFile(); XMLElement rootElem = xml.CreateRoot("node"); selectedNodes[i].SaveXML(rootElem); rootElem.SetBool("local", selectedNodes[i].id >= FIRST_LOCAL_ID); sceneCopyBuffer.Push(xml); } } return true; } bool ScenePaste(bool pasteRoot = false, bool duplication = false) { ui.cursor.shape = CS_BUSY; // Group for storing undo actions EditActionGroup group; for (uint i = 0; i < sceneCopyBuffer.length; ++i) { XMLElement rootElem = sceneCopyBuffer[i].root; String mode = rootElem.name; if (mode == "component" && editNode !is null) { // If this is the root node, do not allow to create duplicate scene-global components if (editNode is editorScene && CheckForExistingGlobalComponent(editNode, rootElem.GetAttribute("type"))) return false; // If copied component was local, make the new local too Component@ newComponent = editNode.CreateComponent(rootElem.GetAttribute("type"), rootElem.GetBool("local") ? LOCAL : REPLICATED); if (newComponent is null) return false; newComponent.LoadXML(rootElem); newComponent.ApplyAttributes(); // Create an undo action CreateComponentAction action; action.Define(newComponent); group.actions.Push(action); } else if (mode == "node") { // If copied node was local, make the new local too Node@ newNode; // Are we pasting into the root node? if (pasteRoot) newNode = editorScene.CreateChild("", rootElem.GetBool("local") ? LOCAL : REPLICATED); else { // If we are duplicating or have the original node selected, paste into the selected nodes parent if (duplication || editNode is null || editNode.id == rootElem.GetUInt("id")) { if (editNode !is null && editNode.parent !is null) newNode = editNode.parent.CreateChild("", rootElem.GetBool("local") ? LOCAL : REPLICATED); else newNode = editorScene.CreateChild("", rootElem.GetBool("local") ? LOCAL : REPLICATED); } // If we aren't duplicating, paste into the selected node else { newNode = editNode.CreateChild("", rootElem.GetBool("local") ? LOCAL : REPLICATED); } } newNode.LoadXML(rootElem); // Create an undo action CreateNodeAction action; action.Define(newNode); group.actions.Push(action); } } SaveEditActionGroup(group); SetSceneModified(); return true; } bool SceneDuplicate() { Array<XMLFile@> copy = sceneCopyBuffer; if (!SceneCopy()) { sceneCopyBuffer = copy; return false; } if (!ScenePaste(false, true)) { sceneCopyBuffer = copy; return false; } sceneCopyBuffer = copy; return true; } bool SceneUnparent() { if (!CheckHierarchyWindowFocus() || !selectedComponents.empty || selectedNodes.empty) return false; ui.cursor.shape = CS_BUSY; // Group for storing undo actions EditActionGroup group; // Parent selected nodes to root Array<Node@> changedNodes; for (uint i = 0; i < selectedNodes.length; ++i) { Node@ sourceNode = selectedNodes[i]; if (sourceNode.parent is null || sourceNode.parent is editorScene) continue; // Root or already parented to root // Perform the reparenting, continue loop even if action fails ReparentNodeAction action; action.Define(sourceNode, editorScene); group.actions.Push(action); SceneChangeParent(sourceNode, editorScene, false); changedNodes.Push(sourceNode); } // Reselect the changed nodes at their new position in the list for (uint i = 0; i < changedNodes.length; ++i) hierarchyList.AddSelection(GetListIndex(changedNodes[i])); SaveEditActionGroup(group); SetSceneModified(); return true; } bool NodesParentToLastSelected() { if (lastSelectedNode.Get() is null) return false; if (!CheckHierarchyWindowFocus() || !selectedComponents.empty || selectedNodes.empty) return false; ui.cursor.shape = CS_BUSY; // Group for storing undo actions EditActionGroup group; // Parent selected nodes to root Array<Node@> changedNodes; // Find new parent node it selected last Node@ lastNode = lastSelectedNode.Get(); //GetListNode(hierarchyList.selection); for (uint i = 0; i < selectedNodes.length; ++i) { Node@ sourceNode = selectedNodes[i]; if ( sourceNode.id == lastNode.id) continue; // Skip last node it is parent if (sourceNode.parent.id == lastNode.id) continue; // Root or already parented to root // Perform the reparenting, continue loop even if action fails ReparentNodeAction action; action.Define(sourceNode, lastNode); group.actions.Push(action); SceneChangeParent(sourceNode, lastNode, false); changedNodes.Push(sourceNode); } // Reselect the changed nodes at their new position in the list for (uint i = 0; i < changedNodes.length; ++i) hierarchyList.AddSelection(GetListIndex(changedNodes[i])); SaveEditActionGroup(group); SetSceneModified(); return true; } bool SceneSmartDuplicateNode() { const float minOffset = 0.1; if (!CheckHierarchyWindowFocus() || !selectedComponents.empty || selectedNodes.empty || lastSelectedNode.Get() is null) return false; Node@ node = lastSelectedNode.Get(); Node@ parent = node.parent; Vector3 offset = Vector3(1,0,0); // default offset if (parent is editorScene) // if parent of selected node is Scene make empty parent for it and place in same position; { parent = CreateNode(LOCAL); SceneChangeParent(parent, editorScene, false); parent.worldPosition = node.worldPosition; parent.name = node.name + "Group"; node.name = parent.name + "Instance" + String(parent.numChildren); SceneChangeParent(node, parent, false); parent = node.parent; SelectNode(node, false); } Vector3 size; BoundingBox bb; // get bb for offset Drawable@ drawable = GetFirstDrawable(node); if (drawable !is null) { bb = drawable.boundingBox; size = bb.size * drawable.node.worldScale; offset = Vector3(size.x, 0, 0); } // make offset on axis that select user by mouse if (gizmoAxisX.selected) { if (size.x < minOffset) size.x = minOffset; offset = node.worldRotation * Vector3(size.x,0,0); } else if (gizmoAxisY.selected) { if (size.y < minOffset) size.y = minOffset; offset = node.worldRotation * Vector3(0,size.y,0); } else if (gizmoAxisZ.selected) { if (size.z < minOffset) size.z = minOffset; offset = node.worldRotation * Vector3(0,0,size.z); } else offset = lastOffsetForSmartDuplicate; Vector3 lastInstancePosition = node.worldPosition; SelectNode(node, false); SceneDuplicate(); Node@ newInstance = parent.children[parent.numChildren-1]; SelectNode(newInstance, false); newInstance.worldPosition = lastInstancePosition; newInstance.Translate(offset, TS_WORLD); newInstance.name = parent.name + "Instance" + String(parent.numChildren-1); lastOffsetForSmartDuplicate = offset; UpdateNodeAttributes(); return true; } bool ViewCloser() { return (viewCloser = true); } bool SceneToggleEnable() { if (!CheckHierarchyWindowFocus()) return false; ui.cursor.shape = CS_BUSY; EditActionGroup group; // Toggle enabled state of nodes recursively for (uint i = 0; i < selectedNodes.length; ++i) { // Do not attempt to disable the Scene if (selectedNodes[i].typeName == "Node") { bool oldEnabled = selectedNodes[i].enabled; selectedNodes[i].SetEnabledRecursive(!oldEnabled); // Create undo action ToggleNodeEnabledAction action; action.Define(selectedNodes[i], oldEnabled); group.actions.Push(action); } } for (uint i = 0; i < selectedComponents.length; ++i) { // Some components purposefully do not expose the Enabled attribute, and it does not affect them in any way // (Octree, PhysicsWorld). Check that the first attribute is in fact called "Is Enabled" if (selectedComponents[i].numAttributes > 0 && selectedComponents[i].attributeInfos[0].name == "Is Enabled") { bool oldEnabled = selectedComponents[i].enabled; selectedComponents[i].enabled = !oldEnabled; // Create undo action EditAttributeAction action; action.Define(selectedComponents[i], 0, Variant(oldEnabled)); group.actions.Push(action); } } SaveEditActionGroup(group); SetSceneModified(); return true; } bool SceneEnableAllNodes() { if (!CheckHierarchyWindowFocus()) return false; ui.cursor.shape = CS_BUSY; EditActionGroup group; // Toggle enabled state of nodes recursively Array<Node@> allNodes; allNodes = editorScene.GetChildren(true); for (uint i = 0; i < allNodes.length; ++i) { // Do not attempt to disable the Scene if (allNodes[i].typeName == "Node") { bool oldEnabled = allNodes[i].enabled; if (oldEnabled == false) allNodes[i].SetEnabledRecursive(true); // Create undo action ToggleNodeEnabledAction action; action.Define(allNodes[i], oldEnabled); group.actions.Push(action); } } Array<Component@> allComponents; allComponents = editorScene.GetComponents(); for (uint i = 0; i < allComponents.length; ++i) { // Some components purposefully do not expose the Enabled attribute, and it does not affect them in any way // (Octree, PhysicsWorld). Check that the first attribute is in fact called "Is Enabled" if (allComponents[i].numAttributes > 0 && allComponents[i].attributeInfos[0].name == "Is Enabled") { bool oldEnabled = allComponents[i].enabled; allComponents[i].enabled = true; // Create undo action EditAttributeAction action; action.Define(allComponents[i], 0, Variant(oldEnabled)); group.actions.Push(action); } } SaveEditActionGroup(group); SetSceneModified(); return true; } bool SceneChangeParent(Node@ sourceNode, Node@ targetNode, bool createUndoAction = true) { // Create undo action if requested if (createUndoAction) { ReparentNodeAction action; action.Define(sourceNode, targetNode); SaveEditAction(action); } sourceNode.parent = targetNode; SetSceneModified(); // Return true if success if (sourceNode.parent is targetNode) { UpdateNodeAttributes(); // Parent change may have changed local transform return true; } else return false; } bool SceneChangeParent(Node@ sourceNode, Array<Node@> sourceNodes, Node@ targetNode, bool createUndoAction = true) { // Create undo action if requested if (createUndoAction) { ReparentNodeAction action; action.Define(sourceNodes, targetNode); SaveEditAction(action); } for (uint i = 0; i < sourceNodes.length; ++i) { Node@ node = sourceNodes[i]; node.parent = targetNode; } SetSceneModified(); // Return true if success if (sourceNode.parent is targetNode) { UpdateNodeAttributes(); // Parent change may have changed local transform return true; } else return false; } bool SceneResetPosition() { if (editNode !is null) { Transform oldTransform; oldTransform.Define(editNode); editNode.position = Vector3(0.0, 0.0, 0.0); // Create undo action EditNodeTransformAction action; action.Define(editNode, oldTransform); SaveEditAction(action); SetSceneModified(); UpdateNodeAttributes(); return true; } else return false; } bool SceneResetRotation() { if (editNode !is null) { Transform oldTransform; oldTransform.Define(editNode); editNode.rotation = Quaternion(); // Create undo action EditNodeTransformAction action; action.Define(editNode, oldTransform); SaveEditAction(action); SetSceneModified(); UpdateNodeAttributes(); return true; } else return false; } bool SceneResetScale() { if (editNode !is null) { Transform oldTransform; oldTransform.Define(editNode); editNode.scale = Vector3(1.0, 1.0, 1.0); // Create undo action EditNodeTransformAction action; action.Define(editNode, oldTransform); SaveEditAction(action); SetSceneModified(); UpdateNodeAttributes(); return true; } else return false; } bool SceneResetTransform() { if (editNode !is null) { Transform oldTransform; oldTransform.Define(editNode); editNode.position = Vector3(0.0, 0.0, 0.0); editNode.rotation = Quaternion(); editNode.scale = Vector3(1.0, 1.0, 1.0); // Create undo action EditNodeTransformAction action; action.Define(editNode, oldTransform); SaveEditAction(action); SetSceneModified(); UpdateNodeAttributes(); return true; } else return false; } bool SceneSelectAll() { BeginSelectionModify(); Array<Node@> rootLevelNodes = editorScene.GetChildren(); Array<uint> indices; for (uint i = 0; i < rootLevelNodes.length; ++i) indices.Push(GetListIndex(rootLevelNodes[i])); hierarchyList.SetSelections(indices); EndSelectionModify(); return true; } bool SceneResetToDefault() { ui.cursor.shape = CS_BUSY; // Group for storing undo actions EditActionGroup group; // Reset selected component to their default if (!selectedComponents.empty) { for (uint i = 0; i < selectedComponents.length; ++i) { Component@ component = selectedComponents[i]; ResetAttributesAction action; action.Define(component); group.actions.Push(action); component.ResetToDefault(); component.ApplyAttributes(); for (uint j = 0; j < component.numAttributes; ++j) PostEditAttribute(component, j); } } // OR reset selected nodes to their default else { for (uint i = 0; i < selectedNodes.length; ++i) { Node@ node = selectedNodes[i]; ResetAttributesAction action; action.Define(node); group.actions.Push(action); node.ResetToDefault(); node.ApplyAttributes(); for (uint j = 0; j < node.numAttributes; ++j) PostEditAttribute(node, j); } } SaveEditActionGroup(group); SetSceneModified(); attributesFullDirty = true; return true; } bool SceneRebuildNavigation() { ui.cursor.shape = CS_BUSY; Array<Component@>@ navMeshes = editorScene.GetComponents("NavigationMesh", true); if (navMeshes.empty) { @navMeshes = editorScene.GetComponents("DynamicNavigationMesh", true); if (navMeshes.empty) { MessageBox("No NavigationMesh components in the scene, nothing to rebuild."); return false; } } bool success = true; for (uint i = 0; i < navMeshes.length; ++i) { NavigationMesh@ navMesh = navMeshes[i]; if (!navMesh.Build()) success = false; } return success; } bool SceneRenderZoneCubemaps() { bool success = false; Array<Zone@> capturedThisCall; bool alreadyCapturing = activeCubeCapture.length > 0; // May have managed to quickly queue up a second round of zones to render cubemaps for for (uint i = 0; i < selectedNodes.length; ++i) { Array<Component@>@ zones = selectedNodes[i].GetComponents("Zone", true); for (uint z = 0; z < zones.length; ++z) { Zone@ zone = cast<Zone>(zones[z]); if (zone !is null) { activeCubeCapture.Push(EditorCubeCapture(zone)); capturedThisCall.Push(zone); } } } for (uint i = 0; i < selectedComponents.length; ++i) { Zone@ zone = cast<Zone>(selectedComponents[i]); if (zone !is null) { if (capturedThisCall.FindByRef(zone) < 0) { activeCubeCapture.Push(EditorCubeCapture(zone)); capturedThisCall.Push(zone); } } } // Start rendering cubemaps if there are any to render and the queue isn't already running if (activeCubeCapture.length > 0 && !alreadyCapturing) activeCubeCapture[0].Start(); if (capturedThisCall.length <= 0) { MessageBox("No zones selected to render cubemaps for/"); } return capturedThisCall.length > 0; } bool SceneAddChildrenStaticModelGroup() { StaticModelGroup@ smg = cast<StaticModelGroup>(editComponents.length > 0 ? editComponents[0] : null); if (smg is null && editNode !is null) smg = editNode.GetComponent("StaticModelGroup"); if (smg is null) { MessageBox("Must have a StaticModelGroup component selected."); return false; } uint attrIndex = GetAttributeIndex(smg, "Instance Nodes"); Variant oldValue = smg.attributes[attrIndex]; Array<Node@> children = smg.node.GetChildren(true); for (uint i = 0; i < children.length; ++i) smg.AddInstanceNode(children[i]); EditAttributeAction action; action.Define(smg, attrIndex, oldValue); SaveEditAction(action); SetSceneModified(); FocusComponent(smg); return true; } bool SceneSetChildrenSplinePath(bool makeCycle) { SplinePath@ sp = cast<SplinePath>(editComponents.length > 0 ? editComponents[0] : null); if (sp is null && editNode !is null) sp = editNode.GetComponent("SplinePath"); if (sp is null) { MessageBox("Must have a SplinePath component selected."); return false; } uint attrIndex = GetAttributeIndex(sp, "Control Points"); Variant oldValue = sp.attributes[attrIndex]; Array<Node@> children = sp.node.GetChildren(true); if (children.length >= 2) { sp.ClearControlPoints(); for (uint i = 0; i < children.length; ++i) sp.AddControlPoint(children[i]); } else { MessageBox("You must have a minimum two children Nodes in selected Node."); return false; } if (makeCycle) sp.AddControlPoint(children[0]); EditAttributeAction action; action.Define(sp, attrIndex, oldValue); SaveEditAction(action); SetSceneModified(); FocusComponent(sp); return true; } void AssignMaterial(StaticModel@ model, String materialPath) { Material@ material = cache.GetResource("Material", materialPath); if (material is null) return; ResourceRefList materials = model.GetAttribute("Material").GetResourceRefList(); Array<String> oldMaterials; for(uint i = 0; i < materials.length; ++i) oldMaterials.Push(materials.names[i]); model.material = material; AssignMaterialAction action; action.Define(model, oldMaterials, material); SaveEditAction(action); SetSceneModified(); FocusComponent(model); } void UpdateSceneMru(String filename) { while (uiRecentScenes.Find(filename) > -1) uiRecentScenes.Erase(uiRecentScenes.Find(filename)); uiRecentScenes.Insert(0, filename); for (uint i = uiRecentScenes.length - 1; i >= maxRecentSceneCount; i--) uiRecentScenes.Erase(i); PopulateMruScenes(); } Drawable@ GetFirstDrawable(Node@ node) { Array<Node@> nodes = node.GetChildren(true); nodes.Insert(0, node); for (uint i = 0; i < nodes.length; ++i) { Array<Component@> components = nodes[i].GetComponents(); for (uint j = 0; j < components.length; ++j) { Drawable@ drawable = cast<Drawable>(components[j]); if (drawable !is null) return drawable; } } return null; } void AssignModel(StaticModel@ assignee, String modelPath) { Model@ model = cache.GetResource("Model", modelPath); if (model is null) return; Model@ oldModel = assignee.model; assignee.model = model; AssignModelAction action; action.Define(assignee, oldModel, model); SaveEditAction(action); SetSceneModified(); FocusComponent(assignee); } void CreateModelWithStaticModel(String filepath, Node@ parent) { if (parent is null) return; /// \todo should be able to specify the createmode if (parent is editorScene) parent = CreateNode(REPLICATED); Model@ model = cache.GetResource("Model", filepath); if (model is null) return; StaticModel@ staticModel = parent.GetOrCreateComponent("StaticModel"); staticModel.model = model; if (applyMaterialList) staticModel.ApplyMaterialList(); CreateLoadedComponent(staticModel); } void CreateModelWithAnimatedModel(String filepath, Node@ parent) { if (parent is null) return; /// \todo should be able to specify the createmode if (parent is editorScene) parent = CreateNode(REPLICATED); Model@ model = cache.GetResource("Model", filepath); if (model is null) return; AnimatedModel@ animatedModel = parent.GetOrCreateComponent("AnimatedModel"); animatedModel.model = model; if (applyMaterialList) animatedModel.ApplyMaterialList(); CreateLoadedComponent(animatedModel); } bool ColorWheelSetupBehaviorForColoring() { Menu@ menu = GetEventSender(); if (menu is null) return false; coloringPropertyName = menu.name; if (coloringPropertyName == "menuCancel") return false; if (coloringComponent.typeName == "Light") { Light@ light = cast<Light>(coloringComponent); if (light !is null) { if (coloringPropertyName == "menuLightColor") { coloringOldColor = light.color; ShowColorWheelWithColor(coloringOldColor); } else if (coloringPropertyName == "menuSpecularIntensity") { // ColorWheel have only 0-1 range output of V-value(BW), and for huge-range values we devide in and multiply out float scaledSpecular = light.specularIntensity * 0.1f; coloringOldScalar = scaledSpecular; ShowColorWheelWithColor(Color(scaledSpecular,scaledSpecular,scaledSpecular)); } else if (coloringPropertyName == "menuBrightnessMultiplier") { float scaledBrightness = light.brightness * 0.1f; coloringOldScalar = scaledBrightness; ShowColorWheelWithColor(Color(scaledBrightness,scaledBrightness,scaledBrightness)); } } } else if (coloringComponent.typeName == "StaticModel") { StaticModel@ model = cast<StaticModel>(coloringComponent); if (model !is null) { Material@ mat = model.materials[0]; if (mat !is null) { if (coloringPropertyName == "menuDiffuseColor") { Variant oldValue = mat.shaderParameters["MatDiffColor"]; Array<String> values = oldValue.ToString().Split(' '); coloringOldColor = Color(values[0].ToFloat(),values[1].ToFloat(),values[2].ToFloat(),values[3].ToFloat()); //RGBA ShowColorWheelWithColor(coloringOldColor); } else if (coloringPropertyName == "menuSpecularColor") { Variant oldValue = mat.shaderParameters["MatSpecColor"]; Array<String> values = oldValue.ToString().Split(' '); coloringOldColor = Color(values[0].ToFloat(),values[1].ToFloat(),values[2].ToFloat()); coloringOldScalar = values[3].ToFloat(); ShowColorWheelWithColor(Color(coloringOldColor.r, coloringOldColor.g, coloringOldColor.b, coloringOldScalar/128.0f)); //RGB + shine } else if (coloringPropertyName == "menuEmissiveColor") { Variant oldValue = mat.shaderParameters["MatEmissiveColor"]; Array<String> values = oldValue.ToString().Split(' '); coloringOldColor = Color(values[0].ToFloat(),values[1].ToFloat(),values[2].ToFloat()); // RGB ShowColorWheelWithColor(coloringOldColor); } else if (coloringPropertyName == "menuEnvironmentMapColor") { Variant oldValue = mat.shaderParameters["MatEnvMapColor"]; Array<String> values = oldValue.ToString().Split(' '); coloringOldColor = Color(values[0].ToFloat(),values[1].ToFloat(),values[2].ToFloat()); //RGB ShowColorWheelWithColor(coloringOldColor); } } } } else if (coloringComponent.typeName == "Zone") { Zone@ zone = cast<Zone>(coloringComponent); if (zone !is null) { if (coloringPropertyName == "menuAmbientColor") { coloringOldColor = zone.ambientColor; } else if (coloringPropertyName == "menuFogColor") { coloringOldColor = zone.fogColor; } ShowColorWheelWithColor(coloringOldColor); } } return true; }
package com.mcleodgaming.elevator.core { //Simple enumerator for ElevatorStates, each number represents a state an Elevator can be in public class ElevatorState { public static var IDLE:int = 0; //Waiting on home floor public static var RISING:int = 1; //Rising towards target floor public static var FALLING:int = 2; //Falling towards target floor public static var WAITING:int = 3; //Waiting on floor accepting passengers public static var RETURNING:int = 4; //Returning to home floor public static var BROKEN:int = 5; //Disabled Elevator public static function asString(state:int):String { //For debugging purposes return ["IDLE","RISING","FALLING","WAITING", "RETURNING", "BROKEN"][state]; } } }
package Ankama_Common.ui { import com.ankamagames.berilia.api.UiApi; import com.ankamagames.berilia.components.Grid; import com.ankamagames.berilia.components.Input; import com.ankamagames.berilia.components.Label; import com.ankamagames.berilia.components.Slot; import com.ankamagames.berilia.components.TextureBitmap; import com.ankamagames.berilia.types.LocationEnum; import com.ankamagames.berilia.types.graphic.ButtonContainer; import com.ankamagames.berilia.types.graphic.GraphicContainer; import com.ankamagames.berilia.utils.BeriliaHookList; import com.ankamagames.berilia.utils.ComponentHookList; import com.ankamagames.dofus.datacenter.effects.EffectInstance; import com.ankamagames.dofus.datacenter.items.EvolutiveItemType; import com.ankamagames.dofus.internalDatacenter.items.ItemWrapper; import com.ankamagames.dofus.kernel.sound.enum.SoundEnum; import com.ankamagames.dofus.logic.game.common.actions.livingObject.LivingObjectFeedAction; import com.ankamagames.dofus.misc.lists.InventoryHookList; import com.ankamagames.dofus.misc.lists.ShortcutHookListEnum; import com.ankamagames.dofus.modules.utils.ItemTooltipSettings; import com.ankamagames.dofus.types.enums.ItemCategoryEnum; import com.ankamagames.dofus.uiApi.DataApi; import com.ankamagames.dofus.uiApi.RoleplayApi; import com.ankamagames.dofus.uiApi.SoundApi; import com.ankamagames.dofus.uiApi.SystemApi; import com.ankamagames.dofus.uiApi.TooltipApi; import com.ankamagames.dofus.uiApi.UiTutoApi; import com.ankamagames.dofus.uiApi.UtilApi; import com.ankamagames.jerakine.benchmark.BenchmarkTimer; import com.ankamagames.jerakine.types.enums.DataStoreEnum; import flash.events.TimerEvent; import flash.utils.Dictionary; public class EvolutiveFeedUi { [Api(name="UiApi")] public var uiApi:UiApi; [Api(name="SystemApi")] public var sysApi:SystemApi; [Api(name="SoundApi")] public var soundApi:SoundApi; [Api(name="TooltipApi")] public var tooltipApi:TooltipApi; [Api(name="UtilApi")] public var utilApi:UtilApi; [Api(name="UiTutoApi")] public var hintsApi:UiTutoApi; [Api(name="DataApi")] public var dataApi:DataApi; [Api(name="RoleplayApi")] public var rpApi:RoleplayApi; [Module(name="Ankama_Common")] public var modCommon:Object; private const MAX_FOOD_ITEMS:int = 50; private const MAX_FOOD_ITEMS_VISIBLE:int = 4; private const LOCK_MAX_FOOD_ITEMS_REACHED:int = 0; private const LOCK_MAX_EXPERIENCE_REACHED:int = 1; private const LOCK_MAX_EXPERIENCE_REACHED_ISNT_LEGENDARY:int = 2; private const LOCK_MAX_EXPERIENCE_REACHED_IS_LEGENDARY:int = 3; private const LOCK_MAX_EXPERIENCE_REACHED_IS_SPECIAL_LEGENDARY:int = 4; private const LOCK_WRONG_FOOD_CATEGORY:int = 5; private const LOCK_ITEM_IS_NOT_FOOD:int = 6; private var _itemToFeed:ItemWrapper; private var _evolutiveTypeToFeed:EvolutiveItemType; private var _foodItemsList:Array; private var _experienceToReachMaxLevel:int = 0; private var _experienceToDisplay:int; private var _dropLocks:Array; private var _compInteractiveList:Dictionary; private var _visibleFoodItemsCount:int = 0; private var _quantityTimer:BenchmarkTimer; private var _quantityModifiedTarget:Input; private var _yBottomCtrWithoutFood:int; private var _heightWindowWithoutFood:int; private var _heightFoodBlockWithoutFood:int; public var lbl_choseQuantity:Label; public var ctr_feed:GraphicContainer; public var btn_close:ButtonContainer; public var btn_help:ButtonContainer; public var btn_feedOk:ButtonContainer; public var ctr_food:GraphicContainer; public var gd_food:Grid; public var ctr_bottom:GraphicContainer; public var btn_ctrDrop:ButtonContainer; public var ctr_invisibleDropLock:GraphicContainer; public var ctr_drop:GraphicContainer; public var ctr_dropError:GraphicContainer; public var lbl_dropError:Label; public var tx_dropBorderOver:TextureBitmap; public var tx_dropBorderSelected:TextureBitmap; public var tx_dropBorderError:TextureBitmap; public var slot_itemToFeed:Slot; public var lbl_petLevel:Label; public var lbl_xpResult:Label; public var lbl_levelResult:Label; public var gd_statResult:Grid; public function EvolutiveFeedUi() { this._compInteractiveList = new Dictionary(true); this._quantityTimer = new BenchmarkTimer(200,1,"EvolutiveFeedUi._quantityTimer"); super(); } public function main(param:Object) : void { this.btn_close.soundId = SoundEnum.WINDOW_CLOSE; this.sysApi.addHook(InventoryHookList.ObjectQuantity,this.onObjectQuantity); this.sysApi.addHook(InventoryHookList.ObjectDeleted,this.onObjectDeleted); this.sysApi.addHook(InventoryHookList.ObjectModified,this.onObjectModified); this.sysApi.addHook(BeriliaHookList.DropStart,this.onEquipementDropStart); this.sysApi.addHook(BeriliaHookList.DropEnd,this.onEquipementDropEnd); this.uiApi.addComponentHook(this.btn_feedOk,ComponentHookList.ON_RELEASE); this.uiApi.addComponentHook(this.slot_itemToFeed,ComponentHookList.ON_ROLL_OVER); this.uiApi.addComponentHook(this.slot_itemToFeed,ComponentHookList.ON_ROLL_OUT); this.uiApi.addComponentHook(this.btn_ctrDrop,ComponentHookList.ON_ROLL_OVER); this.uiApi.addComponentHook(this.btn_ctrDrop,ComponentHookList.ON_ROLL_OUT); this.uiApi.addComponentHook(this.lbl_dropError,ComponentHookList.ON_ROLL_OVER); this.uiApi.addComponentHook(this.lbl_dropError,ComponentHookList.ON_ROLL_OUT); this.uiApi.addShortcutHook(ShortcutHookListEnum.VALID_UI,this.onShortcut); this.uiApi.addShortcutHook(ShortcutHookListEnum.CLOSE_UI,this.onShortcut); this.btn_ctrDrop.dropValidator = this.dropValidatorFunction as Function; this.btn_ctrDrop.processDrop = this.processDropFunction as Function; this.btn_ctrDrop.removeDropSource = this.removeDropSourceFunction as Function; this._dropLocks = []; this._itemToFeed = param.itemToFeed; this._evolutiveTypeToFeed = this._itemToFeed.type.evolutiveType; if(this._itemToFeed.evolutiveEffectIds && this._itemToFeed.evolutiveEffectIds.length > 0) { this._experienceToReachMaxLevel = this._evolutiveTypeToFeed.experienceByLevel[this._evolutiveTypeToFeed.maxLevel] - this._itemToFeed.experiencePoints; } this.slot_itemToFeed.data = this._itemToFeed; this.lbl_petLevel.text = this.uiApi.getText("ui.common.short.level") + this._itemToFeed.displayedLevel; this._yBottomCtrWithoutFood = int(this.uiApi.me().getConstant("y_bottom_no_food")); this._heightWindowWithoutFood = int(this.uiApi.me().getConstant("height_window_no_food")); this._heightFoodBlockWithoutFood = int(this.uiApi.me().getConstant("height_block_no_food")); if(this._foodItemsList && this._foodItemsList.length) { this.gd_food.dataProvider = this._foodItemsList; } else { this._foodItemsList = new Array(); this.btn_feedOk.softDisabled = true; } this.updateExperienceFromFood(); this.updateWindowHeight(); } public function unload() : void { this.uiApi.hideTooltip(); } public function updateFoodItemLine(data:*, components:*, selected:Boolean) : void { if(!this._compInteractiveList[components.ctr_foodLine.name]) { this.uiApi.addComponentHook(components.ctr_foodLine,ComponentHookList.ON_DOUBLE_CLICK); } this._compInteractiveList[components.ctr_foodLine.name] = data; if(!this._compInteractiveList[components.slot_item.name]) { this.uiApi.addComponentHook(components.slot_item,ComponentHookList.ON_ROLL_OVER); this.uiApi.addComponentHook(components.slot_item,ComponentHookList.ON_ROLL_OUT); } this._compInteractiveList[components.slot_item.name] = data; if(!this._compInteractiveList[components.inp_itemQuantity.name]) { this.uiApi.addComponentHook(components.inp_itemQuantity,ComponentHookList.ON_CHANGE); } this._compInteractiveList[components.inp_itemQuantity.name] = data; if(!this._compInteractiveList[components.btn_itemRemove.name]) { this.uiApi.addComponentHook(components.btn_itemRemove,ComponentHookList.ON_RELEASE); this.uiApi.addComponentHook(components.btn_itemRemove,ComponentHookList.ON_ROLL_OVER); this.uiApi.addComponentHook(components.btn_itemRemove,ComponentHookList.ON_ROLL_OUT); } this._compInteractiveList[components.btn_itemRemove.name] = data; if(data) { components.slot_item.data = data.item; components.lbl_itemName.text = data.item.shortName; components.inp_itemQuantity.text = data.quantity; if(data.item.shortName == this._compInteractiveList[components.btn_itemRemove.name].item.shortName && !this._compInteractiveList[components.btn_itemRemove.name].quantityInBags || data.item.shortName == this._compInteractiveList[components.btn_itemRemove.name].item.shortName && this._compInteractiveList[components.btn_itemRemove.name].quantityInBags && this._compInteractiveList[components.btn_itemRemove.name].quantityInBags < data.quantity || data.item.shortName != this._compInteractiveList[components.btn_itemRemove.name].item.shortName) { this._compInteractiveList[components.btn_itemRemove.name].quantityInBags = data.quantity; } components.inp_itemQuantity.restrictChars = "0-9  "; } else { components.lbl_itemName.text = ""; components.slot_item.data = null; components.inp_itemQuantity.text = ""; } } private function updateFoodList() : void { var visibleItemsCount:int = this._foodItemsList.length; if(visibleItemsCount > 0) { this.lbl_choseQuantity.text = this.uiApi.getText("ui.evolutive.pet.choseResourcesQuantity"); } else { this.lbl_choseQuantity.text = ""; } if(visibleItemsCount > this.MAX_FOOD_ITEMS_VISIBLE) { visibleItemsCount = this.MAX_FOOD_ITEMS_VISIBLE; } if(this._visibleFoodItemsCount != visibleItemsCount) { this._visibleFoodItemsCount = visibleItemsCount; this.updateWindowHeight(); if(this._visibleFoodItemsCount == 0) { this.btn_feedOk.softDisabled = true; } else { this.btn_feedOk.softDisabled = false; } } if(this._foodItemsList.length >= this.MAX_FOOD_ITEMS) { this.lockDrop(this.LOCK_MAX_FOOD_ITEMS_REACHED); } else { this.unlockDrop(this.LOCK_MAX_FOOD_ITEMS_REACHED); } this.gd_food.dataProvider = this._foodItemsList; } private function updateWindowHeight() : void { var foodBlockHeight:int = 0; if(this._visibleFoodItemsCount > 0) { this.gd_food.height = this._visibleFoodItemsCount * this.gd_food.slotHeight; this.ctr_food.height = this.gd_food.height + this._heightFoodBlockWithoutFood; this.ctr_food.visible = true; foodBlockHeight = this.gd_food.height + this._heightFoodBlockWithoutFood + this.lbl_choseQuantity.height; } else { this.ctr_food.visible = false; } this.ctr_bottom.y = this._yBottomCtrWithoutFood + foodBlockHeight; this.ctr_feed.height = this._heightWindowWithoutFood + foodBlockHeight; this.uiApi.me().render(); } private function getExperienceFromItem(foodItem:ItemWrapper, quantity:int) : Number { if(foodItem.itemHasLegendaryEffect) { return 0; } var experience:Number = 0; if(foodItem.givenExperienceAsSuperFood > 0) { experience = quantity * foodItem.givenExperienceAsSuperFood; } else if(foodItem.basicExperienceAsFood > 0) { experience = quantity * foodItem.basicExperienceAsFood * this._evolutiveTypeToFeed.experienceBoost; } return experience; } private function updateExperienceFromFood() : void { var itemWrapper:ItemWrapper = null; var levelsCount:int = 0; var totalExperience:Number = 0; var foodItemsCount:int = this._foodItemsList.length; for(var i:int = 0; i < foodItemsCount; ) { itemWrapper = this._foodItemsList[i].item; totalExperience += this.getExperienceFromItem(itemWrapper,this._foodItemsList[i].quantity); i++; } this._experienceToDisplay = Math.floor(totalExperience); if(this._experienceToDisplay >= this._experienceToReachMaxLevel) { this.lockDrop(this.LOCK_MAX_EXPERIENCE_REACHED); this._experienceToDisplay = this._experienceToReachMaxLevel; } else { this.unlockDrop(this.LOCK_MAX_EXPERIENCE_REACHED); } if(foodItemsCount > 0) { this.lbl_xpResult.text = this.uiApi.getText("ui.tooltip.monsterXpAlone","+ " + this.utilApi.kamasToString(this._experienceToDisplay,"")); } else { this.lbl_xpResult.text = ""; } var futurItemExperience:int = this._experienceToDisplay + this._itemToFeed.experiencePoints; var futurLevel:int = this.dataApi.getEvolutiveItemLevelByExperiencePoints(this._itemToFeed,futurItemExperience); if(futurLevel <= this._itemToFeed.evolutiveLevel) { this.lbl_levelResult.text = ""; } else { levelsCount = futurLevel - this._itemToFeed.evolutiveLevel; this.lbl_levelResult.text = "+ " + this.uiApi.processText(this.uiApi.getText("ui.evolutive.levelsCount",levelsCount),"m",levelsCount == 1,levelsCount == 0); } this.updateUnlockedEffects(); } private function updateUnlockedEffects() : void { var ei:EffectInstance = null; var effects:Array = this.dataApi.getEvolutiveEffectInstancesByExperienceBoost(this._itemToFeed,this._experienceToDisplay); var effectsDescriptions:Array = []; for each(ei in effects) { if(ei) { effectsDescriptions.push("+ " + ei.description); } } this.gd_statResult.dataProvider = effectsDescriptions; } private function getMaximumQuantityBeforeMaxLevel(foodItem:ItemWrapper, requestedQuantity:int) : int { if(foodItem.itemHasLegendaryEffect) { return 1; } var maxQuantity:int = requestedQuantity; var experienceLeftToReachMaxLevel:int = this._experienceToReachMaxLevel - this._experienceToDisplay; var experienceWithRequestedQuantity:Number = this.getExperienceFromItem(foodItem,requestedQuantity); if(experienceWithRequestedQuantity <= experienceLeftToReachMaxLevel) { return maxQuantity; } var experienceByItem:Number = this.getExperienceFromItem(foodItem,1); maxQuantity = Math.ceil(experienceLeftToReachMaxLevel / experienceByItem); if(maxQuantity < 0) { maxQuantity = 0; } return maxQuantity; } private function lockDrop(lockReason:int) : void { this._dropLocks[lockReason] = true; if(lockReason == this.LOCK_MAX_EXPERIENCE_REACHED) { if(this._foodItemsList.length > 0 && !this._foodItemsList[0].item.itemHasLegendaryEffect) { this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.errorMaximumExperienceReached"); this.tx_dropBorderError.visible = true; this.btn_ctrDrop.softDisabled = true; this.btn_ctrDrop.handCursor = false; } else if(!this._itemToFeed.itemHoldsLegendaryStatus) { this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_ISNT_LEGENDARY] = true; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_LEGENDARY] = false; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_SPECIAL_LEGENDARY] = false; this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.evolveToLegendary"); } else if(this._itemToFeed.itemHasLockedLegendarySpell) { this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_SPECIAL_LEGENDARY] = true; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_LEGENDARY] = false; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_ISNT_LEGENDARY] = false; this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.errorCantEatAnythingAnymore"); } else { this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_LEGENDARY] = true; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_SPECIAL_LEGENDARY] = false; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_ISNT_LEGENDARY] = false; this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.giveLegendarySpell"); } this.ctr_drop.visible = false; this.ctr_dropError.visible = true; } else { if(lockReason == this.LOCK_MAX_FOOD_ITEMS_REACHED) { this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.errorMaximumResourcesCountReached",this.MAX_FOOD_ITEMS); } else if(lockReason == this.LOCK_WRONG_FOOD_CATEGORY) { this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.errorOnlyResources"); } else if(lockReason == this.LOCK_ITEM_IS_NOT_FOOD) { this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.errorResourceIsNotFood"); } this.tx_dropBorderError.visible = true; this.btn_ctrDrop.softDisabled = true; this.btn_ctrDrop.handCursor = false; this.ctr_drop.visible = false; this.ctr_dropError.visible = true; } } private function unlockDrop(lockReason:int) : void { this._dropLocks[lockReason] = false; if(lockReason == this.LOCK_MAX_EXPERIENCE_REACHED) { this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_LEGENDARY] = false; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_SPECIAL_LEGENDARY] = false; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_ISNT_LEGENDARY] = false; } if(this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED]) { if(this._foodItemsList.length > 0 && !this._foodItemsList[0].item.itemHasLegendaryEffect) { this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_ISNT_LEGENDARY] = false; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_LEGENDARY] = false; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_SPECIAL_LEGENDARY] = false; this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.errorMaximumExperienceReached"); } else if(!this._itemToFeed.itemHoldsLegendaryStatus) { this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_ISNT_LEGENDARY] = true; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_LEGENDARY] = false; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_SPECIAL_LEGENDARY] = false; this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.evolveToLegendary"); } else if(this._itemToFeed.itemHasLockedLegendarySpell) { this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_ISNT_LEGENDARY] = false; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_LEGENDARY] = false; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_SPECIAL_LEGENDARY] = true; this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.errorCantEatAnythingAnymore"); } else { this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_ISNT_LEGENDARY] = false; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_LEGENDARY] = true; this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_SPECIAL_LEGENDARY] = false; this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.giveLegendarySpell"); } return; } if(this._dropLocks[this.LOCK_MAX_FOOD_ITEMS_REACHED]) { this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.errorMaximumResourcesCountReached",this.MAX_FOOD_ITEMS); return; } if(this._dropLocks[this.LOCK_WRONG_FOOD_CATEGORY]) { this.lbl_dropError.text = this.uiApi.getText("ui.evolutive.pet.errorOnlyResources"); return; } this.tx_dropBorderError.visible = false; this.btn_ctrDrop.softDisabled = false; this.btn_ctrDrop.handCursor = true; this.ctr_drop.visible = true; this.ctr_dropError.visible = false; } private function onConfirmFeed() : void { var itemWrapper:ItemWrapper = null; var foodItemsCount:int = this._foodItemsList.length; var i:int = 0; for(var meal:Vector.<Object> = new Vector.<Object>(); i < foodItemsCount; ) { itemWrapper = this._foodItemsList[i].item; meal.push({ "objectUID":itemWrapper.objectUID, "quantity":this._foodItemsList[i].quantity }); i++; } this.sysApi.sendAction(new LivingObjectFeedAction([this._itemToFeed.objectUID,meal])); this._foodItemsList = []; this.updateFoodList(); this.updateExperienceFromFood(); } public function onRelease(target:GraphicContainer) : void { var data:Object = null; var foodItemsCount:int = 0; var i:int = 0; switch(target) { case this.btn_close: this.uiApi.unloadUi(this.uiApi.me().name); break; case this.btn_help: this.hintsApi.showSubHints(); break; case this.btn_feedOk: this.onConfirmFeed(); } if(target.name.indexOf("btn_itemRemove") != -1) { data = this._compInteractiveList[target.name]; foodItemsCount = this._foodItemsList.length; for(i = 0; i < foodItemsCount; ) { if(this._foodItemsList[i].item.objectUID == data.item.objectUID) { break; } i++; } this._foodItemsList.splice(i,1); this.updateFoodList(); this.updateExperienceFromFood(); } } public function onDoubleClick(target:GraphicContainer) : void { var data:Object = null; var foodItemsCount:int = 0; var i:int = 0; if(target.name.indexOf("ctr_foodLine") != -1) { data = this._compInteractiveList[target.name]; foodItemsCount = this._foodItemsList.length; for(i = 0; i < foodItemsCount; ) { if(this._foodItemsList[i].item.objectUID == data.item.objectUID) { break; } i++; } this._foodItemsList.splice(i,1); this.updateFoodList(); this.updateExperienceFromFood(); } } public function onChange(target:GraphicContainer) : void { var data:Object = null; var startValue:int = 0; var value:Number = NaN; if(target.name.indexOf("inp_itemQuantity") != -1) { this._quantityModifiedTarget = target as Input; data = this._compInteractiveList[this._quantityModifiedTarget.name]; startValue = int(this._quantityModifiedTarget.text); if(!data || data.quantity == startValue) { return; } if(data.item.itemHasLegendaryEffect) { this._quantityModifiedTarget.text = "1"; return; } value = startValue; if(value < 1) { value = 1; } if(value > data.quantityInBags) { value = data.quantityInBags; } if(value != startValue) { this._quantityModifiedTarget.text = value.toString(); } this._quantityTimer.reset(); this._quantityTimer.addEventListener(TimerEvent.TIMER,this.onTimerEnd); this._quantityTimer.start(); } } private function onTimerEnd(e:TimerEvent) : void { var newQuantity:int = 0; this._quantityTimer.removeEventListener(TimerEvent.TIMER,this.onTimerEnd); var data:Object = this._compInteractiveList[this._quantityModifiedTarget.name]; if(!data || data.quantity.toString() == this._quantityModifiedTarget.text) { return; } var writtenQuantity:int = int(this._quantityModifiedTarget.text); if(!writtenQuantity || writtenQuantity < 1) { newQuantity = 1; } else { if(writtenQuantity > data.item.quantity) { newQuantity = data.item.quantity; } else { newQuantity = writtenQuantity; } if(newQuantity > data.quantity) { newQuantity = this.getMaximumQuantityBeforeMaxLevel(data.item,newQuantity - data.quantity) + data.quantity; } } if(writtenQuantity != newQuantity) { this._quantityModifiedTarget.text = newQuantity + ""; } if(data.quantity != newQuantity) { data.quantity = newQuantity; this.updateExperienceFromFood(); } } public function onRollOver(target:GraphicContainer) : void { var text:String = null; var tooltipData:Object = null; var itemTooltipSettings:ItemTooltipSettings = null; var settings:* = undefined; var setting:String = null; var objVariables:Vector.<String> = null; var pos:Object = { "point":LocationEnum.POINT_BOTTOM, "relativePoint":LocationEnum.POINT_TOP }; if(target == this.btn_ctrDrop) { if(!this.tx_dropBorderSelected.visible && !this.tx_dropBorderError.visible) { this.tx_dropBorderOver.visible = true; } } if(target.name.indexOf("btn_itemRemove") != -1) { text = this.uiApi.getText("ui.common.remove"); } else if(target.name.indexOf("slot_item") != -1) { if(target == this.slot_itemToFeed) { tooltipData = this._itemToFeed; } else { tooltipData = this._compInteractiveList[target.name].item; } if(!tooltipData) { return; } itemTooltipSettings = this.sysApi.getData("itemTooltipSettings",DataStoreEnum.BIND_ACCOUNT) as ItemTooltipSettings; if(!itemTooltipSettings) { itemTooltipSettings = this.tooltipApi.createItemSettings(); this.sysApi.setData("itemTooltipSettings",itemTooltipSettings,DataStoreEnum.BIND_ACCOUNT); } settings = new Object(); objVariables = this.sysApi.getObjectVariables(itemTooltipSettings); for each(setting in objVariables) { settings[setting] = itemTooltipSettings[setting]; } settings["description"] = false; settings["averagePrice"] = false; this.uiApi.showTooltip(tooltipData,target,false,"standard",LocationEnum.POINT_RIGHT,LocationEnum.POINT_LEFT,3,"itemName",null,settings,"ItemInfo"); } if(text) { this.uiApi.showTooltip(this.uiApi.textTooltipInfo(text),target,false,"standard",pos.point,pos.relativePoint,3,null,null,null,"TextInfo"); } } public function onRollOut(target:GraphicContainer) : void { this.uiApi.hideTooltip(); if(target == this.btn_ctrDrop) { if(this.tx_dropBorderOver.visible) { this.tx_dropBorderOver.visible = false; } } } public function onShortcut(s:String) : Boolean { switch(s) { case "closeUi": this.uiApi.unloadUi(this.uiApi.me().name); return true; case "validUi": if(this._foodItemsList.length) { this.onRelease(this.btn_feedOk); return true; } break; } return false; } public function dropValidatorFunction(target:Object, data:Object, source:Object) : Boolean { return !this.btn_ctrDrop.softDisabled && this.rpApi.canPetEatThisFood(this._itemToFeed,data as ItemWrapper); } public function removeDropSourceFunction(target:Object) : void { } public function processDropFunction(target:Object, data:Object, source:Object) : void { var itemFound:Boolean = false; var foodItemsCount:int = 0; var i:int = 0; var newQuantity:int = 0; var quantity:int = 0; if(this.dropValidatorFunction(target,data,source)) { itemFound = false; foodItemsCount = this._foodItemsList.length; for(i = 0; i < foodItemsCount; ) { if(this._foodItemsList[i].item.objectUID == data.objectUID) { itemFound = true; newQuantity = this._foodItemsList[i].quantity + this.getMaximumQuantityBeforeMaxLevel(data as ItemWrapper,data.quantity); if(newQuantity > data.quantity) { newQuantity = data.quantity; } this._foodItemsList[i].quantity = newQuantity; this.gd_food.updateItem(i); break; } i++; } if(!itemFound) { quantity = this.getMaximumQuantityBeforeMaxLevel(data as ItemWrapper,data.quantity); this._foodItemsList.unshift({ "item":data, "quantity":quantity }); this.updateFoodList(); } this.updateExperienceFromFood(); } } private function onObjectQuantity(item:ItemWrapper, quantity:int, oldQuantity:int) : void { if(!item || !this._foodItemsList) { return; } var foodItemsCount:int = this._foodItemsList.length; for(var i:int = 0; i < foodItemsCount; ) { if(this._foodItemsList[i].item.objectUID == item.objectUID) { if(this._foodItemsList[i].quantity > quantity) { this._foodItemsList[i].quantity = quantity; this.gd_food.updateItem(i); this.updateExperienceFromFood(); break; } } i++; } } private function onObjectDeleted(item:Object) : void { if(!item || !this._foodItemsList) { return; } var foodItemsCount:int = this._foodItemsList.length; for(var i:int = 0; i < foodItemsCount; ) { if(this._foodItemsList[i].item.objectUID == item.objectUID) { this._foodItemsList.splice(i,1); this.updateFoodList(); this.updateExperienceFromFood(); break; } i++; } } public function onObjectModified(item:Object) : void { if(!item || item.objectUID != this._itemToFeed.objectUID) { return; } this._itemToFeed = item as ItemWrapper; this._evolutiveTypeToFeed = this._itemToFeed.type.evolutiveType; if(this._itemToFeed.evolutiveEffectIds && this._itemToFeed.evolutiveEffectIds.length > 0) { this._experienceToReachMaxLevel = this._evolutiveTypeToFeed.experienceByLevel[this._evolutiveTypeToFeed.maxLevel] - this._itemToFeed.experiencePoints; } this.slot_itemToFeed.data = this._itemToFeed; this.lbl_petLevel.text = this.uiApi.getText("ui.common.short.level") + this._itemToFeed.displayedLevel; this.updateExperienceFromFood(); } private function onEquipementDropStart(src:Object) : void { if(this._dropLocks[this.LOCK_MAX_FOOD_ITEMS_REACHED] || this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_SPECIAL_LEGENDARY] || !src.data || !(src.data is ItemWrapper)) { return; } var draggedItem:ItemWrapper = src.data as ItemWrapper; if(this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_ISNT_LEGENDARY] && !draggedItem.itemHoldsLegendaryStatus) { return; } if(this._dropLocks[this.LOCK_MAX_EXPERIENCE_REACHED_IS_LEGENDARY] && !draggedItem.itemHoldsLegendaryPower) { return; } this.ctr_invisibleDropLock.visible = false; if(this.rpApi.resourceIsFood(draggedItem)) { this.tx_dropBorderSelected.visible = true; } else if(draggedItem.category == ItemCategoryEnum.RESOURCES_CATEGORY && draggedItem.basicExperienceAsFood <= 0 && draggedItem.givenExperienceAsSuperFood <= 0 && !draggedItem.itemHasLegendaryEffect) { this.lockDrop(this.LOCK_ITEM_IS_NOT_FOOD); } else { this.lockDrop(this.LOCK_WRONG_FOOD_CATEGORY); } } private function onEquipementDropEnd(src:Object, target:Object) : void { this.tx_dropBorderSelected.visible = false; this.unlockDrop(this.LOCK_WRONG_FOOD_CATEGORY); this.ctr_invisibleDropLock.visible = true; } } }
/* CopyRight @ 2005 XLands.com INC. All rights reserved. */ import GUI.fox.aswing.Component; import GUI.fox.aswing.Icon; import GUI.fox.aswing.JLabel; import GUI.fox.aswing.JList; import GUI.fox.aswing.JListTree; import GUI.fox.aswing.ListCell; import GUI.fox.aswing.tree.list.ListTreeCellBorder; import GUI.fox.aswing.tree.TreePath; /** * @author iiley */ class GUI.fox.aswing.tree.list.AbstractListTreeCell extends JLabel implements ListCell { public static var INDENT_UNIT:Number = 8; private var tree:JListTree; private var path:TreePath; private var border:ListTreeCellBorder; private var indent:Number; public function AbstractListTreeCell(){ super(); setName("ListTreeCell"); indent = 0; border = createListTreeCellBorder(); setHorizontalAlignment(JLabel.LEFT); setOpaque(true); setFocusable(false); setBorder(border); } public function setListCellStatus(list : JList, isSelected : Boolean, index : Number) : Void { var com:Component = getCellComponent(); if(isSelected){ com.setBackground(list.getSelectionBackground()); com.setForeground(list.getSelectionForeground()); }else{ com.setBackground(list.getBackground()); com.setForeground(list.getForeground()); } com.setFont(list.getFont()); } public function setCellValue(value) : Void { path = TreePath(value); indent = getLevel(path) * INDENT_UNIT; border.setIndent(indent); border.setLeaf(isLeaf(path)); border.setExpanded(isExpanded(path)); setIcon(getCellIcon(path)); setText(getCellText(path)); repaint(); } public function setTree(tree:JListTree):Void{ this.tree = tree; } public function getCellValue() { return path; } public function getCellComponent() : Component { return this; } public function getIndent():Number{ return indent; } public function getIndentAndArrowAmount():Number{ return indent + border.getArrowSizeAmount(); } private function isLeaf(path:TreePath):Boolean{ return tree.getTreeModel().isLeaf(path.getLastPathComponent()); } private function isExpanded(path:TreePath):Boolean{ return tree.getListTreeModel().getExpandedState(path); } private function getLevel(path:TreePath):Number{ var level:Number = path.getPathCount() - 1; if(!tree.getListTreeModel().isRootVisible()){ level--; } return level; } //Override this private function getCellIcon(path:TreePath):Icon{ trace("/e/Subclass must override this method"); return null; } //Override this private function getCellText(path:TreePath):String{ trace("/e/Subclass must override this method"); return ""; } //Override this if you want another extended ListTreeCellBorder private function createListTreeCellBorder():ListTreeCellBorder{ return new ListTreeCellBorder(0); } }
package ssen.flexkit.components.grid.renderers { public class GraphicsGridRendererHelper { private var keepWidth:int=-1; private var keepHeight:int=-1; public var dataChanged:Boolean; public var columnChanged:Boolean; public var sizeChanged:Boolean; public var draw:Function; public var clear:Function; public function setSize(width:Number, height:Number):void { if (width <= 0 || height <= 0) { return; } if (keepWidth !== width || keepHeight !== height) { keepWidth=width; keepHeight=height; sizeChanged=true; prepare(true); } } public function prepare(hasBeenRecycled:Boolean):void { draw(hasBeenRecycled, dataChanged, columnChanged, sizeChanged); dataChanged=false; columnChanged=false; sizeChanged=false; } public function discard(willBeRecycled:Boolean):void { clear(willBeRecycled); } } } import mx.core.FlexGlobals; import spark.components.Application; function callLater(func:Function, ... args):void { var app:Application=FlexGlobals.topLevelApplication as Application; app.callLater(func, args); }
//////////////////////////////////////////////////////////////////////////////// // // 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.messaging.messages { [RemoteClass(alias="flex.messaging.messages.ErrorMessage")] /** * The ErrorMessage class is used to report errors within the messaging system. * An error message only occurs in response to a message sent within the * system. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public class ErrorMessage extends AcknowledgeMessage { //-------------------------------------------------------------------------- // // Static Constants // //-------------------------------------------------------------------------- /** * If a message may not have been delivered, the <code>faultCode</code> will * contain this constant. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const MESSAGE_DELIVERY_IN_DOUBT:String = "Client.Error.DeliveryInDoubt"; /** * Header name for the retryable hint header. * This is used to indicate that the operation that generated the error * may be retryable rather than fatal. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public static const RETRYABLE_HINT_HEADER:String = "DSRetryableErrorHint"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructs an ErrorMessage instance. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public function ErrorMessage() { super(); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var _faultCode:String; /** * The fault code for the error. * This value typically follows the convention of * "[outer_context].[inner_context].[issue]". * For example: "Channel.Connect.Failed", "Server.Call.Failed", etc. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public function get faultCode():String { return _faultCode; } public function set faultCode(value:String):void { _faultCode = value; } private var _faultString:String; /** * A simple description of the error. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public function get faultString():String { return _faultString; } public function set faultString(value:String):void { _faultString = value; } private var _faultDetail:String; /** * Detailed description of what caused the error. * This is typically a stack trace from the remote destination. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public function get faultDetail():String { return _faultDetail; } public function set faultDetail(value:String):void { _faultDetail = value; } private var _rootCause:Object; /** * Should a root cause exist for the error, this property contains those details. * This may be an ErrorMessage, a NetStatusEvent info Object, or an underlying * Flash error event: ErrorEvent, IOErrorEvent, or SecurityErrorEvent. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public function get rootCause():Object { return _rootCause; } public function set rootCause(value:Object):void { _rootCause = value; } private var _extendedData:Object; /** * Extended data that the remote destination has chosen to associate * with this error to facilitate custom error processing on the client. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion BlazeDS 4 * @productversion LCDS 3 */ public function get extendedData():Object { return _extendedData; } public function set extendedData(value:Object):void { _extendedData = value; } //-------------------------------------------------------------------------- // // Overridden Methods // //-------------------------------------------------------------------------- /** * @private */ override public function getSmallMessage():IMessage { return null; } } }
package flare.query.methods { import flare.query.Xor; import flare.util.Vectors; /** * Creates a new <code>Xor</code> (exclusive or) query operator. * @param rest a list of expressions to include in the exclusive or * @return the new query operator */ public function xor(...rest):Xor { var x:Xor = new Xor(); x.setChildren(Vectors.copyFromArray(rest)); return x; } }
package UI.abstract.resources { public class AnConst { public static const UP:int = 1; public static const RIGHT_UP:int = 2; public static const RIGHT:int = 3; public static const RIGHT_DOWN:int = 4; public static const DOWN:int = 5; public static const LEFT_DOWN:int = 6; public static const LEFT:int = 7; public static const LEFT_UP:int = 8; public static const STAND:int = 0; public static const WALK:int = 1; public static const ATTACK:int = 2; public static const ATTACKED:int = 3; public static const DIE:int = 4; public static const REST:int = 0; //休息 public static const ATTACK2:int = 6; //攻击第二动作 public static const BIGBODY:int = 19; public static const ATTACK_MOUNT:int = 7; //坐骑攻击动作 public static const MOUNT_STAND:int = 20; public static const MOUNT_WALK:int = 21; public function AnConst() { } } }
/** * * AirMobileFramework * * https://github.com/AbsolutRenal * * Copyright (c) 2012 AbsolutRenal (Renaud Cousin). All rights reserved. * * This ActionScript source code is free. * You can redistribute and/or modify it in accordance with the * terms of the accompanying Simplified BSD License Agreement. * * This framework also include some third party free Classes like Greensocks Tweening engine, Text and Fonts manager, Audio manager, Stats manager (by mrdoob) **/ package fwk.utils.trigonometry { import fwk.utils.types.angle.radToDeg; import flash.geom.Point; /** * @author renaud.cousin * @return Vector.Number => [0] : speed, [1] : orientation (in degrees) * @param vect : moves vector */ public function convertVectorToAngleSpeed(moves:Point):Vector.<Number> { var vect:Vector.<Number> = new Vector.<Number>(); var speed:Number = Point.distance(new Point(), moves); vect[0] = speed; var orientationRad:Number = Math.atan2(moves.y, moves.x); if (orientationRad < 0) { orientationRad += Math.PI * 2; } var orientationDeg:Number = radToDeg(orientationRad); vect[1] = orientationDeg; return vect; } }
//---------------------------------------------------------------------------------------------------- // Fast Fourier Transform module // Ported and modified by keim. // This soruce code is distributed under BSD-style license (see org.si.license.txt). // // Original code (written by c) // The original source code is free licensed. //----- < Following text is from original code's readme.txt. > ----- // Copyright(C) 1996-2001 Takuya OOURA // email: ooura@mmm.t.u-tokyo.ac.jp // download: http://momonga.t.u-tokyo.ac.jp/~ooura/fft.html // You may use, copy, modify this code for any purpose and // without fee. You may distribute this ORIGINAL package. //----- < up to here > ----- // [NOTES] Now the download site is moved to http://www.kurims.kyoto-u.ac.jp/~ooura/fft.html. // And the email address might be unavailable. //---------------------------------------------------------------------------------------------------- package org.si.utils { /** Fast Fourier Transform module */ public class FFT_original { // valiables //------------------------------------------------------------ private var _length:int = 0; private var _waveTable:Vector.<Number> = new Vector.<Number>(); private var _cosTable :Vector.<Number> = new Vector.<Number>(); private var _bitrvTemp:Vector.<int> = new Vector.<int>(256); // constructor //------------------------------------------------------------ /** constructor, specify calculating data length first. */ function FFT_original(length:int) { _initialize(length); } // calculation (original functions) //------------------------------------------------------------ /** Complex Discrete Fourier Tranform * @param isgn 1 for FFT, -1 for IFFT. * @param src data to transform. The length must be same as you passed to constructor. */ public function cdft(isgn:int, src:Vector.<Number>) : void { if (isgn >= 0) { _bitrv2(src, _length); _cftfsub(src); } else { _bitrv2conj(src, _length); _cftbsub(src); } } /** Real Discrete Fourier Tranform * @param isgn 1 for FFT, -1 for IFFT. * @param src data to transform. The length must be same as you passed to constructor. */ public function rdft(isgn:int, src:Vector.<Number>) : void { var xi:Number; if (isgn >= 0) { _bitrv2(src, _length); _cftfsub(src); _rftfsub(src); xi = src[0] - src[1]; src[0] += src[1]; src[1] = xi; } else { src[1] = 0.5 * (src[0] - src[1]); src[0] -= src[1]; _rftbsub(src); _bitrv2(src, _length); _cftbsub(src); } } /** Discrete Cosine Tranform * @param isgn [ATTENTION] -1 for DCT, 1 for IDCT. Opposite from FFT. * @param src data to transform. The length must be same as you passed to constructor. */ public function ddct(isgn:int, src:Vector.<Number>) : void { var j:int, xr:Number; if (isgn < 0) { xr = src[_length - 1]; for (j = _length - 2; j >= 2; j -= 2) { src[j+1] = src[j] - src[j - 1]; src[j] += src[j - 1]; } src[1] = src[0] - xr; src[0] += xr; _rftbsub(src); _bitrv2(src, _length); _cftbsub(src); _dctsub(src); } else { _dctsub(src); _bitrv2(src, _length); _cftfsub(src); _rftfsub(src); xr = src[0] - src[1]; src[0] += src[1]; for (j = 2; j < _length; j += 2) { src[j - 1] = src[j] - src[j+1]; src[j] += src[j+1]; } src[_length - 1] = xr; } } /** Discrete Sine Tranform * @param isgn [ATTENTION] -1 for DST, 1 for IDST. Opposite from FFT. * @param src data to transform. The length must be same as you passed to constructor. */ public function ddst(isgn:int, src:Vector.<Number>) : void { var j:int, xr:Number; if (isgn < 0) { xr = src[_length - 1]; for (j = _length - 2; j >= 2; j -= 2) { src[j+1] = -src[j] - src[j - 1]; src[j] -= src[j - 1]; } src[1] = src[0] + xr; src[0] -= xr; _rftbsub(src); _bitrv2(src, _length); _cftbsub(src); _dstsub(src); } else { _dstsub(src); _bitrv2(src, _length); _cftfsub(src); _rftfsub(src); xr = src[0] - src[1]; src[0] += src[1]; for (j = 2; j < _length; j += 2) { src[j - 1] = -src[j] - src[j+1]; src[j] -= src[j+1]; } src[_length - 1] = -xr; } } // internal function //------------------------------------------------------------ // initializer private function _initialize(len:int) : void { for (_length=8; _length<len;) _length<<=1; _waveTable.length = _length >> 2; _cosTable.length = _length; var i:int, imax:int = _length >> 3, tlen:int = _waveTable.length, dt:Number = 6.283185307179586 / _length; _waveTable[0] = 1; _waveTable[1] = 0; _waveTable[imax+1] = _waveTable[imax] = Math.cos(0.7853981633974483); for (i=2; i<imax; i+=2) { _waveTable[tlen-i+1] = _waveTable[i] = Math.cos(i*dt); _waveTable[tlen-i] = _waveTable[i+1] = Math.sin(i*dt); } _bitrv2(_waveTable, tlen); imax = _cosTable.length; dt = 1.5707963267948965 / imax; for (i=0; i<imax; i++) _cosTable[i] = Math.cos(i*dt) * 0.5; } // bit reverse private function _bitrv2(src:Vector.<Number>, srclen:int) : void { var j:int, j1:int, k:int, k1:int, xr:Number, xi:Number, yr:Number, yi:Number; _bitrvTemp[0] = 0; var l:int = srclen, m:int = 1; while ((m << 3) < l) { l >>= 1; for (j = 0; j < m; j++) _bitrvTemp[m + j] = _bitrvTemp[j] + l; m <<= 1; } var m2:int = m * 2; if ((m << 3) == l) { for (k = 0; k < m; k++) { for (j = 0; j < k; j++) { j1 = j + j + _bitrvTemp[k]; k1 = k + k + _bitrvTemp[j]; xr = src[j1]; xi = src[j1+1]; yr = src[k1]; yi = src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; j1 += m2; k1 += m2 + m2; xr = src[j1]; xi = src[j1+1]; yr = src[k1]; yi = src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; j1 += m2; k1 -= m2; xr = src[j1]; xi = src[j1+1]; yr = src[k1]; yi = src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; j1 += m2; k1 += m2 + m2; xr = src[j1]; xi = src[j1+1]; yr = src[k1]; yi = src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; } j1 = k + k + m2 + _bitrvTemp[k]; k1 = j1 + m2; xr = src[j1]; xi = src[j1+1]; yr = src[k1]; yi = src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; } } else { for (k = 1; k < m; k++) { for (j = 0; j < k; j++) { j1 = j + j + _bitrvTemp[k]; k1 = k + k + _bitrvTemp[j]; xr = src[j1]; xi = src[j1+1]; yr = src[k1]; yi = src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; j1 += m2; k1 += m2; xr = src[j1]; xi = src[j1+1]; yr = src[k1]; yi = src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; } } } } // bit reverse (conjugation) private function _bitrv2conj(src:Vector.<Number>, srclen:int) : void { var j:int, j1:int, k:int, k1:int, xr:Number, xi:Number, yr:Number, yi:Number; _bitrvTemp[0] = 0; var l:int = srclen, m:int = 1; while ((m << 3) < l) { l >>= 1; for (j = 0; j < m; j++) _bitrvTemp[m + j] = _bitrvTemp[j] + l; m <<= 1; } var m2:int = m << 1; if ((m << 3) == l) { for (k = 0; k < m; k++) { for (j = 0; j < k; j++) { j1 = j + j + _bitrvTemp[k]; k1 = k + k + _bitrvTemp[j]; xr = src[j1]; xi = -src[j1+1]; yr = src[k1]; yi = -src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; j1 += m2; k1 += m2 + m2; xr = src[j1]; xi = -src[j1+1]; yr = src[k1]; yi = -src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; j1 += m2; k1 -= m2; xr = src[j1]; xi = -src[j1+1]; yr = src[k1]; yi = -src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; j1 += m2; k1 += m2 + m2; xr = src[j1]; xi = -src[j1+1]; yr = src[k1]; yi = -src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; } k1 = k + k + _bitrvTemp[k]; src[k1+1] = -src[k1+1]; j1 = k1 + m2; k1 = j1 + m2; xr = src[j1]; xi = -src[j1+1]; yr = src[k1]; yi = -src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; k1 += m2; src[k1+1] = -src[k1+1]; } } else { src[1] = -src[1]; src[m2+1] = -src[m2+1]; for (k = 1; k < m; k++) { for (j = 0; j < k; j++) { j1 = j + j + _bitrvTemp[k]; k1 = k + k + _bitrvTemp[j]; xr = src[j1]; xi = -src[j1+1]; yr = src[k1]; yi = -src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; j1 += m2; k1 += m2; xr = src[j1]; xi = -src[j1+1]; yr = src[k1]; yi = -src[k1+1]; src[j1] = yr; src[j1+1] = yi; src[k1] = xr; src[k1+1] = xi; } k1 = k + k + _bitrvTemp[k]; src[k1+1] = -src[k1+1]; src[k1 + m2+1] = -src[k1 + m2+1]; } } } // sub routines //------------------------------------------------------------ private function _cftfsub(src:Vector.<Number>) : void { var j0:int, j1:int, j2:int, j3:int, l:int, x0r:Number, x1r:Number, x2r:Number, x3r:Number, x0i:Number, x1i:Number, x2i:Number, x3i:Number; _cft1st(src); l = 8; while ((l << 2) < _length) { _cftmdl(src, l); l <<= 2; } if ((l << 2) == _length) { for (j0 = 0; j0 < l; j0 += 2) { j1 = j0 + l; j2 = j1 + l; j3 = j2 + l; x0r = src[j0] + src[j1]; x0i = src[j0+1] + src[j1+1]; x1r = src[j0] - src[j1]; x1i = src[j0+1] - src[j1+1]; x2r = src[j2] + src[j3]; x2i = src[j2+1] + src[j3+1]; x3r = src[j2] - src[j3]; x3i = src[j2+1] - src[j3+1]; src[j0] = x0r + x2r; src[j0+1] = x0i + x2i; src[j2] = x0r - x2r; src[j2+1] = x0i - x2i; src[j1] = x1r - x3i; src[j1+1] = x1i + x3r; src[j3] = x1r + x3i; src[j3+1] = x1i - x3r; } } else { for (j0 = 0; j0 < l; j0 += 2) { j1 = j0 + l; x0r = src[j0] - src[j1]; x0i = src[j0+1] - src[j1+1]; src[j0] += src[j1]; src[j0+1] += src[j1+1]; src[j1] = x0r; src[j1+1] = x0i; } } } private function _cftbsub(src:Vector.<Number>) : void { var j0:int, j1:int, j2:int, j3:int, l:int, x0r:Number, x1r:Number, x2r:Number, x3r:Number, x0i:Number, x1i:Number, x2i:Number, x3i:Number; _cft1st(src); l = 8; while ((l << 2) < _length) { _cftmdl(src, l); l <<= 2; } if ((l << 2) == _length) { for (j0 = 0; j0 < l; j0 += 2) { j1 = j0 + l; j2 = j1 + l; j3 = j2 + l; x0r = src[j0] + src[j1]; x0i = -src[j0+1] - src[j1+1]; x1r = src[j0] - src[j1]; x1i = -src[j0+1] + src[j1+1]; x2r = src[j2] + src[j3]; x2i = src[j2+1] + src[j3+1]; x3r = src[j2] - src[j3]; x3i = src[j2+1] - src[j3+1]; src[j0] = x0r + x2r; src[j0+1] = x0i - x2i; src[j2] = x0r - x2r; src[j2+1] = x0i + x2i; src[j1] = x1r - x3i; src[j1+1] = x1i - x3r; src[j3] = x1r + x3i; src[j3+1] = x1i + x3r; } } else { for (j0 = 0; j0 < l; j0 += 2) { j1 = j0 + l; x0r = src[j0] - src[j1]; x0i = -src[j0+1] + src[j1+1]; src[j0] += src[j1]; src[j0+1] = -src[j0+1] - src[j1+1]; src[j1] = x0r; src[j1+1] = x0i; } } } private function _cft1st(src:Vector.<Number>) : void { var j:int, k1:int, k2:int, wk1r:Number, wk2r:Number, wk3r:Number, x0r:Number, x1r:Number, x2r:Number, x3r:Number, wk1i:Number, wk2i:Number, wk3i:Number, x0i:Number, x1i:Number, x2i:Number, x3i:Number; x0r = src[0] + src[2]; x0i = src[1] + src[3]; x1r = src[0] - src[2]; x1i = src[1] - src[3]; x2r = src[4] + src[6]; x2i = src[5] + src[7]; x3r = src[4] - src[6]; x3i = src[5] - src[7]; src[0] = x0r + x2r; src[1] = x0i + x2i; src[4] = x0r - x2r; src[5] = x0i - x2i; src[2] = x1r - x3i; src[3] = x1i + x3r; src[6] = x1r + x3i; src[7] = x1i - x3r; wk1r = _waveTable[2]; x0r = src[8] + src[10]; x0i = src[9] + src[11]; x1r = src[8] - src[10]; x1i = src[9] - src[11]; x2r = src[12] + src[14]; x2i = src[13] + src[15]; x3r = src[12] - src[14]; x3i = src[13] - src[15]; src[8] = x0r + x2r; src[9] = x0i + x2i; src[12] = x2i - x0i; src[13] = x0r - x2r; x0r = x1r - x3i; x0i = x1i + x3r; src[10] = wk1r * (x0r - x0i); src[11] = wk1r * (x0r + x0i); x0r = x3i + x1r; x0i = x3r - x1i; src[14] = wk1r * (x0i - x0r); src[15] = wk1r * (x0i + x0r); k1 = 0; for (j = 16; j < _length; j += 16) { k1 += 2; k2 = 2 * k1; wk2r = _waveTable[k1]; wk2i = _waveTable[k1+1]; wk1r = _waveTable[k2]; wk1i = _waveTable[k2+1]; wk3r = wk1r - 2 * wk2i * wk1i; wk3i = 2 * wk2i * wk1r - wk1i; x0r = src[j] + src[j + 2]; x0i = src[j+1] + src[j + 3]; x1r = src[j] - src[j + 2]; x1i = src[j+1] - src[j + 3]; x2r = src[j + 4] + src[j + 6]; x2i = src[j + 5] + src[j + 7]; x3r = src[j + 4] - src[j + 6]; x3i = src[j + 5] - src[j + 7]; src[j] = x0r + x2r; src[j+1] = x0i + x2i; x0r -= x2r; x0i -= x2i; src[j + 4] = wk2r * x0r - wk2i * x0i; src[j + 5] = wk2r * x0i + wk2i * x0r; x0r = x1r - x3i; x0i = x1i + x3r; src[j + 2] = wk1r * x0r - wk1i * x0i; src[j + 3] = wk1r * x0i + wk1i * x0r; x0r = x1r + x3i; x0i = x1i - x3r; src[j + 6] = wk3r * x0r - wk3i * x0i; src[j + 7] = wk3r * x0i + wk3i * x0r; wk1r = _waveTable[k2 + 2]; wk1i = _waveTable[k2 + 3]; wk3r = wk1r - 2 * wk2r * wk1i; wk3i = 2 * wk2r * wk1r - wk1i; x0r = src[j + 8] + src[j+10]; x0i = src[j + 9] + src[j+11]; x1r = src[j + 8] - src[j+10]; x1i = src[j + 9] - src[j+11]; x2r = src[j+12] + src[j+14]; x2i = src[j+13] + src[j+15]; x3r = src[j+12] - src[j+14]; x3i = src[j+13] - src[j+15]; src[j + 8] = x0r + x2r; src[j + 9] = x0i + x2i; x0r -= x2r; x0i -= x2i; src[j+12] = -wk2i * x0r - wk2r * x0i; src[j+13] = -wk2i * x0i + wk2r * x0r; x0r = x1r - x3i; x0i = x1i + x3r; src[j+10] = wk1r * x0r - wk1i * x0i; src[j+11] = wk1r * x0i + wk1i * x0r; x0r = x1r + x3i; x0i = x1i - x3r; src[j+14] = wk3r * x0r - wk3i * x0i; src[j+15] = wk3r * x0i + wk3i * x0r; } } private function _cftmdl(src:Vector.<Number>, l:int) : void { var j:int, j1:int, j2:int, j3:int, k:int, k1:int, k2:int, m:int, m2:int, wk1r:Number, wk2r:Number, wk3r:Number, x0r:Number, x1r:Number, x2r:Number, x3r:Number, wk1i:Number, wk2i:Number, wk3i:Number, x0i:Number, x1i:Number, x2i:Number, x3i:Number; m = l << 2; for (j = 0; j < l; j += 2) { j1 = j + l; j2 = j1 + l; j3 = j2 + l; x0r = src[j] + src[j1]; x0i = src[j+1] + src[j1+1]; x1r = src[j] - src[j1]; x1i = src[j+1] - src[j1+1]; x2r = src[j2] + src[j3]; x2i = src[j2+1] + src[j3+1]; x3r = src[j2] - src[j3]; x3i = src[j2+1] - src[j3+1]; src[j] = x0r + x2r; src[j+1] = x0i + x2i; src[j2] = x0r - x2r; src[j2+1] = x0i - x2i; src[j1] = x1r - x3i; src[j1+1] = x1i + x3r; src[j3] = x1r + x3i; src[j3+1] = x1i - x3r; } wk1r = _waveTable[2]; for (j = m; j < l + m; j += 2) { j1 = j + l; j2 = j1 + l; j3 = j2 + l; x0r = src[j] + src[j1]; x0i = src[j+1] + src[j1+1]; x1r = src[j] - src[j1]; x1i = src[j+1] - src[j1+1]; x2r = src[j2] + src[j3]; x2i = src[j2+1] + src[j3+1]; x3r = src[j2] - src[j3]; x3i = src[j2+1] - src[j3+1]; src[j] = x0r + x2r; src[j+1] = x0i + x2i; src[j2] = x2i - x0i; src[j2+1] = x0r - x2r; x0r = x1r - x3i; x0i = x1i + x3r; src[j1] = wk1r * (x0r - x0i); src[j1+1] = wk1r * (x0r + x0i); x0r = x3i + x1r; x0i = x3r - x1i; src[j3] = wk1r * (x0i - x0r); src[j3+1] = wk1r * (x0i + x0r); } k1 = 0; m2 = 2 * m; for (k = m2; k < _length; k += m2) { k1 += 2; k2 = 2 * k1; wk2r = _waveTable[k1]; wk2i = _waveTable[k1+1]; wk1r = _waveTable[k2]; wk1i = _waveTable[k2+1]; wk3r = wk1r - 2 * wk2i * wk1i; wk3i = 2 * wk2i * wk1r - wk1i; for (j = k; j < l + k; j += 2) { j1 = j + l; j2 = j1 + l; j3 = j2 + l; x0r = src[j] + src[j1]; x0i = src[j+1] + src[j1+1]; x1r = src[j] - src[j1]; x1i = src[j+1] - src[j1+1]; x2r = src[j2] + src[j3]; x2i = src[j2+1] + src[j3+1]; x3r = src[j2] - src[j3]; x3i = src[j2+1] - src[j3+1]; src[j] = x0r + x2r; src[j+1] = x0i + x2i; x0r -= x2r; x0i -= x2i; src[j2] = wk2r * x0r - wk2i * x0i; src[j2+1] = wk2r * x0i + wk2i * x0r; x0r = x1r - x3i; x0i = x1i + x3r; src[j1] = wk1r * x0r - wk1i * x0i; src[j1+1] = wk1r * x0i + wk1i * x0r; x0r = x1r + x3i; x0i = x1i - x3r; src[j3] = wk3r * x0r - wk3i * x0i; src[j3+1] = wk3r * x0i + wk3i * x0r; } wk1r = _waveTable[k2 + 2]; wk1i = _waveTable[k2 + 3]; wk3r = wk1r - 2 * wk2r * wk1i; wk3i = 2 * wk2r * wk1r - wk1i; for (j = k + m; j < l + (k + m); j += 2) { j1 = j + l; j2 = j1 + l; j3 = j2 + l; x0r = src[j] + src[j1]; x0i = src[j+1] + src[j1+1]; x1r = src[j] - src[j1]; x1i = src[j+1] - src[j1+1]; x2r = src[j2] + src[j3]; x2i = src[j2+1] + src[j3+1]; x3r = src[j2] - src[j3]; x3i = src[j2+1] - src[j3+1]; src[j] = x0r + x2r; src[j+1] = x0i + x2i; x0r -= x2r; x0i -= x2i; src[j2] = -wk2i * x0r - wk2r * x0i; src[j2+1] = -wk2i * x0i + wk2r * x0r; x0r = x1r - x3i; x0i = x1i + x3r; src[j1] = wk1r * x0r - wk1i * x0i; src[j1+1] = wk1r * x0i + wk1i * x0r; x0r = x1r + x3i; x0i = x1i - x3r; src[j3] = wk3r * x0r - wk3i * x0i; src[j3+1] = wk3r * x0i + wk3i * x0r; } } } private function _rftfsub(src:Vector.<Number>) : void { var j:int, k:int, kk:int, m:int, wkr:Number, wki:Number, xr:Number, xi:Number, yr:Number, yi:Number; m = _length >> 1; kk = 0; for (j = 2; j < m; j += 2) { k = _length - j; kk += 4; wkr = 0.5 - _cosTable[_length - kk]; wki = _cosTable[kk]; xr = src[j] - src[k]; xi = src[j+1] + src[k+1]; yr = wkr * xr - wki * xi; yi = wkr * xi + wki * xr; src[j] -= yr; src[j+1] -= yi; src[k] += yr; src[k+1] -= yi; } } private function _rftbsub(src:Vector.<Number>) : void { var j:int, k:int, kk:int, m:int, wkr:Number, wki:Number, xr:Number, xi:Number, yr:Number, yi:Number; src[1] = -src[1]; m = _length >> 1; kk = 0; for (j = 2; j < m; j += 2) { k = _length - j; kk += 4; wkr = 0.5 - _cosTable[_length - kk]; wki = _cosTable[kk]; xr = src[j] - src[k]; xi = src[j+1] + src[k+1]; yr = wkr * xr + wki * xi; yi = wkr * xi - wki * xr; src[j] -= yr; src[j+1] = yi - src[j+1]; src[k] += yr; src[k+1] = yi - src[k+1]; } src[m+1] = -src[m+1]; } private function _dctsub(src:Vector.<Number>) : void { var j:int, k:int, kk:int, m:int, wkr:Number, wki:Number, xr:Number; m = _length >> 1; kk = 0; for (j = 1; j < m; j++) { k = _length - j; kk += 1; wkr = _cosTable[kk] - _cosTable[_length - kk]; wki = _cosTable[kk] + _cosTable[_length - kk]; xr = wki * src[j] - wkr * src[k]; src[j] = wkr * src[j] + wki * src[k]; src[k] = xr; } src[m] *= 0.7071067811865476; // cos(pi/4) } private function _dstsub(src:Vector.<Number>) : void { var j:int, k:int, kk:int, m:int, wkr:Number, wki:Number, xr:Number; m = _length >> 1; kk = 0; for (j = 1; j < m; j++) { k = _length - j; kk += 1; wkr = _cosTable[kk] - _cosTable[_length - kk]; wki = _cosTable[kk] + _cosTable[_length - kk]; xr = wki * src[k] - wkr * src[j]; src[k] = wkr * src[k] + wki * src[j]; src[j] = xr; } src[m] *= 0.7071067811865476; // cos(pi/4) } } }
package States { import org.flixel.*; import Buttons.StateTransitionButton; import Buttons.AudioButton; /** * ... * @author Nicholas 'A' Feinberg */ public class TabState extends FlxState { [Embed(source = "/images/Backgrounds/folders.png")] public static const bg:Class; override public function create():void { add(new FlxSprite(0, 0, bg)); if (FlxG.music) FlxG.music.fadeOut(1, true); for (var i:int = 0; i < IntroState.viewedScenes.length; i++) if (IntroState.viewedScenes[i]) add(new Tab(i)); add(new StateTransitionButton(295, 215, MenuState)); FlxG.stage.frameRate = 30; FlxG.mouse.show(); } } }
/* * Copyright (c) 2006-2010 the original author or authors * * Permission is hereby granted to use, modify, and distribute this file * in accordance with the terms of the license agreement accompanying it. */ package reprise.data { public class IntPoint { //***************************************************************************************** //* Public Properties * //***************************************************************************************** public var x : int; public var y : int; //***************************************************************************************** //* Public Methods * //***************************************************************************************** public function IntPoint(x : int = 0, y : int = 0) { this.x = x; this.y = y; } public function toString() : String { return '[IntPoint] x: ' + x + ', y: ' + y; } } }
/** Licensed under the Apache License, Version 2.0 @copy (c) See LICENSE.txt */ package test.performance.coreperf { import flash.system.System; import flash.utils.clearInterval; import flash.utils.getTimer; import flash.utils.setInterval; import test.performance.coreperf.view.TestViewA; import test.performance.coreperf.view.TestViewB; import test.performance.coreperf.view.TestViewC; import org.bixbite.core.Compound; import test.performance.coreperf.behaviour.TestBehaviour; import test.performance.coreperf.behaviour.TraceOutput; import test.performance.coreperf.data.TestData; import test.performance.coreperf.transponder.TestTransponder; import test.performance.coreperf.view.OutputView; /** * @langversion 3.0 * footprint 11.0kb * * Purpose of this test is to keep track on speed of MVC actor creations. Since Bixbite is self-registered system there is much more going on under the hood. * During construction each Actor getting references to Emitter and getting default signal attached to it as well as unique identifier controlled by system. * During deconstruction (method destroy()) Object has to release all those references and clean up after itself. * Also Emitter always checking if there is empty slot will destroy it. This is why removal is always much slower. * * Taking under consideration all that, results below are still very satisfactory. * * Results: See RESULTS.txt */ public class CorePerformance extends Compound { private var results :Array = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; private var tasks :Array = []; private var iterator :int = 0; private var task :int = 0; private var repeat :int = 10; private var runner :int; private var timeInterval:int = 200; public function CorePerformance() { } override public function init():void { register(OutputView); addBehaviour("traceOutput", TraceOutput); tasks[0] = "register Views 10k"; tasks[1] = "unregister Views 10k"; tasks[2] = "register Views 100k"; tasks[3] = "unregister Views 100k"; tasks[4] = "register Views 1kk"; tasks[5] = "unregister Views 1kk"; tasks[6] = "register Trans 10k"; tasks[7] = "unregister Trans 10k"; tasks[8] = "register Trans 100k"; tasks[9] = "unregister Trans 100k"; tasks[10] = "register Trans 1kk"; tasks[11] = "unregister Trans 1kk"; tasks[12] = "register Data 10k"; tasks[13] = "unregister Data 10k"; tasks[14] = "register Data 100k"; tasks[15] = "unregister Data 100k"; tasks[16] = "register Data 1kk"; tasks[17] = "unregister Data 1kk"; tasks[18] = "add/remove Behaviour 1k"; tasks[19] = "add/remove Behaviour 10k"; tasks[20] = "add/remove Behaviour 100k"; tasks[21] = "add/exe/dispose Behaviour 1k"; tasks[22] = "add/exe/dispose Behaviour 10k"; tasks[23] = "add/exe/dispose Behaviour 100k"; tasks[24] = "reg/unreg Views 1k"; tasks[25] = "reg/unreg Views 10k"; tasks[26] = "reg/unreg Views 100k"; tasks[27] = "reg/unreg Trans 1k"; tasks[28] = "reg/unreg Trans 10k"; tasks[29] = "reg/unreg Trans 100k"; tasks[30] = "reg/unreg Data 1k"; tasks[31] = "reg/unreg Data 10k"; tasks[32] = "reg/unreg Data 100k"; tasks[33] = "reg/unreg Views+Ctx+Slot 1k"; tasks[34] = "reg/unreg Views+Ctx+Slot 10k"; tasks[35] = "reg/unreg Views+Ctx+Slot 100k"; tasks[36] = "reg/unreg Views+Ctx+Gfx+Slot 1k"; tasks[37] = "reg/unreg Views+Ctx+Gfx+Slot 10k"; tasks[38] = "reg/unreg Views+Ctx+Gfx+Slot 100k"; runner = setInterval(run, timeInterval); } private function run():void { System.gc(); switch(task) { case 0: test1(10000, task); break case 1: test2(10000, task); break case 2: test1(100000, task); break case 3: test2(100000, task); break case 4: test1(1000000, task); break case 5: test2(1000000, task); break case 6: test3(10000, task); break; case 7: test4(10000, task); break; case 8: test3(100000, task); break; case 9: test4(100000, task); break; case 10: test3(1000000, task); break; case 11: test4(1000000, task); break; case 12: test5(10000, task); break; case 13: test6(10000, task); break; case 14: test5(100000, task); break; case 15: test6(100000, task); break; case 16: test5(1000000, task); break; case 17: test6(1000000, task); break; case 18: timeInterval = 1000; test7(1000, task); break; case 19: test7(10000, task); break; case 20: test7(100000, task); break; case 21: test8(1000, task); break; case 22: test8(10000, task); break; case 23: test8(100000, task); break; case 24: test9(1000, task); break; case 25: test9(10000, task); break; case 26: test9(100000, task); break; case 27: test10(1000, task); break; case 28: test10(10000, task); break; case 29: test10(100000, task); break; case 30: test11(1000, task); break; case 31: test11(10000, task); break; case 32: test11(100000, task); break; case 33: timeInterval = 10000; test12(1000, task); break; case 34: test12(10000, task); break; case 35: test12(100000, task); break; case 36: test13(1000, task); break; case 37: test13(10000, task); break; case 38: test13(100000, task); break; case 39: emitSignal("traceOutput", { id:40, row:"COMPLETE" } ); clearInterval(runner); return break; } output(task); if (iterator < repeat){ iterator++; } else { clearInterval(runner); iterator = 0; task++; timeInterval = parseInt(results[task]) / iterator + 100; runner = setInterval(run, timeInterval); } System.gc(); } private function test1(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { register(TestViewA); } results[resultsId] += getTimer() - time; } private function test2(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { unregister(TestViewA); } results[resultsId] += getTimer() - time; } private function test3(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { register(TestTransponder); } results[resultsId] += getTimer() - time; } private function test4(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { unregister(TestTransponder); } results[resultsId] += getTimer() - time; } private function test5(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { register(TestData); } results[resultsId] += getTimer() - time; } private function test6(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { unregister(TestData); } results[resultsId] += getTimer() - time; } private function test7(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { addBehaviour("testSignal", TestBehaviour); removeBehaviour("testSignal"); } results[resultsId] += getTimer() - time; } private function test8(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { addBehaviour("testSignal", TestBehaviour, true, true); } results[resultsId] += getTimer() - time; } private function test9(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { register(TestViewA); unregister(TestViewA); } results[resultsId] += getTimer() - time; } private function test10(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { register(TestTransponder); unregister(TestTransponder); } results[resultsId] += getTimer() - time; } private function test11(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { register(TestData); unregister(TestData); } results[resultsId] += getTimer() - time; } private function test12(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { register(TestViewB); unregister(TestViewB); } results[resultsId] += getTimer() - time; } private function test13(max:int, resultsId:int):void { var time:int = getTimer(); for (var i:int = 0; i < max; i++) { register(TestViewC); unregister(TestViewC); } results[resultsId] += getTimer() - time; } private function output(id:int):void { emitSignal("traceOutput", { id:id, row:"TASK:" + tasks[id] + " COUNT:"+ iterator + " TIME:"+ Number(results[id] / (iterator + 1)).toPrecision(5) } ); } } }
package effects { import net.flashpunk.Entity; import net.flashpunk.graphics.Emitter; import net.flashpunk.graphics.ParticleType; import net.flashpunk.utils.Ease; public class Explosion extends Entity { [Embed(source='/assets/sprites/explosion.png')] private const EXPLOSION:Class; public var emitter:Emitter; public function Explosion():void { emitter = new Emitter(EXPLOSION, 32, 32); graphic = emitter; emitter.x = -16; emitter.y = -16; var p:ParticleType = emitter.newType("explosion", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); p.setMotion(0, 0, 1); } } }
package decisions { import interfaces.IDecision; /** * ... * @author Shaun Stone */ public class DecisionAction extends AbstractDecision implements IDecision { public function DecisionAction() { super(); } } }
/* * MIT License * * Copyright (c) 2017 Digital Strawberry 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 tests.async { import breezetest.Assert; import breezetest.async.Async; import breezetest.async.AsyncEvent; import breezetest.errors.AssertionError; import breezetest.errors.AsyncTimeoutError; import flash.utils.setTimeout; public class TestAsync { public function testTimeoutError(async:Async):void { var factory:Async = new Async(this); factory.addEventListener(AsyncEvent.ERROR, function(event:AsyncEvent):void { Assert.equals(AsyncEvent.ERROR, event.type); Assert.isType(event.error, AsyncTimeoutError); Assert.same(factory, event.factory); async.complete(); }); factory.timeout = 1000; // Fail if timeout event is not called in 2000 ms async.timeout = 2000; } public function testCompleteEvent(async:Async):void { var factory:Async = new Async(this); factory.addEventListener(AsyncEvent.COMPLETE, function(event:AsyncEvent):void { Assert.equals(AsyncEvent.COMPLETE, event.type); Assert.same(factory, event.factory); async.complete(); }); // Fail if complete event is not called in 2000 ms async.timeout = 2000; // Call the async handler setTimeout(function():void { factory.complete(); }, 500); } public function testAssertionError(async:Async):void { // uncaughtErrorEvents must be passed to this Async object otherwise // the error below would be caught by the method's Async parameter var factory:Async = new Async(this, Main.root.loaderInfo.uncaughtErrorEvents); factory.addEventListener(AsyncEvent.ERROR, function(event:AsyncEvent):void { Assert.equals(AsyncEvent.ERROR, event.type); Assert.isType(event.error, AssertionError); Assert.same(factory, event.factory); async.complete(); }); // Fail if error event is not called in 2000 ms async.timeout = 2000; // Force an error setTimeout(function():void { Assert.isTrue(false); }, 1000); } } }
/* * Copyright 2020 Tallence AG * * 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.tallence.formeditor.studio.fields { import com.coremedia.ui.data.ValueExpression; import com.coremedia.ui.data.ValueExpressionFactory; import com.tallence.formeditor.studio.model.GroupElementStructWrapper; import ext.util.Format; import ext.window.Window; public class EditOptionWindowBase extends Window { protected var option:GroupElementStructWrapper; protected var optionNameVE:ValueExpression; protected var optionValueVE:ValueExpression; protected var optionCheckedVE:ValueExpression; protected var onSaveCallback:Function; protected var onRemoveCallback:Function; public function EditOptionWindowBase(config:EditOptionWindow = null) { super(config); this.option = config.option; this.onSaveCallback = config.onSaveCallback; this.onRemoveCallback = config.onRemoveCallback; initValues(); } private function initValues():void { getOptionNameVE().setValue(option.getId()); getOptionValueVE().setValue(option.getOptionValueVE().getValue()); getOptionCheckedVE().setValue(option.getOptionSelectedByDefaultVE().getValue()); } public function saveOption():void { if (this.onSaveCallback) { this.onSaveCallback.call(NaN, getOptionNameVE().getValue(), getOptionValueVE().getValue(), getOptionCheckedVE().getValue() ); close(); } } public function removeOption():void { if (this.onRemoveCallback) { this.onRemoveCallback.call(NaN); close(); } } protected function getOptionNameVE():ValueExpression { if (!optionNameVE) { optionNameVE = ValueExpressionFactory.createFromValue(null); } return optionNameVE; } protected function getOptionValueVE():ValueExpression { if (!optionValueVE) { optionValueVE = ValueExpressionFactory.createFromValue(null); } return optionValueVE; } protected function getOptionCheckedVE():ValueExpression { if (!optionCheckedVE) { optionCheckedVE = ValueExpressionFactory.createFromValue(false); } return optionCheckedVE; } protected function getSaveButtonDisabledVE():ValueExpression { return ValueExpressionFactory.createFromFunction(function ():Boolean { var displayName:String = getOptionNameVE().getValue(); return displayName == null || !Format.trim(displayName).length; }) } } }
/* The Great Computer Language Shootout http://shootout.alioth.debian.org/ contributed by Isaac Gouy */ package { public class Body { public static var PI:Number = 3.141592653589793; public static var SOLAR_MASS:Number = 4 * PI * PI; public static var DAYS_PER_YEAR:Number = 365.24; public var x:Number, y:Number, z:Number, vx:Number, vy:Number, vz:Number, mass:Number; public function Body(x:Number, y:Number, z:Number, vx:Number, vy:Number, vz:Number, mass:Number):void{ this.x = x; this.y = y; this.z = z; this.vx = vx; this.vy = vy; this.vz = vz; this.mass = mass; } public static function Jupiter():Body { return new Body( 4.84143144246472090e+00, -1.16032004402742839e+00, -1.03622044471123109e-01, 1.66007664274403694e-03 * DAYS_PER_YEAR, 7.69901118419740425e-03 * DAYS_PER_YEAR, -6.90460016972063023e-05 * DAYS_PER_YEAR, 9.54791938424326609e-04 * SOLAR_MASS ); } public static function Saturn():Body { return new Body( 8.34336671824457987e+00, 4.12479856412430479e+00, -4.03523417114321381e-01, -2.76742510726862411e-03 * DAYS_PER_YEAR, 4.99852801234917238e-03 * DAYS_PER_YEAR, 2.30417297573763929e-05 * DAYS_PER_YEAR, 2.85885980666130812e-04 * SOLAR_MASS ); } public static function Uranus():Body { return new Body( 1.28943695621391310e+01, -1.51111514016986312e+01, -2.23307578892655734e-01, 2.96460137564761618e-03 * DAYS_PER_YEAR, 2.37847173959480950e-03 * DAYS_PER_YEAR, -2.96589568540237556e-05 * DAYS_PER_YEAR, 4.36624404335156298e-05 * SOLAR_MASS ); } public static function Neptune():Body { return new Body( 1.53796971148509165e+01, -2.59193146099879641e+01, 1.79258772950371181e-01, 2.68067772490389322e-03 * DAYS_PER_YEAR, 1.62824170038242295e-03 * DAYS_PER_YEAR, -9.51592254519715870e-05 * DAYS_PER_YEAR, 5.15138902046611451e-05 * SOLAR_MASS ); } public static function Sun():Body { return new Body(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, SOLAR_MASS); } public function offsetMomentum (px:Number, py:Number, pz:Number):Body { this.vx = -px / SOLAR_MASS; this.vy = -py / SOLAR_MASS; this.vz = -pz / SOLAR_MASS; return this; } } public class NBodySystem { public var bodies:Array = new Array(5); public function NBodySystem():void { bodies[0] = Body.Sun(); bodies[1] = Body.Jupiter(); bodies[2] = Body.Saturn(); bodies[3] = Body.Uranus(); bodies[4] = Body.Neptune(); var px:Number = 0.0; var py:Number = 0.0; var pz:Number = 0.0; for(var i:int = 0; i < bodies.length; ++i) { px += bodies[i].vx * bodies[i].mass; py += bodies[i].vy * bodies[i].mass; pz += bodies[i].vz * bodies[i].mass; } bodies[0].offsetMomentum(px,py,pz); } public function advance(dt:Number):void { var dx:Number, dy:Number, dz:Number, distance:Number, mag:Number; var size:Number = this.bodies.length; for (var i:int=0; i<size; i++) { var bodyi:Body = this.bodies[i]; for (var j:int=i+1; j<size; j++) { var bodyj:Body = this.bodies[j]; dx = bodyi.x - bodyj.x; dy = bodyi.y - bodyj.y; dz = bodyi.z - bodyj.z; distance = Math.sqrt(dx*dx + dy*dy + dz*dz); mag = dt / (distance * distance * distance); bodyi.vx -= dx * bodyj.mass * mag; bodyi.vy -= dy * bodyj.mass * mag; bodyi.vz -= dz * bodyj.mass * mag; bodyj.vx += dx * bodyi.mass * mag; bodyj.vy += dy * bodyi.mass * mag; bodyj.vz += dz * bodyi.mass * mag; } } for (var i:int=0; i<size; i++) { var body:Body = this.bodies[i]; body.x += dt * body.vx; body.y += dt * body.vy; body.z += dt * body.vz; } } public function energy():Number { var dx:Number, dy:Number, dz:Number, distance:Number; var e:Number = 0.0; var size:Number = this.bodies.length; for (var i:int=0; i<size; i++) { var bodyi:Body = this.bodies[i]; e += 0.5 * bodyi.mass * ( bodyi.vx * bodyi.vx + bodyi.vy * bodyi.vy + bodyi.vz * bodyi.vz ); for (var j=i+1; j<size; j++) { var bodyj:Body = this.bodies[j]; dx = bodyi.x - bodyj.x; dy = bodyi.y - bodyj.y; dz = bodyi.z - bodyj.z; distance = Math.sqrt(dx*dx + dy*dy + dz*dz); e -= (bodyi.mass * bodyj.mass) / distance; } } return e; } } function runAccessNbody():Number { var res:Number; for ( var n:int = 3; n <= 24 * 4 * 128 * 2; n *= 2 ) { var bodies:NBodySystem = new NBodySystem(); var max:Number = n * 100; res = bodies.energy(); for (var i=0; i<max; i++){ bodies.advance(0.01); } res = bodies.energy(); print(""+n+"="+res); } return res; } var start:Number = new Date(); var res:Number = runAccessNbody(); var totaltime:Number = new Date() - start; if (res-(-0.1690525098446868)<0.00001) print("PASSED res="+res); else print("FAILED nbody result expecting -0.1690525098446868 got "+res); /* if (res-(-0.1690693)<0.00001) print("metric time "+totaltime); else print("error nbody result expecting -0.1690693 got "+res); */ }
package com.bs.amg.tasks { import com.amf.events.AMFErrorEvent; import com.bs.amg.UnisAPI; import com.bs.amg.UnisAPIImplementation; import com.bs.amg.events.AMGGraphDataEvent; import com.bs.amg.tasks.events.GraphTreeExpandErrorEvent; import com.bs.amg.tasks.events.GraphTreeExpandEvent; import com.thread.SimpleTask; import org.un.cava.birdeye.ravis.graphLayout.data.Graph; import org.un.cava.birdeye.ravis.graphLayout.data.IGTree; import org.un.cava.birdeye.ravis.graphLayout.data.IGraph; import org.un.cava.birdeye.ravis.graphLayout.data.INode; /** * Задача - раскрытие дерева объектов до указанной глубины * Параметры : Список идентификаторов объектов * Глубина раскрытия объектов * @author Shavenzov * */ public class UnisGraphExpander extends SimpleTask { /** * Запущен процесс раскрытия */ public static const EXPANDING : int = 10; /** * Глобальный визуализируемый граф */ private var _graph : IGraph; /** * Словарь идентификаторов уже раскрытых узлов ( за все время работы ) */ private var _expandedNodes : Object; /** * Глубина раскрытия узлов */ private var _depth : uint; /** * Двухмерный массив состоящий из групп раскрываемых объектов и их идентификаторов */ private var _groups : Array; /** * Текущая раскрываемая группа объектов */ private var _currentGroup : Array; /** * Текущий раскрываемый узел и граф с ним связанный */ private var _currentResult : NodeExpandResult; /** * Список результатов раскрытия для определенной группы */ private var _currentGroupResult : Vector.<NodeExpandResult>; /** * Идентификатор текущего раскрываемого подузла */ private var _currentExpandingObjectId : String; /** * UNIS API */ private var _unis : UnisAPIImplementation; /** * Последняя ошибка */ private var _lastError : AMFErrorEvent; public function UnisGraphExpander( depth : uint = 1, graph : IGraph = null ) { super(); _depth = depth; _groups = new Array(); _graph = graph ? graph : new Graph(); } public function get depth() : uint { return _depth; } public function set depth( value : uint ) : void { _depth = value; } public function add( nodeId : * ) : void { if ( nodeId is String ) { _groups.push( [ nodeId ] ); return; } if ( nodeId is Array ) { _groups.push( nodeId ); return; } throw new Error( 'not suported data for add' ); } public function get groups() : Array { return _groups; } public function get graph() : IGraph { return _graph; } /** * Определяет раскрыт ли узел с указанным идентификатором или нет * @param nodeId * */ public function isNodeExpanded( nodeId : String ) : Boolean { return _expandedNodes[ nodeId ] != null; } override protected function next() : void { switch( _status ) { case SimpleTask.NONE : _status = EXPANDING; init(); expandNextGroup(); break; case EXPANDING : expandNextNode(); break; case SimpleTask.ERROR : case SimpleTask.DONE : uninit(); break; } super.next(); } /** * Прерывает операцию раскрытия и удаляет все узлы из списка раскрываемых * */ public function cancel() : void { if ( _status == EXPANDING ) { _status = SimpleTask.DONE; next(); } } /** * Запускает процесс раскрытия следующей группы объектов и его потомков, до указанной глубины * */ private function expandNextGroup() : void { if ( _groups.length == 0 ) { if ( ( _graph.noNodes == 0 ) && ( _lastError != null ) ) { _statusString = _lastError.text; _status = SimpleTask.ERROR; } else { _status = SimpleTask.DONE; } next(); return; } _currentGroupResult = new Vector.<NodeExpandResult>(); _currentGroup = _groups.shift(); expandNextObject(); } /** * Запускает процесс ракрытия следуюего объекта в текущей группе объектов * */ private function expandNextObject() : void { if ( _currentGroup.length == 0 ) { var addToGlobalGraph : Boolean = true; //Отсылаем событие "Дерево раскрыто" if ( hasEventListener( GraphTreeExpandEvent.EXPANDED ) ) { addToGlobalGraph = dispatchEvent( new GraphTreeExpandEvent( GraphTreeExpandEvent.EXPANDED, _currentGroupResult ) ); } if ( addToGlobalGraph ) { //Добавляем новое сформированное дерево в глобальный граф _graph.safeInitFromVO( NodeExpandResult.resultUnion( _currentGroupResult ).data ); } expandNextGroup(); return; } _currentResult = new NodeExpandResult( _currentGroup.shift() ); _currentGroupResult.push( _currentResult ); expandNode( _currentResult.nodeId ); } /** * Раскрывает ещё не раскрытые узлы объекта до указанной глубины * */ private function expandNextNode() : void { var node : INode; //Помечаем текущий раскрытый узел, как раскрытый if ( _currentExpandingObjectId ) { node = _currentResult.graph.nodeByStringId( _currentExpandingObjectId ); if ( node ) { node.data.expanded = true; } } node = _currentResult.graph.nodeByStringId( _currentResult.nodeId ); if ( node ) { var tree : IGTree = _currentResult.graph.getTree( node ); //Ищем следующий узел для раскрытия for each( node in tree.nodes ) { //Если узла нету в глобальном графе if ( _graph.nodeByStringId( node.stringid ) == null ) { //Если узел не раскрыт if ( ! nodeExpanded( node.stringid ) ) { //И его глубина меньше depth if ( tree.getDistance( node ) < _depth ) { //Раскрываем его и выходим expandNode( node.stringid ); return; } } } } } else //Во время загрузки информации об корневом узле произошла ошибка { //Переходим к следующему объекту expandNextObject(); return; } /* Если мы здесь, значит все дерево раскрыто */ //Переходим к раскрытию следующего объекта expandNextObject(); } private static const defaultStatusString : String = 'Раскрытие объектов...'; private function expandNode( nodeId : String ) : void { //Если имеется информация о текущем раскрываемом узле, var node : INode = _currentResult.graph.nodeByStringId( nodeId ); if ( ! node ) { node = _graph.nodeByStringId( nodeId ); } if ( node ) { //то указываем имя текущего раскрываемого узла _statusString = 'Раскрываю : ' + node.data.name + '...'; } else { _statusString = defaultStatusString; } _expandedNodes[ nodeId ] = nodeId; _currentExpandingObjectId = nodeId; _unis.getShowGraph( nodeId ); } /** * Определяет был ли этот узел развернут уже * @param nodeId - идентификатор узла для проверки * @return true - был * false - не был * */ private function nodeExpanded( nodeId : String ) : Boolean { return _expandedNodes.hasOwnProperty( nodeId ); } private function init() : void { _unis = UnisAPI.impl; _unis.addListener( AMFErrorEvent.ERROR, onUnisError, this ); _unis.addListener( AMGGraphDataEvent.GRAPH_DATA, onGraphData, this ); _currentExpandingObjectId = null; _currentGroup = null; _currentResult = null; _currentGroupResult = null; _expandedNodes = new Object(); _statusString = defaultStatusString; operationStart(); } private function uninit() : void { _unis.removeAllObjectListeners( this ); _unis = null; _currentGroup = null; _currentResult = null; _currentGroupResult = null; _currentExpandingObjectId = null; _expandedNodes = null; operationComplete(); } private function onUnisError( e : AMFErrorEvent ) : void { _statusString = 'Ошибка : ' + e.text; _lastError = e; dispatchEvent( new GraphTreeExpandErrorEvent( GraphTreeExpandErrorEvent.ERROR, e.call.params[ 1 ], e.text, e.errorID ) ); next(); } private function onGraphData( e : AMGGraphDataEvent ) : void { _currentResult.graph.safeInitFromVO( e.data ); next(); } } }
/* Copyright (c) 2004-2006, The Dojo Foundation All Rights Reserved. Licensed under the Academic Free License version 2.1 or above OR the modified BSD license. For more information on Dojo licensing, see: http://dojotoolkit.org/community/licensing.shtml */ /** A wrapper around Flash 8's ExternalInterface; DojoExternalInterface is needed so that we can do a Flash 6 implementation of ExternalInterface, and be able to support having a single codebase that uses DojoExternalInterface across Flash versions rather than having two seperate source bases, where one uses ExternalInterface and the other uses DojoExternalInterface. DojoExternalInterface class does a variety of optimizations to bypass ExternalInterface's unbelievably bad performance so that we can have good performance on Safari; see the blog post http://codinginparadise.org/weblog/2006/02/how-to-speed-up-flash-8s.html for details. @author Brad Neuberg, bkn3@columbia.edu */ import flash.external.ExternalInterface; class DojoExternalInterface{ public static var available:Boolean; public static var dojoPath = ""; private static var flashMethods:Array = new Array(); private static var numArgs:Number; private static var argData:Array; private static var resultData = null; public static function initialize(){ // extract the dojo base path DojoExternalInterface.dojoPath = DojoExternalInterface.getDojoPath(); // see if we need to do an express install var install:ExpressInstall = new ExpressInstall(); if(install.needsUpdate){ install.init(); } // register our callback functions ExternalInterface.addCallback("startExec", DojoExternalInterface, startExec); ExternalInterface.addCallback("setNumberArguments", DojoExternalInterface, setNumberArguments); ExternalInterface.addCallback("chunkArgumentData", DojoExternalInterface, chunkArgumentData); ExternalInterface.addCallback("exec", DojoExternalInterface, exec); ExternalInterface.addCallback("getReturnLength", DojoExternalInterface, getReturnLength); ExternalInterface.addCallback("chunkReturnData", DojoExternalInterface, chunkReturnData); ExternalInterface.addCallback("endExec", DojoExternalInterface, endExec); // set whether communication is available DojoExternalInterface.available = ExternalInterface.available; DojoExternalInterface.call("loaded"); } public static function addCallback(methodName:String, instance:Object, method:Function) : Boolean{ // register DojoExternalInterface methodName with it's instance DojoExternalInterface.flashMethods[methodName] = instance; // tell JavaScript about DojoExternalInterface new method so we can create a proxy ExternalInterface.call("dojo.flash.comm._addExternalInterfaceCallback", methodName); return true; } public static function call(methodName:String, resultsCallback:Function) : Void{ // we might have any number of optional arguments, so we have to // pass them in dynamically; strip out the results callback var parameters = new Array(); for(var i = 0; i < arguments.length; i++){ if(i != 1){ // skip the callback parameters.push(arguments[i]); } } var results = ExternalInterface.call.apply(ExternalInterface, parameters); // immediately give the results back, since ExternalInterface is // synchronous if(resultsCallback != null && typeof resultsCallback != "undefined"){ resultsCallback.call(null, results); } } /** Called by Flash to indicate to JavaScript that we are ready to have our Flash functions called. Calling loaded() will fire the dojo.flash.loaded() event, so that JavaScript can know that Flash has finished loading and adding its callbacks, and can begin to interact with the Flash file. */ public static function loaded(){ DojoExternalInterface.call("dojo.flash.loaded"); } public static function startExec():Void{ DojoExternalInterface.numArgs = null; DojoExternalInterface.argData = null; DojoExternalInterface.resultData = null; } public static function setNumberArguments(numArgs):Void{ DojoExternalInterface.numArgs = numArgs; DojoExternalInterface.argData = new Array(DojoExternalInterface.numArgs); } public static function chunkArgumentData(value, argIndex:Number):Void{ //getURL("javascript:dojo.debug('FLASH: chunkArgumentData, value="+value+", argIndex="+argIndex+"')"); var currentValue = DojoExternalInterface.argData[argIndex]; if(currentValue == null || typeof currentValue == "undefined"){ DojoExternalInterface.argData[argIndex] = value; }else{ DojoExternalInterface.argData[argIndex] += value; } } public static function exec(methodName):Void{ // decode all of the arguments that were passed in for(var i = 0; i < DojoExternalInterface.argData.length; i++){ DojoExternalInterface.argData[i] = DojoExternalInterface.decodeData(DojoExternalInterface.argData[i]); } var instance = DojoExternalInterface.flashMethods[methodName]; DojoExternalInterface.resultData = instance[methodName].apply( instance, DojoExternalInterface.argData); // encode the result data DojoExternalInterface.resultData = DojoExternalInterface.encodeData(DojoExternalInterface.resultData); //getURL("javascript:dojo.debug('FLASH: encoded result data="+DojoExternalInterface.resultData+"')"); } public static function getReturnLength():Number{ if(DojoExternalInterface.resultData == null || typeof DojoExternalInterface.resultData == "undefined"){ return 0; } var segments = Math.ceil(DojoExternalInterface.resultData.length / 1024); return segments; } public static function chunkReturnData(segment:Number):String{ var numSegments = DojoExternalInterface.getReturnLength(); var startCut = segment * 1024; var endCut = segment * 1024 + 1024; if(segment == (numSegments - 1)){ endCut = segment * 1024 + DojoExternalInterface.resultData.length; } var piece = DojoExternalInterface.resultData.substring(startCut, endCut); //getURL("javascript:dojo.debug('FLASH: chunking return piece="+piece+"')"); return piece; } public static function endExec():Void{ } private static function decodeData(data):String{ // we have to use custom encodings for certain characters when passing // them over; for example, passing a backslash over as //// from JavaScript // to Flash doesn't work data = DojoExternalInterface.replaceStr(data, "&custom_backslash;", "\\"); data = DojoExternalInterface.replaceStr(data, "\\\'", "\'"); data = DojoExternalInterface.replaceStr(data, "\\\"", "\""); return data; } private static function encodeData(data){ //getURL("javascript:dojo.debug('inside flash, data before="+data+"')"); // double encode all entity values, or they will be mis-decoded // by Flash when returned data = DojoExternalInterface.replaceStr(data, "&", "&amp;"); // certain XMLish characters break Flash's wire serialization for // ExternalInterface; encode these into a custom encoding, rather than // the standard entity encoding, because otherwise we won't be able to // differentiate between our own encoding and any entity characters // that are being used in the string itself data = DojoExternalInterface.replaceStr(data, '<', '&custom_lt;'); data = DojoExternalInterface.replaceStr(data, '>', '&custom_gt;'); // encode control characters and JavaScript delimiters data = DojoExternalInterface.replaceStr(data, "\n", "\\n"); data = DojoExternalInterface.replaceStr(data, "\r", "\\r"); data = DojoExternalInterface.replaceStr(data, "\f", "\\f"); data = DojoExternalInterface.replaceStr(data, "'", "\\'"); data = DojoExternalInterface.replaceStr(data, '"', '\"'); //getURL("javascript:dojo.debug('inside flash, data after="+data+"')"); return data; } /** Flash ActionScript has no String.replace method or support for Regular Expressions! We roll our own very simple one. */ private static function replaceStr(inputStr:String, replaceThis:String, withThis:String):String { var splitStr = inputStr.split(replaceThis) inputStr = splitStr.join(withThis) return inputStr; } private static function getDojoPath(){ var url = _root._url; var start = url.indexOf("baseRelativePath=") + "baseRelativePath=".length; var path = url.substring(start); var end = path.indexOf("&"); if(end != -1){ path = path.substring(0, end); } return path; } } // vim:ts=4:noet:tw=0:
/** * 개발자 : refracta * 날짜 : 2014-09-04 오전 4:59 */ package refracta.presentation.manager { import com.greensock.loading.SWFLoader; import flash.display.Loader; import flash.display.MovieClip; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.system.LoaderContext; import flash.utils.ByteArray; import refracta.presentation.pconst.PresentationConst; public class GraphSimulatorManager { private var _viewClip:MovieClip; private var dataLoader:URLLoader; private var testSwfLoader:Loader; private var testLoaderContextData:LoaderContext; private var _isLoaded:Boolean = false; private var locationX:Number = 0; private var locationY:Number = 0; private var swfWidth:Number = 0; private var swfHeight:Number = 0; public function set viewClip(value:MovieClip):void { _viewClip = value; } public function get isLoaded():Boolean { return _isLoaded; } public function set isLoaded(value:Boolean):void { _isLoaded = value; } public function get viewClip():MovieClip { return _viewClip; } public function GraphSimulatorManager(locationX:Number, locationY:Number, swfWidth:Number, swfHeight:Number) { this.locationX = locationX; this.locationY = locationY; this.swfWidth = swfWidth; this.swfHeight = swfHeight; this._viewClip = new MovieClip(); this.dataLoader = new URLLoader(); this.dataLoader.dataFormat = URLLoaderDataFormat.BINARY; this.dataLoader.addEventListener(Event.COMPLETE, dataLoadComplete); this.dataLoader.addEventListener(ProgressEvent.PROGRESS, progressHandler); this.dataLoader.addEventListener(IOErrorEvent.IO_ERROR, useCacheData); this.testLoaderContextData = new LoaderContext(); this.testLoaderContextData.allowLoadBytesCodeExecution = true; this.testSwfLoader = new Loader(); this.testSwfLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, useCacheData); this.testSwfLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler); this.testSwfLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, passSwfTest); } public function loadStart() { if (!PresentationConst.GRAPH_SIMULATOR_CACHE_LOCATION.exists) { trace("Load From Server (GRAPH SIMULATOR)"); this.dataLoader.load(PresentationConst.GRAPH_SIMULATOR_URL); } else { trace("Load From File (GRAPH SIMULATOR)"); this.dataLoader.load(new URLRequest(PresentationConst.GRAPH_SIMULATOR_CACHE_LOCATION.url)); } } private function progressHandler(event:ProgressEvent):void { var percentLoaded:int = event.target.bytesLoaded / event.target.bytesTotal * 100; var callName:String = "GraphSimulator"; trace("[" + callName + "] Current Loading : " + percentLoaded); } private var loadSwfArray:ByteArray; private function dataLoadComplete(event:Event):void { this.loadSwfArray = ByteArray(this.dataLoader.data); this.testSwfLoader.loadBytes(loadSwfArray, this.testLoaderContextData); } private function useCacheData(event:*) { trace("Use Cache Data"); if (!PresentationConst.GRAPH_SIMULATOR_CACHE_LOCATION.exists) { trace("No Cache"); return; } this._isLoaded = true; } private function passSwfTest(event:Event) { saveSwfBytes(event); //뷰에 넣기 this._isLoaded = true; } public function addSwf() { var swfLoader:SWFLoader = new SWFLoader("resources/" + PresentationConst.GRAPH_SIMULATOR_FILE_NAME, { container: _viewClip, x: locationX, y: locationY, width: swfWidth, height: swfHeight }); swfLoader.load(); } private function saveSwfBytes(event:*) { testSwfLoader.unload(); var fileStream:FileStream = new FileStream(); fileStream.addEventListener(IOErrorEvent.IO_ERROR, useCacheData); fileStream.open(PresentationConst.GRAPH_SIMULATOR_CACHE_LOCATION, FileMode.WRITE); fileStream.writeBytes(loadSwfArray); fileStream.close(); } } }
package nid.xfl.compiler.swf.data.actions.swf3 { import nid.xfl.compiler.swf.SWFData; import nid.xfl.compiler.swf.data.actions.*; public class ActionGotoFrame extends Action implements IAction { public static const CODE:uint = 0x81; public var frame:uint; public function ActionGotoFrame(code:uint, length:uint) { super(code, length); } override public function parse(data:SWFData):void { frame = data.readUI16(); } override public function publish(data:SWFData):void { var body:SWFData = new SWFData(); body.writeUI16(frame); write(data, body); } override public function clone():IAction { var action:ActionGotoFrame = new ActionGotoFrame(code, length); action.frame = frame; return action; } override public function toString(indent:uint = 0):String { return "[ActionGotoFrame] Frame: " + frame; } } }
package kabam.rotmg.account.ui.components { import com.company.ui.BaseSimpleText; import flash.display.Sprite; import flash.events.Event; import flash.events.FocusEvent; import flash.events.TextEvent; import flash.filters.DropShadowFilter; import kabam.lib.util.DateValidator; import kabam.rotmg.text.view.TextFieldDisplayConcrete; import kabam.rotmg.text.view.stringBuilder.LineBuilder; import org.osflash.signals.Signal; public class DateField extends Sprite { private static const BACKGROUND_COLOR:uint = 3355443; private static const ERROR_BORDER_COLOR:uint = 16549442; private static const NORMAL_BORDER_COLOR:uint = 4539717; private static const TEXT_COLOR:uint = 11776947; private static const INPUT_RESTRICTION:String = "1234567890"; private static const FORMAT_HINT_COLOR:uint = 5592405; public function DateField() { super(); this.validator = new DateValidator(); this.thisYear = new Date().getFullYear(); this.label = new TextFieldDisplayConcrete().setSize(18).setColor(11776947); this.label.setBold(true); this.label.setStringBuilder(new LineBuilder().setParams(name)); this.label.filters = [new DropShadowFilter(0, 0, 0)]; addChild(this.label); this.months = new BaseSimpleText(20, 11776947, true, 35, 30); this.months.restrict = "1234567890"; this.months.maxChars = 2; this.months.y = 30; this.months.x = 6; this.months.border = false; this.months.updateMetrics(); this.months.addEventListener("textInput", this.onMonthInput); this.months.addEventListener("focusOut", this.onMonthFocusOut); this.months.addEventListener("change", this.onEditMonth); this.monthFormatText = this.createFormatHint(this.months, "DateField.Months"); addChild(this.monthFormatText); addChild(this.months); this.days = new BaseSimpleText(20, 11776947, true, 35, 30); this.days.restrict = "1234567890"; this.days.maxChars = 2; this.days.y = 30; this.days.x = 63; this.days.border = false; this.days.updateMetrics(); this.days.addEventListener("textInput", this.onDayInput); this.days.addEventListener("focusOut", this.onDayFocusOut); this.days.addEventListener("change", this.onEditDay); this.dayFormatText = this.createFormatHint(this.days, "DateField.Days"); addChild(this.dayFormatText); addChild(this.days); this.years = new BaseSimpleText(20, 11776947, true, 55, 30); this.years.restrict = "1234567890"; this.years.maxChars = 4; this.years.y = 30; this.years.x = 118; this.years.border = false; this.years.updateMetrics(); this.years.restrict = "1234567890"; this.years.addEventListener("textInput", this.onYearInput); this.years.addEventListener("change", this.onEditYear); this.yearFormatText = this.createFormatHint(this.years, "DateField.Years"); addChild(this.yearFormatText); addChild(this.years); this.setErrorHighlight(false); } public var label:TextFieldDisplayConcrete; public var days:BaseSimpleText; public var months:BaseSimpleText; public var years:BaseSimpleText; private var dayFormatText:TextFieldDisplayConcrete; private var monthFormatText:TextFieldDisplayConcrete; private var yearFormatText:TextFieldDisplayConcrete; private var thisYear:int; private var validator:DateValidator; public function setTitle(param1:String):void { this.label.setStringBuilder(new LineBuilder().setParams(param1)); } public function setErrorHighlight(param1:Boolean):void { this.drawSimpleTextBackground(this.months, 0, 0, param1); this.drawSimpleTextBackground(this.days, 0, 0, param1); this.drawSimpleTextBackground(this.years, 0, 0, param1); } public function isValidDate():Boolean { var _loc1_:int = parseInt(this.months.text); var _loc3_:int = parseInt(this.days.text); var _loc2_:int = parseInt(this.years.text); return this.validator.isValidDate(_loc1_, _loc3_, _loc2_, 100); } public function getDate():String { var _loc1_:String = this.getFixedLengthString(this.months.text, 2); var _loc3_:String = this.getFixedLengthString(this.days.text, 2); var _loc2_:String = this.getFixedLengthString(this.years.text, 4); return _loc1_ + "/" + _loc3_ + "/" + _loc2_; } public function getTextChanged():Signal { return this.label.textChanged; } private function drawSimpleTextBackground(param1:BaseSimpleText, param2:int, param3:int, param4:Boolean):void { var _loc5_:uint = !!param4 ? 16549442 : 4539717; graphics.lineStyle(2, _loc5_, 1, false, "normal", "round", "round"); graphics.beginFill(3355443, 1); graphics.drawRect(param1.x - param2 - 5, param1.y - param3, param1.width + param2 * 2, param1.height + param3 * 2); graphics.endFill(); graphics.lineStyle(); } private function createFormatHint(param1:BaseSimpleText, param2:String):TextFieldDisplayConcrete { var _loc3_:TextFieldDisplayConcrete = new TextFieldDisplayConcrete().setSize(16).setColor(5592405); _loc3_.setTextWidth(param1.width + 4).setTextHeight(param1.height); _loc3_.x = param1.x - 6; _loc3_.y = param1.y + 3; _loc3_.setStringBuilder(new LineBuilder().setParams(param2)); _loc3_.setAutoSize("center"); return _loc3_; } private function getEarliestYear(param1:String):int { while (param1.length < 4) { param1 = param1 + "0"; } return int(param1); } private function getFixedLengthString(param1:String, param2:int):String { while (param1.length < param2) { param1 = "0" + param1; } return param1; } private function onMonthInput(param1:TextEvent):void { var _loc2_:String = this.months.text + param1.text; var _loc3_:int = parseInt(_loc2_); if (_loc2_ != "0" && !this.validator.isValidMonth(_loc3_)) { param1.preventDefault(); } } private function onMonthFocusOut(param1:FocusEvent):void { var _loc2_:int = parseInt(this.months.text); if (_loc2_ < 10 && this.days.text != "") { this.months.text = "0" + _loc2_.toString(); } } private function onEditMonth(param1:Event):void { this.monthFormatText.visible = !this.months.text; } private function onDayInput(param1:TextEvent):void { var _loc2_:String = this.days.text + param1.text; var _loc3_:int = parseInt(_loc2_); if (_loc2_ != "0" && !this.validator.isValidDay(_loc3_)) { param1.preventDefault(); } } private function onDayFocusOut(param1:FocusEvent):void { var _loc2_:int = parseInt(this.days.text); if (_loc2_ < 10 && this.days.text != "") { this.days.text = "0" + _loc2_.toString(); } } private function onEditDay(param1:Event):void { this.dayFormatText.visible = !this.days.text; } private function onYearInput(param1:TextEvent):void { var _loc2_:String = this.years.text + param1.text; var _loc3_:int = this.getEarliestYear(_loc2_); if (_loc3_ > this.thisYear) { param1.preventDefault(); } } private function onEditYear(param1:Event):void { this.yearFormatText.visible = !this.years.text; } } }
// makeswf -v 7 -r 1 -o point-properties-7.swf point-properties.as #include "trace_properties.as" var a = new Button (); // FIXME: test button embedded in the swf trace_properties (_global.Button, "_global", "Button"); trace_properties (a, "local", "a"); loadMovie ("FSCommand:quit", "");
package chat.protocol.transport { public class Response { public var correlationId:int; public var status:String; public var payload:Payload; public function Response(_id:int, _status:String, _payload:Object) { super(); this.init(_id,_status,_payload); } protected function init(_id:int, _status:String, _payload:Object) : void { this.correlationId = _id; this.status = _status; if(_payload != null) { this.payload = Payload.createFromReceivedJsonObject(_payload.id,_payload.data); } } } }
package com.ankamagames.dofus.network.messages.game.context.fight { import com.ankamagames.dofus.network.types.game.idol.Idol; 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 GameFightStartMessage extends NetworkMessage implements INetworkMessage { public static const protocolId:uint = 5357; private var _isInitialized:Boolean = false; public var idols:Vector.<Idol>; private var _idolstree:FuncTree; public function GameFightStartMessage() { this.idols = new Vector.<Idol>(); super(); } override public function get isInitialized() : Boolean { return this._isInitialized; } override public function getMessageId() : uint { return 5357; } public function initGameFightStartMessage(idols:Vector.<Idol> = null) : GameFightStartMessage { this.idols = idols; this._isInitialized = true; return this; } override public function reset() : void { this.idols = new Vector.<Idol>(); 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_GameFightStartMessage(output); } public function serializeAs_GameFightStartMessage(output:ICustomDataOutput) : void { output.writeShort(this.idols.length); for(var _i1:uint = 0; _i1 < this.idols.length; _i1++) { (this.idols[_i1] as Idol).serializeAs_Idol(output); } } public function deserialize(input:ICustomDataInput) : void { this.deserializeAs_GameFightStartMessage(input); } public function deserializeAs_GameFightStartMessage(input:ICustomDataInput) : void { var _item1:Idol = null; var _idolsLen:uint = input.readUnsignedShort(); for(var _i1:uint = 0; _i1 < _idolsLen; _i1++) { _item1 = new Idol(); _item1.deserialize(input); this.idols.push(_item1); } } public function deserializeAsync(tree:FuncTree) : void { this.deserializeAsyncAs_GameFightStartMessage(tree); } public function deserializeAsyncAs_GameFightStartMessage(tree:FuncTree) : void { this._idolstree = tree.addChild(this._idolstreeFunc); } private function _idolstreeFunc(input:ICustomDataInput) : void { var length:uint = input.readUnsignedShort(); for(var i:uint = 0; i < length; i++) { this._idolstree.addChild(this._idolsFunc); } } private function _idolsFunc(input:ICustomDataInput) : void { var _item:Idol = new Idol(); _item.deserialize(input); this.idols.push(_item); } } }
package serverProto.fight { import com.netease.protobuf.Message; import com.netease.protobuf.fieldDescriptors.RepeatedFieldDescriptor$TYPE_MESSAGE; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_BOOL; import com.netease.protobuf.WireType; 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 ProtoRawFightWheelWarReq extends Message { public static const PLAYER_LIST:RepeatedFieldDescriptor$TYPE_MESSAGE = new RepeatedFieldDescriptor$TYPE_MESSAGE("serverProto.fight.ProtoRawFightWheelWarReq.player_list","playerList",2 << 3 | WireType.LENGTH_DELIMITED,ProtoRawFightWheelWarPlayer); public static const WHEEL_WAR_NEED_PADDED:FieldDescriptor$TYPE_BOOL = new FieldDescriptor$TYPE_BOOL("serverProto.fight.ProtoRawFightWheelWarReq.wheel_war_need_padded","wheelWarNeedPadded",3 << 3 | WireType.VARINT); [ArrayElementType("serverProto.fight.ProtoRawFightWheelWarPlayer")] public var playerList:Array; private var wheel_war_need_padded$field:Boolean; private var hasField$0:uint = 0; public function ProtoRawFightWheelWarReq() { this.playerList = []; super(); } public function clearWheelWarNeedPadded() : void { this.hasField$0 = this.hasField$0 & 4.294967294E9; this.wheel_war_need_padded$field = new Boolean(); } public function get hasWheelWarNeedPadded() : Boolean { return (this.hasField$0 & 1) != 0; } public function set wheelWarNeedPadded(param1:Boolean) : void { this.hasField$0 = this.hasField$0 | 1; this.wheel_war_need_padded$field = param1; } public function get wheelWarNeedPadded() : Boolean { return this.wheel_war_need_padded$field; } override final function writeToBuffer(param1:WritingBuffer) : void { var _loc3_:* = undefined; var _loc2_:uint = 0; while(_loc2_ < this.playerList.length) { WriteUtils.writeTag(param1,WireType.LENGTH_DELIMITED,2); WriteUtils.write$TYPE_MESSAGE(param1,this.playerList[_loc2_]); _loc2_++; } if(this.hasWheelWarNeedPadded) { WriteUtils.writeTag(param1,WireType.VARINT,3); WriteUtils.write$TYPE_BOOL(param1,this.wheel_war_need_padded$field); } for(_loc3_ in this) { super.writeUnknown(param1,_loc3_); } } 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: 2, Size: 2) */ throw new flash.errors.IllegalOperationError("Not decompiled due to error"); } } }
/** * <p>Original Author: toddanderson</p> * <p>Class File: TextInputSkin.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.skin { import com.custardbelly.as3flobile.controls.textinput.TextInput; import com.custardbelly.as3flobile.enum.BasicStateEnum; import com.custardbelly.as3flobile.model.BoxPadding; import flash.display.Graphics; import flash.display.Shape; import flash.display.Sprite; import flash.text.TextField; import flash.text.TextFormat; /** * TextInputSkin is a base skin class for a TextInput control. * @author toddanderson */ public class TextInputSkin extends Skin { protected var _defaultFormat:TextFormat; protected var _boilerFormat:TextFormat; /** * Constructor. */ public function TextInputSkin() { super(); // Create the default and boiler plate formats. _defaultFormat = new TextFormat( "DroidSans", 14 ); _boilerFormat = new TextFormat( "DroidSans", 14, 0xBBBBBB, null, true ); } /** * @private * * Initializes the background display for the control. * @param display Graphics * @param width int * @param height int */ protected function initializeBackground( display:Graphics, width:int, height:int ):void { updateBackground( display, width, height ); } /** * @private * * Initializes the clear button display for the control. * @param display Graphics * @param width int * @param height int */ protected function initializeClearDisplay( display:Sprite, width:int, height:int ):void { updateClearDisplay( display, width, height ); } /** * @private * * Initializes the input display for the control. * @param display TextField * @param width int * @param height int */ protected function initializeInput( display:TextField, width:int, height:int ):void { display.defaultTextFormat = _defaultFormat; } /** * @private * * Updates the background dislpay for the control. * @param display Graphics * @param width int * @param height int */ protected function updateBackground( display:Graphics, width:int, height:int ):void { var lineColor:uint = ( _target.skinState == BasicStateEnum.FOCUSED ) ? 0xFF7F00 : 0x999999; display.clear(); display.beginFill( 0xFFFFFF ); display.lineStyle( 2, lineColor, 1, false, "normal", "square", "miter" ); display.drawRoundRect( 0, 0, width, height, 5, 5 ); display.endFill(); } /** * @private * * updates the clear button display for the control. * @param display Graphics * @param width int * @param height int */ protected function updateClearDisplay( display:Sprite, width:int, height:int ):void { const offset:int = 4; var radius:int = ( height < 10 ) ? ( height * 0.5 ) : 10; var diameter:int = radius * 2; display.graphics.clear(); display.graphics.beginFill( 0xCCCCCC ); display.graphics.drawCircle( radius, radius, radius ); display.graphics.endFill(); display.graphics.lineStyle( 2, 0xFFFFFF, 1, true, "normal", "square", "miter" ); display.graphics.moveTo( offset, offset ); display.graphics.lineTo( diameter - offset, diameter - offset ); display.graphics.moveTo( diameter - offset, offset ); display.graphics.lineTo( offset, diameter - offset ); } /** * @private * * Updates the input display for the control. * @param display TextField * @param width int * @param height int */ protected function updateInput( display:TextField, width:int, height:int ):void { if( _target.skinState == BasicStateEnum.NORMAL ) { var format:TextFormat = ( display.text == ( _target as TextInput ).defaultText ) ? _boilerFormat : _defaultFormat; if( display.getTextFormat() != format ) { display.setTextFormat( format ); } } } /** * @private * * Updates the position of display items. * @param width int * @param height int */ protected function updateLayout( width:int, height:int ):void { var padding:BoxPadding = _target.padding; var inputTarget:TextInput = ( _target as TextInput ); var inputDisplay:TextField = inputTarget.inputDisplay; var clearButtonDisplay:Sprite = inputTarget.clearButtonDisplay; // Update clear button display position. clearButtonDisplay.x = width - clearButtonDisplay.width - padding.right; // Update input size and position. inputDisplay.width = clearButtonDisplay.x - ( padding.right ); inputDisplay.x = padding.left; // Base height on multiline. if( inputDisplay.multiline ) { inputDisplay.height = height - ( padding.top + padding.bottom ); inputDisplay.y = padding.top; clearButtonDisplay.y = padding.top; } else { // position clear button in the middle of height. clearButtonDisplay.y = ( height - clearButtonDisplay.height ) * 0.5; // Base height on font size. This will be overwritten if multiline is true on input. var fontSize:int = ( _target.skinState == BasicStateEnum.NORMAL ) ? int(_defaultFormat.size) : int(_boilerFormat.size); inputDisplay.height = ( fontSize * 2 ); inputDisplay.y = ( height - ( fontSize * 1.5 ) ) * 0.5; } } /** * @inherit */ override public function initializeDisplay( width:int, height:int ):void { super.initializeDisplay( width, height ); var inputTarget:TextInput = ( _target as TextInput ); initializeBackground( inputTarget.backgroundDisplay, width, height ); initializeClearDisplay( inputTarget.clearButtonDisplay, width, height ); initializeInput( inputTarget.inputDisplay, width, height ); updateLayout( width, height ); } /** * @inherit */ override public function updateDisplay( width:int, height:int ):void { super.updateDisplay( width, height ); var inputTarget:TextInput = ( _target as TextInput ); updateBackground( inputTarget.backgroundDisplay, width, height ); updateClearDisplay( inputTarget.clearButtonDisplay, width, height ); updateInput( inputTarget.inputDisplay, width, height ); updateLayout( width, height ); } /** * @inherit */ override public function dispose():void { super.dispose(); _defaultFormat = null; } } }
//////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011 Esri // // All rights reserved under the copyright laws of the United States. // You may freely redistribute and use this software, with or // without modification, provided you include the original copyright // and use restrictions. See use restrictions in the file: // <install location>/License.txt // //////////////////////////////////////////////////////////////////////////////// package widgets.Geoprocessing.parameters { import com.esri.ags.SpatialReference; import com.esri.ags.symbols.SimpleFillSymbol; import com.esri.ags.symbols.SimpleLineSymbol; import com.esri.ags.symbols.SimpleMarkerSymbol; public class InputParamParser extends BaseParamParser { override public function parseParameters(paramsXML:XMLList):Array { var params:Array = []; var param:IGPParameter; for each (var paramXML:XML in paramsXML) { param = GPParameterFactory.getGPParamFromType(paramXML.@type); param.defaultValueFromString(String(paramXML.@defaultvalue)); param.label = paramXML.@label; param.name = paramXML.@name; param.toolTip = paramXML.@tooltip; param.visible = (paramXML.@visible == "true"); param.required = (paramXML.@required == "true"); if (paramXML.choicelist[0]) { if (param.type == GPParameterTypes.MULTI_VALUE) { param.choiceList = parseMultiValueChoiceList(paramXML.choicelist.choice); } else { param.choiceList = parseChoiceList(paramXML.choicelist.choice); } } var featureParam:IGPFeatureParameter = param as IGPFeatureParameter; if (featureParam) { featureParam.geometryType = paramXML.@geometrytype; featureParam.layerName = featureParam.label; var wkid:Number = parseFloat(paramXML.@wkid[0]); var wkt:String = paramXML.@wkt[0]; if (wkid || wkt) { featureParam.spatialReference = new SpatialReference(wkid, wkt) } featureParam.renderer = parseRenderer(paramXML.renderer[0], featureParam.geometryType); } params.push(param); } return params; } private function parseMultiValueChoiceList(choiceListXML:XMLList):Array { var choiceList:Array = []; var choiceValue:String; for each (var choice:XML in choiceListXML) { choiceList.push(new MultiValueItem(choice.@value)); } return choiceList; } private function parseChoiceList(choiceListXML:XMLList):Array { var choiceList:Array = []; var choiceValue:String; for each (var choice:XML in choiceListXML) { choiceValue = choice.@value; choiceList.push(choiceValue); } return choiceList; } //override default symbols to match draw widget defaults override protected function createDefaultPointSymbol():SimpleMarkerSymbol { return new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 15, 0x3FAFDC, 1, 0, 0, 0, new SimpleLineSymbol()); } override protected function createDefaultPolygonSymbol():SimpleFillSymbol { return new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, 0x3FAFDC, 1, new SimpleLineSymbol()); } override protected function createDefaultPolylineSymbol():SimpleLineSymbol { return new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, 0x3FAFDC, 1, 5); } } }
/** * BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ * * Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). * * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 3.0 of the License, or (at your option) any later * version. * * BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with BigBlueButton; if not, see <http://www.gnu.org/licenses/>. * */ package org.bigbluebutton.modules.whiteboard.events { import flash.events.Event; public class ToggleGridEvent extends Event { public static const TOGGLE_GRID:String = "toggleGrid"; public static const GRID_TOGGLED:String = "gridToggled"; public function ToggleGridEvent(type:String) { super(type, true, false); } } }
package org.ro.layout { public class ActionLayout extends MemberLayout { internal var bookmarking:String; internal var position:String; internal var cssClassFa:String; internal var cssClassFaPosition:String; public function ActionLayout(jsonObj:Object = null) { fromObject(json); } } }
package com.logicom.geom { public class ExPolygon { public var outer:Polygon; public var holes:Polygons; } }
package org.osflash.signals.utils { import flash.events.Event; /** Signal Async event. * @author eidiot */ public class SignalAsyncEvent extends Event { //====================================================================== // Class constants //====================================================================== public static const CALLED:String = "called"; //====================================================================== // Constructor //====================================================================== public function SignalAsyncEvent(type:String, args:Array) { super(type); _args = args; } //---------------------------------- // args //---------------------------------- private var _args:Array; /** * Arguments of the called signal. */ public function get args():Array { return _args; } //====================================================================== // Overridden methods //====================================================================== override public function clone():Event { return new SignalAsyncEvent(type, _args); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.graphics.shaderClasses { import flash.display.Shader; /** * Creates a blend shader that is equivalent to * the 'Hue' blend mode for RGB premultiplied colors available * in Adobe Creative Suite tools. This blend mode is not native to Flash, * but is available in tools like Adobe Illustrator and Adobe Photoshop. * * <p>The 'hue' blend mode can be set on Flex groups and graphic * elements. The visual appearance in tools like Adobe Illustrator and * Adobe Photoshop will be mimicked through this blend shader.</p> * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 * * @includeExample examples/HueShaderExample.mxml */ public class HueShader extends flash.display.Shader { [Embed(source="Hue.pbj", mimeType="application/octet-stream")] private static var ShaderClass:Class; /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function HueShader() { super(new ShaderClass()); } } }
/* Copyright (C) 2011 by Billy Schoenberg 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.bschoenberg.components.events { import com.bschoenberg.components.supportClasses.ITreeItem; import flash.events.Event; public class TreeDataEvent extends Event { public static const ADD:String = "add"; public static const REMOVE:String = "remove"; public static const MOVE:String = "move"; private var _parent:ITreeItem; private var _item:ITreeItem; private var _index:int; private var _oldParent:ITreeItem; public function TreeDataEvent(type:String, item:ITreeItem, parent:ITreeItem=null, oldParent:ITreeItem=null, index:int=-1, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); _item = item; _parent = parent; _index = index; _oldParent = oldParent; } public override function clone():Event { return new TreeDataEvent(type,item,parent, oldParent, index); } public function get item():ITreeItem { return _item; } public function get oldParent():ITreeItem { return _oldParent; } public function get parent():ITreeItem { return _parent; } public function get index():int { return _index; } } }
/** * Copyright (c) Michael Baczynski 2007 * http://lab.polygonal.de/ds/ * * This software is distributed under licence. Use of this software * implies agreement with all terms and conditions of the accompanying * software licence. */ package de.polygonal.ds { import de.polygonal.ds.Collection; /** * A two-dimensonal array built upon a single linear array. */ public class Array2 implements Collection { private var _a:Array; private var _w:int, _h:int; /** * Initializes a two-dimensional array to match the given width and height. * * @param w The width (number of colums). * @param h The height (number of rows). */ public function Array2(width:int, height:int) { _a = new Array((_w = width) * (_h = height)); fill(null); } /** * Indicates the width (colums). * If a new width is set, the two-dimensional array is resized accordingly. */ public function get width():int { return _w; } public function set width(w:int):void { resize(w, _h); } /** * Indicates the height (rows). * If a new height is set, the two-dimensional array is resized accordingly. */ public function get height():int { return _h; } public function set height(h:int):void { resize(_w, h); } /** * Sets each cells in the two-dimensional array to a given value. * * @param item The item to be written into each cell. */ public function fill(item:*):void { var k:int = _w * _h; for (var i:int = 0; i < k; i++) _a[i] = item; } /** * Reads the value at the given x/y index. * No boundary check is performed, so you have to * make sure that the input coordinates do not exceed * the width or height of the two-dimensional array. * * @param x The x index. * @param y The y index. */ public function get(x:int, y:int):* { return _a[int(y * _w + x)]; } /** * Writes data into the cell at the given x/y index. * No boundary check is performed, so you have to * make sure that the input coordinates do not exceed * the width or height of the two-dimensional array. * * @param x The x index. * @param y The y index. * @param obj The item to be written into the cell. */ public function set(x:int, y:int, obj:*):void { _a[int(y * _w + x)] = obj; } /** * Resizes the array to match the given width and height * while preserving existing values. * * @param w The new width (cols) * @param h The new height (rows) */ public function resize(w:int, h:int):void { if (w <= 0) w = 1; if (h <= 0) h = 1; var copy:Array = _a.concat(); _a.length = 0; _a.length = w * h; var minx:int = w < _w ? w : _w; var miny:int = h < _h ? h : _h; var x:int, y:int, t1:int, t2:int; for (y = 0; y < miny; y++) { t1 = y * w; t2 = y * _w; for (x = 0; x < minx; x++) _a[int(t1 + x)] = copy[int(t2 + x)]; } _w = w; _h = h; } /** * Extracts the row at the given index. * * @return An array storing the values of the row. */ public function getRow(y:int):Array { var offset:int = y * _w; return _a.slice(offset, offset + _w); } /** * Extracts the colum at the given index. * * @return An array storing the values of the column. */ public function getCol(x:int):Array { var t:Array = []; for (var i:int = 0; i < _h; i++) t[i] = _a[int(i * _w + x)]; return t; } /** * Shifts all columns by one column to the left. * Columns are wrapped, so the column at index 0 is * not lost but appended to the rightmost column. */ public function shiftLeft():void { if (_w == 1) return; var j:int = _w - 1, k:int; for (var i:int = 0; i < _h; i++) { k = i * _w + j; _a.splice(k, 0, _a.splice(k - j, 1)); } } /** * Shifts all columns by one column to the right. * Columns are wrapped, so the column at the last index is * not lost but appended to the leftmost column. */ public function shiftRight():void { if (_w == 1) return; var j:int = _w - 1, k:int; for (var i:int = 0; i < _h; i++) { k = i * _w + j; _a.splice(k - j, 0, _a.splice(k, 1)); } } /** * Shifts all rows up by one row. * Rows are wrapped, so the first row is * not lost but appended to bottommost row. */ public function shiftUp():void { if (_h == 1) return; _a = _a.concat(_a.slice(0, _w)); _a.splice(0, _w); } /** * Shifts all rows down by one row. * Rows are wrapped, so the last row is * not lost but appended to the topmost row. */ public function shiftDown():void { if (_h == 1) return; var offset:int = (_h - 1) * _w; _a = _a.slice(offset, offset + _w).concat(_a); _a.splice(_h * _w, _w); } /** * Appends an array as a new row. * If the given array is longer or shorter than the current width, * it is truncated or widened to match the current dimensions. * * @param a The array to insert. */ public function appendRow(a:Array):void { a.length = _w; _a = _a.concat(a); _h++ } /** * Prepends an array as a new row. * If the given array is longer or shorter than the current width, * it is truncated or widened to match the current dimensions. * * @param a The array to insert. */ public function prependRow(a:Array):void { a.length = _w; _a = a.concat(_a); _h++; } /** * Appends an array as a new column. * If the given array is longer or shorter than the current height, * it is truncated or widened to match the current dimensions. * * @param a The array to insert. */ public function appendCol(a:Array):void { a.length = _h; for (var y:int = 0; y < _h; y++) _a.splice(y * _w + _w + y, 0, a[y]); _w++; } /** * Prepends an array as a new column. * If the given array is longer or shorter than the current height, * it is truncated or widened to match the current dimensions. * * @param a - The array to insert. */ public function prependCol(a:Array):void { a.length = _h; for (var y:int = 0; y < _h; y++) _a.splice(y * _w + y, 0, a[y]); _w++; } /** * Flips rows with cols and vice versa. * This is equivalent of rotating the array about 180 degrees. */ public function transpose():void { var a:Array = _a.concat(); for (var y:int = 0; y < _h; y++) { for (var x:int = 0; x < _w; x++) _a[int(x * _w + y)] = a[int(y * _w + x)] } } /** * Checks if a given item exists. * * @return True if the specified item is found, otherwise false. */ public function contains(obj:*):Boolean { var k:int = size; for (var i:int = 0; i < k; i++) { if (_a[i] === obj) return true; } return false; } /** * Clears all elements. */ public function clear():void { _a = new Array(size); } /** * Initializes an iterator object * pointing to the first value (0, 0). */ public function getIterator():Iterator { return new Array2Iterator(this); } /** * The total number of cells. */ public function get size():int { return _w * _h; } /** * Checks if the 2d array is empty. */ public function isEmpty():Boolean { return false; } /** * Converts the structure into an array. * * @return An array storing the data of this structure. */ public function toArray():Array { var a:Array = _a.concat(); var k:int = size; if (a.length > k) a.length = k; return a; } /** * Returns a string representing the current object. */ public function toString():String { return "[Array2, width=" + width + ", height=" + height + "]"; } /** * Prints all elements (for debug/demo purposes only). */ public function dump():String { var s:String = "Array2\n{"; var offset:int, value:*; for (var y:int = 0; y < _h; y++) { s += "\n" + "\t"; offset = y * _w; for (var x:int = 0; x < _w; x++) { value = _a[int(offset + x)]; s += "[" + (value != undefined ? value : "?") + "]"; } } s += "\n}"; return s; } } } import de.polygonal.ds.Iterator; import de.polygonal.ds.Array2; internal class Array2Iterator implements Iterator { private var _a2:Array2; private var _xCursor:int; private var _yCursor:int; public function Array2Iterator(a2:Array2) { _a2 = a2; _xCursor = _yCursor = 0; } public function get data():* { return _a2.get(_xCursor, _yCursor); } public function set data(obj:*):void { _a2.set(_xCursor, _yCursor, obj); } public function start():void { _xCursor = _yCursor = 0; } public function hasNext():Boolean { return (_yCursor * _a2.width + _xCursor < _a2.size); } public function next():* { var item:* = data; if (++_xCursor == _a2.width) { _yCursor++; _xCursor = 0; } return item; } }
package org.torproject { import flash.events.EventDispatcher; import flash.net.Socket; import flash.net.SecureSocket; import flash.events.Event; import flash.events.ProgressEvent; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; import flash.utils.getDefinitionByName; import org.torproject.events.SOCKS5TunnelEvent; import org.torproject.model.HTTPResponse; import org.torproject.model.HTTPResponseHeader; import org.torproject.model.SOCKS5Model; import org.torproject.model.TorASError; import flash.net.URLRequest; import flash.net.URLRequestDefaults; import flash.net.URLRequestHeader; import flash.net.URLRequestMethod; import flash.net.URLVariables; import org.torproject.utils.URLUtil; import flash.utils.setTimeout; import flash.utils.clearTimeout; //TLS/SSL support thanks to Henri Torgeman, a.k.a. Metal Hurlant - https://code.google.com/p/as3crypto/ import com.hurlant.crypto.tls.*; /** * Provides SOCKS5-capable transport services for proxied network requests. This protocol is also used by Tor to transport * various network requests. * * Since TorControl is used to manage the Tor services process, if this process is already correctly configured and running * SOCKS5Tunnel can be used completely independently (TorControl may be entirely omitted). * * @author Patrick Bay * * The MIT License (MIT) * * Copyright (c) 2013 - 2016 Patrick Bay * * 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. * * --- * * This library incorporate the "as3crypto" library by Henri Torgeman. Additional licences for this libary and additionally * incorporated source code are displayed below: * * Copyright (c) 2007 Henri Torgemane * All Rights Reserved. * * BigInteger, RSA, Random and ARC4 are derivative works of the jsbn library * (http://www-cs-students.stanford.edu/~tjw/jsbn/) * The jsbn library is Copyright (c) 2003-2005 Tom Wu (tjw@cs.Stanford.EDU) * * MD5, SHA1, and SHA256 are derivative works (http://pajhome.org.uk/crypt/md5/) * Those are Copyright (c) 1998-2002 Paul Johnston & Contributors (paj@pajhome.org.uk) * * SHA256 is a derivative work of jsSHA2 (http://anmar.eu.org/projects/jssha2/) * jsSHA2 is Copyright (c) 2003-2004 Angel Marin (anmar@gmx.net) * * AESKey is a derivative work of aestable.c (http://www.geocities.com/malbrain/aestable_c.html) * aestable.c is Copyright (c) Karl Malbrain (malbrain@yahoo.com) * * BlowFishKey, DESKey and TripeDESKey are derivative works of the Bouncy Castle Crypto Package (http://www.bouncycastle.org) * Those are Copyright (c) 2000-2004 The Legion Of The Bouncy Castle * * Base64 is copyright (c) 2006 Steve Webster (http://dynamicflash.com/goodies/base64) * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. Redistributions in binary form must * reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * --- * * Additionally, the MD5 algorithm is covered by the following notice: * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved. * * License to copy and use this software is granted provided that it * is identified as the "RSA Data Security, Inc. MD5 Message-Digest * Algorithm" in all material mentioning or referencing this software * or this function. * * License is also granted to make and use derivative works provided * that such works are identified as "derived from the RSA Data * Security, Inc. MD5 Message-Digest Algorithm" in all material * mentioning or referencing the derived work. * * RSA Data Security, Inc. makes no representations concerning either * the merchantability of this software or the suitability of this * software for any particular purpose. It is provided "as is" * without express or implied warranty of any kind. * * These notices must be retained in any copies of any part of this * documentation and/or software. */ public class SOCKS5Tunnel extends EventDispatcher { /** * Default SOCKS5 IP address. For Tor networking, this is usually 127.0.0.1 (the current local machine). */ public static const defaultSOCKSIP:String = "127.0.0.1"; /** * Default SOCKS5 port. */ public static const defaultSOCKSPort:int = 1080; /** * Maximum number of redirects to follow, if enabled, whenever a 301 or 302 HTTP status is received. */ public static const maxRedirects:int = 5; private var _tunnelSocket:Socket = null; private var _secureTunnelSocket:TLSSocket = null; private var _tunnelIP:String = null; private var _tunnelPort:int = -1; private var _connectionType:int = -1; private var _connected:Boolean = false; private var _authenticated:Boolean = false; private var _tunneled:Boolean = false; private var _requestActive:Boolean = false; private var _requestBuffer:Array = new Array(); private var _responseBuffer:ByteArray = new ByteArray(); private var _HTTPStatusReceived:Boolean = false; private var _HTTPHeadersReceived:Boolean = false; private var _HTTPResponse:HTTPResponse; private var _currentRequest:URLRequest; private var _redirectCount:int = 0; private var _timeoutID:uint; /** * Creates an instance of a SOCKS5 proxy tunnel. * * @param tunnelIPSet The SOCKS proxy IP to use. If not specified, the current default value is used. * @param tunnelPortSet The SOCKS proxy port to use. If not specified, the current default value is used. */ public function SOCKS5Tunnel(tunnelIPSet:String=null, tunnelPortSet:int=-1) { if (tunnelIPSet == null) { this._tunnelIP = defaultSOCKSIP; } else { this._tunnelIP = tunnelIPSet; } if (tunnelPortSet < 1) { this._tunnelPort = defaultSOCKSPort; } else { this._tunnelPort = tunnelPortSet; } }//constructor /** * The current SOCKS proxy tunnel IP being used by the instance. */ public function get tunnelIP():String { return (this._tunnelIP); }//get tunnelIP /** * The current SOCKS proxy tunnel port being used by the instance. */ public function get tunnelPort():int { return (this._tunnelPort); }//get tunnelPort /** * The tunnel connection type being managed by this instance. */ public function get connectionType():int { return (this._connectionType); }//get connectionType /** * The status of the tunnel connection (true=connected, false=not connected). Requests * cannot be sent through the proxy unless it is both connected and tunneled. */ public function get connected():Boolean { return (this._connected); }//get connected /** * The status of the proxy tunnel (true=ready, false=not ready). Requests * cannot be sent through the proxy unless it is both connected and tunneled. */ public function get tunneled():Boolean { return (this._tunneled); }//get tunneled /** * Sends a HTTP request through the socks proxy, sending any included information (such as form data) in the process. Additional * requests via this tunnel connection will be disallowed until this one has completed (since replies may be multi-part). * * @param request The URLRequest object holding the necessary information for the request. * @param timeout The amount of time, in milliseconds, before the request times out. A request times out when a full response * (header + body) is not fully received. Default is 30000 (30 seconds). * * @return True if the request was dispatched successfully, false otherwise. */ public function loadHTTP(request:URLRequest, timeout:Number=30000):Boolean { if (request == null) { return (false); }//if try { this._requestBuffer.push(request); //this._currentRequest = request; this._responseBuffer = new ByteArray(); this._HTTPStatusReceived = false; this._HTTPHeadersReceived = false; this.disconnectSocket(); this._HTTPResponse = new HTTPResponse(); this._connectionType = SOCKS5Model.SOCKS5_conn_TCPIPSTREAM; this._tunnelSocket = new Socket(); this.addSocketListeners(); trace ("request timeout " + timeout); this._timeoutID=setTimeout(this.onRequestTimeout, timeout, request); this._tunnelSocket.connect(this.tunnelIP, this.tunnelPort); return (true); } catch (err:*) { var eventObj:SOCKS5TunnelEvent = new SOCKS5TunnelEvent(SOCKS5TunnelEvent.ONCONNECTERROR); eventObj.error = new TorASError(err.toString()); eventObj.error.rawMessage = err.toString(); this.dispatchEvent(eventObj); return (false); }//catch return (false); }//loadHTTP /** * Invoked when a tunnelled request times out (full response is not received within a specified time limit). */ public function onRequestTimeout(requestObj:URLRequest):void { trace ("SOCKS5Tunnel timedout"); var eventObj:SOCKS5TunnelEvent = new SOCKS5TunnelEvent(SOCKS5TunnelEvent.ONTIMEOUT); eventObj.request = requestObj; this.dispatchEvent(eventObj); } /** * The currently active HTTP/HTTPS request being handled by the tunnel instance. */ public function get activeRequest():* { return (this._currentRequest); }//get activeRequest /** * Attempts to establish a new Tor circuit through a running TorControl instance. * Future SOCKS5Tunnel instances will communicate through the new circuit while * existing and connected instances will continue to communicate through their existing circuits until closed. * A TorControl instance must be instantiated and fully initialized before attempting to invoke this command. * * @return True if TorControl is active and could be invoked to establish a new circuit, false * if the invocation failed for any reason. */ public function establishNewCircuit():Boolean { try { //Dynamically evaluate so that there are no dependencies var tcClass:Class = getDefinitionByName("org.torproject.TorControl") as Class; if (tcClass == null) { return (false); }//if var tcInstance:*= new tcClass(); if (tcClass.connected && tcClass.authenticated) { tcInstance.establishNewCircuit(); return (true); }//if } catch (err:*) { return (false); }//catch return (false); }//establishNewCircuit /** * Disconnects the SOCKS5 tunnel socket if connected. */ private function disconnectSocket():void { this._connected = false; this._authenticated = false; this._tunneled = false; if (this._tunnelSocket != null) { this.removeSocketListeners(); if (this._tunnelSocket.connected) { this._tunnelSocket.close(); }//if this._tunnelSocket = null; var eventObj:SOCKS5TunnelEvent = new SOCKS5TunnelEvent(SOCKS5TunnelEvent.ONDISCONNECT); this.dispatchEvent(eventObj); }//if }//disconnectSocket /** * Removes standard listeners to the default SOCKS5 tunnel socket. */ private function removeSocketListeners():void { if (this._tunnelSocket == null) { return;} this._tunnelSocket.removeEventListener(Event.CONNECT, this.onTunnelConnect); this._tunnelSocket.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onTunnelConnectError); this._tunnelSocket.removeEventListener(IOErrorEvent.IO_ERROR, this.onTunnelConnectError); this._tunnelSocket.removeEventListener(IOErrorEvent.NETWORK_ERROR, this.onTunnelConnectError); this._tunnelSocket.removeEventListener(ProgressEvent.SOCKET_DATA, this.onTunnelData); this._tunnelSocket.removeEventListener(Event.CLOSE, this.onTunnelDisconnect); }//removeSocketListeners /** * Adds standard listeners to the default SOCKS5 tunnel socket. */ private function addSocketListeners():void { if (this._tunnelSocket == null) { return;} this._tunnelSocket.addEventListener(Event.CONNECT, this.onTunnelConnect); this._tunnelSocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onTunnelConnectError); this._tunnelSocket.addEventListener(IOErrorEvent.IO_ERROR, this.onTunnelConnectError); this._tunnelSocket.addEventListener(IOErrorEvent.NETWORK_ERROR, this.onTunnelConnectError); this._tunnelSocket.addEventListener(Event.CLOSE, this.onTunnelDisconnect); }//addSocketListeners /** * Invoked when the SOCKS5 tunnel socket connection is successfully established. * * @param eventObj A standard Event object. */ private function onTunnelConnect(eventObj:Event):void { this._connected = true; this._tunnelSocket.removeEventListener(Event.CONNECT, this.onTunnelConnect); this._tunnelSocket.addEventListener(ProgressEvent.SOCKET_DATA, this.onTunnelData); var connectEvent:SOCKS5TunnelEvent = new SOCKS5TunnelEvent(SOCKS5TunnelEvent.ONCONNECT); this.dispatchEvent(connectEvent); this.authenticateTunnel(); }//onTunnelConnect /** * Invoked when the SOCKS5 tunnel receives an IOErrorEvent event. * * @param eventObj A standard IOErrorEvent object. */ private function onTunnelConnectError(eventObj:IOErrorEvent):void { this.removeSocketListeners(); this._tunnelSocket = null; this._connected = false; this._authenticated = false; this._tunneled = false; var errorEventObj:SOCKS5TunnelEvent = new SOCKS5TunnelEvent(SOCKS5TunnelEvent.ONCONNECTERROR); errorEventObj.error = new TorASError(eventObj.toString()); errorEventObj.error.status = eventObj.errorID; errorEventObj.error.rawMessage = eventObj.toString(); this.dispatchEvent(errorEventObj); }//onTunnelConnectError /** * Invoked when the SOCKS5 tunnel socket has been disconnected. * * @param eventObj A standard Event object. */ private function onTunnelDisconnect(eventObj:Event):void { this.removeSocketListeners(); this._connected = false; this._authenticated = false; this._tunneled = false; this._tunnelSocket = null; var disconnectEvent:SOCKS5TunnelEvent = new SOCKS5TunnelEvent(SOCKS5TunnelEvent.ONDISCONNECT); this.dispatchEvent(disconnectEvent); }//onTunnelDisconnect /** * Invoked to authenticate the SOCKS5 tunnel after it is connected. The tunnel will not accept any outbound * requests until authentication has been completed. * * Note: Currently only the 0 (none) authentication type is supported. */ private function authenticateTunnel():void { this._tunnelSocket.writeByte(SOCKS5Model.SOCKS5_head_VERSION); this._tunnelSocket.writeByte(SOCKS5Model.SOCKS5_auth_NUMMETHODS); this._tunnelSocket.writeByte(SOCKS5Model.SOCKS5_auth_NOAUTH); this._tunnelSocket.flush(); }//authenticateTunnel /** * Invoked when the SOCKS5 tunnel authentication has completed and the end-to-end connection is ready to be established. */ private function onAuthenticateTunnel():void { var currentRequest:* = this._requestBuffer[0]; //var currentRequest:*= this._requestBuffer; if (currentRequest is URLRequest) { this.establishHTTPTunnel(); }//if }//onAuthenticateTunnel /** * Establishes a HTTP/HTTPS tunnel once the SOCKS5 socket has been connected and authenticated. If no port is specified, * HTTP connections will be attempted over port 80 while HTTPS connections will be attempted over port 443. */ private function establishHTTPTunnel():void { this._tunnelSocket.writeByte(SOCKS5Model.SOCKS5_head_VERSION); this._tunnelSocket.writeByte(SOCKS5Model.SOCKS5_conn_TCPIPSTREAM); this._tunnelSocket.writeByte(0); //Reserved this._tunnelSocket.writeByte(SOCKS5Model.SOCKS5_addr_DOMAIN); //Most secure when using DNS through proxy var currentRequest:* = this._requestBuffer[0]; //var currentRequest:*= this._currentRequest; var domain:String = URLUtil.getServerName(currentRequest.url); /* var domainSplit:Array = domain.split("."); if (domainSplit.length>2) { domain = domainSplit[1] + "." + domainSplit[2]; //Ensure we have JUST the domain }//if */ var domainLength:int = int(domain.length); var port:int = int(URLUtil.getPort(currentRequest.url)); this._tunnelSocket.writeByte(domainLength); var portMSB:int = (port & 0xFF00) >> 8; var portLSB:int = port & 0xFF; this._tunnelSocket.writeMultiByte(domain, SOCKS5Model.charSetEncoding); this._tunnelSocket.writeByte(portMSB); this._tunnelSocket.writeByte(portLSB); this._tunnelSocket.flush(); }//establishHTTPTunnel /** * Invoked when the SOCKS5 tunnel has been established (connected and authenticated). */ private function onEstablishTunnel():void { var currentRequest:* = this._requestBuffer[0]; //var currentRequest:*= this._currentRequest; //URLRequest handles HTTP/HTTPS requests... if (currentRequest is URLRequest) { this.sendQueuedHTTPRequest(); }//if }//onEstablishHTTPTunnel /** * Sends the next queued HTTP/HTTPS request. Requests are queued whenever a connection has not yet been established or * authentication is not yet complete. */ private function sendQueuedHTTPRequest():void { //var currentRequest:URLRequest = this._requestBuffer.shift() as URLRequest; //this._currentRequest = currentRequest; this._currentRequest = this._requestBuffer[0]; if (URLUtil.isHttpsURL(this._currentRequest.url)) { this.startTLSTunnel(); } else { if (this._HTTPResponse!=null ) { if (this._currentRequest.manageCookies) { var requestString:String = SOCKS5Model.createHTTPRequestString(this._currentRequest, this._HTTPResponse.cookies); } else { requestString = SOCKS5Model.createHTTPRequestString(this._currentRequest, null); }//else } else { requestString = SOCKS5Model.createHTTPRequestString(this._currentRequest, null); }//else this._HTTPResponse = new HTTPResponse(); this._tunnelSocket.writeMultiByte(requestString, SOCKS5Model.charSetEncoding); this._tunnelSocket.flush(); }//else }//sendQueuedHTTPRequest /** * Starts TLS for HTTPS requests/responses. */ private function startTLSTunnel():void { if (this._HTTPResponse!=null ) { if (this._currentRequest.manageCookies) { var requestString:String = SOCKS5Model.createHTTPRequestString(this._currentRequest, this._HTTPResponse.cookies); } else { requestString = SOCKS5Model.createHTTPRequestString(this._currentRequest, null); }//else } else { requestString = SOCKS5Model.createHTTPRequestString(this._currentRequest, null); }//else this._HTTPResponse = new HTTPResponse(); var domain:String = URLUtil.getServerName(this._currentRequest.url); this._secureTunnelSocket = new TLSSocket(); this._tunnelSocket.removeEventListener(ProgressEvent.SOCKET_DATA, this.onTunnelData); this._secureTunnelSocket.addEventListener(ProgressEvent.SOCKET_DATA, this.onTunnelData); this._secureTunnelSocket.startTLS(this._tunnelSocket, domain); this._secureTunnelSocket.writeMultiByte(requestString, SOCKS5Model.charSetEncoding); //This is queued to send on connect }//startTLSTunnel /** * Tests whether or not the SOCKS5 authentication request was successful. * * @param respData The raw response data to analyze. * * @return True if the response confirms that authentication was successful, false otherwise. */ private function authResponseOkay(respData:ByteArray):Boolean { respData.position = 0; var SOCKSVersion:int = respData.readByte(); var authMethod:int = respData.readByte(); if (SOCKSVersion != SOCKS5Model.SOCKS5_head_VERSION) { return (false); }//if if (authMethod != SOCKS5Model.SOCKS5_auth_NOAUTH) { return (false); }//if return (true); }//authResponseOkay /** * Tests whether or not the SOCKS5 response indicates that the tunnel has been established and is ready for communication. * * @param respData The raw SOCKS5 response message to analyze. * * @return True if the SOCKS5 tunnel is ready to proxy requests and responses, false otherwise. */ private function tunnelResponseOkay(respData:ByteArray):Boolean { respData.position = 0; var currentRequest:* = this._requestBuffer[0]; if (currentRequest is URLRequest) { var SOCKSVersion:int = respData.readByte(); var status:int = respData.readByte(); if (SOCKSVersion != SOCKS5Model.SOCKS5_head_VERSION) { return (false); }//if if (status != 0) { return (false); }//if return (true); }//if return (false); }//tunnelResponseOkay /** * Tests whether or not the SOCKS5 response data indicates that the entire HTTP/HTTPS request and response are complete. * * @param respData The raw SOCKS5 data to analyze. * * @return True if the tunneled transaction appears to be complete, false otherwise. */ private function tunnelRequestComplete(respData:ByteArray):Boolean { var bodySize:int = -1; if (this._HTTPHeadersReceived) { try { //If content length header supplied, use it to determine if response body is fully completed... bodySize = int(this._HTTPResponse.getHeader("Content-Length").value); if (bodySize>-1) { var bodyReceived:int = this._HTTPResponse.body.length; if (bodySize != bodyReceived) { return (false); }//if return (true); }//if } catch (err:*) { bodySize = -1; }//catch }//if //Content-Length header not found so using raw data length instead... respData.position = respData.length - 4; //Not bytesAvailable since already read at this point! var respString:String = respData.readMultiByte(4, SOCKS5Model.charSetEncoding); respData.position = 0; if (respString == SOCKS5Model.doubleLineEnd) { return (true); }//if return (false); }//tunnelRequestComplete /** * Handles a HTTP redirect (301 or 302 response code). * * @param responseObj The HTTPResponse object to analyze for redirection information. * * @return True if the supplied response is a redirect and the redirect was automatically handled, false otherwise. */ private function handleHTTPRedirect(responseObj:HTTPResponse):Boolean { this._currentRequest = _requestBuffer[0] as URLRequest; if (this._currentRequest.followRedirects) { if ((responseObj.statusCode == 301) || (responseObj.statusCode == 302)) { var redirectInfo:HTTPResponseHeader = responseObj.getHeader("Location"); if (redirectInfo != null) { this._redirectCount++; this._currentRequest.url = redirectInfo.value; this._HTTPStatusReceived = false; this._HTTPHeadersReceived = false; this._responseBuffer = new ByteArray(); if (this._redirectCount >= maxRedirects) { //Maximum redirects hit var statusEvent:SOCKS5TunnelEvent = new SOCKS5TunnelEvent(SOCKS5TunnelEvent.ONHTTPMAXREDIRECTS); statusEvent.httpResponse = this._HTTPResponse; this.dispatchEvent(statusEvent); this.disconnectSocket(); return (true); }//if this._requestBuffer.push(this._currentRequest); statusEvent = new SOCKS5TunnelEvent(SOCKS5TunnelEvent.ONHTTPREDIRECT); statusEvent.httpResponse = this._HTTPResponse; this.dispatchEvent(statusEvent); this.sendQueuedHTTPRequest(); return (true); }//if }//if }//if return (false); }//handleHTTPRedirect /** * Handles a raw, partial or complete HTTP response. This method also handles HTTPS responses after decryption using the same * mechanisms. * * @param rawData The raw HTTP data to analyze and process. * @param secure Used with the SOCKS5TunnelEvent dispatched by this method to inform listeners whether or not the response is secure (HTTPS). */ private function handleHTTPResponse(rawData:ByteArray, secure:Boolean = false):void { rawData.readBytes(this._responseBuffer, this._responseBuffer.length); if (!this._HTTPStatusReceived) { if (this._HTTPResponse.parseResponseStatus(this._responseBuffer)) { this._HTTPStatusReceived = true; var statusEvent:SOCKS5TunnelEvent = new SOCKS5TunnelEvent(SOCKS5TunnelEvent.ONHTTPSTATUS); statusEvent.httpResponse = this._HTTPResponse; this.dispatchEvent(statusEvent); }//if }//if if (!this._HTTPHeadersReceived) { if (this._HTTPResponse.parseResponseHeaders(this._responseBuffer)) { this._HTTPHeadersReceived = true; statusEvent = new SOCKS5TunnelEvent(SOCKS5TunnelEvent.ONHTTPHEADERS); statusEvent.httpResponse = this._HTTPResponse; this.dispatchEvent(statusEvent); }//if }//if if (this.handleHTTPRedirect(this._HTTPResponse)) { return; }//if this._responseBuffer.position = 0; this._HTTPResponse.parseResponseBody(this._responseBuffer); this._responseBuffer.position = 0; if (!this.tunnelRequestComplete(rawData)) { //Response not yet fully received...keep waiting. return; }//if //Response fully received. clearTimeout(this._timeoutID); this._timeoutID = 0; var dataEvent:SOCKS5TunnelEvent = new SOCKS5TunnelEvent(SOCKS5TunnelEvent.ONHTTPRESPONSE); dataEvent.request = this._requestBuffer.shift();; dataEvent.secure = secure; dataEvent.httpResponse = this._HTTPResponse; dataEvent.httpResponse.rawResponse = new ByteArray(); dataEvent.httpResponse.rawResponse.writeBytes(this._responseBuffer); this.disconnectSocket(); this.dispatchEvent(dataEvent); this._responseBuffer = new ByteArray(); this._HTTPStatusReceived = false; this._HTTPHeadersReceived = false; }//handleHTTPResponse /** * Handles raw HTTP/HTTPS data from the SOCKS5 tunnel socket. Authentication, tunnel establishment, and message * parsing branching (how responses are interpreted), are all handled automatically in this method. * * @param eventObj A standard ProgressEvent event (usually from an active Socket instance). */ private function onTunnelData(eventObj:ProgressEvent):void { var rawData:ByteArray = new ByteArray(); var stringData:String = new String(); if (eventObj.target is Socket) { //Direct socket this._tunnelSocket.readBytes(rawData); } else { //TLS pseudo-socket this._secureTunnelSocket.readBytes(rawData); }//else rawData.position = 0; stringData = rawData.readMultiByte(rawData.length, SOCKS5Model.charSetEncoding); rawData.position = 0; //_authenticated and _tunneled flags are set for all outgoing connections... if (!this._authenticated) { if (this.authResponseOkay(rawData)) { this._authenticated = true; this.onAuthenticateTunnel(); return; }//if }//if if (!this._tunneled) { if (this.tunnelResponseOkay(rawData)) { this._tunneled = true; this.onEstablishTunnel(); return; }//if }//if //Since the tunnel can handle all types of connections, this is where we decide how responses are handled... //if (this._currentRequest is URLRequest) { if (this._requestBuffer[0] is URLRequest) { if (eventObj.target is Socket) { this.handleHTTPResponse(rawData, false); }//if if (eventObj.target is TLSSocket) { this.handleHTTPResponse(rawData, true); }//if }//if }//onTunnelData }//SOCKS5Tunnel class }//package
/************************************************************************ * Copyright 2012 Worlize Inc. * * 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.worlize.gif.blocks { import com.worlize.gif.constants.BlockType; import flash.utils.ByteArray; import flash.utils.Endian; import flash.utils.IDataInput; public class UnknownExtension implements IGIFBlockCodec { public var extensionLabel:uint; public var bytes:ByteArray; public function decode(stream:IDataInput):void { bytes = DataBlock.decodeDataBlocks(stream); } public function encode(ba:ByteArray = null):ByteArray { if (ba === null) { ba = new ByteArray(); ba.endian = Endian.LITTLE_ENDIAN; } ba.writeByte(BlockType.EXTENSION); ba.writeByte(extensionLabel); ba.writeBytes(DataBlock.encodeDataBlocks(bytes)); return ba; } public function dispose():void { if (bytes) { bytes.clear(); bytes = null; } } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.actionscript.as3project.vo { import actionScripts.factory.FileLocation; import actionScripts.locator.IDEModel; import actionScripts.utils.SDKUtils; import actionScripts.utils.SerializeUtil; import actionScripts.utils.TextUtil; import actionScripts.utils.UtilsCore; public class SWFOutputVO { public static const PLATFORM_AIR:String = "AIR"; public static const PLATFORM_MOBILE:String = "AIR Mobile"; public static const PLATFORM_DEFAULT:String = "Flash Player"; public var disabled:Boolean = false; public var path:FileLocation; public var frameRate:Number = 24; public var swfVersion:uint = 10; public var swfMinorVersion:uint = 0; public var width:int = 100; public var height:int = 100; public var platform:String; // TODO What is this? It's present as <movie input="" /> in FD .as3proj /** Not sure what this is */ public var input:String = ""; /** Background color */ public var background:uint; public function toString():String { return "[SWFOutput path='"+path.fileBridge.nativePath+"' frameRate='"+frameRate+"' swfVersion='"+swfVersion+"' width='"+width+"' height='"+height+"' background='#"+backgroundColorHex+"']"; } public function get backgroundColorHex():String { return TextUtil.padLeft(background.toString(16).toUpperCase(), 6); } public function parse(output:XMLList, project:AS3ProjectVO):void { var params:XMLList = output.movie; disabled = SerializeUtil.deserializeBoolean(params.@disabled); path = project.folderLocation.resolvePath(UtilsCore.fixSlashes(params.@path)); frameRate = Number(params.@fps); width = int(params.@width); height = int(params.@height); background = uint("0x"+String(params.@background).substr(1)); input = String(params.@input); platform = String(params.@platform); // we need to do a little more than just setting SWF version value // from config.xml. // To make thing properly works without much headache, we'll // check if the project does uses any specific SDK, if exists then we'll // continue using the config.xml value. // If no specific SDK is in use, we'll check if any gloabla SDK is set in Moonshine, // if exists then we'll update SWF version by it's version value. // If no global SDK exists, then just copy the config.xml value if (!project.buildOptions.customSDK && IDEModel.getInstance().defaultSDK) { swfVersion = SDKUtils.getSdkSwfMajorVersion(null); } else { swfVersion = uint(params.@version); } } /* Returns XML representation of this class. If root is set you will get relative paths */ public function toXML(folder:FileLocation):XML { var output:XML = <output/>; var pathStr:String = path.fileBridge.nativePath; if (folder) { pathStr = folder.fileBridge.getRelativePath(path); } // in case parsing relative path returns null // particularly in scenario when "path" is outside folder // of "folder" if (!pathStr) pathStr = path.fileBridge.nativePath; var outputPairs:Object = { 'disabled' : SerializeUtil.serializeBoolean(disabled), 'fps' : frameRate, 'path' : pathStr, 'width' : width, 'height' : height, 'version' : swfVersion, 'background': "#"+backgroundColorHex, 'input' : input, 'platform' : platform } output.appendChild(SerializeUtil.serializePairs(outputPairs, <movie/>)); return output; } } }
package equipDebt { import com.pickgliss.ui.ComponentFactory; import equipDebt.view.EquipAddMoneyFrame; import equipDebt.view.EquipDebtFrame; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; public class EquipDebtManager extends EventDispatcher { private static var _instance:EquipDebtManager; private var _viewPrompt:EquipDebtFrame; private var _viewDebt:EquipAddMoneyFrame; private var _equipTimeOutArr:Array; private var _isOpen:Boolean = false; public function EquipDebtManager(param1:IEventDispatcher = null) { super(param1); } public static function get Instance() : EquipDebtManager { if(_instance == null) { _instance = new EquipDebtManager(); } return _instance; } public function start() : void { if(this._isOpen == true) { return; } this._equipTimeOutArr = new Array(); this._viewPrompt = null; this.checkEquipTime(); this._isOpen = true; } private function checkEquipTime() : void { var _loc2_:String = null; } public function openEquipDebt() : void { if(this._equipTimeOutArr.length > 0) { this._viewDebt = ComponentFactory.Instance.creatComponentByStylename("EquipAddMoneyFrame"); this._viewDebt.Equiplist = this._equipTimeOutArr; this._viewDebt.show(); } } public function dispose() : void { this._equipTimeOutArr = null; if(this._viewPrompt) { this._viewPrompt.dispose(); } if(this._viewDebt) { this._viewDebt.dispose(); } this._viewDebt = null; this._viewPrompt = null; } } }
package com.codeazur.as3swf.data.abc.utils { /** * @author Simon Richardson - simon@ustwo.co.uk */ public function getExplicitNamespaceIndentifier():String { return EXPLICIT_NAMESPACE_IDENTIFIER; } }
package laya.utils { import laya.display.Sprite; import laya.filters.ColorFilterAction; import laya.filters.IFilterAction; import laya.renders.Render; import laya.renders.RenderContext; import laya.renders.RenderSprite; import laya.resource.HTMLCanvas; import laya.display.Graphics; import laya.resource.Texture; /** * @private */ public class RunDriver { /** * 滤镜动作集。 */ public static var FILTER_ACTIONS:Array = []; private static var pixelRatio:int = -1; /*[FILEINDEX:10000000]*/ private static var _charSizeTestDiv:*; public static var now:Function = function():Number { return __JS__('Date.now()'); } public static var getWindow:Function = function():* { return __JS__('window'); } public static var getPixelRatio:Function = function():Number { if (pixelRatio < 0) { var ctx:* = Browser.context; var backingStore:Number = ctx.backingStorePixelRatio || ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; pixelRatio = (Browser.window.devicePixelRatio || 1) / backingStore; if (pixelRatio < 1) pixelRatio = 1; } return pixelRatio; } public static var getIncludeStr:Function = function(name:String):String { return null; } public static var createShaderCondition:Function = function(conditionScript:String):Function { var fn:String = "(function() {return " + conditionScript + ";})"; return Browser.window.eval(fn);//生成条件判断函数 } private static var hanzi:RegExp = new RegExp("^[\u4E00-\u9FA5]$"); private static var fontMap:Array = []; public static var measureText:Function = function(txt:String, font:String):* { var isChinese:Boolean = hanzi.test(txt); if (isChinese && fontMap[font]) { return fontMap[font]; } var ctx:* = Browser.context; ctx.font = font; var r:* = ctx.measureText(txt); if (isChinese) fontMap[font] = r; return r; } /** * @private */ public static var getWebGLContext:Function = function(canvas:*):void { } /** * 开始函数。 */ public static var beginFlush:Function = function():void { } public static var endFinish:Function = function():void { /*[IF-FLASH]*/ Render.context.ctx.finish(); } /** * 添加至图集的处理函数。 */ public static var addToAtlas:Function; public static var flashFlushImage:Function = function(atlasWebGLCanvas:*):void { } /** * 绘制到画布。 */ public static var drawToCanvas:Function =/*[STATIC SAFE]*/ function(sprite:Sprite, _renderType:int, canvasWidth:Number, canvasHeight:Number, offsetX:Number, offsetY:Number):* { var canvas:HTMLCanvas = HTMLCanvas.create("2D"); var context:RenderContext = new RenderContext(canvasWidth, canvasHeight, canvas); RenderSprite.renders[_renderType]._fun(sprite, context, offsetX, offsetY); return canvas; } /** * 创建2D例子模型的处理函数。 */ public static var createParticleTemplate2D:Function; /** * 用于创建 WebGL 纹理。 */ public static var createGLTextur:Function = null; /** * 用于创建 WebGLContext2D 对象。 */ public static var createWebGLContext2D:Function = null; /** * 用于改变 WebGL宽高信息。 */ public static var changeWebGLSize:Function = /*[STATIC SAFE]*/ function(w:Number, h:Number):void { } /** * 用于创建 RenderSprite 对象。 */ public static var createRenderSprite:Function = /*[STATIC SAFE]*/ function(type:int, next:RenderSprite):RenderSprite { return new RenderSprite(type, next); } /** * 用于创建滤镜动作。 */ public static var createFilterAction:Function =/*[STATIC SAFE]*/ function(type:int):IFilterAction { return new ColorFilterAction(); } /** * 用于创建 Graphics 对象。 */ public static var createGraphics:Function =/*[STATIC SAFE]*/ function():Graphics { return new Graphics(); } /** @private */ public static var clear:Function = function(value:String):void { Render._context.ctx.clear(); }; /** * 清空纹理函数。 */ public static var cancelLoadByUrl:Function = function(url:String):void { }; /** * 清空纹理函数。 */ public static var clearAtlas:Function = function(value:String):void { }; /** @private */ public static var isAtlas:Function = function(bitmap:*):Boolean { return false; } /** @private */ public static var addTextureToAtlas:Function = function(value:Texture):void { }; /** @private */ public static var getTexturePixels:Function = function(value:Texture, x:Number, y:Number, width:Number, height:Number):Array { return null; }; /** @private */ public static var skinAniSprite:Function = function():* { return null; } /** @private */ public static var update3DLoop:Function = function():void { } } }
package visuals.ui.elements.conventions { import com.playata.framework.display.Sprite; import com.playata.framework.display.lib.flash.FlashDisplayObjectContainer; import com.playata.framework.display.lib.flash.FlashLabel; import com.playata.framework.display.lib.flash.FlashLabelArea; import com.playata.framework.display.lib.flash.FlashSprite; import com.playata.framework.display.ui.controls.ILabel; import com.playata.framework.display.ui.controls.ILabelArea; import flash.display.MovieClip; import visuals.ui.elements.buttons.SymbolButtonHelpGeneric; import visuals.ui.elements.icons.SymbolIconDurationGeneric; import visuals.ui.elements.icons.SymbolIconGameCurrencyGeneric; import visuals.ui.elements.icons.SymbolIconXpGeneric; public class SymbolConventionShowBriefingContentGeneric extends Sprite { private var _nativeObject:SymbolConventionShowBriefingContent = null; public var txtConventionName:ILabel = null; public var txtRewardsCaption:ILabel = null; public var txtRequirementsCaption:ILabel = null; public var iconCoins:SymbolIconGameCurrencyGeneric = null; public var iconXp:SymbolIconXpGeneric = null; public var reward1:SymbolConventionRewardGeneric = null; public var reward2:SymbolConventionRewardGeneric = null; public var txtXpTotal:ILabel = null; public var txtGameCurrency:ILabel = null; public var txtXp:ILabel = null; public var iconDuration:SymbolIconDurationGeneric = null; public var txtDuration:ILabel = null; public var progress:SymbolConventionFansBarGeneric = null; public var txtTimeLeft:ILabel = null; public var txtBriefing:ILabelArea = null; public var btnHelp:SymbolButtonHelpGeneric = null; public function SymbolConventionShowBriefingContentGeneric(param1:MovieClip = null) { if(param1) { _nativeObject = param1 as SymbolConventionShowBriefingContent; } else { _nativeObject = new SymbolConventionShowBriefingContent(); } super(null,FlashSprite.fromNative(_nativeObject)); var _loc2_:FlashDisplayObjectContainer = _sprite as FlashDisplayObjectContainer; txtConventionName = FlashLabel.fromNative(_nativeObject.txtConventionName); txtRewardsCaption = FlashLabel.fromNative(_nativeObject.txtRewardsCaption); txtRequirementsCaption = FlashLabel.fromNative(_nativeObject.txtRequirementsCaption); iconCoins = new SymbolIconGameCurrencyGeneric(_nativeObject.iconCoins); iconXp = new SymbolIconXpGeneric(_nativeObject.iconXp); reward1 = new SymbolConventionRewardGeneric(_nativeObject.reward1); reward2 = new SymbolConventionRewardGeneric(_nativeObject.reward2); txtXpTotal = FlashLabel.fromNative(_nativeObject.txtXpTotal); txtGameCurrency = FlashLabel.fromNative(_nativeObject.txtGameCurrency); txtXp = FlashLabel.fromNative(_nativeObject.txtXp); iconDuration = new SymbolIconDurationGeneric(_nativeObject.iconDuration); txtDuration = FlashLabel.fromNative(_nativeObject.txtDuration); progress = new SymbolConventionFansBarGeneric(_nativeObject.progress); txtTimeLeft = FlashLabel.fromNative(_nativeObject.txtTimeLeft); txtBriefing = FlashLabelArea.fromNative(_nativeObject.txtBriefing); btnHelp = new SymbolButtonHelpGeneric(_nativeObject.btnHelp); } public function setNativeInstance(param1:SymbolConventionShowBriefingContent) : void { FlashSprite.setNativeInstance(_sprite,param1); _nativeObject = param1; syncInstances(); } public function syncInstances() : void { FlashLabel.setNativeInstance(txtConventionName,_nativeObject.txtConventionName); FlashLabel.setNativeInstance(txtRewardsCaption,_nativeObject.txtRewardsCaption); FlashLabel.setNativeInstance(txtRequirementsCaption,_nativeObject.txtRequirementsCaption); if(_nativeObject.iconCoins) { iconCoins.setNativeInstance(_nativeObject.iconCoins); } if(_nativeObject.iconXp) { iconXp.setNativeInstance(_nativeObject.iconXp); } if(_nativeObject.reward1) { reward1.setNativeInstance(_nativeObject.reward1); } if(_nativeObject.reward2) { reward2.setNativeInstance(_nativeObject.reward2); } FlashLabel.setNativeInstance(txtXpTotal,_nativeObject.txtXpTotal); FlashLabel.setNativeInstance(txtGameCurrency,_nativeObject.txtGameCurrency); FlashLabel.setNativeInstance(txtXp,_nativeObject.txtXp); if(_nativeObject.iconDuration) { iconDuration.setNativeInstance(_nativeObject.iconDuration); } FlashLabel.setNativeInstance(txtDuration,_nativeObject.txtDuration); if(_nativeObject.progress) { progress.setNativeInstance(_nativeObject.progress); } FlashLabel.setNativeInstance(txtTimeLeft,_nativeObject.txtTimeLeft); FlashLabelArea.setNativeInstance(txtBriefing,_nativeObject.txtBriefing); if(_nativeObject.btnHelp) { btnHelp.setNativeInstance(_nativeObject.btnHelp); } } } }
package citrus.input.controllers.displaylist { import citrus.input.controllers.AVirtualButton; import flash.display.Sprite; import flash.events.MouseEvent; public class VirtualButton extends AVirtualButton { public var graphic:Sprite; //main Sprite container. protected var button:Sprite; public var buttonUpGraphic:Sprite; public var buttonDownGraphic:Sprite; public function VirtualButton(name:String, params:Object = null) { graphic = new Sprite(); super(name, params); } override protected function initGraphics():void { button = new Sprite(); if (!buttonUpGraphic) { buttonUpGraphic = new Sprite(); buttonUpGraphic.graphics.beginFill(0x000000, 0.1); buttonUpGraphic.graphics.drawCircle(0, 0, _buttonradius); buttonUpGraphic.graphics.endFill(); } if (!buttonDownGraphic) { buttonDownGraphic = new Sprite(); buttonDownGraphic.graphics.beginFill(0xEE0000, 0.85); buttonDownGraphic.graphics.drawCircle(0, 0, _buttonradius); buttonDownGraphic.graphics.endFill(); } button.addChild(buttonUpGraphic); graphic.addChild(button); graphic.x = _x; graphic.y = _y; //Add graphic _ce.stage.addChild(graphic); //MOUSE EVENTS graphic.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseEvent); graphic.addEventListener(MouseEvent.MOUSE_UP, handleMouseEvent); } private function handleMouseEvent(e:MouseEvent):void { if (e.type == MouseEvent.MOUSE_DOWN && button == e.target.parent) { triggerON(buttonAction, 1, null, buttonChannel); button.removeChildAt(0); button.addChild(buttonDownGraphic); _ce.stage.addEventListener(MouseEvent.MOUSE_UP, handleMouseEvent); } if (e.type == MouseEvent.MOUSE_UP && button == e.target.parent) { triggerOFF(buttonAction, 0, null, buttonChannel); button.removeChildAt(0); button.addChild(buttonUpGraphic); _ce.stage.removeEventListener(MouseEvent.MOUSE_UP, handleMouseEvent); } } override public function get visible():Boolean { return _visible = graphic.visible; } override public function set visible(value:Boolean):void { _visible = graphic.visible = value; } override public function destroy():void { //remove mouse events. graphic.removeEventListener(MouseEvent.MOUSE_DOWN, handleMouseEvent); graphic.removeEventListener(MouseEvent.MOUSE_UP, handleMouseEvent); //remove graphic _ce.stage.removeChild(graphic); } } }
package org.robotlegs.test.support { public class TestNoExecuteCommand { } }