CombinedText stringlengths 4 3.42M |
|---|
package serverProto.bath
{
import com.netease.protobuf.Message;
import com.netease.protobuf.WritingBuffer;
import flash.utils.IDataInput;
import com.netease.protobuf.ReadUtils;
public final class ProtoBuyBathTimesReq extends Message
{
public function ProtoBuyBathTimesReq()
{
super();
}
override final function writeToBuffer(param1:WritingBuffer) : void
{
var _loc2_:* = undefined;
for(_loc2_ in this)
{
super.writeUnknown(param1,_loc2_);
}
}
override final function readFromSlice(param1:IDataInput, param2:uint) : void
{
var _loc3_:uint = 0;
while(param1.bytesAvailable > param2)
{
_loc3_ = ReadUtils.read$TYPE_UINT32(param1);
if(false?0:0)
{
}
super.readUnknown(param1,_loc3_);
}
}
}
}
|
// Decompiled by AS3 Sorcerer 3.16
// http://www.as3sorcerer.com/
//Button_emphasizedSkin
package
{
import flash.display.MovieClip;
public dynamic class Button_emphasizedSkin extends MovieClip
{
}
}//package
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2005-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package foo{
}
package foo{
}
import foo.*;
var SECTION = "Definitions"; // provide a document reference (ie, Actionscript section)
var VERSION = "AS 3.0"; // Version of ECMAScript or ActionScript
var TITLE = "PackageDefinition" //Proved ECMA section titile or a description
var BUGNUMBER = "";
startTest(); // leave this alone
AddTestCase( "This should compile and run", 1, 1 );
test(); // leave this alone. this executes the test cases and
// displays results.
|
package helloworld.panel {
import common.ControlPanelBase;
import helloworld.Component;
public class ControlPanel extends ControlPanelBase {
protected var _component : Component;
public function ControlPanel(component : Component) {
// button
_component = component;
_component.x = 2;
_component.y = 66;
// controls
addChild(
document(
hLayout(
label("Width:"),
sliderWithLabel({value:_component.w, minValue:50, maxValue:400, snapInterval:5, change:setWidth}),
spacer(0),
label("Height:"),
sliderWithLabel({value:_component.h, minValue:50, maxValue:200, snapInterval:5, change:setHeight})
),
hLayout(
label("Background:"),
colorPicker({color:_component.backgroundColor, tip:"Background", change:setBackgroundColor}),
spacer(0),
label("Border:"),
colorPicker({color:_component.borderColor, tip:"Border", change:setBorderColor}),
spacer(0),
label("Border size:"),
sliderWithLabel({value:_component.borderSize, minValue:0, maxValue:10, snapInterval:1, change:setBorderSize})
),
vSpacer(0),
dottedSeparator(580)
)
);
}
protected function setWidth(color : uint) : void {
}
protected function setHeight(color : uint) : void {
}
protected function setBackgroundColor(color : uint) : void {
}
protected function setBorderColor(color : uint) : void {
}
protected function setBorderSize(size : uint) : void {
_component.x = Math.floor(size / 2);
_component.y = 65 + Math.floor(size / 2);
}
}
}
|
#include "Hitters.as";
#include "SplashWater.as";
#include "SpongeCommon.as";
const int DRY_COOLDOWN = 8;
int cooldown_time = 0;
//logic
void onInit(CBlob@ this)
{
//todo: some tag-based keys to take interference (doesn't work on net atm)
/*AttachmentPoint@ ap = this.getAttachments().getAttachmentPointByName("PICKUP");
if (ap !is null)
{
ap.SetKeysToTake(key_action1 | key_action2 | key_action3);
}*/
this.getSprite().ReloadSprites(0, 0);
this.set_u8(ABSORBED_PROP, 0);
this.Tag("pushedByDoor");
this.getCurrentScript().runFlags |= Script::tick_not_ininventory;
}
void onTick(CBlob@ this)
{
u8 absorbed = this.get_u8(ABSORBED_PROP);
Vec2f pos = this.getPosition();
CMap@ map = this.getMap();
f32 tilesize = map.tilesize;
//absorb water
if (absorbed < ABSORB_COUNT)
{
Vec2f[] vectors = { pos,
pos + Vec2f(0, -tilesize),
pos + Vec2f(-tilesize, 0),
pos + Vec2f(tilesize, 0),
pos + Vec2f(0, tilesize)
};
for (uint i = 0; i < 5; i++)
{
Vec2f temp = vectors[i];
if (map.isInWater(temp))
{
absorbed = adjustAbsorbedAmount(this, 1);
map.server_setFloodWaterWorldspace(temp, false);
}
}
}
//dry out sponge
if (absorbed > 0)
{
if (this.isInFlames()) //in flames
{
absorbed = adjustAbsorbedAmount(this, -1);
}
else if (cooldown_time == 0) //near fireplace
{
CBlob@[] blobsInRadius;
if (map.getBlobsInRadius(pos, 8.0f, @blobsInRadius))
{
for (uint i = 0; i < blobsInRadius.length; i++)
{
CBlob @blob = blobsInRadius[i];
if (blob.getName() == "fireplace")
{
CSprite@ sprite = blob.getSprite();
if (sprite !is null && sprite.isAnimation("fire"))
{
absorbed = adjustAbsorbedAmount(this, -1);
cooldown_time = DRY_COOLDOWN;
break;
}
}
}
}
}
}
//reduce cooldown time
if (cooldown_time > 0)
{
cooldown_time--;
}
}
//sprite
void onInit(CSprite@ this)
{
this.getCurrentScript().tickFrequency = 15;
}
void onTick(CSprite@ this)
{
u8 absorbed = this.getBlob().get_u8(ABSORBED_PROP);
spongeUpdateSprite(this, absorbed);
}
u8 adjustAbsorbedAmount(CBlob@ this, f32 amount)
{
u8 absorbed = this.get_u8(ABSORBED_PROP);
absorbed = Maths::Clamp(absorbed + amount, 0, ABSORB_COUNT);
this.set_u8(ABSORBED_PROP, absorbed);
this.Sync(ABSORBED_PROP, true);
return absorbed;
}
// custom gibs
f32 onHit(CBlob@ this, Vec2f worldPoint, Vec2f velocity, f32 damage, CBlob@ hitterBlob, u8 customData)
{
if (damage > 0.05f) //sound for all damage
{
f32 angle = (this.getPosition() - worldPoint).getAngle();
if (hitterBlob !is this)
{
this.getSprite().PlayRandomSound("/Wetfall2", Maths::Min(1.25f, Maths::Max(0.5f, damage)));
}
else
{
angle = 90.0f; // self-hit. spawn gibs upwards
}
makeGibParticle("Entities/Items/Sponge/SpongeGibs.png",
worldPoint, getRandomVelocity(angle, 1.0f + damage, 90.0f) + Vec2f(0.0f, -2.0f),
0, 4 + XORRandom(4),
Vec2f(8, 8), 2.0f, 0, "", 0);
}
return damage;
} |
/**
* layer的动作
*
* */
import assets.FileHandler.*;
import assets.data.*;
import assets.manager.*;
import flash.display.*;
import flash.events.*;
import flash.geom.*;
import mx.managers.PopUpManager;
import spark.utils.DataItem;
public var DelWin:DelWindow ;
public var isShowDelWin:Boolean = false;
//新建层
public function createLayHandler(event:MouseEvent):void
{
createLayer();
}
protected function createLayer():void
{
var newLayer:layerInfo=new layerInfo(layerList.length,modeSelect.selectedIndex);
var newLayerData:DataItem=layerInfo.createLayerData(newLayer);
o.layerArr.push(newLayer);layerList.addItem(newLayerData);
if(layerList.length==1){layerBox.selectedIndex=0}
var newShape:Shape=new Shape();
var newCommandVector:Vector.<int>=new Vector.<int>();
var newCoordVector:Vector.<Number>=new Vector.<Number>();
var newMemoryCommandVector:Vector.<int>=new Vector.<int>();
var newMemoryCoordVector:Vector.<Number>=new Vector.<Number>();
o.shapeArr.push(newShape);
//~~ shapeArea.addChildAt(o.shapeArr[o.shapeArr.length-1],0);
shapeArea.addChild(o.shapeArr[o.shapeArr.length-1]);
o.commandArr.push(newCommandVector);o.coordArr.push(newCoordVector);
o.memoryCommandArr.push(newMemoryCommandVector);o.memoryCoordArr.push(newMemoryCoordVector);
o.isStepOne.push(true);
moveBtn.enabled = true;
lineBtn.enabled=true;curveBtn.enabled=true;curveBtn2.enabled=true;layerBox.selectedIndex=layerList.length-1;
}
///////////////////////////删除层///////////////////////////////////////
public function DelWinHandler(event:MouseEvent):void
{
showDelWin();
}
private function showDelWin():void
{
if(layerBox.selectedIndex <= -1)
return;
if( !isShowDelWin )
{
DelWin = DelWindow(PopUpManager.createPopUp(this, DelWindow, true));
DelWin["SureBtn"].addEventListener(MouseEvent.CLICK , SureDel);
DelWin["countLayer"].text = "第 "+(layerBox.selectedIndex+1)+" 层:“"+o.layerArr[layerBox.selectedIndex]._name+"” 吗?";
}else
{
delLayer();
}
}
public function SureDel(e:MouseEvent):void
{
if(DelWin["isShowDelWin"].selected)
isShowDelWin = !isShowDelWin;
trace(DelWin["isShowDelWin"].selected,isShowDelWin);
PopUpManager.removePopUp(DelWin);
delLayer();
}
public function delLayer():void
{
for(var i:Number=layerList.length-1;i>-1;i--)
{
o.shapeArr[i].graphics.clear();
}
i=layerBox.selectedIndex;
if(i <= -1)
return;
layerList.removeItemAt(i);
o.layerArr.splice(i,1);
o.commandArr.splice(i,1);
o.isStepOne.splice(i,1);
o.coordArr.splice(i,1);
o.memoryCommandArr.splice(i,1);
o.memoryCoordArr.splice(i,1);
o.shapeArr.splice(i,1);
layerBox.selectedIndex=layerList.length-1;
if(layerList.length==0)
{
resetState();
}else{
for(i=layerList.length-1;i>-1;i--){
o.drawAgain(i);
}
}
}
/////////////////////////////上移层//////////////////////////////
public function upLayer(e:MouseEvent):void
{
upLayr();
}
public function upLayr():void
{
var k:int = layerBox.selectedIndex;
if( (layerList.length >= 2) && (layerBox.selectedIndex >= 1) )
{
o.layerArr = layerInfo.exchange(k,k-1,o.layerArr);
o.commandArr = layerInfo.exchange(k,k-1,o.commandArr);
o.isStepOne = layerInfo.exchange(k,k-1,o.isStepOne);
o.memoryCommandArr = layerInfo.exchange(k,k-1,o.memoryCommandArr);
o.coordArr = layerInfo.exchange(k,k-1,o.coordArr);
o.memoryCoordArr = layerInfo.exchange(k,k-1,o.memoryCoordArr);
var tempShape:Shape=o.shapeArr[k];
o.shapeArr[k]=o.shapeArr[k-1];
o.shapeArr[k-1]=tempShape;
var tempData:Object = layerList.getItemAt(k);
layerList.setItemAt(layerList.getItemAt(k-1),k);
layerList.setItemAt(tempData,k-1);
//!!改层
shapeArea.swapChildren(o.shapeArr[k] , o.shapeArr[k - 1]);
layerBox.selectedIndex -= 1;
}
}
//////////////////////////下移层////////////////////////////////////////
public function downLayer(e:MouseEvent):void
{
downLayr();
}
public function downLayr():void
{
var k:int = layerBox.selectedIndex;
if((layerList.length>=2)&&(k<layerList.length-1)&&(k>=0)){
o.layerArr=layerInfo.exchange(k,k+1,o.layerArr);
o.commandArr=layerInfo.exchange(k,k+1,o.commandArr);
o.isStepOne=layerInfo.exchange(k,k+1,o.isStepOne);
o.memoryCommandArr=layerInfo.exchange(k,k+1,o.memoryCommandArr);
o.coordArr=layerInfo.exchange(k,k+1,o.coordArr);
o.memoryCoordArr=layerInfo.exchange(k,k+1,o.memoryCoordArr);
o.shapeArr=layerInfo.exchange(k,k+1,o.shapeArr);
var tempData:Object=layerList[k+1];
layerList[k+1]=layerList[k];
layerList[k]=tempData;
shapeArea.swapChildren(o.shapeArr[k] , o.shapeArr[k + 1]);
layerBox.selectedIndex+=1;
}
}
public function exchangeLayr(from:int, to:int):void
{
var k:int = layerBox.selectedIndex;
if((layerList.length >= 2) && (k < layerList.length - 1) && ( k >= 0 ))
{
trace(from,to);
o.layerArr.splice(to,0,o.layerArr[from]);
o.commandArr.splice(to,0,o.commandArr[from]);
o.isStepOne.splice(to,0,o.isStepOne[from]);
o.coordArr.splice(to,0,o.coordArr[from]);
o.memoryCommandArr.splice(to,0,o.memoryCommandArr[from]);
o.memoryCoordArr.splice(to,0,o.memoryCoordArr[from]);
o.shapeArr.splice(to,0,o.shapeArr[from]);
shapeArea.removeChildAt(from);
if(from > to)
from++;
else
to--;
shapeArea.addChildAt(o.shapeArr[from], to);
o.layerArr.splice(from,1);
o.commandArr.splice(from,1);
o.isStepOne.splice(from,1);
o.coordArr.splice(from,1);
o.memoryCommandArr.splice(from,1);
o.memoryCoordArr.splice(from,1);
o.shapeArr.splice(from,1);
layerBox.selectedIndex = to;
}
}
/******************************************************************************/
/** 层属性编辑部分
1、刷新层信息显示在layerInfo
2、用户操作层选中被更改时的侦听
**/
/******************************************************************************/
//
public function changeLayerFocus(e:Event):void
{
////////////////////////////////////////////////////////////////////////////////////
var i :int = layerBox.selectedIndex;
if(i <= -1)
return;
if(layerList.length >= 1)
{
if(o.commandArr[i].length != 0)
{
if(i >= 0)//TODO 如果没有这一步,delLayer在调试版本中会出错,访问到-1的i。报错#1010.虽然不影响实际效果。待改善
o.mousePos[3] = new Point(o.coordArr[i][o.coordArr[i].length-2],o.coordArr[i][o.coordArr[i].length-1]);
}else if(curveBtn.emphasized)
{
canvas.removeEventListener(MouseEvent.MOUSE_DOWN,setSecondPoint);
canvas.addEventListener(MouseEvent.CLICK,startDrawCurve);
}else if(curveBtn2.emphasized)
{
canvas.removeEventListener(MouseEvent.MOUSE_DOWN,curveDown);
canvas.addEventListener(MouseEvent.CLICK,startDrawCurve2);
}
}
if(o.memoryCommandArr[i].length == 0){
redoBtn.enabled=false;
redoBtn.removeEventListener(MouseEvent.CLICK,redoStep);
}else{
redoBtn.enabled=true;
redoBtn.addEventListener(MouseEvent.CLICK,redoStep);
}
if(o.commandArr[i].length!=0){
undoBtn.enabled=true;
undoBtn.addEventListener(MouseEvent.CLICK,undoStep);
}else{
undoBtn.enabled=false;
undoBtn.removeEventListener(MouseEvent.CLICK,undoStep);
}
// selectInfo.text = "当前选中层 : "+(i+1).toString();
}
//层数归0后初始化(虽然觉得不用单独写出来但还是暂时这样吧)
public function resetState():void
{
moveBtn.enabled=false;lineBtn.enabled=false;curveBtn.enabled=false;curveBtn2.enabled=false;undoBtn.enabled=false;redoBtn.enabled=false;
} |
intrinsic class String
{
function String(string:String);
function toUpperCase():String;
function toLowerCase():String;
function charAt(index:Number):String;
function charCodeAt(index:Number):Number;
function concat():String;
function indexOf(value:String, startIndex:Number):Number;
function lastIndexOf(value:String, startIndex:Number):Number;
function slice(index1:Number,index2:Number):String;
function substring(index1:Number,index2:Number):String;
function split(delimiter:String):Array;
function substr(index1:Number,index2:Number):String;
function valueOf():String;
static function fromCharCode():String;
var length:Number;
}
|
table lowelabArkinOperonScore
"Arkin operon score"
(
string name; "operon name"
string gene1; "name of gene1"
string gene2; "name og gene2"
float prob; "probability of operon"
float gnMinus; "gene neighbor score"
)
|
package com.example.references
{
public var referencesPackageVar:Number = 3;
} |
package kabam.rotmg.fame {
import kabam.rotmg.fame.control.ShowFameViewCommand;
import kabam.rotmg.fame.control.ShowFameViewSignal;
import kabam.rotmg.fame.model.FameModel;
import kabam.rotmg.fame.service.RequestCharacterFameTask;
import kabam.rotmg.fame.view.FameMediator;
import kabam.rotmg.fame.view.FameView;
import org.swiftsuspenders.Injector;
import robotlegs.bender.extensions.mediatorMap.api.IMediatorMap;
import robotlegs.bender.extensions.signalCommandMap.api.ISignalCommandMap;
import robotlegs.bender.framework.api.IConfig;
public class FameConfig implements IConfig {
public function FameConfig() {
super();
}
[Inject]
public var injector:Injector;
[Inject]
public var mediatorMap:IMediatorMap;
[Inject]
public var commandMap:ISignalCommandMap;
public function configure():void {
this.injector.map(FameModel).asSingleton();
this.injector.map(RequestCharacterFameTask);
this.commandMap.map(ShowFameViewSignal).toCommand(ShowFameViewCommand);
this.mediatorMap.map(FameView).toMediator(FameMediator);
}
}
}
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
function testBranchNull(options:String = null) {
if (options) {
print("has option");
} else {
print("no option");
}
}
testBranchNull();
testBranchNull("something");
|
package nid.xfl.compiler.swf.tags
{
public interface IDisplayListTag extends ITag
{
}
} |
package cmodule.lua_wrapper
{
public const _body:int = regFunc(FSM_body.start);
}
|
package com.arsec.ui.dialog
{
import com.arsec.ui.*;
import com.arsec.system.*;
import flash.display.MovieClip;
import flash.display.BlendMode;
public class PTZMainDialog extends Window
{
private var sldLabel:TextLabel;
public function PTZMainDialog(ow:Object, o:Osd)
{
System.manager.showOsd(false);
super(ow, o, defX, defY, 498, 266, 2, 50, true, true);
body.blendMode = BlendMode.LAYER;
body.alpha = System.DEF_ALPHA;
_osd.setHandler(body);
System.textLine = System.TEXTLINE_LONG; //'long' text lines ON
gadX = defX - 230;
gadY = defY - 102;
_osd.addLabel(gadX, gadY, "Канал", Osd.COLOR_TEXT); gadX += 71; gadY -= 2;
_osd.addListBox(gadX, gadY, 94, new Array("Все", "1", "2", "3", "4"), 0, false, Osd.CMD_INVALID);
_osd.addImage(defX-208, defY-65, "PTZBackground.png");
_osd.addImageButton(defX - 165, defY - 22, "OKNormal.png", "OKActive.png", "OKPrelight.png", Osd.CMD_INVALID);
gadX = defX - 139;
gadY = defY - 59;
_osd.addImageButton(gadX, gadY, "UpNormal.png", "UpActive.png", "UpPrelight.png", Osd.CMD_INVALID); gadY += 124;
_osd.addImageButton(gadX, gadY, "DownNormal.png", "DownActive.png", "DownPrelight.png", Osd.CMD_INVALID);
gadX = defX - 179;
gadY = defY - 42;
_osd.addImageButton(gadX, gadY, "LeftUpNormal.png", "LeftUpActive.png", "LeftUpPrelight.png", Osd.CMD_INVALID); gadX += 78; gadY += 3;
_osd.addImageButton(gadX, gadY, "RightUpNormal.png", "RightUpActive.png", "RightUpPrelight.png", Osd.CMD_INVALID); gadX += 6; gadY += 79;
_osd.addImageButton(gadX, gadY, "RightDownNormal.png", "RightDownActive.png", "RightDownPrelight.png", Osd.CMD_INVALID); gadX -= 88;
_osd.addImageButton(gadX, gadY, "LeftDownNormal.png", "LeftDownActive.png", "LeftDownPrelight.png", Osd.CMD_INVALID); gadX -= 19; gadY -= 43;
_osd.addImageButton(gadX, gadY, "LeftNormal.png", "LeftActive.png", "LeftPrelight.png", Osd.CMD_INVALID); gadX += 124;
_osd.addImageButton(gadX, gadY, "RightNormal.png", "RightActive.png", "RightPrelight.png", Osd.CMD_INVALID);
gadX = defX - 224;
gadY = defY - 52;
_osd.addImageButton(gadX, gadY, "IrisDecNormal.png", "IrisDecActive.png", "IrisDecPrelight.png", Osd.CMD_INVALID, "диафр-"); gadX += 160;
_osd.addImageButton(gadX, gadY, "IrisIncNormal.png", "IrisIncActive.png", "IrisIncPrelight.png", Osd.CMD_INVALID, "диафр+");
gadX = defX - 237;
gadY = defY - 5;
_osd.addImageButton(gadX, gadY, "FocusDecNormal.png", "FocusDecActive.png", "FocusDecPrelight.png", Osd.CMD_INVALID, "фокус-"); gadX += 183;
_osd.addImageButton(gadX, gadY, "FocusIncNormal.png", "FocusIncActive.png", "FocusIncPrelight.png", Osd.CMD_INVALID, "фокус+");
gadX = defX - 225;
gadY = defY + 40;
_osd.addImageButton(gadX, gadY, "ZoomDecNormal.png", "ZoomDecActive.png", "ZoomDecPrelight.png", Osd.CMD_INVALID, "увелич-"); gadX += 160;
_osd.addImageButton(gadX, gadY, "ZoomIncNormal.png", "ZoomIncActive.png", "ZoomIncPrelight.png", Osd.CMD_INVALID, "увелич+");
gadX = defX - 38;
gadY = defY + 97;
_osd.addImage(gadX, gadY, "SpeedInc.png"); gadX -= 190;
_osd.addImage(gadX, gadY, "SpeedDec.png");
gadX = defX - 64;
gadY = defY + 94;
sldLabel = _osd.addLabel(gadX, gadY, "00", Osd.COLOR_TEXT); gadX -= 141; gadY += 10;
_osd.addSlider(gadX, gadY, 137, 3, 1, 32, Osd.CMD_INVALID, 16, sldLabel);
var data:Array = new Array();
for (var i:int = 0; i < 255; i++) data.push(new String(i+1));
gadX = defX + 90;
gadY = defY - 109;
_osd.addLabel(gadX, gadY, "Пресет", Osd.COLOR_TEXT); gadX -= 69; gadY += 30;
_osd.addListBox(gadX, gadY, 198, data, 5); gadX -= 6; gadY += 40;
_osd.addTextButton(gadX, gadY, "Уст", Osd.CMD_INVALID, TextLabel.TYPE_NORMAL, Osd.COLOR_TEXT); gadX += 69;
_osd.addTextButton(gadX, gadY, "Сброс", Osd.CMD_INVALID, TextLabel.TYPE_NORMAL, Osd.COLOR_TEXT); gadX += 80;
_osd.addTextButton(gadX, gadY, "Вызов", Osd.CMD_INVALID, TextLabel.TYPE_NORMAL, Osd.COLOR_TEXT); gadX -= 75; gadY += 35;
_osd.addLabel(gadX, gadY, "Маршрут", Osd.COLOR_TEXT); gadX -= 68; gadY += 30;
_osd.addListBox(gadX, gadY, 198, new Array(" ")).disable(); gadX += 23; gadY += 40;
_osd.addTextButton(gadX, gadY, "Старт", Osd.CMD_INVALID, TextLabel.TYPE_NORMAL, Osd.COLOR_TEXT); gadX += 80;
_osd.addTextButton(gadX, gadY, "Стоп", Osd.CMD_INVALID, TextLabel.TYPE_NORMAL, Osd.COLOR_TEXT); gadX -= 95; gadY += 35;
_osd.addTextButton(gadX, gadY, "Установки маршрута", Osd.CMD_INVALID, TextLabel.TYPE_NORMAL, Osd.COLOR_TEXT);
System.textLine = System.TEXTLINE_NORMAL; //'long' text lines OFF
_osd.setHandler(this);
}
public override function finalize()
{
System.manager.showOsd(true);
super.finalize();
}
public override function pressRight()
{
if (body.visible) super.pressRight(); //implementing standard action for right click, if there is no window above
}
public override function activate(...args):void
{
if (!body.visible) body.visible = true;
super.activate();
}
public override function deactivate(...args):void
{
if (body.visible) body.visible = false;
super.deactivate();
}
public override function osdCommand(cmd:int):void
{
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.skins.ios7
{
import mx.core.DPIClassification;
import spark.skins.ios7.assets.ButtonBarMiddleButton_down;
import spark.skins.ios7.assets.ButtonBarMiddleButton_up;
import spark.skins.mobile.supportClasses.ButtonBarButtonSkinBase;
/**
* iOS7+ specific Button skin base for the Buttons in a ButtonBar.
*
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class IOS7ButtonBarButtonSkinBase extends ButtonBarButtonSkinBase
{
/**
* Class to use for the border in the selected and down state.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
protected var selectedDownBorderSkin:Class;
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function IOS7ButtonBarButtonSkinBase()
{
super();
// set the dimensions to use based on the screen density
switch (applicationDPI)
{
case DPIClassification.DPI_640:
{
measuredDefaultHeight = 116;
measuredDefaultWidth = 400;
break;
}
case DPIClassification.DPI_480:
{
measuredDefaultHeight = 88;
measuredDefaultWidth = 300;
break;
}
case DPIClassification.DPI_320:
{
measuredDefaultHeight = 58;
measuredDefaultWidth = 200;
break;
}
case DPIClassification.DPI_240:
{
measuredDefaultHeight = 44;
measuredDefaultWidth = 150;
break;
}
case DPIClassification.DPI_120:
{
measuredDefaultHeight = 22;
measuredDefaultWidth = 75;
break;
}
default:
{
// default DPI_160
measuredDefaultHeight = 29;
measuredDefaultWidth = 100;
break;
}
}
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
override protected function drawBackground(unscaledWidth:Number, unscaledHeight:Number):void
{
//Dont draw background
}
override protected function getBorderClassForCurrentState():Class
{
var isSelected:Boolean = currentState.indexOf("Selected") >= 0;
var isDown:Boolean = currentState.indexOf("down") >= 0;
if (isSelected && !isDown )
return selectedBorderSkin;
else if (isSelected && isDown)
return selectedDownBorderSkin;
else if (!isSelected && !isDown)
return upBorderSkin;
else
return downBorderSkin;
}
override protected function commitCurrentState():void
{
super.commitCurrentState();
var isSelected:Boolean = currentState.indexOf("Selected") >= 0;
var isDown:Boolean = currentState.indexOf("down") >= 0;
if(xor(isSelected,isDown))
{
var highlightColor:uint = getStyle("highlightTextColor");
labelDisplay.setStyle("color",highlightColor);
}
else
{
var color:uint = getStyle("color");
labelDisplay.setStyle("color",color);
}
}
private function xor(lhs:Boolean, rhs:Boolean):Boolean {
return !( lhs && rhs ) && ( lhs || rhs );
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.components.calendarClasses
{
import spark.collections.OnDemandDataProvider;
import spark.globalization.supportClasses.DateTimeFormatterEx;
[ExcludeClass]
/**
* Helper class for creating a dynamic date range for DateSpinner in DATE_AND_TIME
* mode. Using this class instead of generating all the dates statically avoids
* the cost of applying DateTimeFormatter.format() to every date.
*
* @langversion 3.0
* @playerversion AIR 3
* @productversion Flex 4.6
*/
public class DateAndTimeProvider extends OnDemandDataProvider
{
//----------------------------------------------------------------------------------------------
//
// Class constants
//
//----------------------------------------------------------------------------------------------
// number of milliseconds in a day
private static const MS_IN_DAY:Number = 1000 * 60 * 60 * 24;
// default min/max date
private static const MIN_DATE_DEFAULT:Date = new Date(DateTimeFormatterEx.MIN_YEAR, 0, 1);
private static const MAX_DATE_DEFAULT:Date = new Date(9999, 11, 31, 23, 59, 59, 999);
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Construct a DATE_AND_TIME range for DateSpinner from the start to
* end dates, inclusive. Locale is used to generate the appropriate
* labels.
*
* @langversion 3.0
* @playerversion AIR 3
* @productversion Flex 4.6
*/
public function DateAndTimeProvider(locale:String, start:Date, end:Date,
today:Date = null)
{
if (start == null)
start = MIN_DATE_DEFAULT;
if (end == null)
end = MAX_DATE_DEFAULT;
// we only count days; reset clocks so there are no rounding errors
startDate = new Date(start.time);
endDate = new Date(end.time);
// note: set hours to 11 to avoid being near day boundaries that can
// cause repeat days due to daylight savings time
startDate.hours = 11;
startDate.minutes = 0;
startDate.seconds = 0;
startDate.milliseconds = 0;
endDate.hours = 11;
endDate.minutes = 0;
endDate.seconds = 0;
endDate.milliseconds = 0;
// calculate how many days there are between the two
// +1 because we need to include both start and end dates
_length = ((endDate.time - startDate.time) / MS_IN_DAY) + 1;
formatter = new DateTimeFormatterEx();
if (locale)
formatter.setStyle("locale", locale);
else
formatter.clearStyle("locale");
formatter.dateTimeSkeletonPattern = DateTimeFormatterEx.DATESTYLE_MMMEEEd;
todayDate = today;
}
//----------------------------------------------------------------------------------------------
//
// Variables
//
//----------------------------------------------------------------------------------------------
// start of the date range
private var startDate:Date;
// end of the date range
private var endDate:Date;
private var todayDate:Date;
// formatter to use in localizing the date labels
private var formatter:DateTimeFormatterEx;
//----------------------------------------------------------------------------------------------
//
// Properties
//
//----------------------------------------------------------------------------------------------
//----------------------------------
// length
//----------------------------------
private var _length:int;
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion AIR 3
* @productversion Flex 4.6
*/
override public function get length():int
{
return _length;
}
//----------------------------------------------------------------------------------------------
//
// Overridden Methods
//
//----------------------------------------------------------------------------------------------
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion AIR 3
* @productversion Flex 4.6
*/
override public function getItemAt(index:int, prefetch:int=0):Object
{
// calc date you want from index
var d:Date = new Date(startDate.time + index * MS_IN_DAY);
// generate the appropriate object
var item:Object = { label:formatter.format(d), data:d.time };
if (todayDate)
{
if (d.getFullYear() == todayDate.getFullYear() &&
d.getMonth() == todayDate.getMonth() &&
d.getDate() == todayDate.getDate())
{
item["_emphasized_"] = true;
}
}
return item;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion AIR 3
* @productversion Flex 4.6
*/
override public function getItemIndex(item:Object):int
{
try
{
if (!isNaN(item.data))
{
// set firstDate's hour/min/second to the same values
var dateObj:Date = new Date(item.data);
dateObj.hours = startDate.hours;
dateObj.minutes = startDate.minutes;
dateObj.seconds = startDate.seconds;
dateObj.milliseconds = startDate.milliseconds;
if (dateObj.time >= startDate.time && dateObj.time <= endDate.time)
return Math.round((dateObj.time - startDate.time) / MS_IN_DAY);
}
}
catch(error:Error)
{
}
return -1;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion AIR 3
* @productversion Flex 4.6
*/
override public function toArray():Array
{
var result:Array = [];
var numItems:int = length;
for (var i:int = 0; i < numItems; i++)
result.push(getItemAt(i));
return result;
}
}
} |
package com.media.simpleVideo
{
import com.event.simpleVideo.SimpleVideoEvent;
import com.utils.Log;
import flash.events.AsyncErrorEvent;
import flash.events.ErrorEvent;
import flash.events.IOErrorEvent;
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.external.ExternalInterface;
import flash.media.SoundTransform;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.Timer;
import flash.utils.setTimeout;
[Event(name = "playingProgress", type = "com.events.simpleVideo.SimpleVideoEvent")]
[Event(name = "playComplete", type = "com.events.simpleVideo.SimpleVideoEvent")]
[Event(name = "loadComplete", type = "com.events.simpleVideo.SimpleVideoEvent")]
[Event(name = "gotMetadata", type = "com.events.simpleVideo.SimpleVideoEvent")]
[Event(name = "videoPlayStart", type = "com.events.simpleVideo.SimpleVideoEvent")]
[Event(name = "nsPlayStart", type = "com.events.simpleVideo.SimpleVideoEvent")]
[Event(name = "videoPlayStart", type = "com.events.simpleVideo.SimpleVideoEvent")]
[Event(name = "resumed", type = "com.events.simpleVideo.SimpleVideoEvent")]
[Event(name = "paused", type = "com.events.simpleVideo.SimpleVideoEvent")]
[Event(name = "playing", type = "com.events.simpleVideo.SimpleVideoEvent")]
[Event(name = "bufferFull", type = "com.events.simpleVideo.SimpleVideoEvent")]
[Event(name = "bufferEmpty", type = "com.events.simpleVideo.SimpleVideoEvent")]
/**
* 简单的视频播放类
* @author Lukia Lee
* @version 1.0
* @created 18-三月-2013 14:43:46
*/
public class SimpleVideo extends Video implements ICommonLoader
{
public function SimpleVideo(needReloading:Boolean = false){
super();
_needReloadingVideoAfterPlayComplete = needReloading;
}
private var nc:NetConnection;
protected var ns:NetStream;
private var callbackClient:VideoCallbackClient;
private var playingStatusTimer:Timer;
private var _hasInited:Boolean = false;
public var loadIdx:int;
/**
* 是否在播放完成后停止视频
*/
public var isCloseAfterPlayComplete:Boolean = false;
/**
* 是否报告播放状态,默认为true。如果是false,则playingStatusTimer不要初始化,不主动报告播放进度
*/
public var isReportPlayingStatus:Boolean = true;
private var loadingStatusTimer:Timer;
/**
* 报告当前时间的间隔值。默认为0.5,单位为秒
*/
public var reportStatusInterval:Number = 0.5;
private var _autoPlay:Boolean = true;
private var _loadComplete:Boolean = false;
private var _url:String;
public var isAutoSize:Boolean = false;
private var _isPlaying:Boolean = false;
private var _isVideoPlayStarted:Boolean = false;
public var duration:Number = 0;
public var isStreamStarted:Boolean = false;
public var metaDataInfo:Object;
private var _curLoadedPercent:int = 0;
private var _curLoadedVideoTime:Number = 0;
public static const TIME_DELAY_TO_FINISH:Number = 0.2;// 单位:s
private var _needReloadingVideoAfterPlayComplete:Boolean = false;
public function get autoPlay():Boolean
{
return _autoPlay;
}
public function set autoPlay(value:Boolean):void// 在 VideoLoadEvent.createVideo()里赋值
{
_autoPlay = value;
}
private var _loadedFunc:Function;
/**
* 一般情况下,发现是同样的url值,就不要加载,在特殊情况下也可以设置为false,免除相同值检测
*/
public var isRefuseSameURL:Boolean = true;
private var _isStreamFound:Boolean = false;
private var _bufferTime:Number = 0.8;
public function get bufferTime():Number
{
return _bufferTime;
}
public function set bufferTime(value:Number):void
{
_bufferTime = value;
}
public function get loadedFunc():Function
{
return _loadedFunc;
}
public function set loadedFunc(value:Function):void
{
_loadedFunc = value;
}
public function get isPlaying():Boolean
{
return _isPlaying && _isVideoPlayStarted;
}
public function set isPlaying(value:Boolean):void
{
_isPlaying = value;
// initPlayingStatusTimer();
}
public function get url():String{
return _url;
}
/** 加载视频素材 */
public function set url(value:String):void{
if(!value)return;
if(isRefuseSameURL && value==_url){//如果需要杜绝同样的值,则检查之
return;
}
//EIUtil.logTrace(this+" set url "+_url);
if(value && value!="" ){
_url = value;
if(_url==""){
closeVideo();
}else{
loadVideo();
}
}else{
closeVideo();
}
}
/*public function changeSize(w:Number, h:Number):void{
width = w;
height = h;
dispatchEvent(new CommonControlsEvent(CommonControlsEvent.RESIZE));
}
*/
protected function loadVideo():void{
_loadComplete = false;
_isStreamFound = true;
if(!nc)
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
nc.addEventListener(ErrorEvent.ERROR, errorHandler);
nc.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
nc.connect(null);
if(!ns){
ns = new NetStream(nc);
updateVideoVol();
}
ns.bufferTime=_bufferTime;
ns.checkPolicyFile = true;
ns.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
ns.addEventListener(ErrorEvent.ERROR, errorHandler);
ns.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
ns.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
ns.play(_url);
if(!callbackClient)
callbackClient = new VideoCallbackClient(this);
ns.client = callbackClient;
this.attachNetStream(ns);
initLoadingStatusTimer();
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.LOAD_START, { url: _url}));
CONFIG::debug
{
if(!_hasInited)
{
// Log.info("SimpleVideo.loadVideo() : loadVideo Again!");
Log.info("SimpleVideo.loadVideo() : loadVideo " + loadIdx + " first time! url = " + _url);
}
else
{
Log.info("SimpleVideo.loadVideo() : loadVideo " + loadIdx + " Again! url = " + _url);
}
}
}
private function initLoadingStatusTimer():void{
if(!loadingStatusTimer)
loadingStatusTimer = new Timer(reportStatusInterval*1000, 0);
loadingStatusTimer.start();
loadingStatusTimer.addEventListener(TimerEvent.TIMER, reportLoadingStatus);
}
private function reportLoadingStatus(e:TimerEvent):void{
if(!ns){
return;
}
// var pct:int = int(ns.bytesLoaded/ns.bytesTotal * 100);
_curLoadedPercent = int(ns.bytesLoaded/ns.bytesTotal * 100);
_curLoadedVideoTime = ns.bytesLoaded/ns.bytesTotal * duration;
if(_curLoadedPercent ==100){
_loadComplete = true;
stopLoadingStatusTimer();
if(_isStreamFound){//如果视频文件没找到,也就是服务器返回错误信息,则不要派发加载完成的事件
onLoadComplete();
}
}
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.LOADING_PROGRESS, _curLoadedPercent));
}
private function stopLoadingStatusTimer():void{
if(loadingStatusTimer){
loadingStatusTimer.stop();
loadingStatusTimer.removeEventListener(TimerEvent.TIMER, reportLoadingStatus);
loadingStatusTimer = null;
}
}
public function resumeVideo():void{
Log.info("SimpleVideo.resumeVideo() : ns = " + ns);
if(!ns)
return;
// Log.info("SimpleVideo.resumeVideo() : ");
//ns.seek(ns.time);
ns.resume();
initPlayingStatusTimer();
isPlaying = true;
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.VIDEO_RESUMED));
}
public function pauseVideo():void{
if(ns){
ns.pause();
}else{
}
isPlaying = false;
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.VIDEO_PAUSED));
}
public function closeLoader():void{
//EIUtil.logTrace(this+"closeLoader()");
closeVideo();
}
public function closeVideo():void{
Log.info("SimpleVideo.closeVideo()");
this.volume = 0;
closeNCAndNS();
stopVideo();
this.clear();
if(_needReloadingVideoAfterPlayComplete)
{
setTimeout(function():void
{
// clear();
loadVideo();
}, 500);
}
}
private function closeNCAndNS():void{
if(ns){
//ns.client = this;
ns.close();
ns.removeEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
ns.removeEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
ns.removeEventListener(ErrorEvent.ERROR, errorHandler);
ns.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
ns.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
ns = null;
Log.info("SimpleVideo.closeNCAndNS(): now ns == null!");
}
/*if(callbackClient){
callbackClient.destroy();
callbackClient = null;
}*/
if(nc){
nc.removeEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
nc.removeEventListener(ErrorEvent.ERROR, errorHandler);
nc.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
nc.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
nc.close();
nc = null;
}
}
public function stopVideo():void{
//EIUtil.logTrace(this+" stopVideo()");
isPlaying = false;
_isVideoPlayStarted = false;
stopPlayingStatusTimer();
stopLoadingStatusTimer();
/*seek(0);
if(ns){
ns.pause();
}*/
// setTimeout(this.clear, 500);
// this.clear();
// Log.info("SimpleVideo.stopVideo() : seek(0)");
Log.info("SimpleVideo.stopVideo()");
}
private var _volume:Number;
public function set volume(value:Number):void {
_volume = value;
updateVideoVol();
}
private function updateVideoVol():void {
if(!ns)return;
var st:SoundTransform = ns.soundTransform;
st.volume = _volume;
ns.soundTransform = st;
}
public function get volume():Number {
if(ns)
_volume = ns.soundTransform.volume;
return _volume;
}
private function initPlayingStatusTimer():void{
if(!isReportPlayingStatus)
return;
if(!playingStatusTimer){
reportPlayingStatus();
playingStatusTimer = new Timer(reportStatusInterval*1000, 0);
}
if(!playingStatusTimer.running){
playingStatusTimer.start();
playingStatusTimer.addEventListener(TimerEvent.TIMER, reportPlayingStatus);
}
}
private function stopPlayingStatusTimer():void{
if(playingStatusTimer){
playingStatusTimer.stop();
playingStatusTimer.removeEventListener(TimerEvent.TIMER, reportPlayingStatus);
playingStatusTimer = null;
}
}
private function reportPlayingStatus(e:TimerEvent=null):void{
//if(ns)
//EIUtil.logTrace(this+" reportPlayingStatus() "+ns.time+" duration:"+duration);
if(duration==0)return;
if(ns)
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.PLAYING_PROGRESS, ns.time));
}
private function asyncErrorHandler(event:AsyncErrorEvent):void {
//ignore metadata error message
//trace(this + " asyncErrorHandler->>"+event.text);
}
public function onLoadComplete():void{
//EIUtil.logTrace(this + " onLoadComplete")
CONFIG::debug
{
Log.info("SimpleVideo.onLoadComplete() : video loading " + loadIdx + " complete!" + " _url = " + _url);
}
if(!_hasInited)
{
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.LOAD_COMPLETE, ns.time));
if(_loadedFunc!=null){
_loadedFunc.apply();
}
_hasInited = true;
}
}
/**
* 缓冲中
*
*/
public function onBuffering():void{
//trace(this + " onBuffering");
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.BUFFER_EMPTY));
}
protected function onBufferFull():void{
//trace(this +" onBufferFull");
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.BUFFER_FULL));
}
protected function onBufferFlush():void{
//EIUtil.logTrace(this +" onBufferFlush - isPlaying"+isPlaying);
if(_isPlaying){//如果是正在播放状态,却遇到了Flush的情况,则可能导致异常暂停,所以在此强行继续播放
//EIUtil.logTrace("如果是正在播放状态,却遇到了Flush的情况,则可能导致异常暂停,所以在此强行继续播放");
//resumeVideo();
}
//var delayResume:DelayFuncionCall = new DelayFuncionCall(resumeAfterFlush, 1000);
}
private function resumeAfterFlush():void{
//trace("确保在异常暂停情况下继续播放视频");
}
protected function onResumed():void{
//trace(this +" onResumed");
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.NS_RESUMED));
if(isStreamStarted){
onNSPlayStart();
}
}
/**
* 播放完成后调度
*
*/
public function onPlayComplete():void{
//EIUtil.logTrace(this+" onPlayComplete" +this.ns.time);
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.PLAY_COMPLETE, this.ns.time));
if(isCloseAfterPlayComplete){//如果播放完毕,需要自我销毁,就直接关闭视频,否则只是断开连接,但最后一帧画面不消失
Log.info("SimpleVideo.onPlayComplete() : closeVideo()");
closeVideo();
}else{
Log.info("SimpleVideo.onPlayComplete() : stopVideo()");
stopVideo();
}
// dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.PLAY_COMPLETE, this.ns.time));
}
protected function onNSPlayStart():void{
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.NS_PLAY_START));
}
protected function onVideoPlayStart():void{
if(_isVideoPlayStarted == false){
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.VIDEO_PLAY_START));
_isVideoPlayStarted = true;
// _isPlaying = true;
}
}
/**
*
* @param event
*
*/
private function netStatusHandler(event:NetStatusEvent):void {
//PAPManager.instance().log(this+" netStatusHandler:"+event.info.code)
//if(ns){
//trace("已经加载:" + (ns.bytesLoaded/ns.bytesTotal * 100) + "%");
//trace("bufferLength " + ns.bufferLength +" bufferTime:"+ ns.bufferTime);
//}
trace("simpleVideo.netStatusHandler() : event.info.code = " + event.info.code);
// 顺序依次为:Success --> Start --> Notify --> Full
switch (event.info.code) {
case "NetConnection.Connect.Success":
//connectStream();
break;
case "NetStream.Play.Start":
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.NS_PLAY_START2));
//trace(url+"Start [" + ns.time.toFixed(3) + " seconds] autoPlay"+autoPlay);
onReadyToPlay();
if(autoPlay==false ){
pauseVideo();
}else{
isPlaying = true;
onNSPlayStart();
}
isStreamStarted = true;
break;
case "NetStream.Play.Stop":
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.PLAY_COMPLETE2));
// //EIUtil.logTrace("Stop [" + ns.time.toFixed(3) + " seconds]");
// //isPlaying = false;
onPlayComplete();
if(ExternalInterface.available)
{
try
{
ExternalInterface.call("console.log", "SimpleVideo.netStatusHandler(): NetStream.Play.Stop!");
}
catch(error:Error)
{
}
}
/*setTimeout(function():void{
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.PLAY_COMPLETE2));
onPlayComplete();
}, TIME_DELAY_TO_FINISH * 1000);*/
break;
case "NetStream.Play.Complete":
isPlaying = false;
_isVideoPlayStarted = false;
break;
case "NetStream.Unpause.Notify":
onResumed();
break;
case "NetStream.Seek.Notify":
_isVideoPlayStarted = false;
break;
case "NetStream.SeekStart.Notify":
break;
case "NetStream.Buffer.Flush":
// onVideoPlayStart();
//数据已完成流式加载,并且剩余缓冲区被清空。
//onBufferFlush();
break;
case "NetStream.Buffer.Empty":
onBuffering();//缓冲状态
onPlayComplete();
break;
case "NetStream.Buffer.Full":
dispatchEvent(new SimpleVideoEvent(SimpleVideoEvent.BUFFER_FULL2));
if(_isPlaying)
onVideoPlayStart();
//缓冲区已满,流开始播放。
onBufferFull();
break;
case "NetStream.Play.StreamNotFound":
if(ExternalInterface.available)
{
try
{
ExternalInterface.call("console.log", "SimpleVideo.netStatusHandler(): NetStream.Play.StreamNotFound!");
}
catch(error:Error)
{
}
}
ioErrorHandler();
break;
}
}
protected function errorHandler(event:ErrorEvent = null):void
{
// TODO Auto-generated method stub
Log.info("SimpleVideo.onErrorHandler() : " + event);
}
protected function ioErrorHandler(event:IOErrorEvent = null):void {
_isStreamFound = false;
//trace("Unable to locate video: " + _url);
Log.info("SimpleVideo.ioErrorHandler() : Unable to locate video: " + _url);
}
protected function securityErrorHandler(event:SecurityErrorEvent = null):void {
//trace("securityErrorHandler: " + event);
Log.info("SimpleVideo.securityErrorHandler() : Unable to locate video: " + _url);
}
public function get currentTime():Number{
if(ns)
return ns.time;
else
return 0;
}
protected function onReadyToPlay():void{
}
public function replay():void{
// seek(0);
Log.info("SimpleVideo.replay() : ns.time = " + ns.time);
resumeVideo();
// playVideo();
}
public function seek(offset:Number, needPlay:Boolean = true):void{
trace(this+" seek()"+offset);
if(ns)
{
ns.seek(offset);
// ns.play2();
if(needPlay)
{
ns.resume();
}
}
}
/** 当前已经加载到的视频流的时长 */
public function get curLoadedVideoTime():Number
{
return _curLoadedVideoTime;
}
/** 当前已经加载的视频流的百分比 */
public function get curLoadedPercent():int
{
return _curLoadedPercent;
}
public function get loadComplete():Boolean
{
return _loadComplete;
}
public function get hasInited():Boolean
{
return _hasInited;
}
}
} |
package com.smbc.enemies
{
import com.smbc.data.EnemyInfo;
import com.smbc.data.HealthValue;
import com.smbc.data.ScoreValue;
import com.smbc.level.FlyingCheepSpawner;
public class CheepFlying extends CheepFast
{
public static const ENEMY_NUM:int = EnemyInfo.CheepFlying;
public function CheepFlying(fLab:String, flyingCheepSpawner:FlyingCheepSpawner=null)
{
super(fLab, flyingCheepSpawner);
}
override protected function overwriteInitialStats():void
{
super.overwriteInitialStats();
_health = HealthValue.CHEEP_FLYING;
scoreAttack = ScoreValue.CHEEP_ATTACK;
scoreBelow = ScoreValue.CHEEP_BELOW;
scoreStar = ScoreValue.CHEEP_STAR;
scoreStomp = ScoreValue.CHEEP_STOMP;
}
}
} |
import org.caleb.movieclip.ObservableMovieClip;
import org.caleb.animation.AnimationManager;
import org.caleb.event.Event;
import org.caleb.components.slider.HorizontalScrollThumb;
import org.caleb.state.ILockable;
class org.caleb.components.slider.PercentageSlider extends org.caleb.movieclip.ObservableMovieClip implements ILockable
{
public static var SymbolName:String = '__Packages.org.caleb.components.slider.PercentageSlider';
public static var SymbolLinked = Object.registerClass(SymbolName, PercentageSlider);
public var slider_mc:HorizontalScrollThumb;
public var slidebar_mc:MovieClip;
private var $slider_tw:AnimationManager;
private var $zoom_out_mc:MovieClip;
private var $zoom_in_mc:MovieClip;
private var $slide_si:Number;
private var $w:Number;
private var $h:Number;
private var $e:Event;
public function PercentageSlider() {this.setClassDescription('org.caleb.components.slider.PercentageSlider');}
public function init()
{
//trace('init invoked')
this.$e = new org.caleb.event.Event();
if(this.slidebar_mc == undefined)
{
if(this.$w == undefined && this.$h == undefined)
{
this.slidebar_mc = org.caleb.util.DrawingUtil.drawRectangle(this, 500, 15, 0, 0, 0, 0x990099, 0x999999);
}
else
{
this.slidebar_mc = org.caleb.util.DrawingUtil.drawRectangle(this, this.$w, this.$h, 0, 0, 0, 0x990099, 0x999999);
}
}
if(this.slider_mc == undefined)
{
this.slider_mc = HorizontalScrollThumb(this.attachMovie(HorizontalScrollThumb.SymbolName, 'slider_mc', this.getNextHighestDepth()));
}
this.$initButtons();
if (this.isLocked()) {
this.unlock();
}
}
public function get scrollpos():Number
{
var tot = (this.slidebar_mc._width - this.slider_mc._width);
var per = (this.slider_mc._x - this.slidebar_mc._x) / tot;
//trace('scrollpos: ' + per)
return per;
}
public function set scrollpos(per:Number)
{
var tot = this.slidebar_mc._width - this.slider_mc._width + this.slidebar_mc._x;
this.slider_mc._x = tot * per;
this.$e.setType('onSliderProceduralUpdate');
var tot = (this.slidebar_mc._width - this.slider_mc._width);
var per = (this.slider_mc._x - this.slidebar_mc._x) / tot;
this.$e.addArgument('per', per);
this.dispatchEvent($e);
}
public function set scrollX(x:Number)
{
this.slider_mc._x = x;
this.$e.setType('onSliderProceduralUpdate');
var tot = (this.slidebar_mc._width - this.slider_mc._width);
var per = (this.slider_mc._x - this.slidebar_mc._x) / tot;
this.$e.addArgument('per', per);
this.dispatchEvent($e);
}
public function watchSlide() {
this.$e.setType('onSliderUpdate');
var tot = (this.slidebar_mc._width - this.slider_mc._width);
var per = (this.slider_mc._x - this.slidebar_mc._x) / tot;
this.$e.addArgument('per', per);
this.dispatchEvent($e);
}
private function $initButtons() {
this.slider_mc.thumbwidth = this.slidebar_mc._width;
this.slider_mc.init();
if (this.$slider_tw == undefined) {
this.$slider_tw = new AnimationManager(this.slider_mc);
}
this.$zoom_in_mc.onPress = function() {
this._parent.slider_mc.onEnterFrame = function() {
this._x += 5;
}
}
this.$zoom_in_mc.onRelease = this.$zoom_in_mc.onReleaseOutside = function() {
this._parent.slider_mc.onEnterFrame = undefined;
this._parent.slider_mc.onRelease();
}
this.$zoom_out_mc.onPress = function() {
this._parent.slider_mc.onEnterFrame = function() {
this._x -= 5;
}
}
this.$zoom_out_mc.onRelease = this.$zoom_out_mc.onReleaseOutside = function() {
this._parent.slider_mc.onEnterFrame = undefined;
this._parent.slider_mc.onRelease();
}
this.slidebar_mc.onRelease = function()
{
this._parent.scrollpos = this._parent._xmouse / this._parent.slidebar_mc._width;
this._parent.slider_mc.onRelease();
};
}
//Sets the scroll width of the scroll bar.
public function set total(arg:Number) {
var per = 1 / arg;
var w = per * this.slidebar_mc._width;
this.$slider_tw.tween('thumbwidth', w, .5);
}
public function lock():Void {
//slider should now move in accordance with the zoomLevel via setX
this.enabled = false;
}
public function unlock():Void {
this.enabled = true;
}
public function isLocked():Boolean {
return this.enabled;
}
public function set w(arg:Number):Void
{
this.$w = arg;
}
public function set h(arg:Number):Void
{
this.$h = arg;
}
} |
package punk.transition.effects
{
import flash.display.*;
import flash.geom.Rectangle;
import net.flashpunk.*;
import net.flashpunk.graphics.*;
import punk.transition.Transition;
import punk.transition.util.Drawing;
/**
* @author GIT: cjke
* @author Mail: cjke.7777@gmail.com
*/
public class Star extends Effect
{
protected var _color:uint = 0xFF000000;
protected var _distance:Number;
protected var _duration:Number = 1;
protected var _graphic:Image;
protected var _r:Rectangle;
protected var _scale:Number;
protected var _starBm:BitmapData;
protected var _startX:Number = FP.halfWidth;
protected var _startY:Number = FP.halfHeight;
protected var _tempSprite:Sprite = new Sprite();
protected var _track:String = "";
protected var _offset:Boolean = true;
public function Star(options:Object = null)
{
super();
if (options) {
if (options.hasOwnProperty("color")) _color = options.color;
if (options.hasOwnProperty("duration")) _duration = options.duration;
if (options.hasOwnProperty("startX")) _startX = options.startX;
if (options.hasOwnProperty("startY")) _startY = options.startY;
if (options.hasOwnProperty("track")) _track = options.track;
if (options.hasOwnProperty("offset")) _offset = options.offset;
}
// Find the longest distance from the start to any corner,
// used to track if the animation is done
var distances:Array = [
FP.distance(_startX, _startY, 0, 0),
FP.distance(_startX, _startY, FP.width, 0),
FP.distance(_startX, _startY, FP.width, FP.height),
FP.distance(_startX, _startY, 0, FP.height)
];
distances.sort();
_distance = distances[distances.length-1];
// Image Data
_r = new Rectangle(0, 0, FP.width, FP.height);
_starBm = new BitmapData(FP.width, FP.height, true, 0xFF003300);
_graphic = new Image(_starBm);
graphic = _graphic;
}
override public function render():void
{
_tempSprite.graphics.clear();
// Draw Star
_tempSprite.graphics.beginFill(0xFF0000, 1);
if(FP.world.hasOwnProperty(_track))
{
if(_offset)
{
Drawing.drawStar(_tempSprite.graphics, FP.world[_track].x - FP.camera.x, FP.world[_track].y - FP.camera.y, _scale, _scale*2);
}
else
{
Drawing.drawStar(_tempSprite.graphics, FP.world[_track].x, FP.world[_track].y, _scale, _scale*2);
}
}
else
{
Drawing.drawStar(_tempSprite.graphics, _startX, _startY, _scale, _scale*2);
}
// Draw bg
_starBm.fillRect(_r, _color);
_starBm.draw(_tempSprite, null, null, BlendMode.ERASE);
_graphic.updateBuffer();
super.render();
}
}
} |
package kabam.rotmg.ui.view {
import com.company.assembleegameclient.objects.ImageFactory;
import com.company.assembleegameclient.objects.Player;
import com.company.assembleegameclient.parameters.Parameters;
import com.company.assembleegameclient.ui.BoostPanelButton;
import com.company.assembleegameclient.ui.ExperienceBoostTimerPopup;
import com.company.assembleegameclient.ui.icons.IconButton;
import com.company.assembleegameclient.ui.icons.IconButtonFactory;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.filters.DropShadowFilter;
import kabam.rotmg.text.model.TextKey;
import kabam.rotmg.text.view.TextFieldDisplayConcrete;
import kabam.rotmg.text.view.stringBuilder.StaticStringBuilder;
import org.osflash.signals.Signal;
import org.osflash.signals.natives.NativeSignal;
public class CharacterDetailsView extends Sprite {
private var portrait_:Bitmap;
private var button:IconButton;
private var nameText_:TextFieldDisplayConcrete;
public function CharacterDetailsView() {
this.portrait_ = new Bitmap(null);
this.nameText_ = new TextFieldDisplayConcrete().setSize(20).setColor(0xB3B3B3);
super();
}
public function init(_arg_1:String, _arg_2:String):void {
this.createPortrait();
this.createNameText(_arg_1);
}
private function createPortrait():void {
this.portrait_.x = -2;
this.portrait_.y = -8;
addChild(this.portrait_);
}
private function createNameText(_arg_1:String):void {
this.nameText_.setBold(true);
this.nameText_.x = 36;
this.nameText_.y = 3;
this.nameText_.filters = [new DropShadowFilter(0, 0, 0)];
this.setName(_arg_1);
addChild(this.nameText_);
}
public function update(_arg_1:Player):void {
this.portrait_.bitmapData = _arg_1.getPortrait();
}
public function setName(_arg_1:String):void {
var fakename:String = Parameters.data_.fakeName;
if (fakename != null) {
_arg_1 = fakename;
}
this.nameText_.setStringBuilder(new StaticStringBuilder(_arg_1));
}
}
}//package kabam.rotmg.ui.view
|
package core {
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
/**
* ...
* @author notSafeForDev
*/
public class TPStage {
private static var _stage : Stage;
private static var focusedInputTextField : TextField;
public static function init(_object : DisplayObject, _frameRate : Number) : void {
_stage = _object.stage;
_stage.frameRate = _frameRate;
_stage.addEventListener(MouseEvent.CLICK, onStageClick);
}
public static function get stageWidth() : Number {
return _stage.stageWidth;
}
public static function get stageHeight() : Number {
return _stage.stageHeight;
}
public static function get mouseX() : Number {
return _stage.mouseX;
}
public static function get mouseY() : Number {
return _stage.mouseY;
}
public static function get frameRate() : Number {
return _stage.frameRate;
}
public static function set frameRate(_value : Number) : void {
_stage.frameRate = _value;
}
public static function get quality() : String {
return _stage.quality;
}
public static function set quality(_value : String) : void {
_stage.quality = _value;
}
public static function get stage() : Stage {
return _stage;
}
public static function hasFocusedInputTextField() : Boolean {
return focusedInputTextField != null;
}
private static function onStageClick(e : MouseEvent) : void {
if (e.target is TextField) {
var textField : TextField = e.target as TextField;
if (textField.type == "input") {
focusedInputTextField = textField;
return;
}
}
focusedInputTextField = null;
}
}
} |
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
package spine.animation {
import spine.Bone;
import spine.Event;
import spine.MathUtils;
import spine.Pool;
import spine.Skeleton;
import flash.utils.Dictionary;
import spine.Slot;
public class AnimationState {
public static var SUBSEQUENT : int = 0;
public static var FIRST : int = 1;
public static var HOLD_SUBSEQUENT : int = 2;
public static var HOLD_FIRST : int = 3;
public static var HOLD_MIX : int = 4;
public static var SETUP : int = 1;
public static var CURRENT : int = 2;
internal static var emptyAnimation : Animation = new Animation("<empty>", new Vector.<Timeline>(), 0);
public var data : AnimationStateData;
public var tracks : Vector.<TrackEntry> = new Vector.<TrackEntry>();
internal var events : Vector.<Event> = new Vector.<Event>();
public var onStart : Listeners = new Listeners();
public var onInterrupt : Listeners = new Listeners();
public var onEnd : Listeners = new Listeners();
public var onDispose : Listeners = new Listeners();
public var onComplete : Listeners = new Listeners();
public var onEvent : Listeners = new Listeners();
internal var queue : EventQueue;
internal var propertyIDs : Dictionary = new Dictionary();
internal var mixingTo : Vector.<TrackEntry> = new Vector.<TrackEntry>();
internal var animationsChanged : Boolean;
public var timeScale : Number = 1;
internal var trackEntryPool : Pool;
internal var unkeyedState : int = 0;
public function AnimationState(data : AnimationStateData) {
if (data == null) throw new ArgumentError("data can not be null");
this.data = data;
this.queue = new EventQueue(this);
this.trackEntryPool = new Pool(function() : Object {
return new TrackEntry();
});
}
public function update(delta : Number) : void {
delta *= timeScale;
for (var i : int = 0, n : int = tracks.length; i < n; i++) {
var current : TrackEntry = tracks[i];
if (current == null) continue;
current.animationLast = current.nextAnimationLast;
current.trackLast = current.nextTrackLast;
var currentDelta : Number = delta * current.timeScale;
if (current.delay > 0) {
current.delay -= currentDelta;
if (current.delay > 0) continue;
currentDelta = -current.delay;
current.delay = 0;
}
var next : TrackEntry = current.next;
if (next != null) {
// When the next entry's delay is passed, change to the next entry, preserving leftover time.
var nextTime : Number = current.trackLast - next.delay;
if (nextTime >= 0) {
next.delay = 0;
next.trackTime += current.timeScale == 0 ? 0 : (nextTime / current.timeScale + delta) * next.timeScale;
current.trackTime += currentDelta;
setCurrent(i, next, true);
while (next.mixingFrom != null) {
next.mixTime += delta;
next = next.mixingFrom;
}
continue;
}
} else {
// Clear the track when there is no next entry, the track end time is reached, and there is no mixingFrom.
if (current.trackLast >= current.trackEnd && current.mixingFrom == null) {
tracks[i] = null;
queue.end(current);
disposeNext(current);
continue;
}
}
if (current.mixingFrom != null && updateMixingFrom(current, delta)) {
// End mixing from entries once all have completed.
var from : TrackEntry = current.mixingFrom;
current.mixingFrom = null;
if (from != null) from.mixingTo = null;
while (from != null) {
queue.end(from);
from = from.mixingFrom;
}
}
current.trackTime += currentDelta;
}
queue.drain();
}
private function updateMixingFrom(to : TrackEntry, delta : Number) : Boolean {
var from : TrackEntry = to.mixingFrom;
if (from == null) return true;
var finished : Boolean = updateMixingFrom(from, delta);
from.animationLast = from.nextAnimationLast;
from.trackLast = from.nextTrackLast;
// Require mixTime > 0 to ensure the mixing from entry was applied at least once.
if (to.mixTime > 0 && to.mixTime >= to.mixDuration) {
// Require totalAlpha == 0 to ensure mixing is complete, unless mixDuration == 0 (the transition is a single frame).
if (from.totalAlpha == 0 || to.mixDuration == 0) {
to.mixingFrom = from.mixingFrom;
if (from.mixingFrom != null) from.mixingFrom.mixingTo = to;
to.interruptAlpha = from.interruptAlpha;
queue.end(from);
}
return finished;
}
from.trackTime += delta * from.timeScale;
to.mixTime += delta;
return false;
}
public function apply(skeleton : Skeleton) : Boolean {
if (skeleton == null) throw new ArgumentError("skeleton cannot be null.");
if (animationsChanged) _animationsChanged();
var events : Vector.<Event> = this.events;
var applied : Boolean = false;
for (var i : int = 0, n : int = tracks.length; i < n; i++) {
var current : TrackEntry = tracks[i];
if (current == null || current.delay > 0) continue;
applied = true;
var blend : MixBlend = i == 0 ? MixBlend.first : current.mixBlend;
// Apply mixing from entries first.
var mix : Number = current.alpha;
if (current.mixingFrom != null)
mix *= applyMixingFrom(current, skeleton, blend);
else if (current.trackTime >= current.trackEnd && current.next == null)
mix = 0;
// Apply current entry.
var animationLast : Number = current.animationLast, animationTime : Number = current.getAnimationTime();
var timelineCount : int = current.animation.timelines.length;
var timelines : Vector.<Timeline> = current.animation.timelines;
var ii : int = 0;
if ((i == 0 && mix == 1) || blend == MixBlend.add) {
for (ii = 0; ii < timelineCount; ii++) {
var timeline : Timeline = timelines[ii];
if (timeline is AttachmentTimeline) {
applyAttachmentTimeline(AttachmentTimeline(timeline), skeleton, animationTime, blend, true);
} else {
timeline.apply(skeleton, animationLast, animationTime, events, mix, blend, MixDirection.In);
}
}
} else {
var timelineMode : Vector.<int> = current.timelineMode;
var firstFrame : Boolean = current.timelinesRotation.length == 0;
if (firstFrame) current.timelinesRotation.length = timelineCount << 1;
var timelinesRotation : Vector.<Number> = current.timelinesRotation;
for (ii = 0; ii < timelineCount; ii++) {
var timeline : Timeline = timelines[ii];
var timelineBlend : MixBlend = timelineMode[ii] == SUBSEQUENT ? blend : MixBlend.setup;
if (timeline is RotateTimeline) {
applyRotateTimeline(timeline, skeleton, animationTime, mix, timelineBlend, timelinesRotation, ii << 1, firstFrame);
} else if (timeline is AttachmentTimeline) {
applyAttachmentTimeline(AttachmentTimeline(timeline), skeleton, animationTime, timelineBlend, true);
} else
timeline.apply(skeleton, animationLast, animationTime, events, mix, timelineBlend, MixDirection.In);
}
}
queueEvents(current, animationTime);
events.length = 0;
current.nextAnimationLast = animationTime;
current.nextTrackLast = current.trackTime;
}
// Set slots attachments to the setup pose, if needed. This occurs if an animation that is mixing out sets attachments so
// subsequent timelines see any deform, but the subsequent timelines don't set an attachment (eg they are also mixing out or
// the time is before the first key).
var setupState : int = unkeyedState + SETUP;
var slots : Vector.<Slot> = skeleton.slots;
for (var i : int = 0, n : int = skeleton.slots.length; i < n; i++) {
var slot : Slot = slots[i];
if (slot.attachmentState == setupState) {
var attachmentName : String = slot.data.attachmentName;
slot.attachment = (attachmentName == null ? null : skeleton.getAttachmentForSlotIndex(slot.data.index, attachmentName));
}
}
this.unkeyedState += 2; // Increasing after each use avoids the need to reset attachmentState for every slot.
queue.drain();
return applied;
}
private function applyMixingFrom(to : TrackEntry, skeleton : Skeleton, blend : MixBlend) : Number {
var from : TrackEntry = to.mixingFrom;
if (from.mixingFrom != null) applyMixingFrom(from, skeleton, blend);
var mix : Number = 0;
if (to.mixDuration == 0) { // Single frame mix to undo mixingFrom changes.
mix = 1;
if (blend == MixBlend.first) blend = MixBlend.setup;
} else {
mix = to.mixTime / to.mixDuration;
if (mix > 1) mix = 1;
if (blend != MixBlend.first) blend = from.mixBlend;
}
var events : Vector.<Event> = mix < from.eventThreshold ? this.events : null;
var attachments : Boolean = mix < from.attachmentThreshold, drawOrder : Boolean = mix < from.drawOrderThreshold;
var animationLast : Number = from.animationLast, animationTime : Number = from.getAnimationTime();
var timelineCount : int = from.animation.timelines.length;
var timelines : Vector.<Timeline> = from.animation.timelines;
var alphaHold : Number = from.alpha * to.interruptAlpha;
var alphaMix : Number = alphaHold * (1 - mix);
var i : int = 0;
if (blend == MixBlend.add) {
for (i = 0; i < timelineCount; i++)
timelines[i].apply(skeleton, animationLast, animationTime, events, alphaMix, blend, MixDirection.Out);
} else {
var timelineMode : Vector.<int> = from.timelineMode;
var timelineHoldMix : Vector.<TrackEntry> = from.timelineHoldMix;
var firstFrame : Boolean = from.timelinesRotation.length == 0;
if (firstFrame) from.timelinesRotation.length = timelineCount << 1;
var timelinesRotation : Vector.<Number> = from.timelinesRotation;
from.totalAlpha = 0;
for (i = 0; i < timelineCount; i++) {
var timeline : Timeline = timelines[i];
var direction : MixDirection = MixDirection.Out;
var timelineBlend: MixBlend;
var alpha : Number = 0;
switch (timelineMode[i]) {
case SUBSEQUENT:
if (!drawOrder && timeline is DrawOrderTimeline) continue;
timelineBlend = blend;
alpha = alphaMix;
break;
case FIRST:
timelineBlend = MixBlend.setup;
alpha = alphaMix;
break;
case HOLD_SUBSEQUENT:
timelineBlend = blend;
alpha = alphaHold;
break;
case HOLD_FIRST:
timelineBlend = MixBlend.setup;
alpha = alphaHold;
break;
default:
timelineBlend = MixBlend.setup;
var holdMix : TrackEntry = timelineHoldMix[i];
alpha = alphaHold * Math.max(0, 1 - holdMix.mixTime / holdMix.mixDuration);
break;
}
from.totalAlpha += alpha;
if (timeline is RotateTimeline)
applyRotateTimeline(timeline, skeleton, animationTime, alpha, timelineBlend, timelinesRotation, i << 1, firstFrame);
else if (timeline is AttachmentTimeline) {
applyAttachmentTimeline(AttachmentTimeline(timeline), skeleton, animationTime, timelineBlend, attachments);
} else {
if (drawOrder && timeline is DrawOrderTimeline && timelineBlend == MixBlend.setup) direction = MixDirection.In;
timeline.apply(skeleton, animationLast, animationTime, events, alpha, timelineBlend, direction);
}
}
}
if (to.mixDuration > 0) queueEvents(from, animationTime);
this.events.length = 0;
from.nextAnimationLast = animationTime;
from.nextTrackLast = from.trackTime;
return mix;
}
private function applyAttachmentTimeline (timeline: AttachmentTimeline, skeleton: Skeleton, time: Number, blend: MixBlend, attachments: Boolean) : void {
var slot : Slot = skeleton.slots[timeline.slotIndex];
if (!slot.bone.active) return;
var frames : Vector.<Number> = timeline.frames;
if (time < frames[0]) { // Time is before first frame.
if (blend == MixBlend.setup || blend == MixBlend.first)
setAttachment(skeleton, slot, slot.data.attachmentName, attachments);
}
else {
var frameIndex : Number;
if (time >= frames[frames.length - 1]) // Time is after last frame.
frameIndex = frames.length - 1;
else
frameIndex = Animation.binarySearch1(frames, time) - 1;
setAttachment(skeleton, slot, timeline.attachmentNames[frameIndex], attachments);
}
// If an attachment wasn't set (ie before the first frame or attachments is false), set the setup attachment later.
if (slot.attachmentState <= unkeyedState) slot.attachmentState = unkeyedState + SETUP;
}
private function setAttachment (skeleton: Skeleton, slot: Slot, attachmentName: String, attachments: Boolean) : void {
slot.attachment = attachmentName == null ? null : skeleton.getAttachmentForSlotIndex(slot.data.index, attachmentName);
if (attachments) slot.attachmentState = unkeyedState + CURRENT;
}
private function applyRotateTimeline(timeline : Timeline, skeleton : Skeleton, time : Number, alpha : Number, blend : MixBlend, timelinesRotation : Vector.<Number>, i : int, firstFrame : Boolean) : void {
if (firstFrame) timelinesRotation[i] = 0;
if (alpha == 1) {
timeline.apply(skeleton, 0, time, null, 1, blend, MixDirection.In);
return;
}
var rotateTimeline : RotateTimeline = RotateTimeline(timeline);
var frames : Vector.<Number> = rotateTimeline.frames;
var bone : Bone = skeleton.bones[rotateTimeline.boneIndex];
if (!bone.active) return;
var r1 : Number, r2 : Number;
if (time < frames[0]) {
switch (blend) {
case MixBlend.setup:
bone.rotation = bone.data.rotation;
default:
return;
case MixBlend.first:
r1 = bone.rotation;
r2 = bone.data.rotation;
}
} else {
r1 = blend == MixBlend.setup ? bone.data.rotation : bone.rotation;
if (time >= frames[frames.length - RotateTimeline.ENTRIES]) // Time is after last frame.
r2 = bone.data.rotation + frames[frames.length + RotateTimeline.PREV_ROTATION];
else {
// Interpolate between the previous frame and the current frame.
var frame : int = Animation.binarySearch(frames, time, RotateTimeline.ENTRIES);
var prevRotation : Number = frames[frame + RotateTimeline.PREV_ROTATION];
var frameTime : Number = frames[frame];
var percent : Number = rotateTimeline.getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + RotateTimeline.PREV_TIME] - frameTime));
r2 = frames[frame + RotateTimeline.ROTATION] - prevRotation;
r2 -= (16384 - int((16384.499999999996 - r2 / 360))) * 360;
r2 = prevRotation + r2 * percent + bone.data.rotation;
r2 -= (16384 - int((16384.499999999996 - r2 / 360))) * 360;
}
}
// Mix between rotations using the direction of the shortest route on the first frame while detecting crosses.
var total : Number, diff : Number = r2 - r1;
diff -= (16384 - int((16384.499999999996 - diff / 360))) * 360;
if (diff == 0) {
total = timelinesRotation[i];
} else {
var lastTotal : Number, lastDiff : Number;
if (firstFrame) {
lastTotal = 0;
lastDiff = diff;
} else {
lastTotal = timelinesRotation[i]; // Angle and direction of mix, including loops.
lastDiff = timelinesRotation[i + 1]; // Difference between bones.
}
var current : Boolean = diff > 0, dir : Boolean = lastTotal >= 0;
// Detect cross at 0 (not 180).
if (MathUtils.signum(lastDiff) != MathUtils.signum(diff) && Math.abs(lastDiff) <= 90) {
// A cross after a 360 rotation is a loop.
if (Math.abs(lastTotal) > 180) lastTotal += 360 * MathUtils.signum(lastTotal);
dir = current;
}
total = diff + lastTotal - lastTotal % 360; // Store loops as part of lastTotal.
if (dir != current) total += 360 * MathUtils.signum(lastTotal);
timelinesRotation[i] = total;
}
timelinesRotation[i + 1] = diff;
r1 += total * alpha;
bone.rotation = r1 - (16384 - int((16384.499999999996 - r1 / 360))) * 360;
}
private function queueEvents(entry : TrackEntry, animationTime : Number) : void {
var animationStart : Number = entry.animationStart, animationEnd : Number = entry.animationEnd;
var duration : Number = animationEnd - animationStart;
var trackLastWrapped : Number = entry.trackLast % duration;
// Queue events before complete.
var events : Vector.<Event> = this.events;
var event : Event;
var i : int = 0, n : int = events.length;
for (; i < n; i++) {
event = events[i];
if (event.time < trackLastWrapped) break;
if (event.time > animationEnd) continue; // Discard events outside animation start/end.
queue.event(entry, event);
}
// Queue complete if completed a loop iteration or the animation.
var complete:Boolean;
if (entry.loop)
complete = duration == 0 || trackLastWrapped > entry.trackTime % duration;
else
complete = animationTime >= animationEnd && entry.animationLast < animationEnd;
if (complete) queue.complete(entry);
// Queue events after complete.
for (; i < n; i++) {
event = events[i];
if (event.time < animationStart) continue; // Discard events outside animation start/end.
queue.event(entry, events[i]);
}
}
public function clearTracks() : void {
var oldTrainDisabled : Boolean = queue.drainDisabled;
queue.drainDisabled = true;
for (var i : int = 0, n : int = tracks.length; i < n; i++)
clearTrack(i);
tracks.length = 0;
queue.drainDisabled = oldTrainDisabled;
queue.drain();
}
public function clearTrack(trackIndex : int) : void {
if (trackIndex >= tracks.length) return;
var current : TrackEntry = tracks[trackIndex];
if (current == null) return;
queue.end(current);
disposeNext(current);
var entry : TrackEntry = current;
while (true) {
var from : TrackEntry = entry.mixingFrom;
if (from == null) break;
queue.end(from);
entry.mixingFrom = null;
entry.mixingTo = null;
entry = from;
}
tracks[current.trackIndex] = null;
queue.drain();
}
private function setCurrent(index : int, current : TrackEntry, interrupt : Boolean) : void {
var from : TrackEntry = expandToIndex(index);
tracks[index] = current;
if (from != null) {
if (interrupt) queue.interrupt(from);
current.mixingFrom = from;
from.mixingTo = current;
current.mixTime = 0;
// Store the interrupted mix percentage.
if (from.mixingFrom != null && from.mixDuration > 0)
current.interruptAlpha *= Math.min(1, from.mixTime / from.mixDuration);
from.timelinesRotation.length = 0; // Reset rotation for mixing out, in case entry was mixed in.
}
queue.start(current);
}
public function setAnimationByName(trackIndex : int, animationName : String, loop : Boolean) : TrackEntry {
var animation : Animation = data.skeletonData.findAnimation(animationName);
if (animation == null) throw new ArgumentError("Animation not found: " + animationName);
return setAnimation(trackIndex, animation, loop);
}
public function setAnimation(trackIndex : int, animation : Animation, loop : Boolean) : TrackEntry {
if (animation == null) throw new ArgumentError("animation cannot be null.");
var interrupt : Boolean = true;
var current : TrackEntry = expandToIndex(trackIndex);
if (current != null) {
if (current.nextTrackLast == -1) {
// Don't mix from an entry that was never applied.
tracks[trackIndex] = current.mixingFrom;
queue.interrupt(current);
queue.end(current);
disposeNext(current);
current = current.mixingFrom;
interrupt = false;
} else
disposeNext(current);
}
var entry : TrackEntry = trackEntry(trackIndex, animation, loop, current);
setCurrent(trackIndex, entry, interrupt);
queue.drain();
return entry;
}
public function addAnimationByName(trackIndex : int, animationName : String, loop : Boolean, delay : Number) : TrackEntry {
var animation : Animation = data.skeletonData.findAnimation(animationName);
if (animation == null) throw new ArgumentError("Animation not found: " + animationName);
return addAnimation(trackIndex, animation, loop, delay);
}
public function addAnimation(trackIndex : int, animation : Animation, loop : Boolean, delay : Number) : TrackEntry {
if (animation == null) throw new ArgumentError("animation cannot be null.");
var last : TrackEntry = expandToIndex(trackIndex);
if (last != null) {
while (last.next != null)
last = last.next;
}
var entry : TrackEntry = trackEntry(trackIndex, animation, loop, last);
if (last == null) {
setCurrent(trackIndex, entry, true);
queue.drain();
} else {
last.next = entry;
if (delay <= 0) {
var duration : Number = last.animationEnd - last.animationStart;
if (duration != 0) {
if (last.loop)
delay += duration * (1 + (int)(last.trackTime / duration));
else
delay += Math.max(duration, last.trackTime);
} else
delay = last.trackTime;
}
}
entry.delay = delay;
return entry;
}
public function setEmptyAnimation(trackIndex : int, mixDuration : Number) : TrackEntry {
var entry : TrackEntry = setAnimation(trackIndex, emptyAnimation, false);
entry.mixDuration = mixDuration;
entry.trackEnd = mixDuration;
return entry;
}
public function addEmptyAnimation(trackIndex : int, mixDuration : Number, delay : Number) : TrackEntry {
if (delay <= 0) delay -= mixDuration;
var entry : TrackEntry = addAnimation(trackIndex, emptyAnimation, false, delay);
entry.mixDuration = mixDuration;
entry.trackEnd = mixDuration;
return entry;
}
public function setEmptyAnimations(mixDuration : Number) : void {
var oldDrainDisabled : Boolean = queue.drainDisabled;
queue.drainDisabled = true;
for (var i : int = 0, n : int = tracks.length; i < n; i++) {
var current : TrackEntry = tracks[i];
if (current != null) setEmptyAnimation(current.trackIndex, mixDuration);
}
queue.drainDisabled = oldDrainDisabled;
queue.drain();
}
private function expandToIndex(index : int) : TrackEntry {
if (index < tracks.length) return tracks[index];
tracks.length = index + 1;
return null;
}
private function trackEntry(trackIndex : int, animation : Animation, loop : Boolean, last : TrackEntry) : TrackEntry {
var entry : TrackEntry = TrackEntry(trackEntryPool.obtain());
entry.trackIndex = trackIndex;
entry.animation = animation;
entry.loop = loop;
entry.holdPrevious = false;
entry.eventThreshold = 0;
entry.attachmentThreshold = 0;
entry.drawOrderThreshold = 0;
entry.animationStart = 0;
entry.animationEnd = animation.duration;
entry.animationLast = -1;
entry.nextAnimationLast = -1;
entry.delay = 0;
entry.trackTime = 0;
entry.trackLast = -1;
entry.nextTrackLast = -1;
entry.trackEnd = int.MAX_VALUE;
entry.timeScale = 1;
entry.alpha = 1;
entry.interruptAlpha = 1;
entry.mixTime = 0;
entry.mixDuration = last == null ? 0 : data.getMix(last.animation, animation);
return entry;
}
private function disposeNext(entry : TrackEntry) : void {
var next : TrackEntry = entry.next;
while (next != null) {
queue.dispose(next);
next = next.next;
}
entry.next = null;
}
private function _animationsChanged() : void {
animationsChanged = false;
propertyIDs = new Dictionary();
var i : int = 0;
var n: int = 0;
var entry : TrackEntry = null;
for (i = 0, n = tracks.length; i < n; i++) {
entry = tracks[i];
if (entry == null) continue;
while (entry.mixingFrom != null)
entry = entry.mixingFrom;
do {
if (entry.mixingTo == null || entry.mixBlend != MixBlend.add) computeHold(entry);
entry = entry.mixingTo;
} while (entry != null);
}
}
private function computeHold (entry: TrackEntry) : void {
var to: TrackEntry = entry.mixingTo;
var timelines : Vector.<Timeline> = entry.animation.timelines;
var timelinesCount : int = entry.animation.timelines.length;
var timelineMode : Vector.<int> = entry.timelineMode;
timelineMode.length = timelinesCount;
var timelineHoldMix : Vector.<TrackEntry> = entry.timelineHoldMix;
timelineHoldMix.length = 0;
var propertyIDs: Dictionary = this.propertyIDs;
var i : int = 0;
if (to != null && to.holdPrevious) {
for (i = 0; i < timelinesCount; i++) {
if (!propertyIDs[timelines[i].getPropertyId().toString()]) {
timelineMode[i] = HOLD_FIRST;
} else {
timelineMode[i] = HOLD_SUBSEQUENT;
}
propertyIDs[timelines[i].getPropertyId().toString()] = true;
}
return;
}
outer:
for (i = 0; i < timelinesCount; i++) {
var timeline : Timeline = Timeline(timelines[i]);
var intId : int = timeline.getPropertyId();
var id : String = intId.toString();
var contained: Object = propertyIDs[id];
propertyIDs[id] = true;
if (contained != null) {
timelineMode[i] = AnimationState.SUBSEQUENT;
} else if (to == null || timeline is AttachmentTimeline || timeline is DrawOrderTimeline
|| timeline is EventTimeline || !to.animation.hasTimeline(intId)) {
timelineMode[i] = AnimationState.FIRST;
} else {
for (var next : TrackEntry = to.mixingTo; next != null; next = next.mixingTo) {
if (next.animation.hasTimeline(intId)) continue;
if (entry.mixDuration > 0) {
timelineMode[i] = AnimationState.HOLD_MIX;
timelineHoldMix[i] = entry;
continue outer;
}
break;
}
timelineMode[i] = AnimationState.HOLD_FIRST;
}
}
}
public function getCurrent(trackIndex : int) : TrackEntry {
if (trackIndex >= tracks.length) return null;
return tracks[trackIndex];
}
public function clearListeners() : void {
onStart.listeners.length = 0;
onInterrupt.listeners.length = 0;
onEnd.listeners.length = 0;
onDispose.listeners.length = 0;
onComplete.listeners.length = 0;
onEvent.listeners.length = 0;
}
public function clearListenerNotifications() : void {
queue.clear();
}
}
}
|
package widgets.supportClasses.utils
{
import com.adobe.serializers.json.JSONEncoder;
import com.esri.ags.FeatureSet;
import com.esri.ags.Graphic;
import com.esri.ags.layers.GraphicsLayer;
public class GraphicsLayerUtil
{
public function GraphicsLayerUtil()
{
/**
* Returns an object representing a json arcgis featureset object. User must supply a valid geometry type as feauresets can only contain
* a single geometry type. Graphics utilising a text symbol will be considered a label, and will be filtered out of the results by default.
* Generic attributes will be included - attributes that the graphic includes will not be translated into the output.
* <p>
* <b>Parameters</b><br/>
* <ul>
* <li><i>layer [GraphicsLayer]: </i>Graphics layer to translated into a featureset json object.</li>
* <li><i>geometryType [String]: </i>Geometry type to be used in the output featureset. Only graphics with this geometry type will be included in the output.
* Accepts the standard Geometry types.</li>
* <li><i>includeLabels [Boolean] (optional): </i>Specify whether to include label points in the output set. If true, the geometry must be a MapPoint to be accepted.
* Defaults to false.</li>
* </ul>
* </p>
*/
public static function graphicsLayerToArcGISFeaturesetJson(layer:GraphicsLayer, geometryType:String, includeLabels:Boolean = false):Object
{
var result:Object;
var features:Array = [];
var id:int = 0;
for each (var graphic:Graphic in layer.graphicProvider)
{
// Check if the geometry of the graphic is of the required type
if (graphic.geometry && graphic.geometry.type == geometryType)
{
// Create the attributes object and populate with objects
var attributes = {};
// Add a unique object id
id ++;
attributes.id = id;
// Create a new feature
var feature:Graphic = new Graphic(graphic.geometry, null, attributes);
features.push(feature);
}
}
var fset:FeatureSet = new FeatureSet(features);
result = fset.toJSON();
return result;
}
}
}
} |
/* Copyright 2019 Tua Rua Ltd.
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.tuarua.iap.storekit {
[RemoteClass(alias="com.tuarua.iap.storekit.PaymentTransaction")]
public class PaymentTransaction {
private var _id:String;
public var transactionIdentifier:String;
public var transactionDate:Date;
public var transactionState:int;
public var downloads:Vector.<Download> = new Vector.<Download>();
public function PaymentTransaction(id:String) {
this._id = id;
}
/** The purchase id associated with this transaction */
public function get id():String {
return _id;
}
}
}
|
package SJ.Game.data.config
{
import SJ.Common.Constants.ConstResource;
import SJ.Game.data.json.Json_rolename_propertys;
import engine_starling.utils.AssetManagerUtil;
public class CJDataOfNameProperty
{
private static var _o:CJDataOfNameProperty;
public static function get o():CJDataOfNameProperty
{
if(_o == null)
_o = new CJDataOfNameProperty();
return _o;
}
/** 姓氏 **/
private var _lastNameArr:Array;
/** 男子名称 **/
private var _maleNameArr:Array;
/** 女子名称 **/
private var _femaleNameArr:Array;
/** 中间名 **/
private var _midNameArr:Array;
public function CJDataOfNameProperty()
{
_initData();
}
private function _initData():void
{
var obj:Array = AssetManagerUtil.o.getObject(ConstResource.sResJsonNameConfig) as Array;
if(obj == null)
{
return;
}
_lastNameArr = new Array;
_maleNameArr = new Array;
_femaleNameArr = new Array;
_midNameArr = new Array;
var length:int = obj.length;
for(var i:int=0 ; i < length ; i++)
{
var data:Json_rolename_propertys = new Json_rolename_propertys();
data.loadFromJsonObject(obj[i]);
// 根据类型区分 姓氏、男子名称、女子名称
if (int(data.type) == 0)
_lastNameArr.push(data.value);
else if (int(data.type) == 1)
_maleNameArr.push(data.value);
else if (int(data.type) == 2)
_femaleNameArr.push(data.value);
else if (int(data.type) == 3)
{
// 不限男女的名字
_maleNameArr.push(data.value);
_femaleNameArr.push(data.value);
}
else if (int(data.type) == 4)
{
// 中间名字
_midNameArr.push(data.value);
}
}
}
/**
* 获取姓氏列表
* @return
*
*/
public function getLastNameList():Array
{
return _lastNameArr;
}
/**
* 获取男子名列表
* @return
*
*/
public function getMaleNameList():Array
{
return _maleNameArr;
}
/**
* 获取女子名列表
* @return
*
*/
public function getFemaleNamelist():Array
{
return _femaleNameArr;
}
/**
* 获取中间名列表
* @return
*/
public function getMidNameArr():Array
{
return _midNameArr;
}
}
} |
/*
* _________ __ __
* _/ / / /____ / /________ ____ ____ ___
* _/ / / __/ -_) __/ __/ _ `/ _ `/ _ \/ _ \
* _/________/ \__/\__/\__/_/ \_,_/\_, /\___/_//_/
* /___/
*
* Tetragon : Game Engine for multi-platform ActionScript projects.
* http://www.tetragonengine.com/ - Copyright (C) 2012 Sascha Balkau
*
* 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 tetragon.view.render2d.animation
{
import tetragon.view.render2d.events.Event2D;
import tetragon.view.render2d.events.EventDispatcher2D;
/**
* The Juggler takes objects that implement IAnimatable (like Tweens) and executes them.
*
* <p>A juggler is a simple object. It does no more than saving a list of objects implementing
* "IAnimatable" and advancing their time if it is told to do so (by calling its own
* "advanceTime"-method). When an animation is completed, it throws it away.</p>
*
* <p>There is a default juggler available at the Render2D class:</p>
*
* <pre>
* var juggler:Juggler = Render2D.juggler;
* </pre>
*
* <p>You can create juggler objects yourself, just as well. That way, you can group
* your game into logical components that handle their animations independently. All you have
* to do is call the "advanceTime" method on your custom juggler once per frame.</p>
*
* <p>Another handy feature of the juggler is the "delayCall"-method. Use it to
* execute a function at a later time. Different to conventional approaches, the method
* will only be called when the juggler is advanced, giving you perfect control over the
* call.</p>
*
* <pre>
* juggler.delayCall(object.removeFromParent, 1.0);
* juggler.delayCall(object.addChild, 2.0, theChild);
* juggler.delayCall(function():void { doSomethingFunny(); }, 3.0);
* </pre>
*
* @see Tween
* @see DelayedCall
*/
public class Juggler2D implements IAnimatable2D
{
//-----------------------------------------------------------------------------------------
// Properties
//-----------------------------------------------------------------------------------------
private var _objects:Vector.<IAnimatable2D>;
private var _elapsedTime:Number;
//-----------------------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------------------
/**
* Create an empty juggler.
*/
public function Juggler2D()
{
_elapsedTime = 0;
_objects = new <IAnimatable2D>[];
}
//-----------------------------------------------------------------------------------------
// Public Methods
//-----------------------------------------------------------------------------------------
/**
* Adds an object to the juggler.
*
* @param object
*/
public function add(object:IAnimatable2D):void
{
if (object && _objects.indexOf(object) == -1)
{
_objects.push(object);
var dispatcher:EventDispatcher2D = object as EventDispatcher2D;
if (dispatcher) dispatcher.addEventListener(Event2D.REMOVE_FROM_JUGGLER, onRemove);
}
}
/**
* Determines if an object has been added to the juggler.
*
* @param object
* @return Boolean
*/
public function contains(object:IAnimatable2D):Boolean
{
return _objects.indexOf(object) != -1;
}
/**
* Removes an object from the juggler.
*
* @param object
*/
public function remove(object:IAnimatable2D):void
{
if (!object) return;
var dispatcher:EventDispatcher2D = object as EventDispatcher2D;
if (dispatcher) dispatcher.removeEventListener(Event2D.REMOVE_FROM_JUGGLER, onRemove);
var index:int = _objects.indexOf(object);
if (index != -1) _objects[index] = null;
}
/** Removes all tweens with a certain target. */
public function removeTweens(target:Object):void
{
if (target == null) return;
for (var i:int = _objects.length - 1; i >= 0; --i)
{
var tween:Tween2D = _objects[i] as Tween2D;
if (tween && tween.target == target)
{
tween.removeEventListener(Event2D.REMOVE_FROM_JUGGLER, onRemove);
_objects[i] = null;
}
}
}
/** Removes all objects at once. */
public function purge():void
{
// the object vector is not purged right away, because if this method is called
// from an 'advanceTime' call, this would make the loop crash. Instead, the
// vector is filled with 'null' values. They will be cleaned up on the next call
// to 'advanceTime'.
for (var i:int = _objects.length - 1; i >= 0; --i)
{
var dispatcher:EventDispatcher2D = _objects[i] as EventDispatcher2D;
if (dispatcher) dispatcher.removeEventListener(Event2D.REMOVE_FROM_JUGGLER, onRemove);
_objects[i] = null;
}
}
/** Delays the execution of a function until a certain time has passed. Creates an
* object of type 'DelayedCall' internally and returns it. Remove that object
* from the juggler to cancel the function call. */
public function delayCall(call:Function, delay:Number, ...args):DelayedCall2D
{
if (call == null) return null;
var delayedCall:DelayedCall2D = new DelayedCall2D(call, delay, args);
add(delayedCall);
return delayedCall;
}
/** Utilizes a tween to animate the target object over a certain time. Internally, this
* method uses a tween instance (taken from an object pool) that is added to the
* juggler right away. This method provides a convenient alternative for creating
* and adding a tween manually.
*
* <p>Fill 'properties' with key-value pairs that describe both the
* tween and the animation target. Here is an example:</p>
*
* <pre>
* juggler.tween(object, 2.0, {
* transition: Transitions.EASE_IN_OUT,
* delay: 20, // -> tween.delay = 20
* x: 50 // -> tween.animate("x", 50)
* });
* </pre>
*/
public function tween(target:Object, time:Number, properties:Object):void
{
var tween:Tween2D = Tween2D.fromPool(target, time);
for (var property:String in properties)
{
var value:Object = properties[property];
if (tween.hasOwnProperty(property))
tween[property] = value;
else if (target.hasOwnProperty(property))
tween.animate(property, value as Number);
else
throw new ArgumentError("Invalid property: " + property);
}
tween.addEventListener(Event2D.REMOVE_FROM_JUGGLER, onPooledTweenComplete);
add(tween);
}
/**
* Advances all objects by a certain time (in seconds).
*
* @param time
*/
public function advanceTime(time:Number):void
{
var numObjects:int = _objects.length;
var currentIndex:int = 0;
_elapsedTime += time;
if (numObjects == 0) return;
// there is a high probability that the "advanceTime" function modifies the list
// of animatables. we must not process new objects right now (they will be processed
// in the next frame), and we need to clean up any empty slots in the list.
var i:int;
for (i = 0; i < numObjects; ++i)
{
var object:IAnimatable2D = _objects[i];
if (object)
{
// shift objects into empty slots along the way
if (currentIndex != i)
{
_objects[currentIndex] = object;
_objects[i] = null;
}
object.advanceTime(time);
++currentIndex;
}
}
if (currentIndex != i)
{
numObjects = _objects.length; // count might have changed!
while (i < numObjects)
{
_objects[int(currentIndex++)] = _objects[int(i++)];
}
_objects.length = currentIndex;
}
}
//-----------------------------------------------------------------------------------------
// Accessors
//-----------------------------------------------------------------------------------------
/** The total life time of the juggler. */
public function get elapsedTime():Number
{
return _elapsedTime;
}
public function get numObjects():uint
{
return _objects.length;
}
//-----------------------------------------------------------------------------------------
// Callback Handlers
//-----------------------------------------------------------------------------------------
private function onPooledTweenComplete(e:Event2D):void
{
Tween2D.toPool(e.target as Tween2D);
}
private function onRemove(e:Event2D):void
{
remove(e.target as IAnimatable2D);
var tween:Tween2D = e.target as Tween2D;
if (tween && tween.isComplete) add(tween.nextTween);
}
}
}
|
package SJ.Game.utils
{
/**
+------------------------------------------------------------------------------
* 日期工具类
+------------------------------------------------------------------------------
* @author caihua
* @email caihua.bj@gmail.com
* @date 2013-11-20 下午4:46:14
+------------------------------------------------------------------------------
*/
public class SDateUtil
{
public static function get currentUTCSeconds():Number
{
return new Date().millisecondsUTC / 1000;
}
public static function get currentSeconds():Number
{
return new Date().milliseconds / 1000;
}
/**
* 本地时间 -> Y-M-D h:i:s
*/
public static function LTSeconds2YMDHIS(ltSeconds:Number = 0):String
{
var date:Date;
if(int(ltSeconds) == 0)
{
date = new Date();
}
else
{
date = new Date(ltSeconds * 1000 + new Date().timezoneOffset * 60 * 1000);
}
return date.fullYear+"-"+int(date.month + 1)+"-"+date.date + " " + date.hours + ":" +date.minutes +":" +date.seconds;
}
/**
* 本地时间 -> YY-MM-DD HH:II:SS
*/
public static function LTSeconds2YYMMDDHHIISS(ltSeconds:Number = 0):String
{
var date:Date;
if(int(ltSeconds) == 0)
{
date = new Date();
}
else
{
date = new Date(ltSeconds * 1000 + new Date().timezoneOffset * 60 * 1000);
}
var monthAS:int = date.month + 1;
var month:String = monthAS < 10 ? "0"+ monthAS : ""+monthAS;
var d:String = date.date < 10 ? "0"+ date.date : ""+date.date;
var hours:String = date.hours < 10 ? "0"+ date.hours : ""+date.hours;
var minutes:String = date.minutes < 10 ? "0"+ date.minutes : ""+date.minutes;
var seconds:String = date.seconds < 10 ? "0"+ date.seconds : ""+date.seconds;
return date.fullYear+"-"+month+"-"+d + " " + hours + ":" +minutes +":" +seconds;
}
/**
* UTC时间 -> Y-M-D h:i:s
*/
public static function UTCSeconds2YMDHIS(utcSeconds:Number):String
{
var date:Date;
if(int(utcSeconds) == 0)
{
date = new Date();
}
else
{
date = new Date(utcSeconds * 1000);
}
return date.fullYear+"-"+int(date.month + 1)+"-"+date.date + " " + date.hours + ":" +date.minutes +":" +date.seconds;
}
/**
* UTC时间 -> YY-MM-DD HH:II:SS
*/
public static function UTCSeconds2YYMMDDHHIISS(utcSeconds:Number):String
{
var date:Date;
if(int(utcSeconds) == 0)
{
date = new Date();
}
else
{
date = new Date(utcSeconds * 1000);
}
var monthAS:int = date.month + 1;
var month:String = monthAS < 10 ? "0"+ monthAS : ""+monthAS;
var d:String = date.date < 10 ? "0"+ date.date : ""+date.date;
var hours:String = date.hours < 10 ? "0"+ date.hours : ""+date.hours;
var minutes:String = date.minutes < 10 ? "0"+ date.minutes : ""+date.minutes;
var seconds:String = date.seconds < 10 ? "0"+ date.seconds : ""+date.seconds;
return date.fullYear+"-"+month+"-"+d + " " + hours + ":" +minutes +":" +seconds;
}
}
} |
/**
* VERSION: 1.0
* DATE: 2012-03-22
* AS3 (AS2 and JS versions are also available)
* UPDATES AND DOCS AT: http://www.greensock.com
**/
import com.greensock.easing.Ease;
/**
* See AS3 files for full ASDocs
*
* <p><strong>Copyright 2008-2014, GreenSock. All rights reserved.</strong> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for <a href="http://www.greensock.com/club/">Club GreenSock</a> members, the software agreement that was issued with the membership.</p>
*
* @author Jack Doyle, jack@greensock.com
*/
class com.greensock.easing.SineIn extends Ease {
private static var _HALF_PI:Number = Math.PI / 2;
public static var ease:SineIn = new SineIn();
public function getRatio(p:Number):Number {
return -Math.cos(p * _HALF_PI) + 1;
}
}
|
package com.pcup.framework.singleNotice
{
/**
*
* @author phx
* @createTime Sep 25, 2014 1:50:17 AM
*/
public class Dispatcher implements IDispatcher
{
public function addListener(type:String, listener:Function):void
{
Notifier.ins.addListener(type, listener);
}
public function removeListener(type:String, listener:Function):void
{
Notifier.ins.removeListener(type, listener);
}
public function sendEvent(type:String, data:Object = null):void
{
Notifier.ins.sendEvent(type, data);
}
}
} |
/*
* fireworks.as - Kenneth Kufluk (http://kenneth.kufluk.com/)
* MIT Licensed
* http://js-fireworks.appspot.com/
*
*/
function rgb2hex(r, g, b):Number {
return(r<<16 | g<<8 | b);
}
var FireworkDisplay = {
GRAVITY : 5,
FRAME_RATE : 30,
DEPLOYMENT_RATE : 10,
FIREWORK_SPEED : 2,
DISPERSION_WIDTH : 1,
DISPERSION_HEIGHT : 2,
FIREWORK_PAYLOAD : 10,
FRAGMENT_SPREAD : 8,
TEXT_LINE_HEIGHT : 70,
FIREWORK_READY : 0,
FIREWORK_LAUNCHED : 1,
FIREWORK_EXPLODED : 2,
FIREWORK_FRAGMENT : 3,
canvas : 0,
canvaswidth : 0,
canvasheight : 0,
ctx : 0,
blockPointer : 0,
fireworks : [],
allBlocks : new Array(),
gameloop : 0,
updateDisplay : function() {
FireworkDisplay.ctx.clear();
var firecount = 0;
for (var i1=0;i1<FireworkDisplay.fireworks.length;i1++) {
if (FireworkDisplay.fireworks[i1]==null) continue;
if (FireworkDisplay.fireworks[i1].status!=FireworkDisplay.FIREWORK_EXPLODED) {
firecount++;
}
FireworkDisplay.displayFirework(FireworkDisplay.fireworks[i1]);
}
},
addFireworks : function() {
if (FireworkDisplay.blockPointer>=FireworkDisplay.allBlocks.length) {
return;
}
var fw = FireworkDisplay.fireworks[FireworkDisplay.fireworks.length] = new Firework(FireworkDisplay.fireworks.length);
var targetx = FireworkDisplay.allBlocks[FireworkDisplay.blockPointer][0];
targetx = (((targetx)) / 300) * FireworkDisplay.DISPERSION_HEIGHT;
var targety = FireworkDisplay.allBlocks[FireworkDisplay.blockPointer][1];
targety = (((10-targety) / 100) * FireworkDisplay.DISPERSION_WIDTH) + 3.5;
FireworkDisplay.launchFirework(fw, targetx, targety);
FireworkDisplay.blockPointer++;
setTimeout(FireworkDisplay.addFireworks, 1000/FireworkDisplay.DEPLOYMENT_RATE);
},
launchText : function(canvas) {
FireworkDisplay.fireworks = [];
FireworkDisplay.blockPointer = 0;
clearTimeout(FireworkDisplay.gameloop);
//CANVAS
FireworkDisplay.canvas = canvas;
FireworkDisplay.ctx = FireworkDisplay.canvas.graphics;
FireworkDisplay.ctx.clear();
FireworkDisplay.ctx.lineStyle(1, 0xdddddd);
FireworkDisplay.canvaswidth = 500;
FireworkDisplay.canvasheight = 500;
var text = "hello world";
var chararr = '';
var maxWidthOffset = 0;
var totalHeightOffset = 0;
var totalWidthOffset = new Array();
var widthCounter = 0;
totalWidthOffset[widthCounter] = 0;
for (var i2=0;i2<text.length;i2++) {
if (text.charAt(i2)==' ') {
totalHeightOffset += FireworkDisplay.TEXT_LINE_HEIGHT;
widthCounter++;
totalWidthOffset[widthCounter] = 0;
} else {
maxWidthOffset = 0;
for (var j1=0;j1<FONT_FIREWORK[text.charAt(i2)].length;j1++) {
chararr = FONT_FIREWORK[text.charAt(i2)][j1];
maxWidthOffset = Math.max(maxWidthOffset, chararr[0]);
}
totalWidthOffset[widthCounter] += maxWidthOffset + 40;
}
}
FireworkDisplay.allBlocks = new Array();
var windowHeight = 500;
var offsetTop = totalHeightOffset;
offsetTop += (windowHeight-totalHeightOffset)/6;
var offsetLeft = 0;
var heightOffsetCount = 0;
for (var i3=0;i3<text.length;i3++) {
if (text.charAt(i3)==' ') {
heightOffsetCount++;
offsetTop = offsetTop - FireworkDisplay.TEXT_LINE_HEIGHT;
offsetLeft = 0;
} else {
maxWidthOffset = 0;
for (var j2=0;j2<FONT_FIREWORK[text.charAt(i3)].length;j2++) {
chararr = FONT_FIREWORK[text.charAt(i3)][j2];
FireworkDisplay.allBlocks[FireworkDisplay.allBlocks.length] = [(chararr[0]+offsetLeft)-(totalWidthOffset[heightOffsetCount]/2), chararr[1]-offsetTop];
maxWidthOffset = Math.max(maxWidthOffset, chararr[0]);
}
offsetLeft += maxWidthOffset+40; //plus character spacing
}
}
FireworkDisplay.gameloop = setInterval(FireworkDisplay.updateDisplay, 1000/FireworkDisplay.FRAME_RATE);
FireworkDisplay.addFireworks();
},
launchFirework : function(fw, dispersion, speed) {
fw.dx = dispersion;
fw.dy = speed;
fw.status = FireworkDisplay.FIREWORK_LAUNCHED;
},
disperseFirework : function(fw, speed) {
fw.dx = speed * (0.5-Math.random());
fw.dy = speed * (0.5-Math.random()) + 1;
},
explodeFirework : function(fw, speed) {
fw.status = FireworkDisplay.FIREWORK_EXPLODED;
fw.r = (Math.random() /2) + 0.5;
fw.g = (Math.random() /2) + 0.5;
fw.b = (Math.random() /2) + 0.5;
fw.brightness = 200;
FireworkDisplay.ctx.lineStyle(1, rgb2hex(200, 200, 200));
// add the fragments
var frags = Math.random() * FireworkDisplay.FIREWORK_PAYLOAD;
for (var i4=0;i4<frags;i4++) {
var spark = FireworkDisplay.fireworks[FireworkDisplay.fireworks.length] = new Firework(FireworkDisplay.fireworks.length);
spark.x = fw.x;
spark.y = fw.y;
spark.r = fw.r;
spark.g = fw.g;
spark.b = fw.b;
spark.status = FireworkDisplay.FIREWORK_FRAGMENT;
FireworkDisplay.disperseFirework(spark, Math.random()*FireworkDisplay.FRAGMENT_SPREAD);
}
},
destroyFirework : function(fw) {
FireworkDisplay.fireworks[fw.index] = null;
},
displayFirework : function(fw, speed) {
if (fw.y<0) FireworkDisplay.destroyFirework(fw);
if (fw.status==FireworkDisplay.FIREWORK_EXPLODED) {
var radius = 3; // Arc radius
var startAngle = 0; // Starting point on circle
var endAngle = Math.PI*2; // End point on circle
var anticlockwise = true; // clockwise or anticlockwise
FireworkDisplay.ctx.beginFill(rgb2hex(200, 200, 200));
FireworkDisplay.ctx.drawCircle(fw.x, FireworkDisplay.canvasheight-fw.y, radius);
FireworkDisplay.ctx.endFill();
return;
}
fw.colour = rgb2hex(80, 80, 80);
FireworkDisplay.ctx.lineStyle(1, fw.colour);
var forces = {x:0,y:-0.05};
if (fw.status==FireworkDisplay.FIREWORK_FRAGMENT) {
forces.y = FireworkDisplay.GRAVITY/-100;
fw.colour = rgb2hex(Math.round(fw.r*fw.brightness), Math.round(fw.g*fw.brightness), Math.round(fw.b*fw.brightness));
FireworkDisplay.ctx.lineStyle(1, fw.colour);
fw.brightness-=5;
if (fw.brightness<0) FireworkDisplay.destroyFirework(fw);
}
if (fw.dy<-1 && fw.status==FireworkDisplay.FIREWORK_LAUNCHED) {
FireworkDisplay.explodeFirework(fw);
}
fw.start = {x:fw.x, y:fw.y};
//apply accelerations
fw.dx += forces.x*FireworkDisplay.FIREWORK_SPEED;
fw.dy += forces.y*FireworkDisplay.FIREWORK_SPEED;
//apply velocities
fw.x += fw.dx*FireworkDisplay.FIREWORK_SPEED;
fw.y += fw.dy*FireworkDisplay.FIREWORK_SPEED;
//show
if (fw.previous) {
FireworkDisplay.ctx.moveTo(fw.previous.x, FireworkDisplay.canvasheight-fw.previous.y);
FireworkDisplay.ctx.lineTo(fw.x, FireworkDisplay.canvasheight-fw.y);
}
fw.previous = {x:fw.start.x, y:fw.start.y};
}
}
var Firework = function(index) {
this.index = index;
this.dx = 0;
this.dy = 0;
this.x = FireworkDisplay.canvaswidth/2;
this.y = 0;
this.status = FireworkDisplay.FIREWORK_READY;
this.brightness = 255;
this.r = 1;
this.g = 1;
this.b = 1;
this.start = {x:0, y:0};
this.previous = 0;
}
// Home-made point-based font.
var FONT_FIREWORK = {"!":[[5,-40],[5,-30],[5,-20],[5,0]],"\"":[[20,-40],[20,-30],[5,-40],[5,-30]],"#":[[35,-40],[45,-30],[35,-30],[15,-40],[25,-30],[35,-20],[45,-10],[15,-30],[35,-10],[5,-30],[15,-20],[25,-10],[35,0],[15,-10],[5,-10],[15,0]],"%":[[45,-40],[35,-30],[15,-40],[45,-10],[5,-40],[15,-30],[25,-20],[35,-10],[45,0],[5,-30],[35,0],[15,-10],[5,0]],"&":[[35,-40],[25,-40],[35,-30],[15,-40],[35,-20],[15,-30],[25,-20],[15,-20],[25,-10],[35,0],[5,-20],[25,0],[5,-10],[15,0],[25,10],[5,0]],"'":[[5,-40],[5,-30]],"(":[[15,-40],[5,-30],[5,-20],[5,-10],[15,0]],")":[[5,-40],[15,-30],[15,-20],[15,-10],[5,0]],"*":[[25,-40],[5,-40],[15,-30],[25,-20],[5,-20]],"+":[[20,-40],[35,-20],[20,-30],[25,-20],[15,-20],[20,-10],[5,-20],[20,0]],",":[[5,0],[5,10]],"-":[[35,-20],[25,-20],[15,-20],[5,-20]],"-":[[35,-20],[25,-20],[15,-20],[5,-20]],".":[[5,0]],"/":[[45,-40],[35,-30],[25,-20],[15,-10],[5,0]],":":[[5,-30],[5,-10]],";":[[5,-30],[5,-10],[5,0]],"<":[[15,-25],[5,-15],[15,-5]],"=":[[35,-30],[25,-30],[15,-30],[35,-10],[5,-30],[25,-10],[15,-10],[5,-10]],">":[[5,-25],[15,-15],[5,-5]],"?":[[35,-40],[25,-40],[35,-30],[15,-40],[35,-20],[5,-40],[25,-20],[15,-20],[15,0]],"@":[[35,-30],[25,-40],[15,-40],[35,-20],[25,-20],[35,-10],[5,-30],[35,0],[15,-15],[5,-20],[25,0],[15,-5],[5,-10],[15,5],[5,0]],"A":[[35,-30],[25,-40],[15,-40],[35,-20],[25,-20],[35,-10],[5,-30],[15,-20],[35,0],[5,-20],[5,-10],[5,0]],"B":[[25,-40],[15,-40],[25,-30],[35,-20],[5,-40],[25,-20],[35,-10],[5,-30],[15,-20],[35,0],[5,-20],[25,0],[5,-10],[15,0],[5,0]],"C":[[35,-40],[25,-40],[15,-40],[5,-30],[35,0],[5,-20],[25,0],[5,-10],[15,0]],"D":[[35,-30],[25,-40],[15,-40],[35,-20],[5,-40],[35,-10],[5,-30],[5,-20],[25,0],[5,-10],[15,0],[5,0]],"E":[[35,-40],[25,-40],[15,-40],[5,-40],[25,-20],[5,-30],[15,-20],[35,0],[5,-20],[25,0],[5,-10],[15,0],[5,0]],"F":[[35,-40],[25,-40],[15,-40],[5,-40],[25,-20],[5,-30],[15,-20],[5,-20],[5,-10],[5,0]],"G":[[35,-40],[25,-40],[15,-40],[35,-20],[25,-20],[35,-10],[5,-30],[35,0],[5,-20],[25,0],[5,-10],[15,0]],"H":[[35,-40],[35,-30],[35,-20],[5,-40],[25,-20],[35,-10],[5,-30],[15,-20],[35,0],[5,-20],[5,-10],[5,0]],"I":[[25,-40],[15,-40],[5,-40],[15,-30],[15,-20],[15,-10],[25,0],[15,0],[5,0]],"J":[[35,-40],[25,-40],[35,-30],[35,-20],[35,-10],[25,0],[5,-10],[15,0]],"K":[[35,-40],[25,-30],[5,-40],[25,-20],[35,-10],[5,-30],[15,-20],[35,0],[5,-20],[5,-10],[5,0]],"L":[[5,-40],[5,-30],[35,0],[5,-20],[25,0],[5,-10],[15,0],[5,0]],"M":[[35,-40],[35,-30],[25,-30],[35,-20],[5,-40],[15,-30],[35,-10],[20,-20],[5,-30],[35,0],[5,-20],[5,-10],[5,0]],"N":[[35,-40],[35,-30],[35,-20],[5,-40],[15,-30],[25,-20],[35,-10],[5,-30],[35,0],[5,-20],[5,-10],[5,0]],"O":[[35,-30],[25,-40],[15,-40],[35,-20],[35,-10],[5,-30],[5,-20],[25,0],[5,-10],[15,0]],"P":[[35,-30],[25,-40],[15,-40],[5,-40],[25,-20],[5,-30],[15,-20],[5,-20],[5,-10],[5,0]],"Q":[[35,-30],[25,-40],[15,-40],[35,-20],[35,-10],[5,-30],[25,-10],[35,0],[5,-20],[25,0],[5,-10],[15,0]],"R":[[35,-30],[25,-40],[15,-40],[5,-40],[25,-20],[35,-10],[5,-30],[15,-20],[35,0],[5,-20],[5,-10],[5,0]],"S":[[35,-35],[25,-40],[15,-40],[35,-15],[25,-20],[5,-35],[35,-5],[15,-20],[5,-25],[25,0],[15,0],[5,-5]],"T":[[35,-40],[25,-40],[15,-40],[20,-30],[5,-40],[20,-20],[20,-10],[20,0]],"U":[[35,-40],[35,-30],[35,-20],[5,-40],[35,-10],[5,-30],[5,-20],[25,0],[5,-10],[15,0]],"V":[[35,-40],[35,-30],[35,-20],[5,-40],[5,-30],[25,-10],[5,-20],[15,-10],[20,0]],"W":[[35,-40],[35,-30],[20,-40],[35,-20],[20,-30],[5,-40],[35,-10],[20,-20],[5,-30],[35,0],[20,-10],[5,-20],[25,0],[5,-10],[15,0]],"X":[[35,-40],[25,-30],[5,-40],[15,-30],[20,-20],[25,-10],[35,0],[15,-10],[5,0]],"Y":[[35,-40],[35,-30],[5,-40],[25,-20],[5,-30],[15,-20],[20,-10],[20,0]],"Z":[[35,-40],[25,-40],[15,-40],[25,-30],[5,-40],[20,-20],[35,0],[15,-10],[25,0],[15,0],[5,0]],"_":[[45,0],[35,0],[25,0],[15,0],[5,0]],"a":[[25,-30],[35,-20],[15,-30],[35,-10],[25,-15],[5,-30],[35,0],[15,-15],[25,0],[5,-10],[15,0]],"b":[[25,-30],[35,-20],[5,-40],[15,-30],[35,-10],[5,-30],[5,-20],[25,0],[5,-10],[15,0],[5,0]],"c":[[35,-30],[25,-30],[15,-30],[35,0],[5,-20],[25,0],[5,-10],[15,0]],"d":[[35,-40],[35,-30],[25,-30],[35,-20],[15,-30],[35,-10],[35,0],[5,-20],[25,0],[5,-10],[15,0]],"e":[[25,-30],[35,-20],[15,-30],[25,-15],[35,0],[15,-15],[5,-20],[25,0],[5,-10],[15,0]],"f":[[25,-40],[15,-40],[25,-20],[5,-30],[15,-20],[5,-20],[5,-10],[5,0]],"g":[[35,-30],[25,-30],[35,-20],[15,-30],[35,-10],[25,-10],[35,0],[5,-20],[15,-10],[25,10],[15,10],[5,10]],"h":[[5,-40],[25,-20],[35,-10],[5,-30],[15,-20],[35,0],[5,-20],[5,-10],[5,0]],"i":[[5,-40],[5,-20],[5,-10],[5,0]],"j":[[15,-40],[15,-20],[15,-10],[15,0],[5,10]],"k":[[35,-30],[5,-40],[25,-20],[35,-10],[5,-30],[15,-20],[35,0],[5,-20],[5,-10],[5,0]],"l":[[5,-40],[5,-30],[5,-20],[5,-10],[15,0]],"m":[[35,-30],[45,-20],[25,-30],[45,-10],[15,-30],[25,-20],[45,0],[5,-30],[25,-10],[5,-20],[25,0],[5,-10],[5,0]],"n":[[25,-30],[35,-20],[15,-30],[35,-10],[5,-30],[35,0],[5,-20],[5,-10],[5,0]],"o":[[25,-30],[35,-20],[15,-30],[35,-10],[5,-20],[25,0],[5,-10],[15,0]],"p":[[25,-30],[35,-20],[15,-30],[35,-10],[5,-30],[5,-20],[25,0],[5,-10],[15,0],[5,0],[5,10]],"q":[[35,-30],[25,-30],[35,-20],[15,-30],[35,-10],[35,0],[5,-20],[25,0],[35,10],[5,-10],[15,0]],"r":[[35,-30],[25,-30],[5,-30],[15,-20],[5,-20],[5,-10],[5,0]],"s":[[35,-30],[25,-30],[15,-30],[35,-10],[25,-15],[15,-15],[5,-20],[25,0],[15,0],[5,0]],"t":[[25,-30],[5,-40],[15,-30],[5,-30],[5,-20],[25,0],[5,-10],[15,0]],"u":[[35,-30],[35,-20],[35,-10],[5,-30],[35,0],[5,-20],[25,0],[5,-10],[15,0]],"v":[[35,-30],[35,-20],[5,-30],[25,-10],[5,-20],[15,-10],[20,0]],"w":[[35,-30],[35,-20],[20,-30],[35,-10],[20,-20],[5,-30],[35,0],[20,-10],[5,-20],[25,0],[5,-10],[15,0]],"x":[[35,-30],[25,-20],[5,-30],[15,-20],[25,-10],[35,0],[15,-10],[5,0]],"y":[[35,-30],[35,-20],[35,-10],[5,-30],[25,-10],[35,0],[5,-20],[15,-10],[25,10],[15,10]],"z":[[35,-30],[25,-30],[15,-30],[25,-20],[5,-30],[35,0],[15,-10],[25,0],[15,0],[5,0]],"0":[[35,-30],[25,-40],[15,-40],[35,-20],[35,-10],[15,-25],[25,-15],[5,-30],[5,-20],[25,0],[5,-10],[15,0]],"1":[[15,-40],[15,-30],[5,-30],[15,-20],[15,-10],[15,0]],"2":[[35,-35],[25,-40],[35,-25],[15,-40],[25,-20],[5,-35],[15,-20],[35,0],[25,0],[5,-10],[15,0],[5,0]],"3":[[25,-40],[35,-30],[15,-40],[5,-40],[25,-20],[35,-10],[15,-20],[25,0],[15,0],[5,0]],"4":[[35,-40],[35,-30],[35,-20],[5,-40],[25,-20],[35,-10],[5,-30],[15,-20],[35,0],[5,-20]],"5":[[35,-40],[25,-40],[15,-40],[35,-15],[5,-40],[25,-20],[35,-5],[5,-30],[15,-20],[5,-20],[25,0],[15,0],[5,0]],"6":[[35,-40],[25,-40],[15,-40],[35,-20],[25,-20],[35,-10],[5,-30],[15,-20],[5,-20],[25,0],[5,-10],[15,0]],"7":[[35,-40],[35,-30],[25,-40],[15,-40],[5,-40],[25,-20],[5,-30],[25,-10],[25,0]],"8":[[35,-35],[25,-40],[35,-25],[15,-40],[35,-15],[25,-20],[5,-35],[35,-5],[15,-20],[5,-25],[25,0],[5,-15],[15,0],[5,-5]],"9":[[35,-30],[25,-40],[15,-40],[35,-20],[25,-20],[35,-10],[5,-30],[15,-20],[5,-20],[25,0],[15,0],[5,0]]}; |
/* Copyright (c) 2007 Derek Wischusen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.as3yaml.events {
public class StreamEndEvent extends Event {
}// StreamEndEvent
} |
package com.unhurdle.spectrum.controllers
{
import org.apache.royale.core.IBeadController;
import org.apache.royale.core.IIndexedItemRenderer;
import org.apache.royale.core.IItemRenderer;
import org.apache.royale.core.IRuntimeSelectableItemRenderer;
import org.apache.royale.core.ISelectableItemRenderer;
import org.apache.royale.core.IStrand;
import org.apache.royale.events.Event;
import org.apache.royale.events.IEventDispatcher;
import org.apache.royale.events.ItemClickedEvent;
import org.apache.royale.utils.getSelectionRenderBead;
public class ItemRendererMouseController implements IBeadController
{
public function ItemRendererMouseController()
{
}
private var renderer:ISelectableItemRenderer;
private var _strand:IStrand;
public function set strand(value:IStrand):void
{
_strand = value;
renderer = value as ISelectableItemRenderer;
// COMPILE::SWF {
// renderer.addEventListener(MouseEvent.ROLL_OVER, rollOverHandler);
// renderer.addEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
// renderer.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
// renderer.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
// }
var host:IEventDispatcher = _strand as IEventDispatcher;
host.addEventListener("mouseover", handleMouseOver);
host.addEventListener("mouseout", handleMouseOut);
host.addEventListener("mousedown", handleMouseDown);
host.addEventListener("click", handleMouseUp);
}
/**
* @royaleemitcoercion org.apache.royale.core.IItemRenderer
*/
protected function handleMouseOver(event:Event):void
{
var target:IItemRenderer = event.currentTarget as IItemRenderer;
if (target) {
target.dispatchEvent(new Event("itemRollOver",true));
}
}
/**
* @royaleemitcoercion org.apache.royale.core.IItemRenderer
*/
protected function handleMouseOut(event:Event):void
{
var target:IItemRenderer = event.currentTarget as IItemRenderer;
if (target)
{
target.dispatchEvent(new Event("itemRollOut",true));
}
}
/**
* @royaleemitcoercion org.apache.royale.core.IItemRenderer
*/
protected function handleMouseDown(event:Event):void
{
var target:IItemRenderer = event.currentTarget as IItemRenderer;
if (target)
{
var selectionBead:ISelectableItemRenderer = getSelectionRenderBead(target);
if(selectionBead){
selectionBead.down = true;
selectionBead.hovered = false;
}
}
}
/**
* @royaleemitcoercion org.apache.royale.core.IRuntimeSelectableItemRenderer
* @royaleignorecoercion org.apache.royale.core.IIndexedItemRenderer
*/
protected function handleMouseUp(event:Event):void
{
event.stopImmediatePropagation();
var target:IRuntimeSelectableItemRenderer = event.currentTarget as IRuntimeSelectableItemRenderer;
if (target && target.selectable)
{
var newEvent:ItemClickedEvent = new ItemClickedEvent("itemClicked");
var indexRenderer:IIndexedItemRenderer = target as IIndexedItemRenderer;
newEvent.data = indexRenderer.data;
newEvent.index = indexRenderer.index;
indexRenderer.dispatchEvent(newEvent);
}
}
}
}
|
package feathers.examples.layoutExplorer.screens
{
import feathers.controls.Button;
import feathers.controls.Header;
import feathers.controls.PanelScreen;
import feathers.controls.ScrollContainer;
import feathers.events.FeathersEventType;
import feathers.examples.layoutExplorer.data.VerticalLayoutSettings;
import feathers.layout.VerticalLayout;
import feathers.system.DeviceCapabilities;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Quad;
import starling.events.Event;
[Event(name="complete",type="starling.events.Event")]
[Event(name="showSettings",type="starling.events.Event")]
public class VerticalLayoutScreen extends PanelScreen
{
public static const SHOW_SETTINGS:String = "showSettings";
public function VerticalLayoutScreen()
{
super();
}
public var settings:VerticalLayoutSettings;
override protected function initialize():void
{
//never forget to call super.initialize()
super.initialize();
this.title = "Vertical Layout";
var layout:VerticalLayout = new VerticalLayout();
layout.gap = this.settings.gap;
layout.paddingTop = this.settings.paddingTop;
layout.paddingRight = this.settings.paddingRight;
layout.paddingBottom = this.settings.paddingBottom;
layout.paddingLeft = this.settings.paddingLeft;
layout.horizontalAlign = this.settings.horizontalAlign;
layout.verticalAlign = this.settings.verticalAlign;
this.layout = layout;
//when the scroll policy is set to on, the "elastic" edges will be
//active even when the max scroll position is zero
this.verticalScrollPolicy = ScrollContainer.SCROLL_POLICY_ON;
this.snapScrollPositionsToPixels = true;
var minQuadSize:Number = Math.min(Starling.current.stage.stageWidth, Starling.current.stage.stageHeight) / 15;
for(var i:int = 0; i < this.settings.itemCount; i++)
{
var size:Number = (minQuadSize + minQuadSize * 2 * Math.random());
var quad:Quad = new Quad(size, size, 0xff8800);
this.addChild(quad);
}
this.headerFactory = this.customHeaderFactory;
//this screen doesn't use a back button on tablets because the main
//app's uses a split layout
if(!DeviceCapabilities.isTablet(Starling.current.nativeStage))
{
this.backButtonHandler = this.onBackButton;
}
this.addEventListener(FeathersEventType.TRANSITION_IN_COMPLETE, transitionInCompleteHandler);
}
private function customHeaderFactory():Header
{
var header:Header = new Header();
//this screen doesn't use a back button on tablets because the main
//app's uses a split layout
if(!DeviceCapabilities.isTablet(Starling.current.nativeStage))
{
var backButton:Button = new Button();
backButton.styleNameList.add(Button.ALTERNATE_STYLE_NAME_BACK_BUTTON);
backButton.label = "Back";
backButton.addEventListener(Event.TRIGGERED, backButton_triggeredHandler);
header.leftItems = new <DisplayObject>
[
backButton
];
}
var settingsButton:Button = new Button();
settingsButton.label = "Settings";
settingsButton.addEventListener(Event.TRIGGERED, settingsButton_triggeredHandler);
header.rightItems = new <DisplayObject>
[
settingsButton
];
return header;
}
private function onBackButton():void
{
this.dispatchEventWith(Event.COMPLETE);
}
private function transitionInCompleteHandler(event:Event):void
{
this.revealScrollBars();
}
private function backButton_triggeredHandler(event:Event):void
{
this.onBackButton();
}
private function settingsButton_triggeredHandler(event:Event):void
{
this.dispatchEventWith(SHOW_SETTINGS);
}
}
}
|
package com.myflexhero.network
{
import com.myflexhero.network.core.IData;
import com.myflexhero.network.core.ui.FloorUI;
import com.myflexhero.network.core.util.room.ShapeUtil;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.Dictionary;
public class Floor extends Node
{
private var _row:int=1;
private var _col:int=1;
private var pointMap:Dictionary;
private var _borderPoints:Array;
private var validateFlag:Boolean=true;
private var eqCollection:Vector.<IData>=new Vector.<IData>();
public function addEquipment(eq:Equipment):void
{
eqCollection.push(eq);
}
public function removeEquipment(eq:Equipment):void
{
var eqIndex:int = eqCollection.indexOf(eq);
if(eqIndex!=-1)
eqCollection.splice(eqIndex,1);
}
public function getInUseList():Dictionary
{
var col:Dictionary=new Dictionary();
eqCollection.forEach(function(eq:Equipment,index:int, array:Vector.<IData>):void
{
var rSpan:int=eq.rowSpan;
var cSpan:int=eq.colSpan;
for (var i:int=0; i < cSpan; i++)
{
// col.addItem(eq.rowIndex + ":" + (eq.colIndex + i));
if((eq.colIndex+i)<_col)
col[eq.rowIndex + ":" + (eq.colIndex + i)]=eq;
}
for (i=0; i < rSpan; i++)
{
// col.addItem((eq.rowIndex - i) + ":" + eq.colIndex);
if((eq.rowIndex+i)<_row)
col[(eq.rowIndex + i) + ":" + eq.colIndex]=eq;
}
});
return col;
}
public function Floor(id:Object=null)
{
super(id);
this.width=500;
this.height=400;
}
public function get col():int
{
return _col;
}
public function set col(value:int):void
{
var old:int=this.col;
_col=value;
if (this.dispatchPropertyChangeEvent("col", old, col))
{
validateFlag=true;
}
}
public function get row():int
{
return _row;
}
public function set row(value:int):void
{
var old:int=this.row;
_row=value;
if (this.dispatchPropertyChangeEvent("row", old, row))
{
validateFlag=true;
}
}
override public function get elementUIClass():Class
{
return FloorUI;
}
private function calculatePoint():void
{
if (validateFlag)
{
_borderPoints=ShapeUtil.createParallelogram(this.x, this.y, this._width, this._height, 0.3, 0.3);
var s:int=_borderPoints.length;
if (col > 1 || row > 1)
{
pointMap=ShapeUtil.splitParallelogram(_borderPoints, row, col);
}
validateFlag=false;
var children:Vector.<IData>=this.children;
children.forEach(function(c:Element,index:int, array:Vector.<IData>):void
{
var wall:Wall=c as Wall;
if (wall)
{
wall.invalidateFlag();
}
});
}
}
/**
* 监听属性更改,如果发生改变,则设置validateFlag为true,供calculatePoint方法判断。
*/
override public function dispatchPropertyChangeEvent(property:String, oldValue:Object, newValue:Object):Boolean
{
var result:Boolean=super.dispatchPropertyChangeEvent(property, oldValue, newValue);
if (result)
{
if ("location" == property || "width" == property || "height" == property||"x" == property || "y"==property||"addChild"==property)
{
validateFlag=true;
}
}
return result;
}
public function get borderPoints():Array
{
calculatePoint();
return _borderPoints;
}
public function getPointArray(r:int, c:int):Array
{
calculatePoint();
return pointMap[r + ":" + c];
}
public function getBounds(r:int, c:int):Rectangle
{
var a:Array=getPointArray(r, c);
var l:int=a.length;
var minx:Number=0;
var miny:Number=0;
var maxx:Number=0;
var maxy:Number=0;
//计算四边形的四个顶点
for (var i:int=0; i < l; i++)
{
var p:Point=a[i];
if (i == 0)
{
minx=p.x;
miny=p.y;
maxx=p.x;
maxy=p.y;
}
else
{
if (minx > p.x)
{
minx=p.x;
}
if (miny > p.y)
{
miny=p.y;
}
if (maxx < p.x)
{
maxx=p.x;
}
if (maxy < p.y)
{
maxy=p.y;
}
}
}
return new Rectangle(minx, miny, maxx - minx, maxy - miny);
}
public function getFillColor(r:int, c:int):uint
{
if (r % 2 == 0)
{
if (c % 2 == 0)
{
return 0x000000;
}
else
{
return 0xFFFFFF;
}
}
else
{
if (c % 2 == 0)
{
return 0xFFFFFF;
}
else
{
return 0x000000;
}
}
}
}
} |
package asx.array {
/**
* Alias of <code>head()</code>
*
* @see asx.array#head()
*/
public function first(iterable:Object):Object {
return head(iterable);
}
} |
package serverProto.team
{
import com.netease.protobuf.Message;
import com.netease.protobuf.fieldDescriptors.RepeatedFieldDescriptor$TYPE_MESSAGE;
import com.netease.protobuf.WireType;
import serverProto.inc.ProtoPlayerKey;
import com.netease.protobuf.WritingBuffer;
import com.netease.protobuf.WriteUtils;
import flash.utils.IDataInput;
import com.netease.protobuf.ReadUtils;
public final class ProtoInviteMemberRequest extends Message
{
public static const INVITE_PLAYER:RepeatedFieldDescriptor$TYPE_MESSAGE = new RepeatedFieldDescriptor$TYPE_MESSAGE("serverProto.team.ProtoInviteMemberRequest.invite_player","invitePlayer",1 << 3 | WireType.LENGTH_DELIMITED,ProtoPlayerKey);
[ArrayElementType("serverProto.inc.ProtoPlayerKey")]
public var invitePlayer:Array;
public function ProtoInviteMemberRequest()
{
this.invitePlayer = [];
super();
}
override final function writeToBuffer(param1:WritingBuffer) : void
{
var _loc3_:* = undefined;
var _loc2_:uint = 0;
while(_loc2_ < this.invitePlayer.length)
{
WriteUtils.writeTag(param1,WireType.LENGTH_DELIMITED,1);
WriteUtils.write$TYPE_MESSAGE(param1,this.invitePlayer[_loc2_]);
_loc2_++;
}
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: 1, Size: 1)
*/
throw new flash.errors.IllegalOperationError("Not decompiled due to error");
}
}
}
|
package framework.view.component
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import framework.util.DisplayUtil;
import framework.view.mediator.pack.ClickItemSingleMenu;
import framework.view.mediator.pack.ItemBackGround;
public class DropMenu extends Sprite
{
private var _menuBg:ItemBackGround;
private const SPACE:int = 10;
private const SPACEHEIGHT:int = 3;
public var currentTarget:MovieClip;
private static var _instance:DropMenu;
public var list:Vector.<ClickItemSingleMenu>;
public function DropMenu()
{
init();
}
public static function getInstance():DropMenu
{
if(_instance == null)
{
_instance = new DropMenu();
}
return _instance;
}
private function init():void
{
list = new Vector.<ClickItemSingleMenu>;
}
public function push(label:String,data:*,clickHandle:Function):void
{
var option:ClickItemSingleMenu = new ClickItemSingleMenu(label);
option.data = data;
option.clickHandle = clickHandle;
option.addEventListener(ClickItemSingleMenu.CLICK_MENU,onClick);
var content:Sprite = new Sprite();
this.addChild(content);
content.x = SPACE;
content.y = SPACE>>1;
option.y = this.height;
content.addChild(option);
list.push(option);
}
private function onClick(e:Event):void
{
if(e.target.data)
{
trace("@!#^%$#^$(&*^(*^&%$%^#$%@#@%$@%$&%$&^%(*&^*&%!!%&^^*(^(%$#");
(e.target as ClickItemSingleMenu).clickHandle(e);
}
}
public function setBackGround():void
{
if(_menuBg)
{
_menuBg.removeSelf();
}
_menuBg = new ItemBackGround(this.width,this.height);
this.addChildAt(_menuBg,0);
}
public function clear():void
{
for each(var option:ClickItemSingleMenu in list)
{
if(option.hasEventListener(ClickItemSingleMenu.CLICK_MENU))
{
option.removeEventListener(ClickItemSingleMenu.CLICK_MENU,onClick);
}
}
DisplayUtil.removeAllChildren(this);
if(this.parent)
{
this.parent.removeChild(this);
}
}
}
} |
*Include config.mac
*Include apiasm.mac
;
; Measuring mailbox messaging (while optionally reading a big .HEX file)
;
;
; 7,3728 : 652 micros = SendMail+GetMail (20 bytes)
;
GLOBAL _main
psect text
_main:
ld bc,60H
ld hl,Task2
ld e,10
call __StartUp
ret
;
Task2:
call __RoundRobinOFF
ld bc,20 ;20 bytes moved
call __MakeMB
ld (Mail),hl
ld bc,60H
ld hl,Task3
ld e,50
call __RunTask
ld (TCB3),hl
COND IO_COMM
ld bc,60H
ld hl,TaskHEX
ld e,30
call __RunTask
ENDC
call __MakeSem
ld (W),hl
call __MakeSem
ld (S),hl
call __MakeSem
ld (X),hl
call __MakeTimer
ld (Timer),hl
ld de,(S)
COND IO_COMM
ld bc,600 ;wait 3 secs
ENDC
COND IO_COMM=0
ld bc,1 ;wait 5 ms
ENDC
xor a ;just once
call __StartTimer
ld hl,(S)
call __Wait
call __GetTicks
ld (T_start),de
; ld de,(S)
; ld bc,2 ;10 milisec
; ld a,1 ;forever
; call __StartTimer
loop2: ;10secs, 100 SendMail/sec
; ld hl,(S)
; call __Wait
ld hl,(Mail)
ld de,buf20
call __SendMail
ld hl,(Cnt)
dec hl
ld (Cnt),hl
ld a,l
or h
jr nz,loop2
call __GetTicks
ex de,hl
or a
ld de,(T_start)
sbc hl,de
ex de,hl
ld hl,delta
call StoreDE
COND IO_COMM
ld hl,(X)
call __Wait
ENDC
ld hl,tx1 ;write Delta!
call type_str
ld hl,(TCB3)
call __StopTask
call __GetCrtTask
call __StopTask
Task3:
loopm: ld hl,(Mail)
ld de,buf20
call __GetMail
jr loopm
COND IO_COMM
GLOBAL _ReadHEX
TaskHEX:
call _ReadHEX
ld a,h
cp 0FFH
jr nz,ok
ld a,l
cp 0FEH
jr z,tmo
cp 0FDH
jr z,badck
cp 0FCH
jr z,eofnf
ld hl,mallocf
prt: call type_str
ld hl,(X)
call __Signal
call __GetCrtTask
call __StopTask
tmo: ld hl,mtmo
jr prt
badck: ld hl,mbadck
jr prt
eofnf: ld hl,meofnf
jr prt
ok: ld hl,mok
jr prt
ENDC
;
; Type string
; HL=string
;
type_str:
push hl
ld bc,0
loop: ld a,(hl)
or a
jr z,1f
inc bc
inc hl
jr loop
1: pop hl
ld de,(W)
call __CON_Write
ld hl,(W)
call __Wait
ret
;
; Store Word
;
; store DE in hexa at HL
; DE not affected
;
StoreDE:
push de
ld a,d
call ByteToNibbles
ld a,d
call NibbleToASCII
ld (hl),a
inc hl
ld a,e
call NibbleToASCII
ld (hl),a
inc hl
pop de
push de
ld a,e
call ByteToNibbles
ld a,d
call NibbleToASCII
ld (hl),a
inc hl
ld a,e
call NibbleToASCII
ld (hl),a
pop de
ret
;
; Byte To Nibbles
;
; Convert byte to nibbles
; A = Hex byte
; returns D = Most significant nibble, E = Least significant nibble
; registers not affected (except AF)
;
ByteToNibbles:
ld e,a
rra
rra
rra
rra
and 0FH
ld d,a
ld a,e
and 0FH
ld e,a
ret
;
; Converts Nibble A to ASCII
;
; Converts Nibble (0-15) to its ASCII value ('0' to '9', or 'A' to 'F')
;
; A=Nibble
; returns A=ASCII value of byte (letters in uppercase)
; registers not affected (except AF)
;
NibbleToASCII:
cp 10 ;digit?
jr nc,1f
add a,'0' ;it's a digit
ret
1: add a,'A'-10 ;no, it's a letter (A to F)
ret
TCB3: defs 2
buf20: defs 20
W: defs 2
S: defs 2
X: defs 2
Timer: defs 2
Mail: defs 2
Delta: defs 2 ;count of tics for 10000 WriteQ + ReadQ
T_start:defs 2
Cnt: defw 10000 ;how many SendMail+GetMail
tx1: defb 0dh,0ah
defm 'Delta='
delta: defs 4
defb 'H'
defb 0
mallocf:defb 0dh,0ah
defm 'Alloc failed!'
defb 0
mtmo: defb 0dh,0ah
defm 'TimeOut!'
defb 0
mbadck: defb 0dh,0ah
defm 'Bad Checksum!'
defb 0
meofnf: defb 0dh,0ah
defm 'Could not reach EOF!'
defb 0
mok: defb 0dh,0ah
defm 'OK!'
defb 0
|
//
// Wyvern Tail Project
// Copyright 2014 Jason Estey
//
// This program is free software. You can redistribute and/or modify it
// in accordance with the terms of the accompanying license agreement.
//
package wyverntail.ogmo
{
import starling.display.Image;
import starling.textures.Texture;
import starling.textures.TextureAtlas;
import wyverntail.core.TileData;
public class TileLayer extends Layer implements TileData
{
public var tilesAtlas :TextureAtlas;
// in tiles
private var _width :int;
private var _height :int;
public function get width() :int { return _width; }
public function get height() :int { return _height; }
private var _tileData :Vector.<int>;
public function TileLayer(levelWidth :int, levelHeight :int)
{
_width = levelWidth / Settings.TileWidth;
_height = levelHeight / Settings.TileHeight;
_tileData = new Vector.<int>(_width * _height);
}
override public function init(data :XML) :void
{
for each (var tileXML :XML in data.children())
{
setTile(int(tileXML.@x), int(tileXML.@y), tileXML.@id);
}
}
private function setTile(x :int, y :int, tile :int) :void
{
var i :int = y * _width + x;
_tileData[i] = tile;
}
public function getTileTexture(x :int, y :int) :Image
{
var i :int = y * _width + x;
var textureName :String = "tile";
if (_tileData[i] < 10)
{
textureName += "00" + _tileData[i];
}
else if (_tileData[i] < 100)
{
textureName += "0" + _tileData[i];
}
else
{
textureName += _tileData[i];
}
var tex :Texture = tilesAtlas.getTexture(textureName);
if (!tex)
{
trace("unknown texture: " + textureName);
return null;
}
return new Image(tex);
}
} // class
} // package
|
/**
* __ __ __
* ____/ /_ ____/ /______ _ ___ / /_
* / __ / / ___/ __/ ___/ / __ `/ __/
* / /_/ / (__ ) / / / / / /_/ / /
* \__,_/_/____/_/ /_/ /_/\__, /_/
* / /
* \/
* http://distriqt.com
*
* @author Michael (https://github.com/marchbold)
* @created 8/9/21
*/
package com.apm.client.commands.airsdk.processes
{
import com.apm.client.APM;
import com.apm.client.logging.Log;
import com.apm.client.processes.ProcessBase;
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.events.IOErrorEvent;
import flash.events.NativeProcessExitEvent;
import flash.events.ProgressEvent;
import flash.filesystem.File;
public class InstallAIRSDKFinaliseProcess extends ProcessBase
{
////////////////////////////////////////////////////////
// CONSTANTS
//
private static const TAG:String = "UpgradeClientFinaliseProcess";
////////////////////////////////////////////////////////
// VARIABLES
//
private var _process:NativeProcess;
private var _airSDKDir:File;
private var _failMessage:String = "Could not set permissions: try running: 'xattr -r -d com.apple.quarantine air_sdk_folder'";
////////////////////////////////////////////////////////
// FUNCTIONALITY
//
public function InstallAIRSDKFinaliseProcess( airSDKDir:File )
{
_airSDKDir = airSDKDir;
}
override public function start( completeCallback:Function = null, failureCallback:Function = null ):void
{
super.start( completeCallback, failureCallback );
if (APM.config.isMacOS)
{
// Need to ensure script permissions are set correctly
if (NativeProcess.isSupported)
{
var processArgs:Vector.<String> = new Vector.<String>();
processArgs.push( "-r" );
processArgs.push( "-d" );
processArgs.push( "com.apple.quarantine" );
processArgs.push( _airSDKDir.nativePath );
var processStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
processStartupInfo.executable = new File( "/usr/bin/xattr" );
processStartupInfo.arguments = processArgs;
_process = new NativeProcess();
_process.addEventListener( NativeProcessExitEvent.EXIT, onExit );
_process.addEventListener( ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData );
_process.addEventListener( ProgressEvent.STANDARD_ERROR_DATA, onErrorData );
_process.addEventListener( IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError );
_process.addEventListener( IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError );
APM.io.showSpinner( "Setting permissions" );
_process.start( processStartupInfo );
}
else
{
failure( _failMessage );
}
}
else if (APM.config.isWindows)
{
complete();
}
else
{
complete();
}
}
private function onOutputData( event:ProgressEvent ):void
{
Log.d( TAG, _process.standardOutput.readUTFBytes( _process.standardOutput.bytesAvailable ) );
}
private function onErrorData( event:ProgressEvent ):void
{
Log.d( TAG, "ERROR: " + _process.standardError.readUTFBytes( _process.standardError.bytesAvailable ) );
}
private function onExit( event:NativeProcessExitEvent ):void
{
Log.d( TAG, "Process exited with: " + event.exitCode );
if (event.exitCode == 0)
{
APM.io.stopSpinner( true, "complete" );
complete();
}
else
{
APM.io.stopSpinner( false, _failMessage );
failure( _failMessage );
}
}
private function onIOError( event:IOErrorEvent ):void
{
// Log.d( TAG, "IOError: " + event.toString() );
}
}
}
|
package com.swfjunkie.tweetr.data.objects
{
/**
* Trends Data Object
* @author Sandro Ducceschi [swfjunkie.com, Switzerland]
*/
public class TrendData
{
//--------------------------------------------------------------------------
//
// Class variables
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// Initialization
//
//--------------------------------------------------------------------------
public function TrendData(name:String = null, url:String = null)
{
this.name = name;
this.url = url;
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
public var name:String;
public var url:String;
//--------------------------------------------------------------------------
//
// API
//
//--------------------------------------------------------------------------
}
} |
package Ankama_Tooltips.blockParams
{
public class EffectsTooltipBlockParameters extends TooltipBlockParameters
{
public var effects:Object;
public var isCriticalEffects:Boolean = false;
public var setInfo:String;
public var splitDamageAndEffects:Boolean = true;
public var length:int = 409;
public var showDamages:Boolean = true;
public var showSpecialEffects:Boolean = true;
public var showTheoreticalEffects:Boolean = true;
public var addTheoreticalEffects:Boolean = false;
public var showDuration:Boolean = true;
public var showLabel:Boolean = true;
public var itemTheoreticalEffects:Object = null;
public var customli:String = "customlirightmargin";
public var fromBuff:Boolean = false;
public function EffectsTooltipBlockParameters()
{
super();
}
public static function create(effects:Object, chunkType:String = "chunks") : EffectsTooltipBlockParameters
{
var params:EffectsTooltipBlockParameters = new EffectsTooltipBlockParameters();
params.effects = effects;
params.chunkType = chunkType;
return params;
}
}
}
|
package com.pirkadat.ui
{
import com.pirkadat.display.*;
import flash.text.*;
public class TextDefaults extends TrueSizeText
{
public static var globalEmbedFonts:Boolean = true;
public static var globalStyleSheet:StyleSheet = new StyleSheet();
public static var globalDefaultTextFormat:TextFormat = new TextFormat("Font1", 12, Colors.WHITE, null, null, null, null, null, null, null, null, null, 2);
public function TextDefaults()
{
tabEnabled = false;
}
}
} |
package com.ankamagames.dofus.network.messages.game.prism
{
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 PrismInfoInValidMessage extends NetworkMessage implements INetworkMessage
{
public static const protocolId:uint = 1525;
private var _isInitialized:Boolean = false;
public var reason:uint = 0;
public function PrismInfoInValidMessage()
{
super();
}
override public function get isInitialized() : Boolean
{
return this._isInitialized;
}
override public function getMessageId() : uint
{
return 1525;
}
public function initPrismInfoInValidMessage(reason:uint = 0) : PrismInfoInValidMessage
{
this.reason = reason;
this._isInitialized = true;
return this;
}
override public function reset() : void
{
this.reason = 0;
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_PrismInfoInValidMessage(output);
}
public function serializeAs_PrismInfoInValidMessage(output:ICustomDataOutput) : void
{
output.writeByte(this.reason);
}
public function deserialize(input:ICustomDataInput) : void
{
this.deserializeAs_PrismInfoInValidMessage(input);
}
public function deserializeAs_PrismInfoInValidMessage(input:ICustomDataInput) : void
{
this._reasonFunc(input);
}
public function deserializeAsync(tree:FuncTree) : void
{
this.deserializeAsyncAs_PrismInfoInValidMessage(tree);
}
public function deserializeAsyncAs_PrismInfoInValidMessage(tree:FuncTree) : void
{
tree.addChild(this._reasonFunc);
}
private function _reasonFunc(input:ICustomDataInput) : void
{
this.reason = input.readByte();
if(this.reason < 0)
{
throw new Error("Forbidden value (" + this.reason + ") on element of PrismInfoInValidMessage.reason.");
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.InteractiveObject;
import flash.display.Shape;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.geom.Point;
import flash.system.Capabilities;
import flash.text.TextField;
import flash.utils.Timer;
import mx.core.IVisualElement;
import mx.core.IVisualElementContainer;
import mx.core.mx_internal;
import mx.graphics.SolidColor;
import mx.graphics.SolidColorStroke;
import mx.utils.GetTimerUtil;
import spark.components.Group;
import spark.components.Scroller;
import spark.core.SpriteVisualElement;
import spark.primitives.Ellipse;
import spark.primitives.Path;
use namespace mx_internal;
/**
* Exposes some helper methods that are useful for testing touch scrolling
* on a mobile device. These methods can be used in a standalone application
* to reproduce or demonstrate a bug and is also used in the SimulateMouseGesture
* Mustella test step.
*
* Example usage 1 - recording events:
*
* <s:actionContent>
* <s:Button label="enable" click="TouchScrollingUtil.enableMouseEventTracking(target)" />
* <s:Button label="disable" click="TouchScrollingUtil.disableMouseEventTracking(target)" />
* <s:Button label="write" click="TouchScrollingUtil.writeFileToDisk('/sdcard/Flex/QA/List/mouseEvents.txt',
* TouchScrollingUtil.getEventsAsMXMLString(TouchScrollingUtil.recordedMouseEvents));" />
* </s:actionContent>
*
* Example usage 2 - playing back events:
*
* <s:actionContent>
* <s:Button label="play" click="TouchScrollingUtil.simulateTouchScrollFrameBased(target, eventsArray)" />
* </s:actionContent>
*
*/
public class TouchScrollingUtil
{
/**
* The name of the event that is fired when all mouse events have been fired
*/
public static const SIMULATION_COMPLETE:String = "simulationComplete";
/**
* Keeps track of all the mouse events that have fired while tracking was enabled
*/
public static var recordedMouseEvents:Array = new Array();
/**
* Controls whether to trace out extra debug information, for example tracing
* out information about every mouse event as it is dispatched.
*/
public static var enableVerboseTraceOuput:Boolean = true;
/**
* Dispatches a series of MouseEvents that simulate how a user scrolls
* using touch scrolling on a mobile device.
*
* @param actualTarget - the target component to scroll
*
* @param events - An array of mouse events to dispatch.
*
* Use this for realistic simulation as you have complete control over the
* type, location, and time of each event.
*
* These events should be defined as an array of objects in this form:
*
* <fx:Object type="mouseDown" localX="150" localY="150" fakeTimeValue="0" />
* <fx:Object type="mouseMove" localX="149" localY="149" fakeTimeValue="16" />
* ...
* <fx:Object type="mouseUp" localX="100" localY="100" fakeTimeValue="343" />
*
* If this property is not null then it takes precedence over any
* dragX/dragY values that might also be defined.
*
* TODO: Possible Enhancement: Allow each individual mouse event entry to specify its own
* waitEvent before continuing on to the next. This would allow for more control
* over when the events are fired, but may not be of any value.
*
* TODO: Possible Enhancement: Fully support sequences that go outside the bounds of the target.
*
* @param dragXFrom - the x coordinate of the target to start the drag motion
* @param dragYFrom - the y coordinate of the target to start the drag motion
* @param dragXTo - the x coordinate of the target to end the drag motion
* @param dragYTo - the y coordinate of the target to end the drag motion
* @param delay - the time between events when an events array isn't defined
*
*/
public static function simulateTouchScroll(actualTarget:Object,
events:Array,
recordedDPI:Number = NaN,
dragXFrom:Number = NaN, dragYFrom:Number = NaN,
dragXTo:Number = NaN, dragYTo:Number = NaN,
delay:Number = 17):void
{
// reset the index into the event list
var eventIndex:int = 0;
// if a specific event sequence wasn't provided, then create one
if (events == null)
events = createEventsArray(dragXFrom, dragYFrom, dragXTo, dragYTo, delay);
// shove the target into each element of the events array
for (var j:int = 0; j < events.length; j++)
events[j].target = actualTarget;
// setup the timer based firing
var eventTimer:Timer = new Timer(1);
// the method that loops through the events to fire
var tickerFunction:Function = function(e:TimerEvent):void
{
if (eventIndex >= events.length)
{
// all mouse events have been fired at this point
// turn off fake time
GetTimerUtil.fakeTimeValue = undefined;
// turn mouse event thinning back on
Scroller.dragEventThinning = true;
// signal that this test step is ready for completion
actualTarget.dispatchEvent(new Event(SIMULATION_COMPLETE));
// stop the timer loop
eventTimer.stop();
eventTimer.removeEventListener(TimerEvent.TIMER, tickerFunction);
return;
}
// trace details on the event we are firing
traceLog("Dispatching MouseEvent:",
events[eventIndex].type,
events[eventIndex].localX,
events[eventIndex].localY,
events[eventIndex].fakeTimeValue);
// update the fake time
GetTimerUtil.fakeTimeValue = events[eventIndex].fakeTimeValue;
// turn off mouse event thinning
// ----
// Late in the 4.5 release the runtime changed their behavior on Android that
// fired too many mouseMove events making Flex sluggish on drag scrolls. We
// put logic in the SDK to thin out excess events and this logic is
// non-deterministic so we need to turn that logic off in Mustella.
// ----
// TODO: This is a dependency on the SDK and a possible risk for automation
// not following the same code path as a user.
// We're stuck with it for now until the runtime allows us more control
// over the mouse event firing rate.
// ----
// See http://bugs.adobe.com/jira/browse/SDK-29188 for a full explanation
//
Scroller.dragEventThinning = false;
// scale the localX/localY co-ordinates if requested
var adjustedLocalX:Number = scaleByDPIRatio(events[eventIndex].localX, recordedDPI);
var adjustedLocalY:Number = scaleByDPIRatio(events[eventIndex].localY, recordedDPI);
// fire the next event
dispatchMouseEvent(events[eventIndex].target,
events[eventIndex].type,
adjustedLocalX,
adjustedLocalY);
// update the timer delay to be the difference between time values of the next and current events
if (eventIndex + 1 < events.length)
{
var nextTimeValue:int = events[eventIndex + 1].fakeTimeValue;
var currTimeValue:int = events[eventIndex].fakeTimeValue;
eventTimer.delay = (nextTimeValue - currTimeValue);
traceLog('timer is now', eventTimer.delay);
}
// move on to the next event
eventIndex++;
};
// start firing the mouse events
eventTimer.addEventListener(TimerEvent.TIMER, tickerFunction);
eventTimer.start();
}
/**
* Similar to simulateTouchScroll(), but used in Mustella so it's not based
* on a timer but rather fires off a couple mouse events per enterFrame.
*
* @see simulateTouchScroll()
*/
public static function simulateTouchScrollFrameBased(actualTarget:Object,
events:Array,
recordedDPI:Number = NaN,
dragXFrom:Number = NaN, dragYFrom:Number = NaN,
dragXTo:Number = NaN, dragYTo:Number = NaN,
delay:Number = 17):void
{
// reset the index into the event list
var eventIndex:int = 0;
// if a specific event sequence wasn't provided, then create one
if (events == null)
events = createEventsArray(dragXFrom, dragYFrom, dragXTo, dragYTo, delay);
// shove the target into each element of the events array
for (var j:int = 0; j < events.length; j++)
events[j].target = actualTarget;
// the method that loops through the events to fire
var tickerFunction:Function = function(e:Event):void
{
// fire a few mouse events per enterFrame
var numEventsPerEnterFrame:int = 3;
for (var i:int = 0; i < numEventsPerEnterFrame; i++)
{
if (eventIndex >= events.length)
{
// all mouse events have been fired at this point
// turn off fake time
GetTimerUtil.fakeTimeValue = undefined;
// turn mouse event thinning back on
Scroller.dragEventThinning = true;
// signal that this test step is ready for completion
actualTarget.dispatchEvent(new Event(SIMULATION_COMPLETE));
// remove the enterFrame listener
actualTarget.removeEventListener("enterFrame", tickerFunction)
return;
}
// trace details on the event we are firing
traceLog("Dispatching MouseEvent:",
events[eventIndex].type,
events[eventIndex].localX,
events[eventIndex].localY,
events[eventIndex].fakeTimeValue);
// update the fake time
GetTimerUtil.fakeTimeValue = events[eventIndex].fakeTimeValue;
// turn off mouse event thinning
// ----
// Late in the 4.5 release the runtime changed their behavior on Android that
// fired too many mouseMove events making Flex sluggish on drag scrolls. We
// put logic in the SDK to thin out excess events and this logic is
// non-deterministic so we need to turn that logic off in Mustella.
// ----
// TODO: This is a dependency on the SDK and a possible risk for automation
// not following the same code path as a user.
// We're stuck with it for now until the runtime allows us more control
// over the mouse event firing rate.
// ----
// See http://bugs.adobe.com/jira/browse/SDK-29188 for a full explanation
//
Scroller.dragEventThinning = false;
// scale the localX/localY co-ordinates if requested
var adjustedLocalX:Number = scaleByDPIRatio(events[eventIndex].localX, recordedDPI);
var adjustedLocalY:Number = scaleByDPIRatio(events[eventIndex].localY, recordedDPI);
trace(adjustedLocalX, adjustedLocalY);
// fire the next event
dispatchMouseEvent(events[eventIndex].target,
events[eventIndex].type,
adjustedLocalX,
adjustedLocalY);
// move on to the next event
eventIndex++;
}
}
// start firing the mouse events
actualTarget.addEventListener("enterFrame", tickerFunction);
}
/**
* This takes an x/y value and scales it by the current device's exact DPI over the recorded
* device's exact dpi.
*
* This allows support for recording a mouseEvent sequence at one DPI and have it scale automatically
* on different DPIs to maintain the same physical distance scrolled (in inches).
*/
private static function scaleByDPIRatio(value:Number, recordedDPI:Number):Number
{
if (!isNaN(recordedDPI))
return Math.round(value * (Capabilities.screenDPI / recordedDPI));
else
return value;
}
/**
* TODO: This is an untyped version of MouseEventEntry in Mustella.
*/
private static function createMouseEventEntry(type:String, localX:Number, localY:Number, fakeTimeValue:Number):Object
{
var mouseEventEntry:Object = new Object();
mouseEventEntry.type = type;
mouseEventEntry.localX = localX;
mouseEventEntry.localY = localY;
mouseEventEntry.fakeTimeValue = fakeTimeValue;
return mouseEventEntry;
}
/**
* Creates a sequence of mouse events to perform the requested drag scroll
*/
private static function createEventsArray(dragXFrom:Number, dragYFrom:Number, dragXTo:Number, dragYTo:Number, delay:Number):Array
{
var arr:Array = new Array();
var deltaX:Number = isNaN(dragXFrom - dragXTo) ? 0 : dragXFrom - dragXTo;
var deltaY:Number = isNaN(dragYFrom - dragYTo) ? 0 : dragYFrom - dragYTo;
var numSteps:Number = 6;
var chunkX:Number = deltaX / numSteps;
var chunkY:Number = deltaY / numSteps;
// first need a move, rollOver, over, mouseDown at the start position
arr.push(createMouseEventEntry(MouseEvent.MOUSE_MOVE, dragXFrom, dragYFrom, arr.length * delay));
arr.push(createMouseEventEntry(MouseEvent.ROLL_OVER, dragXFrom, dragYFrom, arr.length * delay));
arr.push(createMouseEventEntry(MouseEvent.MOUSE_OVER, dragXFrom, dragYFrom, arr.length * delay));
arr.push(createMouseEventEntry(MouseEvent.MOUSE_DOWN, dragXFrom, dragYFrom, arr.length * delay));
for (var i:int = 0; i < numSteps; i++)
{
// then a couple mouseMoves along the way
arr.push(createMouseEventEntry(MouseEvent.MOUSE_MOVE,
Math.round(dragXFrom - (chunkX * i)),
Math.round(dragYFrom - (chunkY * i)),
arr.length * delay));
}
// then a few mouseMoves near/at the end to take away any potential
// velocity so we guarantee a drag instead of a throw
arr.push(createMouseEventEntry(MouseEvent.MOUSE_MOVE, dragXTo, dragYTo, arr.length * delay));
arr.push(createMouseEventEntry(MouseEvent.MOUSE_MOVE, dragXTo, dragYTo, arr.length * delay));
arr.push(createMouseEventEntry(MouseEvent.MOUSE_MOVE, dragXTo, dragYTo, arr.length * delay));
arr.push(createMouseEventEntry(MouseEvent.MOUSE_MOVE, dragXTo, dragYTo, arr.length * delay));
// then a mouseMove at the destination
arr.push(createMouseEventEntry(MouseEvent.MOUSE_MOVE, dragXTo, dragYTo, arr.length * delay));
// finally a mouseUp at the destination
arr.push(createMouseEventEntry(MouseEvent.MOUSE_UP, dragXTo, dragYTo, arr.length * delay));
return arr;
}
/**
* Fires a mouseEvent of the given type and location on the target.
*
* This method inspired by DispatchMouseClickEvent and tweaked to be
* a static method available outside of Mustella too. This means a few
* more optional parameters.
*/
public static function dispatchMouseEvent(actualTarget:Object,
type:String,
localX:Number = NaN,
localY:Number = NaN,
stageX:Number = NaN,
stageY:Number = NaN,
ctrlKey:Boolean = false,
shiftKey:Boolean = false,
delta:Number = 0,
relatedObject:Object = null):void
{
var event:MouseEvent = new MouseEvent(type, true); // all mouse events bubble
event.ctrlKey = ctrlKey;
event.shiftKey = shiftKey;
event.buttonDown = type == "mouseDown";
event.delta = delta;
if (relatedObject && relatedObject.length > 0)
{
// SEJS: Removing Mustella specific context stuff for now so this static method
// is available outside of Mustella too. TODO: Look into refactoring to allow this support
//
//event.relatedObject = InteractiveObject(context.stringToObject(relatedObject));
}
var stagePt:Point;
if (!isNaN(localX) && !isNaN(localY))
{
stagePt = actualTarget.localToGlobal(new Point(localX, localY));
}
else if (!isNaN(stageX) && !isNaN(stageY))
{
stagePt = new Point(stageX, stageY);
}
else
{
stagePt = actualTarget.localToGlobal(new Point(0, 0));
}
// SEJS: Removing Mustella specific context stuff for now so this static method
// is available outside of Mustella too. TODO: Look into refactoring to allow this support
//
// This class was inspired by DispatchMouseClickEvent, but in a mobile sense we don't care
// about other sandboxes for now so we can hopefully remove this mustella context sensitive code
//
//root[mouseX] = stagePt.x;
//root[mouseY] = stagePt.y;
//UnitTester.setMouseXY(stagePt);
//
//if (root["topLevelSystemManager"] != root)
//{
// root["topLevelSystemManager"][mouseX] = stagePt.x;
// root["topLevelSystemManager"][mouseY] = stagePt.y;
//}
if (actualTarget is DisplayObjectContainer)
{
var targets:Array = actualTarget.stage.getObjectsUnderPoint(stagePt);
// SEJS: Removing Mustella specific context stuff for now so this static method
// is available outside of Mustella too. TODO: Look into refactoring to allow this support
//
// This class was inspired by DispatchMouseClickEvent, but in a mobile sense we don't care
// about other sandboxes for now so we can hopefully remove this mustella context sensitive code
//
//var arr:Array = UnitTester.getObjectsUnderPoint(DisplayObject(actualTarget), stagePt);
//targets = targets.concat(arr);
for (var i:int = targets.length - 1; i >= 0; i--)
{
if (targets[i] is InteractiveObject)
{
if (targets[i] is TextField && !targets[i].selectable)
{
actualTarget = targets[i].parent;
break;
}
if (InteractiveObject(targets[i]).mouseEnabled)
{
actualTarget = targets[i];
break;
}
}
else if (targets[i] is Shape)
{
// Looks like getObjectsUnderPoint() returns a Shape for FXG elements.
// Here we assume that if we see a Shape like this then we check its parent
// DisplayObjectContainer to see if it has mouseEnabled true
// FIXME: Talk to Brian and Alex to see if this is the right fix and get it into DispatchMouseEvent/DispatchMouseClickEvent and here. is this a player bug?
var shapeParent:DisplayObjectContainer = (targets[i] as Shape).parent;
if (shapeParent.mouseEnabled)
{
actualTarget = targets[i];
break;
}
}
else
{
try
{
actualTarget = targets[i].parent;
while (actualTarget)
{
if (actualTarget is InteractiveObject)
{
if (InteractiveObject(actualTarget).mouseEnabled)
{
break;
}
}
actualTarget = actualTarget.parent;
}
if (actualTarget)
break;
}
catch (e:Error)
{
trace('error');
if (actualTarget)
break;
}
}
}
}
// Examine parent chain for "mouseChildren" set to false:
try
{
var parent:DisplayObjectContainer = actualTarget.parent;
while (parent)
{
if (!parent.mouseChildren){
trace('mouseChildren step: set actualTarget to parent:', parent);
actualTarget = parent;
}
parent = parent.parent;
}
}
catch (e1:Error)
{
}
var localPt:Point = actualTarget.globalToLocal(stagePt);
event.localX = localPt.x;
event.localY = localPt.y;
if (actualTarget is TextField)
{
if (type == "mouseDown")
{
var charIndex:int = actualTarget.getCharIndexAtPoint(event.localX, event.localY);
actualTarget.setSelection(charIndex + 1, charIndex + 1);
}
}
try
{
actualTarget.dispatchEvent(event);
}
catch (e2:Error)
{
trace("Error: Exception thrown in TouchScrollingUtil.dispatchMouseEvent()");
// SEJS: Removing Mustella specific context stuff for now so this static method
// is available outside of Mustella too. TODO: Look into refactoring to allow this support
//
//TestOutput.logResult("Exception thrown in DispatchMouseClickEvent.");
//testResult.doFail (e2.getStackTrace());
return;
}
}
/** placeholder for the function closure so the listener can be removed later */
private static var traceFunctionHolder:Function = null;
/** placeholder for the function closure so the listener can be removed later */
private static var enterFunctionHolder:Function = null;
/**
* Traces all of the relevant mouse events that happen on the target. You can access an array of
* these events via the recordedMoueEvents static property.
*
* @param target - the component to track mouse events on
* @param showEnterFrameEvents - set this to true to show when enterFrames are being fired within the sequence
*/
public static function enableMouseEventTracking(target:DisplayObject, showEnterFrameEvents:Boolean = false):void
{
// closure for tracing mouse events
var traceMouseEvents:Function = function (event:MouseEvent):void
{
// convert the stage value to be relative to the main target
var stagePt:Point = event.target.localToGlobal(new Point(event.localX, event.localY));
var targetPt:Point = target.globalToLocal(stagePt);
var newEvent:Object = new Object();
newEvent.target = target;
newEvent.type = event.type;
newEvent.localX = targetPt.x;
newEvent.localY = targetPt.y;
newEvent.fakeTimeValue = flash.utils.getTimer();
// track this event
recordedMouseEvents.push(newEvent);
// trace the event
trace(newEvent.type, newEvent.localX, newEvent.localY, newEvent.fakeTimeValue);
}
// closure for tracing enterFrame events
var traceEnterFrameEvents:Function = function (event:Event):void
{
if (showEnterFrameEvents)
trace(event.type);
}
// throw the closures into the static placeholders so they can be removed later
traceFunctionHolder = traceMouseEvents;
enterFunctionHolder = traceEnterFrameEvents;
// listen to enterFrame and all mouse events (use a higher priority than Scroller)
// TODO: Containers seem to need a different useCapture value than elements
if (target is IVisualElementContainer)
{
target.addEventListener(MouseEvent.CLICK, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.CONTEXT_MENU, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.DOUBLE_CLICK, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.MIDDLE_CLICK, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.MIDDLE_MOUSE_UP, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.MOUSE_DOWN, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.MOUSE_MOVE, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.MOUSE_OUT, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.MOUSE_OVER, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.MOUSE_UP, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.MOUSE_WHEEL, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.RIGHT_CLICK, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.RIGHT_MOUSE_UP, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.ROLL_OUT, traceFunctionHolder, true, 1);
target.addEventListener(MouseEvent.ROLL_OVER, traceFunctionHolder, true, 1);
}
else
{
target.addEventListener(MouseEvent.CLICK, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.CONTEXT_MENU, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.DOUBLE_CLICK, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.MIDDLE_CLICK, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.MIDDLE_MOUSE_UP, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.MOUSE_DOWN, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.MOUSE_MOVE, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.MOUSE_OUT, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.MOUSE_OVER, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.MOUSE_UP, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.MOUSE_WHEEL, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.RIGHT_CLICK, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.RIGHT_MOUSE_UP, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.ROLL_OUT, traceFunctionHolder, false, 1);
target.addEventListener(MouseEvent.ROLL_OVER, traceFunctionHolder, false, 1);
}
target.addEventListener(Event.ENTER_FRAME, enterFunctionHolder);
}
/**
* Removes the mouse and enterFrame event listeners from the target.
*/
public static function disableMouseEventTracking(target:DisplayObject):void
{
if (target is IVisualElementContainer)
{
target.removeEventListener(MouseEvent.CLICK, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.CONTEXT_MENU, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.DOUBLE_CLICK, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.MIDDLE_CLICK, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.MIDDLE_MOUSE_UP, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.MOUSE_DOWN, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.MOUSE_MOVE, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.MOUSE_OUT, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.MOUSE_OVER, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.MOUSE_UP, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.MOUSE_WHEEL, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.RIGHT_CLICK, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.RIGHT_MOUSE_DOWN, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.RIGHT_MOUSE_UP, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.ROLL_OUT, traceFunctionHolder, true);
target.removeEventListener(MouseEvent.ROLL_OVER, traceFunctionHolder, true);
}
else
{
target.removeEventListener(MouseEvent.CLICK, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.CONTEXT_MENU, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.DOUBLE_CLICK, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.MIDDLE_CLICK, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.MIDDLE_MOUSE_UP, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.MOUSE_DOWN, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.MOUSE_MOVE, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.MOUSE_OUT, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.MOUSE_OVER, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.MOUSE_UP, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.MOUSE_WHEEL, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.RIGHT_CLICK, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.RIGHT_MOUSE_DOWN, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.RIGHT_MOUSE_UP, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.ROLL_OUT, traceFunctionHolder, false);
target.removeEventListener(MouseEvent.ROLL_OVER, traceFunctionHolder, false);
}
target.removeEventListener(Event.ENTER_FRAME, enterFunctionHolder);
}
/**
* Returns a String representation of the given array of events as MouseEventEntry tags
*
* Example: <MouseEventEntry type="mouseMove" localX="8" localY="0" fakeTimeValue="21515" />
*/
public static function getEventsAsMXMLString(events:Array):String
{
var output:String = "";
for each (var e:Object in events)
output += '<MouseEventEntry type="' + e.type + '" localX="' + e.localX + '" localY="' + e.localY + '" fakeTimeValue="' + e.fakeTimeValue + '" />\n';
return output;
}
/**
* Returns a visual representation of the given sequence of mouse events.
*/
public static function getEventsAsPath(events:Array, recordedDPI:Number = NaN):Group
{
// create a new group to hold the path and circles
var g:Group = new Group();
g.mouseEnabled = false;
var p:Path = new Path();
p.stroke = new SolidColorStroke(0xFFFF00, 3);
p.data = "";
g.addElement(p);
// add a point to the path for each event
for (var i:int = 0; i < events.length; i++)
{
var e:Object = events[i];
// scale the co-ordinates if DPI scaling is requested
var adjustedLocalX:Number = scaleByDPIRatio(e.localX, recordedDPI);
var adjustedLocalY:Number = scaleByDPIRatio(e.localY, recordedDPI);
if (i == 0)
p.data += "M " + adjustedLocalX + " " + adjustedLocalY + " ";
else
p.data += "L " + adjustedLocalX + " " + adjustedLocalY + " ";
if (e.type == MouseEvent.MOUSE_DOWN)
{
// draw a mouse down circle (green)
var downCircle:Ellipse = createCircle(10, 0x00FF00);
downCircle.x = adjustedLocalX - downCircle.width / 2;
downCircle.y = adjustedLocalY - downCircle.height / 2;
g.addElement(downCircle);
}
if (e.type == MouseEvent.MOUSE_UP)
{
// draw a mouse up circle (red)
var upCircle:Ellipse = createCircle(10, 0xFF0000);
upCircle.x = adjustedLocalX - upCircle.width / 2;
upCircle.y = adjustedLocalY - upCircle.height / 2;
g.addElement(upCircle);
}
}
return g;
}
/**
* Returns a circle of the given radius and fill color
*/
private static function createCircle(radius:Number, fillColor:uint):Ellipse
{
var c:Ellipse = new Ellipse();
c.width = radius;
c.height = radius;
var solidColor:SolidColor = new SolidColor(fillColor);
c.fill = solidColor;
return c;
}
/**
* Writes the given content string to the disk at location fileName.
*
* Useful for writing sequences of mouse events to disk on the phone and
* transferring that off of the device.
*
* Sample usage:
*
* writeFileToDisk('/sdcard/Flex/QA/List/mouseEvents.txt',
* TouchScrollingUtil.getEventsAsMXMLString(TouchScrollingUtil.recordedMouseEvents));
*/
public static function writeFileToDisk(fileName:String, content:String):void
{
var file:File = new File (fileName);
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
fileStream.writeUTF(content);
fileStream.close();
}
/**
* Basically just calls trace(), but only does so if the verbose flag
* is set to true. This helps us avoid inflating the log with hundreds
* of extra trace statements while running in Mustella.
*/
private static function traceLog(... rest):void
{
// don't trace this message if debugging isn't enabled
if (!enableVerboseTraceOuput)
return;
// format the output the same way trace() does with a space
// in between each piece of the rest array
var output:String = "";
var i:int = 0;
const restLength:int = rest.length;
for (i = 0; i < restLength; i++)
{
output += rest[i];
if (i < restLength - 1)
output += " ";
}
trace(output);
}
}
}
|
/**
* Copyright (c) 2007-2009 The PyAMF Project.
* See LICENSE.txt for details.
*/
package org.pyamf.examples.addressbook.models
{
[Bindable]
public class PhoneNumber extends SAObject
{
public static var ALIAS : String = 'org.pyamf.examples.addressbook.models.PhoneNumber';
public var id : Object;
public var user_id : Object;
public var label : String;
public var number : String;
}
} |
psect text
global iregset, iregstore, asalxor, asllxor, alxor
asalxor:
asllxor:
call iregset
call alxor
jp iregstore
|
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 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.managers
{
import mx.core.Singleton;
/**
* The BrowserManager is a Singleton manager that acts as
* a proxy between the browser and the application.
* It provides access to the URL in the browser address
* bar similar to accessing the <code>document.location</code> property in JavaScript.
* Events are dispatched when the <code>url</code> property is changed.
* Listeners can then respond, alter the URL, and/or block others
* from getting the event.
*
* <p>To use the BrowserManager, you call the <code>getInstance()</code> method to get the current
* instance of the manager, and call methods and listen to
* events on that manager. See the IBrowserManager class for the
* methods, properties, and events to use.</p>
*
* @see mx.managers.IBrowserManager
* @see mx.managers.HistoryManager
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class BrowserManager
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Class variables
//
//--------------------------------------------------------------------------
/**
* @private
* Linker dependency on implementation class.
*/
private static var implClassDependency:BrowserManagerImpl;
/**
* @private
*/
private static var instance:IBrowserManager;
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
/**
* Returns the sole instance of this Singleton class;
* creates it if it does not already exist.
*
* @return Returns the sole instance of this Singleton class;
* creates it if it does not already exist.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function getInstance():IBrowserManager
{
if (!instance)
{
instance = IBrowserManager(
Singleton.getInstance("mx.managers::IBrowserManager"));
}
return instance;
}
}
}
|
package dragonBones.objects
{
/**
* Copyright 2012-2013. DragonBones. All Rights Reserved.
* @playerversion Flash 10.0, Flash 10
* @langversion 3.0
* @version 2.0
*/
import dragonBones.core.DragonBones;
import dragonBones.core.dragonBones_internal;
import dragonBones.textures.TextureData;
import dragonBones.utils.ConstValues;
import dragonBones.utils.DBDataUtil;
import flash.geom.ColorTransform;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.Dictionary;
use namespace dragonBones_internal;
/**
* The XMLDataParser class parses xml data from dragonBones generated maps.
*/
final public class XMLDataParser
{
public static function parseTextureAtlasData(rawData:XML, scale:Number = 1):Object
{
var textureAtlasData:Object = {};
textureAtlasData.__name = rawData.@[ConstValues.A_NAME];
var subTextureFrame:Rectangle;
for each (var subTextureXML:XML in rawData[ConstValues.SUB_TEXTURE])
{
var subTextureName:String = subTextureXML.@[ConstValues.A_NAME];
var subTextureRegion:Rectangle = new Rectangle();
subTextureRegion.x = int(subTextureXML.@[ConstValues.A_X]) / scale;
subTextureRegion.y = int(subTextureXML.@[ConstValues.A_Y]) / scale;
subTextureRegion.width = int(subTextureXML.@[ConstValues.A_WIDTH]) / scale;
subTextureRegion.height = int(subTextureXML.@[ConstValues.A_HEIGHT]) / scale;
var rotated:Boolean = subTextureXML.@[ConstValues.A_ROTATED] == "true";
var frameWidth:Number = int(subTextureXML.@[ConstValues.A_FRAME_WIDTH]) / scale;
var frameHeight:Number = int(subTextureXML.@[ConstValues.A_FRAME_HEIGHT]) / scale;
if(frameWidth > 0 && frameHeight > 0)
{
subTextureFrame = new Rectangle();
subTextureFrame.x = int(subTextureXML.@[ConstValues.A_FRAME_X]) / scale;
subTextureFrame.y = int(subTextureXML.@[ConstValues.A_FRAME_Y]) / scale;
subTextureFrame.width = frameWidth;
subTextureFrame.height = frameHeight;
}
else
{
subTextureFrame = null;
}
textureAtlasData[subTextureName] = new TextureData(subTextureRegion, subTextureFrame, rotated);
}
return textureAtlasData;
}
/**
* Parse the SkeletonData.
* @param xml The SkeletonData xml to parse.
* @return A SkeletonData instance.
*/
public static function parseSkeletonData(rawData:XML, ifSkipAnimationData:Boolean = false, outputAnimationDictionary:Dictionary = null):SkeletonData
{
if(!rawData)
{
throw new ArgumentError();
}
var version:String = rawData.@[ConstValues.A_VERSION];
switch (version)
{
case "2.3":
case "3.0":
//Update2_3To3_0.format(rawData as XML);
break;
case DragonBones.DATA_VERSION:
break;
default:
throw new Error("Nonsupport version!");
}
var frameRate:uint = int(rawData.@[ConstValues.A_FRAME_RATE]);
var data:SkeletonData = new SkeletonData();
data.name = rawData.@[ConstValues.A_NAME];
var isGlobalData:Boolean = rawData.@[ConstValues.A_IS_GLOBAL] == "0" ? false : true;
for each(var armatureXML:XML in rawData[ConstValues.ARMATURE])
{
data.addArmatureData(parseArmatureData(armatureXML, data, frameRate, isGlobalData, ifSkipAnimationData, outputAnimationDictionary));
}
return data;
}
private static function parseArmatureData(armatureXML:XML, data:SkeletonData, frameRate:uint, isGlobalData:Boolean, ifSkipAnimationData:Boolean, outputAnimationDictionary:Dictionary):ArmatureData
{
var armatureData:ArmatureData = new ArmatureData();
armatureData.name = armatureXML.@[ConstValues.A_NAME];
for each(var boneXML:XML in armatureXML[ConstValues.BONE])
{
armatureData.addBoneData(parseBoneData(boneXML, isGlobalData));
}
for each(var skinXML:XML in armatureXML[ConstValues.SKIN])
{
armatureData.addSkinData(parseSkinData(skinXML, data));
}
if(isGlobalData)
{
DBDataUtil.transformArmatureData(armatureData);
}
armatureData.sortBoneDataList();
var animationXML:XML;
if(ifSkipAnimationData)
{
if(outputAnimationDictionary!= null)
{
outputAnimationDictionary[armatureData.name] = new Dictionary();
}
var index:int = 0;
for each(animationXML in armatureXML[ConstValues.ANIMATION])
{
if(index == 0)
{
armatureData.addAnimationData(parseAnimationData(animationXML, armatureData, frameRate, isGlobalData));
}
else if(outputAnimationDictionary != null)
{
outputAnimationDictionary[armatureData.name][animationXML.@[ConstValues.A_NAME]] = animationXML;
}
index++;
}
}
else
{
for each(animationXML in armatureXML[ConstValues.ANIMATION])
{
armatureData.addAnimationData(parseAnimationData(animationXML, armatureData, frameRate, isGlobalData));
}
}
for each(var rectangleXML:XML in armatureXML[ConstValues.RECTANGLE])
{
armatureData.addAreaData(parseRectangleData(rectangleXML));
}
for each(var ellipseXML:XML in armatureXML[ConstValues.ELLIPSE])
{
armatureData.addAreaData(parseEllipseData(ellipseXML));
}
return armatureData;
}
private static function parseBoneData(boneXML:XML, isGlobalData:Boolean):BoneData
{
var boneData:BoneData = new BoneData();
boneData.name = boneXML.@[ConstValues.A_NAME];
boneData.parent = boneXML.@[ConstValues.A_PARENT];
boneData.length = Number(boneXML.@[ConstValues.A_LENGTH]);
boneData.inheritRotation = getBoolean(boneXML, ConstValues.A_INHERIT_ROTATION, true);
boneData.inheritScale = getBoolean(boneXML, ConstValues.A_INHERIT_SCALE, true);
parseTransform(boneXML[ConstValues.TRANSFORM][0], boneData.transform);
if(isGlobalData)//绝对数据
{
boneData.global.copy(boneData.transform);
}
for each(var rectangleXML:XML in boneXML[ConstValues.RECTANGLE])
{
boneData.addAreaData(parseRectangleData(rectangleXML));
}
for each(var ellipseXML:XML in boneXML[ConstValues.ELLIPSE])
{
boneData.addAreaData(parseEllipseData(ellipseXML));
}
return boneData;
}
private static function parseRectangleData(rectangleXML:XML):RectangleData
{
var rectangleData:RectangleData = new RectangleData();
rectangleData.name = rectangleXML.@[ConstValues.A_NAME];
rectangleData.width = Number(rectangleXML.@[ConstValues.A_WIDTH]);
rectangleData.height = Number(rectangleXML.@[ConstValues.A_HEIGHT]);
parseTransform(rectangleXML[ConstValues.TRANSFORM][0], rectangleData.transform, rectangleData.pivot);
return rectangleData;
}
private static function parseEllipseData(ellipseXML:XML):EllipseData
{
var ellipseData:EllipseData = new EllipseData();
ellipseData.name = ellipseXML.@[ConstValues.A_NAME];
ellipseData.width = Number(ellipseXML.@[ConstValues.A_WIDTH]);
ellipseData.height = Number(ellipseXML.@[ConstValues.A_HEIGHT]);
parseTransform(ellipseXML[ConstValues.TRANSFORM][0], ellipseData.transform, ellipseData.pivot);
return ellipseData;
}
private static function parseSkinData(skinXML:XML, data:SkeletonData):SkinData
{
var skinData:SkinData = new SkinData();
skinData.name = skinXML.@[ConstValues.A_NAME];
for each(var slotXML:XML in skinXML[ConstValues.SLOT])
{
skinData.addSlotData(parseSlotData(slotXML, data));
}
return skinData;
}
private static function parseSlotData(slotXML:XML, data:SkeletonData):SlotData
{
var slotData:SlotData = new SlotData();
slotData.name = slotXML.@[ConstValues.A_NAME];
slotData.parent = slotXML.@[ConstValues.A_PARENT];
slotData.zOrder = getNumber(slotXML, ConstValues.A_Z_ORDER, 0) || 0;
slotData.blendMode = slotXML.@[ConstValues.A_BLENDMODE];
for each(var displayXML:XML in slotXML[ConstValues.DISPLAY])
{
slotData.addDisplayData(parseDisplayData(displayXML, data));
}
return slotData;
}
private static function parseDisplayData(displayXML:XML, data:SkeletonData):DisplayData
{
var displayData:DisplayData = new DisplayData();
displayData.name = displayXML.@[ConstValues.A_NAME];
displayData.type = displayXML.@[ConstValues.A_TYPE];
displayData.pivot = data.addSubTexturePivot(
0,
0,
displayData.name
);
parseTransform(displayXML[ConstValues.TRANSFORM][0], displayData.transform, displayData.pivot);
return displayData;
}
/** @private */
dragonBones_internal static function parseAnimationData(animationXML:XML, armatureData:ArmatureData, frameRate:uint, isGlobalData:Boolean):AnimationData
{
var animationData:AnimationData = new AnimationData();
animationData.name = animationXML.@[ConstValues.A_NAME];
animationData.frameRate = frameRate;
animationData.duration = Math.round((int(animationXML.@[ConstValues.A_DURATION]) || 1) * 1000 / frameRate);
animationData.playTimes = int(getNumber(animationXML, ConstValues.A_LOOP, 1));
animationData.fadeTime = getNumber(animationXML, ConstValues.A_FADE_IN_TIME, 0) || 0;
animationData.scale = getNumber(animationXML, ConstValues.A_SCALE, 1) || 0;
//use frame tweenEase, NaN
//overwrite frame tweenEase, [-1, 0):ease in, 0:line easing, (0, 1]:ease out, (1, 2]:ease in out
animationData.tweenEasing = getNumber(animationXML, ConstValues.A_TWEEN_EASING, NaN);
animationData.autoTween = getBoolean(animationXML, ConstValues.A_AUTO_TWEEN, true);
for each(var frameXML:XML in animationXML[ConstValues.FRAME])
{
var frame:Frame = parseTransformFrame(frameXML, frameRate, isGlobalData);
animationData.addFrame(frame);
}
parseTimeline(animationXML, animationData);
var lastFrameDuration:int = animationData.duration;
for each(var timelineXML:XML in animationXML[ConstValues.TIMELINE])
{
var timeline:TransformTimeline = parseTransformTimeline(timelineXML, animationData.duration, frameRate, isGlobalData);
lastFrameDuration = Math.min(lastFrameDuration, timeline.frameList[timeline.frameList.length - 1].duration);
animationData.addTimeline(timeline);
}
if(animationData.frameList.length > 0)
{
lastFrameDuration = Math.min(lastFrameDuration, animationData.frameList[animationData.frameList.length - 1].duration);
}
animationData.lastFrameDuration = lastFrameDuration;
DBDataUtil.addHideTimeline(animationData, armatureData);
DBDataUtil.transformAnimationData(animationData, armatureData, isGlobalData);
return animationData;
}
private static function parseTransformTimeline(timelineXML:XML, duration:int, frameRate:uint, isGlobalData:Boolean):TransformTimeline
{
var timeline:TransformTimeline = new TransformTimeline();
timeline.name = timelineXML.@[ConstValues.A_NAME];
timeline.scale = getNumber(timelineXML, ConstValues.A_SCALE, 1) || 0;
timeline.offset = getNumber(timelineXML, ConstValues.A_OFFSET, 0) || 0;
timeline.originPivot.x = getNumber(timelineXML, ConstValues.A_PIVOT_X, 0) || 0;
timeline.originPivot.y = getNumber(timelineXML, ConstValues.A_PIVOT_Y, 0) || 0;
timeline.duration = duration;
for each(var frameXML:XML in timelineXML[ConstValues.FRAME])
{
var frame:TransformFrame = parseTransformFrame(frameXML, frameRate, isGlobalData);
timeline.addFrame(frame);
}
parseTimeline(timelineXML, timeline);
return timeline;
}
private static function parseMainFrame(frameXML:XML, frameRate:uint):Frame
{
var frame:Frame = new Frame();
parseFrame(frameXML, frame, frameRate);
return frame;
}
private static function parseTransformFrame(frameXML:XML, frameRate:uint, isGlobalData:Boolean):TransformFrame
{
var frame:TransformFrame = new TransformFrame();
parseFrame(frameXML, frame, frameRate);
frame.visible = !getBoolean(frameXML, ConstValues.A_HIDE, false);
//NaN:no tween, 10:auto tween, [-1, 0):ease in, 0:line easing, (0, 1]:ease out, (1, 2]:ease in out
frame.tweenEasing = getNumber(frameXML, ConstValues.A_TWEEN_EASING, 10);
frame.tweenRotate = int(getNumber(frameXML, ConstValues.A_TWEEN_ROTATE,0));
frame.tweenScale = getBoolean(frameXML, ConstValues.A_TWEEN_SCALE, true);
frame.displayIndex = int(getNumber(frameXML, ConstValues.A_DISPLAY_INDEX, 0));
//如果为NaN,则说明没有改变过zOrder
frame.zOrder = getNumber(frameXML, ConstValues.A_Z_ORDER, isGlobalData ? NaN : 0);
parseTransform(frameXML[ConstValues.TRANSFORM][0], frame.transform, frame.pivot);
if(isGlobalData)//绝对数据
{
frame.global.copy(frame.transform);
}
frame.scaleOffset.x = getNumber(frameXML, ConstValues.A_SCALE_X_OFFSET, 0) || 0;
frame.scaleOffset.y = getNumber(frameXML, ConstValues.A_SCALE_Y_OFFSET, 0) || 0;
var colorTransformXML:XML = frameXML[ConstValues.COLOR_TRANSFORM][0];
if(colorTransformXML)
{
frame.color = new ColorTransform();
parseColorTransform(colorTransformXML, frame.color);
}
return frame;
}
private static function parseTimeline(timelineXML:XML, timeline:Timeline):void
{
var position:int = 0;
var frame:Frame;
for each(frame in timeline.frameList)
{
frame.position = position;
position += frame.duration;
}
if(frame)
{
frame.duration = timeline.duration - frame.position;
}
}
private static function parseFrame(frameXML:XML, frame:Frame, frameRate:uint):void
{
frame.duration = Math.round((int(frameXML.@[ConstValues.A_DURATION]) || 1) * 1000 / frameRate);
frame.action = frameXML.@[ConstValues.A_ACTION];
frame.event = frameXML.@[ConstValues.A_EVENT];
frame.sound = frameXML.@[ConstValues.A_SOUND];
}
private static function parseTransform(transformXML:XML, transform:DBTransform, pivot:Point = null):void
{
if(transformXML)
{
if(transform)
{
transform.x = getNumber(transformXML, ConstValues.A_X, 0) || 0;
transform.y = getNumber(transformXML, ConstValues.A_Y, 0) || 0;
transform.skewX = getNumber(transformXML, ConstValues.A_SKEW_X, 0) * ConstValues.ANGLE_TO_RADIAN || 0;
transform.skewY = getNumber(transformXML, ConstValues.A_SKEW_Y, 0) * ConstValues.ANGLE_TO_RADIAN || 0;
transform.scaleX = getNumber(transformXML, ConstValues.A_SCALE_X, 1) || 0;
transform.scaleY = getNumber(transformXML, ConstValues.A_SCALE_Y, 1) || 0;
}
if(pivot)
{
pivot.x = getNumber(transformXML, ConstValues.A_PIVOT_X, 0) || 0;
pivot.y = getNumber(transformXML, ConstValues.A_PIVOT_Y, 0) || 0;
}
}
}
private static function parseColorTransform(colorTransformXML:XML, colorTransform:ColorTransform):void
{
if(colorTransformXML)
{
if(colorTransform)
{
colorTransform.alphaOffset = int(colorTransformXML.@[ConstValues.A_ALPHA_OFFSET]);
colorTransform.redOffset = int(colorTransformXML.@[ConstValues.A_RED_OFFSET]);
colorTransform.greenOffset = int(colorTransformXML.@[ConstValues.A_GREEN_OFFSET]);
colorTransform.blueOffset = int(colorTransformXML.@[ConstValues.A_BLUE_OFFSET]);
colorTransform.alphaMultiplier = int(colorTransformXML.@[ConstValues.A_ALPHA_MULTIPLIER]) * 0.01;
colorTransform.redMultiplier = int(colorTransformXML.@[ConstValues.A_RED_MULTIPLIER]) * 0.01;
colorTransform.greenMultiplier = int(colorTransformXML.@[ConstValues.A_GREEN_MULTIPLIER]) * 0.01;
colorTransform.blueMultiplier = int(colorTransformXML.@[ConstValues.A_BLUE_MULTIPLIER]) * 0.01;
}
}
}
private static function getBoolean(data:XML, key:String, defaultValue:Boolean):Boolean
{
if(data && data.@[key].length() > 0)
{
switch(String(data.@[key]))
{
case "0":
case "NaN":
case "":
case "false":
case "null":
case "undefined":
return false;
case "1":
case "true":
default:
return true;
}
}
return defaultValue;
}
private static function getNumber(data:XML, key:String, defaultValue:Number):Number
{
if(data && data.@[key].length() > 0)
{
switch(String(data.@[key]))
{
case "NaN":
case "":
case "false":
case "null":
case "undefined":
return NaN;
default:
return Number(data.@[key]);
}
}
return defaultValue;
}
}
} |
package
{
import flash.display.Bitmap;
/**
* ...
* @author UnknownGuardian
*/
public class Overlay extends OverlayScreenBar
{
public function Overlay()
{
mouseEnabled = false;
}
public function frame():void
{
bar.y += 4;
if (bar.y > stage.stageHeight + 300)
{
bar.y = -bar.height;
}
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.automation.delegates.charts
{
import flash.display.DisplayObject;
import flash.geom.Point;
import mx.automation.Automation;
import mx.charts.ChartItem;
import mx.charts.series.PieSeries;
import mx.charts.series.items.PieSeriesItem;
import mx.core.IFlexDisplayObject;
import mx.core.mx_internal;
use namespace mx_internal;
[Mixin]
/**
*
* Defines the methods and properties required to perform instrumentation for the
* LineSeries class.
*
* @see mx.charts.series.LineSeries
*
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class PieSeriesAutomationImpl extends SeriesAutomationImpl
{
include "../../../core/Version.as";
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
/**
* Registers the delegate class for a component class with automation manager.
*
* @param root The SystemManger of the application.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function init(root:DisplayObject):void
{
Automation.registerDelegateClass(PieSeries, PieSeriesAutomationImpl);
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
* @param obj PieSeries object to be automated.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function PieSeriesAutomationImpl(obj:PieSeries)
{
super(obj);
pieSeries = obj;
}
/**
* @private
*/
private var pieSeries:PieSeries;
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function getChartItemLocation(item:ChartItem):Point
{
if (item is PieSeriesItem)
{
var aItem:PieSeriesItem = item as PieSeriesItem;
var startAngle:Number = aItem.startAngle - pieSeries.startAngle ;
var a:Number = startAngle + pieSeries.startAngle * Math.PI/180 + aItem.angle/2;
var inr:Number = pieSeries.getInnerRadiusInPixels();
var xpos:Number = aItem.origin.x + Math.cos(a)*(inr + (pieSeries.getRadiusInPixels()-inr)*.5);
var ypos:Number = aItem.origin.y - Math.sin(a)*(inr + (pieSeries.getRadiusInPixels()-inr)*.5);
var p:Point = new Point(xpos,ypos);
p = pieSeries.localToGlobal(p);
p = pieSeries.owner.globalToLocal(p);
return p;
}
return super.getChartItemLocation(item);
}
}
} |
/*
Copyright 2008-2011 by the authors of asaplibrary, http://asaplibrary.org
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 org.asaplibrary.data.xml {
import flash.events.Event;
import flash.utils.getQualifiedClassName;
/**
Event class for use with the Service class. Listen to the generic event type to receive these events.
The event has room for both a list of objects as result of a load operation, or a single object. It is left to the implementation of an extension of Service to determine which of these are used.
@example
<code>myService.addEventListener(ServiceEvent._EVENT, handleServiceEvent);</code>
*/
public class ServiceEvent extends Event {
/** Generic type of event */
public static const _EVENT : String = "onServiceEvent";
/** subtype of event sent when loading and parsing went ok */
public static const COMPLETE : String = "loadComplete";
/** subtype of event sent when all requests have completed; does not check for errors */
public static const ALL_COMPLETE : String = "allLoadComplete";
/** subtype of event sent when there was an error loading the data */
public static var LOAD_ERROR : String = "loadError";
/** subtype of event sent when there was an error parsing the data */
public static var PARSE_ERROR : String = "parseError";
/** subtype of event */
public var subtype : String;
/** name of original request*/
public var name : String;
/** if applicable, a single array of typed data objects */
public var list : Array;
/** if applicable, a single object */
public var object : Object;
/** if applicable, a string describing the error */
public var error : String;
public function ServiceEvent(inSubtype : String, inName : String = null, inList : Array = null, inObject : Object = null, inError : String = null) {
super(_EVENT);
subtype = inSubtype;
name = inName;
list = inList;
object = inObject;
error = inError;
}
override public function clone() : Event {
return new ServiceEvent(subtype, name, list, object, error);
}
override public function toString() : String {
return getQualifiedClassName(this) + ": subtype = " + subtype + ", name = " + name;
}
}
}
|
package h2olib.control
{
import flash.events.Event;
import flash.events.FocusEvent;
import mx.controls.TextInput;
/**
* The <code>PromptingTextInput</code> component is a small enhancement to
* standard <code>TextInput</code>. It adds the ability to specify a prompt
* value that displays when the text is empty, similar to how the prompt
* property of the <code>ComboBox</code> behaves when there is no selected value.
*/
public class PromptingTextInput extends TextInput
{
/** Flag to indicate if the text is empty or not */
private var _textEmpty:Boolean;
/**
* Flag to prevent us from re-inserting the prompt if the text is cleared
* while the component still has focus.
*/
private var _currentlyFocused:Boolean = false;
/**
* Constructor
*/
public function PromptingTextInput()
{
_textEmpty = true;
addEventListener( Event.CHANGE, handleChange );
addEventListener( FocusEvent.FOCUS_IN, handleFocusIn );
addEventListener( FocusEvent.FOCUS_OUT, handleFocusOut );
}
// ==============================================================
// prompt
// ==============================================================
/** Storage for the prompt property */
private var _prompt:String = "";
/**
* The string to use as the prompt value
*/
public function get prompt():String
{
return _prompt;
}
[Bindable]
public function set prompt( value:String ):void
{
_prompt = value;
invalidateProperties();
}
// ==============================================================
// promptFormat
// ==============================================================
/** Storage for the promptFormat property */
private var _promptFormat:String = '<font color="#999999"><i>[prompt]</i></font>';
/**
* A format string to specify how the prompt is displayed. This is typically
* an HTML string that can set the font color and style. Use <code>[prompt]</code>
* within the string as a replacement token that will be replaced with the actual
* prompt text.
*
* The default value is "<font color="#999999"><i>[prompt]</i></font>"
*/
public function get promptFormat():String
{
return _promptFormat;
}
public function set promptFormat( value:String ):void
{
_promptFormat = value;
// Check to see if the replacement code is found in the new format string
if ( _promptFormat.indexOf( "[prompt]" ) < 0 )
{
// TODO: Log error with the logging framework, or just use trace?
//trace( "PromptingTextInput warning: prompt format does not contain [prompt] replacement code." );
}
invalidateDisplayList();
}
// ==============================================================
// text
// ==============================================================
/**
* Override the behavior of text so that it doesn't take into account
* the prompt. If the prompt is displaying, the text is just an empty
* string.
*/
[Bindable("textChanged")]
[CollapseWhiteSpace]
[NonCommittingChangeEvent("change")]
override public function set text( value:String ):void
{
// changed the test to also test for null values, not just 0 length
// if we were passed undefined or null then the zero length test would
// still return false. - Doug McCune
_textEmpty = (!value) || value.length == 0;
super.text = value;
invalidateDisplayList();
}
override public function get text():String
{
// If the text has changed
if ( _textEmpty )
{
// Skip the prompt text value
return "";
}
else
{
return super.text;
}
}
/**
* We store a local copy of displayAsPassword. We need to keep this so that we can
* change it to false if we're showing the prompt. Then we change it back (if it was
* set to true) once we're no longer showing the prompt.
*/
private var _displayAsPassword:Boolean = false;
override public function set displayAsPassword(value:Boolean):void {
_displayAsPassword = value;
super.displayAsPassword = value;
}
override public function get displayAsPassword():Boolean {
return _displayAsPassword;
}
// ==============================================================
// overriden methods
// ==============================================================
/**
* @private
*
* Determines if the prompt needs to be displayed.
*/
override protected function updateDisplayList( unscaledWidth:Number, unscaledHeight:Number ):void
{
// If the text is empty and a prompt value is set and the
// component does not currently have focus, then the component
// needs to display the prompt
if ( _textEmpty && _prompt != "" && !_currentlyFocused )
{
if ( _promptFormat == "" )
{
super.text = _prompt;
}
else
{
super.htmlText = _promptFormat.replace( /\[prompt\]/g, _prompt );
}
if(super.displayAsPassword) {
//If we're showing the prompt and we have displayAsPassword set then
//we need to set it to false while the prompt is showing.
var oldVal:Boolean = _displayAsPassword;
super.displayAsPassword = false;
_displayAsPassword = oldVal;
}
}
else {
if(super.displayAsPassword != _displayAsPassword) {
super.displayAsPassword = _displayAsPassword;
}
}
super.updateDisplayList( unscaledWidth, unscaledHeight );
var pattern:RegExp = /<TEXTFORMAT.*TEXTFORMAT>/;
if(pattern.test(super.htmlText)) {
super.htmlText = super.text;
}
}
// ==============================================================
// event handlers
// ==============================================================
/**
* @private
*/
protected function handleChange( event:Event ):void
{
_textEmpty = super.text.length == 0;
}
/**
* @private
*
* When the component recevies focus, check to see if the prompt
* needs to be cleared or not.
*/
protected function handleFocusIn( event:FocusEvent ):void
{
_currentlyFocused = true;
// If the text is empty, clear the prompt
if ( _textEmpty )
{
super.htmlText = "";
// KLUDGE: Have to validate now to avoid a bug where the format
// gets "stuck" even though the text gets cleared.
validateNow();
}
}
/**
* @private
*
* When the component loses focus, check to see if the prompt needs
* to be displayed or not.
*/
protected function handleFocusOut( event:FocusEvent ):void
{
_currentlyFocused = false;
// If the text is empty, put the prompt back
invalidateDisplayList();
}
} // end class
} // en package
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.automation.delegates.components
{
import flash.display.DisplayObject;
import mx.automation.Automation;
import mx.core.mx_internal;
import spark.automation.delegates.components.supportClasses.SparkSkinnableTextBaseAutomationImpl;
import spark.components.TextInput;
use namespace mx_internal;
[Mixin]
/**
*
* Defines methods and properties required to perform instrumentation for the
* TextInput control.
*
* @see spark.components.TextInput
*
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
public class SparkTextInputAutomationImpl extends SparkSkinnableTextBaseAutomationImpl
{
include "../../../core/Version.as";
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
/**
* Registers the delegate class for a component class with automation manager.
*
* @param root The SystemManger of the application.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
public static function init(root:DisplayObject):void
{
Automation.registerDelegateClass(spark.components.TextInput, SparkTextInputAutomationImpl);
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
* @param obj TextInput object to be automated.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 4
*/
public function SparkTextInputAutomationImpl(obj:spark.components.TextInput)
{
super(obj);
}
/**
* @private
* storage for the owner component
*/
protected function get textInput():spark.components.TextInput
{
return uiComponent as spark.components.TextInput;
}
/**
* @private
*/
override public function get automationName():String
{
return textInput.id || super.automationName;
}
}
} |
/*
Copyright aswing.org, see the LICENCE.txt.
*/
package org.aswing.table{
/**
* Texts in this cell is selectable.
*/
public class SelectablePoorTextCell extends PoorTextCell{
public function SelectablePoorTextCell(){
super();
textField.mouseEnabled = true;
textField.selectable = true;
}
}
} |
package player.commands
{
import flash.geom.Point;
public class SetSelfPlayerPosAndDirCommand extends BasePlayerCommand
{
public var position:Point;
public var direction:int;
public function SetSelfPlayerPosAndDirCommand(param1:Point, param2:int = -1)
{
super();
this.position = param1;
this.direction = param2;
}
}
}
|
/* AS3
Copyright 2008
*/
package com.neopets.util.text
{
import flash.display.MovieClip;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.text.TextField;
import virtualworlds.lang.TranslationManager;
/**
* This class uses a movie clip shell and bitmap manipulation to get around a bug where dynamic
* text fields become hidden when rotated.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @NP9 Game System
*
* @author David Cary
* @since 1.05.2010
*/
public class BitmapText extends MovieClip {
//--------------------------------------
// CLASS CONSTANTS
//--------------------------------------
//--------------------------------------
// VARIABLES
//--------------------------------------
// protected variables
protected var _textField:TextField;
protected var _translationID:String;
protected var _translatedText:String;
protected var _bitmap:Bitmap;
//--------------------------------------
// CONSTRUCTOR
//--------------------------------------
/**
* @Constructor
*/
public function BitmapText():void {
// create bitmap element
_bitmap = new Bitmap();
_bitmap.smoothing = true;
addChild(_bitmap);
// search for textfield
var child:DisplayObject;
for(var i:int = 0; i < numChildren; i++) {
child = getChildAt(i);
if(child is TextField) {
textField = child as TextField;
break;
}
}
}
//--------------------------------------
// GETTER/SETTERS
//--------------------------------------
public function get bitmap():Bitmap { return _bitmap; }
public function get translatedText():String { return _translatedText; }
public function set translatedText(str:String) {
if(_translatedText != str) {
_translatedText = str;
updateText();
}
}
public function get textField():TextField { return _textField; }
public function set textField(txt:TextField) {
if(txt != _textField) {
_textField = txt;
updateText();
}
}
public function get translationID():String { return _translationID; }
public function set translationID(id:String) {
if(_translationID != id) {
_translationID = id;
// get translation
var translator:TranslationManager = TranslationManager.instance;
_translatedText = translator.getTranslationOf(_translationID);
updateText();
}
}
//--------------------------------------
// PUBLIC METHODS
//--------------------------------------
/**
* This function makes sure our displayed bitmap matches our text.
*/
public function updateText():void {
// update text
if(_textField != null && _translatedText != null) {
_textField.htmlText = _translatedText;
}
// copy textfield to bitmap
if(_bitmap != null) {
if(_textField != null) {
// draw textfield to bitmap data
var bmd:BitmapData = new BitmapData(_textField.width,_textField.height,true,0x00FFFFFF);
bmd.draw(_textField);
// assign map data to display object
_bitmap.bitmapData = bmd;
// pass position, rotation, ect.. from textfield to bitmap
_bitmap.transform.matrix = _textField.transform.matrix;
// hide text
_textField.visible = false;
} else {
// clear bitmap
_bitmap.bitmapData = null;
}
}
}
//--------------------------------------
// EVENT HANDLERS
//--------------------------------------
//--------------------------------------
// PRIVATE & PROTECTED INSTANCE METHODS
//--------------------------------------
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright 2016 Prominic.NET, 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
//
// Author: Prominic.NET, Inc.
// No warranty of merchantability or fitness of any kind.
// Use this software at your own risk.
////////////////////////////////////////////////////////////////////////////////
package actionScripts.valueObjects
{
/**
* Implementation of Command interface from Language Server Protocol
*
* <p><strong>DO NOT</strong> add new properties or methods to this class
* that are specific to Moonshine IDE or to a particular language. Create a
* subclass for new properties or create a utility function for methods.</p>
*
* @see https://microsoft.github.io/language-server-protocol/specification#command
*/
public class Command
{
/**
* Title of the command, like `save`.
*/
public var title: String = "";
/**
* The identifier of the actual command handler.
*/
public var command: String = "";
/**
* Arguments that the command handler should be invoked with.
*/
public var arguments: Array;
public function Command()
{
}
public static function parse(original:Object):Command
{
var vo:Command = new Command();
vo.title = original.title;
vo.command = original.command;
vo.arguments = original.arguments;
return vo;
}
}
} |
/**
* <p>Original Author: Daniel Freeman</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 asfiles {
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.ui.Mouse;
import flash.utils.Timer;
public class Cursor extends Sprite {
static public function changecursor(mystage:Stage,mde:Sprite=null,setToDefault:Boolean=false,rect:Rectangle=null):void {mystage.dispatchEvent(new MyEvent(CURSOR,mde,setToDefault,rect));}
static public function cursorhint(mystage:Stage,txt:String=''):void {mystage.dispatchEvent(new MyEvent(HINT,txt));}
static public function delayhint(mystage:Stage,txt:String=''):void {mystage.dispatchEvent(new MyEvent(DELAYHINT,txt));}
static public function infront(mystage:Stage,what:*=null,pt:Point=null,dontmove:Boolean=false):void {mystage.dispatchEvent(new MyEvent(INFRONT,what,pt,dontmove));}
public static var HINT_Y:Number = 0;
static private const CURSOR:String='Cursor.cursor';
static private const HINT:String='Cursor.hint';
static private const DELAYHINT:String='Cursor.delayhint';
static public const INFRONT:String='Cursor.infront';
private const delay:int=500;
private var hint:HintText;
private var thing:DisplayObject=null;
private var mycursor:Sprite=null;
private var timer:Timer = new Timer(delay, 1);
private var yesfunction:Function;
private var nofunction:Function;
protected var _defaultCursor:Sprite=null;
public function Cursor(screen:Sprite) {
hint=new HintText(this);
screen.addChild(this);x=y=0;mouseEnabled=hint.visible=hint.mouseEnabled=false;
stage.addEventListener(CURSOR,echangecursor);
stage.addEventListener(HINT,ecursorhint);
stage.addEventListener(DELAYHINT,edelayhint);
stage.addEventListener(INFRONT,einfront);
timer.addEventListener(TimerEvent.TIMER,showhint);
}
private function einfront(ev:MyEvent):void {
var wht:DisplayObject=ev.parameters[0];
var pt:Point=ev.parameters[1];
var dontmove:Boolean=ev.parameters[2];
if (wht==null) {if (thing!=null) thing.visible=false;}
else {
if (wht!=thing) {
if (thing!=null) removeChild(thing);
addChild(thing=wht);
}
thing.visible=true;
if (pt!=null) {
if (dontmove) {thing.x=pt.x;thing.y=pt.y;}
else {
if (pt.x+thing.width>stage.stageWidth) thing.x=pt.x-thing.width; else thing.x=pt.x;
if (pt.y+thing.height>stage.stageHeight) thing.y=pt.y-thing.height-20; else thing.y=pt.y+4;
}
}
setChildIndex(thing,numChildren-1);
}
}
private function ecursorhint(ev:MyEvent):void {
var txt:String=ev.parameters[0];
if (txt==null || txt=='') {
hint.visible=false;
stage.removeEventListener(MouseEvent.MOUSE_MOVE,mousemove);
} else {
hint.text=txt;
hint.x=mouseX-hint.width*(HINT_Y==0 ? 1 : 0.5);hint.y=mouseY-HINT_Y;
if (hint.x<0) hint.x=0; else if (hint.x+hint.width>stage.stageWidth) hint.x=stage.stageWidth-hint.width;
hint.visible=true;
stage.addEventListener(MouseEvent.MOUSE_MOVE,mousemove);
}
}
private function edelayhint(ev:MyEvent):void {
var txt:String=ev.parameters[0];
if (txt==null || txt=='') {
hint.visible=false;
timer.stop();
} else {
hint.text=txt;
timer.start();
}
}
private function showhint(ev:TimerEvent):void {
hint.x=mouseX-hint.width/2;
if (hint.x<0) hint.x=0; else if (hint.x+hint.width>stage.stageWidth) hint.x=stage.stageWidth-hint.width;
hint.y=mouseY+16;
if (hint.y+hint.height>stage.stageHeight) hint.y=stage.stageHeight-hint.height-16;
hint.visible=true;
}
private function mousemove(ev:MouseEvent):void {
hint.x=mouseX-hint.width*(HINT_Y==0 ? 1 : 0.5);hint.y=mouseY-HINT_Y;
}
private function echangecursor(ev:MyEvent):void {
var mde:Sprite=ev.parameters[0];
var setToDefault:Boolean=ev.parameters[1];
var rect:Rectangle=ev.parameters[2];
if (setToDefault) _defaultCursor=mde;
if (mde==null) mde=_defaultCursor;
if (mde==null) {
stopDrag();
Mouse.show();
if (mycursor!=null) mycursor.visible=false;
} else {
if (mde!=mycursor) {
if (mycursor!=null && this.contains(mycursor)) removeChild(mycursor);
addChild(mde);
mycursor=mde;
}
mycursor.startDrag(true,rect);
Mouse.hide();
mycursor.visible=true;
mycursor.x=mouseX;
mycursor.y=mouseY;
}
}
public function destructor():void {
stage.removeEventListener(CURSOR,echangecursor);
stage.removeEventListener(HINT,ecursorhint);
stage.removeEventListener(DELAYHINT,edelayhint);
stage.removeEventListener(INFRONT,einfront);
timer.removeEventListener(TimerEvent.TIMER,showhint);
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.controls.dataGridClasses
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.utils.Dictionary;
import mx.controls.TextInput;
import mx.controls.listClasses.IListItemRenderer;
import mx.core.ClassFactory;
import mx.core.ContextualClassFactory;
import mx.core.IEmbeddedFontRegistry;
import mx.core.IFactory;
import mx.core.IFlexModuleFactory;
import mx.core.IIMESupport;
import mx.core.Singleton;
import mx.core.mx_internal;
import mx.styles.CSSStyleDeclaration;
import mx.styles.StyleManager;
import mx.utils.StringUtil;
use namespace mx_internal;
//--------------------------------------
// Styles
//--------------------------------------
include "../../styles/metadata/TextStyles.as";
/**
* The Background color of the column.
* The default value is <code>undefined</code>, which means it uses the value of the
* <code>backgroundColor</code> style of the associated DataGrid control.
* The default value for the DataGrid control is <code>0xFFFFFF</code>.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="backgroundColor", type="uint", format="Color", inherit="no")]
/**
* The name of a CSS style declaration for controlling other aspects of
* the appearance of the column headers.
* The default value is <code>undefined</code>, which means it uses the value of the
* <code>headerStyleName</code> style of the associated DataGrid control.
* The default value for the DataGrid control is
* <code>".dataGridStyles"</code>.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="headerStyleName", type="String", inherit="no")]
/**
* The number of pixels between the container's left border and its content
* area.
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="paddingLeft", type="Number", format="Length", inherit="no")]
/**
* The number of pixels between the container's right border and its content
* area.
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Style(name="paddingRight", type="Number", format="Length", inherit="no")]
/**
* The DataGridColumn class describes a column in a DataGrid control.
* There is one DataGridColumn per displayable column, even if a column
* is hidden or off-screen.
* The data provider items of a DataGrid control
* can contain properties that are not displayed
* and, therefore, do not need a DataGridColumn.
* A DataGridColumn allows specification of the color and font of the text
* in a column; what kind of component displays the data for the column;
* whether the column is editable, sortable, or resizable;
* and the text for the column header.
*
* <p><strong>Notes:</strong><ul>
* <li>A DataGridColumn only holds information about a column;
* it is not the parent of the item renderers in the column.</li>
* <li>If you specify a DataGridColumn class without a <code>dataField</code>
* property, you must specify a <code>sortCompareFunction</code>
* property. Otherwise, sort operations may cause run-time errors.</li></ul>
* </p>
*
* @mxml
*
* <p>You use the <code><mx.DataGridColumn></code> tag to configure a column
* of a DataGrid control.
* You specify the <code><mx.DataGridColumn></code> tag as a child
* of the columns property in MXML.
* The <code><mx.DataGridColumn></code> tag inherits all of the
* tag attributes of its superclass, and adds the following tag attributes:</p>
*
* <pre>
* <mx:DataGridColumn
* <b>Properties </b>
* dataField="<i>No default</i>"
* dataTipField="<i>No default</i>"
* dataTipFunction="<i>No default</i>"
* editable="true|false"
* editorDataField="text"
* editorHeightOffset="0"
* editorUsesEnterKey="false|true"
* editorWidthOffset="0"
* editorXOffset="0"
* editorYOffset="0"
* headerRenderer="DataGridItemRenderer"
* headerText="<i>No default</i>"
* headerWordWrap="undefined"
* imeMode="null"
* itemEditor="TextInput"
* itemRenderer="DataGridItemRenderer"
* labelFunction="<i>No default</i>"
* minWidth="20"
* rendererIsEditor="false|true"
* resizable="true|false"
* showDataTips="false|true"
* sortable="true|false"
* sortCompareFunction="<i>No default</i>"
* sortDescending="false|true"
* visible="true|false"
* width="100"
* wordWrap="false|true"
*
* <b>Styles</b>
* backgroundColor="0xFFFFFF"
* color="<i>No default.</i>"
* disabledColor="0xAAB3B3"
* fontAntiAliasType="advanced"
* fontFamily="<i>No default</i>"
* fontGridFitType="pixel"
* fontSharpness="0"
* fontSize="<i>No default</i>"
* fontStyle="normal|italic"
* fontThickness="0"
* fontWeight="normal|bold"
* headerStyleName="<i>No default</i>"
* paddingLeft="0"
* paddingRight="0"
* textAlign="right|center|left"
* textDecoration="none|underline"
* textIndent="0"
* />
* </pre>
* </p>
*
* @see mx.controls.DataGrid
*
* @see mx.styles.CSSStyleDeclaration
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class DataGridColumn extends CSSStyleDeclaration implements IIMESupport
{
include "../../core/Version.as";
//--------------------------------------------------------------------------
//
// Class properties
//
//--------------------------------------------------------------------------
//----------------------------------
// embeddedFontRegistry
//----------------------------------
private static var noEmbeddedFonts:Boolean;
/**
* @private
* Storage for the embeddedFontRegistry property.
* This gets initialized on first access,
* not at static initialization time, in order to ensure
* that the Singleton registry has already been initialized.
*/
private static var _embeddedFontRegistry:IEmbeddedFontRegistry;
/**
* @private
* A reference to the embedded font registry.
* Single registry in the system.
* Used to look up the moduleFactory of a font.
*/
private static function get embeddedFontRegistry():IEmbeddedFontRegistry
{
if (!_embeddedFontRegistry && !noEmbeddedFonts)
{
try
{
_embeddedFontRegistry = IEmbeddedFontRegistry(
Singleton.getInstance("mx.core::IEmbeddedFontRegistry"));
}
catch (e:Error)
{
noEmbeddedFonts = true;
}
}
return _embeddedFontRegistry;
}
private static var _defaultItemEditorFactory:IFactory;
mx_internal static function get defaultItemEditorFactory():IFactory
{
if (!_defaultItemEditorFactory)
_defaultItemEditorFactory = new ClassFactory(TextInput);
return _defaultItemEditorFactory;
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @param columnName The name of the field in the data provider
* associated with the column, and the text for the header cell of this
* column. This is equivalent to setting the <code>dataField</code>
* and <code>headerText</code> properties.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function DataGridColumn(columnName:String = null)
{
super();
if (columnName)
{
dataField = columnName;
headerText = columnName;
}
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @private
* The DataGrid that owns this column.
*/
mx_internal var owner:DataGridBase;
/**
* @private
*/
mx_internal var explicitWidth:Number;
/**
* @private
* cached header renderer so we don't have to keep
* making new ones
*/
mx_internal var cachedHeaderRenderer:IListItemRenderer;
/**
* @private
* Holds the last recorded value of the module factory used to create the font.
*/
private var oldEmbeddedFontContext:IFlexModuleFactory = null;
private var oldHeaderEmbeddedFontContext:IFlexModuleFactory = null;
/**
* @private
*
* Columns has complex data field named.
*/
protected var hasComplexFieldName:Boolean = false;
/**
* @private
*
* Array of split complex field name derived when set so that it is not derived each time.
*/
protected var complexFieldNameComponents:Array;
//--------------------------------------------------------------------------
//
// Overridden properties
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// sortDescending
//----------------------------------
/**
* Indicates whether the column sort is
* in ascending order, <code>false</code>,
* or <code>descending</code> order, true.
*
* <p>Setting this property does not start a sort; it only sets the sort direction.
* Click on the column header to perform the sort.</p>
*
* @default false;
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var sortDescending:Boolean = false;
//----------------------------------
// itemRenderer
//----------------------------------
/**
* @private
* Storage for the itemRenderer property.
*/
private var _itemRenderer:IFactory;
private var _contextItemRenderer:IFactory;
[Bindable("itemRendererChanged")]
[Inspectable(category="Other")]
/**
* The class factory for item renderer instances that display the
* data for each item in the column.
* You can specify a drop-in item renderer,
* an inline item renderer, or a custom item renderer component as the
* value of this property.
*
* <p>The default item renderer is the DataGridItemRenderer class,
* which displays the item data as text. </p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get itemRenderer():IFactory
{
return _itemRenderer;
}
/**
* @private
*/
public function set itemRenderer(value:IFactory):void
{
_itemRenderer = value;
// this is expensive... but unless set after init (not recommended), ok.
if (owner)
{
owner.invalidateList();
owner.columnRendererChanged(this);
_contextItemRenderer = null;
}
dispatchEvent(new Event("itemRendererChanged"));
}
//----------------------------------
// colNum
//----------------------------------
/**
* @private
* The zero-based index of this column as it is displayed in the grid.
* It is not related to the structure of the data being displayed.
* In MXML, the default order of the columns is the order of the
* <code>mx:DataGridColumn</code> tags.
*/
mx_internal var colNum:Number;
//----------------------------------
// dataField
//----------------------------------
/**
* @private
* Storage for the dataField property.
*/
private var _dataField:String;
[Inspectable(category="General", defaultValue="")]
/**
* The name of the field or property in the data provider item associated
* with the column.
* Each DataGridColumn control
* requires this property and/or the <code>labelFunction</code> property
* to be set in order to calculate the displayable text for the item
* renderer.
* If the <code>dataField</code>
* and <code>labelFunction</code> properties are set,
* the data is displayed using the <code>labelFunction</code> and sorted
* using the <code>dataField</code>. If the property named in the
* <code>dataField</code> does not exist, the
* <code>sortCompareFunction</code> must be set for the sort to work
* correctly.
*
* <p>This value of this property is not necessarily the String that
* is displayed in the column header. This property is
* used only to access the data in the data provider.
* For more information, see the <code>headerText</code> property.</p>
*
* @see #headerText
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get dataField():String
{
return _dataField;
}
/**
* @private
*/
public function set dataField(value:String):void
{
_dataField = value;
if ( value.indexOf( "." ) != -1 )
{
hasComplexFieldName = true;
complexFieldNameComponents = value.split( "." );
if ( _sortCompareFunction == null )
{
//if the sort field is null, but the user supplied a complex dataField, we will assign a generic
//sort compare that handles this situation. It will yield identical results to the sort created in
//datagrid under normal circumstances
//intentionally not using the setter, the user might still override this or be looking for that change
//we want to this to be purely happen behind the scenes if there is no function provided
_sortCompareFunction = complexColumnSortCompare;
}
}
else
hasComplexFieldName = false;
if (owner)
owner.invalidateList();
}
//----------------------------------
// dataTipField
//----------------------------------
/**
* @private
* Storage for the dataTipField property.
*/
private var _dataTipField:String;
[Bindable("dataTipFieldChanged")]
[Inspectable(category="Advanced", defaultValue="label")]
/**
* The name of the field in the data provider to display as the datatip.
* By default, the DataGrid control looks for a property named
* <code>label</code> on each data provider item and displays it.
* However, if the data provider does not contain a <code>label</code>
* property, you can set the <code>dataTipField</code> property to
* specify a different property.
* For example, you could set the value to "FullName" when a user views a
* set of people's names included from a database.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get dataTipField():String
{
return _dataTipField;
}
/**
* @private
*/
public function set dataTipField(value:String):void
{
_dataTipField = value;
if (owner)
{
owner.invalidateList();
}
dispatchEvent(new Event("dataTipChanged"));
}
//----------------------------------
// dataTipFunction
//----------------------------------
/**
* @private
* Storage for the dataTipFunction property.
*/
private var _dataTipFunction:Function;
[Bindable("dataTipFunctionChanged")]
[Inspectable(category="Advanced")]
/**
* Specifies a callback function to run on each item of the data provider
* to determine its dataTip.
* This property is used by the <code>itemToDataTip</code> method.
*
* <p>By default the control looks for a property named <code>label</code>
* on each data provider item and displays it as its dataTip.
* However, some data providers do not have a <code>label</code> property
* nor do they have another property that you can use for displaying data
* in the rows.
* For example, you might have a data provider that contains a lastName
* and firstName fields, but you want to display full names as the dataTip.
* You can specify a function to the <code>dataTipFunction</code> property
* that returns a single String containing the value of both fields. You
* can also use the <code>dataTipFunction</code> property for handling
* formatting and localization.</p>
*
* <p>The function must take a single Object parameter, containing the
* data provider element, and return a String.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get dataTipFunction():Function
{
return _dataTipFunction;
}
/**
* @private
*/
public function set dataTipFunction(value:Function):void
{
_dataTipFunction = value;
if (owner)
{
owner.invalidateList();
}
dispatchEvent(new Event("labelFunctionChanged"));
}
//----------------------------------
// draggable
//----------------------------------
[Inspectable(category="General")]
/**
* A flag that indicates whether the user is allowed to drag
* the column to a new position
* If <code>true</code>, the user can drag the
* the column headers to a new position
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var draggable:Boolean = true;
//----------------------------------
// editable
//----------------------------------
private var _editable:Boolean = true;
[Inspectable(category="General")]
/**
* A flag that indicates whether the items in the column are editable.
* If <code>true</code>, and the DataGrid's <code>editable</code>
* property is also <code>true</code>, the items in a column are
* editable and can be individually edited
* by clicking on an item or by navigating to the item by using the
* Tab and Arrow keys.
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get editable():Boolean
{
return _editable;
}
/**
* @private
*/
public function set editable(value:Boolean):void
{
_editable = value;
}
//----------------------------------
// itemEditor
//----------------------------------
[Inspectable(category="General")]
/**
* A class factory for the instances of the item editor to use for the
* column, when it is editable.
*
* @default new ClassFactory(mx.controls.TextInput)
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var itemEditor:IFactory = defaultItemEditorFactory;
//----------------------------------
// editorDataField
//----------------------------------
[Inspectable(category="General")]
/**
* The name of the property of the item editor that contains the new
* data for the list item.
* For example, the default <code>itemEditor</code> is
* TextInput, so the default value of the <code>editorDataField</code>
* property is <code>"text"</code>, which specifies the
* <code>text</code> property of the TextInput control.
*
* @default "text"
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var editorDataField:String = "text";
//----------------------------------
// editorHeightOffset
//----------------------------------
[Inspectable(category="General", defaultValue="0")]
/**
* The height of the item editor, in pixels, relative to the size of the
* item renderer. This property can be used to make the editor overlap
* the item renderer by a few pixels to compensate for a border around the
* editor.
* Note that changing these values while the editor is displayed
* will have no effect on the current editor, but will affect the next
* item renderer that opens an editor.
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var editorHeightOffset:Number = 0;
//----------------------------------
// editorWidthOffset
//----------------------------------
[Inspectable(category="General", defaultValue="0")]
/**
* The width of the item editor, in pixels, relative to the size of the
* item renderer. This property can be used to make the editor overlap
* the item renderer by a few pixels to compensate for a border around the
* editor.
* Note that changing these values while the editor is displayed
* will have no effect on the current editor, but will affect the next
* item renderer that opens an editor.
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var editorWidthOffset:Number = 0;
//----------------------------------
// editorXOffset
//----------------------------------
[Inspectable(category="General", defaultValue="0")]
/**
* The x location of the upper-left corner of the item editor,
* in pixels, relative to the upper-left corner of the item.
* This property can be used to make the editor overlap
* the item renderer by a few pixels to compensate for a border around the
* editor.
* Note that changing these values while the editor is displayed
* will have no effect on the current editor, but will affect the next
* item renderer that opens an editor.
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var editorXOffset:Number = 0;
//----------------------------------
// editorYOffset
//----------------------------------
[Inspectable(category="General", defaultValue="0")]
/**
* The y location of the upper-left corner of the item editor,
* in pixels, relative to the upper-left corner of the item.
* This property can be used to make the editor overlap
* the item renderer by a few pixels to compensate for a border around the
* editor.
* Note that changing these values while the editor is displayed
* will have no effect on the current editor, but will affect the next
* item renderer that opens an editor.
*
* @default 0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var editorYOffset:Number = 0;
//----------------------------------
// editorUsesEnterKey
//----------------------------------
[Inspectable(category="General", defaultValue="false")]
/**
* A flag that indicates whether the item editor uses Enter key.
* If <code>true</code> the item editor uses the Enter key and the
* DataGrid will not look for the Enter key and move the editor in
* response.
* Note that changing this value while the editor is displayed
* will have no effect on the current editor, but will affect the next
* item renderer that opens an editor.
*
* @default false.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var editorUsesEnterKey:Boolean = false;
//----------------------------------
// enableIME
//----------------------------------
/**
* A flag that indicates whether the IME should
* be enabled when the component receives focus.
*
* If an editor is up, it will set enableIME
* accordingly.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
* @productversion Flex 4
*/
public function get enableIME():Boolean
{
return false;
}
//----------------------------------
// headerRenderer
//----------------------------------
/**
* @private
* Storage for the headerRenderer property.
*/
private var _headerRenderer:IFactory;
private var _contextHeaderRenderer:IFactory;
[Bindable("headerRendererChanged")]
[Inspectable(category="Other")]
/**
* The class factory for item renderer instances that display the
* column header for the column.
* You can specify a drop-in item renderer,
* an inline item renderer, or a custom item renderer component as the
* value of this property.
*
* <p>The default item renderer is the DataGridItemRenderer class,
* which displays the item data as text. </p>
*
* @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;
// rebuild the headers
if (owner)
{
owner.invalidateList();
owner.columnRendererChanged(this);
_contextHeaderRenderer = null;
}
dispatchEvent(new Event("headerRendererChanged"));
}
//----------------------------------
// headerText
//----------------------------------
/**
* @private
* Storage for the headerText property.
*/
private var _headerText:String;
[Bindable("headerTextChanged")]
[Inspectable(category="General")]
/**
* Text for the header of this column. By default, the DataGrid
* control uses the value of the <code>dataField</code> property
* as the header text.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get headerText():String
{
return (_headerText != null) ? _headerText : dataField;
}
/**
* @private
*/
public function set headerText(value:String):void
{
_headerText = value;
if (owner)
owner.invalidateList();
dispatchEvent(new Event("headerTextChanged"));
}
//----------------------------------
// headerWordWrap
//----------------------------------
/**
* @private
* Storage for the headerWordWrap property.
*/
private var _headerWordWrap:*;
[Inspectable(category="Advanced")]
/**
* A flag that indicates whether text in the header will be
* word wrapped if it doesn't fit on one line.
* If <code>undefined</code>, the DataGrid control's <code>wordWrap</code> property
* is used.
*
* @default undefined
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get headerWordWrap():*
{
return _headerWordWrap;
}
/**
* @private
*/
public function set headerWordWrap(value:*):void
{
_headerWordWrap = value;
if (owner)
{
owner.invalidateList();
}
}
//----------------------------------
// imeMode
//----------------------------------
/**
* @private
* Storage for the imeMode property.
*/
private var _imeMode:String;
[Inspectable(category="Other")]
/**
* Specifies the IME (input method editor) mode.
* The IME enables users to enter text in Chinese, Japanese, and Korean.
* Flex sets the IME mode when the <code>itemFocusIn</code> event occurs,
* and sets it back
* to the previous value when the <code>itemFocusOut</code> event occurs.
* The flash.system.IMEConversionMode class defines constants for
* the valid values for this property.
*
* <p>The default value is null, in which case it uses the value of the
* DataGrid control's <code>imeMode</code> property.</p>
*
* @see flash.system.IMEConversionMode
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get imeMode():String
{
return _imeMode;
}
/**
* @private
*/
public function set imeMode(value:String):void
{
_imeMode = value;
}
//----------------------------------
// rendererIsEditor
//----------------------------------
[Inspectable(category="General", defaultValue="false")]
/**
* A flag that indicates that the item renderer is also an item editor.
* If this property is <code>true</code>, Flex
* ignores the <code>itemEditor</code> property and uses the item
* renderer for that item as the editor.
*
* @default false
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var rendererIsEditor:Boolean = false;
//----------------------------------
// labelFunction
//----------------------------------
/**
* @private
* Storage for the labelFunction property.
*/
private var _labelFunction:Function;
[Bindable("labelFunctionChanged")]
[Inspectable(category="Other")]
/**
* A function that determines the text to display in this column. By default
* the column displays the text for the field in the data that matches the
* column name. However, sometimes you want to display text based on
* more than one field in the data, or display something that does not
* have the format that you want.
* In such a case you specify a callback function using <code>labelFunction</code>.
*
* <p>For the DataGrid control, the method signature has the following form:</p>
*
* <pre>labelFunction(item:Object, column:DataGridColumn):String</pre>
*
* <p>Where <code>item</code> contains the DataGrid item object, and
* <code>column</code> specifies the DataGrid column.</p>
*
* <p>A callback function might concatenate the firstName and
* lastName fields in the data, or do some custom formatting on a Date,
* or convert a number for the month into the string for the month.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get labelFunction():Function
{
return _labelFunction;
}
/**
* @private
*/
public function set labelFunction(value:Function):void
{
_labelFunction = value;
if (owner)
{
owner.invalidateList();
}
dispatchEvent(new Event("labelFunctionChanged"));
}
//----------------------------------
// minWidth
//----------------------------------
/**
* @private
* Storage for the minWidth property.
*/
private var _minWidth:Number = 20;
[Bindable("minWidthChanged")]
[Inspectable(category="General", defaultValue="100")]
/**
* The minimum width of the column.
* @default 20
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get minWidth():Number
{
return _minWidth;
}
/**
* @private
*/
public function set minWidth(value:Number):void
{
_minWidth = value;
if (owner)
{
owner.invalidateList();
}
if (_width < value)
_width = value;
dispatchEvent(new Event("minWidthChanged"));
}
//----------------------------------
// nullItemRenderer
//----------------------------------
/**
* @private
* Storage for the nullItemRenderer property.
*/
private var _nullItemRenderer:IFactory;
private var _contextNullItemRenderer:IFactory;
[Bindable("nullItemRendererChanged")]
[Inspectable(category="Other")]
/**
* The class factory for item renderer instances that display the
* data for each item in the column.
* You can specify a drop-in item renderer,
* an inline item renderer, or a custom item renderer component as the
* value of this property.
*
* <p>The default item renderer is the DataGridItemRenderer class,
* which displays the item data as text. </p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get nullItemRenderer():IFactory
{
return _nullItemRenderer;
}
/**
* @private
*/
public function set nullItemRenderer(value:IFactory):void
{
_nullItemRenderer = value;
// this is expensive... but unless set after init (not recommended), ok.
if (owner)
{
owner.invalidateList();
owner.columnRendererChanged(this);
_contextNullItemRenderer = null;
}
dispatchEvent(new Event("nullItemRendererChanged"));
}
//----------------------------------
// resizable
//----------------------------------
[Inspectable(category="General")]
/**
* A flag that indicates whether the user is allowed to resize
* the width of the column.
* If <code>true</code>, the user can drag the grid lines between
* the column headers to resize
* the column.
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var resizable:Boolean = true;
//----------------------------------
// showDataTips
//----------------------------------
/**
* @private
* Storage for the showDataTips property.
*/
private var _showDataTips:*;
[Inspectable(category="Advanced")]
/**
* A flag that indicates whether the datatips are shown in the column.
* If <code>true</code>, datatips are displayed for text in the rows. Datatips
* are tooltips designed to show the text that is too long for the row.
*
* @default false
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get showDataTips():*
{
return _showDataTips;
}
/**
* @private
*/
public function set showDataTips(value:*):void
{
_showDataTips = value;
if (owner)
{
owner.invalidateList();
}
}
//----------------------------------
// sortable
//----------------------------------
[Inspectable(category="General")]
/**
* A flag that indicates whether the user can click on the
* header of this column to sort the data provider.
* If this property and the DataGrid <code>sortableColumns</code> property
* are both <code>true</code>, the DataGrid control dispatches a
* <code>headerRelease</code> event when a user releases the mouse button
* on this column's header.
* If no other handler calls the <code>preventDefault()</code> method on
* the <code>headerRelease</code> event, the <code>dataField</code>
* property or <code>sortCompareFunction</code> in the column is used
* to reorder the items in the dataProvider.
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var sortable:Boolean = true;
//----------------------------------
// sortCompareFunction
//----------------------------------
/**
* @private
* Storage for the sortCompareFunction property.
*/
private var _sortCompareFunction:Function;
[Bindable("sortCompareFunctionChanged")]
[Inspectable(category="Advanced")]
/**
*
* A callback function that gets called when sorting the data in
* the column. If this property is not specified, the sort tries
* to use a basic string or number sort on the data.
* If the data is not a string or number or if the <code>dataField</code>
* property is not a valid property of the data provider, the sort does
* not work or will generate an exception.
* If you specify a value of the <code>labelFunction</code> property,
* you typically also provide a function to the <code>sortCompareFunction</code> property,
* unless sorting is not allowed on this column.
* That means you specify a function when the value from the column's <code>dataField</code>
* does not sort in the same way as the computed value from the <code>labelFunction</code> property.
*
* <p>The DataGrid control uses this function to sort the elements of the data
* provider collection. The function signature of
* the callback function takes two parameters and have the following form:</p>
*
* <pre>mySortCompareFunction(obj1:Object, obj2:Object):int </pre>
*
* <p><code>obj1</code> — A data element to compare.</p>
*
* <p><code>obj2</code> — Another data element to compare with obj1.</p>
*
* <p>The function should return a value based on the comparison
* of the objects: </p>
* <ul>
* <li>-1 if obj1 should appear before obj2 in ascending order. </li>
* <li>0 if obj1 = obj2. </li>
* <li>1 if obj1 should appear after obj2 in ascending order.</li>
* </ul>
*
* <p><strong>Note:</strong> The <code>obj1</code> and
* <code>obj2</code> parameters are entire data provider elements and not
* just the data for the item.</p>
*
* @default null
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get sortCompareFunction():Function
{
return _sortCompareFunction;
}
/**
* @private
*/
public function set sortCompareFunction(value:Function):void
{
_sortCompareFunction = value;
dispatchEvent(new Event("sortCompareFunctionChanged"));
}
//----------------------------------
// visible
//----------------------------------
/**
* @private
* Storage for the visible property.
*/
private var _visible:Boolean = true;
[Inspectable(category="General", defaultValue="true")]
/**
* A flag that indicates whethe the column is visible.
* If <code>true</code>, the column is visible.
*
* @default true
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get visible():Boolean
{
return _visible;
}
/**
* @private
*/
public function set visible(value:Boolean):void
{
if (_visible != value)
{
_visible = value;
if (value)
newlyVisible = true;
if (owner)
{
owner.columnsInvalid = true;
owner.invalidateSize();
owner.invalidateList();
}
}
}
mx_internal var newlyVisible:Boolean = false;
//----------------------------------
// width
//----------------------------------
/**
* @private
* Storage for the width property.
*/
private var _width:Number = 100;
// preferred width is the number we should use when measuring
// regular width will be changed if we shrink columns to fit.
mx_internal var preferredWidth:Number = 100;
[Bindable("widthChanged")]
[Inspectable(category="General", defaultValue="100")]
/**
* The width of the column, in pixels.
* If the DataGrid's <code>horizontalScrollPolicy</code> property
* is <code>false</code>, all visible columns must fit in the displayable
* area, and the DataGrid will not always honor the width of
* the columns if the total width of the columns is too
* small or too large for the displayable area.
*
* @default 100
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get width():Number
{
return _width;
}
/**
* @private
*/
public function set width(value:Number):void
{
// remove any queued equal spacing commands
explicitWidth = value;
// use this value for future measurements
preferredWidth = value;
if (owner != null)
{
// if we aren't resizing as part of grid layout, resize it's column
var oldVal:Boolean = resizable;
// anchor this column to not accept any overflow width for accurate sizing
resizable = false;
owner.resizeColumn(colNum, value);
resizable = oldVal;
}
else
{
// otherwise, just store the size
_width = value;
}
dispatchEvent(new Event("widthChanged"));
}
/**
* @private
* Internal function to allow the DataGrid to set the width of the
* column without locking it as an explicitWidth
*/
mx_internal function setWidth(value:Number):void
{
var oldValue:Number = _width;
_width = value;
if (oldValue != value)
dispatchEvent(new Event("widthChanged"));
}
//----------------------------------
// wordWrap
//----------------------------------
/**
* @private
* Storage for the wordWrap property.
*/
private var _wordWrap:*;
[Inspectable(category="Advanced")]
/**
* A flag that indicates whether the text in a row of this column
* is word wrapped if it doesn't fit on one line.
* If <code>undefined</code>, the DataGrid control's <code>wordWrap</code> property
* is used.
*
* <p>Only takes effect if the <code>DataGrid.variableRowHeight</code> property is also
* <code>true</code>.</p>
*
* @default undefined
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get wordWrap():*
{
return _wordWrap;
}
/**
* @private
*/
public function set wordWrap(value:*):void
{
_wordWrap = value;
if (owner)
{
owner.invalidateList();
}
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override mx_internal function addStyleToProtoChain(
chain:Object, target:DisplayObject, filterMap:Object = null):Object
{
var parentGrid:DataGridBase = owner;
var item:IListItemRenderer = IListItemRenderer(target);
// If there is a DataGridColumn.styleName property,
// add it to the head of the proto chain.
// (The fact that styles can be set on both DataGridColumn
// and DataGridColumn.styleName seems a bit redundant,
// but both are supported for backward compatibility.)
var styleName:Object = styleName;
if (styleName)
{
if (styleName is String)
{
chain = addStylesToProtoChain(String(styleName), chain, target);
}
else if (styleName is CSSStyleDeclaration)
{
chain = styleName.addStyleToProtoChain(chain, target);
}
}
chain = super.addStyleToProtoChain(chain, target);
// If the target data is a DataGridColumn and has a data
// field in its data, then it is a header so add the
// DataGrid.headerStyleName object to the head of the proto chain.
if (item.data && (item.data is DataGridColumn))
{
var s:Object;
var headerStyleName:Object =
parentGrid.getStyle("headerStyleName");
if (headerStyleName)
{
if (headerStyleName is String)
{
chain = addStylesToProtoChain(String(headerStyleName), chain, target);
}
else if (headerStyleName is CSSStyleDeclaration)
{
chain = headerStyleName.addStyleToProtoChain(chain, target);
}
}
headerStyleName = getStyle("headerStyleName");
if (headerStyleName)
{
if (headerStyleName is String)
{
chain = addStylesToProtoChain(String(headerStyleName), chain, target);
}
else if (headerStyleName is CSSStyleDeclaration)
{
chain = headerStyleName.addStyleToProtoChain(chain, target);
}
}
}
return chain;
}
/**
* @private
*/
override public function setStyle(styleProp:String, value:*):void
{
if (styleProp == "fontFamily" || styleProp == "fontWeight" || styleProp == "fontStyle")
{
if (owner)
{
owner.fontContextChanged = true;
owner.invalidateProperties();
}
}
var oldValue:Object = getStyle(styleProp);
var regenerate:Boolean = false;
// If this DataGridColumn didn't previously have a factory, defaultFactory, or
// overrides object, then this DataGridColumn hasn't been added to the item
// renderers proto chains. In that case, we need to regenerate all the item
// renderers proto chains.
if (factory == null &&
defaultFactory == null &&
!overrides &&
(oldValue !== value)) // must be !==
{
regenerate = true;
}
super.setLocalStyle(styleProp, value);
// The default implementation of setStyle won't always regenerate
// the proto chain when headerStyleName is set, and we need to make sure
// that they are regenerated
if (styleProp == "headerStyleName")
{
if (owner)
{
owner.regenerateStyleCache(true);
owner.notifyStyleChangeInChildren("headerStyleName", true);
}
return;
}
if (owner)
{
if (regenerate)
{
owner.regenerateStyleCache(true);
}
owner.invalidateList();
}
}
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
/**
* Returns the String that the item renderer displays for the given data object.
* If the DataGridColumn or its DataGrid control
* has a non-null <code>labelFunction</code>
* property, it applies the function to the data object.
* Otherwise, the method extracts the contents of the field specified by the
* <code>dataField</code> property, or gets the string value of the data object.
* If the method cannot convert the parameter to a String, it returns a
* single space.
*
* @param data Object to be rendered.
*
* @return Displayable String based on the data.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function itemToLabel(data:Object):String
{
if (!data)
return " ";
if (labelFunction != null)
return labelFunction(data, this);
if (owner.labelFunction != null)
return owner.labelFunction(data, this);
if (typeof(data) == "object" || typeof(data) == "xml")
{
try
{
if ( !hasComplexFieldName )
data = data[dataField];
else
data = deriveComplexColumnData( data );
}
catch(e:Error)
{
data = null;
}
}
if (data is String)
return String(data);
try
{
return data.toString();
}
catch(e:Error)
{
}
return " ";
}
/**
* Returns a String that the item renderer displays as the datatip for the given data object,
* based on the <code>dataTipField</code> and <code>dataTipFunction</code> properties.
* If the method cannot convert the parameter to a String, it returns a
* single space.
*
* <p>This method is for use by developers who are creating subclasses
* of the DataGridColumn class.
* It is not for use by application developers.</p>
*
* @param data Object to be rendered.
*
* @return Displayable String based on the data.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function itemToDataTip(data:Object):String
{
if (dataTipFunction != null)
return dataTipFunction(data);
if (owner.dataTipFunction != null)
return owner.dataTipFunction(data);
if (typeof(data) == "object" || typeof(data) == "xml")
{
var field:String = dataTipField;
if (!field)
field = owner.dataTipField;
try
{
if (data[field] != null)
data = data[field];
else if (data[dataField] != null)
data = data[dataField];
}
catch(e:Error)
{
data = null;
}
}
if (data is String)
return String(data);
try
{
return data.toString();
}
catch(e:Error)
{
}
return " ";
}
/**
* @private
*/
protected function deriveComplexColumnData( data:Object ):Object
{
var currentRef:Object = data;
if ( complexFieldNameComponents )
{
for ( var i:int=0; i<complexFieldNameComponents.length; i++ )
currentRef = currentRef[ complexFieldNameComponents[ i ] ];
}
return currentRef;
}
/**
* @private
*/
protected function complexColumnSortCompare( obj1:Object, obj2:Object ):int
{
if ( !obj1 && !obj2 )
return 0;
if ( !obj1 )
return 1;
if ( !obj2 )
return -1;
var obj1Data:String = deriveComplexColumnData( obj1 ).toString();
var obj2Data:String = deriveComplexColumnData( obj2 ).toString();
if ( obj1Data < obj2Data )
return -1;
if ( obj1Data > obj2Data )
return 1;
return 0;
}
/**
* Return the appropriate factory, using the default factory if none specified.
*
* @param forHeader <code>true</code> if this is a header renderer.
*
* @param data The data to be presented by the item renderer.
*
* @return if <code>data</code> is null, the default item renderer,
* otherwis it returns the custom item renderer.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function getItemRendererFactory(forHeader:Boolean, data:Object):IFactory
{
if (forHeader)
{
if (!_contextHeaderRenderer)
_contextHeaderRenderer = replaceItemRendererFactory(headerRenderer, true);
return _contextHeaderRenderer;
}
if (!data)
{
if (!_contextNullItemRenderer)
_contextNullItemRenderer = replaceItemRendererFactory(nullItemRenderer);
return _contextNullItemRenderer;
}
if (!_contextItemRenderer)
_contextItemRenderer = replaceItemRendererFactory(itemRenderer);
return _contextItemRenderer;
}
/**
* @private
*
* This methods does two things:
*
* 1. If the column uses styles that require an embedded font and the column has no renderer,
* then use the owner's item render, so we can replace it.
* 2. If the column uses styles that require an embedded font, then replace
* the existing class factory with a ContextualClassFactory so the item can
* be created in the correct context.
*/
private function replaceItemRendererFactory(rendererFactory:IFactory, forHeader:Boolean = false):IFactory
{
// No use of embedded font so just return
if (oldEmbeddedFontContext == null)
return rendererFactory;
// Using an embedded font, but no local item renderer, so
// grab the owner's renderer and see if we can convert
// it to a ContextualClassFactory.
if (rendererFactory == null && owner != null)
rendererFactory = owner.itemRenderer;
if (rendererFactory is ClassFactory) {
var contextualClassFactory: ContextualClassFactory =
new ContextualClassFactory(ClassFactory(rendererFactory).generator,
forHeader ? oldHeaderEmbeddedFontContext : oldEmbeddedFontContext);
contextualClassFactory.properties = ClassFactory(rendererFactory).properties;
return contextualClassFactory;
}
return rendererFactory;
}
mx_internal function getMeasuringRenderer(forHeader:Boolean, data:Object):IListItemRenderer
{
var factory:IFactory = getItemRendererFactory(forHeader, data);
if (!factory)
factory = owner.itemRenderer;
if (!measuringObjects)
measuringObjects = new Dictionary(false);
var item:IListItemRenderer = measuringObjects[factory];
if (!item)
{
item = factory.newInstance();
item.visible = false;
item.styleName = this;
measuringObjects[factory] = item;
}
return item;
}
/**
* @private
*
* Reset the factories so they get re-generated.
*/
mx_internal function resetFactories():void
{
_contextHeaderRenderer = null;
_contextItemRenderer = null;
_contextNullItemRenderer = null;
determineFontContext();
}
/**
* @private
*
* Save the current font context to member fields.
*/
mx_internal function determineFontContext():void
{
var embeddedFontContext:IFlexModuleFactory;
// Save for hasFontContextChanged()
var fontName:String = StringUtil.trimArrayElements(getStyle("fontFamily"), ",");
var fontWeight:String = getStyle("fontWeight");
var fontStyle:String = getStyle("fontStyle");
if (fontName == null)
fontName = StringUtil.trimArrayElements(owner.getStyle("fontFamily"), ",");
if (fontWeight == null)
fontWeight = owner.getStyle("fontWeight");
if (fontStyle == null)
fontStyle = owner.getStyle("fontStyle");
var bold:Boolean = fontWeight == "bold";
var italic:Boolean = fontStyle == "italic";
embeddedFontContext = (noEmbeddedFonts || !embeddedFontRegistry) ?
null :
embeddedFontRegistry.getAssociatedModuleFactory(
fontName, bold, italic, this, owner.moduleFactory,
owner.systemManager);
if (embeddedFontContext != oldEmbeddedFontContext)
{
oldEmbeddedFontContext = embeddedFontContext;
owner.invalidateList();
owner.columnRendererChanged(this);
_contextItemRenderer = null;
_contextNullItemRenderer = null;
}
var headerStyleName:Object =
owner.getStyle("headerStyleName");
if (headerStyleName)
{
if (headerStyleName is String)
{
headerStyleName = owner.styleManager.getMergedStyleDeclaration(String(headerStyleName));
}
}
if (headerStyleName)
{
var headerFontName:String = StringUtil.trimArrayElements(headerStyleName.getStyle("fontFamily"), ",");
if (headerFontName)
fontName = headerFontName;
var headerFontWeight:String = headerStyleName.getStyle("fontWeight");
if (headerFontWeight)
fontWeight = headerFontWeight;
var headerFontStyle:String = headerStyleName.getStyle("fontStyle");
if (headerFontStyle)
fontStyle = headerFontStyle;
bold = fontWeight == "bold";
italic = fontStyle == "italic";
}
headerStyleName = getStyle("headerStyleName");
if (headerStyleName)
{
if (headerStyleName is String)
{
headerStyleName = owner.styleManager.getMergedStyleDeclaration(String(headerStyleName));
}
}
if (headerStyleName)
{
headerFontName = StringUtil.trimArrayElements(headerStyleName.getStyle("fontFamily"), ",");
if (headerFontName)
fontName = headerFontName;
headerFontWeight = headerStyleName.getStyle("fontWeight");
if (headerFontWeight)
fontWeight = headerFontWeight;
headerFontStyle = headerStyleName.getStyle("fontStyle");
if (headerFontStyle)
fontStyle = headerFontStyle;
bold = fontWeight == "bold";
italic = fontStyle == "italic";
}
embeddedFontContext = (noEmbeddedFonts || !embeddedFontRegistry) ?
null :
embeddedFontRegistry.getAssociatedModuleFactory(
fontName, bold, italic, this, owner.moduleFactory,
owner.systemManager);
if (embeddedFontContext != oldHeaderEmbeddedFontContext)
{
oldHeaderEmbeddedFontContext = embeddedFontContext;
cachedHeaderRenderer = null;
owner.dataGridHeader.headerItemsChanged = true;
_contextHeaderRenderer = null;
}
}
/**
* @private
*/
private function addStylesToProtoChain(styles:String, chain:Object, target:DisplayObject):Object
{
var styleNames:Array = styles.split(/\s+/);
for (var c:int=0; c < styleNames.length; c++)
{
if (styleNames[c].length)
{
var declaration:CSSStyleDeclaration =
owner.styleManager.getMergedStyleDeclaration("." + styleNames[c]);
if (declaration)
chain = declaration.addStyleToProtoChain(chain, target);
}
}
return chain;
}
/**
* @private
* A hash table of objects used to calculate sizes
*/
mx_internal var measuringObjects:Dictionary;
/**
* A map of free item renderers by factory.
* This property is a Dictionary indexed by factories
* where the values are Dictionaries of itemRenderers
*
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
mx_internal var freeItemRenderersByFactory:Dictionary;
}
}
|
package kabam.rotmg.dailyLogin.view {
import com.company.assembleegameclient.objects.ObjectLibrary;
import com.company.assembleegameclient.ui.panels.itemgrids.itemtiles.EquipmentTile;
import com.company.assembleegameclient.ui.panels.itemgrids.itemtiles.ItemTile;
import com.company.assembleegameclient.ui.tooltip.EquipmentToolTip;
import com.company.assembleegameclient.ui.tooltip.TextToolTip;
import com.company.assembleegameclient.ui.tooltip.ToolTip;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.filters.ColorMatrixFilter;
import flash.geom.Matrix;
import kabam.rotmg.constants.ItemConstants;
import kabam.rotmg.core.StaticInjectorContext;
import kabam.rotmg.core.signals.HideTooltipsSignal;
import kabam.rotmg.core.signals.ShowTooltipSignal;
import kabam.rotmg.text.model.TextKey;
import kabam.rotmg.text.view.BitmapTextFactory;
import org.swiftsuspenders.Injector;
public class ItemTileRenderer extends Sprite {
protected static const DIM_FILTER:Array = [new ColorMatrixFilter([0.4, 0, 0, 0, 0, 0, 0.4, 0, 0, 0, 0, 0, 0.4, 0, 0, 0, 0, 0, 1, 0])];
private static const IDENTITY_MATRIX:Matrix = new Matrix();
private static const DOSE_MATRIX:Matrix = function ():Matrix {
var _loc1_:Matrix = new Matrix();
_loc1_.translate(10, 5);
return _loc1_;
}();
public function ItemTileRenderer(param1:int) {
super();
this.itemId = param1;
this.itemBitmap = new Bitmap();
addChild(this.itemBitmap);
this.drawTile();
this.addEventListener("mouseOver", this.onTileHover);
this.addEventListener("mouseOut", this.onTileOut);
}
private var itemId:int;
private var tooltip:ToolTip;
private var itemBitmap:Bitmap;
public function drawTile():void {
var _loc1_:* = null;
var _loc3_:* = null;
var _loc4_:* = null;
var _loc2_:* = null;
var _loc5_:int = this.itemId;
if (_loc5_ != -1) {
_loc1_ = ObjectLibrary.getRedrawnTextureFromType(_loc5_, 100, true);
_loc3_ = ObjectLibrary.xmlLibrary_[_loc5_];
if (_loc3_ && _loc3_.hasOwnProperty("Doses")) {
_loc1_ = _loc1_.clone();
_loc4_ = BitmapTextFactory.make(_loc3_.Doses, 12, 16777215, false, IDENTITY_MATRIX, false);
_loc1_.draw(_loc4_, DOSE_MATRIX);
}
if (_loc3_ && _loc3_.hasOwnProperty("Quantity")) {
_loc1_ = _loc1_.clone();
_loc2_ = BitmapTextFactory.make(_loc3_.Quantity, 12, 16777215, false, IDENTITY_MATRIX, false);
_loc1_.draw(_loc2_, DOSE_MATRIX);
}
this.itemBitmap.bitmapData = _loc1_;
this.itemBitmap.x = -_loc1_.width / 2;
this.itemBitmap.y = -_loc1_.width / 2;
visible = true;
} else {
visible = false;
}
}
private function addToolTipToTile(param1:ItemTile):void {
var _loc3_:* = null;
if (this.itemId > 0) {
this.tooltip = new EquipmentToolTip(this.itemId, null, -1, "");
} else {
if (param1 is EquipmentTile) {
_loc3_ = ItemConstants.itemTypeToName((param1 as EquipmentTile).itemType);
} else {
_loc3_ = "item.toolTip";
}
this.tooltip = new TextToolTip(3552822, 10197915, null, "item.emptySlot", 200, {"itemType": TextKey.wrapForTokenResolution(_loc3_)});
}
this.tooltip.attachToTarget(param1);
var _loc2_:Injector = StaticInjectorContext.getInjector();
var _loc4_:ShowTooltipSignal = _loc2_.getInstance(ShowTooltipSignal);
_loc4_.dispatch(this.tooltip);
}
private function onTileOut(param1:MouseEvent):void {
var _loc2_:Injector = StaticInjectorContext.getInjector();
var _loc3_:HideTooltipsSignal = _loc2_.getInstance(HideTooltipsSignal);
_loc3_.dispatch();
}
private function onTileHover(param1:MouseEvent):void {
if (!stage) {
return;
}
var _loc2_:ItemTile = param1.currentTarget as ItemTile;
this.addToolTipToTile(_loc2_);
}
}
}
|
package
{
import com.kidoz.sdk.api.platforms.IFlexiViewInterface;
import com.kidoz.sdk.api.platforms.SdkController;
/** Example Implementation of the Flexi View events listener */
public class FlexiViewActionListener implements IFlexiViewInterface
{
var mController:SdkController;
public function FlexiViewActionListener(controller:SdkController)
{
mController = controller;
}
/** On Flexi view ready callback */
public function onFlexiViewReady():void {
mController.printToastDebugLog("Flexi view Ready");
}
/** On Flexi view visible callback */
public function onFlexiViewVisible():void {
mController.printToastDebugLog("Flexi view Visible");
}
/** On Flexi view hidden callback */
public function onFlexiViewHidden():void {
mController.printToastDebugLog("Flexi view Hidden");
}
}
} |
package {
import flash.display.MovieClip;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
public class XMLBasicNamespace extends MovieClip {
private var feed:XML;
private var mm:Namespace;
private var dc:Namespace;
/* These namespaces will allow us to get data inside of
the namespaces in the xml
<mm:Artist>
<dc:title>Foreigner</dc:title>
</mm:Artist>
*/
private var feedLoader:URLLoader = new URLLoader();
public function XMLBasicNamespace() {
// constructor code
init();
}
private function init():void{
feedLoader.load(new URLRequest("pandora.xml"));
feedLoader.addEventListener(Event.COMPLETE, loaded)
}
private function loaded(e:Event):void{
feed = new XML(e.target.data)
// this allows for namespace communication
mm = feed.namespace("mm")
dc= feed.namespace("dc")
// the double :: allows communication in the namespace
// EXAMPLE
// feed.channel.item.mm::Artist.dc::title
trace(feed.channel.item.mm::Artist.dc::title[0]);
one.scaleX= one.scaleY = searchXML("The Black Keys");
two.scaleX= two.scaleY = searchXML("Weezer");
three.scaleX= three.scaleY = searchXML("Taylor Swift");
four.scaleX= four.scaleY = searchXML("Taking Back Sunday");
}
private function searchXML(keyword:String):int{
var count:int = 0;
for(var i:int=0; i<feed.channel.item.length(); i++){
if(keyword == feed.channel.item.mm::Artist.dc::title[i]){
count++
}
}
return count;
}
}
}
|
package utils
{
import flash.display.DisplayObject;
import flash.net.LocalConnection;
import flash.utils.ByteArray;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import org.flexlite.domUI.collections.ArrayCollection;
public class ObjectUtil
{
public function ObjectUtil()
{
}
/**
* 将obj1 和 obj2 的属性合并进入obj1中,如果有相同的属性则不合并
* @param object1
* @param object2
*
*/
public static function concat(object1:Object , object2:Object):void
{
for(var str:String in object2){
if(!object1.hasOwnProperty(str)){
object1[str] = object2[str];
}
}
}
/**
* 深拷贝,对于Function或可视化对象实现的是浅拷贝
* 注意:ObjectUtil.copy是无法拷贝Function或可视化对象的
*/
public static function deepCopy(obj:Object):Object{
if(!obj)
return null;
var bytes:ByteArray = new ByteArray();
bytes.writeObject(obj);
bytes.position = 0;
return bytes.readObject();
// if(obj == null||obj is String||obj is Number||obj is Boolean||obj is Function||obj is DisplayObject){
// return obj;
// }else if(obj is ByteArray){
// var buffer:ByteArray = new ByteArray();
// buffer.writeObject(obj);
// buffer.position = 0;
// var result:Object = buffer.readObject();
// return result;
// }else if(obj is Array){
// var newArray:Array=new Array();
// var arraylen:int=obj.length;
// for(var i1:int=0;i1<arraylen;i1++){
// newArray.push(deepCopy(obj[i1]));
// }
// return newArray;
// }else if(obj is ArrayCollection){
// var newArrayList:ArrayCollection=new ArrayCollection();
// var arrayListlen:int=obj.length;
// for(var i2:int=0;i2<arrayListlen;i2++){
// newArrayList.addItem(deepCopy(obj.getItemAt(i2)));
// }
// return newArrayList;
// }else if((typeof obj) is Vector){
// var newVector:Vector=new Vector();
// var vectorlen:int=obj.length;
// for(var i3:int=0;i3<vectorlen;i3++){
// newVector.push(deepCopy(obj[i3]));
// }
// return newVector;
// }else{
// var newObj:Object=new (getDefinitionByName(getQualifiedClassName(obj)) as Class)();
// for(var f:String in obj){
// newObj[f]=deepCopy(obj[f]);
// }
// return newObj;
// }
}
/**
* 黑科技,垃圾回收器
*/
public static function gc():void
{
try{
new LocalConnection().connect("GC");
new LocalConnection().connect("GC");
}catch(error : Error){
}
}
}
} |
package com.tinyspeck.engine.net
{
public class NetOutgoingPlayMusicVO extends NetOutgoingMessageVO
{
public var name:String;
public var loops:int;
public function NetOutgoingPlayMusicVO(name:String, loops:uint = 0)
{
super(MessageTypes.PLAY_MUSIC);
this.name = name;
this.loops = loops;
}
}
} |
void func() { int a; a++; }
|
package kabam.rotmg.assets.EmbeddedData {
import mx.core.*;
[Embed(source="xmls/EmbeddedData_OryxChamberCXML.xml", mimeType="application/octet-stream")]
public class EmbeddedData_OryxChamberCXML extends ByteArrayAsset {
public function EmbeddedData_OryxChamberCXML() {
super();
return;
}
}
}
|
// Decompiled by AS3 Sorcerer 6.08
// www.as3sorcerer.com
//io.decagames.rotmg.classes.NewClassUnlockNotification
package io.decagames.rotmg.classes
{
import flash.display.Sprite;
import flash.display.Shape;
import flash.display.Bitmap;
import com.greensock.TimelineMax;
import io.decagames.rotmg.ui.labels.UILabel;
import com.greensock.TweenMax;
import com.greensock.easing.Bounce;
import com.greensock.easing.Expo;
import com.company.assembleegameclient.objects.ObjectLibrary;
import io.decagames.rotmg.ui.defaults.DefaultLabelFormat;
import io.decagames.rotmg.ui.sliceScaling.SliceScalingBitmap;
import io.decagames.rotmg.ui.texture.TextureParser;
import com.company.assembleegameclient.appengine.SavedCharacter;
import com.company.assembleegameclient.util.AnimatedChar;
import flash.display.BitmapData;
import flash.display.Graphics;
public class NewClassUnlockNotification extends Sprite
{
private const WIDTH:int = 192;
private const HEIGHT:int = 192;
private const NEW_CLASS_UNLOCKED:String = "New Class Unlocked!";
private var _contentContainer:Sprite;
private var _whiteSplash:Shape;
private var _newClass:Bitmap;
private var _objectTypes:Array;
private var _timeLineMax:TimelineMax;
private var _characterName:UILabel;
public function NewClassUnlockNotification()
{
this.init();
}
public function playNotification(_arg_1:Array=null):void
{
this._objectTypes = _arg_1;
this.createCharacter();
this.playAnimation();
}
private function playAnimation():void
{
if (!this._timeLineMax)
{
this._timeLineMax = new TimelineMax();
this._timeLineMax.add(TweenMax.to(this._whiteSplash, 0.1, {
"autoAlpha":1,
"transformAroundCenter":{
"scaleX":1,
"scaleY":1
},
"ease":Bounce.easeOut
}));
this._timeLineMax.add(TweenMax.to(this._whiteSplash, 0.1, {
"alpha":0.4,
"tint":0,
"ease":Expo.easeOut
}));
this._timeLineMax.add(TweenMax.to(this._contentContainer, 0.2, {
"autoAlpha":1,
"transformAroundCenter":{
"scaleX":1,
"scaleY":1
},
"ease":Bounce.easeOut
}));
this._timeLineMax.add(TweenMax.to(this._contentContainer, 2, {"onComplete":this.resetAnimation}));
}
else
{
this._timeLineMax.play(0);
}
}
private function resetAnimation():void
{
if (this._objectTypes.length > 0)
{
this.createCharacter();
this.playAnimation();
}
else
{
this._timeLineMax.reverse();
}
}
private function createCharacter():void
{
var _local_3:XML;
var _local_5:int;
if (this._newClass)
{
this._contentContainer.removeChild(this._newClass);
this._newClass.bitmapData.dispose();
this._newClass = null;
}
var _local_1:int = ObjectLibrary.playerChars_.length;
var _local_2:int = this._objectTypes.shift();
var _local_4:int;
while (_local_4 < _local_1)
{
_local_3 = ObjectLibrary.playerChars_[_local_4];
_local_5 = int(_local_3.@type);
if (_local_2 == _local_5)
{
this._newClass = new Bitmap(this.getImageBitmapData(_local_3));
break;
}
_local_4++;
}
if (this._newClass)
{
this._newClass.x = ((this.WIDTH - this._newClass.width) / 2);
this._newClass.y = (((this.HEIGHT - this._newClass.height) / 2) - 20);
this._contentContainer.addChild(this._newClass);
if (!this._characterName)
{
this.createCharacterName();
}
this._characterName.text = _local_3.@id;
this._characterName.x = ((this.WIDTH - this._characterName.width) / 2);
this._characterName.y = (((this.HEIGHT - this._characterName.height) / 2) + 20);
}
}
private function createCharacterName():void
{
this._characterName = new UILabel();
DefaultLabelFormat.notificationLabel(this._characterName, 14, 0xFFFFFF, "center", true);
this._contentContainer.addChild(this._characterName);
}
private function createCharacterBackground():void
{
var _local_1:Shape;
var _local_2:SliceScalingBitmap;
_local_1 = new Shape();
_local_1.graphics.beginFill(0x545454);
_local_1.graphics.drawRect(0, 0, 105, 105);
_local_1.x = ((this.WIDTH - _local_1.width) / 2);
_local_1.y = (((this.HEIGHT - _local_1.height) / 2) - 6);
this._contentContainer.addChild(_local_1);
_local_2 = TextureParser.instance.getSliceScalingBitmap("UI", "popup_background_decoration");
_local_2.width = 105;
_local_2.height = 105;
_local_2.x = _local_1.x;
_local_2.y = _local_1.y;
this._contentContainer.addChild(_local_2);
}
private function getImageBitmapData(_arg_1:XML):BitmapData
{
return (SavedCharacter.getImage(null, _arg_1, AnimatedChar.DOWN, AnimatedChar.STAND, 0, true, false));
}
private function init():void
{
this.createWhiteSplash();
this.createContainers();
this.createCharacterBackground();
this.createClassUnlockLabel();
}
private function createClassUnlockLabel():void
{
var _local_1:UILabel;
_local_1 = new UILabel();
_local_1.text = this.NEW_CLASS_UNLOCKED;
DefaultLabelFormat.notificationLabel(_local_1, 18, 0xFF00, "center", true);
_local_1.width = this.WIDTH;
_local_1.x = ((this.WIDTH - _local_1.width) / 2);
_local_1.y = ((this.HEIGHT - _local_1.height) - 12);
this._contentContainer.addChild(_local_1);
}
private function createWhiteSplash():void
{
this._whiteSplash = new Shape();
var _local_1:Graphics = this._whiteSplash.graphics;
_local_1.beginFill(0xFFFFFF);
_local_1.drawRect(0, 0, this.WIDTH, this.HEIGHT);
this._whiteSplash.x = (this._whiteSplash.width / 2);
this._whiteSplash.y = (this._whiteSplash.height / 2);
this._whiteSplash.alpha = 0;
this._whiteSplash.visible = false;
this._whiteSplash.scaleX = (this._whiteSplash.scaleY = 0);
addChild(this._whiteSplash);
}
private function createContainers():void
{
this._contentContainer = new Sprite();
this._contentContainer.alpha = 0;
this._contentContainer.visible = false;
addChild(this._contentContainer);
}
}
}//package io.decagames.rotmg.classes
|
package crew.cmd
{
import com.tencent.morefun.framework.base.Command;
import def.PluginDef;
public class OpenCrewCommand extends Command
{
public var viewId:int;
public var pageTab:uint;
public var bagTabIndex:int = -1;
public var data;
public function OpenCrewCommand(param1:int = 1, param2:uint = 1, param3:* = null, param4:int = -1)
{
super();
this.viewId = param1;
this.pageTab = param2;
this.data = param3;
this.bagTabIndex = param4;
}
override public function getPluginName() : String
{
return PluginDef.CREW;
}
}
}
|
package org.floxy.tests.integration
{
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.system.ApplicationDomain;
import org.flexunit.Assert;
import org.flexunit.async.Async;
import org.floxy.IProxyRepository;
import org.floxy.ProxyRepository;
import org.floxy.tests.*;
[TestCase]
public class NoPackageInterfaceSupportFixture
{
private var _proxyRepository : IProxyRepository;
[Before(async)]
public function setupProxy() : void
{
_proxyRepository = new ProxyRepository();
var result : IEventDispatcher =
_proxyRepository.prepare([INoPackageReferenceInterface], ApplicationDomain.currentDomain);
result.addEventListener(Event.COMPLETE, Async.asyncHandler(this, function(... args):void
{
}, 1000));
}
[Test]
public function can_be_accessed_directly() : void
{
var interceptor : MockIntercepter = new MockIntercepter();
var a : INoPackageReferenceInterface =
INoPackageReferenceInterface(_proxyRepository.create(INoPackageReferenceInterface, [], interceptor));
a.getValue();
Assert.assertEquals(1, interceptor.invocationCount);
}
}
}
|
package com.mintdigital.hemlock.widgets.chatroom{
import com.mintdigital.hemlock.HemlockEnvironment;
import com.mintdigital.hemlock.Logger;
import com.mintdigital.hemlock.data.Message;
import com.mintdigital.hemlock.widgets.HemlockWidget;
import com.mintdigital.hemlock.controls.HemlockButton;
import com.mintdigital.hemlock.controls.HemlockTextInput;
import com.mintdigital.hemlock.data.JID;
import com.mintdigital.hemlock.data.Presence;
import com.mintdigital.hemlock.display.HemlockSprite;
import com.mintdigital.hemlock.models.Roster;
import com.mintdigital.hemlock.models.User;
import com.mintdigital.hemlock.utils.ArrayUtils;
import com.mintdigital.hemlock.utils.HashUtils;
import com.mintdigital.hemlock.utils.StringUtils;
import flash.events.Event;
/*
// Imports for testing avatar support:
import flash.display.BlendMode;
import flash.display.Loader;
*/
public class ChatroomWidget extends HemlockWidget {
private var eventTypes:Object;
protected var _room:String = 'chat';
protected static var _defaultOptions:Object = {
bg: skin.BGBlock,
paddingN: skin.CHATROOM_WIDGET_PADDING_N || 10,
paddingS: skin.CHATROOM_WIDGET_PADDING_S || 15,
paddingW: skin.CHATROOM_WIDGET_PADDING_W || 15,
paddingE: skin.CHATROOM_WIDGET_PADDING_E || 15,
roomStyleSheet: null, // Override with a StyleSheet object
messageButtonWidth: 60,
messageButtonHeight: null, // Defaults to height of views.messageInput
messageButtonBG: HemlockButton.defaultOptions.bg,
messageButtonBGHover: HemlockButton.defaultOptions.bgHover,
messageButtonBGActive: HemlockButton.defaultOptions.bgActive,
messageInputFontSize: HemlockTextInput.defaultOptions.fontSize,
showRoster: true,
showTimestamps: true,
strings: {
messageInput: 'Say something!',
messageButton: 'Post',
rosterText: 'Currently in the chatroom: '
}
};
public function ChatroomWidget(parentSprite:HemlockSprite, options:Object = null){
_options = options = HashUtils.merge(_defaultOptions, options);
roster = new Roster();
super(parentSprite, HashUtils.merge({
delegates: {
views: new ChatroomWidgetViews(this),
events: new ChatroomWidgetEvents(this)
}
}, options));
}
public function updateRosterView(presenceType:String):void {
if(!this.views.roster){ return; }
var rosterText:String = options.strings.rosterText || 'Currently in the chatroom: ';
rosterText += ArrayUtils.toSentence(ArrayUtils.map(roster, 'nickname'));
this.views.roster.text = rosterText;
}
public function displayChatMessage(msg:String, createdAt:Date, cssClass:String = 'presence'):void {
insertTextIntoRoom(msg, createdAt, {
cssClass: cssClass
});
}
public function getNick(jid:JID) : String {
return jid.resource;
// TODO: This is currently the same as the username, because
// that's what's set as the container's JID when the session
// is created. This should ideally be the user's nickname,
// which either the user could supply upon login, or could
// later be stored in the Jabber database.
}
internal function insertTextIntoRoom(text:String, timestamp:Date, options:Object = null) : void {
if(!options){ options = {}; }
if(!options.cssClass){ options.cssClass = 'status'; }
// Track whether to scroll; should be false if user manually
// changed scroll position.
var scrollToBottom:Boolean = (
views.room.scrollV == 0
|| views.room.scrollV == views.room.maxScrollV
);
var newText:String;
newText = '<p class="' + options.cssClass + '">';
if(this.options.showTimestamps){
newText += '<span class="timestamp" style="color:#999">('
// + timestamp.toLocaleTimeString()
+ timestamp.hours + ':' + (timestamp.minutes < 10 ? '0' : '') + timestamp.minutes
// TODO: Accept a widget constructor option for switching between 12- and 24-hour clock
+ ')</span> ';
}
newText += text + '</p>';
views.room.htmlText += newText;
// Notify scrollbar
views.room.dispatchEvent(new Event(Event.CHANGE));
// Scroll to bottom if appropriate
if(scrollToBottom){ views.room.scrollV = views.room.maxScrollV; }
}
internal function sendChatMessage():void{
var msg:String = StringUtils.trim(views.messageInput.value);
if(msg.length > 0){ sendMessage(msg); }
views.messageInput.value = '';
/*
// FIXME: Testing; disable
if(msg == '/invisible'){
// TODO: Figure out why presence doesn't go through with "type" attribute
sendPresence({ show: Presence.SHOW_AWAY, type: Presence.INVISIBLE_TYPE }); // Allows for updating views
container.updatePrivacyList(jid, 'presence-out', 'deny');
}else if(msg == '/visible'){
sendPresence({ show: Presence.SHOW_CHAT, type: Presence.VISIBLE_TYPE });
container.updatePrivacyList(jid, 'presence-out', 'allow');
}else if(msg == '/brb'){
sendPresence({ show: Presence.SHOW_AWAY });
}else if(msg == '/bak'){
sendPresence({ show: Presence.SHOW_CHAT });
}
*/
}
override public function get room():String {
return _room + "@" + domain;
}
//--------------------------------------
// Properties
//--------------------------------------
public static function get defaultOptions():Object { return _defaultOptions; }
public static function set defaultOptions(value:Object):void { _defaultOptions = value; }
}
}
|
package net.manaca.managers
{
import flash.display.DisplayObject;
import flash.display.InteractiveObject;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Dictionary;
import flash.utils.Timer;
import net.manaca.errors.SingletonError;
/**
* The ToolTipManager lets you set basic ToolTip functionality,
* such as display delay and the disabling of ToolTips.
* @author Sean Zou
*
*/
public class ToolTipManager extends EventDispatcher
{
//==========================================================================
// Class variables
//==========================================================================
/**
* Define mouse over target this time start show tooltip.
*/
static public var TRIGG_TIME:uint = 1000;
/**
* Define the tooltip max display time.
*/
static public var MAX_DISPLAY_TIME:uint = 5000;
/**
* Define reset the fast mode time.
*/
static public var QUASH_TIME:uint = 1000;
/**
* Define the faet mode display tooltip time.
*/
static public var FAST_DISPLAY_TIME:uint = 50;
/**
* @private
*/
static private var instance:ToolTipManager;
//==========================================================================
// Class methods
//==========================================================================
/**
* Returns the sole instance of this singleton class,
* creating it if it does not already exist.
*/
static public function getInstance():ToolTipManager
{
if (!instance)
{
instance = new ToolTipManager();
}
return instance;
}
//==========================================================================
// Variables
//==========================================================================
/* all need tooltip objects */
private var toolTipMap:Dictionary;
/* current show tooltip target */
private var currentTarget:InteractiveObject;
/* is use fast mode display tooltip */
private var isFastDisplay:Boolean = false;
/* trigg tooltip timer */
private var triggTimer:Timer;
/* quash fast mode timer */
private var quashTimer:Timer;
//==========================================================================
// Constructor
//==========================================================================
/**
* Constructs a singleton <code>ToolTipManager</code> instance.
*
*/
public function ToolTipManager()
{
super();
if(instance)
{
throw new SingletonError(instance);
}
toolTipMap = new Dictionary(true);
triggTimer = new Timer(TRIGG_TIME, 1);
triggTimer.addEventListener(TimerEvent.TIMER_COMPLETE, triggTimeConplete);
quashTimer = new Timer(QUASH_TIME, 1);
quashTimer.addEventListener(TimerEvent.TIMER_COMPLETE, quashTimeConplete);
}
//==========================================================================
// Properties
//==========================================================================
//----------------------------------
// toolTipDisplay
//----------------------------------
private var _toolTipDisplay:IToolTipDisplay = new ToolTipDisplay();
/**
* Define the tooltip view.
* @return
*
*/
public function get toolTipDisplay():IToolTipDisplay
{
return _toolTipDisplay;
}
public function set toolTipDisplay(value:IToolTipDisplay):void
{
_toolTipDisplay = value;
}
//----------------------------------
// enabled
//----------------------------------
private var _enabled:Boolean = true;
/**
* If true, the ToolTipManager will automatically show ToolTips when the user moves the mouse pointer over components.
* If false, no ToolTips will be shown.
* @return
*
*/
public function get enabled():Boolean
{
return _enabled;
}
public function set enabled(value:Boolean):void
{
_enabled = value;
}
//==========================================================================
// Methods
//==========================================================================
/**
* Add a tooltip target to manager.
* @param target spring the tooltip target.
* @param toolTip the show info.
*
*/
public function addToolTip(target:InteractiveObject, toolTip:* = null):void
{
if(target)
{
if(toolTipMap[target] == null)
{
target.addEventListener(MouseEvent.MOUSE_OVER,
mouseOverHanlder, false, 0, true);
target.addEventListener(MouseEvent.MOUSE_OUT,
mouseOutHanlder, false, 0, true);
target.addEventListener(Event.REMOVED,
mouseOutHanlder, false, 0, true);
}
if(target.hasOwnProperty("toolTip"))
{
toolTipMap[target] = target["toolTip"];
}
else if(toolTip)
{
toolTipMap[target] = toolTip;
}
}
}
/**
* Remove a tooltip target.
* @param target will remove tooltip target
*
*/
public function removeToolTip(target:InteractiveObject):void
{
if(target && toolTipMap[target] != null)
{
target.removeEventListener(MouseEvent.MOUSE_OVER, mouseOverHanlder);
target.removeEventListener(MouseEvent.MOUSE_OUT, mouseOutHanlder);
target.removeEventListener(Event.REMOVED, mouseOutHanlder);
delete toolTipMap[target];
}
}
//==========================================================================
// Event handlers
//==========================================================================
private function mouseOverHanlder(event:MouseEvent):void
{
if( !enabled) return;
currentTarget = InteractiveObject(event.currentTarget);
if(currentTarget.stage)
{
triggTimer.stop();
if(isFastDisplay)
{
triggTimer.delay = FAST_DISPLAY_TIME;
}
else
{
triggTimer.delay = TRIGG_TIME;
}
triggTimer.reset();
triggTimer.start();
}
}
private function mouseOutHanlder(event:Event):void
{
if(toolTipDisplay && DisplayObject(toolTipDisplay).stage)
{
DisplayObject(toolTipDisplay).stage.removeChild(
DisplayObject(toolTipDisplay));
}
triggTimer.stop();
quashTimer.stop();
quashTimer.reset();
quashTimer.start();
currentTarget = null;
}
private function triggTimeConplete(event:TimerEvent):void
{
isFastDisplay = true;
if(currentTarget && currentTarget.stage)
{
var toolTipTemp:DisplayObject = DisplayObject(toolTipDisplay);
toolTipDisplay.display(toolTipMap[currentTarget]);
currentTarget.stage.addChild(toolTipTemp);
var tx:int = currentTarget.stage.mouseX;
var ty:int = currentTarget.stage.mouseY + 20;
if(toolTipTemp.width + tx > currentTarget.stage.stageWidth)
{
tx = currentTarget.stage.stageWidth - toolTipTemp.width - 3;
}
if(toolTipTemp.height + ty > currentTarget.stage.stageHeight)
{
ty = currentTarget.stage.stageHeight - toolTipTemp.height - 30;
}
toolTipTemp.x = tx;
toolTipTemp.y = ty;
}
}
private function quashTimeConplete(event:TimerEvent):void
{
isFastDisplay = false;
}
}
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// var SECTION = "Definitions"; // provide a document reference (ie, ECMA section)
// var VERSION = "AS3"; // Version of JavaScript or ECMA
// var TITLE = "Class Definition"; // Provide ECMA section title or a description
var BUGNUMBER = "";
//-----------------------------------------------------------------------------
import Bug118272Package.*;
import com.adobe.test.Assert;
import com.adobe.test.Utils;
var eg = new BugTest();
Assert.expectEq("Trying to initialize public class identifier", "ReferenceError: Error #1074", Utils.referenceError(eg.thisError));
Assert.expectEq("Trying to initialize default class identifier", "ReferenceError: Error #1074", Utils.referenceError(eg.thisError1));
Assert.expectEq("Trying to initialize internal class identifier", "ReferenceError: Error #1074", Utils.referenceError(eg.thisError2));
Assert.expectEq("Trying to initialize dynamic class identifier", "ReferenceError: Error #1074", Utils.referenceError(eg.thisError3));
Assert.expectEq("Trying to initialize final class identifier", "ReferenceError: Error #1074", Utils.referenceError(eg.thisError4));
//test case in bug118272
class A { }
var thisError:String = "no error";
try{
A = null;
}catch(e:ReferenceError){
thisError = e.toString();
}finally{
Assert.expectEq("Trying to initialize class identifier,the class is outside the package", "ReferenceError: Error #1074", Utils.referenceError(thisError));
}
// displays results.
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.collections {
import mx.collections.ArrayCollection;
public class DataNode {
private var _label:String;
private var _children:ArrayCollection;
private var _isSelected:Boolean = false;
private var _isPreviousSiblingRemoved:Boolean = false;
private var _parent:DataNode;
public function DataNode(label:String)
{
_label = label;
}
public function get children():ArrayCollection
{
return _children;
}
public function set children(value:ArrayCollection):void
{
_children = value;
}
public function get label():String
{
return _label + (_isSelected ? " [SEL]" : "") + (_isPreviousSiblingRemoved ? " [PREV ITEM REMOVED]" : "");
}
public function toString():String
{
return label;
}
public function addChild(node:DataNode):void
{
if(!_children)
_children = new ArrayCollection();
_children.addItem(node);
node.parent = this;
}
public function set isSelected(value:Boolean):void
{
_isSelected = value;
}
public function get isSelected():Boolean
{
return _isSelected;
}
public function clone():DataNode
{
var newNode:DataNode = new DataNode(_label);
for each(var childNode:DataNode in children)
{
newNode.addChild(childNode.clone());
}
return newNode;
}
public function set isPreviousSiblingRemoved(value:Boolean):void
{
_isPreviousSiblingRemoved = value;
}
public function get parent():DataNode
{
return _parent;
}
public function set parent(value:DataNode):void
{
_parent = value;
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import com.adobe.test.Assert;
class State {
var next = null;
}
const depths = new Vector.<State>(2,true);
function expand(depth)
{
var x = new State;
x.next = depths[depth];
return(x);
}
// var TITLE = "Regression Testcase for Bug 492046: null value assigned to slot raises assertion failure";
Assert.expectEq("null value assigned to slot should not assert", "[object State]", String(expand(1)) );
|
// Simple Context pattern.
// AngelScript allows custom classes to be defined in
// the script.
class RequestContext {
// To store references, AngelScript has it's own Handle identifier.
Logger@ logger;
// AngelScript classes allows constructors. Others, such as copy constructor,
// are also possible. The ':' initializer for members is not available.
// Reference parameters can be of style 'in', 'out' and 'inout'. When not specified,
// 'inout' is assumed.
RequestContext(Logger& logger) {
// Operations on handles are prepended by @. Note that this is accessed
// by '.' operator. Without @, the operation are on the type.
@this.logger = logger;
}
};
// Receiving a context by const reference. The alternative could be a 'in' reference type,
// but a copy constructor of RequestContext would be called.
void doRequest(const RequestContext& context, const Request& request, Response& response) {
// Enriching the context logger with more information is possible.
context.logger.Info().Str("target", request.target).Msg("Processing request");
response.statusCode = HttpStatusCode::Ok;
response.body = "{\n";
response.body += " \"method\": \"" + request.method + "\",\n";
response.body += " \"target\": \"" + request.target + "\"\n";
response.body += "}\n";
}
/* ProcessRequest is the entry point of the script from chttpm. The
request and responses are created by the chttpm engine, and cannot be
created by AngelScript scripts. */
void ProcessRequest(const Request& request, Response& response)
{
// Logger is defined in the chttpm engine.
Logger logger;
// Add some initial information to the logger before adding it to
// the context structure.
logger = logger.With().Str("method", request.method).Logger();
RequestContext context(logger);
doRequest(context, request, response);
}
|
/**
* This class handles sending out ECards.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @author David Cary
* @since 04.09.2010
*/
package com.neopets.games.marketing.destination.capriSun.disrespectoids.widgets.quest
{
//----------------------------------------
// IMPORTS
//----------------------------------------
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.display.DisplayObject;
import flash.text.TextField;
import flash.events.TextEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import flash.display.Loader;
import com.neopets.games.marketing.destination.capriSun.disrespectoids.widgets.BasicPopUp;
import com.neopets.games.marketing.destination.capriSun.disrespectoids.util.BroadcastEvent;
import com.neopets.games.marketing.destination.capriSun.disrespectoids.LogInMessage;
import com.neopets.games.marketing.destination.capriSun.disrespectoids.widgets.InstructionCallButton;
import com.neopets.games.marketing.destination.capriSun.disrespectoids.pages.QuestPage;
import com.neopets.games.marketing.destination.capriSun.disrespectoids.DestinationView;
import com.neopets.projects.destination.destinationV3.Parameters;
import com.neopets.projects.destination.destinationV3.AbsView;
import com.neopets.util.general.GeneralFunctions;
import com.neopets.util.events.CustomEvent;
import com.neopets.util.display.ListPane;
import com.neopets.util.servers.NeopetsServerFinder;
import com.neopets.util.display.BoundedIconRow;
public class QuestPopUp extends BasicPopUp
{
//----------------------------------------
// CONSTANTS
//----------------------------------------
public static const ICON_SIZE:Number = 80;
//----------------------------------------
// VARIABLES
//----------------------------------------
// global variables
public static var INSTRUCTION_HEADER:String = "Instructions:";
public static var INSTRUCTION_TEXT:String = "It looks like the pouches have gotten fed up with being disrespected and have hidden throughout the Disrespectoids Clubhouse. Can you find each wayward pouch? All you have to do is check your Task List for hints of each pouch's location. Once you've cracked the clue and found the pouch, you'll be awarded Neopoints. Completing more tasks will earn you extra prizes. Plus, an extra-special virtual prize awaits those who can finish the quest. Now show those pouches some respect and get going!";
public static var LOGIN_HEADER:String = "Please Log In:";
public static var PRIZE_HEADER:String = "Congratulations!";
public static var POINT_PRIZE_TEXT:String = "Congratulations, you have completed the task and earned %prize!";
public static var CLAIM_PRIZE_TEXT:String = "Click <a href='event:claimPrize'><u>here</u></a> to claim your prize!";
public var CLAIM_SUCCESS_POINTS:String = "%prize has been added to your total.";
public var CLAIM_SUCCESS_ONE_ITEM:String = "%prize has been added to your <a href='%url'><u>inventory</u></a>.";
public var CLAIM_SUCCESS_MANY_ITEMS:String = "%prizes have been added to your <a href='%url'><u>inventory</u></a>.";
public var ANOTHER_PRIZE:String = "Hey! There's another <a href='event:nextPrize'><u>prize</u></a> waiting for you...";
public var CLAIM_ERROR_HEADER:String = "Prize Error";
public var CLAIM_ERROR_TEXT:String = "Hmm, there seems to have been some kind of error claiming your prize. Reload the page and try again!";
// components
protected var _titleField:TextField;
protected var _messageField:TextField;
protected var _messagePane:ListPane;
// local variables
protected var _loggedIn:Boolean;
protected var _pendingPrizes:Array;
protected var _servers:NeopetsServerFinder;
//----------------------------------------
// CONSTRUCTOR
//----------------------------------------
public function QuestPopUp():void {
super();
// set up components
_titleField = getChildByName("title_txt") as TextField;
messageField = getChildByName("main_txt") as TextField;
// check login status
var tag:String = Parameters.userName;
//tag = "Grue"; // comment in to test logged in status locally
loggedIn = (tag != null && tag != AbsView.GUEST_USER);
}
//----------------------------------------
// GETTERS AND SETTORS
//----------------------------------------
public function get loggedIn():Boolean { return _loggedIn; }
public function set loggedIn(bool:Boolean) {
_loggedIn = bool;
if(!_loggedIn) showLogin();
}
public function get messageField():TextField { return _messageField; }
public function set messageField(txt:TextField) {
_messageField = txt;
// create message pane
initMessagePane();
}
override public function set sharedDispatcher(disp:EventDispatcher) {
// clear listeners
if(_sharedDispatcher != null) {
_sharedDispatcher.removeEventListener(InstructionCallButton.BROADCAST_EVENT,onPopUpRequest);
_sharedDispatcher.removeEventListener(QuestPage.QUEST_STATUS_RESULT,onStatusResult);
_sharedDispatcher.removeEventListener(QuestPage.CLAIM_PRIZE_RESULT,onClaimResult);
_sharedDispatcher.removeEventListener(POPUP_SHOWN,onPopUpShown);
}
_sharedDispatcher = disp;
_dispatcherClass = GeneralFunctions.getClassOf(_sharedDispatcher);
// set up listeners
if(_sharedDispatcher != null) {
_sharedDispatcher.addEventListener(InstructionCallButton.BROADCAST_EVENT,onPopUpRequest);
_sharedDispatcher.addEventListener(QuestPage.QUEST_STATUS_RESULT,onStatusResult);
_sharedDispatcher.addEventListener(QuestPage.CLAIM_PRIZE_RESULT,onClaimResult);
_sharedDispatcher.addEventListener(POPUP_SHOWN,onPopUpShown);
}
}
//----------------------------------------
// PUBLIC METHODS
//----------------------------------------
// This function appends a section of text to the end of our content.
// param url String Server independant path to target image.
// param index int Position in the list to load text.
public function addImage(url:String,index:int=-1):Loader {
if(url == null || url.length <= 0) return null;
// create loader
var loader:Loader = new Loader();
var req:URLRequest = new URLRequest(url);
loader.load(req);
_messagePane.addItemAt(loader,index);
return loader;
}
// Use this function to add a line of text to our message list pane.
// param msg String Text to load into the textfield.
// param index int Position in the list to load text.
public function addText(msg:String,index:int=-1):TextField {
var shell:MovieClip = new PrizeTextMC();
// find text field in shell
var child:DisplayObject;
var txt:TextField;
for(var i:int = 0; i < shell.numChildren; i++) {
child = shell.getChildAt(i);
if(child is TextField) {
txt = child as TextField;
break;
}
}
// if we found text, resize it and add the shell
if(txt != null) {
// get the target text width
var txt_width:Number;
if(_messageField != null) {
txt_width = _messageField.width;
} else {
if(_titleField != null) txt_width = _titleField.width;
else txt_width = width;
}
// update field text
txt.htmlText = msg;
// resize field
txt.width = txt_width;
txt.height = txt.textHeight + 4; // add extra padding to make sure text shows
// add shell to our pane
_messagePane.addItemAt(shell,index);
}
return txt;
}
// Extracts prize names into a list style string.
// param info Object Prize data entry
// param restriction Number If positive number, only use entries of a this type code.
public function getPrizeNamesString(info:Object,restriction:Number=0):String {
if(info == null) return null;
// extract prize data
var prizes:Array = info["prizes"] as Array;
if(prizes == null) return null; // abort if there are no prizes
var entry:Object;
var entry_type:Number;
var entry_name:String;
var names_str:String;
var end_index:int = prizes.length - 1;
for(var i:int = 0; i < prizes.length; i++) {
entry = prizes[i];
// apply type restrictions
entry_type = Number(entry["type"]);
if(restriction <= 0 || entry_type == restriction) {
// extract prize names
entry_name = String(entry["name"]);
if(names_str == null) names_str = entry_name;
else {
if(i < end_index) names_str += ", ";
else names_str += " and ";
names_str += entry_name;
}
}
}
return names_str;
}
// Extracts prize icon urls.
// param info Object Prize data entry
// param restriction Number If positive number, only use entries of a this type code.
public function getPrizeURLS(info:Object,restriction:Number=0):Array {
if(info == null) return null;
// extract prize data
var prizes:Array = info["prizes"] as Array;
if(prizes == null) return null; // abort if there are no prizes
var entry:Object;
var entry_type:Number;
var entry_url:String;
var urls:Array = new Array();
for(var i:int = 0; i < prizes.length; i++) {
entry = prizes[i];
// apply type restrictions
entry_type = Number(entry["type"]);
if(restriction <= 0 || entry_type == restriction) {
// extract icon
entry_url = String(entry["url"]);
if(entry_url != null) urls.push(entry_url);
}
}
return urls;
}
// Use this function to add a row of icons to our content pane.
// param urls String This is an array of icon urls.
// param index int This is where in the list the item should be placed.
// imported from NP9_Prize_Pop_Up
public function loadIcons(urls:Array,index:int=-1):void
{
if(urls == null) return;
// create the new icon row
var row:BoundedIconRow = new BoundedIconRow();
// add a bounding area to the row
var clip:MovieClip = new MovieClip();
clip.graphics.beginFill(0x000000,0.01);
clip.graphics.drawRect(0,0,width,ICON_SIZE);
clip.graphics.endFill();
row.addChild(clip);
row.setBoundingObj(clip);
// load images into the icon row
var backing:MovieClip;
var offset:Number = ICON_SIZE / -2;
for(var i:int = 0; i < urls.length; i++) {
backing = new MovieClip();
backing.graphics.beginFill(0xFFFFFF,1);
backing.graphics.drawRect(offset,offset,ICON_SIZE,ICON_SIZE);
backing.graphics.endFill();
row.loadIconFrom(urls[i],backing);
}
// add the row to our content pane
_messagePane.addItemAt(row,index);
}
// If not logged in show login text.
public function showLogin():void {
var msg:LogInMessage = new LogInMessage("earn Neopoints and win prizes");
showMessage(LOGIN_HEADER,msg.toString());
}
// Use this function to send to show a specified text message with header.
public function showMessage(header:String,msg:String):void {
if(_titleField != null) _titleField.htmlText = header;
if(_messageField != null) _messageField.htmlText = msg;
_messagePane.clearItems();
visible = true;
}
// This function shows the current top entry in our pending prize list.
public function showPrize():void {
if(_pendingPrizes == null || _pendingPrizes.length < 1) return;
// set title
if(_titleField != null) _titleField.htmlText = PRIZE_HEADER;
// clear existing messages
if(_messageField != null) _messageField.htmlText = "";
_messagePane.clearItems();
// get top entry
var prize_data:Object = _pendingPrizes[0];
// set up first text block
var names_str = getPrizeNamesString(prize_data);
var prize_str:String = POINT_PRIZE_TEXT.replace("%prize",names_str);
addText(prize_str);
// add icon row to pane
var urls:Array = getPrizeURLS(prize_data);
if(urls != null && urls.length > 0) loadIcons(urls);
// set up second text block
var txt:TextField = addText(CLAIM_PRIZE_TEXT);
if(txt != null) txt.addEventListener(TextEvent.LINK,onClaimPrizeClick);
// show pop up
visible = true;
}
//----------------------------------------
// PROTECTED METHODS
//----------------------------------------
// Use this to add an area for loading answer lines.
protected function initMessagePane():void {
// creat pane if it doesn't exist
if(_messagePane == null) {
_messagePane = new ListPane();
_messagePane.alignment = ListPane.CENTER_ALIGN;
addChild(_messagePane);
}
// if there's a message textfield, reposition over that text
if(_messageField != null) {
_messagePane.x = _messageField.x + (_messageField.width / 2);
_messagePane.y = _messageField.y;
} else {
// move over our center
var bounds:Rectangle = getBounds(this);
_messagePane.x = (bounds.left + bounds.right) / 2;
_messagePane.y = bounds.top;
}
}
// This function send out tracking requests for each prize when it's been awarded.
// This function will usually be overriden by subclasses.
protected function sendPrizeTracking(info:Object) {
if(info == null) return;
switch(info["id"]) {
case "act3":
broadcast(DestinationView.NEOCONTENT_TRACKING_REQUEST,16080);
broadcast(DestinationView.REPORTING_REQUEST,"CollectionQuest-Task3");
break;
case "act4":
broadcast(DestinationView.NEOCONTENT_TRACKING_REQUEST,16081);
broadcast(DestinationView.REPORTING_REQUEST,"CollectionQuest-Task4");
break;
case "act6":
broadcast(DestinationView.NEOCONTENT_TRACKING_REQUEST,16083);
broadcast(DestinationView.REPORTING_REQUEST,"CollectionQuest-Task6");
break;
case "act7":
broadcast(DestinationView.NEOCONTENT_TRACKING_REQUEST,16084);
broadcast(DestinationView.REPORTING_REQUEST,"CollectionQuest-Task7");
break;
case "act9":
broadcast(DestinationView.NEOCONTENT_TRACKING_REQUEST,16086);
broadcast(DestinationView.REPORTING_REQUEST,"CollectionQuest-Task9");
break;
case "act10":
broadcast(DestinationView.NEOCONTENT_TRACKING_REQUEST,16087);
broadcast(DestinationView.REPORTING_REQUEST,"CollectionQuest-Task10");
break;
case "final":
broadcast(DestinationView.NEOCONTENT_TRACKING_REQUEST,16088);
broadcast(DestinationView.REPORTING_REQUEST,"CollectionQuest-FinalPrize");
break;
}
}
// This function shows a prize after it's been claimed through an amf-php call.
protected function showClaimedPrize(info:Object) {
if(info == null) return;
// set title
if(_titleField != null) _titleField.htmlText = PRIZE_HEADER;
// clear existing messages
if(_messageField != null) _messageField.htmlText = "";
_messagePane.clearItems();
// Find out how many items we have
var names:String;
var urls:Array = getPrizeURLS(info,1);
if(urls != null && urls.length > 0) {
// show inventory
names = getPrizeNamesString(info,1);
var prize_str:String;
if(urls.length > 1) prize_str = CLAIM_SUCCESS_MANY_ITEMS.replace("%prizes",names);
else prize_str = CLAIM_SUCCESS_ONE_ITEM.replace("%prize",names);
// replace url
var base_url:String = Parameters.baseURL;
if(base_url == null) base_url = "http://dev.neopets.com";
prize_str = prize_str.replace("%url",base_url+"/objects.phtml?type=inventory");
// add textfield
addText(prize_str);
// show icons
loadIcons(urls);
} else {
// check for point prizes
urls = getPrizeURLS(info,2);
if(urls != null && urls.length > 0) {
names = getPrizeNamesString(info,2);
prize_str = CLAIM_SUCCESS_POINTS.replace("%prize",names);
addText(prize_str);
// show icons
loadIcons(urls);
}
}
// check if more prizes are available
if(_pendingPrizes != null && _pendingPrizes.length > 0) {
var txt:TextField = addText(ANOTHER_PRIZE);
if(txt != null) txt.addEventListener(TextEvent.LINK,onNextPrizeRequest);
}
}
//----------------------------------------
// PRIVATE METHODS
//----------------------------------------
//----------------------------------------
// EVENT LISTENERS
//----------------------------------------
// This function is triggered when a claim prize call is successfully made to php.
public function onClaimResult(ev:CustomEvent) {
// check if the claim was a success
if(ev.oData) {
// pop the top entry off our pending list
if(_pendingPrizes == null) return;
var info:Object = _pendingPrizes.shift();
sendPrizeTracking(info);
showClaimedPrize(info);
}
}
// This function is triggered when a character selection event is broadcast.
override protected function onPopUpRequest(ev:BroadcastEvent) {
showMessage(INSTRUCTION_HEADER,INSTRUCTION_TEXT);
broadcast(POPUP_SHOWN);
}
// When there's a status event, extract the data.
protected function onStatusResult(ev:CustomEvent) {
// extract prize list
var info:Object = ev.oData;
_pendingPrizes = info["prizeConditions"] as Array;
showPrize();
}
// Link Events
protected function onClaimPrizeClick(ev:TextEvent) {
if(_pendingPrizes == null || _pendingPrizes.length < 1) return;
// get top entry
var prize_data:Object = _pendingPrizes[0];
// check if the top prize has a valid prize id
var prize_id:String = String(prize_data["id"]);
if(prize_id != null) {
broadcast(QuestPage.CLAIM_PRIZE_REQUEST,prize_id);
// grant shop award
if(prize_id == "final") broadcast(DestinationView.SHOP_AWARD_REQUEST,"8");
else broadcast(DestinationView.SHOP_AWARD_REQUEST,"7");
}
}
protected function onNextPrizeRequest(ev:TextEvent) {
showPrize();
}
}
} |
/*
Feathers
Copyright (c) 2012 Josh Tynjala. All Rights Reserved.
This program is free software. You can redistribute and/or modify it in
accordance with the terms of the accompanying license agreement.
*/
package feathers.layout
{
import flash.geom.Point;
import starling.display.DisplayObject;
import starling.events.Event;
import starling.events.EventDispatcher;
/**
* @inheritDoc
*/
[Event(name="change",type="starling.events.Event")]
/**
* Positions items as tiles (equal width and height) from left to right
* in multiple rows. Constrained to the suggested width, the tiled rows
* layout will change in height as the number of items increases or
* decreases
*/
public class TiledRowsLayout extends EventDispatcher implements IVirtualLayout
{
/**
* @private
*/
private static const HELPER_VECTOR:Vector.<DisplayObject> = new <DisplayObject>[];
/**
* If the total item height is smaller than the height of the bounds,
* the items will be aligned to the top.
*/
public static const VERTICAL_ALIGN_TOP:String = "top";
/**
* If the total item height is smaller than the height of the bounds,
* the items will be aligned to the middle.
*/
public static const VERTICAL_ALIGN_MIDDLE:String = "middle";
/**
* If the total item height is smaller than the height of the bounds,
* the items will be aligned to the bottom.
*/
public static const VERTICAL_ALIGN_BOTTOM:String = "bottom";
/**
* If the total item width is smaller than the width of the bounds, the
* items will be aligned to the left.
*/
public static const HORIZONTAL_ALIGN_LEFT:String = "left";
/**
* If the total item width is smaller than the width of the bounds, the
* items will be aligned to the center.
*/
public static const HORIZONTAL_ALIGN_CENTER:String = "center";
/**
* If the total item width is smaller than the width of the bounds, the
* items will be aligned to the right.
*/
public static const HORIZONTAL_ALIGN_RIGHT:String = "right";
/**
* If an item height is smaller than the height of a tile, the item will
* be aligned to the top edge of the tile.
*/
public static const TILE_VERTICAL_ALIGN_TOP:String = "top";
/**
* If an item height is smaller than the height of a tile, the item will
* be aligned to the middle of the tile.
*/
public static const TILE_VERTICAL_ALIGN_MIDDLE:String = "middle";
/**
* If an item height is smaller than the height of a tile, the item will
* be aligned to the bottom edge of the tile.
*/
public static const TILE_VERTICAL_ALIGN_BOTTOM:String = "bottom";
/**
* The item will be resized to fit the height of the tile.
*/
public static const TILE_VERTICAL_ALIGN_JUSTIFY:String = "justify";
/**
* If an item width is smaller than the width of a tile, the item will
* be aligned to the left edge of the tile.
*/
public static const TILE_HORIZONTAL_ALIGN_LEFT:String = "left";
/**
* If an item width is smaller than the width of a tile, the item will
* be aligned to the center of the tile.
*/
public static const TILE_HORIZONTAL_ALIGN_CENTER:String = "center";
/**
* If an item width is smaller than the width of a tile, the item will
* be aligned to the right edge of the tile.
*/
public static const TILE_HORIZONTAL_ALIGN_RIGHT:String = "right";
/**
* The item will be resized to fit the width of the tile.
*/
public static const TILE_HORIZONTAL_ALIGN_JUSTIFY:String = "justify";
/**
* The items will be positioned in pages horizontally from left to right.
*/
public static const PAGING_HORIZONTAL:String = "horizontal";
/**
* The items will be positioned in pages vertically from top to bottom.
*/
public static const PAGING_VERTICAL:String = "vertical";
/**
* The items will not be paged. In other words, they will be positioned
* in a continuous set of rows without gaps.
*/
public static const PAGING_NONE:String = "none";
/**
* Constructor.
*/
public function TiledRowsLayout()
{
}
/**
* @private
*/
protected var _gap:Number = 0;
/**
* The space, in pixels, between tiles.
*/
public function get gap():Number
{
return this._gap;
}
/**
* @private
*/
public function set gap(value:Number):void
{
if(this._gap == value)
{
return;
}
this._gap = value;
this.dispatchEventWith(Event.CHANGE);
}
/**
* @private
*/
protected var _paddingTop:Number = 0;
/**
* The space, in pixels, above of items.
*/
public function get paddingTop():Number
{
return this._paddingTop;
}
/**
* @private
*/
public function set paddingTop(value:Number):void
{
if(this._paddingTop == value)
{
return;
}
this._paddingTop = value;
this.dispatchEventWith(Event.CHANGE);
}
/**
* @private
*/
protected var _paddingRight:Number = 0;
/**
* The space, in pixels, to the right of the items.
*/
public function get paddingRight():Number
{
return this._paddingRight;
}
/**
* @private
*/
public function set paddingRight(value:Number):void
{
if(this._paddingRight == value)
{
return;
}
this._paddingRight = value;
this.dispatchEventWith(Event.CHANGE);
}
/**
* @private
*/
protected var _paddingBottom:Number = 0;
/**
* The space, in pixels, below the items.
*/
public function get paddingBottom():Number
{
return this._paddingBottom;
}
/**
* @private
*/
public function set paddingBottom(value:Number):void
{
if(this._paddingBottom == value)
{
return;
}
this._paddingBottom = value;
this.dispatchEventWith(Event.CHANGE);
}
/**
* @private
*/
protected var _paddingLeft:Number = 0;
/**
* The space, in pixels, to the left of the items.
*/
public function get paddingLeft():Number
{
return this._paddingLeft;
}
/**
* @private
*/
public function set paddingLeft(value:Number):void
{
if(this._paddingLeft == value)
{
return;
}
this._paddingLeft = value;
this.dispatchEventWith(Event.CHANGE);
}
/**
* @private
*/
protected var _verticalAlign:String = VERTICAL_ALIGN_TOP;
[Inspectable(type="String",enumeration="top,middle,bottom")]
/**
* If the total column height is less than the bounds, the items in the
* column can be aligned vertically.
*/
public function get verticalAlign():String
{
return this._verticalAlign;
}
/**
* @private
*/
public function set verticalAlign(value:String):void
{
if(this._verticalAlign == value)
{
return;
}
this._verticalAlign = value;
this.dispatchEventWith(Event.CHANGE);
}
/**
* @private
*/
protected var _horizontalAlign:String = HORIZONTAL_ALIGN_CENTER;
[Inspectable(type="String",enumeration="left,center,right")]
/**
* If the total row width is less than the bounds, the items in the row
* can be aligned horizontally.
*/
public function get horizontalAlign():String
{
return this._horizontalAlign;
}
/**
* @private
*/
public function set horizontalAlign(value:String):void
{
if(this._horizontalAlign == value)
{
return;
}
this._horizontalAlign = value;
this.dispatchEventWith(Event.CHANGE);
}
/**
* @private
*/
protected var _tileVerticalAlign:String = TILE_VERTICAL_ALIGN_MIDDLE;
[Inspectable(type="String",enumeration="top,middle,bottom,justify")]
/**
* If an item's height is less than the tile bounds, the position of the
* item can be aligned vertically.
*/
public function get tileVerticalAlign():String
{
return this._tileVerticalAlign;
}
/**
* @private
*/
public function set tileVerticalAlign(value:String):void
{
if(this._tileVerticalAlign == value)
{
return;
}
this._tileVerticalAlign = value;
this.dispatchEventWith(Event.CHANGE);
}
/**
* @private
*/
protected var _tileHorizontalAlign:String = TILE_HORIZONTAL_ALIGN_CENTER;
[Inspectable(type="String",enumeration="left,center,right,justify")]
/**
* If the item's width is less than the tile bounds, the position of the
* item can be aligned horizontally.
*/
public function get tileHorizontalAlign():String
{
return this._tileHorizontalAlign;
}
/**
* @private
*/
public function set tileHorizontalAlign(value:String):void
{
if(this._tileHorizontalAlign == value)
{
return;
}
this._tileHorizontalAlign = value;
this.dispatchEventWith(Event.CHANGE);
}
/**
* @private
*/
protected var _paging:String = PAGING_NONE;
/**
* If the total combined height of the rows is larger than the height
* of the view port, the layout will be split into pages where each
* page is filled with the maximum number of rows that may be displayed
* without cutting off any items.
*/
public function get paging():String
{
return this._paging;
}
/**
* @private
*/
public function set paging(value:String):void
{
if(this._paging == value)
{
return;
}
this._paging = value;
this.dispatchEventWith(Event.CHANGE);
}
/**
* @private
*/
protected var _useSquareTiles:Boolean = true;
/**
* Determines if the tiles must be square or if their width and height
* may have different values.
*/
public function get useSquareTiles():Boolean
{
return this._useSquareTiles;
}
/**
* @private
*/
public function set useSquareTiles(value:Boolean):void
{
if(this._useSquareTiles == value)
{
return;
}
this._useSquareTiles = value;
this.dispatchEventWith(Event.CHANGE);
}
/**
* @private
*/
protected var _useVirtualLayout:Boolean = true;
/**
* @inheritDoc
*/
public function get useVirtualLayout():Boolean
{
return this._useVirtualLayout;
}
/**
* @private
*/
public function set useVirtualLayout(value:Boolean):void
{
if(this._useVirtualLayout == value)
{
return;
}
this._useVirtualLayout = value;
this.dispatchEventWith(Event.CHANGE);
}
/**
* @private
*/
protected var _typicalItemWidth:Number = 0;
/**
* @inheritDoc
*/
public function get typicalItemWidth():Number
{
return this._typicalItemWidth;
}
/**
* @private
*/
public function set typicalItemWidth(value:Number):void
{
if(this._typicalItemWidth == value)
{
return;
}
this._typicalItemWidth = value;
}
/**
* @private
*/
protected var _typicalItemHeight:Number = 0;
/**
* @inheritDoc
*/
public function get typicalItemHeight():Number
{
return this._typicalItemHeight;
}
/**
* @private
*/
public function set typicalItemHeight(value:Number):void
{
if(this._typicalItemHeight == value)
{
return;
}
this._typicalItemHeight = value;
}
/**
* @inheritDoc
*/
public function layout(items:Vector.<DisplayObject>, viewPortBounds:ViewPortBounds = null, result:LayoutBoundsResult = null):LayoutBoundsResult
{
const boundsX:Number = viewPortBounds ? viewPortBounds.x : 0;
const boundsY:Number = viewPortBounds ? viewPortBounds.y : 0;
const minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0;
const minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0;
const maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY;
const maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY;
const explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN;
const explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN;
HELPER_VECTOR.length = 0;
const itemCount:int = items.length;
var tileWidth:Number = this._useSquareTiles ? Math.max(0, this._typicalItemWidth, this._typicalItemHeight) : this._typicalItemWidth;
var tileHeight:Number = this._useSquareTiles ? tileWidth : this._typicalItemHeight;
//a virtual layout assumes that all items are the same size as
//the typical item, so we don't need to measure every item in
//that case
if(!this._useVirtualLayout)
{
for(var i:int = 0; i < itemCount; i++)
{
var item:DisplayObject = items[i];
if(!item)
{
continue;
}
tileWidth = this._useSquareTiles ? Math.max(tileWidth, item.width, item.height) : Math.max(tileWidth, item.width);
tileHeight = this._useSquareTiles ? Math.max(tileWidth, tileHeight) : Math.max(tileHeight, item.height);
}
}
var availableWidth:Number = NaN;
var availableHeight:Number = NaN;
var horizontalTileCount:int = Math.max(1, itemCount);
if(!isNaN(explicitWidth))
{
availableWidth = explicitWidth;
horizontalTileCount = Math.max(1, (explicitWidth - this._paddingLeft - this._paddingRight + this._gap) / (tileWidth + this._gap));
}
else if(!isNaN(maxWidth))
{
availableWidth = maxWidth;
horizontalTileCount = Math.max(1, (maxWidth - this._paddingLeft - this._paddingRight + this._gap) / (tileWidth + this._gap));
}
var verticalTileCount:int = 1;
if(!isNaN(explicitHeight))
{
availableHeight = explicitHeight;
verticalTileCount = Math.max(1, (explicitHeight - this._paddingTop - this._paddingBottom + this._gap) / (tileHeight + this._gap));
}
else if(!isNaN(maxHeight))
{
availableHeight = maxHeight;
verticalTileCount = Math.max(1, (maxHeight - this._paddingTop - this._paddingBottom + this._gap) / (tileHeight + this._gap));
}
const totalPageWidth:Number = horizontalTileCount * (tileWidth + this._gap) - this._gap + this._paddingLeft + this._paddingRight;
const totalPageHeight:Number = verticalTileCount * (tileHeight + this._gap) - this._gap + this._paddingTop + this._paddingBottom;
const availablePageWidth:Number = isNaN(availableWidth) ? totalPageWidth : availableWidth;
const availablePageHeight:Number = isNaN(availableHeight) ? totalPageHeight : availableHeight;
const startX:Number = boundsX + this._paddingLeft;
const startY:Number = boundsY + this._paddingTop;
const perPage:int = horizontalTileCount * verticalTileCount;
var pageIndex:int = 0;
var nextPageStartIndex:int = perPage;
var pageStartX:Number = startX;
var positionX:Number = startX;
var positionY:Number = startY;
for(i = 0; i < itemCount; i++)
{
item = items[i];
if(i != 0 && i % horizontalTileCount == 0)
{
positionX = pageStartX;
positionY += tileHeight + this._gap;
}
if(i == nextPageStartIndex)
{
//we're starting a new page, so handle alignment of the
//items on the current page and update the positions
if(this._paging != PAGING_NONE)
{
var discoveredItems:Vector.<DisplayObject> = this._useVirtualLayout ? HELPER_VECTOR : items;
var discoveredItemsFirstIndex:int = this._useVirtualLayout ? 0 : (i - perPage);
var discoveredItemsLastIndex:int = this._useVirtualLayout ? (HELPER_VECTOR.length - 1) : (i - 1);
this.applyHorizontalAlign(discoveredItems, discoveredItemsFirstIndex, discoveredItemsLastIndex, totalPageWidth, availablePageWidth);
this.applyVerticalAlign(discoveredItems, discoveredItemsFirstIndex, discoveredItemsLastIndex, totalPageHeight, availablePageHeight);
HELPER_VECTOR.length = 0;
}
pageIndex++;
nextPageStartIndex += perPage;
//we can use availableWidth and availableHeight here without
//checking if they're NaN because we will never reach a
//new page without them already being calculated.
if(this._paging == PAGING_HORIZONTAL)
{
positionX = pageStartX = startX + availableWidth * pageIndex;
positionY = startY;
}
else if(this._paging == PAGING_VERTICAL)
{
positionY = startY + availableHeight * pageIndex;
}
}
if(item)
{
switch(this._tileHorizontalAlign)
{
case TILE_HORIZONTAL_ALIGN_JUSTIFY:
{
item.x = positionX;
item.width = tileWidth;
break;
}
case TILE_HORIZONTAL_ALIGN_LEFT:
{
item.x = positionX;
break;
}
case TILE_HORIZONTAL_ALIGN_RIGHT:
{
item.x = positionX + tileWidth - item.width;
break;
}
default: //center or unknown
{
item.x = positionX + (tileWidth - item.width) / 2;
}
}
switch(this._tileVerticalAlign)
{
case TILE_VERTICAL_ALIGN_JUSTIFY:
{
item.y = positionY;
item.height = tileHeight;
break;
}
case TILE_VERTICAL_ALIGN_TOP:
{
item.y = positionY;
break;
}
case TILE_VERTICAL_ALIGN_BOTTOM:
{
item.y = positionY + tileHeight - item.height;
break;
}
default: //middle or unknown
{
item.y = positionY + (tileHeight - item.height) / 2;
}
}
if(this._useVirtualLayout)
{
HELPER_VECTOR.push(item);
}
}
positionX += tileWidth + this._gap;
}
//align the last page
if(this._paging != PAGING_NONE)
{
discoveredItems = this._useVirtualLayout ? HELPER_VECTOR : items;
discoveredItemsFirstIndex = this._useVirtualLayout ? 0 : (nextPageStartIndex - perPage);
discoveredItemsLastIndex = this._useVirtualLayout ? (discoveredItems.length - 1) : (i - 1);
this.applyHorizontalAlign(discoveredItems, discoveredItemsFirstIndex, discoveredItemsLastIndex, totalPageWidth, availablePageWidth);
this.applyVerticalAlign(discoveredItems, discoveredItemsFirstIndex, discoveredItemsLastIndex, totalPageHeight, availablePageHeight);
}
var totalWidth:Number = totalPageWidth;
if(!isNaN(availableWidth) && this._paging == PAGING_HORIZONTAL)
{
totalWidth = Math.ceil(itemCount / perPage) * availableWidth;
}
var totalHeight:Number = positionY + tileHeight + this._paddingBottom;
if(!isNaN(availableHeight))
{
if(this._paging == PAGING_HORIZONTAL)
{
totalHeight = availableHeight;
}
else if(this._paging == PAGING_VERTICAL)
{
totalHeight = Math.ceil(itemCount / perPage) * availableHeight;
}
}
if(isNaN(availableWidth))
{
availableWidth = totalWidth;
}
if(isNaN(availableHeight))
{
availableHeight = totalHeight;
}
availableWidth = Math.max(minWidth, availableWidth);
availableHeight = Math.max(minHeight, availableHeight);
if(this._paging == PAGING_NONE)
{
discoveredItems = this._useVirtualLayout ? HELPER_VECTOR : items;
discoveredItemsLastIndex = discoveredItems.length - 1;
this.applyHorizontalAlign(discoveredItems, 0, discoveredItemsLastIndex, totalWidth, availableWidth);
this.applyVerticalAlign(discoveredItems, 0, discoveredItemsLastIndex, totalHeight, availableHeight);
}
HELPER_VECTOR.length = 0;
if(!result)
{
result = new LayoutBoundsResult();
}
result.contentWidth = totalWidth;
result.contentHeight = totalHeight;
result.viewPortWidth = availableWidth;
result.viewPortHeight = availableHeight;
return result;
}
/**
* @inheritDoc
*/
public function measureViewPort(itemCount:int, viewPortBounds:ViewPortBounds = null, result:Point = null):Point
{
if(!result)
{
result = new Point();
}
const explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN;
const explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN;
const needsWidth:Boolean = isNaN(explicitWidth);
const needsHeight:Boolean = isNaN(explicitHeight);
if(!needsWidth && !needsHeight)
{
result.x = explicitWidth;
result.y = explicitHeight;
return result;
}
const boundsX:Number = viewPortBounds ? viewPortBounds.x : 0;
const boundsY:Number = viewPortBounds ? viewPortBounds.y : 0;
const minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0;
const minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0;
const maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY;
const maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY;
const tileWidth:Number = this._useSquareTiles ? Math.max(0, this._typicalItemWidth, this._typicalItemHeight) : this._typicalItemWidth;
const tileHeight:Number = this._useSquareTiles ? tileWidth : this._typicalItemHeight;
var availableWidth:Number = NaN;
var availableHeight:Number = NaN;
var horizontalTileCount:int = Math.max(1, itemCount);
if(!isNaN(explicitWidth))
{
availableWidth = explicitWidth;
horizontalTileCount = Math.max(1, (explicitWidth - this._paddingLeft - this._paddingRight + this._gap) / (tileWidth + this._gap));
}
else if(!isNaN(maxWidth))
{
availableWidth = maxWidth;
horizontalTileCount = Math.max(1, (maxWidth - this._paddingLeft - this._paddingRight + this._gap) / (tileWidth + this._gap));
}
var verticalTileCount:int = 1;
if(!isNaN(explicitHeight))
{
availableHeight = explicitHeight;
verticalTileCount = Math.max(1, (explicitHeight - this._paddingTop - this._paddingBottom + this._gap) / (tileHeight + this._gap));
}
else if(!isNaN(maxHeight))
{
availableHeight = maxHeight;
verticalTileCount = Math.max(1, (maxHeight - this._paddingTop - this._paddingBottom + this._gap) / (tileHeight + this._gap));
}
const totalPageWidth:Number = horizontalTileCount * (tileWidth + this._gap) - this._gap + this._paddingLeft + this._paddingRight;
const totalPageHeight:Number = verticalTileCount * (tileHeight + this._gap) - this._gap + this._paddingTop + this._paddingBottom;
const availablePageWidth:Number = isNaN(availableWidth) ? totalPageWidth : availableWidth;
const availablePageHeight:Number = isNaN(availableHeight) ? totalPageHeight : availableHeight;
const startX:Number = boundsX + this._paddingLeft;
const startY:Number = boundsY + this._paddingTop;
const perPage:int = horizontalTileCount * verticalTileCount;
var pageIndex:int = 0;
var nextPageStartIndex:int = perPage;
var pageStartX:Number = startX;
var positionX:Number = startX;
var positionY:Number = startY;
for(var i:int = 0; i < itemCount; i++)
{
if(i != 0 && i % horizontalTileCount == 0)
{
positionX = pageStartX;
positionY += tileHeight + this._gap;
}
if(i == nextPageStartIndex)
{
pageIndex++;
nextPageStartIndex += perPage;
//we can use availableWidth and availableHeight here without
//checking if they're NaN because we will never reach a
//new page without them already being calculated.
if(this._paging == PAGING_HORIZONTAL)
{
positionX = pageStartX = startX + availableWidth * pageIndex;
positionY = startY;
}
else if(this._paging == PAGING_VERTICAL)
{
positionY = startY + availableHeight * pageIndex;
}
}
}
var totalWidth:Number = totalPageWidth;
if(!isNaN(availableWidth) && this._paging == PAGING_HORIZONTAL)
{
totalWidth = Math.ceil(itemCount / perPage) * availableWidth;
}
var totalHeight:Number = positionY + tileHeight + this._paddingBottom;
if(!isNaN(availableHeight))
{
if(this._paging == PAGING_HORIZONTAL)
{
totalHeight = availableHeight;
}
else if(this._paging == PAGING_VERTICAL)
{
totalHeight = Math.ceil(itemCount / perPage) * availableHeight;
}
}
result.x = needsWidth ? Math.max(minWidth, totalWidth) : explicitWidth;
result.y = needsHeight ? Math.max(minHeight, totalHeight) : explicitHeight;
return result;
}
/**
* @inheritDoc
*/
public function getVisibleIndicesAtScrollPosition(scrollX:Number, scrollY:Number, width:Number, height:Number, itemCount:int, result:Vector.<int> = null):Vector.<int>
{
if(!result)
{
result = new <int>[];
}
result.length = 0;
const tileWidth:Number = this._useSquareTiles ? Math.max(0, this._typicalItemWidth, this._typicalItemHeight) : this._typicalItemWidth;
const tileHeight:Number = this._useSquareTiles ? tileWidth : this._typicalItemHeight;
const horizontalTileCount:int = Math.max(1, (width - this._paddingLeft - this._paddingRight + this._gap) / (tileWidth + this._gap));
if(this._paging != PAGING_NONE)
{
var verticalTileCount:int = Math.max(1, (height - this._paddingTop - this._paddingBottom + this._gap) / (tileHeight + this._gap));
const perPage:Number = horizontalTileCount * verticalTileCount;
if(this._paging == PAGING_HORIZONTAL)
{
var startPageIndex:int = Math.round(scrollX / width);
var minimum:int = startPageIndex * perPage;
var totalRowWidth:Number = horizontalTileCount * (tileWidth + this._gap) - this._gap;
var leftSideOffset:Number = 0;
var rightSideOffset:Number = 0;
if(totalRowWidth < width)
{
if(this._horizontalAlign == HORIZONTAL_ALIGN_RIGHT)
{
leftSideOffset = width - this._paddingLeft - this._paddingRight - totalRowWidth;
rightSideOffset = 0;
}
else if(this._horizontalAlign == HORIZONTAL_ALIGN_CENTER)
{
leftSideOffset = rightSideOffset = (width - this._paddingLeft - this._paddingRight - totalRowWidth) / 2;
}
else if(this._horizontalAlign == HORIZONTAL_ALIGN_LEFT)
{
leftSideOffset = 0;
rightSideOffset = width - this._paddingLeft - this._paddingRight - totalRowWidth;
}
}
var columnOffset:int = 0;
var pageStartPosition:Number = startPageIndex * width;
var partialPageSize:Number = scrollX - pageStartPosition;
if(partialPageSize < 0)
{
partialPageSize = Math.max(0, -partialPageSize - this._paddingRight - rightSideOffset);
columnOffset = -Math.floor(partialPageSize / (tileWidth + this._gap)) - 1;
minimum += -perPage + horizontalTileCount + columnOffset;
}
else if(partialPageSize > 0)
{
partialPageSize = Math.max(0, partialPageSize - this._paddingLeft - leftSideOffset);
columnOffset = Math.floor(partialPageSize / (tileWidth + this._gap));
minimum += columnOffset;
}
if(minimum < 0)
{
minimum = 0;
columnOffset = 0;
}
var rowIndex:int = 0;
var columnIndex:int = (horizontalTileCount + columnOffset) % horizontalTileCount;
var maxColumnIndex:int = columnIndex + horizontalTileCount + 2;
var pageStart:int = int(minimum / perPage) * perPage;
var i:int = minimum;
do
{
result.push(i);
rowIndex++;
if(rowIndex == verticalTileCount)
{
rowIndex = 0;
columnIndex++;
if(columnIndex == horizontalTileCount)
{
columnIndex = 0;
pageStart += perPage;
maxColumnIndex -= horizontalTileCount;
}
i = pageStart + columnIndex - horizontalTileCount;
}
i += horizontalTileCount;
}
while(columnIndex != maxColumnIndex)
}
else
{
startPageIndex = Math.round(scrollY / height);
minimum = startPageIndex * perPage;
if(minimum > 0)
{
pageStartPosition = startPageIndex * height;
partialPageSize = scrollY - pageStartPosition;
if(partialPageSize < 0)
{
minimum -= horizontalTileCount * Math.ceil((-partialPageSize - this._paddingBottom) / (tileHeight + this._gap));
}
else if(partialPageSize > 0)
{
minimum += horizontalTileCount * Math.floor((partialPageSize - this._paddingTop) / (tileHeight + this._gap));
}
}
var maximum:int = minimum + perPage + 2 * horizontalTileCount - 1;
for(i = minimum; i <= maximum; i++)
{
result.push(i);
}
}
}
else
{
var rowIndexOffset:int = 0;
const totalRowHeight:Number = Math.ceil(itemCount / horizontalTileCount) * (tileHeight + this._gap) - this._gap;
if(totalRowHeight < height)
{
if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM)
{
rowIndexOffset = Math.ceil((height - totalRowHeight) / (tileHeight + this._gap));
}
else if(this._verticalAlign == VERTICAL_ALIGN_MIDDLE)
{
rowIndexOffset = Math.ceil((height - totalRowHeight) / (tileHeight + this._gap) / 2);
}
}
rowIndex = -rowIndexOffset + Math.floor((scrollY - this._paddingTop + this._gap) / (tileHeight + this._gap));
verticalTileCount = Math.ceil((height - this._paddingTop + this._gap) / (tileHeight + this._gap)) + 1;
minimum = rowIndex * horizontalTileCount;
maximum = minimum + horizontalTileCount * verticalTileCount;
for(i = minimum; i <= maximum; i++)
{
result.push(i);
}
}
return result;
}
/**
* @inheritDoc
*/
public function getScrollPositionForIndex(index:int, items:Vector.<DisplayObject>, x:Number, y:Number, width:Number, height:Number, result:Point = null):Point
{
if(!result)
{
result = new Point();
}
const itemCount:int = items.length;
var tileWidth:Number = this._useSquareTiles ? Math.max(0, this._typicalItemWidth, this._typicalItemHeight) : this._typicalItemWidth;
var tileHeight:Number = this._useSquareTiles ? tileWidth : this._typicalItemHeight;
//a virtual layout assumes that all items are the same size as
//the typical item, so we don't need to measure every item in
//that case
if(!this._useVirtualLayout)
{
for(var i:int = 0; i < itemCount; i++)
{
var item:DisplayObject = items[i];
if(!item)
{
continue;
}
tileWidth = this._useSquareTiles ? Math.max(tileWidth, item.width, item.height) : Math.max(tileWidth, item.width);
tileHeight = this._useSquareTiles ? Math.max(tileWidth, tileHeight) : Math.max(tileHeight, item.height);
}
}
const horizontalTileCount:int = Math.max(1, (width - this._paddingLeft - this._paddingRight + this._gap) / (tileWidth + this._gap));
if(this._paging != PAGING_NONE)
{
const verticalTileCount:int = Math.max(1, (height - this._paddingTop - this._paddingBottom + this._gap) / (tileHeight + this._gap));
const perPage:Number = horizontalTileCount * verticalTileCount;
const pageIndex:int = index / perPage;
if(this._paging == PAGING_HORIZONTAL)
{
result.x = pageIndex * width;
result.y = 0;
}
else
{
result.x = 0;
result.y = pageIndex * height;
}
}
else
{
result.x = 0;
result.y = this._paddingTop + ((tileHeight + this._gap) * index / horizontalTileCount) + (height - tileHeight) / 2;
}
return result;
}
/**
* @private
*/
protected function applyHorizontalAlign(items:Vector.<DisplayObject>, startIndex:int, endIndex:int, totalItemWidth:Number, availableWidth:Number):void
{
if(totalItemWidth >= availableWidth)
{
return;
}
var horizontalAlignOffsetX:Number = 0;
if(this._horizontalAlign == HORIZONTAL_ALIGN_RIGHT)
{
horizontalAlignOffsetX = availableWidth - totalItemWidth;
}
else if(this._horizontalAlign != HORIZONTAL_ALIGN_LEFT)
{
//we're going to default to center if we encounter an
//unknown value
horizontalAlignOffsetX = (availableWidth - totalItemWidth) / 2;
}
if(horizontalAlignOffsetX != 0)
{
for(var i:int = startIndex; i <= endIndex; i++)
{
var item:DisplayObject = items[i];
item.x += horizontalAlignOffsetX;
}
}
}
/**
* @private
*/
protected function applyVerticalAlign(items:Vector.<DisplayObject>, startIndex:int, endIndex:int, totalItemHeight:Number, availableHeight:Number):void
{
if(totalItemHeight >= availableHeight)
{
return;
}
var verticalAlignOffsetY:Number = 0;
if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM)
{
verticalAlignOffsetY = availableHeight - totalItemHeight;
}
else if(this._verticalAlign == VERTICAL_ALIGN_MIDDLE)
{
verticalAlignOffsetY = (availableHeight - totalItemHeight) / 2;
}
if(verticalAlignOffsetY != 0)
{
for(var i:int = startIndex; i <= endIndex; i++)
{
var item:DisplayObject = items[i];
item.y += verticalAlignOffsetY;
}
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.royale.html.beads.models
{
import org.apache.royale.core.IBeadModel;
import org.apache.royale.core.IStrand;
import org.apache.royale.events.Event;
import org.apache.royale.events.EventDispatcher;
/**
* The WebBrowserModel class bead defines the data associated with an org.apache.royale.html.WebBrowser
* component.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public class WebBrowserModel extends EventDispatcher implements IBeadModel
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public function WebBrowserModel()
{
super();
}
private var _strand:IStrand;
/**
* @copy org.apache.royale.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
}
private var _url:String;
/**
* The URL to load into the WebBrowser.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public function get url():String
{
return _url;
}
public function set url(value:String):void
{
if (value != _url) {
_url = value;
dispatchEvent( new Event("urlChanged") );
}
}
/**
* Sets the URL value without dispatching an event.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
*/
public function setURL(value:String):void
{
_url = value;
}
}
}
|
package multipublish.commands
{
import cn.vision.utils.DateUtil;
import cn.vision.utils.FileUtil;
import cn.vision.utils.LogUtil;
import cn.vision.utils.StringUtil;
import com.winonetech.tools.LogSQLite;
import multipublish.consts.EventConsts;
import multipublish.consts.MPTipConsts;
import multipublish.consts.TypeConsts;
import multipublish.consts.URLConsts;
import multipublish.tools.Controller;
import multipublish.utils.DataUtil;
import multipublish.vo.elements.Arrange;
import mx.utils.OnDemandEventDispatcher;
/**
*
* 截图命令。
*
*/
public final class ShotcutPlayerCommand extends _InternalCommand
{
/**
*
* <code>ShotcutPlayerCommand</code>构造函数。
*
*/
public function ShotcutPlayerCommand($cmd:String = "config")
{
super();
initialize($cmd);
}
/**
* @inheritDoc
*/
override public function execute():void
{
commandStart();
shotcutPlayer();
commandEnd();
}
/**
* @private
*/
private function initialize($cmd:String):void
{
cmd = $cmd;
}
/**
* @private
*/
private function shotcutPlayer():void
{
//无参数则不做任何操作。
if (!StringUtil.isEmpty(cmd))
{
if (isNaN(Number(cmd)))
{
if (cmd == "config")
{
//第一次初始化时进入。
if (config.shotcut)
{
cmd = config.shotcut;
shotcutSettime();
}
}
else if (cmd.indexOf("&") == -1)
{
//仅为回调时反馈。
shotcutCheckDay();
}
else
{
//仅当传入参数时会进入。
controller.removeControlAllShotcut(); //清空之前的记录。
config.shotcutName = {};
shotcutSettime();
}
}
else
{
time = uint(cmd); //纯数字参数继续沿用老方法。
shotcutByGap();
}
}
}
private function shotcutCheckDay():void
{
var temp:Array = cmd.split(",");
var t1:String = temp[0].replace(/-/g, "/"); //格式化开始时间。
var t2:String = temp[1].replace(/-/g, "/"); //格式化结束时间。
var s:Date = new Date(t1);
var e:Date = new Date(t2);
e.date ++;
var d:Date = new Date;
if (s.time <= d.time && d.time <= e.time)
{
config.shotcuter.start(1, true, 1, d.time.toString());
}
}
private function shotcutSettime():void
{
if (cmd != "config")
{
config.shotcut = cmd;
FileUtil.saveUTF(FileUtil.resolvePathApplication(URLConsts.NATIVE_CONFIG), DataUtil.getConfig());
}
if (cmd != "null" && cmd.indexOf("false") < 0)
{
//截图策略多加一个日期范围限制。
var t:Array = cmd.split("&"); //切出日期。
if (t.length == 2)
{
var s_eDate:Array = t[1].split(","); //分离出日期范围。
cmd = t[0]; //分离出时间策略。
}
else return;
//cmd格式:星期 -hh:mm:ss; 星期 -hh:mm:ss; ... ...
var t1:Array = cmd.split(";"); //分割出每个星期所对应的关机时间。
for each (var i:String in t1)
{
var t2:Array = i.split("-"); //t2[0]为星期数解析。
var time:String = t2[1]; //t2[1]为时间解析。
if (time != "null")
{
var temp:Date = new Date;
var t3:Array = time.split(":"); //t3[0]为时,t3[1]为分,t3[2]为秒。
//2000年 1月表示特定的 日期 =星期 -2。
var date:Date = new Date(2000, 0, 2 + Number(t2[0]), t3[0], t3[1], t3[2]);
controller.registControlShotcut(date, presenter.shotcutPlayer, s_eDate);
}
}
}
}
//需要解析参数。如果纯数字则是每隔多久截一次图。其他格式要求不变。
private function shotcutByGap():void
{
time > 0
? config.shotcuter.start(time)
: config.shotcuter.stop();
}
/**
* @private
*/
private function get controller():Controller
{
return config.controller;
}
private var shotcutName:Object = {};
/**
* @private
*/
private var cmd:String;
private var time:uint;
}
} |
class RandomNumber {
var __firstNumber:Number=0
var __lastNumber:Number=3
var __arrayTemplate:Array
var __array:Array
var __currentValue:Number
/////////////////////////////////////////////////////////////////////////////////////////////////////////
function RandomNumber(firstNumber_,lastNumber_){
__firstNumber=firstNumber_
__lastNumber=lastNumber_
createArrayTemplate()
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
function createArrayTemplate(){
this.__arrayTemplate=[]
for(var i=this.__firstNumber;i<=__lastNumber;i++){
this.__arrayTemplate.push(i)
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
function getRandomNumber(){
var value=getRandom()
if(value==this.__currentValue){
var value=getRandom()
}
this.__currentValue=value
return this.__currentValue;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
private function getRandom(){
if(this.__array.length==0||this.__array==undefined){
this.__array=this.__arrayTemplate.slice()
}
var length:Number=this.__array.length
var _nrPosition=random(length)
var value=this.__array[_nrPosition]
this.__array.splice(_nrPosition,1)
return value
}
//////////////////////////////////////////////////////////////////
} |
package _-E4
{
import mx.core.ByteArrayAsset;
public class Level1_humanWaypointsInitData extends ByteArrayAsset
{
public function Level1_humanWaypointsInitData()
{
var _loc1_:* = true;
var _loc2_:* = false;
if(_loc1_ || (_loc2_))
{
super();
}
}
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2008 Pierluigi Pesenti (blog.oaxoa.com)
Contributor 2014 Andras Csizmadia (www.vpmedia.eu)
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.oaxoa.fx {
/**
* Lightning Fade Type Enums
*
* @author Pierluigi Pesenti (blog.oaxoa.com)
* @contributor Andras Csizmadia (www.vpmedia.eu)
* @version 0.6.0
*
*/
public final class LightningFadeType {
/**
* TBD
*/
public static const NONE:String = "none";
/**
* TBD
*/
public static const GENERATION:String = "generation";
/**
* TBD
*/
public static const TIP_TO_END:String = "tip";
}
}
|
package{
import flash.display.Sprite;
import flash.events.Event;
/**
* ...
* @author illuzor // illuzor.com
*/
public class Main extends Sprite {
private var vect:Vector.<String> = new <String>["sdfs", "sfsf", "sgsgsg"]
public function Main() {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
for (var i:int = 0; i < vect.length; i++) {
trace(vect[i])
}
for each (var item:String in vect) {
trace(item)
}
for (var name:String in vect) {
trace(name)
}
}
}
} |
package org.bigbluebutton.core.services
{
import org.as3commons.logging.api.ILogger;
import org.as3commons.logging.api.getClassLogger;
import org.bigbluebutton.core.model.users.UsersModel;
import org.bigbluebutton.core.vo.UserVO;
import org.bigbluebutton.core.vo.VoiceUserVO;
public class UsersService
{
private static const LOGGER:ILogger = getClassLogger(UsersService);
private static var instance:UsersService = null;
private var msgProc: UsersMessageProcessor = new UsersMessageProcessor();
public function UsersService(enforcer: UsersServiceSingletonEnforcer) {
if (enforcer == null){
throw new Error("There can only be 1 UsersService instance");
}
}
public static function getInstance():UsersService{
if (instance == null){
instance = new UsersService(new UsersServiceSingletonEnforcer());
}
return instance;
}
public function userJoinedVoice(user:Object):void {
var vu: VoiceUserVO = msgProc.processUserJoinedVoiceMessage(user);
if (vu != null) {
var u: UserVO = UsersModel.getInstance().userJoinedVoice(vu);
if (u != null) {
// dispatch event
}
}
}
public function userLeftVoice(user: Object):void {
var vu: VoiceUserVO = msgProc.processUserLeftVoiceMessage(user);
if (vu != null) {
var u: UserVO = UsersModel.getInstance().userLeftVoice(vu);
if (u != null) {
// dispatch event
}
}
}
public function userJoined(user: Object):void {
var vu: UserVO = msgProc.processUserJoinedMessage(user);
if (vu != null) {
var u: UserVO = UsersModel.getInstance().userJoined(vu);
if (u != null) {
// dispatch event
}
}
}
public function userLeft(user: Object):void {
var vu:UserVO = msgProc.processUserLeftMessage(user);
if (vu != null) {
var u: UserVO = UsersModel.getInstance().userLeft(vu);
if (u != null) {
// dispatch event
}
}
}
public function userMuted(msg: Object):void {
var vu: Object = msgProc.processUserMutedMessage(msg);
if (vu != null) {
var u: UserVO = UsersModel.getInstance().userMuted(vu.userId, vu.voiceId, vu.muted);
if (u != null) {
// dispatch event
}
}
}
public function userTalking(msg: Object):void {
var vu: Object = msgProc.processUserTalkingMessage(msg);
if (vu != null) {
var u: UserVO = UsersModel.getInstance().userTalking(vu.userId, vu.voiceId, vu.talking);
if (u != null) {
// dispatch event
}
}
}
}
}
class UsersServiceSingletonEnforcer{}
|
/*
Feathers
Copyright 2012-2016 Bowler Hat LLC. All Rights Reserved.
This program is free software. You can redistribute and/or modify it in
accordance with the terms of the accompanying license agreement.
*/
package feathers.controls
{
import feathers.core.FeathersControl;
import feathers.core.IFeathersControl;
import feathers.core.IFocusDisplayObject;
import feathers.core.IMeasureDisplayObject;
import feathers.core.IValidating;
import feathers.core.PropertyProxy;
import feathers.events.ExclusiveTouch;
import feathers.events.FeathersEventType;
import feathers.layout.Direction;
import feathers.skins.IStyleProvider;
import feathers.utils.math.clamp;
import feathers.utils.math.roundToNearest;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.ui.Keyboard;
import flash.utils.Timer;
import starling.display.DisplayObject;
import starling.events.Event;
import starling.events.KeyboardEvent;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.events.TouchPhase;
/**
* A style name to add to the slider's maximum track sub-component.
* Typically used by a theme to provide different skins to different
* sliders.
*
* <p>In the following example, a custom maximum track style name is
* passed to the slider:</p>
*
* <listing version="3.0">
* slider.customMaximumTrackStyleName = "my-custom-maximum-track";</listing>
*
* <p>In your theme, you can target this sub-component style name to
* provide different styles than the default:</p>
*
* <listing version="3.0">
* getStyleProviderForClass( Button ).setFunctionForStyleName( "my-custom-maximum-track", setCustomMaximumTrackStyles );</listing>
*
* @default null
*
* @see #DEFAULT_CHILD_STYLE_NAME_MAXIMUM_TRACK
* @see feathers.core.FeathersControl#styleNameList
* @see #maximumTrackFactory
*/
[Style(name="customMaximumTrackStyleName",type="String")]
/**
* A style name to add to the slider's minimum track sub-component.
* Typically used by a theme to provide different styles to different
* sliders.
*
* <p>In the following example, a custom minimum track style name is
* passed to the slider:</p>
*
* <listing version="3.0">
* slider.customMinimumTrackStyleName = "my-custom-minimum-track";</listing>
*
* <p>In your theme, you can target this sub-component style name to
* provide different styles than the default:</p>
*
* <listing version="3.0">
* getStyleProviderForClass( Button ).setFunctionForStyleName( "my-custom-minimum-track", setCustomMinimumTrackStyles );</listing>
*
* @default null
*
* @see #DEFAULT_CHILD_STYLE_NAME_MINIMUM_TRACK
* @see feathers.core.FeathersControl#styleNameList
* @see #minimumTrackFactory
*/
[Style(name="customMinimumTrackStyleName",type="String")]
/**
* A style name to add to the slider's thumb sub-component. Typically
* used by a theme to provide different styles to different sliders.
*
* <p>In the following example, a custom thumb style name is passed
* to the slider:</p>
*
* <listing version="3.0">
* slider.customThumbStyleName = "my-custom-thumb";</listing>
*
* <p>In your theme, you can target this sub-component style name to
* provide different styles than the default:</p>
*
* <listing version="3.0">
* getStyleProviderForClass( Button ).setFunctionForStyleName( "my-custom-thumb", setCustomThumbStyles );</listing>
*
* @default null
*
* @see #DEFAULT_CHILD_STYLE_NAME_THUMB
* @see feathers.core.FeathersControl#styleNameList
* @see #thumbFactory
*/
[Style(name="customThumbStyleName",type="String")]
/**
* Determines if the slider's thumb can be dragged horizontally or
* vertically. When this value changes, the slider's width and height
* values do not change automatically.
*
* <p>In the following example, the direction is changed to vertical:</p>
*
* <listing version="3.0">
* slider.direction = Direction.VERTICAL;</listing>
*
* @default feathers.layout.Direction.HORIZONTAL
*
* @see feathers.layout.Direction#HORIZONTAL
* @see feathers.layout.Direction#VERTICAL
*/
[Style(name="direction",type="String")]
/**
* The space, in pixels, between the maximum position of the thumb and
* the maximum edge of the track. May be negative to extend the range
* of the thumb.
*
* <p>In the following example, maximum padding is set to 20 pixels:</p>
*
* <listing version="3.0">
* slider.maximumPadding = 20;</listing>
*
* @default 0
*
* @see #style:minimumPadding
*/
[Style(name="maximumPadding",type="Number")]
/**
* The space, in pixels, between the minimum position of the thumb and
* the minimum edge of the track. May be negative to extend the range of
* the thumb.
*
* <p>In the following example, minimum padding is set to 20 pixels:</p>
*
* <listing version="3.0">
* slider.minimumPadding = 20;</listing>
*
* @default 0
*
* @see #style:maximumPadding
*/
[Style(name="minimumPadding",type="Number")]
/**
* Determines if the thumb should be displayed.
*
* <p>In the following example, the thumb is hidden:</p>
*
* <listing version="3.0">
* slider.showThumb = false;</listing>
*
* @default true
*/
[Style(name="showThumb",type="Boolean")]
/**
* Offsets the position of the thumb by a certain number of pixels in a
* direction perpendicular to the track. This does not affect the
* measurement of the slider. The slider will measure itself as if the
* thumb were not offset from its original position.
*
* <p>In the following example, the thumb is offset by 20 pixels:</p>
*
* <listing version="3.0">
* slider.thumbOffset = 20;</listing>
*
* @default 0
*/
[Style(name="thumbOffset",type="Number")]
/**
* Determines how the slider's value changes when the track is touched.
*
* <p>If <code>showThumb</code> is set to <code>false</code>, the slider
* will always behave as if <code>trackInteractionMode</code> has been
* set to <code>TrackInteractionMode.TO_VALUE</code>. In other
* words, the value of <code>trackInteractionMode</code> may be ignored
* if the thumb is hidden.</p>
*
* <p>In the following example, the slider's track interaction is changed:</p>
*
* <listing version="3.0">
* slider.trackScaleMode = TrackInteractionMode.BY_PAGE;</listing>
*
* @default TrackInteractionMode.TO_VALUE
*
* @see feathers.controls.TrackInteractionMode#TO_VALUE
* @see feathers.controls.TrackInteractionMode#BY_PAGE
* @see #page
*/
[Style(name="trackInteractionMode",type="String")]
/**
* Determines how the minimum and maximum track skins are positioned and
* sized.
*
* <p>In the following example, the slider is given two tracks:</p>
*
* <listing version="3.0">
* slider.trackLayoutMode = TrackLayoutMode.SPLIT;</listing>
*
* @default feathers.controls.TrackLayoutMode.SINGLE
*
* @see feathers.controls.TrackLayoutMode#SINGLE
* @see feathers.controls.TrackLayoutMode#SPLIT
* @see #style:trackScaleMode
*/
[Style(name="trackLayoutMode",type="String")]
/**
* Determines how the minimum and maximum track skins are positioned and
* sized.
*
* <p>In the following example, the slider's track layout is customized:</p>
*
* <listing version="3.0">
* slider.trackScaleMode = TrackScaleMode.EXACT_FIT;</listing>
*
* @default feathers.controls.TrackScaleMode.DIRECTIONAL
*
* @see feathers.controls.TrackScaleMode#DIRECTIONAL
* @see feathers.controls.TrackScaleMode#EXACT_FIT
* @see #style:trackLayoutMode
*/
[Style(name="trackScaleMode",type="String")]
/**
* Dispatched when the slider's value changes.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>.</td></tr>
* <tr><td><code>data</code></td><td>null</td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event. Use the
* <code>currentTarget</code> property to always access the Object
* listening for the event.</td></tr>
* </table>
*
* @eventType starling.events.Event.CHANGE
*/
[Event(name="change",type="starling.events.Event")]
/**
* Dispatched when the user starts dragging the slider's thumb or track.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>.</td></tr>
* <tr><td><code>data</code></td><td>null</td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event. Use the
* <code>currentTarget</code> property to always access the Object
* listening for the event.</td></tr>
* </table>
*
* @eventType feathers.events.FeathersEventType.BEGIN_INTERACTION
*/
[Event(name="beginInteraction",type="starling.events.Event")]
/**
* Dispatched when the user stops dragging the slider's thumb or track.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>.</td></tr>
* <tr><td><code>data</code></td><td>null</td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event. Use the
* <code>currentTarget</code> property to always access the Object
* listening for the event.</td></tr>
* </table>
*
* @eventType feathers.events.FeathersEventType.END_INTERACTION
*/
[Event(name="endInteraction",type="starling.events.Event")]
/**
* Select a value between a minimum and a maximum by dragging a thumb over
* the bounds of a track. The slider's track is divided into two parts split
* by the thumb.
*
* <p>The following example sets the slider's range and listens for when the
* value changes:</p>
*
* <listing version="3.0">
* var slider:Slider = new Slider();
* slider.minimum = 0;
* slider.maximum = 100;
* slider.step = 1;
* slider.page = 10;
* slider.value = 12;
* slider.addEventListener( Event.CHANGE, slider_changeHandler );
* this.addChild( slider );</listing>
*
* @see ../../../help/slider.html How to use the Feathers Slider component
*/
public class Slider extends FeathersControl implements IDirectionalScrollBar, IFocusDisplayObject
{
/**
* @private
*/
private static const HELPER_POINT:Point = new Point();
/**
* @private
*/
protected static const INVALIDATION_FLAG_THUMB_FACTORY:String = "thumbFactory";
/**
* @private
*/
protected static const INVALIDATION_FLAG_MINIMUM_TRACK_FACTORY:String = "minimumTrackFactory";
/**
* @private
*/
protected static const INVALIDATION_FLAG_MAXIMUM_TRACK_FACTORY:String = "maximumTrackFactory";
/**
* @private
* DEPRECATED: Replaced by <code>feathers.layout.Direction.HORIZONTAL</code>.
*
* <p><strong>DEPRECATION WARNING:</strong> This constant is deprecated
* starting with Feathers 3.0. It will be removed in a future version of
* Feathers according to the standard
* <a target="_top" href="../../../help/deprecation-policy.html">Feathers deprecation policy</a>.</p>
*/
public static const DIRECTION_HORIZONTAL:String = "horizontal";
/**
* @private
* DEPRECATED: Replaced by <code>feathers.layout.Direction.VERTICAL</code>.
*
* <p><strong>DEPRECATION WARNING:</strong> This constant is deprecated
* starting with Feathers 3.0. It will be removed in a future version of
* Feathers according to the standard
* <a target="_top" href="../../../help/deprecation-policy.html">Feathers deprecation policy</a>.</p>
*/
public static const DIRECTION_VERTICAL:String = "vertical";
/**
* @private
* DEPRECATED: Replaced by <code>feathers.controls.TrackLayoutMode.SINGLE</code>.
*
* <p><strong>DEPRECATION WARNING:</strong> This constant is deprecated
* starting with Feathers 3.0. It will be removed in a future version of
* Feathers according to the standard
* <a target="_top" href="../../../help/deprecation-policy.html">Feathers deprecation policy</a>.</p>
*/
public static const TRACK_LAYOUT_MODE_SINGLE:String = "single";
/**
* @private
* DEPRECATED: Replaced by <code>feathers.controls.TrackLayoutMode.SPLIT</code>.
*
* <p><strong>DEPRECATION WARNING:</strong> This constant is deprecated
* starting with Feathers 3.0. It will be removed in a future version of
* Feathers according to the standard
* <a target="_top" href="../../../help/deprecation-policy.html">Feathers deprecation policy</a>.</p>
*/
public static const TRACK_LAYOUT_MODE_MIN_MAX:String = "minMax";
/**
* @private
* DEPRECATED: Replaced by <code>feathers.controls.TrackLayoutMode.EXACT_FIT</code>.
*
* <p><strong>DEPRECATION WARNING:</strong> This constant is deprecated
* starting with Feathers 3.0. It will be removed in a future version of
* Feathers according to the standard
* <a target="_top" href="../../../help/deprecation-policy.html">Feathers deprecation policy</a>.</p>
*/
public static const TRACK_SCALE_MODE_EXACT_FIT:String = "exactFit";
/**
* @private
* DEPRECATED: Replaced by <code>feathers.controls.TrackLayoutMode.DIRECTIONAL</code>.
*
* <p><strong>DEPRECATION WARNING:</strong> This constant is deprecated
* starting with Feathers 3.0. It will be removed in a future version of
* Feathers according to the standard
* <a target="_top" href="../../../help/deprecation-policy.html">Feathers deprecation policy</a>.</p>
*/
public static const TRACK_SCALE_MODE_DIRECTIONAL:String = "directional";
/**
* @private
* DEPRECATED: Replaced by <code>feathers.controls.TrackInteractionMode.TO_VALUE</code>.
*
* <p><strong>DEPRECATION WARNING:</strong> This constant is deprecated
* starting with Feathers 3.0. It will be removed in a future version of
* Feathers according to the standard
* <a target="_top" href="../../../help/deprecation-policy.html">Feathers deprecation policy</a>.</p>
*/
public static const TRACK_INTERACTION_MODE_TO_VALUE:String = "toValue";
/**
* @private
* DEPRECATED: Replaced by <code>feathers.controls.TrackInteractionMode.BY_PAGE</code>.
*
* <p><strong>DEPRECATION WARNING:</strong> This constant is deprecated
* starting with Feathers 3.0. It will be removed in a future version of
* Feathers according to the standard
* <a target="_top" href="../../../help/deprecation-policy.html">Feathers deprecation policy</a>.</p>
*/
public static const TRACK_INTERACTION_MODE_BY_PAGE:String = "byPage";
/**
* The default value added to the <code>styleNameList</code> of the
* minimum track.
*
* @see feathers.core.FeathersControl#styleNameList
*/
public static const DEFAULT_CHILD_STYLE_NAME_MINIMUM_TRACK:String = "feathers-slider-minimum-track";
/**
* The default value added to the <code>styleNameList</code> of the
* maximum track.
*
* @see feathers.core.FeathersControl#styleNameList
*/
public static const DEFAULT_CHILD_STYLE_NAME_MAXIMUM_TRACK:String = "feathers-slider-maximum-track";
/**
* The default value added to the <code>styleNameList</code> of the thumb.
*
* @see feathers.core.FeathersControl#styleNameList
*/
public static const DEFAULT_CHILD_STYLE_NAME_THUMB:String = "feathers-slider-thumb";
/**
* The default <code>IStyleProvider</code> for all <code>Slider</code>
* components.
*
* @default null
* @see feathers.core.FeathersControl#styleProvider
*/
public static var globalStyleProvider:IStyleProvider;
/**
* @private
*/
protected static function defaultThumbFactory():BasicButton
{
return new Button();
}
/**
* @private
*/
protected static function defaultMinimumTrackFactory():BasicButton
{
return new Button();
}
/**
* @private
*/
protected static function defaultMaximumTrackFactory():BasicButton
{
return new Button();
}
/**
* Constructor.
*/
public function Slider()
{
super();
this.addEventListener(Event.REMOVED_FROM_STAGE, slider_removedFromStageHandler);
}
/**
* The value added to the <code>styleNameList</code> of the minimum
* track. This variable is <code>protected</code> so that sub-classes
* can customize the minimum track style name in their constructors
* instead of using the default style name defined by
* <code>DEFAULT_CHILD_STYLE_NAME_MINIMUM_TRACK</code>.
*
* <p>To customize the minimum track style name without subclassing, see
* <code>customMinimumTrackStyleName</code>.</p>
*
* @see #style:customMinimumTrackStyleName
* @see feathers.core.FeathersControl#styleNameList
*/
protected var minimumTrackStyleName:String = DEFAULT_CHILD_STYLE_NAME_MINIMUM_TRACK;
/**
* The value added to the <code>styleNameList</code> of the maximum
* track. This variable is <code>protected</code> so that sub-classes
* can customize the maximum track style name in their constructors
* instead of using the default style name defined by
* <code>DEFAULT_CHILD_STYLE_NAME_MAXIMUM_TRACK</code>.
*
* <p>To customize the maximum track style name without subclassing, see
* <code>customMaximumTrackStyleName</code>.</p>
*
* @see #style:customMaximumTrackStyleName
* @see feathers.core.FeathersControl#styleNameList
*/
protected var maximumTrackStyleName:String = DEFAULT_CHILD_STYLE_NAME_MAXIMUM_TRACK;
/**
* The value added to the <code>styleNameList</code> of the thumb. This
* variable is <code>protected</code> so that sub-classes can customize
* the thumb style name in their constructors instead of using the
* default style name defined by <code>DEFAULT_CHILD_STYLE_NAME_THUMB</code>.
*
* <p>To customize the thumb style name without subclassing, see
* <code>customThumbStyleName</code>.</p>
*
* @see #style:customThumbStyleName
* @see feathers.core.FeathersControl#styleNameList
*/
protected var thumbStyleName:String = DEFAULT_CHILD_STYLE_NAME_THUMB;
/**
* The thumb sub-component.
*
* <p>For internal use in subclasses.</p>
*
* @see #thumbFactory
* @see #createThumb()
*/
protected var thumb:DisplayObject;
/**
* The minimum track sub-component.
*
* <p>For internal use in subclasses.</p>
*
* @see #minimumTrackFactory
* @see #createMinimumTrack()
*/
protected var minimumTrack:DisplayObject;
/**
* The maximum track sub-component.
*
* <p>For internal use in subclasses.</p>
*
* @see #maximumTrackFactory
* @see #createMaximumTrack()
*/
protected var maximumTrack:DisplayObject;
/**
* @private
*/
protected var _minimumTrackSkinExplicitWidth:Number;
/**
* @private
*/
protected var _minimumTrackSkinExplicitHeight:Number;
/**
* @private
*/
protected var _minimumTrackSkinExplicitMinWidth:Number;
/**
* @private
*/
protected var _minimumTrackSkinExplicitMinHeight:Number;
/**
* @private
*/
protected var _maximumTrackSkinExplicitWidth:Number;
/**
* @private
*/
protected var _maximumTrackSkinExplicitHeight:Number;
/**
* @private
*/
protected var _maximumTrackSkinExplicitMinWidth:Number;
/**
* @private
*/
protected var _maximumTrackSkinExplicitMinHeight:Number;
/**
* @private
*/
override protected function get defaultStyleProvider():IStyleProvider
{
return Slider.globalStyleProvider;
}
/**
* @private
*/
protected var _direction:String = Direction.HORIZONTAL;
[Inspectable(type="String",enumeration="horizontal,vertical")]
/**
* @private
*/
public function get direction():String
{
return this._direction;
}
/**
* @private
*/
public function set direction(value:String):void
{
if(this.processStyleRestriction(arguments.callee))
{
return;
}
if(this._direction === value)
{
return;
}
this._direction = value;
this.invalidate(INVALIDATION_FLAG_DATA);
this.invalidate(INVALIDATION_FLAG_MINIMUM_TRACK_FACTORY);
this.invalidate(INVALIDATION_FLAG_MAXIMUM_TRACK_FACTORY);
this.invalidate(INVALIDATION_FLAG_THUMB_FACTORY);
}
/**
* @private
*/
protected var _value:Number = 0;
/**
* The value of the slider, between the minimum and maximum.
*
* <p>In the following example, the value is changed to 12:</p>
*
* <listing version="3.0">
* slider.minimum = 0;
* slider.maximum = 100;
* slider.step = 1;
* slider.page = 10
* slider.value = 12;</listing>
*
* @default 0
*
* @see #minimum
* @see #maximum
* @see #step
* @see #page
*/
public function get value():Number
{
return this._value;
}
/**
* @private
*/
public function set value(newValue:Number):void
{
if(this._step != 0 && newValue != this._maximum && newValue != this._minimum)
{
newValue = roundToNearest(newValue - this._minimum, this._step) + this._minimum;
}
newValue = clamp(newValue, this._minimum, this._maximum);
if(this._value == newValue)
{
return;
}
this._value = newValue;
this.invalidate(INVALIDATION_FLAG_DATA);
if(this.liveDragging || !this.isDragging)
{
this.dispatchEventWith(Event.CHANGE);
}
}
/**
* @private
*/
protected var _minimum:Number = 0;
/**
* The slider's value will not go lower than the minimum.
*
* <p>In the following example, the minimum is set to 0:</p>
*
* <listing version="3.0">
* slider.minimum = 0;
* slider.maximum = 100;
* slider.step = 1;
* slider.page = 10
* slider.value = 12;</listing>
*
* @default 0
*
* @see #value
* @see #maximum
*/
public function get minimum():Number
{
return this._minimum;
}
/**
* @private
*/
public function set minimum(value:Number):void
{
if(this._minimum == value)
{
return;
}
this._minimum = value;
this.invalidate(INVALIDATION_FLAG_DATA);
}
/**
* @private
*/
protected var _maximum:Number = 0;
/**
* The slider's value will not go higher than the maximum. The maximum
* is zero (<code>0</code>), by default, and it should almost always be
* changed to something more appropriate.
*
* <p>In the following example, the maximum is set to 100:</p>
*
* <listing version="3.0">
* slider.minimum = 0;
* slider.maximum = 100;
* slider.step = 1;
* slider.page = 10
* slider.value = 12;</listing>
*
* @default 0
*
* @see #value
* @see #minimum
*/
public function get maximum():Number
{
return this._maximum;
}
/**
* @private
*/
public function set maximum(value:Number):void
{
if(this._maximum == value)
{
return;
}
this._maximum = value;
this.invalidate(INVALIDATION_FLAG_DATA);
}
/**
* @private
*/
protected var _step:Number = 0;
/**
* As the slider's thumb is dragged, the value is snapped to a multiple
* of the step. Paging using the slider's track will use the <code>step</code>
* value if the <code>page</code> value is <code>NaN</code>. If the
* <code>step</code> is zero (<code>0</code>), paging with the track will not be possible.
*
* <p>In the following example, the step is changed to 1:</p>
*
* <listing version="3.0">
* slider.minimum = 0;
* slider.maximum = 100;
* slider.step = 1;
* slider.page = 10;
* slider.value = 10;</listing>
*
* @default 0
*
* @see #value
* @see #page
*/
public function get step():Number
{
return this._step;
}
/**
* @private
*/
public function set step(value:Number):void
{
if(this._step == value)
{
return;
}
this._step = value;
}
/**
* @private
*/
protected var _page:Number = NaN;
/**
* If the <code>trackInteractionMode</code> property is set to
* <code>TrackInteractionMode.BY_PAGE</code>, and the slider's
* track is touched, and the thumb is shown, the slider value will be
* incremented or decremented by the page value. If the
* <code>trackInteractionMode</code> property is set to
* <code>TrackInteractionMode.TO_VALUE</code>, this property will be
* ignored.
*
* <p>If this value is <code>NaN</code>, the <code>step</code> value
* will be used instead. If the <code>step</code> value is zero, paging
* with the track is not possible.</p>
*
* <p>In the following example, the page is changed to 10:</p>
*
* <listing version="3.0">
* slider.minimum = 0;
* slider.maximum = 100;
* slider.step = 1;
* slider.page = 10
* slider.value = 12;</listing>
*
* @default NaN
*
* @see #value
* @see #page
* @see #style:trackInteractionMode
*/
public function get page():Number
{
return this._page;
}
/**
* @private
*/
public function set page(value:Number):void
{
if(this._page == value)
{
return;
}
this._page = value;
}
/**
* @private
*/
protected var isDragging:Boolean = false;
/**
* Determines if the slider dispatches the <code>Event.CHANGE</code>
* event every time the thumb moves, or only once it stops moving.
*
* <p>In the following example, live dragging is disabled:</p>
*
* <listing version="3.0">
* slider.liveDragging = false;</listing>
*
* @default true
*/
public var liveDragging:Boolean = true;
/**
* @private
*/
protected var _showThumb:Boolean = true;
/**
* @private
*/
public function get showThumb():Boolean
{
return this._showThumb;
}
/**
* @private
*/
public function set showThumb(value:Boolean):void
{
if(this.processStyleRestriction(arguments.callee))
{
return;
}
if(this._showThumb === value)
{
return;
}
this._showThumb = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _thumbOffset:Number = 0;
/**
* @private
*/
public function get thumbOffset():Number
{
return this._thumbOffset;
}
/**
* @private
*/
public function set thumbOffset(value:Number):void
{
if(this.processStyleRestriction(arguments.callee))
{
return;
}
if(this._thumbOffset === value)
{
return;
}
this._thumbOffset = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _minimumPadding:Number = 0;
/**
* @private
*/
public function get minimumPadding():Number
{
return this._minimumPadding;
}
/**
* @private
*/
public function set minimumPadding(value:Number):void
{
if(this.processStyleRestriction(arguments.callee))
{
return;
}
if(this._minimumPadding === value)
{
return;
}
this._minimumPadding = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _maximumPadding:Number = 0;
/**
* @private
*/
public function get maximumPadding():Number
{
return this._maximumPadding;
}
/**
* @private
*/
public function set maximumPadding(value:Number):void
{
if(this.processStyleRestriction(arguments.callee))
{
return;
}
if(this._maximumPadding === value)
{
return;
}
this._maximumPadding = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _trackLayoutMode:String = TrackLayoutMode.SINGLE;
[Inspectable(type="String",enumeration="single,split")]
/**
* @private
*/
public function get trackLayoutMode():String
{
return this._trackLayoutMode;
}
/**
* @private
*/
public function set trackLayoutMode(value:String):void
{
if(value === TRACK_LAYOUT_MODE_MIN_MAX)
{
value = TrackLayoutMode.SPLIT;
}
if(this.processStyleRestriction(arguments.callee))
{
return;
}
if(this._trackLayoutMode === value)
{
return;
}
this._trackLayoutMode = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _trackScaleMode:String = TrackScaleMode.DIRECTIONAL;
[Inspectable(type="String",enumeration="exactFit,directional")]
/**
* @private
*/
public function get trackScaleMode():String
{
return this._trackScaleMode;
}
/**
* @private
*/
public function set trackScaleMode(value:String):void
{
if(this.processStyleRestriction(arguments.callee))
{
return;
}
if(this._trackScaleMode === value)
{
return;
}
this._trackScaleMode = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _trackInteractionMode:String = TrackInteractionMode.TO_VALUE;
[Inspectable(type="String",enumeration="toValue,byPage")]
/**
* @private
*/
public function get trackInteractionMode():String
{
return this._trackInteractionMode;
}
/**
* @private
*/
public function set trackInteractionMode(value:String):void
{
if(this.processStyleRestriction(arguments.callee))
{
return;
}
this._trackInteractionMode = value;
}
/**
* @private
*/
protected var currentRepeatAction:Function;
/**
* @private
*/
protected var _repeatTimer:Timer;
/**
* @private
*/
protected var _repeatDelay:Number = 0.05;
/**
* The time, in seconds, before actions are repeated. The first repeat
* happens after a delay that is five times longer than the following
* repeats.
*
* <p>In the following example, the slider's repeat delay is set to
* 500 milliseconds:</p>
*
* <listing version="3.0">
* slider.repeatDelay = 0.5;</listing>
*
* @default 0.05
*/
public function get repeatDelay():Number
{
return this._repeatDelay;
}
/**
* @private
*/
public function set repeatDelay(value:Number):void
{
if(this._repeatDelay == value)
{
return;
}
this._repeatDelay = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _minimumTrackFactory:Function;
/**
* A function used to generate the slider's minimum track sub-component.
* The minimum track must be an instance of <code>BasicButton</code> (or
* a subclass). This factory can be used to change properties on the
* minimum track when it is first created. For instance, if you are
* skinning Feathers components without a theme, you might use this
* factory to set skins and other styles on the minimum track.
*
* <p>The function should have the following signature:</p>
* <pre>function():BasicButton</pre>
*
* <p>In the following example, a custom minimum track factory is passed
* to the slider:</p>
*
* <listing version="3.0">
* slider.minimumTrackFactory = function():BasicButton
* {
* var track:BasicButton = new BasicButton();
* var skin:ImageSkin = new ImageSkin( upTexture );
* skin.setTextureForState( ButtonState.DOWN, downTexture );
* track.defaultSkin = skin;
* return track;
* };</listing>
*
* @default null
*
* @see feathers.controls.BasicButton
*/
public function get minimumTrackFactory():Function
{
return this._minimumTrackFactory;
}
/**
* @private
*/
public function set minimumTrackFactory(value:Function):void
{
if(this._minimumTrackFactory == value)
{
return;
}
this._minimumTrackFactory = value;
this.invalidate(INVALIDATION_FLAG_MINIMUM_TRACK_FACTORY);
}
/**
* @private
*/
protected var _customMinimumTrackStyleName:String;
/**
* @private
*/
public function get customMinimumTrackStyleName():String
{
return this._customMinimumTrackStyleName;
}
/**
* @private
*/
public function set customMinimumTrackStyleName(value:String):void
{
if(this.processStyleRestriction(arguments.callee))
{
return;
}
if(this._customMinimumTrackStyleName === value)
{
return;
}
this._customMinimumTrackStyleName = value;
this.invalidate(INVALIDATION_FLAG_MINIMUM_TRACK_FACTORY);
}
/**
* @private
*/
protected var _minimumTrackProperties:PropertyProxy;
/**
* An object that stores properties for the slider's "minimum" track,
* and the properties will be passed down to the "minimum" track when
* the slider validates. For a list of available properties, refer to
* <a href="BasicButton.html"><code>feathers.controls.BasicButton</code></a>.
*
* <p>If the subcomponent has its own subcomponents, their properties
* can be set too, using attribute <code>@</code> notation. For example,
* to set the skin on the thumb which is in a <code>SimpleScrollBar</code>,
* which is in a <code>List</code>, you can use the following syntax:</p>
* <pre>list.verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);</pre>
*
* <p>Setting properties in a <code>minimumTrackFactory</code> function
* instead of using <code>minimumTrackProperties</code> will result in
* better performance.</p>
*
* <p>In the following example, the slider's minimum track properties
* are updated:</p>
*
* <listing version="3.0">
* slider.minimumTrackProperties.defaultSkin = new Image( upTexture );
* slider.minimumTrackProperties.downSkin = new Image( downTexture );</listing>
*
* @default null
*
* @see #minimumTrackFactory
* @see feathers.controls.BasicButton
*/
public function get minimumTrackProperties():Object
{
if(!this._minimumTrackProperties)
{
this._minimumTrackProperties = new PropertyProxy(childProperties_onChange);
}
return this._minimumTrackProperties;
}
/**
* @private
*/
public function set minimumTrackProperties(value:Object):void
{
if(this._minimumTrackProperties == value)
{
return;
}
if(!value)
{
value = new PropertyProxy();
}
if(!(value is PropertyProxy))
{
var newValue:PropertyProxy = new PropertyProxy();
for(var propertyName:String in value)
{
newValue[propertyName] = value[propertyName];
}
value = newValue;
}
if(this._minimumTrackProperties)
{
this._minimumTrackProperties.removeOnChangeCallback(childProperties_onChange);
}
this._minimumTrackProperties = PropertyProxy(value);
if(this._minimumTrackProperties)
{
this._minimumTrackProperties.addOnChangeCallback(childProperties_onChange);
}
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _maximumTrackFactory:Function;
/**
* A function used to generate the slider's maximum track sub-component.
* The maximum track must be an instance of <code>BasicButton</code> (or
* a subclass). This factory can be used to change properties on the
* maximum track when it is first created. For instance, if you are
* skinning Feathers components without a theme, you might use this
* factory to set skins and other styles on the maximum track.
*
* <p>The function should have the following signature:</p>
* <pre>function():BasicButton</pre>
*
* <p>In the following example, a custom maximum track factory is passed
* to the slider:</p>
*
* <listing version="3.0">
* slider.maximumTrackFactory = function():BasicButton
* {
* var track:BasicButton = new BasicButton();
* var skin:ImageSkin = new ImageSkin( upTexture );
* skin.setTextureForState( ButtonState.DOWN, downTexture );
* track.defaultSkin = skin;
* return track;
* };</listing>
*
* @default null
*
* @see feathers.controls.BasicButton
*/
public function get maximumTrackFactory():Function
{
return this._maximumTrackFactory;
}
/**
* @private
*/
public function set maximumTrackFactory(value:Function):void
{
if(this._maximumTrackFactory == value)
{
return;
}
this._maximumTrackFactory = value;
this.invalidate(INVALIDATION_FLAG_MAXIMUM_TRACK_FACTORY);
}
/**
* @private
*/
protected var _customMaximumTrackStyleName:String;
/**
* @private
*/
public function get customMaximumTrackStyleName():String
{
return this._customMaximumTrackStyleName;
}
/**
* @private
*/
public function set customMaximumTrackStyleName(value:String):void
{
if(this.processStyleRestriction(arguments.callee))
{
return;
}
if(this._customMaximumTrackStyleName === value)
{
return;
}
this._customMaximumTrackStyleName = value;
this.invalidate(INVALIDATION_FLAG_MAXIMUM_TRACK_FACTORY);
}
/**
* @private
*/
protected var _maximumTrackProperties:PropertyProxy;
/**
* An object that stores properties for the slider's "maximum" track,
* and the properties will be passed down to the "maximum" track when
* the slider validates. For a list of available properties, refer to
* <a href="BasicButton.html"><code>feathers.controls.BasicButton</code></a>.
*
* <p>If the subcomponent has its own subcomponents, their properties
* can be set too, using attribute <code>@</code> notation. For example,
* to set the skin on the thumb which is in a <code>SimpleScrollBar</code>,
* which is in a <code>List</code>, you can use the following syntax:</p>
* <pre>list.verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);</pre>
*
* <p>Setting properties in a <code>maximumTrackFactory</code> function
* instead of using <code>maximumTrackProperties</code> will result in
* better performance.</p>
*
* <p>In the following example, the slider's maximum track properties
* are updated:</p>
*
* <listing version="3.0">
* slider.maximumTrackProperties.defaultSkin = new Image( upTexture );
* slider.maximumTrackProperties.downSkin = new Image( downTexture );</listing>
*
* @default null
*
* @see #maximumTrackFactory
* @see feathers.controls.BasicButton
*/
public function get maximumTrackProperties():Object
{
if(!this._maximumTrackProperties)
{
this._maximumTrackProperties = new PropertyProxy(childProperties_onChange);
}
return this._maximumTrackProperties;
}
/**
* @private
*/
public function set maximumTrackProperties(value:Object):void
{
if(this._maximumTrackProperties == value)
{
return;
}
if(!value)
{
value = new PropertyProxy();
}
if(!(value is PropertyProxy))
{
var newValue:PropertyProxy = new PropertyProxy();
for(var propertyName:String in value)
{
newValue[propertyName] = value[propertyName];
}
value = newValue;
}
if(this._maximumTrackProperties)
{
this._maximumTrackProperties.removeOnChangeCallback(childProperties_onChange);
}
this._maximumTrackProperties = PropertyProxy(value);
if(this._maximumTrackProperties)
{
this._maximumTrackProperties.addOnChangeCallback(childProperties_onChange);
}
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _thumbFactory:Function;
/**
* A function used to generate the slider's thumb sub-component.
* The thumb must be an instance of <code>BasicButton</code> (or a
* subclass). This factory can be used to change properties on the thumb
* when it is first created. For instance, if you are skinning Feathers
* components without a theme, you might use this factory to set skins
* and other styles on the thumb.
*
* <p>The function should have the following signature:</p>
* <pre>function():BasicButton</pre>
*
* <p>In the following example, a custom thumb factory is passed
* to the slider:</p>
*
* <listing version="3.0">
* slider.thumbFactory = function():BasicButton
* {
* var thumb:BasicButton = new BasicButton();
* var skin:ImageSkin = new ImageSkin( upTexture );
* skin.setTextureForState( ButtonState.DOWN, downTexture );
* thumb.defaultSkin = skin;
* return thumb;
* };</listing>
*
* @default null
*
* @see feathers.controls.BasicButton
*/
public function get thumbFactory():Function
{
return this._thumbFactory;
}
/**
* @private
*/
public function set thumbFactory(value:Function):void
{
if(this._thumbFactory == value)
{
return;
}
this._thumbFactory = value;
this.invalidate(INVALIDATION_FLAG_THUMB_FACTORY);
}
/**
* @private
*/
protected var _customThumbStyleName:String;
/**
* @private
*/
public function get customThumbStyleName():String
{
return this._customThumbStyleName;
}
/**
* @private
*/
public function set customThumbStyleName(value:String):void
{
if(this.processStyleRestriction(arguments.callee))
{
return;
}
if(this._customThumbStyleName === value)
{
return;
}
this._customThumbStyleName = value;
this.invalidate(INVALIDATION_FLAG_THUMB_FACTORY);
}
/**
* @private
*/
protected var _thumbProperties:PropertyProxy;
/**
* An object that stores properties for the slider's thumb, and the
* properties will be passed down to the thumb when the slider
* validates. For a list of available properties, refer to
* <a href="BasicButton.html"><code>feathers.controls.BasicButton</code></a>.
*
* <p>If the subcomponent has its own subcomponents, their properties
* can be set too, using attribute <code>@</code> notation. For example,
* to set the skin on the thumb which is in a <code>SimpleScrollBar</code>,
* which is in a <code>List</code>, you can use the following syntax:</p>
* <pre>list.verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);</pre>
*
* <p>Setting properties in a <code>thumbFactory</code> function instead
* of using <code>thumbProperties</code> will result in better
* performance.</p>
*
* <p>In the following example, the slider's thumb properties
* are updated:</p>
*
* <listing version="3.0">
* slider.thumbProperties.defaultSkin = new Image( upTexture );
* slider.thumbProperties.downSkin = new Image( downTexture );</listing>
*
* @default null
*
* @see feathers.controls.BasicButton
* @see #thumbFactory
*/
public function get thumbProperties():Object
{
if(!this._thumbProperties)
{
this._thumbProperties = new PropertyProxy(childProperties_onChange);
}
return this._thumbProperties;
}
/**
* @private
*/
public function set thumbProperties(value:Object):void
{
if(this._thumbProperties == value)
{
return;
}
if(!value)
{
value = new PropertyProxy();
}
if(!(value is PropertyProxy))
{
var newValue:PropertyProxy = new PropertyProxy();
for(var propertyName:String in value)
{
newValue[propertyName] = value[propertyName];
}
value = newValue;
}
if(this._thumbProperties)
{
this._thumbProperties.removeOnChangeCallback(childProperties_onChange);
}
this._thumbProperties = PropertyProxy(value);
if(this._thumbProperties)
{
this._thumbProperties.addOnChangeCallback(childProperties_onChange);
}
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _touchPointID:int = -1;
/**
* @private
*/
protected var _touchStartX:Number = NaN;
/**
* @private
*/
protected var _touchStartY:Number = NaN;
/**
* @private
*/
protected var _thumbStartX:Number = NaN;
/**
* @private
*/
protected var _thumbStartY:Number = NaN;
/**
* @private
*/
protected var _touchValue:Number;
/**
* @private
*/
override protected function initialize():void
{
if(this._value < this._minimum)
{
this.value = this._minimum;
}
else if(this._value > this._maximum)
{
this.value = this._maximum;
}
}
/**
* @private
*/
override protected function draw():void
{
var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES);
var sizeInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SIZE);
var stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE);
var focusInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_FOCUS);
var layoutInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_LAYOUT);
var thumbFactoryInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_THUMB_FACTORY);
var minimumTrackFactoryInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_MINIMUM_TRACK_FACTORY);
var maximumTrackFactoryInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_MAXIMUM_TRACK_FACTORY);
if(thumbFactoryInvalid)
{
this.createThumb();
}
if(minimumTrackFactoryInvalid)
{
this.createMinimumTrack();
}
if(maximumTrackFactoryInvalid || layoutInvalid)
{
this.createMaximumTrack();
}
if(thumbFactoryInvalid || stylesInvalid)
{
this.refreshThumbStyles();
}
if(minimumTrackFactoryInvalid || stylesInvalid)
{
this.refreshMinimumTrackStyles();
}
if((maximumTrackFactoryInvalid || layoutInvalid || stylesInvalid) && this.maximumTrack)
{
this.refreshMaximumTrackStyles();
}
if(stateInvalid || thumbFactoryInvalid || minimumTrackFactoryInvalid ||
maximumTrackFactoryInvalid)
{
this.refreshEnabled();
}
sizeInvalid = this.autoSizeIfNeeded() || sizeInvalid;
this.layoutChildren();
if(sizeInvalid || focusInvalid)
{
this.refreshFocusIndicator();
}
}
/**
* If the component's dimensions have not been set explicitly, it will
* measure its content and determine an ideal size for itself. If the
* <code>explicitWidth</code> or <code>explicitHeight</code> member
* variables are set, those value will be used without additional
* measurement. If one is set, but not the other, the dimension with the
* explicit value will not be measured, but the other non-explicit
* dimension will still need measurement.
*
* <p>Calls <code>saveMeasurements()</code> to set up the
* <code>actualWidth</code> and <code>actualHeight</code> member
* variables used for layout.</p>
*
* <p>Meant for internal use, and subclasses may override this function
* with a custom implementation.</p>
*/
protected function autoSizeIfNeeded():Boolean
{
if(this._direction === Direction.VERTICAL)
{
return this.measureVertical();
}
return this.measureHorizontal();
}
/**
* @private
*/
protected function measureVertical():Boolean
{
var needsWidth:Boolean = this._explicitWidth !== this._explicitWidth; //isNaN
var needsHeight:Boolean = this._explicitHeight !== this._explicitHeight; //isNaN
var needsMinWidth:Boolean = this._explicitMinWidth !== this._explicitMinWidth; //isNaN
var needsMinHeight:Boolean = this._explicitMinHeight !== this._explicitMinHeight; //isNaN
if(!needsWidth && !needsHeight && !needsMinWidth && !needsMinHeight)
{
return false;
}
var isSingle:Boolean = this._trackLayoutMode === TrackLayoutMode.SINGLE;
if(needsHeight)
{
this.minimumTrack.height = this._minimumTrackSkinExplicitHeight;
}
else if(isSingle)
{
this.minimumTrack.height = this._explicitHeight;
}
if(this.minimumTrack is IMeasureDisplayObject)
{
var measureMinTrack:IMeasureDisplayObject = IMeasureDisplayObject(this.minimumTrack);
if(needsMinHeight)
{
measureMinTrack.minHeight = this._minimumTrackSkinExplicitMinHeight;
}
else if(isSingle)
{
var minTrackMinHeight:Number = this._explicitMinHeight;
if(this._minimumTrackSkinExplicitMinHeight > minTrackMinHeight)
{
minTrackMinHeight = this._minimumTrackSkinExplicitMinHeight;
}
measureMinTrack.minHeight = minTrackMinHeight;
}
}
if(!isSingle)
{
if(needsHeight)
{
this.maximumTrack.height = this._maximumTrackSkinExplicitHeight;
}
if(this.maximumTrack is IMeasureDisplayObject)
{
var measureMaxTrack:IMeasureDisplayObject = IMeasureDisplayObject(this.maximumTrack);
if(needsMinHeight)
{
measureMaxTrack.minHeight = this._maximumTrackSkinExplicitMinHeight;
}
}
}
if(this.minimumTrack is IValidating)
{
IValidating(this.minimumTrack).validate();
}
if(this.maximumTrack is IValidating)
{
IValidating(this.maximumTrack).validate();
}
if(this.thumb is IValidating)
{
IValidating(this.thumb).validate();
}
var newWidth:Number = this._explicitWidth;
var newHeight:Number = this._explicitHeight;
var newMinWidth:Number = this._explicitMinWidth;
var newMinHeight:Number = this._explicitMinHeight;
if(needsWidth)
{
newWidth = this.minimumTrack.width;
if(!isSingle && //split
this.maximumTrack.width > newWidth)
{
newWidth = this.maximumTrack.width;
}
if(this.thumb.width > newWidth)
{
newWidth = this.thumb.width;
}
}
if(needsHeight)
{
newHeight = this.minimumTrack.height;
if(!isSingle) //split
{
if(this.maximumTrack.height > newHeight)
{
newHeight = this.maximumTrack.height;
}
newHeight += this.thumb.height / 2;
}
}
if(needsMinWidth)
{
if(measureMinTrack !== null)
{
newMinWidth = measureMinTrack.minWidth;
}
else
{
newMinWidth = this.minimumTrack.width;
}
if(!isSingle) //split
{
if(measureMaxTrack !== null)
{
if(measureMaxTrack.minWidth > newMinWidth)
{
newMinWidth = measureMaxTrack.minWidth;
}
}
else if(this.maximumTrack.width > newMinWidth)
{
newMinWidth = this.maximumTrack.width;
}
}
if(this.thumb is IMeasureDisplayObject)
{
var measureThumb:IMeasureDisplayObject = IMeasureDisplayObject(this.thumb);
if(measureThumb.minWidth > newMinWidth)
{
newMinWidth = measureThumb.minWidth;
}
}
else if(this.thumb.width > newMinWidth)
{
newMinWidth = this.thumb.width;
}
}
if(needsMinHeight)
{
if(measureMinTrack !== null)
{
newMinHeight = measureMinTrack.minHeight;
}
else
{
newMinHeight = this.minimumTrack.height;
}
if(!isSingle) //split
{
if(measureMaxTrack !== null)
{
if(measureMaxTrack.minHeight > newMinHeight)
{
newMinHeight = measureMaxTrack.minHeight;
}
}
else
{
newMinHeight = this.maximumTrack.height;
}
if(this.thumb is IMeasureDisplayObject)
{
newMinHeight += IMeasureDisplayObject(this.thumb).minHeight / 2;
}
else
{
newMinHeight += this.thumb.height / 2;
}
}
}
return this.saveMeasurements(newWidth, newHeight, newMinWidth, newMinHeight);
}
/**
* @private
*/
protected function measureHorizontal():Boolean
{
var needsWidth:Boolean = this._explicitWidth !== this._explicitWidth; //isNaN
var needsHeight:Boolean = this._explicitHeight !== this._explicitHeight; //isNaN
var needsMinWidth:Boolean = this._explicitMinWidth !== this._explicitMinWidth; //isNaN
var needsMinHeight:Boolean = this._explicitMinHeight !== this._explicitMinHeight; //isNaN
if(!needsWidth && !needsHeight && !needsMinWidth && !needsMinHeight)
{
return false;
}
var isSingle:Boolean = this._trackLayoutMode === TrackLayoutMode.SINGLE;
if(needsWidth)
{
this.minimumTrack.width = this._minimumTrackSkinExplicitWidth;
}
else if(isSingle)
{
this.minimumTrack.width = this._explicitWidth;
}
if(this.minimumTrack is IMeasureDisplayObject)
{
var measureMinTrack:IMeasureDisplayObject = IMeasureDisplayObject(this.minimumTrack);
if(needsMinWidth)
{
measureMinTrack.minWidth = this._minimumTrackSkinExplicitMinWidth;
}
else if(isSingle)
{
var minTrackMinWidth:Number = this._explicitMinWidth;
if(this._minimumTrackSkinExplicitMinWidth > minTrackMinWidth)
{
minTrackMinWidth = this._minimumTrackSkinExplicitMinWidth;
}
measureMinTrack.minWidth = minTrackMinWidth;
}
}
if(!isSingle)
{
if(needsWidth)
{
this.maximumTrack.width = this._maximumTrackSkinExplicitWidth;
}
if(this.maximumTrack is IMeasureDisplayObject)
{
var measureMaxTrack:IMeasureDisplayObject = IMeasureDisplayObject(this.maximumTrack);
if(needsMinWidth)
{
measureMaxTrack.minWidth = this._maximumTrackSkinExplicitMinWidth;
}
}
}
if(this.minimumTrack is IValidating)
{
IValidating(this.minimumTrack).validate();
}
if(this.maximumTrack is IValidating)
{
IValidating(this.maximumTrack).validate();
}
if(this.thumb is IValidating)
{
IValidating(this.thumb).validate();
}
var newWidth:Number = this._explicitWidth;
var newHeight:Number = this._explicitHeight;
var newMinWidth:Number = this._explicitMinWidth;
var newMinHeight:Number = this._explicitMinHeight;
if(needsWidth)
{
newWidth = this.minimumTrack.width;
if(!isSingle) //split
{
if(this.maximumTrack.width > newWidth)
{
newWidth = this.maximumTrack.width;
}
newWidth += this.thumb.width / 2;
}
}
if(needsHeight)
{
newHeight = this.minimumTrack.height;
if(!isSingle && //split
this.maximumTrack.height > newHeight)
{
newHeight = this.maximumTrack.height;
}
if(this.thumb.height > newHeight)
{
newHeight = this.thumb.height;
}
}
if(needsMinWidth)
{
if(measureMinTrack !== null)
{
newMinWidth = measureMinTrack.minWidth;
}
else
{
newMinWidth = this.minimumTrack.width;
}
if(!isSingle) //split
{
if(measureMaxTrack !== null)
{
if(measureMaxTrack.minWidth > newMinWidth)
{
newMinWidth = measureMaxTrack.minWidth;
}
}
else if(this.maximumTrack.width > newMinWidth)
{
newMinWidth = this.maximumTrack.width;
}
if(this.thumb is IMeasureDisplayObject)
{
newMinWidth += IMeasureDisplayObject(this.thumb).minWidth / 2;
}
else
{
newMinWidth += this.thumb.width / 2;
}
}
}
if(needsMinHeight)
{
if(measureMinTrack !== null)
{
newMinHeight = measureMinTrack.minHeight;
}
else
{
newMinHeight = this.minimumTrack.height;
}
if(!isSingle) //split
{
if(measureMaxTrack !== null)
{
if(measureMaxTrack.minHeight > newMinHeight)
{
newMinHeight = measureMaxTrack.minHeight;
}
}
else if(this.maximumTrack.height > newMinHeight)
{
newMinHeight = this.maximumTrack.height;
}
}
if(this.thumb is IMeasureDisplayObject)
{
var measureThumb:IMeasureDisplayObject = IMeasureDisplayObject(this.thumb);
if(measureThumb.minHeight > newMinHeight)
{
newMinHeight = measureThumb.minHeight;
}
}
else if(this.thumb.height > newMinHeight)
{
newMinHeight = this.thumb.height;
}
}
return this.saveMeasurements(newWidth, newHeight, newMinWidth, newMinHeight);
}
/**
* Creates and adds the <code>thumb</code> sub-component and
* removes the old instance, if one exists.
*
* <p>Meant for internal use, and subclasses may override this function
* with a custom implementation.</p>
*
* @see #thumb
* @see #thumbFactory
* @see #style:customThumbStyleName
*/
protected function createThumb():void
{
if(this.thumb)
{
this.thumb.removeFromParent(true);
this.thumb = null;
}
var factory:Function = this._thumbFactory != null ? this._thumbFactory : defaultThumbFactory;
var thumbStyleName:String = this._customThumbStyleName != null ? this._customThumbStyleName : this.thumbStyleName;
var thumb:BasicButton = BasicButton(factory());
thumb.styleNameList.add(thumbStyleName);
thumb.keepDownStateOnRollOut = true;
thumb.addEventListener(TouchEvent.TOUCH, thumb_touchHandler);
this.addChild(thumb);
this.thumb = thumb;
}
/**
* Creates and adds the <code>minimumTrack</code> sub-component and
* removes the old instance, if one exists.
*
* <p>Meant for internal use, and subclasses may override this function
* with a custom implementation.</p>
*
* @see #minimumTrack
* @see #minimumTrackFactory
* @see #style:customMinimumTrackStyleName
*/
protected function createMinimumTrack():void
{
if(this.minimumTrack)
{
this.minimumTrack.removeFromParent(true);
this.minimumTrack = null;
}
var factory:Function = this._minimumTrackFactory != null ? this._minimumTrackFactory : defaultMinimumTrackFactory;
var minimumTrackStyleName:String = this._customMinimumTrackStyleName != null ? this._customMinimumTrackStyleName : this.minimumTrackStyleName;
var minimumTrack:BasicButton = BasicButton(factory());
minimumTrack.styleNameList.add(minimumTrackStyleName);
minimumTrack.keepDownStateOnRollOut = true;
minimumTrack.addEventListener(TouchEvent.TOUCH, track_touchHandler);
this.addChildAt(minimumTrack, 0);
this.minimumTrack = minimumTrack;
if(this.minimumTrack is IFeathersControl)
{
IFeathersControl(this.minimumTrack).initializeNow();
}
if(this.minimumTrack is IMeasureDisplayObject)
{
var measureMinTrack:IMeasureDisplayObject = IMeasureDisplayObject(this.minimumTrack);
this._minimumTrackSkinExplicitWidth = measureMinTrack.explicitWidth;
this._minimumTrackSkinExplicitHeight = measureMinTrack.explicitHeight;
this._minimumTrackSkinExplicitMinWidth = measureMinTrack.explicitMinWidth;
this._minimumTrackSkinExplicitMinHeight = measureMinTrack.explicitMinHeight;
}
else
{
//this is a regular display object, and we'll treat its
//measurements as explicit when we auto-size the slider
this._minimumTrackSkinExplicitWidth = this.minimumTrack.width;
this._minimumTrackSkinExplicitHeight = this.minimumTrack.height;
this._minimumTrackSkinExplicitMinWidth = this._minimumTrackSkinExplicitWidth;
this._minimumTrackSkinExplicitMinHeight = this._minimumTrackSkinExplicitHeight
}
}
/**
* Creates and adds the <code>maximumTrack</code> sub-component and
* removes the old instance, if one exists. If the maximum track is not
* needed, it will not be created.
*
* <p>Meant for internal use, and subclasses may override this function
* with a custom implementation.</p>
*
* @see #maximumTrack
* @see #maximumTrackFactory
* @see #style:customMaximumTrackStyleName
*/
protected function createMaximumTrack():void
{
if(this.maximumTrack !== null)
{
this.maximumTrack.removeFromParent(true);
this.maximumTrack = null;
}
if(this._trackLayoutMode === TrackLayoutMode.SINGLE)
{
return;
}
var factory:Function = this._maximumTrackFactory != null ? this._maximumTrackFactory : defaultMaximumTrackFactory;
var maximumTrackStyleName:String = this._customMaximumTrackStyleName != null ? this._customMaximumTrackStyleName : this.maximumTrackStyleName;
var maximumTrack:BasicButton = BasicButton(factory());
maximumTrack.styleNameList.add(maximumTrackStyleName);
maximumTrack.keepDownStateOnRollOut = true;
maximumTrack.addEventListener(TouchEvent.TOUCH, track_touchHandler);
this.addChildAt(maximumTrack, 1);
this.maximumTrack = maximumTrack;
if(this.maximumTrack is IFeathersControl)
{
IFeathersControl(this.maximumTrack).initializeNow();
}
if(this.maximumTrack is IMeasureDisplayObject)
{
var measureMaxTrack:IMeasureDisplayObject = IMeasureDisplayObject(this.maximumTrack);
this._maximumTrackSkinExplicitWidth = measureMaxTrack.explicitWidth;
this._maximumTrackSkinExplicitHeight = measureMaxTrack.explicitHeight;
this._maximumTrackSkinExplicitMinWidth = measureMaxTrack.explicitMinWidth;
this._maximumTrackSkinExplicitMinHeight = measureMaxTrack.explicitMinHeight;
}
else
{
//this is a regular display object, and we'll treat its
//measurements as explicit when we auto-size the slider
this._maximumTrackSkinExplicitWidth = this.maximumTrack.width;
this._maximumTrackSkinExplicitHeight = this.maximumTrack.height;
this._maximumTrackSkinExplicitMinWidth = this._maximumTrackSkinExplicitWidth;
this._maximumTrackSkinExplicitMinHeight = this._maximumTrackSkinExplicitHeight
}
}
/**
* @private
*/
protected function refreshThumbStyles():void
{
for(var propertyName:String in this._thumbProperties)
{
var propertyValue:Object = this._thumbProperties[propertyName];
this.thumb[propertyName] = propertyValue;
}
this.thumb.visible = this._showThumb;
}
/**
* @private
*/
protected function refreshMinimumTrackStyles():void
{
for(var propertyName:String in this._minimumTrackProperties)
{
var propertyValue:Object = this._minimumTrackProperties[propertyName];
this.minimumTrack[propertyName] = propertyValue;
}
}
/**
* @private
*/
protected function refreshMaximumTrackStyles():void
{
if(!this.maximumTrack)
{
return;
}
for(var propertyName:String in this._maximumTrackProperties)
{
var propertyValue:Object = this._maximumTrackProperties[propertyName];
this.maximumTrack[propertyName] = propertyValue;
}
}
/**
* @private
*/
protected function refreshEnabled():void
{
if(this.thumb is IFeathersControl)
{
IFeathersControl(this.thumb).isEnabled = this._isEnabled;
}
if(this.minimumTrack is IFeathersControl)
{
IFeathersControl(this.minimumTrack).isEnabled = this._isEnabled;
}
if(this.maximumTrack is IFeathersControl)
{
IFeathersControl(this.maximumTrack).isEnabled = this._isEnabled;
}
}
/**
* @private
*/
protected function layoutChildren():void
{
this.layoutThumb();
if(this._trackLayoutMode == TrackLayoutMode.SPLIT)
{
this.layoutTrackWithMinMax();
}
else //single
{
this.layoutTrackWithSingle();
}
}
/**
* @private
*/
protected function layoutThumb():void
{
//this will auto-size the thumb, if needed
if(this.thumb is IValidating)
{
IValidating(this.thumb).validate();
}
if(this._minimum === this._maximum)
{
var percentage:Number = 1;
}
else
{
percentage = (this._value - this._minimum) / (this._maximum - this._minimum);
if(percentage < 0)
{
percentage = 0;
}
else if(percentage > 1)
{
percentage = 1;
}
}
if(this._direction == Direction.VERTICAL)
{
var trackScrollableHeight:Number = this.actualHeight - this.thumb.height - this._minimumPadding - this._maximumPadding;
this.thumb.x = Math.round((this.actualWidth - this.thumb.width) / 2) + this._thumbOffset;
//maximum is at the top, so we need to start the y position of
//the thumb from the maximum padding
this.thumb.y = Math.round(this._maximumPadding + trackScrollableHeight * (1 - percentage));
}
else //horizontal
{
var trackScrollableWidth:Number = this.actualWidth - this.thumb.width - this._minimumPadding - this._maximumPadding;
//minimum is at the left, so we need to start the x position of
//the thumb from the minimum padding
this.thumb.x = Math.round(this._minimumPadding + (trackScrollableWidth * percentage));
this.thumb.y = Math.round((this.actualHeight - this.thumb.height) / 2) + this._thumbOffset;
}
}
/**
* @private
*/
protected function layoutTrackWithMinMax():void
{
if(this._direction === Direction.VERTICAL)
{
var maximumTrackHeight:Number = Math.round(this.thumb.y + (this.thumb.height / 2));
this.maximumTrack.y = 0;
this.maximumTrack.height = maximumTrackHeight;
this.minimumTrack.y = maximumTrackHeight;
this.minimumTrack.height = this.actualHeight - maximumTrackHeight;
if(this._trackScaleMode === TrackScaleMode.EXACT_FIT)
{
this.maximumTrack.x = 0;
this.maximumTrack.width = this.actualWidth;
this.minimumTrack.x = 0;
this.minimumTrack.width = this.actualWidth;
}
else //directional
{
this.maximumTrack.width = this._maximumTrackSkinExplicitWidth;
this.minimumTrack.width = this._minimumTrackSkinExplicitWidth;
}
//final validation to avoid juggler next frame issues
if(this.minimumTrack is IValidating)
{
IValidating(this.minimumTrack).validate();
}
if(this.maximumTrack is IValidating)
{
IValidating(this.maximumTrack).validate();
}
if(this._trackScaleMode === TrackScaleMode.DIRECTIONAL)
{
this.maximumTrack.x = Math.round((this.actualWidth - this.maximumTrack.width) / 2);
this.minimumTrack.x = Math.round((this.actualWidth - this.minimumTrack.width) / 2);
}
}
else //horizontal
{
var minimumTrackWidth:Number = Math.round(this.thumb.x + (this.thumb.width / 2));
this.minimumTrack.x = 0;
this.minimumTrack.width = minimumTrackWidth;
this.maximumTrack.x = minimumTrackWidth;
this.maximumTrack.width = this.actualWidth - minimumTrackWidth;
if(this._trackScaleMode === TrackScaleMode.EXACT_FIT)
{
this.minimumTrack.y = 0;
this.minimumTrack.height = this.actualHeight;
this.maximumTrack.y = 0;
this.maximumTrack.height = this.actualHeight;
}
else //directional
{
this.minimumTrack.height = this._minimumTrackSkinExplicitHeight;
this.maximumTrack.height = this._maximumTrackSkinExplicitHeight;
}
//final validation to avoid juggler next frame issues
if(this.minimumTrack is IValidating)
{
IValidating(this.minimumTrack).validate();
}
if(this.maximumTrack is IValidating)
{
IValidating(this.maximumTrack).validate();
}
if(this._trackScaleMode === TrackScaleMode.DIRECTIONAL)
{
this.minimumTrack.y = Math.round((this.actualHeight - this.minimumTrack.height) / 2);
this.maximumTrack.y = Math.round((this.actualHeight - this.maximumTrack.height) / 2);
}
}
}
/**
* @private
*/
protected function layoutTrackWithSingle():void
{
if(this._direction === Direction.VERTICAL)
{
this.minimumTrack.y = 0;
this.minimumTrack.height = this.actualHeight;
if(this._trackScaleMode === TrackScaleMode.EXACT_FIT)
{
this.minimumTrack.x = 0;
this.minimumTrack.width = this.actualWidth;
}
else //directional
{
//we'll calculate x after validation in case the track needs
//to auto-size
this.minimumTrack.width = this._minimumTrackSkinExplicitWidth;
}
//final validation to avoid juggler next frame issues
if(this.minimumTrack is IValidating)
{
IValidating(this.minimumTrack).validate();
}
if(this._trackScaleMode === TrackScaleMode.DIRECTIONAL)
{
this.minimumTrack.x = Math.round((this.actualWidth - this.minimumTrack.width) / 2);
}
}
else //horizontal
{
this.minimumTrack.x = 0;
this.minimumTrack.width = this.actualWidth;
if(this._trackScaleMode === TrackScaleMode.EXACT_FIT)
{
this.minimumTrack.y = 0;
this.minimumTrack.height = this.actualHeight;
}
else //directional
{
//we'll calculate y after validation in case the track needs
//to auto-size
this.minimumTrack.height = this._minimumTrackSkinExplicitHeight;
}
//final validation to avoid juggler next frame issues
if(this.minimumTrack is IValidating)
{
IValidating(this.minimumTrack).validate();
}
if(this._trackScaleMode === TrackScaleMode.DIRECTIONAL)
{
this.minimumTrack.y = Math.round((this.actualHeight - this.minimumTrack.height) / 2);
}
}
}
/**
* @private
*/
protected function locationToValue(location:Point):Number
{
var percentage:Number;
if(this._direction == Direction.VERTICAL)
{
var trackScrollableHeight:Number = this.actualHeight - this.thumb.height - this._minimumPadding - this._maximumPadding;
var yOffset:Number = location.y - this._touchStartY - this._maximumPadding;
var yPosition:Number = Math.min(Math.max(0, this._thumbStartY + yOffset), trackScrollableHeight);
percentage = 1 - (yPosition / trackScrollableHeight);
}
else //horizontal
{
var trackScrollableWidth:Number = this.actualWidth - this.thumb.width - this._minimumPadding - this._maximumPadding;
var xOffset:Number = location.x - this._touchStartX - this._minimumPadding;
var xPosition:Number = Math.min(Math.max(0, this._thumbStartX + xOffset), trackScrollableWidth);
percentage = xPosition / trackScrollableWidth;
}
return this._minimum + percentage * (this._maximum - this._minimum);
}
/**
* @private
*/
protected function startRepeatTimer(action:Function):void
{
this.currentRepeatAction = action;
if(this._repeatDelay > 0)
{
if(!this._repeatTimer)
{
this._repeatTimer = new Timer(this._repeatDelay * 1000);
this._repeatTimer.addEventListener(TimerEvent.TIMER, repeatTimer_timerHandler);
}
else
{
this._repeatTimer.reset();
this._repeatTimer.delay = this._repeatDelay * 1000;
}
this._repeatTimer.start();
}
}
/**
* @private
*/
protected function adjustPage():void
{
var page:Number = this._page;
if(page !== page) //isNaN
{
page = this._step;
}
if(this._touchValue < this._value)
{
this.value = Math.max(this._touchValue, this._value - page);
}
else if(this._touchValue > this._value)
{
this.value = Math.min(this._touchValue, this._value + page);
}
}
/**
* @private
*/
protected function childProperties_onChange(proxy:PropertyProxy, name:Object):void
{
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected function slider_removedFromStageHandler(event:Event):void
{
this._touchPointID = -1;
var wasDragging:Boolean = this.isDragging;
this.isDragging = false;
if(wasDragging && !this.liveDragging)
{
this.dispatchEventWith(Event.CHANGE);
}
}
/**
* @private
*/
override protected function focusInHandler(event:Event):void
{
super.focusInHandler(event);
this.stage.addEventListener(KeyboardEvent.KEY_DOWN, stage_keyDownHandler);
}
/**
* @private
*/
override protected function focusOutHandler(event:Event):void
{
super.focusOutHandler(event);
this.stage.removeEventListener(KeyboardEvent.KEY_DOWN, stage_keyDownHandler);
}
/**
* @private
*/
protected function track_touchHandler(event:TouchEvent):void
{
if(!this._isEnabled)
{
this._touchPointID = -1;
return;
}
var track:DisplayObject = DisplayObject(event.currentTarget);
if(this._touchPointID >= 0)
{
var touch:Touch = event.getTouch(track, null, this._touchPointID);
if(!touch)
{
return;
}
if(touch.phase === TouchPhase.MOVED)
{
touch.getLocation(this, HELPER_POINT);
this.value = this.locationToValue(HELPER_POINT);
}
else if(touch.phase === TouchPhase.ENDED)
{
if(this._repeatTimer)
{
this._repeatTimer.stop();
}
this._touchPointID = -1;
this.isDragging = false;
if(!this.liveDragging)
{
this.dispatchEventWith(Event.CHANGE);
}
this.dispatchEventWith(FeathersEventType.END_INTERACTION);
}
}
else
{
touch = event.getTouch(track, TouchPhase.BEGAN);
if(!touch)
{
return;
}
touch.getLocation(this, HELPER_POINT);
this._touchPointID = touch.id;
if(this._direction == Direction.VERTICAL)
{
this._thumbStartX = HELPER_POINT.x;
this._thumbStartY = Math.min(this.actualHeight - this.thumb.height, Math.max(0, HELPER_POINT.y - this.thumb.height / 2));
}
else //horizontal
{
this._thumbStartX = Math.min(this.actualWidth - this.thumb.width, Math.max(0, HELPER_POINT.x - this.thumb.width / 2));
this._thumbStartY = HELPER_POINT.y;
}
this._touchStartX = HELPER_POINT.x;
this._touchStartY = HELPER_POINT.y;
this._touchValue = this.locationToValue(HELPER_POINT);
this.isDragging = true;
this.dispatchEventWith(FeathersEventType.BEGIN_INTERACTION);
if(this._showThumb && this._trackInteractionMode === TrackInteractionMode.BY_PAGE)
{
this.adjustPage();
this.startRepeatTimer(this.adjustPage);
}
else
{
this.value = this._touchValue;
}
}
}
/**
* @private
*/
protected function thumb_touchHandler(event:TouchEvent):void
{
if(!this._isEnabled)
{
this._touchPointID = -1;
return;
}
if(this._touchPointID >= 0)
{
var touch:Touch = event.getTouch(this.thumb, null, this._touchPointID);
if(!touch)
{
return;
}
if(touch.phase == TouchPhase.MOVED)
{
var exclusiveTouch:ExclusiveTouch = ExclusiveTouch.forStage(this.stage);
var claim:DisplayObject = exclusiveTouch.getClaim(this._touchPointID);
if(claim != this)
{
if(claim)
{
//already claimed by another display object
return;
}
else
{
exclusiveTouch.claimTouch(this._touchPointID, this);
}
}
touch.getLocation(this, HELPER_POINT);
this.value = this.locationToValue(HELPER_POINT);
}
else if(touch.phase == TouchPhase.ENDED)
{
this._touchPointID = -1;
this.isDragging = false;
if(!this.liveDragging)
{
this.dispatchEventWith(Event.CHANGE);
}
this.dispatchEventWith(FeathersEventType.END_INTERACTION);
}
}
else
{
touch = event.getTouch(this.thumb, TouchPhase.BEGAN);
if(!touch)
{
return;
}
touch.getLocation(this, HELPER_POINT);
this._touchPointID = touch.id;
this._thumbStartX = this.thumb.x;
this._thumbStartY = this.thumb.y;
this._touchStartX = HELPER_POINT.x;
this._touchStartY = HELPER_POINT.y;
this.isDragging = true;
this.dispatchEventWith(FeathersEventType.BEGIN_INTERACTION);
}
}
/**
* @private
*/
protected function stage_keyDownHandler(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.HOME)
{
this.value = this._minimum;
return;
}
if(event.keyCode == Keyboard.END)
{
this.value = this._maximum;
return;
}
var page:Number = this._page;
if(page !== page) //isNaN
{
page = this._step;
}
if(this._direction == Direction.VERTICAL)
{
if(event.keyCode == Keyboard.UP)
{
if(event.shiftKey)
{
this.value += page;
}
else
{
this.value += this._step;
}
}
else if(event.keyCode == Keyboard.DOWN)
{
if(event.shiftKey)
{
this.value -= page;
}
else
{
this.value -= this._step;
}
}
}
else
{
if(event.keyCode == Keyboard.LEFT)
{
if(event.shiftKey)
{
this.value -= page;
}
else
{
this.value -= this._step;
}
}
else if(event.keyCode == Keyboard.RIGHT)
{
if(event.shiftKey)
{
this.value += page;
}
else
{
this.value += this._step;
}
}
}
}
/**
* @private
*/
protected function repeatTimer_timerHandler(event:TimerEvent):void
{
var exclusiveTouch:ExclusiveTouch = ExclusiveTouch.forStage(this.stage);
var claim:DisplayObject = exclusiveTouch.getClaim(this._touchPointID);
if(claim && claim != this)
{
return;
}
if(this._repeatTimer.currentCount < 5)
{
return;
}
this.currentRepeatAction();
}
}
} |
def main() {
if false {
let mutable index = 10;
index += 10;
}
while true {
let mutable counter = 20;
counter -= 1;
}
}
|
package
{
import flash.display.Sprite;
import starling.core.Starling;
[SWF(width="800", height="600", frameRate="30", backgroundColor="#cccccc")]
public class Example_Dragon_DemoEntry extends Sprite
{
public function Example_Dragon_DemoEntry()
{
var _starling:Starling = new Starling(Dragon_SwitchClothes, stage);
//var _starling:Starling = new Starling(Dragon_ChaseStarling, stage);
//_starling.antiAliasing = 1;
_starling.showStats = true;
_starling.start();
}
}
} |
package com.ankamagames.dofus.datacenter.bonus.criterion
{
public class BonusAreaCriterion extends BonusCriterion
{
public function BonusAreaCriterion()
{
super();
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.managers
{
COMPILE::SWF
{
import flash.display.MovieClip;
}
COMPILE::JS
{
import org.apache.royale.core.UIBase;
}
/**
* The platform base class for SystemManager
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Royale 0.9.4
*/
COMPILE::SWF
public class SystemManagerBase extends MovieClip
{
}
COMPILE::JS
public class SystemManagerBase extends UIBase
{
}
}
|
package org.papervision3d.core.log
{
/**
* @author Ralph Hauwert
*/
public class PaperLogVO
{
public var level:int;
public var msg:String;
public var object:Object;
public var arg:Array;
public function PaperLogVO(level:int, msg:String, object:Object, arg:Array)
{
this.level = level;
this.msg = msg;
this.object = object;
this.arg = arg;
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// 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 flexUnitTests.reflection
{
import org.apache.royale.test.asserts.*;
import flexUnitTests.reflection.support.*;
import org.apache.royale.reflection.*;
/**
* @royalesuppresspublicvarwarning
*/
public class ReflectionTesterTestDynamic
{
public static var isJS:Boolean = COMPILE::JS;
[BeforeClass]
public static function setUpBeforeClass():void
{
}
[AfterClass]
public static function tearDownAfterClass():void
{
}
[Before]
public function setUp():void
{
}
[After]
public function tearDown():void
{
}
private static function contentStringsMatch(arr1:Array, arr2:Array):Boolean
{
if (arr1 == arr2) return true;
if (!arr1 || !arr2) return false;
if (arr1.length != arr2.length) return false;
const arr1Copy:Array = arr1.concat();
var l:uint = arr1Copy.length;
while (l--)
{
var s:String = arr1Copy.shift();
if (arr2.indexOf(s) == -1) return false
}
return true;
}
[Test]
public function testisDynamic():void
{
//class
assertTrue( isDynamicObject(Object), "class should be dynamic");
assertTrue( isDynamicObject(TestClass1), "class should be dynamic");
//interface is dynamic (even if it doesn't make much sense)
assertTrue( isDynamicObject(ITestInterface), "interface should be dynamic");
//instance
assertTrue( isDynamicObject({}), "generic object should be dynamic");
assertFalse( isDynamicObject(new TestClass1()), "sealed class instance should not be dynamic");
assertTrue( isDynamicObject(new DynamicTestClass()), "dynamic class instance should be dynamic");
assertFalse( isDynamicObject("String"), "String instance should not be dynamic");
assertFalse( isDynamicObject(99), "int instance should not be dynamic");
assertFalse( isDynamicObject(99.99), "Number instance should not be dynamic");
assertFalse( isDynamicObject(true), "Boolean instance should not be dynamic");
assertTrue( isDynamicObject(function ():void
{
}), "function instance should be dynamic");
assertTrue( isDynamicObject([]), "Array instance should be dynamic");
}
[TestVariance(variance="JS", description="Variance in test due to reliance on 'js-default-initializers=true' throughout entire inheritance chain for 'getDynamicFields' function")]
[Test]
public function testGetDynamicFields():void
{
const emptyArray:Array = [];
const singleDynField:Array = ['test'];
assertTrue( contentStringsMatch(getDynamicFields(Object), emptyArray), "dynamic fields should match reference list");
Object['test'] = true;
assertTrue( contentStringsMatch(getDynamicFields(Object), singleDynField), "dynamic fields should match reference list");
delete Object['test'];
assertTrue( contentStringsMatch(getDynamicFields(TestClass1), emptyArray), "dynamic fields should match reference list");
TestClass1['test'] = true;
assertTrue( contentStringsMatch(getDynamicFields(TestClass1), singleDynField), "dynamic fields should match reference list");
delete TestClass1['test'];
//interface is dynamic (even if it doesn't make much sense)
assertTrue( contentStringsMatch(getDynamicFields(ITestInterface), emptyArray), "dynamic fields should match reference list");
ITestInterface['test'] = true;
assertTrue( contentStringsMatch(getDynamicFields(ITestInterface), singleDynField), "dynamic fields should match reference list");
delete ITestInterface['test'];
//instance
assertTrue( contentStringsMatch(getDynamicFields({}), emptyArray), "dynamic fields should match reference list");
assertTrue( contentStringsMatch(getDynamicFields({test: true}), singleDynField), "dynamic fields should match reference list");
assertTrue( contentStringsMatch(getDynamicFields(new TestClass1()), emptyArray), "dynamic fields should match reference list");
const dynInstance:DynamicTestClass = new DynamicTestClass();
dynInstance.test = true;
assertTrue( contentStringsMatch(getDynamicFields(dynInstance), singleDynField), "dynamic fields should match reference list");
assertTrue( contentStringsMatch(getDynamicFields("String"), emptyArray), "dynamic fields should match reference list");
assertTrue( contentStringsMatch(getDynamicFields(99), emptyArray), "dynamic fields should match reference list");
assertTrue( contentStringsMatch(getDynamicFields(99.99), emptyArray), "dynamic fields should match reference list");
assertTrue( contentStringsMatch(getDynamicFields(true), emptyArray), "dynamic fields should match reference list");
assertTrue( contentStringsMatch(getDynamicFields(function ():void
{
}), emptyArray), "dynamic fields should match reference list");
const numericFields:Array = ["0", "1", "2", "3"];
var arr:Array = [1, 2, 3, 4];
assertTrue( contentStringsMatch(getDynamicFields(arr), numericFields), "dynamic fields should match reference list");
numericFields.push('test');
arr['test'] = true;
assertTrue( contentStringsMatch(getDynamicFields(arr), numericFields), "dynamic fields should match reference list");
var testclass2:DynamicTestClass2 = new DynamicTestClass2();
testclass2.test = true;
testclass2.something = '*something*';
assertTrue( contentStringsMatch(getDynamicFields(testclass2), singleDynField), "dynamic fields should match reference list");
testclass2.test = 'test';
testclass2.something = '*something else*';
assertTrue( contentStringsMatch(getDynamicFields(testclass2), singleDynField), "dynamic fields should match reference list");
var testClass3:DynamicTestClass3 = new DynamicTestClass3();
var swapAssertion:Boolean;
COMPILE::JS{
var check:Boolean = new CompilationData(testClass3).hasSameAncestry(CompilationData.WITH_DEFAULT_INITIALIZERS);
if (!check)
{
//variance... due framework ancestry having different compilation settings
swapAssertion = true;
}
}
if (!swapAssertion)
{
assertTrue( contentStringsMatch(getDynamicFields(testClass3), emptyArray), "dynamic fields should match reference list");
} else
{
assertFalse( contentStringsMatch(getDynamicFields(testClass3), emptyArray), "dynamic fields should match reference list");
trace('[WARN] Variance: a test is technically wrong in javascript, but is expected to be wrong, because the compilation settings do not support it throughout the inheritance chain');
}
testClass3.test = 'true';
testClass3.x = 10;
testClass3.className = 'hello';
if (!swapAssertion)
{
assertTrue( contentStringsMatch(getDynamicFields(testClass3), singleDynField), "dynamic fields should match reference list");
} else
{
assertFalse( contentStringsMatch(getDynamicFields(testClass3), singleDynField), "dynamic fields should not match reference list");
trace('[WARN] Variance: a test is technically wrong in javascript, but is expected to be wrong, because the compilation settings do not support it throughout the inheritance chain');
}
}
[Test]
public function testGetDynamicFieldsWithPredicate():void
{
const test:Object = {
'test1': true,
'test2': true,
'_underscore': true
};
const withoutUnderscores:Array = ['test1', 'test2'];
var excludeUnderscores:Function = function (prop:String):Boolean
{
return prop && prop.charAt(0) != '_';
};
assertTrue( contentStringsMatch(getDynamicFields(test, excludeUnderscores), withoutUnderscores), "dynamic fields should match reference list");
}
}
}
|
/**
* VERSION: 0.21 (beta)
* DATE: 2010-04-21
* ACTIONSCRIPT VERSION: 3.0
* UPDATES AND DOCUMENTATION AT: http://www.GreenSock.com
**/
package com.greensock.motionPaths {
import flash.display.Shape;
import flash.events.Event;
/**
* A MotionPath defines a path along which a PathFollower can travel, making it relatively simple to do
* things like tween an object in a circular path. A PathFollower's position along the path is described using
* its <code>progress</code> property, a value between 0 and 1 where 0 is at the beginning of the path, 0.5 is in
* the middle, and 1 is at the very end of the path. So to tween a PathFollower along the path, you can simply
* tween its <code>progress</code> property. To tween ALL of the followers on the path at once, you can
* tween the MotionPath's <code>progress</code> property. PathFollowers automatically wrap so that if
* the <code>progress</code> value exceeds 1 or drops below 0, it shows up on the other end of the path.<br /><br />
*
* Since MotionPath extends the Shape class, you can add an instance to the display list to see a line representation
* of the path drawn which can be helpful especially during the production phase. Use <code>lineStyle()</code>
* to adjust the color, thickness, and other attributes of the line that is drawn (or set the MotionPath's
* <code>visible</code> property to false or don't add it to the display list if you don't want to see the line
* at all). You can also adjust all of its properties like <code>scaleX, scaleY, rotation, width, height, x,</code>
* and <code>y</code> just like any DisplayObject. That means you can tween those values as well to achieve very
* dynamic, complex effects with ease.<br /><br />
*
* @example Example AS3 code:<listing version="3.0">
import com.greensock.~~;
import com.greensock.plugins.~~;
import com.greensock.motionPaths.~~;
TweenPlugin.activate([CirclePath2DPlugin]); // only needed once in your swf, and only if you plan to use the circlePath2D tweening feature for convenience
// create a circle motion path at coordinates x:150, y:150 with a radius of 100
var circle:CirclePath2D = new CirclePath2D(150, 150, 100);
// tween mc along the path from the bottom (90 degrees) to 315 degrees in the counter-clockwise direction and make an extra revolution
TweenLite.to(mc, 3, {circlePath2D:{path:circle, startAngle:90, endAngle:315, autoRotate:true, direction:Direction.COUNTER_CLOCKWISE, extraRevolutions:1}});
// tween the circle's rotation, scaleX, scaleY, x, and y properties:
TweenLite.to(circle, 3, {rotation:180, scaleX:0.5, scaleY:2, x:250, y:200});
// show the path visually by adding it to the display list (optional)
this.addChild(circle);
// --- Instead of using the plugin, you could manually manage followers and tween their "progress" property...
// make the MovieClip "mc2" follow the circle and start at a position of 90 degrees (this returns a PathFollower instance)
var follower:PathFollower = circle.addFollower(mc2, circle.angleToProgress(90));
// tween the follower clockwise along the path to 315 degrees
TweenLite.to(follower, 2, {progress:circle.followerTween(follower, 315, Direction.CLOCKWISE)});
// tween the follower counter-clockwise to 200 degrees and add an extra revolution
TweenLite.to(follower, 2, {progress:circle.followerTween(follower, 200, Direction.COUNTER_CLOCKWISE, 1)});
</listing>
*
* <b>NOTES</b><br />
* <ul>
* <li>All followers are automatically updated when you alter the MotionPath that they're following.</li>
* <li>To tween all followers along the path at once, simply tween the MotionPath's <code>progress</code>
* property which will provide better performance than tweening each follower independently.</li>
* </ul>
*
* <b>Copyright 2010, GreenSock. All rights reserved.</b> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership.
*
* @author Jack Doyle, jack@greensock.com
*/
public class MotionPath extends Shape {
/** @private **/
protected static const _RAD2DEG : Number = 180 / Math.PI;
/** @private **/
protected static const _DEG2RAD : Number = Math.PI / 180;
/** @private **/
protected var _redrawLine : Boolean;
/** @private **/
protected var _thickness : Number;
/** @private **/
protected var _color : uint;
/** @private **/
protected var _lineAlpha : Number;
/** @private **/
protected var _pixelHinting : Boolean;
/** @private **/
protected var _scaleMode : String;
/** @private **/
protected var _caps : String;
/** @private **/
protected var _joints : String;
/** @private **/
protected var _miterLimit : Number;
/** @private **/
protected var _rootFollower : PathFollower;
/** @private **/
protected var _progress : Number;
/** @private **/
public function MotionPath() {
_progress = 0;
lineStyle(1, 0x666666, 1, false, "none", null, null, 3, true);
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true);
}
/** @private **/
protected function onAddedToStage(event : Event) : void {
renderAll();
}
/**
* Adds a follower to the path, optionally setting it to a particular progress position. If
* the target isn't a PathFollower instance already, one will be created for it. The target
* can be any object that has x and y properties.
*
* @param target Any object that has x and y properties that you'd like to follow the path. Existing PathFollower instances are allowed.
* @param progress The progress position at which the target should be placed initially (0 by default)
* @param autoRotate When <code>autoRotate</code> is <code>true</code>, the target will automatically be rotated so that it is oriented to the angle of the path. To offset this value (like to always add 90 degrees for example), use the <code>rotationOffset</code> property.
* @param rotationOffset When <code>autoRotate</code> is <code>true</code>, this value will always be added to the resulting <code>rotation</code> of the target.
* @return A PathFollower instance associated with the target (you can tween this PathFollower's <code>progress</code> property to move it along the path).
*/
public function addFollower(target : *, progress : Number = 0, autoRotate : Boolean = false, rotationOffset : Number = 0) : PathFollower {
var f : PathFollower = getFollower(target);
if (f == null) {
f = new PathFollower(target);
}
f.autoRotate = autoRotate;
f.rotationOffset = rotationOffset;
if (f.path != this) {
if (_rootFollower) {
_rootFollower.cachedPrev = f;
}
f.cachedNext = _rootFollower;
_rootFollower = f;
f.path = this;
f.cachedProgress = progress;
renderObjectAt(f.target, progress, autoRotate, rotationOffset);
}
return f;
}
/**
* Removes the target as a follower. The target can be a PathFollower instance or the target associated
* with one of the PathFollower instances.
*
* @param target the target or PathFollower instance to remove.
*/
public function removeFollower(target : *) : void {
var f : PathFollower = getFollower(target);
if (f == null) {
return;
}
if (f.cachedNext) {
f.cachedNext.cachedPrev = f.cachedPrev;
}
if (f.cachedPrev) {
f.cachedPrev.cachedNext = f.cachedNext;
} else if (_rootFollower == f) {
_rootFollower = null;
}
f.cachedNext = f.cachedPrev = null;
f.path = null;
}
/** Removes all followers. **/
public function removeAllFollowers() : void {
var f : PathFollower = _rootFollower;
var next : PathFollower;
while (f) {
next = f.cachedNext;
f.cachedNext = f.cachedPrev = null;
f.path = null;
f = next;
}
_rootFollower = null;
}
/**
* Distributes objects evenly along the MotionPath. You can optionally define minimum and maximum
* <code>progress</code> values between which the objects will be distributed. For example, if you want them
* distributed from the very beginning of the path to the middle, you would do:<br /><br /><code>
*
* path.distribute([mc1, mc2, mc3], 0, 0.5);<br /><br /></code>
*
* As it loops through the <code>targets</code> array, if a target is found for which a PathFollower
* doesn't exist, one will automatically be created and added to the path. The <code>targets</code>
* array can be populated with PathFollowers or DisplayObjects or Points or pretty much any object.
*
* @param targets An array of targets (PathFollowers, DisplayObjects, Points, or pretty much any object) that should be distributed evenly along the MotionPath. As it loops through the <code>targets</code> array, if a target is found for which a PathFollower doesn't exist, one will automatically be created and added to the path.
* @param min The minimum <code>progress</code> value at which the targets will begin being distributed. This value will always be between 0 and 1. For example, if the targets should be distributed from the midpoint of the path through the end, the <code>min</code> parameter would be 0.5 and the <code>max</code> parameter would be 1.
* @param max The maximum <code>progress</code> value where the targets will end distribution. This value will always be between 0 and 1. For example, if the targets should be distributed from the midpoint of the path through the end, the <code>min</code> parameter would be 0.5 and the <code>max</code> parameter would be 1.
* @param autoRotate When <code>autoRotate</code> is <code>true</code>, the target will automatically be rotated so that it is oriented to the angle of the path. To offset this value (like to always add 90 degrees for example), use the <code>rotationOffset</code> property.
* @param rotationOffset When <code>autoRotate</code> is <code>true</code>, this value will always be added to the resulting <code>rotation</code> of the target. For example, to always add 90 degrees to the autoRotation, <code>rotationOffset</code> would be 90.
*/
public function distribute(targets : Array = null, min : Number = 0, max : Number = 1, autoRotate : Boolean = false, rotationOffset : Number = 0) : void {
if (targets == null) {
targets = this.followers;
}
min = _normalize(min);
max = _normalize(max);
var f : PathFollower;
var i : int = targets.length;
var space : Number = (i > 1) ? (max - min) / (i - 1) : 1;
while (--i > -1) {
f = getFollower(targets[i]);
if (f == null) {
f = this.addFollower(targets[i], 0, autoRotate, rotationOffset);
}
f.cachedProgress = min + (space * i);
this.renderObjectAt(f.target, f.cachedProgress, autoRotate, rotationOffset);
}
}
/** @private **/
protected function _normalize(num : Number) : Number {
if (num > 1) {
num -= int(num);
} else if (num < 0) {
num -= int(num) - 1;
}
return num;
}
/**
* Returns the PathFollower instance associated with a particular target or null if none exists.
*
* @param target The target whose PathFollower instance you want returned.
* @return PathFollower instance
*/
public function getFollower(target : Object) : PathFollower {
if (target is PathFollower) {
return target as PathFollower;
}
var f : PathFollower = _rootFollower;
while (f) {
if (f.target == target) {
return f;
}
f = f.cachedNext;
}
return null;
}
/** @private **/
protected function renderAll() : void {
}
/**
* Positions any object with x and y properties on the path at a specific progress position.
* For example, to position <code>mc</code> in the middle of the path, you would do:<br /><br /><code>
*
* myPath.renderObjectAt(mc, 0.5);</code><br /><br />
*
* Some paths have methods to translate other meaningful information into a progress value, like
* for a <code>CirclePath2D</code> you can get the progress associated with the 90-degree position with the
* <code>angleToPosition()</code> method like this:<br /><br /><code>
*
* myCircle.renderObjectAt(mc, myCircle.angleToProgress(90));
*
* </code><br />
*
* @param target The target object to position
* @param progress The progress value (typically between 0 and 1 where 0 is the beginning of the path, 0.5 is in the middle, and 1 is at the end)
* @param autoRotate When <code>autoRotate</code> is <code>true</code>, the target will automatically be rotated so that it is oriented to the angle of the path. To offset this value (like to always add 90 degrees for example), use the <code>rotationOffset</code> property.
* @param rotationOffset When <code>autoRotate</code> is <code>true</code>, this value will always be added to the resulting <code>rotation</code> of the target.
*/
public function renderObjectAt(target : Object, progress : Number, autoRotate : Boolean = false, rotationOffset : Number = 0) : void {
}
/**
* Sets the line style for the path which you will only see if you add the path to the display list
* with something like addChild() and make sure the visible property is true. For example, to make
* a CirclePath2D visible with a red line red that's 3 pixels thick, you could do: <br /><br /><code>
*
* var myCircle:CirclePath2D = new CirclePath2D(150, 150, 100); <br />
* myCircle.lineStyle(3, 0xFF0000);<br />
* addChild(myCircle);<br />
*
* </code>
*
* @param thickness line thickness
* @param color line color
* @param alpha line alpha
* @param pixelHinting pixel hinting
* @param scaleMode scale mode
* @param caps caps
* @param joints joints
* @param miterLimit miter limit
* @param skipRedraw if true, the redraw will be skipped.
*/
public function lineStyle(thickness : Number = 1, color : uint = 0x666666, alpha : Number = 1, pixelHinting : Boolean = false, scaleMode : String = "none", caps : String = null, joints : String = null, miterLimit : Number = 3, skipRedraw : Boolean = false) : void {
_thickness = thickness;
_color = color;
_lineAlpha = alpha;
_pixelHinting = pixelHinting;
_scaleMode = scaleMode;
_caps = caps;
_joints = joints;
_miterLimit = miterLimit;
_redrawLine = true;
if (!skipRedraw) {
renderAll();
}
}
/** @inheritDoc **/
override public function get rotation() : Number {
return super.rotation;
}
override public function set rotation(value : Number) : void {
super.rotation = value;
renderAll();
}
/** @inheritDoc **/
override public function get scaleX() : Number {
return super.scaleX;
}
override public function set scaleX(value : Number) : void {
super.scaleX = value;
renderAll();
}
/** @inheritDoc **/
override public function get scaleY() : Number {
return super.scaleY;
}
override public function set scaleY(value : Number) : void {
super.scaleY = value;
renderAll();
}
/** @inheritDoc **/
override public function get x() : Number {
return super.x;
}
override public function set x(value : Number) : void {
super.x = value;
renderAll();
}
/** @inheritDoc **/
override public function get y() : Number {
return super.y;
}
override public function set y(value : Number) : void {
super.y = value;
renderAll();
}
/** @inheritDoc **/
override public function get width() : Number {
return super.width;
}
override public function set width(value : Number) : void {
super.width = value;
renderAll();
}
/** @inheritDoc **/
override public function get height() : Number {
return super.height;
}
override public function set height(value : Number) : void {
super.height = value;
renderAll();
}
/** @inheritDoc **/
override public function get visible() : Boolean {
return super.visible;
}
override public function set visible(value : Boolean) : void {
super.visible = value;
_redrawLine = true;
renderAll();
}
/**
* A value (typically between 0 and 1) that can be used to move all followers along the path. Unlike a PathFollower's
* <code>progress</code>, this value is not absolute - it simply facilitates movement of followers together along the
* path in a way that performs better than tweening each follower independently (plus it's easier). You can tween to
* values that are greater than 1 or less than 0 but the values are simply wrapped. So, for example, setting
* <code>progress</code> to 1.2 is the same as setting it to 0.2 and -0.2 is the same as 0.8. If your goal is to
* tween all followers around a CirclePath2D twice completely, you could just add 2 to the progress value or use a
* relative value in the tween, like: <br /><br /><code>
*
* TweenLite.to(myCircle, 5, {progress:"2"}); // or myCircle.progress + 2
*
* </code>
**/
public function get progress() : Number {
return _progress;
}
public function set progress(value : Number) : void {
if (value > 1) {
value -= int(value);
} else if (value < 0) {
value -= int(value) - 1;
}
var dif : Number = value - _progress;
var f : PathFollower = _rootFollower;
while (f) {
f.cachedProgress += dif;
if (f.cachedProgress > 1) {
f.cachedProgress -= int(f.cachedProgress);
} else if (f.cachedProgress < 0) {
f.cachedProgress -= int(f.cachedProgress) - 1;
}
f = f.cachedNext;
}
_progress = value;
renderAll();
}
/** Returns an array of all PathFollower instances associated with this path **/
public function get followers() : Array {
var a : Array = [];
var cnt : uint = 0;
var f : PathFollower = _rootFollower;
while (f) {
a[cnt++] = f;
f = f.cachedNext;
}
return a;
}
/** Returns an array of all target instances associated with the PathFollowers of this path **/
public function get targets() : Array {
var a : Array = [];
var cnt : uint = 0;
var f : PathFollower = _rootFollower;
while (f) {
a[cnt++] = f.target;
f = f.cachedNext;
}
return a;
}
}
} |
package gov.lbl.aercalc.view.settings {
import flash.events.EventDispatcher;
import spark.components.VGroup;
import gov.lbl.aercalc.events.SettingsEvent;
import gov.lbl.aercalc.model.settings.AppSettings;
public class SettingsEditor extends VGroup
{
public function SettingsEditor()
{
super();
}
private var _settings:AppSettings;
private var settingsChanged:Boolean = false;
[Bindable]
[Inject(source="settingsModel.editableSettings", bind="true")]
public function get settings():AppSettings {
return _settings;
}
[Dispatcher]
public var dispatcher:EventDispatcher;
public function set settings(value:AppSettings):void {
if(_settings != value) {
_settings = value;
settingsChanged = true;
invalidateProperties();
if(dispatcher){
dispatcher.dispatchEvent(new SettingsEvent(SettingsEvent.SETTINGS_CHANGED, true));
}
}
}
protected override function commitProperties():void {
super.commitProperties();
if(settingsChanged) {
settingsChanged = false;
if(settings) {
read(settings);
}
}
}
protected function read(settings:AppSettings):void {
}
protected function write(settings:AppSettings):void {
}
protected function onChange():void
{
if(settings)
write(settings);
}
}
}
|
package quickb2.thirdparty.flash
{
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.setTimeout;
import quickb2.display.immediate.graphics.qb2I_Graphics2d;
import quickb2.display.immediate.style.qb2S_StyleProps;
import quickb2.lang.errors.qb2E_RuntimeErrorCode;
import quickb2.lang.errors.qb2U_Error;
import quickb2.lang.types.qb2U_Type;
import quickb2.math.geo.qb2S_GeoStyle;
import quickb2.physics.core.backend.qb2I_BackEndWorldRepresentation;
import quickb2.physics.core.joints.qb2S_JointStyle;
import quickb2.physics.core.tangibles.qb2S_TangibleStyle;
import quickb2.physics.core.prop.qb2S_PhysicsProps;
import quickb2.physics.core.tangibles.qb2World;
import quickb2.physics.core.tangibles.qb2WorldConfig;
import quickb2.physics.extras.qb2WindowWalls;
import quickb2.physics.extras.qb2WindowWallsConfig;
import quickb2.physics.utils.qb2DebugDragger;
import quickb2.physics.utils.qb2EntryPointConfig;
import quickb2.physics.utils.qb2F_EntryPointOption;
import quickb2.physics.utils.qb2U_PhysicsStyleSheet;
import quickb2.platform.input.qb2I_Mouse;
import quickb2.platform.qb2I_EntryPoint;
import quickb2.platform.qb2I_Window;
import quickb2.thirdparty.box2d.qb2Box2dWorldRepresentation;
import quickb2.thirdparty.flash.*;
import quickb2.utils.qb2I_Clock;
import quickb2.utils.qb2I_Timer;
/**
* ...
* @author
*/
public class qb2FlashEntryPointCaller extends Sprite
{
private var m_world:qb2World;
private var m_config:qb2EntryPointConfig;
private var m_backEnd:qb2I_BackEndWorldRepresentation;
private var m_debugDragger:qb2DebugDragger;
public function qb2FlashEntryPointCaller(backEnd:qb2I_BackEndWorldRepresentation, config_nullable:qb2EntryPointConfig):void
{
m_config = config_nullable != null ? config_nullable : new qb2EntryPointConfig();
m_backEnd = backEnd;
m_debugDragger = null;
if (stage != null)
{
init();
}
else
{
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
//--- DRK > Populate the static name->prop dictionary for Prop.getByName();
qb2S_PhysicsProps.ACTOR;
qb2S_JointStyle.ANCHOR_RADIUS;
qb2S_TangibleStyle.CENTROID_RADIUS;
qb2S_GeoStyle.INFINITE;
var entryPoint:qb2I_EntryPoint = this as qb2I_EntryPoint;
if ( entryPoint == null )
{
qb2U_Error.throwCode(qb2E_RuntimeErrorCode.MISSING_DEPENDENCY, "Subclass must implement qb2I_EntryPoint.");
}
m_world = new qb2World(m_backEnd);
m_world.setProp(qb2S_PhysicsProps.PIXELS_PER_METER, m_config.pixelsPerMeter);
m_world.setProp(qb2S_PhysicsProps.GRAVITY.Y, m_config.gravityY);
var worldConfig:qb2WorldConfig = m_world.getConfig();
if ( qb2F_EntryPointOption.DEBUG_DRAG.overlaps(m_config.options) )
{
var mouse:qb2I_Mouse = new qb2FlashMouse(this.stage);
m_debugDragger = new qb2DebugDragger(mouse, m_world, m_config.debugDragAcceleration);
}
if ( qb2F_EntryPointOption.DEBUG_DRAW.overlaps(m_config.options) )
{
worldConfig.graphics = new qb2FlashVectorGraphics2d(this.graphics);
}
if ( qb2F_EntryPointOption.WINDOW_WALLS.overlaps(m_config.options) )
{
var window:qb2I_Window = new qb2FlashWindow(this.stage);
var windowWallsConfig:qb2WindowWallsConfig = new qb2WindowWallsConfig();
windowWallsConfig.overhang = m_config.windowWallOverhang;
var windowWalls:qb2WindowWalls = new qb2WindowWalls(window, windowWallsConfig);
m_world.addChild(windowWalls);
}
if ( qb2F_EntryPointOption.AUTO_STEP.overlaps(m_config.options) )
{
var timer:qb2I_Timer = new qb2FlashEnterFrameTimer(this.stage);
var clock:qb2I_Clock = new qb2FlashClock();
m_world.startAutoStep(timer, clock);
}
setTimeout(entryPoint.entryPoint, 0);
}
public function getDebugDragger():qb2DebugDragger
{
return m_debugDragger;
}
public function getWorld():qb2World
{
return m_world;
}
}
} |
/////////////////////////////////////////////////////////////////////////////////////
//
// Simplified BSD License
// ======================
//
// Copyright 2013 Pascal ECHEMANN. 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.
//
// 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.
//
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the copyright holders.
//
/////////////////////////////////////////////////////////////////////////////////////
package org.flashapi.hummingbird.core {
// -----------------------------------------------------------
// AbstractModelUpdater.as
// -----------------------------------------------------------
/**
* @author Pascal ECHEMANN
* @version 1.0.0, 05/07/2013 20:02
* @see http://www.flashapi.org/
*/
import flash.events.EventDispatcher;
import org.flashapi.hummingbird.events.DependencyEvent;
//--------------------------------------------------------------------------
//
// Events
//
//--------------------------------------------------------------------------
/**
* Dispatched when the dependency injection is complete on this <code>AbstractModelUpdater</code>
* object.
*
* @eventType org.flashapi.hummingbird.events.DependencyEvent.DEPENDENCY_COMPLETE
*/
[Event(name="dependencyComplete", type="org.flashapi.hummingbird.events.DependencyEvent")]
/**
* Abstract class for <code>IController</code> and <code>IOrchestrator</code>
* implementations.
*
* @see org.flashapi.hummingbird.controller.IController
* @see org.flashapi.hummingbird.orchestrator.IOrchestrator
*/
public class AbstractModelUpdater extends EventDispatcher {
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor. Creates a new <code>AbstractModelUpdater</code> instance.
*/
public function AbstractModelUpdater() {
super();
this.initObj();
}
//--------------------------------------------------------------------------
//
// Public methods
//
//--------------------------------------------------------------------------
/**
* @copy org.flashapi.hummingbird.core.IFinalizable#finalize()
*/
public function finalize():void { }
//--------------------------------------------------------------------------
//
// Protected methods
//
//--------------------------------------------------------------------------
/**
* Called when the Dependency Injection process is completely performed on
* this MVC object.
*/
protected function onDependencyComplete():void { }
//--------------------------------------------------------------------------
//
// Private methods
//
//--------------------------------------------------------------------------
/**
* Initializes this MVC object.
*/
private function initObj():void {
this.addEventListener(DependencyEvent.DEPENDENCY_COMPLETE, this.dependencyCompleteHandler);
}
/**
* Event handler invoked when the Dependency Injection process is completely
* performed on this MVC object.
*/
private function dependencyCompleteHandler(e:DependencyEvent):void {
this.removeEventListener(DependencyEvent.DEPENDENCY_COMPLETE, this.dependencyCompleteHandler);
this.onDependencyComplete();
}
}
} |
package io.decagames.rotmg.pets.panels {
import com.company.assembleegameclient.parameters.Parameters;
import com.company.assembleegameclient.ui.tooltip.ToolTip;
import com.company.assembleegameclient.util.StageProxy;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import io.decagames.rotmg.pets.data.PetsModel;
import io.decagames.rotmg.pets.data.vo.PetVO;
import io.decagames.rotmg.pets.popup.releasePet.ReleasePetDialog;
import io.decagames.rotmg.pets.signals.ActivatePet;
import io.decagames.rotmg.pets.signals.DeactivatePet;
import io.decagames.rotmg.pets.signals.NotifyActivePetUpdated;
import io.decagames.rotmg.pets.signals.ShowPetTooltip;
import io.decagames.rotmg.ui.popups.signals.ShowPopupSignal;
import kabam.rotmg.core.signals.ShowTooltipSignal;
import kabam.rotmg.dialogs.control.OpenDialogSignal;
import org.swiftsuspenders.Injector;
import robotlegs.bender.bundles.mvcs.Mediator;
public class PetPanelMediator extends Mediator {
public function PetPanelMediator() {
super();
}
[Inject]
public var view:PetPanel;
[Inject]
public var petModel:PetsModel;
[Inject]
public var showPetTooltip:ShowPetTooltip;
[Inject]
public var showToolTip:ShowTooltipSignal;
[Inject]
public var deactivatePet:DeactivatePet;
[Inject]
public var activatePet:ActivatePet;
[Inject]
public var notifyActivePetUpdated:NotifyActivePetUpdated;
[Inject]
public var openDialog:OpenDialogSignal;
[Inject]
public var injector:Injector;
[Inject]
public var showPopupSignal:ShowPopupSignal;
private var stageProxy:StageProxy;
override public function initialize():void {
this.view.setState(this.returnButtonState());
this.view.addToolTip.add(this.onAddToolTip);
this.stageProxy = new StageProxy(this.view);
this.setEventListeners();
this.notifyActivePetUpdated.add(this.onNotifyActivePetUpdated);
}
override public function destroy():void {
this.view.followButton.removeEventListener("click", this.onButtonClick);
this.view.releaseButton.removeEventListener("click", this.onReleaseClick);
this.view.unFollowButton.removeEventListener("click", this.onButtonClick);
this.stageProxy.removeEventListener("keyDown", this.onKeyDown);
}
private function setEventListeners():void {
this.view.followButton.addEventListener("click", this.onButtonClick);
this.view.releaseButton.addEventListener("click", this.onReleaseClick);
this.view.unFollowButton.addEventListener("click", this.onButtonClick);
this.stageProxy.addEventListener("keyDown", this.onKeyDown);
}
private function onNotifyActivePetUpdated():void {
var _loc1_:PetVO = this.petModel.getActivePet();
this.view.toggleButtons(!_loc1_);
}
private function returnButtonState():uint {
if (this.isPanelPetSameAsActivePet()) {
return 2;
}
return 1;
}
private function followPet():void {
if (this.isPanelPetSameAsActivePet()) {
this.deactivatePet.dispatch(this.view.petVO.getID());
} else {
this.activatePet.dispatch(this.view.petVO.getID());
}
}
private function onAddToolTip(param1:ToolTip):void {
this.showToolTip.dispatch(param1);
}
private function isPanelPetSameAsActivePet():Boolean {
return !this.petModel.getActivePet() ? false : this.petModel.getActivePet().getID() == this.view.petVO.getID();
}
protected function onButtonClick(param1:MouseEvent):void {
this.followPet();
}
private function onReleaseClick(param1:MouseEvent):void {
this.injector.map(PetVO).toValue(this.view.petVO);
this.showPopupSignal.dispatch(new ReleasePetDialog(this.view.petVO.getID()));
}
private function onKeyDown(param1:KeyboardEvent):void {
if (param1.keyCode == Parameters.data.interact && this.view.stage.focus == null) {
this.followPet();
}
}
}
}
|
// Remake of NinjaSnowWar in script
#include "Scripts/NinjaSnowWar/FootSteps.as"
#include "Scripts/NinjaSnowWar/LightFlash.as"
#include "Scripts/NinjaSnowWar/Ninja.as"
#include "Scripts/NinjaSnowWar/Player.as"
#include "Scripts/NinjaSnowWar/Potion.as"
#include "Scripts/NinjaSnowWar/SnowBall.as"
#include "Scripts/NinjaSnowWar/SnowCrate.as"
#include "Scripts/Utilities/Network.as"
const float mouseSensitivity = 0.125;
const float touchSensitivity = 2.0;
const float joySensitivity = 0.5;
const float joyMoveDeadZone = 0.333;
const float joyLookDeadZone = 0.05;
const float cameraMinDist = 0.25;
const float cameraMaxDist = 5;
const float cameraSafetyDist = 0.3;
const int initialMaxEnemies = 5;
const int finalMaxEnemies = 25;
const int maxPowerups = 5;
const int incrementEach = 10;
const int playerHealth = 20;
const float enemySpawnRate = 1;
const float powerupSpawnRate = 15;
const float spawnAreaSize = 5;
Scene@ gameScene;
Node@ gameCameraNode;
Node@ musicNode;
Camera@ gameCamera;
Text@ scoreText;
Text@ hiscoreText;
Text@ messageText;
BorderImage@ healthBar;
BorderImage@ sight;
BorderImage@ moveButton;
BorderImage@ fireButton;
SoundSource@ musicSource;
Controls playerControls;
Controls prevPlayerControls;
bool singlePlayer = true;
bool gameOn = false;
bool drawDebug = false;
bool drawOctreeDebug = false;
int maxEnemies = 0;
int incrementCounter = 0;
float enemySpawnTimer = 0;
float powerupSpawnTimer = 0;
uint clientNodeID = 0;
int clientScore = 0;
int screenJoystickID = -1;
int screenJoystickSettingsID = -1;
bool touchEnabled = false;
Array<Player> players;
Array<HiscoreEntry> hiscores;
void Start()
{
if (engine.headless)
OpenConsoleWindow();
ParseNetworkArguments();
if (runServer || runClient)
singlePlayer = false;
InitAudio();
InitConsole();
InitScene();
InitNetworking();
CreateCamera();
CreateOverlays();
SubscribeToEvent(gameScene, "SceneUpdate", "HandleUpdate");
if (gameScene.physicsWorld !is null)
SubscribeToEvent(gameScene.physicsWorld, "PhysicsPreStep", "HandleFixedUpdate");
SubscribeToEvent(gameScene, "ScenePostUpdate", "HandlePostUpdate");
SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
SubscribeToEvent("KeyDown", "HandleKeyDown");
SubscribeToEvent("Points", "HandlePoints");
SubscribeToEvent("Kill", "HandleKill");
SubscribeToEvent("ScreenMode", "HandleScreenMode");
if (singlePlayer)
{
StartGame(null);
engine.pauseMinimized = true;
}
}
void InitAudio()
{
if (engine.headless)
return;
// Lower mastervolumes slightly.
audio.masterGain[SOUND_MASTER] = 0.75;
audio.masterGain[SOUND_MUSIC] = 0.9;
if (!nobgm)
{
Sound@ musicFile = cache.GetResource("Sound", "Music/Ninja Gods.ogg");
musicFile.looped = true;
// Note: the non-positional sound source component need to be attached to a node to become effective
// Due to networked mode clearing the scene on connect, do not attach to the scene itself
musicNode = Node();
musicSource = musicNode.CreateComponent("SoundSource");
musicSource.soundType = SOUND_MUSIC;
musicSource.Play(musicFile);
}
}
void InitConsole()
{
if (engine.headless)
return;
XMLFile@ uiStyle = cache.GetResource("XMLFile", "UI/DefaultStyle.xml");
ui.root.defaultStyle = uiStyle;
Console@ console = engine.CreateConsole();
console.defaultStyle = uiStyle;
console.background.opacity = 0.8;
engine.CreateDebugHud();
debugHud.defaultStyle = uiStyle;
}
void InitScene()
{
gameScene = Scene("NinjaSnowWar");
// Enable access to this script file & scene from the console
script.defaultScene = gameScene;
script.defaultScriptFile = scriptFile;
// For the multiplayer client, do not load the scene, let it load from the server
if (runClient)
return;
gameScene.LoadXML(cache.GetFile("Scenes/NinjaSnowWar.xml"));
// On mobile devices render the shadowmap first. Also adjust the shadow quality for performance
String platform = GetPlatform();
if (platform == "Android" || platform == "iOS" || platform == "Raspberry Pi")
{
renderer.reuseShadowMaps = false;
renderer.shadowQuality = SHADOWQUALITY_LOW_16BIT;
// Adjust the directional light shadow range slightly further, as only the first
// cascade is supported
Node@ dirLightNode = gameScene.GetChild("GlobalLight", true);
if (dirLightNode !is null)
{
Light@ dirLight = dirLightNode.GetComponent("Light");
dirLight.shadowCascade = CascadeParameters(15.0f, 0.0f, 0.0f, 0.0f, 0.9f);
dirLight.shadowIntensity = 0.333f;
}
}
// Precache shaders if possible
if (!engine.headless && cache.Exists("NinjaSnowWarShaders.xml"))
graphics.PrecacheShaders(cache.GetFile("NinjaSnowWarShaders.xml"));
}
void InitNetworking()
{
network.updateFps = 25; // 1/4 of physics FPS
network.RegisterRemoteEvent("PlayerSpawned");
network.RegisterRemoteEvent("UpdateScore");
network.RegisterRemoteEvent("UpdateHiscores");
network.RegisterRemoteEvent("ParticleEffect");
if (runServer)
{
network.StartServer(serverPort);
// Disable physics interpolation to ensure clients get sent physically correct transforms
gameScene.physicsWorld.interpolation = false;
SubscribeToEvent("ClientIdentity", "HandleClientIdentity");
SubscribeToEvent("ClientSceneLoaded", "HandleClientSceneLoaded");
SubscribeToEvent("ClientDisconnected", "HandleClientDisconnected");
}
if (runClient)
{
VariantMap identity;
identity["UserName"] = userName;
network.updateFps = 50; // Increase controls send rate for better responsiveness
network.Connect(serverAddress, serverPort, gameScene, identity);
SubscribeToEvent("PlayerSpawned", "HandlePlayerSpawned");
SubscribeToEvent("UpdateScore", "HandleUpdateScore");
SubscribeToEvent("UpdateHiscores", "HandleUpdateHiscores");
SubscribeToEvent("NetworkUpdateSent", "HandleNetworkUpdateSent");
SubscribeToEvent("ParticleEffect", "HandleParticleEffect");
}
}
void InitTouchInput()
{
touchEnabled = true;
screenJoystickID = input.AddScreenJoystick(cache.GetResource("XMLFile", "UI/ScreenJoystick_NinjaSnowWar.xml"));
}
void CreateCamera()
{
// Note: the camera is not in the scene
gameCameraNode = Node();
gameCameraNode.position = Vector3(0, 2, -10);
gameCamera = gameCameraNode.CreateComponent("Camera");
gameCamera.nearClip = 0.5;
gameCamera.farClip = 160;
if (!engine.headless)
{
renderer.viewports[0] = Viewport(gameScene, gameCamera);
audio.listener = gameCameraNode.CreateComponent("SoundListener");
}
}
void CreateOverlays()
{
if (engine.headless || runServer)
return;
int height = graphics.height / 22;
if (height > 64)
height = 64;
sight = BorderImage();
sight.texture = cache.GetResource("Texture2D", "Textures/NinjaSnowWar/Sight.png");
sight.SetAlignment(HA_CENTER, VA_CENTER);
sight.SetSize(height, height);
ui.root.AddChild(sight);
Font@ font = cache.GetResource("Font", "Fonts/BlueHighway.ttf");
scoreText = Text();
scoreText.SetFont(font, 13);
scoreText.SetAlignment(HA_LEFT, VA_TOP);
scoreText.SetPosition(5, 5);
scoreText.colors[C_BOTTOMLEFT] = Color(1, 1, 0.25);
scoreText.colors[C_BOTTOMRIGHT] = Color(1, 1, 0.25);
ui.root.AddChild(scoreText);
@hiscoreText = Text();
hiscoreText.SetFont(font, 13);
hiscoreText.SetAlignment(HA_RIGHT, VA_TOP);
hiscoreText.SetPosition(-5, 5);
hiscoreText.colors[C_BOTTOMLEFT] = Color(1, 1, 0.25);
hiscoreText.colors[C_BOTTOMRIGHT] = Color(1, 1, 0.25);
ui.root.AddChild(hiscoreText);
@messageText = Text();
messageText.SetFont(font, 13);
messageText.SetAlignment(HA_CENTER, VA_CENTER);
messageText.SetPosition(0, -height * 2);
messageText.color = Color(1, 0, 0);
ui.root.AddChild(messageText);
BorderImage@ healthBorder = BorderImage();
healthBorder.texture = cache.GetResource("Texture2D", "Textures/NinjaSnowWar/HealthBarBorder.png");
healthBorder.SetAlignment(HA_CENTER, VA_TOP);
healthBorder.SetPosition(0, 8);
healthBorder.SetSize(120, 20);
ui.root.AddChild(healthBorder);
healthBar = BorderImage();
healthBar.texture = cache.GetResource("Texture2D", "Textures/NinjaSnowWar/HealthBarInside.png");
healthBar.SetPosition(2, 2);
healthBar.SetSize(116, 16);
healthBorder.AddChild(healthBar);
if (GetPlatform() == "Android" || GetPlatform() == "iOS")
// On mobile platform, enable touch by adding a screen joystick
InitTouchInput();
else if (input.numJoysticks == 0)
// On desktop platform, do not detect touch when we already got a joystick
SubscribeToEvent("TouchBegin", "HandleTouchBegin");
}
void SetMessage(const String&in message)
{
if (messageText !is null)
messageText.text = message;
}
void StartGame(Connection@ connection)
{
// Clear the scene of all existing scripted objects
{
Array<Node@> scriptedNodes = gameScene.GetChildrenWithScript(true);
for (uint i = 0; i < scriptedNodes.length; ++i)
scriptedNodes[i].Remove();
}
players.Clear();
SpawnPlayer(connection);
ResetAI();
gameOn = true;
maxEnemies = initialMaxEnemies;
incrementCounter = 0;
enemySpawnTimer = 0;
powerupSpawnTimer = 0;
if (singlePlayer)
{
playerControls.yaw = 0;
playerControls.pitch = 0;
SetMessage("");
}
}
void SpawnPlayer(Connection@ connection)
{
Vector3 spawnPosition;
if (singlePlayer)
spawnPosition = Vector3(0, 0.97, 0);
else
spawnPosition = Vector3(Random(spawnAreaSize) - spawnAreaSize * 0.5, 0.97, Random(spawnAreaSize) - spawnAreaSize);
Node@ playerNode = SpawnObject(spawnPosition, Quaternion(), "Ninja");
// Set owner connection. Owned nodes are always updated to the owner at full frequency
playerNode.owner = connection;
playerNode.name = "Player";
// Initialize variables
Ninja@ playerNinja = cast<Ninja>(playerNode.scriptObject);
playerNinja.health = playerNinja.maxHealth = playerHealth;
playerNinja.side = SIDE_PLAYER;
// Make sure the player can not shoot on first frame by holding the button down
if (connection is null)
playerNinja.controls = playerNinja.prevControls = playerControls;
else
playerNinja.controls = playerNinja.prevControls = connection.controls;
// Check if player entry already exists
int playerIndex = -1;
for (uint i = 0; i < players.length; ++i)
{
if (players[i].connection is connection)
{
playerIndex = i;
break;
}
}
// Does not exist, create new
if (playerIndex < 0)
{
playerIndex = players.length;
players.Resize(players.length + 1);
players[playerIndex].connection = connection;
if (connection !is null)
{
players[playerIndex].name = connection.identity["UserName"].GetString();
// In multiplayer, send current hiscores to the new player
SendHiscores(playerIndex);
}
else
{
players[playerIndex].name = "Player";
// In singleplayer, create also the default hiscore entry immediately
HiscoreEntry newHiscore;
newHiscore.name = players[playerIndex].name;
newHiscore.score = 0;
hiscores.Push(newHiscore);
}
}
players[playerIndex].nodeID = playerNode.id;
players[playerIndex].score = 0;
if (connection !is null)
{
// In multiplayer, send initial score, then send a remote event that tells the spawned node's ID
// It is important for the event to be in-order so that the node has been replicated first
SendScore(playerIndex);
VariantMap eventData;
eventData["NodeID"] = playerNode.id;
connection.SendRemoteEvent("PlayerSpawned", true, eventData);
// Create name tag (Text3D component) for players in multiplayer
Node@ textNode = playerNode.CreateChild("NameTag");
textNode.position = Vector3(0, 1.2, 0);
Text3D@ text3D = textNode.CreateComponent("Text3D");
Font@ font = cache.GetResource("Font", "Fonts/BlueHighway.ttf");
text3D.SetFont(font, 19);
text3D.color = Color(1, 1, 0);
text3D.text = players[playerIndex].name;
text3D.horizontalAlignment = HA_CENTER;
text3D.verticalAlignment = VA_CENTER;
text3D.faceCamera = true;
}
}
void HandleUpdate(StringHash eventType, VariantMap& eventData)
{
float timeStep = eventData["TimeStep"].GetFloat();
UpdateControls();
CheckEndAndRestart();
if (engine.headless)
{
String command = GetConsoleInput();
if (command.length > 0)
script.Execute(command);
}
else
{
if (debugHud.mode != DEBUGHUD_SHOW_NONE)
{
Node@ playerNode = FindOwnNode();
if (playerNode !is null)
{
debugHud.SetAppStats("Player Pos", playerNode.worldPosition.ToString());
debugHud.SetAppStats("Player Yaw", Variant(playerNode.worldRotation.yaw));
}
else
debugHud.ClearAppStats();
}
}
}
void HandleFixedUpdate(StringHash eventType, VariantMap& eventData)
{
float timeStep = eventData["TimeStep"].GetFloat();
// Spawn new objects, singleplayer or server only
if (singlePlayer || runServer)
SpawnObjects(timeStep);
}
void HandlePostUpdate()
{
UpdateCamera();
UpdateStatus();
}
void HandlePostRenderUpdate()
{
if (engine.headless)
return;
if (drawDebug)
gameScene.physicsWorld.DrawDebugGeometry(true);
if (drawOctreeDebug)
gameScene.octree.DrawDebugGeometry(true);
}
void HandleTouchBegin(StringHash eventType, VariantMap& eventData)
{
// On some platforms like Windows the presence of touch input can only be detected dynamically
InitTouchInput();
UnsubscribeFromEvent("TouchBegin");
}
void HandleKeyDown(StringHash eventType, VariantMap& eventData)
{
int key = eventData["Key"].GetInt();
if (key == KEY_ESC)
{
if (!console.visible)
engine.Exit();
else
console.visible = false;
}
if (key == KEY_F1)
console.Toggle();
if (key == KEY_F2)
debugHud.ToggleAll();
if (key == KEY_F3)
drawDebug = !drawDebug;
if (key == KEY_F4)
drawOctreeDebug = !drawOctreeDebug;
// Allow pause only in singleplayer
if (key == 'P' && singlePlayer && !console.visible && gameOn)
{
gameScene.updateEnabled = !gameScene.updateEnabled;
if (!gameScene.updateEnabled)
{
SetMessage("PAUSED");
// Open the settings joystick only if the controls screen joystick was already open
if (screenJoystickID >= 0)
{
// Lazy initialization
if (screenJoystickSettingsID < 0)
screenJoystickSettingsID = input.AddScreenJoystick(cache.GetResource("XMLFile", "UI/ScreenJoystickSettings_NinjaSnowWar.xml"));
else
input.screenJoystickVisible[screenJoystickSettingsID] = true;
}
}
else
{
SetMessage("");
// Hide the settings joystick
if (screenJoystickSettingsID >= 0)
input.screenJoystickVisible[screenJoystickSettingsID] = false;
}
}
}
void HandlePoints(StringHash eventType, VariantMap& eventData)
{
if (eventData["DamageSide"].GetInt() == SIDE_PLAYER)
{
// Get node ID of the object that should receive points -> use it to find player index
int playerIndex = FindPlayerIndex(eventData["Receiver"].GetInt());
if (playerIndex >= 0)
{
players[playerIndex].score += eventData["Points"].GetInt();
SendScore(playerIndex);
bool newHiscore = CheckHiscore(playerIndex);
if (newHiscore)
SendHiscores(-1);
}
}
}
void HandleKill(StringHash eventType, VariantMap& eventData)
{
if (eventData["DamageSide"].GetInt() == SIDE_PLAYER)
{
MakeAIHarder();
// Increment amount of simultaneous enemies after enough kills
incrementCounter++;
if (incrementCounter >= incrementEach)
{
incrementCounter = 0;
if (maxEnemies < finalMaxEnemies)
maxEnemies++;
}
}
}
void HandleClientIdentity(StringHash eventType, VariantMap& eventData)
{
Connection@ connection = GetEventSender();
// If user has empty name, invent one
if (connection.identity["UserName"].GetString().Trimmed().empty)
connection.identity["UserName"] = "user" + RandomInt(1000);
// Assign scene to begin replicating it to the client
connection.scene = gameScene;
}
void HandleClientSceneLoaded(StringHash eventType, VariantMap& eventData)
{
// Now client is actually ready to begin. If first player, clear the scene and restart the game
Connection@ connection = GetEventSender();
if (players.empty)
StartGame(connection);
else
SpawnPlayer(connection);
}
void HandleClientDisconnected(StringHash eventType, VariantMap& eventData)
{
Connection@ connection = GetEventSender();
// Erase the player entry, and make the player's ninja commit seppuku (if exists)
for (uint i = 0; i < players.length; ++i)
{
if (players[i].connection is connection)
{
players[i].connection = null;
Node@ playerNode = FindPlayerNode(i);
if (playerNode !is null)
{
Ninja@ playerNinja = cast<Ninja>(playerNode.scriptObject);
playerNinja.health = 0;
playerNinja.lastDamageSide = SIDE_NEUTRAL; // No-one scores from this
}
players.Erase(i);
return;
}
}
}
void HandlePlayerSpawned(StringHash eventType, VariantMap& eventData)
{
// Store our node ID and mark the game as started
clientNodeID = eventData["NodeID"].GetInt();
gameOn = true;
SetMessage("");
// Copy initial yaw from the player node (we should have it replicated now)
Node@ playerNode = FindOwnNode();
if (playerNode !is null)
{
playerControls.yaw = playerNode.rotation.yaw;
playerControls.pitch = 0;
// Disable the nametag from own character
Node@ nameTag = playerNode.GetChild("NameTag");
nameTag.enabled = false;
}
}
void HandleUpdateScore(StringHash eventType, VariantMap& eventData)
{
clientScore = eventData["Score"].GetInt();
scoreText.text = "Score " + clientScore;
}
void HandleUpdateHiscores(StringHash eventType, VariantMap& eventData)
{
VectorBuffer data = eventData["Hiscores"].GetBuffer();
hiscores.Resize(data.ReadVLE());
for (uint i = 0; i < hiscores.length; ++i)
{
hiscores[i].name = data.ReadString();
hiscores[i].score = data.ReadInt();
}
String allHiscores;
for (uint i = 0; i < hiscores.length; ++i)
allHiscores += hiscores[i].name + " " + hiscores[i].score + "\n";
hiscoreText.text = allHiscores;
}
void HandleNetworkUpdateSent()
{
// Clear accumulated buttons from the network controls
if (network.serverConnection !is null)
network.serverConnection.controls.Set(CTRL_ALL, false);
}
void HandleParticleEffect(StringHash eventType, VariantMap& eventData)
{
Vector3 position = eventData["Position"].GetVector3();
String effectName = eventData["EffectName"].GetString();
float duration = eventData["Duration"].GetFloat();
SpawnParticleEffect(position, effectName, duration, LOCAL);
}
int FindPlayerIndex(uint nodeID)
{
for (uint i = 0; i < players.length; ++i)
{
if (players[i].nodeID == nodeID)
return i;
}
return -1;
}
Node@ FindPlayerNode(int playerIndex)
{
if (playerIndex >= 0 && playerIndex < int(players.length))
return gameScene.GetNode(players[playerIndex].nodeID);
else
return null;
}
Node@ FindOwnNode()
{
if (singlePlayer)
return gameScene.GetChild("Player", true);
else
return gameScene.GetNode(clientNodeID);
}
bool CheckHiscore(int playerIndex)
{
for (uint i = 0; i < hiscores.length; ++i)
{
if (hiscores[i].name == players[playerIndex].name)
{
if (players[playerIndex].score > hiscores[i].score)
{
hiscores[i].score = players[playerIndex].score;
SortHiscores();
return true;
}
else
return false; // No update to individual hiscore
}
}
// Not found, create new hiscore entry
HiscoreEntry newHiscore;
newHiscore.name = players[playerIndex].name;
newHiscore.score = players[playerIndex].score;
hiscores.Push(newHiscore);
SortHiscores();
return true;
}
void SortHiscores()
{
for (int i = 1; i < int(hiscores.length); ++i)
{
HiscoreEntry temp = hiscores[i];
int j = i;
while (j > 0 && temp.score > hiscores[j - 1].score)
{
hiscores[j] = hiscores[j - 1];
--j;
}
hiscores[j] = temp;
}
}
void SendScore(int playerIndex)
{
if (!runServer || playerIndex < 0 || playerIndex >= int(players.length))
return;
VariantMap eventData;
eventData["Score"] = players[playerIndex].score;
players[playerIndex].connection.SendRemoteEvent("UpdateScore", true, eventData);
}
void SendHiscores(int playerIndex)
{
if (!runServer)
return;
VectorBuffer data;
data.WriteVLE(hiscores.length);
for (uint i = 0; i < hiscores.length; ++i)
{
data.WriteString(hiscores[i].name);
data.WriteInt(hiscores[i].score);
}
VariantMap eventData;
eventData["Hiscores"] = data;
if (playerIndex >= 0 && playerIndex < int(players.length))
players[playerIndex].connection.SendRemoteEvent("UpdateHiscores", true, eventData);
else
network.BroadcastRemoteEvent(gameScene, "UpdateHiscores", true, eventData); // Send to all in scene
}
Node@ SpawnObject(const Vector3&in position, const Quaternion&in rotation, const String&in className)
{
XMLFile@ xml = cache.GetResource("XMLFile", "Objects/" + className + ".xml");
return scene.InstantiateXML(xml, position, rotation);
}
Node@ SpawnParticleEffect(const Vector3&in position, const String&in effectName, float duration, CreateMode mode = REPLICATED)
{
if (runServer && mode == REPLICATED)
{
VariantMap eventData;
eventData["Position"] = position;
eventData["EffectName"] = effectName;
eventData["Duration"] = duration;
network.BroadcastRemoteEvent(gameScene, "ParticleEffect", false, eventData);
}
Node@ newNode = scene.CreateChild("Effect", LOCAL);
newNode.position = position;
// Create the particle emitter
ParticleEmitter@ emitter = newNode.CreateComponent("ParticleEmitter");
emitter.Load(cache.GetResource("XMLFile", effectName));
// Create a GameObject for managing the effect lifetime
GameObject@ object = cast<GameObject>(newNode.CreateScriptObject(scriptFile, "GameObject", LOCAL));
object.duration = duration;
return newNode;
}
Node@ SpawnSound(const Vector3&in position, const String&in soundName, float duration)
{
Node@ newNode = scene.CreateChild();
newNode.position = position;
// Create the sound source
SoundSource3D@ source = newNode.CreateComponent("SoundSource3D");
Sound@ sound = cache.GetResource("Sound", soundName);
source.SetDistanceAttenuation(200, 5000, 1);
source.Play(sound);
// Create a GameObject for managing the sound lifetime
GameObject@ object = cast<GameObject>(newNode.CreateScriptObject(scriptFile, "GameObject", LOCAL));
object.duration = duration;
return newNode;
}
void SpawnObjects(float timeStep)
{
// If game not running, run only the random generator
if (!gameOn)
{
Random();
return;
}
// Spawn powerups
powerupSpawnTimer += timeStep;
if (powerupSpawnTimer >= powerupSpawnRate)
{
powerupSpawnTimer = 0;
int numPowerups = gameScene.GetChildrenWithScript("SnowCrate", true).length + gameScene.GetChildrenWithScript("Potion", true).length;
if (numPowerups < maxPowerups)
{
const float maxOffset = 40;
float xOffset = Random(maxOffset * 2.0) - maxOffset;
float zOffset = Random(maxOffset * 2.0) - maxOffset;
SpawnObject(Vector3(xOffset, 50, zOffset), Quaternion(), "SnowCrate");
}
}
// Spawn enemies
enemySpawnTimer += timeStep;
if (enemySpawnTimer > enemySpawnRate)
{
enemySpawnTimer = 0;
int numEnemies = 0;
Array<Node@> ninjaNodes = gameScene.GetChildrenWithScript("Ninja", true);
for (uint i = 0; i < ninjaNodes.length; ++i)
{
Ninja@ ninja = cast<Ninja>(ninjaNodes[i].scriptObject);
if (ninja.side == SIDE_ENEMY)
++numEnemies;
}
if (numEnemies < maxEnemies)
{
const float maxOffset = 40;
float offset = Random(maxOffset * 2.0) - maxOffset;
// Random north/east/south/west direction
int dir = RandomInt() & 3;
dir *= 90;
Quaternion rotation(0, dir, 0);
Node@ enemyNode = SpawnObject(rotation * Vector3(offset, 10, -120), rotation, "Ninja");
// Initialize variables
Ninja@ enemyNinja = cast<Ninja>(enemyNode.scriptObject);
enemyNinja.side = SIDE_ENEMY;
@enemyNinja.controller = AIController();
RigidBody@ enemyBody = enemyNode.GetComponent("RigidBody");
enemyBody.linearVelocity = rotation * Vector3(0, 10, 30);
}
}
}
void CheckEndAndRestart()
{
// Only check end of game if singleplayer or client
if (runServer)
return;
// Check if player node has vanished
Node@ playerNode = FindOwnNode();
if (gameOn && playerNode is null)
{
gameOn = false;
SetMessage("Press Fire or Jump to restart!");
return;
}
// Check for restart (singleplayer only)
if (!gameOn && singlePlayer && playerControls.IsPressed(CTRL_FIRE | CTRL_JUMP, prevPlayerControls))
StartGame(null);
}
void UpdateControls()
{
if (singlePlayer || runClient)
{
prevPlayerControls = playerControls;
playerControls.Set(CTRL_ALL, false);
if (touchEnabled)
{
for (uint i = 0; i < input.numTouches; ++i)
{
TouchState@ touch = input.touches[i];
if (touch.touchedElement.Get() is null)
{
// Touch on empty space
playerControls.yaw += touchSensitivity * gameCamera.fov / graphics.height * touch.delta.x;
playerControls.pitch += touchSensitivity * gameCamera.fov / graphics.height * touch.delta.y;
}
}
}
if (input.numJoysticks > 0)
{
JoystickState@ joystick = touchEnabled ? input.joysticks[screenJoystickID] : input.joysticksByIndex[0];
if (joystick.numButtons > 0)
{
if (joystick.buttonDown[0])
playerControls.Set(CTRL_JUMP, true);
if (joystick.buttonDown[1])
playerControls.Set(CTRL_FIRE, true);
if (joystick.numButtons >= 6)
{
if (joystick.buttonDown[4])
playerControls.Set(CTRL_JUMP, true);
if (joystick.buttonDown[5])
playerControls.Set(CTRL_FIRE, true);
}
if (joystick.numHats > 0)
{
if (joystick.hatPosition[0] & HAT_LEFT != 0)
playerControls.Set(CTRL_LEFT, true);
if (joystick.hatPosition[0] & HAT_RIGHT != 0)
playerControls.Set(CTRL_RIGHT, true);
if (joystick.hatPosition[0] & HAT_UP != 0)
playerControls.Set(CTRL_UP, true);
if (joystick.hatPosition[0] & HAT_DOWN != 0)
playerControls.Set(CTRL_DOWN, true);
}
if (joystick.numAxes >= 2)
{
if (joystick.axisPosition[0] < -joyMoveDeadZone)
playerControls.Set(CTRL_LEFT, true);
if (joystick.axisPosition[0] > joyMoveDeadZone)
playerControls.Set(CTRL_RIGHT, true);
if (joystick.axisPosition[1] < -joyMoveDeadZone)
playerControls.Set(CTRL_UP, true);
if (joystick.axisPosition[1] > joyMoveDeadZone)
playerControls.Set(CTRL_DOWN, true);
}
if (joystick.numAxes >= 4)
{
float lookX = joystick.axisPosition[2];
float lookY = joystick.axisPosition[3];
if (lookX < -joyLookDeadZone)
playerControls.yaw -= joySensitivity * lookX * lookX;
if (lookX > joyLookDeadZone)
playerControls.yaw += joySensitivity * lookX * lookX;
if (lookY < -joyLookDeadZone)
playerControls.pitch -= joySensitivity * lookY * lookY;
if (lookY > joyLookDeadZone)
playerControls.pitch += joySensitivity * lookY * lookY;
}
}
}
// For the triggered actions (fire & jump) check also for press, in case the FPS is low
// and the key was already released
if (console is null || !console.visible)
{
if (input.keyDown['W'])
playerControls.Set(CTRL_UP, true);
if (input.keyDown['S'])
playerControls.Set(CTRL_DOWN, true);
if (input.keyDown['A'])
playerControls.Set(CTRL_LEFT, true);
if (input.keyDown['D'])
playerControls.Set(CTRL_RIGHT, true);
if (input.keyDown[KEY_LCTRL] || input.keyPress[KEY_LCTRL])
playerControls.Set(CTRL_FIRE, true);
if (input.keyDown[' '] || input.keyPress[' '])
playerControls.Set(CTRL_JUMP, true);
if (input.mouseButtonDown[MOUSEB_LEFT] || input.mouseButtonPress[MOUSEB_LEFT])
playerControls.Set(CTRL_FIRE, true);
if (input.mouseButtonDown[MOUSEB_RIGHT] || input.mouseButtonPress[MOUSEB_RIGHT])
playerControls.Set(CTRL_JUMP, true);
playerControls.yaw += mouseSensitivity * input.mouseMoveX;
playerControls.pitch += mouseSensitivity * input.mouseMoveY;
playerControls.pitch = Clamp(playerControls.pitch, -60.0, 60.0);
}
// In singleplayer, set controls directly on the player's ninja. In multiplayer, transmit to server
if (singlePlayer)
{
Node@ playerNode = gameScene.GetChild("Player", true);
if (playerNode !is null)
{
Ninja@ playerNinja = cast<Ninja>(playerNode.scriptObject);
playerNinja.controls = playerControls;
}
}
else if (network.serverConnection !is null)
{
// Set the latest yaw & pitch to server controls, and accumulate the buttons so that we do not miss any presses
network.serverConnection.controls.yaw = playerControls.yaw;
network.serverConnection.controls.pitch = playerControls.pitch;
network.serverConnection.controls.buttons |= playerControls.buttons;
// Tell the camera position to server for interest management
network.serverConnection.position = gameCameraNode.worldPosition;
}
}
if (runServer)
{
// Apply each connection's controls to the ninja they control
for (uint i = 0; i < players.length; ++i)
{
Node@ playerNode = FindPlayerNode(i);
if (playerNode !is null)
{
Ninja@ playerNinja = cast<Ninja>(playerNode.scriptObject);
playerNinja.controls = players[i].connection.controls;
}
else
{
// If player has no ninja, respawn if fire/jump is pressed
if (players[i].connection.controls.IsPressed(CTRL_FIRE | CTRL_JUMP, players[i].lastControls))
SpawnPlayer(players[i].connection);
}
players[i].lastControls = players[i].connection.controls;
}
}
}
void UpdateCamera()
{
if (engine.headless)
return;
// On the server, use a simple freelook camera
if (runServer)
{
UpdateFreelookCamera();
return;
}
Node@ playerNode = FindOwnNode();
if (playerNode is null)
return;
Vector3 pos = playerNode.position;
Quaternion dir;
// Make controls seem more immediate by forcing the current mouse yaw to player ninja's Y-axis rotation
if (playerNode.vars["Health"].GetInt() > 0)
playerNode.rotation = Quaternion(0, playerControls.yaw, 0);
dir = dir * Quaternion(playerNode.rotation.yaw, Vector3(0, 1, 0));
dir = dir * Quaternion(playerControls.pitch, Vector3(1, 0, 0));
Vector3 aimPoint = pos + Vector3(0, 1, 0);
Vector3 minDist = aimPoint + dir * Vector3(0, 0, -cameraMinDist);
Vector3 maxDist = aimPoint + dir * Vector3(0, 0, -cameraMaxDist);
// Collide camera ray with static objects (collision mask 2)
Vector3 rayDir = (maxDist - minDist).Normalized();
float rayDistance = cameraMaxDist - cameraMinDist + cameraSafetyDist;
PhysicsRaycastResult result = gameScene.physicsWorld.RaycastSingle(Ray(minDist, rayDir), rayDistance, 2);
if (result.body !is null)
rayDistance = Min(rayDistance, result.distance - cameraSafetyDist);
gameCameraNode.position = minDist + rayDir * rayDistance;
gameCameraNode.rotation = dir;
}
void UpdateFreelookCamera()
{
if (console is null || !console.visible)
{
float timeStep = time.timeStep;
float speedMultiplier = 1.0;
if (input.keyDown[KEY_LSHIFT])
speedMultiplier = 5.0;
if (input.keyDown[KEY_LCTRL])
speedMultiplier = 0.1;
if (input.keyDown['W'])
gameCameraNode.Translate(Vector3(0, 0, 10) * timeStep * speedMultiplier);
if (input.keyDown['S'])
gameCameraNode.Translate(Vector3(0, 0, -10) * timeStep * speedMultiplier);
if (input.keyDown['A'])
gameCameraNode.Translate(Vector3(-10, 0, 0) * timeStep * speedMultiplier);
if (input.keyDown['D'])
gameCameraNode.Translate(Vector3(10, 0, 0) * timeStep * speedMultiplier);
playerControls.yaw += mouseSensitivity * input.mouseMoveX;
playerControls.pitch += mouseSensitivity * input.mouseMoveY;
playerControls.pitch = Clamp(playerControls.pitch, -90.0, 90.0);
gameCameraNode.rotation = Quaternion(playerControls.pitch, playerControls.yaw, 0);
}
}
void UpdateStatus()
{
if (engine.headless || runServer)
return;
if (singlePlayer)
{
if (players.length > 0)
scoreText.text = "Score " + players[0].score;
if (hiscores.length > 0)
hiscoreText.text = "Hiscore " + hiscores[0].score;
}
Node@ playerNode = FindOwnNode();
if (playerNode !is null)
{
int health = 0;
if (singlePlayer)
{
GameObject@ object = cast<GameObject>(playerNode.scriptObject);
health = object.health;
}
else
{
// In multiplayer the client does not have script logic components, but health is replicated via node user variables
health = playerNode.vars["Health"].GetInt();
}
healthBar.width = 116 * health / playerHealth;
}
}
void HandleScreenMode()
{
int height = graphics.height / 22;
if (height > 64)
height = 64;
sight.SetSize(height, height);
messageText.SetPosition(0, -height * 2);
}
|
/**
* Crypto
*
* An abstraction layer to instanciate our crypto algorithms
* Copyright (c) 2007 Henri Torgemane
*
* See LICENSE.txt for full license information.
*/
package com.hurlant.crypto
{
import com.hurlant.crypto.hash.HMAC;
import com.hurlant.crypto.hash.IHash;
import com.hurlant.crypto.hash.MD2;
import com.hurlant.crypto.hash.MD5;
import com.hurlant.crypto.hash.SHA1;
import com.hurlant.crypto.hash.SHA224;
import com.hurlant.crypto.hash.SHA256;
import com.hurlant.crypto.prng.ARC4;
import com.hurlant.crypto.rsa.RSAKey;
import com.hurlant.crypto.symmetric.AESKey;
import com.hurlant.crypto.symmetric.BlowFishKey;
import com.hurlant.crypto.symmetric.CBCMode;
import com.hurlant.crypto.symmetric.CFB8Mode;
import com.hurlant.crypto.symmetric.CFBMode;
import com.hurlant.crypto.symmetric.CTRMode;
import com.hurlant.crypto.symmetric.DESKey;
import com.hurlant.crypto.symmetric.ECBMode;
import com.hurlant.crypto.symmetric.ICipher;
import com.hurlant.crypto.symmetric.IMode;
import com.hurlant.crypto.symmetric.IPad;
import com.hurlant.crypto.symmetric.ISymmetricKey;
import com.hurlant.crypto.symmetric.IVMode;
import com.hurlant.crypto.symmetric.NullPad;
import com.hurlant.crypto.symmetric.OFBMode;
import com.hurlant.crypto.symmetric.PKCS5;
import com.hurlant.crypto.symmetric.SimpleIVMode;
import com.hurlant.crypto.symmetric.TripleDESKey;
import com.hurlant.crypto.symmetric.XTeaKey;
import com.hurlant.util.Base64;
import flash.utils.ByteArray;
/**
* A class to make it easy to use the rest of the framework.
* As a side-effect, using this class will cause most of the framework
* to be linked into your application, which is not always what you want.
*
* If you want to optimize your download size, don't use this class.
* (But feel free to read it to get ideas on how to get the algorithm you want.)
*/
public class Crypto
{
private var b64:Base64; // we don't use it, but we want the swc to include it, so cheap trick.
public function Crypto(){
}
/**
* Things that should work, among others:
* "aes"
* "aes-128-ecb"
* "aes-128-cbc"
* "aes-128-cfb"
* "aes-128-cfb8"
* "aes-128-ofb"
* "aes-192-cfb"
* "aes-256-ofb"
* "blowfish-cbc"
* "des-ecb"
* "xtea"
* "xtea-ecb"
* "xtea-cbc"
* "xtea-cfb"
* "xtea-cfb8"
* "xtea-ofb"
* "rc4"
* "simple-aes-cbc"
*/
public static function getCipher(name:String, key:ByteArray, pad:IPad=null):ICipher {
// split name into an array.
var keys:Array = name.split("-");
switch (keys[0]) {
/*
* "simple" is a special case. It means:
* "If using an IV mode, prepend the IV to the ciphertext"
*/
case "simple":
keys.shift();
name = keys.join("-");
var cipher:ICipher = getCipher(name, key, pad);
if (cipher is IVMode) {
return new SimpleIVMode(cipher as IVMode);
} else {
return cipher;
}
/*
* we support both "aes-128" and "aes128"
* Technically, you could use "aes192-128", but you'd
* only be hurting yourself.
*/
case "aes":
case "aes128":
case "aes192":
case "aes256":
keys.shift();
if (key.length*8==keys[0]) {
// support for "aes-128-..." and such.
keys.shift();
}
return getMode(keys[0], new AESKey(key), pad);
break;
case "bf":
case "blowfish":
keys.shift();
return getMode(keys[0], new BlowFishKey(key), pad);
/*
* des-ede and des-ede3 are both equivalent to des3.
* the choice between 2tdes and 3tdes is made based
* on the length of the key provided.
*/
case "des":
keys.shift();
if (keys[0]!="ede" && keys[0]!="ede3") {
return getMode(keys[0], new DESKey(key), pad);
}
if (keys.length==1) {
keys.push("ecb"); // default mode for 2tdes and 3tdes with openssl enc
}
// fall-through to triple des
case "3des":
case "des3":
keys.shift();
return getMode(keys[0], new TripleDESKey(key), pad);
case "xtea":
keys.shift();
return getMode(keys[0], new XTeaKey(key), pad);
break;
/*
* Technically, you could say "rc4-128" or whatever,
* but really, the length of the key is what counts here.
*/
case "rc4":
keys.shift();
return new ARC4(key);
break;
}
return null;
}
/**
* Returns the size of a key for a given cipher identifier.
*/
public static function getKeySize(name:String):uint {
var keys:Array = name.split("-");
switch (keys[0]) {
case "simple":
keys.shift();
return getKeySize(keys.join("-"));
case "aes128":
return 16;
case "aes192":
return 24;
case "aes256":
return 32;
case "aes":
keys.shift();
return parseInt(keys[0])/8;
case "bf":
case "blowfish":
return 16;
case "des":
keys.shift();
switch (keys[0]) {
case "ede":
return 16;
case "ede3":
return 24;
default:
return 8;
}
case "3des":
case "des3":
return 24;
case "xtea":
return 8;
case "rc4":
if (parseInt(keys[1])>0) {
return parseInt(keys[1])/8;
}
return 16; // why not.
}
return 0; // unknown;
}
private static function getMode(name:String, alg:ISymmetricKey, padding:IPad=null):IMode {
switch (name) {
case "ecb":
return new ECBMode(alg, padding);
case "cfb":
return new CFBMode(alg, padding);
case "cfb8":
return new CFB8Mode(alg, padding);
case "ofb":
return new OFBMode(alg, padding);
case "ctr":
return new CTRMode(alg, padding);
case "cbc":
default:
return new CBCMode(alg, padding);
}
}
/**
* Things that should work:
* "md5"
* "sha"
* "sha1"
* "sha224"
* "sha256"
*/
public static function getHash(name:String):IHash {
switch(name) {
case "md2":
return new MD2;
case "md5":
return new MD5;
case "sha": // let's hope you didn't mean sha-0
case "sha1":
return new SHA1;
case "sha224":
return new SHA224;
case "sha256":
return new SHA256;
}
return null;
}
/**
* Things that should work:
* "sha1"
* "md5-64"
* "hmac-md5-96"
* "hmac-sha1-128"
* "hmac-sha256-192"
* etc.
*/
public static function getHMAC(name:String):HMAC {
var keys:Array = name.split("-");
if (keys[0]=="hmac") keys.shift();
var bits:uint = 0;
if (keys.length>1) {
bits = parseInt(keys[1]);
}
return new HMAC(getHash(keys[0]), bits);
}
public static function getPad(name:String):IPad {
switch(name) {
case "null":
return new NullPad;
case "pkcs5":
default:
return new PKCS5;
}
}
/** mostly useless.
*/
public static function getRSA(E:String, M:String):RSAKey {
return RSAKey.parsePublicKey(M,E);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.