CombinedText
stringlengths
4
3.42M
package org.superkaka.KLib.manager { import flash.display.Stage; import flash.events.Event; /** * ... * @author kaka */ public class EnterFrameManager { ///注册列表 static private const list:Array = []; static private var stage:Stage; static public function init(stg:Stage):void { stage = stg; } /** * 注册帧频调用函数 * @param fun * */ static public function registerEnterFrameFunction(fun:Function):void { var index:int=list.indexOf(fun); if(index != -1) { return; } list.push(fun); } /** * 移除帧频调用函数 * @param fun * */ static public function removeEnterFrameFunction(fun:Function):void { var index:int=list.indexOf(fun); if(index==-1) { return; } list.splice(index,1); } /** * 开始调度帧频事件 */ static public function startEnterFrame():void { stage.addEventListener(Event.ENTER_FRAME, enterFramehandler); } /** * 停止调度帧频事件 * */ static public function stopEnterFrame():void { stage.removeEventListener(Event.ENTER_FRAME, enterFramehandler); } static private function enterFramehandler(evt:Event):void { doEnterFrame(); } static private function doEnterFrame():void { ///备份函数列表 防止在列表函数中执行registerEnterFrameFunction和removeEnterFrameFunction导致遍历列表出错 var list_copy:Array = list.concat(); var c:int = list_copy.length; var i:int = 0; while (i < c) { list_copy[i](); i++; } } } }
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2004-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 flexlib.controls.sliderClasses { import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.geom.Point; import flash.ui.Keyboard; import mx.controls.Button; import mx.controls.ButtonPhase; import mx.core.mx_internal; import mx.events.SliderEvent; import mx.managers.ISystemManager; import mx.controls.sliderClasses.SliderDirection; import flexlib.baseClasses.SliderBase; use namespace mx_internal; /** * The SliderThumb class represents a thumb of a Slider control. * The SliderThumb class can only be used within the context * of a Slider control. * You can create a subclass of the SliderThumb class, * and use it with a Slider control by setting the * <code>sliderThumbClass</code> * property of the Slider control to your subclass. * * @see mx.controls.HSlider * @see mx.controls.VSlider * @see mx.controls.sliderClasses.Slider * @see mx.controls.sliderClasses.SliderDataTip * @see mx.controls.sliderClasses.SliderLabel */ public class SliderThumb extends Button { //include "../../core/Version.as"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. */ public function SliderThumb() { super(); stickyHighlighting = true; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * The zero-based index number of this thumb. */ mx_internal var thumbIndex:int; /** * @private * x-position offset. */ private var xOffset:Number; //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- //---------------------------------- // x //---------------------------------- /** * @private * Handle changes to the x-position value of the thumb. */ override public function set x(value:Number):void { var result:Number = moveXPos(value); updateValue(); super.x = result; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // xPosition //---------------------------------- /** * Specifies the position of the center of the thumb on the x-axis. */ public function get xPosition():Number { return $x + width / 2; } /** * @private */ public function set xPosition(value:Number):void { $x = value - width / 2; SliderBase(owner).drawTrackHighlight(); } //-------------------------------------------------------------------------- // // Overridden methods: UIComponent // //-------------------------------------------------------------------------- /** * @private */ override protected function measure():void { super.measure(); measuredWidth = 12; measuredHeight = 12; } /** * @private */ override public function drawFocus(isFocused:Boolean):void { phase = isFocused ? ButtonPhase.DOWN : ButtonPhase.UP; } //-------------------------------------------------------------------------- // // Overridden methods: Button // //-------------------------------------------------------------------------- /** * @private */ override mx_internal function buttonReleased():void { super.buttonReleased(); if (enabled) { systemManager.getSandboxRoot().removeEventListener( MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); systemManager.deployMouseShields(false); SliderBase(owner).onThumbRelease(this); } } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * Move the thumb into the correct position. */ private function moveXPos(value:Number, overrideSnap:Boolean = false, noUpdate:Boolean = false):Number { var result:Number = calculateXPos(value, overrideSnap); xPosition = result; if (!noUpdate) updateValue(); return result; } /** * @private * Ask the Slider if we should be moving into a snap position * and make sure we haven't exceeded the min or max position */ private function calculateXPos(value:Number, overrideSnap:Boolean = false):Number { var bounds:Object = SliderBase(owner).getXBounds(thumbIndex); var result:Number = Math.min(Math.max(value, bounds.min), bounds.max); if (!overrideSnap) result = SliderBase(owner).getSnapValue(result, this); return result; } /** * @private * Used by the Slider for animating the sliding of the thumb. */ mx_internal function onTweenUpdate(value:Number):void { moveXPos(value, true, true); } /** * @private * Used by the Slider for animating the sliding of the thumb. */ mx_internal function onTweenEnd(value:Number):void { moveXPos(value); } /** * @private * Tells the Slider to update its value for the thumb based on the thumb's * current position */ private function updateValue():void { SliderBase(owner).updateThumbValue(thumbIndex); } //-------------------------------------------------------------------------- // // Overridden event handlers: UIComponent // //-------------------------------------------------------------------------- /** * @private * Handle key presses when focus is on the thumb. */ override protected function keyDownHandler(event:KeyboardEvent):void { var multiThumbs:Boolean = SliderBase(owner).thumbCount > 1; var currentVal:Number = xPosition; var moveInterval:Number = SliderBase(owner).snapInterval > 0 ? SliderBase(owner).getSnapIntervalWidth() : 1; var isHorizontal:Boolean = SliderBase(owner).direction == SliderDirection.HORIZONTAL; var newVal:Number; if ((event.keyCode == Keyboard.DOWN && !isHorizontal) || (event.keyCode == Keyboard.LEFT && isHorizontal)) { newVal = currentVal - moveInterval; } else if ((event.keyCode == Keyboard.UP && !isHorizontal) || (event.keyCode == Keyboard.RIGHT && isHorizontal)) { newVal = currentVal + moveInterval; } else if ((event.keyCode == Keyboard.PAGE_DOWN && !isHorizontal) || (event.keyCode == Keyboard.HOME && isHorizontal)) { newVal = SliderBase(owner).getXFromValue(SliderBase(owner).minimum); } else if ((event.keyCode == Keyboard.PAGE_UP && !isHorizontal) || (event.keyCode == Keyboard.END && isHorizontal)) { newVal = SliderBase(owner).getXFromValue(SliderBase(owner).maximum); } if (!isNaN(newVal)) { event.stopPropagation(); //mark last interaction as key SliderBase(owner).keyInteraction = true; moveXPos(newVal); } } //-------------------------------------------------------------------------- // // Overridden event handlers: Button // //-------------------------------------------------------------------------- /** * @private */ override protected function mouseDownHandler(event:MouseEvent):void { super.mouseDownHandler(event); if (enabled) { // Store where the mouse is positioned // relative to the thumb when first pressed. xOffset = event.localX; systemManager.getSandboxRoot().addEventListener( MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); systemManager.deployMouseShields(true); SliderBase(owner).onThumbPress(this); } } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private * Internal function to handle mouse movements * when the thumb is in a pressed state * We want the thumb to follow the x-position of the mouse. */ private function mouseMoveHandler(event:MouseEvent):void { if (enabled) { var pt:Point = new Point(event.stageX, event.stageY); pt = SliderBase(owner).innerSlider.globalToLocal(pt); // Place the thumb in the correct position. moveXPos(pt.x - xOffset + width / 2, false, true); // Callback to the Slider to handle tooltips and update its value. SliderBase(owner).onThumbMove(this); } } } }
/** * VERSION: 1.03 * DATE: 10/2/2009 * ACTIONSCRIPT VERSION: 3.0 * UPDATES AND DOCUMENTATION AT: http://www.TweenMax.com **/ package com.greensock.plugins { import flash.display.*; import flash.geom.ColorTransform; import com.greensock.*; import com.greensock.plugins.*; /** * Removes the tint of a DisplayObject over time. <br /><br /> * * <b>USAGE:</b><br /><br /> * <code> * import com.greensock.TweenLite; <br /> * import com.greensock.plugins.TweenPlugin; <br /> * import com.greensock.plugins.RemoveTintPlugin; <br /> * TweenPlugin.activate([RemoveTintPlugin]); // activation is permanent in the SWF, so this line only needs to be run once.<br /><br /> * * TweenLite.to(mc, 1, {removeTint:true}); <br /><br /> * </code> * * <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 RemoveTintPlugin extends TintPlugin { /** @private **/ public static const API : Number = 1.0; // If the API/Framework for plugins changes in the future, this number helps determine compatibility /** @private **/ public function RemoveTintPlugin() { super(); this.propName = "removeTint"; } } }
package com.codeazur.as3swf.exporters { import com.codeazur.as3swf.SWF; import com.codeazur.as3swf.utils.ColorUtils; import com.codeazur.as3swf.utils.NumberUtils; import flash.display.CapsStyle; import flash.display.InterpolationMethod; import flash.display.JointStyle; import flash.display.LineScaleMode; import flash.display.SpreadMethod; import flash.geom.Matrix; import flash.geom.Point; import com.codeazur.as3swf.exporters.core.DefaultShapeExporter; public class JSCanvasShapeExporter extends DefaultShapeExporter { protected static const NOT_ACTIVE:String = "notActive"; protected static const FILL_ACTIVE:String = "fillActive"; protected static const BITMAP_FILL_ACTIVE:String = "bitmapFillActive"; protected static const STROKE_ACTIVE:String = "strokeActive"; protected var _js:String = ""; protected var fills:Vector.<String>; protected var strokes:Vector.<String>; protected var geometry:Array; protected var prefix:Array; protected var suffix:Array; protected var active:String = NOT_ACTIVE; protected var condensed:Boolean; protected var lineSep:String = ""; public function JSCanvasShapeExporter(swf:SWF, condensed:Boolean = true) { super(swf); this.condensed = condensed; if(!condensed) { lineSep = "\r"; } } public function get js():String { return _js; } override public function beginShape():void { _js = ""; } override public function beginFills():void { fills = new Vector.<String>(); } override public function endFills():void { } override public function beginLines():void { strokes = new Vector.<String>(); } override public function endLines():void { processPreviousStroke(); } override public function endShape():void { var i:uint; if (fills != null) { _js += fills.join(lineSep); } if (strokes != null) { _js += strokes.join(lineSep); } fills = null; strokes = null; } override public function beginFill(color:uint, alpha:Number = 1.0):void { processPreviousFill(); active = FILL_ACTIVE; prefix = ["c.save();"]; geometry = ["c.beginPath();"]; suffix = ["c.fillStyle=\"rgba(" + ColorUtils.r(color) * 255 + ", " + ColorUtils.g(color) * 255 + ", " + ColorUtils.b(color) * 255 + ", " + alpha + ")\";", "c.fill();", "c.restore();"]; } override public function beginGradientFill(type:String, colors:Array, alphas:Array, ratios:Array, matrix:Matrix = null, spreadMethod:String = SpreadMethod.PAD, interpolationMethod:String = InterpolationMethod.RGB, focalPointRatio:Number = 0):void { processPreviousFill(); active = NOT_ACTIVE; // TODO /* processPreviousFill(); active = FILL_ACTIVE; prefix = "\tCGContextSaveGState(ctx);\r\r"; geometry = "\tCGContextBeginPath(ctx);\r"; var i:uint; var len:uint = uint(Math.min(Math.min(colors.length, alphas.length), ratios.length)); if (type == GradientType.LINEAR) { suffix = "\tCGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();\r" suffix += "\tCGFloat colors[" + (len * 4) + "] = {\r"; for (i = 0; i < len; i++) { var color:uint = colors[i]; suffix += "\t\t" + ObjCUtils.num2str(ColorUtils.r(color)) + ", " + ObjCUtils.num2str(ColorUtils.g(color)) + ", " + ObjCUtils.num2str(ColorUtils.b(color)) + ", " + ObjCUtils.num2str(alphas[i]); if (i < colors.length - 1) { suffix += ","; } suffix += "\r"; } suffix += "\t};\r"; suffix += "\tCGFloat ratios[" + len + "] = { "; for (i = 0; i < len; i++) { suffix += ObjCUtils.num2str(Number(ratios[i]) / 255); if (i < ratios.length - 1) { suffix += ", "; } } suffix += " };\r"; suffix += "\tCGGradientRef g = CGGradientCreateWithColorComponents(cs, colors, ratios, " + len + ");\r" suffix += "\tCGContextEOClip(ctx);\r" var from:Point = new Point(-819.2 * matrix.a + matrix.tx, -819.2 * matrix.b + matrix.ty); var to:Point = new Point(819.2 * matrix.a + matrix.tx, 819.2 * matrix.b + matrix.ty); suffix += "\tCGPoint from = CGPointMake(" + ObjCUtils.num2str(from.x) + ", " + ObjCUtils.num2str(from.y) + ");\r"; suffix += "\tCGPoint to = CGPointMake(" + ObjCUtils.num2str(to.x) + ", " + ObjCUtils.num2str(to.y) + ");\r"; suffix += "\tCGContextDrawLinearGradient(ctx, g, from, to, 0);\r"; suffix += "\tCGGradientRelease(g);\r"; suffix += "\tCGColorSpaceRelease(cs);\r\r" } else if (type == GradientType.RADIAL) { // TODO suffix = ""; } suffix += "\tCGContextRestoreGState(ctx);\r" */ } override public function beginBitmapFill(bitmapId:uint, matrix:Matrix = null, repeat:Boolean = true, smooth:Boolean = false):void { processPreviousFill(); active = BITMAP_FILL_ACTIVE; prefix = ["c.save();"]; geometry = []; suffix = ["var i=swf.ia[swf.ca[" + bitmapId + "].i].i;", "c.drawImage(i," + "0," + "0," + "i.width," + "i.height," + matrix.tx + "," + matrix.ty + "," + (matrix.a/20) + "*i.width," + (matrix.d/20) + "*i.height" + ");", "c.restore();"] } override public function endFill():void { processPreviousFill(); active = NOT_ACTIVE; } override public function lineStyle(thickness:Number = NaN, color:uint = 0, alpha:Number = 1.0, pixelHinting:Boolean = false, scaleMode:String = LineScaleMode.NORMAL, startCaps:String = null, endCaps:String = null, joints:String = null, miterLimit:Number = 3):void { processPreviousStroke(); active = STROKE_ACTIVE; prefix = ["c.save();"]; if (startCaps == null || startCaps == CapsStyle.ROUND) { prefix.push("c.lineCap = \"round\";"); } else if (startCaps == CapsStyle.SQUARE) { prefix.push("c.lineCap = \"square\";"); } if (joints == null || joints == JointStyle.ROUND) { prefix.push("c.lineJoin = \"round\";"); } else if (joints == JointStyle.BEVEL) { prefix.push("c.lineJoin = \"miter\";"); prefix.push("c.miterLimit = " + miterLimit + ";"); } else { prefix.push("c.miterLimit = " + miterLimit + ";"); } geometry = ["c.beginPath();"]; suffix = ["c.strokeStyle=\"rgba(" + ColorUtils.r(color) * 255 + ", " + ColorUtils.g(color) * 255 + ", " + ColorUtils.b(color) * 255 + ", " + alpha + ")\";", "c.lineWidth = " + thickness + ";", "c.stroke();", "c.restore();"]; } override public function moveTo(x:Number, y:Number):void { if (active != NOT_ACTIVE && active != BITMAP_FILL_ACTIVE) { geometry.push("c.moveTo(" + NumberUtils.roundPixels20(x) + ", " + NumberUtils.roundPixels20(y) + ");"); } } override public function lineTo(x:Number, y:Number):void { if (active != NOT_ACTIVE && active != BITMAP_FILL_ACTIVE) { geometry.push("c.lineTo(" + NumberUtils.roundPixels20(x) + ", " + NumberUtils.roundPixels20(y) + ");"); } } override public function curveTo(controlX:Number, controlY:Number, anchorX:Number, anchorY:Number):void { if (active != NOT_ACTIVE && active != BITMAP_FILL_ACTIVE) { geometry.push("c.quadraticCurveTo(" + NumberUtils.roundPixels20(controlX) + ", " + NumberUtils.roundPixels20(controlY) + ", " + NumberUtils.roundPixels20(anchorX) + ", " + NumberUtils.roundPixels20(anchorY) + ");"); } } protected function processPreviousFill():void { if (active == FILL_ACTIVE) { active = NOT_ACTIVE; geometry.push("c.closePath();"); fills.push( prefix.join(lineSep), geometry.join(lineSep), suffix.join(lineSep) ); } else if(active == BITMAP_FILL_ACTIVE) { active = NOT_ACTIVE; fills.push( prefix.join(lineSep), suffix.join(lineSep) ); } } protected function processPreviousStroke():void { if (active == STROKE_ACTIVE) { active = NOT_ACTIVE; strokes.push( prefix.join(lineSep), geometry.join(lineSep), suffix.join(lineSep) ); } } } }
package game.manager { import laya.display.Sprite; import laya.display.Node; import laya.display.Scene; import com.utils.Dictionary; import common.GameConstants; import laya.display.Animation; import laya.utils.Handler; import laya.net.Loader; import laya.events.Event; import common.GameFunctions; import common.UIFunctions; import common.UIFactory; public final class AnimationManager{ private static var _instance:AnimationManager = new AnimationManager(); private var gameAnimation:Sprite = null; private var cacheMap:Dictionary = new Dictionary(); private var resIsLoaded:Boolean = false; private var imgIsLoaded:Boolean = false; public function AnimationManager(){ if (_instance == null) { this.loadImg(); this.loadRes(); this.loadAni(); }else{ throw new Error("只能用getInstance()来获取实例!"); } } public static function getInstance():AnimationManager { return _instance; } public function reset():void { resIsLoaded = false; gameAnimation = null; } private function loadImg():void { var imgArray:Array = []; imgArray.push("ani/plane/plane_body_blur.png"); Laya.loader.load(imgArray, new Handler(this, onImgLoaded), null, Loader.IMAGE); } private function loadRes():void { var atlasArray:Array = []; atlasArray.push("res/atlas/ani/bomb.atlas"); atlasArray.push("res/atlas/ani/plane.atlas"); atlasArray.push("res/atlas/ani/rocket.atlas"); atlasArray.push("res/atlas/ani/shunzi.atlas"); atlasArray.push("res/atlas/ani/settle.atlas"); Laya.loader.load(atlasArray, new Handler(this, onResLoaded), null, Loader.ATLAS); } private function loadAni():void { // Animation.createFrames(["poker/poker_bg.png"], "ani/deal.ani#ani1"); // Animation.createFrames(["poker/poker_bg.png"], "ani/deal.ani#ani2"); // Animation.createFrames(["poker/poker_bg.png"], "ani/deal.ani#ani3"); // Animation.createFrames(["poker/poker_bg.png"], "ani/deal.ani#ani4"); // Animation.createFrames(["poker/poker_bg.png"], "ani/deal.ani#ani5"); // Animation.createFrames(["poker/poker_bg.png"], "ani/deal.ani#ani6"); } private function onResLoaded():void { resIsLoaded = true; } private function onImgLoaded():void { imgIsLoaded = true; } private function extractMount():void { if(gameAnimation == null) { var gameNode:Node = Scene.root.getChildByName("gameScene"); if(gameNode != null) { gameAnimation = gameNode.getChildByName("Animation") as Sprite; } } } private function checkRes():void { if(resIsLoaded) { this.extractMount(); }else { this.loadRes(); } if(imgIsLoaded == false) { this.loadImg(); } } private function onLabel(lab:String = null):void { if(lab != null) { if(lab == "bomb") { AudioManager.getInstance().playAni(GameConstants.POKER_TYPE_BOMB); }else if(lab == "rocket") { AudioManager.getInstance().playAni(GameConstants.POKER_TYPE_KING); }else if(lab == "shunzi") { AudioManager.getInstance().playAni(GameConstants.POKER_TYPE_1STRAIGHT); }else if(lab == "plane") { AudioManager.getInstance().playAni(GameConstants.POKER_TYPE_3STRAIGHT); }else if(lab == "win") { AudioManager.getInstance().playAni(GameConstants.POKER_TYPE_WIN); }else if(lab == "fail") { AudioManager.getInstance().playAni(GameConstants.POKER_TYPE_FAIL); }else if(lab == "settle") { GameFunctions.control_markStart.call(null, true); UIFunctions.popup(UIFactory.SETTLE); } } } public function playGame(type:int):void { this.checkRes(); if(this.gameAnimation) { var name:String = null; var playName:String = ""; switch(type) { case GameConstants.POKER_TYPE_BOMB: { name = "ani/bomb.ani"; break; } case GameConstants.POKER_TYPE_KING: { name = "ani/rocket.ani"; break; } case GameConstants.POKER_TYPE_1STRAIGHT: { name = "ani/shunzi.ani"; break; } case GameConstants.POKER_TYPE_3STRAIGHT: case GameConstants.POKER_TYPE_3STRAIGHT1: case GameConstants.POKER_TYPE_3STRAIGHT2: { name = "ani/plane.ani"; break; } case GameConstants.POKER_TYPE_WIN: { name = "ani/win.ani"; // playName = "ani1"; break; } case GameConstants.POKER_TYPE_WIN1: { name = "ani/win.ani"; playName = "ani2"; break; } case GameConstants.POKER_TYPE_FAIL: { name = "ani/fail.ani"; // playName = "ani1"; break; } case GameConstants.POKER_TYPE_FAIL1: { name = "ani/fail.ani"; playName = "ani2"; break; } } if(name != null) { var ti:Animation = this.cacheMap.get(name); if(ti == null) { ti = new Animation(); ti.loadAnimation(name); ti.on(Event.LABEL, this, onLabel); this.gameAnimation.addChild(ti); this.cacheMap.set(name, ti); } ti.play(0, false, playName); } } } public function playDeal(type:int):void { this.checkRes(); if(this.gameAnimation) { var name:String = null; var playName:String = ""; switch(type) { case GameConstants.POKER_TYPE_DEAL1: { name = "ani/deal.ani"; playName = "ani1"; break; } case GameConstants.POKER_TYPE_DEAL2: { name = "ani/deal.ani"; playName = "ani2"; break; } case GameConstants.POKER_TYPE_DEAL3: { name = "ani/deal.ani"; playName = "ani3"; break; } case GameConstants.POKER_TYPE_DEAL4: { name = "ani/deal.ani"; playName = "ani4"; break; } case GameConstants.POKER_TYPE_DEAL5: { name = "ani/deal.ani"; playName = "ani5"; break; } case GameConstants.POKER_TYPE_DEAL6: { name = "ani/deal.ani"; playName = "ani6"; break; } } if(name != null) { var ti:Animation = this.cacheMap.get(name); if(ti == null) { ti = new Animation(); ti.loadAnimation(name); this.gameAnimation.addChild(ti); this.cacheMap.set(name, ti); } ti.play(0, false, playName); } } } } }
#fileID<SearchHLD_as> <DocumentInfo> docID A_Spec_Search_HLD; docVer 00; docRev a; </DocumentInfo> #import<toolkit.al> begin type List LIST = seq int; end begin axdef Find bool find: LIST <--> int; where forAll{list: LIST; value: int; ? @ find(list, value) <=> (value in ran(list)); }; end
package ember.io { import ember.core.Entity; import ember.core.Game; final public class EntityEncoder { private var _componentEncoder:ComponentEncoder; public function EntityEncoder(componentEncoder:ComponentEncoder) { _componentEncoder = componentEncoder; } public function encode(entity:Entity):Object { var components:Vector.<Object> = entity.getComponents(); var list:Array = []; for each (var component:Object in components) list.push(_componentEncoder.encode(component)); var output:Object = {components:list}; if (entity.name) output.name = entity.name; return output; } public function decode(game:Game, object:Object):Entity { var name:String = object["name"] || ""; var entity:Entity = game.createEntity(name); var list:Object = object.components; for each (var component:Object in list) entity.addComponent(_componentEncoder.decode(component)); return entity; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.graphics.codec { import flash.display.BitmapData; import flash.utils.ByteArray; /** * The JPEGEncoder class converts raw bitmap images into encoded * images using Joint Photographic Experts Group (JPEG) compression. * * For information about the JPEG algorithm, see the document * http://www.opennet.ru/docs/formats/jpeg.txt by Cristi Cuturicu. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class JPEGEncoder implements IImageEncoder { include "../../core/Version.as"; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @private */ private static const CONTENT_TYPE:String = "image/jpeg"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param quality A value between 0.0 and 100.0. * The smaller the <code>quality</code> value, * the smaller the file size of the resultant image. * The value does not affect the encoding speed. *. Note that even though this value is a number between 0.0 and 100.0, * it does not represent a percentage. * The default value is 50.0. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function JPEGEncoder(quality:Number = 50.0) { super(); if (quality <= 0.0) quality = 1.0; if (quality > 100.0) quality = 100.0; var sf:int = 0; if (quality < 50.0) sf = int(5000 / quality); else sf = int(200 - quality * 2); // Create tables initHuffmanTbl(); initCategoryNumber(); initQuantTables(sf); } //-------------------------------------------------------------------------- // // Constants // //-------------------------------------------------------------------------- /** * @private */ private const std_dc_luminance_nrcodes:Array = [ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]; /** * @private */ private const std_dc_luminance_values:Array = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]; /** * @private */ private const std_dc_chrominance_nrcodes:Array = [ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 ]; /** * @private */ private const std_dc_chrominance_values:Array = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]; /** * @private */ private const std_ac_luminance_nrcodes:Array = [ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7D ]; /** * @private */ private const std_ac_luminance_values:Array = [ 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA ]; /** * @private */ private const std_ac_chrominance_nrcodes:Array = [ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 ]; /** * @private */ private const std_ac_chrominance_values:Array = [ 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA ]; /** * @private */ private const ZigZag:Array = [ 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63 ]; //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Initialized by initHuffmanTbl() in constructor. */ private var YDC_HT:Array; /** * @private * Initialized by initHuffmanTbl() in constructor. */ private var UVDC_HT:Array; /** * @private * Initialized by initHuffmanTbl() in constructor. */ private var YAC_HT:Array; /** * @private * Initialized by initHuffmanTbl() in constructor. */ private var UVAC_HT:Array; /** * @private * Initialized by initCategoryNumber() in constructor. */ private var category:Array = new Array(65535); /** * @private * Initialized by initCategoryNumber() in constructor. */ private var bitcode:Array = new Array(65535); /** * @private * Initialized by initQuantTables() in constructor. */ private var YTable:Array = new Array(64); /** * @private * Initialized by initQuantTables() in constructor. */ private var UVTable:Array = new Array(64); /** * @private * Initialized by initQuantTables() in constructor. */ private var fdtbl_Y:Array = new Array(64); /** * @private * Initialized by initQuantTables() in constructor. */ private var fdtbl_UV:Array = new Array(64); /** * @private * The output ByteArray containing the encoded image data. */ private var byteout:ByteArray; /** * @private */ private var bytenew:int = 0; /** * @private */ private var bytepos:int = 7; /** * @private */ private var DU:Array = new Array(64); /** * @private */ private var YDU:Array = new Array(64); /** * @private */ private var UDU:Array = new Array(64); /** * @private */ private var VDU:Array = new Array(64); //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // contentType //---------------------------------- /** * The MIME type for the JPEG encoded image. * The value is <code>"image/jpeg"</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get contentType():String { return CONTENT_TYPE; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Converts the pixels of BitmapData object * to a JPEG-encoded ByteArray object. * * @param bitmapData The input BitmapData object. * * @return Returns a ByteArray object containing JPEG-encoded image data. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function encode(bitmapData:BitmapData):ByteArray { return internalEncode(bitmapData, bitmapData.width, bitmapData.height, bitmapData.transparent); } /** * Converts a ByteArray object containing raw pixels * in 32-bit ARGB (Alpha, Red, Green, Blue) format * to a new JPEG-encoded ByteArray object. * The original ByteArray is left unchanged. * Transparency is not supported; however you still must represent * each pixel as four bytes in ARGB format. * * @param byteArray The input ByteArray object containing raw pixels. * This ByteArray should contain * <code>4 * width * height</code> bytes. * Each pixel is represented by 4 bytes, in the order ARGB. * The first four bytes represent the top-left pixel of the image. * The next four bytes represent the pixel to its right, etc. * Each row follows the previous one without any padding. * * @param width The width of the input image, in pixels. * * @param height The height of the input image, in pixels. * * @param transparent If <code>false</code>, * alpha channel information is ignored. * * @return Returns a ByteArray object containing JPEG-encoded image data. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function encodeByteArray(byteArray:ByteArray, width:int, height:int, transparent:Boolean = true):ByteArray { return internalEncode(byteArray, width, height, transparent); } //-------------------------------------------------------------------------- // // Methods: Initialization // //-------------------------------------------------------------------------- /** * @private * Initializes the Huffman tables YDC_HT, UVDC_HT, YAC_HT, and UVAC_HT. */ private function initHuffmanTbl():void { YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes, std_dc_luminance_values); UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes, std_dc_chrominance_values); YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes, std_ac_luminance_values); UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes, std_ac_chrominance_values); } /** * @private */ private function computeHuffmanTbl(nrcodes:Array, std_table:Array):Array { var codevalue:int = 0; var pos_in_table:int = 0; var HT:Array = []; for (var k:int = 1; k <= 16; k++) { for (var j:int = 1; j <= nrcodes[k]; j++) { HT[std_table[pos_in_table]] = new BitString(); HT[std_table[pos_in_table]].val = codevalue; HT[std_table[pos_in_table]].len = k; pos_in_table++; codevalue++; } codevalue *= 2; } return HT; } /** * @private * Initializes the category and bitcode arrays. */ private function initCategoryNumber():void { var nr:int; var nrlower:int = 1; var nrupper:int = 2; for (var cat:int = 1; cat <= 15; cat++) { // Positive numbers for (nr = nrlower; nr < nrupper; nr++) { category[32767 + nr] = cat; bitcode[32767 + nr] = new BitString(); bitcode[32767 + nr].len = cat; bitcode[32767 + nr].val = nr; } // Negative numbers for (nr = -(nrupper - 1); nr <= -nrlower; nr++) { category[32767 + nr] = cat; bitcode[32767 + nr] = new BitString(); bitcode[32767 + nr].len = cat; bitcode[32767 + nr].val = nrupper - 1 + nr; } nrlower <<= 1; nrupper <<= 1; } } /** * @private * Initializes YTable, UVTable, fdtbl_Y, and fdtbl_UV. */ private function initQuantTables(sf:int):void { var i:int = 0; var t:Number; var YQT:Array = [ 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99 ]; for (i = 0; i < 64; i++) { t = Math.floor((YQT[i] * sf + 50)/100); if (t < 1) t = 1; else if (t > 255) t = 255; YTable[ZigZag[i]] = t; } var UVQT:Array = [ 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99 ]; for (i = 0; i < 64; i++) { t = Math.floor((UVQT[i] * sf + 50) / 100); if (t < 1) t = 1; else if (t > 255) t = 255; UVTable[ZigZag[i]] = t; } var aasf:Array = [ 1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379 ]; i = 0; for (var row:int = 0; row < 8; row++) { for (var col:int = 0; col < 8; col++) { fdtbl_Y[i] = (1.0 / (YTable [ZigZag[i]] * aasf[row] * aasf[col] * 8.0)); fdtbl_UV[i] = (1.0 / (UVTable[ZigZag[i]] * aasf[row] * aasf[col] * 8.0)); i++; } } } //-------------------------------------------------------------------------- // // Methods: Core processing // //-------------------------------------------------------------------------- /** * @private */ private function internalEncode(source:Object, width:int, height:int, transparent:Boolean = true):ByteArray { // The source is either a BitmapData or a ByteArray. var sourceBitmapData:BitmapData = source as BitmapData; var sourceByteArray:ByteArray = source as ByteArray; // Initialize bit writer byteout = new ByteArray(); bytenew = 0; bytepos = 7; // Add JPEG headers writeWord(0xFFD8); // SOI writeAPP0(); writeDQT(); writeSOF0(width, height); writeDHT(); writeSOS(); // Encode 8x8 macroblocks var DCY:Number = 0; var DCU:Number = 0; var DCV:Number = 0; bytenew = 0; bytepos = 7; for (var ypos:int = 0; ypos < height; ypos += 8) { for (var xpos:int = 0; xpos < width; xpos += 8) { RGB2YUV(sourceBitmapData, sourceByteArray, xpos, ypos, width, height); DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); } } // Do the bit alignment of the EOI marker if (bytepos >= 0) { var fillbits:BitString = new BitString(); fillbits.len = bytepos + 1; fillbits.val = (1 << (bytepos + 1)) - 1; writeBits(fillbits); } // Add EOI writeWord(0xFFD9); return byteout; } /** * @private */ private function RGB2YUV(sourceBitmapData:BitmapData, sourceByteArray:ByteArray, xpos:int, ypos:int, width:int, height:int):void { var k:int = 0; // index into 64-element block arrays for (var j:int = 0; j < 8; j++) { var y:int = ypos + j; if (y >= height) y = height - 1; for (var i:int = 0; i < 8; i++) { var x:int = xpos + i; if (x >= width) x = width - 1; var pixel:uint; if (sourceBitmapData) { pixel = sourceBitmapData.getPixel32(x, y); } else { sourceByteArray.position = 4 * (y * width + x); pixel = sourceByteArray.readUnsignedInt(); } var r:Number = Number((pixel >> 16) & 0xFF); var g:Number = Number((pixel >> 8) & 0xFF); var b:Number = Number(pixel & 0xFF); YDU[k] = 0.29900 * r + 0.58700 * g + 0.11400 * b - 128.0; UDU[k] = -0.16874 * r - 0.33126 * g + 0.50000 * b; VDU[k] = 0.50000 * r - 0.41869 * g - 0.08131 * b; k++; } } } /** * @private */ private function processDU(CDU:Array, fdtbl:Array, DC:Number, HTDC:Array, HTAC:Array):Number { var EOB:BitString = HTAC[0x00]; var M16zeroes:BitString = HTAC[0xF0]; var i:int; var DU_DCT:Array = fDCTQuant(CDU, fdtbl); // ZigZag reorder for (i = 0; i < 64; i++) { DU[ZigZag[i]] = DU_DCT[i]; } var Diff:int = DU[0] - DC; DC = DU[0]; // Encode DC if (Diff == 0) { writeBits(HTDC[0]); // Diff might be 0 } else { writeBits(HTDC[category[32767 + Diff]]); writeBits(bitcode[32767 + Diff]); } // Encode ACs var end0pos:int = 63; for (; (end0pos > 0) && (DU[end0pos] == 0); end0pos--) { }; // end0pos = first element in reverse order != 0 if (end0pos == 0) { writeBits(EOB); return DC; } i = 1; while (i <= end0pos) { var startpos:int = i; for (; (DU[i] == 0) && (i <= end0pos); i++) { } var nrzeroes:int = i - startpos; if (nrzeroes >= 16) { for (var nrmarker:int = 1; nrmarker <= nrzeroes / 16; nrmarker++) { writeBits(M16zeroes); } nrzeroes = int(nrzeroes & 0xF); } writeBits(HTAC[nrzeroes * 16 + category[32767 + DU[i]]]); writeBits(bitcode[32767 + DU[i]]); i++; } if (end0pos != 63) writeBits(EOB); return DC; } /** * @private */ private function fDCTQuant(data:Array, fdtbl:Array):Array { // Pass 1: process rows. var dataOff:int = 0; var i:int; for (i = 0; i < 8; i++) { var tmp0:Number = data[dataOff + 0] + data[dataOff + 7]; var tmp7:Number = data[dataOff + 0] - data[dataOff + 7]; var tmp1:Number = data[dataOff + 1] + data[dataOff + 6]; var tmp6:Number = data[dataOff + 1] - data[dataOff + 6]; var tmp2:Number = data[dataOff + 2] + data[dataOff + 5]; var tmp5:Number = data[dataOff + 2] - data[dataOff + 5]; var tmp3:Number = data[dataOff + 3] + data[dataOff + 4]; var tmp4:Number = data[dataOff + 3] - data[dataOff + 4]; // Even part var tmp10:Number = tmp0 + tmp3; // phase 2 var tmp13:Number = tmp0 - tmp3; var tmp11:Number = tmp1 + tmp2; var tmp12:Number = tmp1 - tmp2; data[dataOff + 0] = tmp10 + tmp11; // phase 3 data[dataOff + 4] = tmp10 - tmp11; var z1:Number = (tmp12 + tmp13) * 0.707106781; // c4 data[dataOff + 2] = tmp13 + z1; // phase 5 data[dataOff + 6] = tmp13 - z1; // Odd part tmp10 = tmp4 + tmp5; // phase 2 tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; // The rotator is modified from fig 4-8 to avoid extra negations. var z5:Number = (tmp10 - tmp12) * 0.382683433; // c6 var z2:Number = 0.541196100 * tmp10 + z5; // c2 - c6 var z4:Number = 1.306562965 * tmp12 + z5; // c2 + c6 var z3:Number = tmp11 * 0.707106781; // c4 var z11:Number = tmp7 + z3; // phase 5 var z13:Number = tmp7 - z3; data[dataOff + 5] = z13 + z2; // phase 6 data[dataOff + 3] = z13 - z2; data[dataOff + 1] = z11 + z4; data[dataOff + 7] = z11 - z4; dataOff += 8; // advance pointer to next row } // Pass 2: process columns. dataOff = 0; for (i = 0; i < 8; i++) { tmp0 = data[dataOff + 0] + data[dataOff + 56]; tmp7 = data[dataOff + 0] - data[dataOff + 56]; tmp1 = data[dataOff + 8] + data[dataOff + 48]; tmp6 = data[dataOff + 8] - data[dataOff + 48]; tmp2 = data[dataOff + 16] + data[dataOff + 40]; tmp5 = data[dataOff + 16] - data[dataOff + 40]; tmp3 = data[dataOff + 24] + data[dataOff + 32]; tmp4 = data[dataOff + 24] - data[dataOff + 32]; // Even par tmp10 = tmp0 + tmp3; // phase 2 tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; data[dataOff + 0] = tmp10 + tmp11; // phase 3 data[dataOff + 32] = tmp10 - tmp11; z1 = (tmp12 + tmp13) * 0.707106781; // c4 data[dataOff + 16] = tmp13 + z1; // phase 5 data[dataOff + 48] = tmp13 - z1; // Odd part tmp10 = tmp4 + tmp5; // phase 2 tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; // The rotator is modified from fig 4-8 to avoid extra negations. z5 = (tmp10 - tmp12) * 0.382683433; // c6 z2 = 0.541196100 * tmp10 + z5; // c2 - c6 z4 = 1.306562965 * tmp12 + z5; // c2 + c6 z3 = tmp11 * 0.707106781; // c4 z11 = tmp7 + z3; // phase 5 */ z13 = tmp7 - z3; data[dataOff + 40] = z13 + z2; // phase 6 data[dataOff + 24] = z13 - z2; data[dataOff + 8] = z11 + z4; data[dataOff + 56] = z11 - z4; dataOff++; // advance pointer to next column } // Quantize/descale the coefficients for (i = 0; i < 64; i++) { // Apply the quantization and scaling factor // and round to nearest integer data[i] = Math.round((data[i] * fdtbl[i])); } return data; } //-------------------------------------------------------------------------- // // Methods: Output // //-------------------------------------------------------------------------- /** * @private */ private function writeBits(bs:BitString):void { var value:int = bs.val; var posval:int = bs.len - 1; while (posval >= 0) { if (value & uint(1 << posval) ) { bytenew |= uint(1 << bytepos); } posval--; bytepos--; if (bytepos < 0) { if (bytenew == 0xFF) { writeByte(0xFF); writeByte(0); } else { writeByte(bytenew); } bytepos = 7; bytenew = 0; } } } /** * @private */ private function writeByte(value:int):void { byteout.writeByte(value); } /** * @private */ private function writeWord(value:int):void { writeByte((value >> 8) & 0xFF); writeByte(value & 0xFF); } /** * @private */ private function writeAPP0():void { writeWord(0xFFE0); // marker writeWord(16); // length writeByte(0x4A); // J writeByte(0x46); // F writeByte(0x49); // I writeByte(0x46); // F writeByte(0); // = "JFIF",'\0' writeByte(1); // versionhi writeByte(1); // versionlo writeByte(0); // xyunits writeWord(1); // xdensity writeWord(1); // ydensity writeByte(0); // thumbnwidth writeByte(0); // thumbnheight } /** * @private */ private function writeDQT():void { writeWord(0xFFDB); // marker writeWord(132); // length writeByte(0); var i:int; for (i = 0; i < 64; i++) { writeByte(YTable[i]); } writeByte(1); for (i = 0; i < 64; i++) { writeByte(UVTable[i]); } } /** * @private */ private function writeSOF0(width:int, height:int):void { writeWord(0xFFC0); // marker writeWord(17); // length, truecolor YUV JPG writeByte(8); // precision writeWord(height); writeWord(width); writeByte(3); // nrofcomponents writeByte(1); // IdY writeByte(0x11); // HVY writeByte(0); // QTY writeByte(2); // IdU writeByte(0x11); // HVU writeByte(1); // QTU writeByte(3); // IdV writeByte(0x11); // HVV writeByte(1); // QTV } /** * @private */ private function writeDHT():void { var i:int; writeWord(0xFFC4); // marker writeWord(0x01A2); // length writeByte(0); // HTYDCinfo for (i = 0; i < 16; i++) { writeByte(std_dc_luminance_nrcodes[i + 1]); } for (i = 0; i <= 11; i++) { writeByte(std_dc_luminance_values[i]); } writeByte(0x10); // HTYACinfo for (i = 0; i < 16; i++) { writeByte(std_ac_luminance_nrcodes[i + 1]); } for (i = 0; i <= 161; i++) { writeByte(std_ac_luminance_values[i]); } writeByte(1); // HTUDCinfo for (i = 0; i < 16; i++) { writeByte(std_dc_chrominance_nrcodes[i + 1]); } for (i = 0; i <= 11; i++) { writeByte(std_dc_chrominance_values[i]); } writeByte(0x11); // HTUACinfo for (i = 0; i < 16; i++) { writeByte(std_ac_chrominance_nrcodes[i + 1]); } for (i = 0; i <= 161; i++) { writeByte(std_ac_chrominance_values[i]); } } /** * @private */ private function writeSOS():void { writeWord(0xFFDA); // marker writeWord(12); // length writeByte(3); // nrofcomponents writeByte(1); // IdY writeByte(0); // HTY writeByte(2); // IdU writeByte(0x11); // HTU writeByte(3); // IdV writeByte(0x11); // HTV writeByte(0); // Ss writeByte(0x3f); // Se writeByte(0); // Bf } } } class BitString { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function BitString() { super(); } /** * @private */ public var len:int = 0; /** * @private */ public var val:int = 0; }
//////////////////////////////////////////////////////////////////////////////// // // 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.events { import flash.events.Event; import mx.core.IToolTip; /** * The ToolTipEvent class represents ToolTip events, which are generated by the ToolTipManager * class. The ToolTipManager class calls the <code>dispatchEvent()</code> method * of the object to which the tip applies to dispatch the event. * * @see mx.managers.ToolTipManager * @see mx.core.UIComponent * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class ToolTipEvent extends Event { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * The <code>ToolTipEvent.TOOL_TIP_CREATE</code> constant defines the value of the * <code>type</code> property of the event object for a <code>toolTipCreate</code> event. * * <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>cancelable</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>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> * <tr><td><code>tooltip</code></td><td>The ToolTip object to * which this event applies.</td></tr> * </table> * * @eventType toolTipCreate * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const TOOL_TIP_CREATE:String = "toolTipCreate"; /** * The <code>ToolTipEvent.TOOL_TIP_END</code> constant defines the value of the * <code>type</code> property of the event object for a <code>toolTipEnd</code> event. * * <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>cancelable</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>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> * <tr><td><code>tooltip</code></td><td>The ToolTip object to * which this event applies.</td></tr> * </table> * * @eventType toolTipEnd * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const TOOL_TIP_END:String = "toolTipEnd"; /** * The <code>ToolTipEvent.TOOL_TIP_HIDE</code> constant defines the value of the * <code>type</code> property of the event object for a <code>toolTipHide</code> event. * * <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>cancelable</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>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> * <tr><td><code>tooltip</code></td><td>The ToolTip object to * which this event applies.</td></tr> * </table> * * @eventType toolTipHide * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const TOOL_TIP_HIDE:String = "toolTipHide"; /** * The <code>ToolTipEvent.TOOL_TIP_SHOW</code> constant defines the value of the * <code>type</code> property of the event object for a <code>toolTipShow</code> event. * * <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>cancelable</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>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> * <tr><td><code>tooltip</code></td><td>The ToolTip object to * which this event applies.</td></tr> * </table> * * @eventType toolTipShow * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const TOOL_TIP_SHOW:String = "toolTipShow"; /** * The <code>ToolTipEvent.TOOL_TIP_SHOWN</code> constant defines the value of the * <code>type</code> property of the event object for a <code>toolTipShown</code> event. * * <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>cancelable</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>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> * <tr><td><code>tooltip</code></td><td>The ToolTip object to * which this event applies.</td></tr> * </table> * * @eventType toolTipShown * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const TOOL_TIP_SHOWN:String = "toolTipShown"; /** * The <code>ToolTipEvent.TOOL_TIP_START</code> constant defines the value of the * <code>type</code> property of the event object for a <code>toolTipStart</code> event. * * <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>cancelable</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>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> * <tr><td><code>tooltip</code></td><td>The ToolTip object to * which this event applies.</td></tr> * </table> * * @eventType toolTipStart * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const TOOL_TIP_START:String = "toolTipStart"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param type The event type; indicates the action that caused the event. * * @param bubbles Specifies whether the event can bubble * up the display list hierarchy. * * @param cancelable Specifies whether the behavior * associated with the event can be prevented. * * @param toolTip The ToolTip object to which this event applies. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function ToolTipEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false, toolTip:IToolTip = null) { super(type, bubbles, cancelable); this.toolTip = toolTip; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // toolTip //---------------------------------- /** * The ToolTip object to which this event applies. * This object is normally an instance of ToolTip object, * but can be any UIComponent object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var toolTip:IToolTip; //-------------------------------------------------------------------------- // // Overridden methods: Event // //-------------------------------------------------------------------------- /** * @private */ override public function clone():Event { return new ToolTipEvent(type, bubbles, cancelable, toolTip); } } }
/** * User: booster * Date: 14/05/14 * Time: 15:51 */ package medkit.geom.shapes.crossings { import medkit.geom.shapes.PathIterator; import medkit.geom.shapes.Point2D; import medkit.geom.shapes.curve.Curve; import medkit.geom.shapes.enum.SegmentType; import medkit.geom.shapes.enum.WindingRule; public class Crossings { internal var limit:int = 0; internal var yranges:Vector.<Number> = new Vector.<Number>(10); internal var xlo:Number, ylo:Number, xhi:Number, yhi:Number; private var tmp:Vector.<Curve> = new <Curve>[]; public function Crossings(xlo:Number, ylo:Number, xhi:Number, yhi:Number) { this.xlo = xlo; this.ylo = ylo; this.xhi = xhi; this.yhi = yhi; } public final function getXLo():Number { return xlo; } public final function getYLo():Number { return ylo; } public final function getXHi():Number { return xhi; } public final function getYHi():Number { return yhi; } public final function isEmpty():Boolean { return (limit == 0); } public function record(ystart:Number, yend:Number, direction:int):void { throw new Error("abstract method"); } public function covers(ystart:Number, yend:Number):Boolean { throw new Error("abstract method"); } /* public function print():void{ System.out.println("Crossings ["); System.out.println(" bounds = ["+ylo+", "+yhi+"]"); for (var i:int= 0; i < limit; i += 2) { System.out.println(" ["+yranges[i]+", "+yranges[i+1]+"]"); } System.out.println("]"); } */ public static function findCrossings(curves:Vector.<Curve>, xlo:Number, ylo:Number, xhi:Number, yhi:Number):Crossings { var cross:Crossings = new EvenOdd(xlo, ylo, xhi, yhi); var count:int = curves.length; for(var i:int = 0; i < count; ++i) { var c:Curve = curves[i]; if(c.accumulateCrossings(cross)) return null; } return cross; } public static function findCrossingsPathIt(pi:PathIterator, xlo:Number, ylo:Number, xhi:Number, yhi:Number):Crossings { var cross:Crossings; if(pi.getWindingRule() == WindingRule.EvenOdd) cross = new EvenOdd(xlo, ylo, xhi, yhi); else cross = new NonZero(xlo, ylo, xhi, yhi); // coords array is big enough for holding: // coordinates returned from currentSegment (6) // OR // two subdivided quadratic curves (2+4+4=10) // AND // 0-1 horizontal splitting parameters // OR // 2 parametric equation derivative coefficients // OR // three subdivided cubic curves (2+6+6+6=20) // AND // 0-2 horizontal splitting parameters // OR // 3 parametric equation derivative coefficients var coords:Vector.<Point2D> = new Vector.<Point2D>(3, true); var movx:Number = 0; var movy:Number = 0; var curx:Number = 0; var cury:Number = 0; var newx:Number, newy:Number; while(!pi.isDone()) { var segType:SegmentType = pi.currentSegment(coords); switch(segType) { case SegmentType.MoveTo: if(movy != cury && cross.accumulateLine(curx, cury, movx, movy)) return null; movx = curx = coords[0].x; movy = cury = coords[0].y; break; case SegmentType.LineTo: newx = coords[0].x; newy = coords[0].y; if(cross.accumulateLine(curx, cury, newx, newy)) return null; curx = newx; cury = newy; break; case SegmentType.QuadTo: newx = coords[1].x; newy = coords[1].y; if(cross.accumulateQuad(curx, cury, coords)) return null; curx = newx; cury = newy; break; case SegmentType.CubicTo: newx = coords[2].x; newy = coords[2].y; if(cross.accumulateCubic(curx, cury, coords)) return null; curx = newx; cury = newy; break; case SegmentType.Close: if(movy != cury && cross.accumulateLine(curx, cury, movx, movy)) return null; curx = movx; cury = movy; break; } pi.next(); } if(movy != cury) { if(cross.accumulateLine(curx, cury, movx, movy)) return null; } return cross; } public function accumulateLine(x0:Number, y0:Number, x1:Number, y1:Number):Boolean { if(y0 <= y1) return accumulateLineDir(x0, y0, x1, y1, 1); else return accumulateLineDir(x1, y1, x0, y0, -1); } public function accumulateLineDir(x0:Number, y0:Number, x1:Number, y1:Number, direction:int):Boolean { if(yhi <= y0 || ylo >= y1) return false; if(x0 >= xhi && x1 >= xhi) return false; if(y0 == y1) return (x0 >= xlo || x1 >= xlo); var xstart:Number, ystart:Number, xend:Number, yend:Number; var dx:Number = (x1 - x0); var dy:Number = (y1 - y0); if(y0 < ylo) { xstart = x0 + (ylo - y0) * dx / dy; ystart = ylo; } else { xstart = x0; ystart = y0; } if(yhi < y1) { xend = x0 + (yhi - y0) * dx / dy; yend = yhi; } else { xend = x1; yend = y1; } if(xstart >= xhi && xend >= xhi) return false; if(xstart > xlo || xend > xlo) return true; record(ystart, yend, direction); return false; } public function accumulateQuad(x0:Number, y0:Number, coords:Vector.<Point2D>):Boolean { if(y0 < ylo && coords[0].y < ylo && coords[1].y < ylo) return false; if(y0 > yhi && coords[0].y > yhi && coords[1].y > yhi) return false; if(x0 > xhi && coords[0].x > xhi && coords[1].x > xhi) return false; if(x0 < xlo && coords[0].x < xlo && coords[1].x < xlo) { if(y0 < coords[1].y) record(y0 > ylo ? y0 : ylo, coords[1].y < yhi ? coords[1].y : yhi, 1); else if(y0 > coords[1].y) record(coords[1].y > ylo ? coords[1].y : ylo, y0 < yhi ? y0 : yhi, -1); return false; } Curve.insertQuad(tmp, x0, y0, coords); var count:int = tmp.length; for(var i:int = 0; i < count; ++i) { var c:Curve = tmp[i]; if(c.accumulateCrossings(this)) return true; } tmp.length = 0; return false; } public function accumulateCubic(x0:Number, y0:Number, coords:Vector.<Point2D>):Boolean { if(y0 < ylo && coords[0].y < ylo && coords[1].y < ylo && coords[2].y < ylo) return false; if(y0 > yhi && coords[0].y > yhi && coords[1].y > yhi && coords[2].y > yhi) return false; if(x0 > xhi && coords[0].x > xhi && coords[1].x > xhi && coords[2].x > xhi) return false; if(x0 < xlo && coords[0].x < xlo && coords[1].x < xlo && coords[2].x < xlo) { if(y0 <= coords[2].y) record(y0 > ylo ? y0 : ylo, coords[2].y < yhi ? coords[2].y : yhi, 1); else record(coords[2].y > ylo ? coords[2].y : ylo, y0 < yhi ? y0 : yhi, -1); return false; } Curve.insertCubic(tmp, x0, y0, coords); var count:int = tmp.length; for(var i:int = 0; i < count; ++i) { var c:Curve = tmp[i]; if(c.accumulateCrossings(this)) return true; } tmp.length = 0; return false; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.effects.interpolation { import mx.styles.StyleManager; import mx.utils.HSBColor; /** * The HSBInterpolator class provides Hue, Saturation, and Brightness (HSB) * color interpolation between RGB <code>uint</code> start and end values. * Interpolation is done by treating * the start and end values as integers with RGB color channel information in * the least-significant 3 bytes, converting these to HSB values, and * interpolating linearly for each of the h (hue), s (saturation), * and b (brightness) parameters. * * <p>Because this interpolator may perform more calculations than a * typical interpolator that is simply interpolating a given type, * specifically to convert the RGB start and end values, this * interpolator provides the option of supplying start and end values * to the constructor. If you specify the start and end RGB values, then * the conversions of these values is calculated once, * and does not need to be done at every future call to * the <code>interpolate()</code> method during the animation.</p> * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public class HSBInterpolator implements IInterpolator { private static var theInstance:HSBInterpolator; private var startHSB:HSBColor; private var endHSB:HSBColor; /** * Constructor. * * The optional parameters for <code>startRGB</code> and * <code>endRGB</code> help to optimize runtime performance by * performing RGB to HSB conversions at construction time, instead of * dynamically with every call to the <code>interpolate()</code> method. * * @param startRGB The starting color, as an unsigned integer RGB value. * * @param endRGB The ending color, as an unsigned integer RGB value. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function HSBInterpolator(startRGB:uint = StyleManager.NOT_A_COLOR, endRGB:uint = StyleManager.NOT_A_COLOR) { super(); if (startRGB != StyleManager.NOT_A_COLOR) startHSB = HSBColor.convertRGBtoHSB(startRGB); if (endRGB != StyleManager.NOT_A_COLOR) endHSB = HSBColor.convertRGBtoHSB(endRGB); } /** * Returns the singleton of this class. * * <p>Note that the singleton * of the HSBInterpolator class might be less useful than separate instances * of the class because separate instances can take advantage of * precalculating the RGB to HSB conversions for the start and end colors.</p> * * @return The singleton of the HSBInterpolator class. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public static function getInstance():HSBInterpolator { if (!theInstance) theInstance = new HSBInterpolator(); return theInstance; } /** * The interpolation for the HSBInterpolator class takes the form of parametric * calculations on each of the three values h (hue), s (saturation), * and b (brightness) of HSB colors derived from the start and end RGB colors. * * @param fraction The fraction elapsed of the * animation, between 0.0 and 1.0. * * @param startValue The start value of the interpolation. * * @param endValue The end value of the interpolation. * * @return The interpolated value. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function interpolate(fraction:Number, startValue:Object, endValue:Object):Object { if (fraction == 0) return startValue; else if (fraction == 1) return endValue; var start:HSBColor = startHSB; var end:HSBColor = endHSB; // If we have not converted start/end values at construction time, // do so now if (!start) start = HSBColor.convertRGBtoHSB(uint(startValue)); if (!end) end = HSBColor.convertRGBtoHSB(uint(endValue)); var startH:Number = start.hue; var endH:Number = end.hue; var deltaH:Number; var deltaS:Number = end.saturation - start.saturation; var deltaB:Number = end.brightness - start.brightness; if (isNaN(startH) || isNaN(endH)) deltaH = 0; else { deltaH = endH - startH; if (Math.abs(deltaH) > 180) { if (startH < endH) startH += 360; else endH += 360; deltaH = endH - startH; } } var saturation:Number = start.saturation + deltaS * fraction; var brightness:Number = start.brightness + deltaB * fraction; var hue:Number; if (isNaN(startH)) hue = endH; else if (isNaN(endH)) hue = startH; else hue = startH + deltaH * fraction; var rgb:uint = HSBColor.convertHSBtoRGB(hue, saturation, brightness); return rgb; } /** * @private * * Utility function called by increment() and decrement() */ private function combine(baseValue:uint, deltaValue:uint, increment:Boolean):Object { var start:HSBColor = HSBColor.convertRGBtoHSB(baseValue); var delta:HSBColor = HSBColor.convertRGBtoHSB(deltaValue); var newH:Number, newS:Number, newB:Number; if (increment) { newH = (start.hue + delta.hue) % 360; newS = Math.min(start.saturation + delta.saturation, 1); newB = Math.min(start.brightness + delta.brightness, 1); } else { newH = (start.hue + delta.hue) % 360; newS = Math.max(start.saturation - delta.saturation, 0); newB = Math.max(start.brightness - delta.brightness, 0); } return HSBColor.convertHSBtoRGB(newH, newS, newB); } /** * Returns the result of the two RGB values added * together as HSB colors. Each value is converted to an HSB color * first, and then each component (hue, saturation, and brightness) * will be treated individually. * The saturation and brightness * components are clamped to lie between 0 and 1, and the hue degrees * are modulated by 360 to lie between 0 and 360. * * @param baseValue The start value of the interpolation. * * @param incrementValue The change to apply to the <code>baseValue</code>. * * @return The interpolated value. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function increment(baseValue:Object, incrementValue:Object):Object { return combine(uint(baseValue), uint(incrementValue), true); } /** * Returns the result of the two RGB values added * together as HSB colors. Each value is converted to an HSB color * first, and then each component (hue, saturation, and brightness) * is treated individually. * The saturation and brightness * components are clamped to lie between 0 and 1, and the hue degrees * are modulated by 360 to lie between 0 and 360. * * @param baseValue The start value of the interpolation. * * @param decrementValue The change to apply to the <code>baseValue</code>. * * @return The interpolated value. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function decrement(baseValue:Object, decrementValue:Object):Object { return combine(uint(baseValue), uint(decrementValue), false); } } }
package tryonSystem { import bagAndInfo.cell.PersonalInfoCell; import com.pickgliss.ui.ComponentFactory; import com.pickgliss.ui.controls.SelectedCheckButton; import com.pickgliss.ui.controls.container.SimpleTileList; import com.pickgliss.ui.core.Disposeable; import com.pickgliss.ui.image.MovieImage; import com.pickgliss.ui.image.Scale9CornerImage; import com.pickgliss.ui.text.FilterFrameText; import com.pickgliss.utils.ObjectUtils; import ddt.data.goods.InventoryItemInfo; import ddt.manager.LanguageMgr; import ddt.manager.PlayerManager; import ddt.manager.SoundManager; import ddt.utils.PositionUtils; import ddt.view.character.CharactoryFactory; import ddt.view.character.RoomCharacter; import equipretrieve.effect.AnimationControl; import equipretrieve.effect.GlowFilterAnimation; import flash.display.Bitmap; import flash.display.MovieClip; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import road7th.data.DictionaryData; public class TryonPanelView extends Sprite implements Disposeable { private static const CELL_PLACE:Array = [0,1,2,3,4,5,11,13]; private var _controller:TryonSystemController; private var _model:TryonModel; private var _bg:Scale9CornerImage; private var _bg1:Scale9CornerImage; private var _tryTxt:Bitmap; private var _chBg:Bitmap; private var _hideTxt:Bitmap; private var _hideBg:Bitmap; private var _hideHatBtn:SelectedCheckButton; private var _hideGlassBtn:SelectedCheckButton; private var _hideSuitBtn:SelectedCheckButton; private var _hideWingBtn:SelectedCheckButton; private var _bagItems:DictionaryData; private var _character:RoomCharacter; private var _itemList:SimpleTileList; private var _cells:Array; private var _bagCells:Array; private var _nickName:FilterFrameText; private var _effect:MovieClip; public function TryonPanelView(param1:TryonSystemController) { super(); this._controller = param1; this._model = this._controller.model; this._cells = []; this.initView(); this.initEvents(); } private function initView() : void { var _loc2_:InventoryItemInfo = null; var _loc3_:int = 0; var _loc4_:Sprite = null; var _loc5_:TryonCell = null; var _loc6_:MovieImage = null; var _loc7_:GlowFilterAnimation = null; var _loc8_:PersonalInfoCell = null; this._bg = ComponentFactory.Instance.creatComponentByStylename("core.tryOnBigBg"); addChild(this._bg); this._bg1 = ComponentFactory.Instance.creatComponentByStylename("core.tryOnSmallBg"); addChild(this._bg1); this._tryTxt = ComponentFactory.Instance.creatBitmap("asset.tryOnTxtImage"); addChild(this._tryTxt); this._chBg = ComponentFactory.Instance.creatBitmap("asset.core.tryonCharaterBgAsset"); addChild(this._chBg); this._hideBg = ComponentFactory.Instance.creatBitmap("asset.core.hideBgAsset"); addChild(this._hideBg); this._hideTxt = ComponentFactory.Instance.creatBitmap("asset.core.hideTxtAsset"); addChild(this._hideTxt); this._hideGlassBtn = ComponentFactory.Instance.creatComponentByStylename("tryon.HideHatCheckBox"); addChild(this._hideGlassBtn); this._hideHatBtn = ComponentFactory.Instance.creatComponentByStylename("tryon.HideGlassCheckBox"); addChild(this._hideHatBtn); this._hideSuitBtn = ComponentFactory.Instance.creatComponentByStylename("tryon.HideSuitCheckBox"); addChild(this._hideSuitBtn); this._hideWingBtn = ComponentFactory.Instance.creatComponentByStylename("tryon.HideWingCheckBox"); addChild(this._hideWingBtn); this._hideHatBtn.text = LanguageMgr.GetTranslation("shop.ShopIITryDressView.hideHat"); this._hideGlassBtn.text = LanguageMgr.GetTranslation("tank.view.changeColor.ChangeColorLeftView.glass"); this._hideSuitBtn.text = LanguageMgr.GetTranslation("tank.view.changeColor.ChangeColorLeftView.suit"); this._hideWingBtn.text = LanguageMgr.GetTranslation("tank.view.changeColor.ChangeColorLeftView.wing"); this._hideGlassBtn.selected = this._model.playerInfo.getGlassHide(); this._hideSuitBtn.selected = this._model.playerInfo.getSuitesHide(); this._hideWingBtn.selected = this._model.playerInfo.wingHide; this._character = CharactoryFactory.createCharacter(this._model.playerInfo,"room") as RoomCharacter; this._character.x = 160; this._character.y = 26; addChild(this._character); this._character.show(false,-1); this._effect = ComponentFactory.Instance.creat("asset.core.tryonEffect"); PositionUtils.setPos(this._effect,"tryonSystem.TryonPanelView.effectPos"); this._effect.stop(); addChild(this._effect); this._itemList = new SimpleTileList(2); this._itemList.vSpace = 50; this._itemList.hSpace = 50; this._itemList.x = 219; this._itemList.y = 32; var _loc1_:AnimationControl = new AnimationControl(); _loc1_.addEventListener(Event.COMPLETE,this._cellLightComplete); for each(_loc2_ in this._model.items) { _loc4_ = new Sprite(); _loc4_.graphics.beginFill(16777215,0); _loc4_.graphics.drawRect(0,0,43,43); _loc4_.graphics.endFill(); _loc5_ = new TryonCell(_loc4_); _loc5_.info = _loc2_; _loc5_.addEventListener(MouseEvent.CLICK,this.__onClick); _loc5_.buttonMode = true; this._itemList.addChild(_loc5_); this._cells.push(_loc5_); if(_loc2_.CategoryID == 3) { this._hideHatBtn.selected = true; this._model.playerInfo.setHatHide(this._hideHatBtn.selected); } else { this._hideHatBtn.selected = this._model.playerInfo.getHatHide(); } _loc6_ = ComponentFactory.Instance.creatComponentByStylename("asset.core.itemBigShinelight"); _loc6_.movie.play(); _loc5_.addChildAt(_loc6_,1); _loc7_ = new GlowFilterAnimation(); _loc7_.start(_loc6_,false,16763955,0,0); _loc7_.addMovie(0,0,19,0); _loc1_.addMovies(_loc7_); } addChild(this._itemList); this._bagItems = this._model.bagItems; this._bagCells = []; _loc3_ = 0; while(_loc3_ < 8) { _loc8_ = new PersonalInfoCell(_loc3_,this._bagItems[CELL_PLACE[_loc3_]] as InventoryItemInfo,true); this._bagCells.push(_loc8_); _loc3_++; } this._nickName = ComponentFactory.Instance.creatComponentByStylename("tryonNickNameText"); addChild(this._nickName); this._nickName.text = PlayerManager.Instance.Self.NickName; _loc1_.startMovie(); } private function _cellLightComplete(param1:Event) : void { var _loc2_:int = 0; var _loc3_:int = 0; var _loc4_:MovieImage = null; param1.currentTarget.removeEventListener(Event.COMPLETE,this._cellLightComplete); if(this._cells) { _loc2_ = this._cells.length; _loc3_ = 0; while(_loc3_ < _loc2_) { _loc4_ = this._cells[_loc3_].removeChildAt(1); _loc4_.dispose(); _loc3_++; } } } private function initEvents() : void { this._hideGlassBtn.addEventListener(MouseEvent.CLICK,this.__hideGlassClickHandler); this._hideHatBtn.addEventListener(MouseEvent.CLICK,this.__hideHatClickHandler); this._hideSuitBtn.addEventListener(MouseEvent.CLICK,this.__hideSuitClickHandler); this._hideWingBtn.addEventListener(MouseEvent.CLICK,this.__hideWingClickHandler); this._model.addEventListener(Event.CHANGE,this.__onchange); } private function removeEvents() : void { this._hideGlassBtn.removeEventListener(MouseEvent.CLICK,this.__hideGlassClickHandler); this._hideHatBtn.removeEventListener(MouseEvent.CLICK,this.__hideHatClickHandler); this._hideSuitBtn.removeEventListener(MouseEvent.CLICK,this.__hideSuitClickHandler); this._hideWingBtn.removeEventListener(MouseEvent.CLICK,this.__hideWingClickHandler); this._model.removeEventListener(Event.CHANGE,this.__onchange); } private function __onchange(param1:Event) : void { var _loc2_:int = 0; while(_loc2_ < 8) { this._bagCells[_loc2_].info = this._bagItems[CELL_PLACE[_loc2_]] as InventoryItemInfo; _loc2_++; } } private function __hideWingClickHandler(param1:MouseEvent) : void { SoundManager.instance.play("008"); this._model.playerInfo.wingHide = this._hideWingBtn.selected; } private function __hideSuitClickHandler(param1:MouseEvent) : void { SoundManager.instance.play("008"); this._model.playerInfo.setSuiteHide(this._hideSuitBtn.selected); } private function __hideHatClickHandler(param1:MouseEvent) : void { SoundManager.instance.play("008"); this._model.playerInfo.setHatHide(this._hideHatBtn.selected); } private function __hideGlassClickHandler(param1:MouseEvent) : void { SoundManager.instance.play("008"); this._model.playerInfo.setGlassHide(this._hideGlassBtn.selected); } private function __onClick(param1:MouseEvent) : void { var _loc2_:TryonCell = null; SoundManager.instance.play("008"); for each(_loc2_ in this._cells) { _loc2_.selected = false; } TryonCell(param1.currentTarget).selected = true; this._model.selectedItem = TryonCell(param1.currentTarget).info as InventoryItemInfo; if(this._effect) { this._effect.play(); } } public function dispose() : void { var _loc1_:TryonCell = null; var _loc2_:PersonalInfoCell = null; this.removeEvents(); for each(_loc1_ in this._cells) { _loc1_.removeEventListener(MouseEvent.CLICK,this.__onClick); _loc1_.dispose(); } this._cells = null; for each(_loc2_ in this._bagCells) { _loc2_.dispose(); } this._bagCells = null; if(this._effect) { if(this._effect.parent) { this._effect.parent.removeChild(this._effect); } this._effect = null; } this._bg1.dispose(); this._bg1 = null; this._bg.dispose(); this._bg = null; ObjectUtils.disposeObject(this._tryTxt); this._tryTxt = null; ObjectUtils.disposeObject(this._chBg); this._chBg = null; ObjectUtils.disposeObject(this._hideBg); this._hideBg = null; ObjectUtils.disposeObject(this._hideTxt); this._hideTxt = null; ObjectUtils.disposeObject(this._hideGlassBtn); this._hideGlassBtn = null; ObjectUtils.disposeObject(this._hideSuitBtn); this._hideSuitBtn = null; ObjectUtils.disposeObject(this._hideWingBtn); this._hideWingBtn = null; ObjectUtils.disposeObject(this._nickName); this._nickName = null; this._character.dispose(); this._character = null; this._itemList.dispose(); this._itemList = null; this._bagItems = null; this._model = null; this._controller = null; if(parent) { parent.removeChild(this); } } } }
package org.un.cava.birdeye.ravis.graphLayout.visual.events { import flash.events.Event; public class VisualGraphEvent extends Event { public static const BEGIN_ANIMATION : String = "beginAnimation"; public static const END_ANIMATION : String = "endAnimation"; /** * Во время расчета или анимации раскладки был вызван метод resetAll */ public static const RESET_ALL : String = 'resetAll'; /** * Был вызван метод draw объекта IVisualGraph */ public static const DRAW : String = 'draw'; /** * Изменились параметры VisualGraph, путем установки св-ва data */ public static const VISUAL_GRAPH_DATA_CHANGED : String = 'visualGraphDataChanged'; /** * Изменились параметры layouterа путем установки св-ва data */ public static const LAYOUT_DATA_CHANGED : String = 'layoutDataChanged'; /** * Изменился один из параметров раскладки */ public static const LAYOUT_PARAM_CHANGED : String = 'layoutParamChanged'; /** * Изменилось св-во layouter */ public static const LAYOUT_CHANGED : String = 'layoutChanged'; /** * Координаты узлов компоновки уже просчитаны, осталось только отрисовать или запустить анимацию */ public static const LAYOUT_CALCULATED : String = 'layoutCalculated'; /** * Произошла перерисовка узлов и связей компоновщиком */ public static const LAYOUT_UPDATED : String = 'layoutUpdated'; /** * Произошло изменение масштаба */ public static const SCALED : String = "scaled"; /** * Начало перетаскивания какого-либо или нескольких узлов пользователем */ public static const BEGIN_NODES_DRAG : String = 'beginNodesDrag'; /** * Окончание перетаскивания какого-либо или нескольких узлов пользователем */ public static const END_NODES_DRAG : String = 'endNodesDrag'; /** * Координаты узлов были изменены */ public static const NODES_UPDATED : String = 'nodesUpdated'; /** * Какой-то из объектов node и/или edge были удалены */ public static const DELETE : String = 'delete'; /** * Запустился асинхронный процесс расчета раскладки */ public static const START_ASYNCHROUNOUS_LAYOUT_CALCULATION : String = 'startAsynchrounousLayoutCalculation'; /** * Асинхронный процесс расчета раскладки завершен */ public static const END_ASYNCHROUNOUS_LAYOUT_CALCULATION : String = 'endAsynchrounousLayoutCalculation'; public function VisualGraphEvent( type : String ) { super( type ); } override public function clone() : Event { return new VisualGraphEvent( type ); } } }
package { public dynamic class Error extends Object { public static const length:int = 1; public var message:Object; public var name:String; private var _errorID:int; public function Error(message:* = "", id:* = 0) { super(); this.message = message; this._errorID = id; this.name = ""; } public static function getErrorMessage(param1:int) : String{return null} public static function throwError(type:Class, index:uint, ... rest) : * { var i:* = 0; var f:* = function(match:*, pos:*, string:*):* { var arg_num:* = -1; switch(match.charAt(1)) { case "1": break; case "2": arg_num = 1; break; case "3": arg_num = 2; break; case "4": arg_num = 3; break; case "5": arg_num = 4; break; case "6": case 6: arg_num = 5; break; default: arg_num = 0; } if(arg_num > -1 && rest.length > arg_num) { return rest[arg_num]; } return ""; }; throw new type(Error.getErrorMessage(index).replace(new RegExp("%[0-9]","g"),f),index); } public function getStackTrace() : String{return null} public function get errorID() : int { return this._errorID; } } }
/*------------------------------------------------------------------------------ | | WinChatty | Copyright (C) 2009 Brian Luft | | 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 util { import flash.filesystem.*; import flash.utils.ByteArray; import flash.utils.Dictionary; import mx.collections.ArrayCollection; /** * Caches the body text of thread replies. */ public class PostCache { /** * Local file to save the cache to. */ private static const FILENAME : String = "WinChatty Cache"; /** * Maximum number of stories we will hold in the cache before culling the old ones. */ private static const MAX_STORIES : int = 20; /** * Contains all of the cached stories. The key is the story ID. */ private static var stories : Object = {}; /** * Load the cache from disk. */ /*public static function load() : void { var file : File = File.applicationStorageDirectory.resolvePath(FILENAME); var stream : FileStream = new FileStream(); try { stream.open(file, FileMode.READ); stories = stream.readObject(); stream.close(); } catch (error : Error) { // Use an empty cache. stories = null; } if (stories == null) stories = {}; else cull(); }*/ /** * Save the cache to disk. */ /*public static function save() : void { var file : File = File.applicationStorageDirectory.resolvePath(FILENAME); var stream : FileStream = new FileStream(); cull(); stream.open(file, FileMode.WRITE); stream.writeObject(stories); stream.close(); }*/ /** * Retrieve a post body from the cache. Throws an exception if the post is not in the cache. * @param storyID Story ID. * @param threadID Thread ID. * @param postID Post ID. * @return Post body text. */ public static function getPost(storyID : int, threadID : int, postID : int) : Object { var threads : Object = stories[storyID]; if (threads == null) return null; var posts : Object = threads[threadID]; if (posts == null) return null; var text : Object = posts[postID]; if (text == null) return null; return text; } /** * Add a thread of posts to the cache. * @param storyID Story ID. * @param threadID Thread ID. * @param posts Dictionary of posts (key = post ID, value = post body) */ public static function setThread(storyID : int, threadID : int, posts : Dictionary) : void { var threads : Object = stories[storyID]; if (threads == null) { threads = {}; stories[storyID] = threads; } threads[threadID] = posts; } /** * Removes old stories from the cache if needed. */ private static function cull() : void { var storyIDs : ArrayCollection = new ArrayCollection(); var i : int; var j : int; // Read the list of story IDs into an array. for (var key : Object in stories) storyIDs.addItem(key); // Sort the IDs numerically function swap(a : int, b : int) : void { var temp : int = storyIDs[a]; storyIDs[a] = storyIDs[b]; storyIDs[b] = temp; } for (i = 0; i < storyIDs.length; i++) for (j = 0; j < storyIDs.length - 1; j++) if (storyIDs[j] as int > storyIDs[j + 1] as int) swap(j, j + 1); if (storyIDs.length > MAX_STORIES) { for (i = 0; i < storyIDs.length - MAX_STORIES; i++) delete stories[storyIDs[i]]; } } /** * Get statistics on the cache size. * @return Object with keys "stories", "threads", "posts", and "bytes". */ public static function getStatistics() : Object { var o : Object = {stories: 0, threads: 0, posts: 0, bytes: 0}; for each (var threads : Object in stories) { o.stories++; for each (var posts : Object in threads) { o.threads++; for each (var post : Object in posts) o.posts++; } } var byteArray : ByteArray = new ByteArray(); byteArray.writeObject(stories); o.bytes = byteArray.length; return o; } /** * Clear the cache. */ public static function clearCache() : void { stories = {}; //save(); } } }
/* ----------------------------------------------------------------------------------------------------------------------------------------------------- / public class GameModule extends Module - 类功能 - / ----------------------------------------------------------------------------------------------------------------------------------------------------- */ package modules.game { import common.CommonModule; import hall.HallModule; import laya.display.Stage; import laya.utils.Browser; import modules.game.context.GameMainContext; import modules.game.majiangGame.context.MajiangGameContext; import modules.game.majiangGame.view.animation.HuAnimation; import rb.framework.mvc.GameContext; import rb.framework.mvc.Module; /*[COMPILER OPTIONS:ForcedCompile]*/ public class GameModule extends Module { // --- Vars ------------------------------------------------------------------------------------------------------------------------------------------------ // public var needResize:Boolean = true; /**是否暂停游戏消息队列*/ public static var isPauseGameQueue:Boolean = false; protected var _main:GameMainContext; public static var inGame:Boolean=false; /**是否是在收到了总的结算数据了*/ public static var isSettlement:Boolean = false; public function get main():GameMainContext { return _main; } protected var _majiangGameContext:MajiangGameContext; // --- Public Functions ------------------------------------------------------------------------------------------------------------------------------------ // public function GameModule() { super(); // if (_instance != null){ // throw (new SingletonError(this)); // }; // _instance = this; } // --- Protected Functions --------------------------------------------------------------------------------------------------------------------------------- // public function get gameContext():MajiangGameContext { return _majiangGameContext; } protected var _mainContext:GameContext; public override function startup():void{ if(_mainContext == null) { _mainContext = new GameContext("GameMainmain",this); _main=new GameMainContext("GameMain",this,_mainContext); _majiangGameContext = new MajiangGameContext("MajiangGame",this,_main); } this.switchState(this._mainContext); } public function stopGame(gotoHall:Boolean=true,needClear:Boolean=false):void { if(needClear) { _majiangGameContext.controller.clear(); } inGame=false; isSettlement = false; this.switchState(this._mainContext); if(gotoHall){ if(AppConfig.isNewHall){ QuickUtils.gotoHall() }else{ inHallResize(); HallModule.instance.gotoHall(); } } HuAnimation.instance.noticeHide(); } public function startGame():void { if(inGame == true) { return; } HallModule.instance.goEmpty(); inGame=true; CommonModule.instance.gotoCommonContext(); this.switchState(this.gameContext); inGameResize(); WX.onMenuShareTimeline(UserData.nickname+"-一乐西周麻将 【房间号:"+UserData.roomid+"】",UserData.roomid+"--"+UserData.uniqueCode); WX.onMenuShareAppMessage(UserData.nickname+"-一乐西周麻将 【房间号:"+UserData.roomid+"】","房主创建了西周麻将 【房间号:"+UserData.roomid+"】"+AppConfig.getRule(UserData.Rule[1]).desc+"局",UserData.roomid+"--"+UserData.uniqueCode); trace("startMajiangGame..........."); } protected function inGameResize(isFirst:Boolean=true):void { if(QuickUtils.sysem()!="windows"){ Laya.stage.screenMode = Stage.SCREEN_HORIZONTAL; } Laya.stage.size(1038,640);//1038,640 GameModule.instance.gameContext.view.gui.visible = false; if(isFirst == true)//第一次 { Laya.timer.once(200,this,onCheckInGameResize); } else { Laya.timer.frameOnce(1,this,onCheckInGameResize); } } protected function onCheckInGameResize():void { if(ModuleDef.CurGameModule.inGame == true) { var canvas:* = Browser.getElementById("layaCanvas"); if(canvas.width < canvas.height)//不正常了 { QuickUtils.showChScreenGuideView(); inGameResize(false); } else { QuickUtils.hideChScreenGuideView(); GameModule.instance.gameContext.view.gui.visible = true; } } else { QuickUtils.hideChScreenGuideView(); } } protected function inHallResize():void { if(QuickUtils.sysem()=="windows"){ }else if(QuickUtils.sysem()=="ipad"||QuickUtils.sysem()=="mac"){ Laya.stage.screenMode = Stage.SCREEN_VERTICAL;//SCREEN_VERTICAL //SCREEN_HORIZONTAL }else{ Laya.stage.screenMode = Stage.SCREEN_VERTICAL;//SCREEN_VERTICAL //SCREEN_HORIZONTAL } Laya.stage.size(640,1038); } // --- Internal&protected Functions -------------------------------------------------------------------------------------------------------------------------- // // --- Static Vars ----------------------------------------------------------------------------------------------------------------------------------------- // // static protected var _instance:GameModule; // --- Static Functions ------------------------------------------------------------------------------------------------------------------------------------ // public static function get instance():GameModule{ return ModuleDef.CurGameModule.instance; } } }
/** * @author Peter Hansen * @copyright p3337.de All rights reserved. */ package de.p3337.straightouttaspace.Objects.Players { import flash.display.Stage; import de.p3337.straightouttaspace.Objects.Board; import de.p3337.straightouttaspace.Objects.Players.AI.AttackStrategy; import de.p3337.straightouttaspace.Objects.Players.AI.SimpleAttackStrategy; import de.p3337.straightouttaspace.Objects.Spaceships.OpponentSpaceship; import de.p3337.straightouttaspace.Objects.Spaceships.Spaceship; import de.p3337.straightouttaspace.Objects.Spaceships.SpaceshipFactory; /** * The Opponent uses a certain "AttackStrategy" to build different number * and sizes of spaceships to attack the users spaceship. For now a simple * one was implemented. */ public class Opponent extends PlayerObject { private var _stage:Stage; private var _attackStrategy:AttackStrategy; public function Opponent(parent:Board, spaceshipFactory:SpaceshipFactory) { super(parent, spaceshipFactory); this.spaceshipVector = new Vector.<Spaceship>(); this._stage = parent.parent.main.stage; this._attackStrategy = new SimpleAttackStrategy(this, 7000); } /** * @inheritDoc */ override public function createSpaceships():void { this._attackStrategy.sendNewSpaceshipWave(); this._attackStrategy.attackTimer.start(); } /** * @inheritDoc */ override public function update():void { super.update(); // check if ship was destroyed and remove it or update the attack // strategy for this ship var x:uint = this._spaceshipVector.length; while (--x > -1) { var ship:OpponentSpaceship = this._spaceshipVector[x] as OpponentSpaceship; if(ship.toBeDestroyed) { ship = null; this._spaceshipVector.splice(x,1); } else { ship.update(); this._attackStrategy.update(ship); } } } public function get attackStrategy():AttackStrategy { return _attackStrategy; } public function get stage():Stage { return _stage; } /** * @inheritDoc */ override public function destroy():void { super.destroy(); this._attackStrategy.destroy(); this._attackStrategy = null; this._stage = null; } } }
package cmodule.decry { import avm2.intrinsics.memory.lf64; import avm2.intrinsics.memory.li32; import avm2.intrinsics.memory.li8; import avm2.intrinsics.memory.sf64; import avm2.intrinsics.memory.si32; import avm2.intrinsics.memory.sxi8; public final class FSM___find_arguments extends Machine { public static const intRegCount:int = 12; public static const NumberRegCount:int = 1; public var i10:int; public var i11:int; public var f0:Number; public var i0:int; public var i1:int; public var i2:int; public var i3:int; public var i4:int; public var i5:int; public var i6:int; public var i7:int; public var i8:int; public var i9:int; public function FSM___find_arguments() { super(); } public static function start() : void { var _loc1_:FSM___find_arguments = null; _loc1_ = new FSM___find_arguments(); FSM___find_arguments.gworker = _loc1_; } override public final function work() : void { switch(state) { case 0: mstate.esp = mstate.esp - 4; si32(mstate.ebp,mstate.esp); mstate.ebp = mstate.esp; mstate.esp = mstate.esp - 52; this.i0 = mstate.ebp + -48; this.i1 = li32(mstate.ebp + 12); si32(this.i1,mstate.ebp + -4); si32(this.i0,mstate.ebp + -8); this.i1 = 8; si32(this.i1,mstate.ebp + -52); this.i1 = 0; si32(this.i1,mstate.ebp + -48); si32(this.i1,mstate.ebp + -44); si32(this.i1,mstate.ebp + -40); si32(this.i1,mstate.ebp + -36); si32(this.i1,mstate.ebp + -32); si32(this.i1,mstate.ebp + -28); si32(this.i1,mstate.ebp + -24); si32(this.i1,mstate.ebp + -20); this.i2 = 1; this.i3 = li32(mstate.ebp + 8); this.i4 = li32(mstate.ebp + 16); continue loop0; case 1: this.i3 = mstate.eax; mstate.esp = mstate.esp + 8; si32(this.i3,this.i4); si32(this.i2,this.i3); this.i2 = li32(mstate.ebp + -8); if(this.i1 >= 1) { this.i3 = 1; this.i5 = 4; this.i6 = 8; while(true) { this.i2 = this.i2 + this.i5; this.i2 = li32(this.i2); if(this.i2 <= 11) { if(this.i2 <= 5) { if(this.i2 <= 2) { if(this.i2 != 0) { if(this.i2 != 1) { if(this.i2 == 2) { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else if(this.i2 != 3) { if(this.i2 != 4) { if(this.i2 == 5) { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else if(this.i2 <= 8) { if(this.i2 != 6) { if(this.i2 != 7) { if(this.i2 == 8) { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 8; si32(this.i8,mstate.ebp + -4); this.i8 = li32(this.i7); this.i7 = li32(this.i7 + 4); this.i2 = this.i2 + this.i6; si32(this.i8,this.i2); si32(this.i7,this.i2 + 4); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else if(this.i2 != 9) { if(this.i2 != 10) { if(this.i2 == 11) { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 8; si32(this.i8,mstate.ebp + -4); this.i8 = li32(this.i7); this.i7 = li32(this.i7 + 4); this.i2 = this.i2 + this.i6; si32(this.i8,this.i2); si32(this.i7,this.i2 + 4); } } else if(this.i2 <= 17) { if(this.i2 <= 14) { if(this.i2 != 12) { if(this.i2 != 13) { if(this.i2 == 14) { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else if(this.i2 != 15) { if(this.i2 != 16) { if(this.i2 == 17) { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 8; si32(this.i8,mstate.ebp + -4); this.i8 = li32(this.i7); this.i7 = li32(this.i7 + 4); this.i2 = this.i2 + this.i6; si32(this.i8,this.i2); si32(this.i7,this.i2 + 4); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 8; si32(this.i8,mstate.ebp + -4); this.i8 = li32(this.i7); this.i7 = li32(this.i7 + 4); this.i2 = this.i2 + this.i6; si32(this.i8,this.i2); si32(this.i7,this.i2 + 4); } } else if(this.i2 <= 20) { if(this.i2 != 18) { if(this.i2 != 19) { if(this.i2 == 20) { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else if(this.i2 <= 22) { if(this.i2 != 21) { if(this.i2 == 22) { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 8; si32(this.i8,mstate.ebp + -4); this.f0 = lf64(this.i7); this.i2 = this.i2 + this.i6; sf64(this.f0,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 8; si32(this.i8,mstate.ebp + -4); this.f0 = lf64(this.i7); this.i2 = this.i2 + this.i6; sf64(this.f0,this.i2); } } else if(this.i2 != 23) { if(this.i2 == 24) { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } } else { this.i2 = li32(this.i4); this.i7 = li32(mstate.ebp + -4); this.i8 = this.i7 + 4; si32(this.i8,mstate.ebp + -4); this.i7 = li32(this.i7); this.i2 = this.i2 + this.i6; si32(this.i7,this.i2); } this.i2 = li32(mstate.ebp + -8); this.i6 = this.i6 + 8; this.i5 = this.i5 + 4; this.i3 = this.i3 + 1; if(this.i3 <= this.i1) { continue; } break; } this.i1 = this.i2; } else { this.i1 = this.i2; } if(this.i2 != 0) { if(this.i0 != this.i1) { this.i0 = 0; mstate.esp = mstate.esp - 8; si32(this.i1,mstate.esp); si32(this.i0,mstate.esp + 4); state = 39; mstate.esp = mstate.esp - 4; FSM___find_arguments.start(); return; } break; } break; case 2: mstate.esp = mstate.esp + 12; continue loop13; case 3: mstate.esp = mstate.esp + 12; continue loop15; case 4: mstate.esp = mstate.esp + 12; continue loop16; case 5: mstate.esp = mstate.esp + 12; continue loop17; case 6: mstate.esp = mstate.esp + 12; continue loop19; case 7: mstate.esp = mstate.esp + 12; while(true) { this.i7 = 2; this.i8 = li32(mstate.ebp + -8); this.i9 = this.i3 << 2; this.i8 = this.i8 + this.i9; si32(this.i7,this.i8); this.i1 = this.i3 > this.i1?int(this.i3):int(this.i1); this.i3 = this.i6 + 1; continue loop18; } case 8: mstate.esp = mstate.esp + 12; while(true) { this.i3 = 2; this.i6 = li32(mstate.ebp + -8); this.i8 = this.i2 << 2; this.i6 = this.i6 + this.i8; si32(this.i3,this.i6); this.i1 = this.i2 > this.i1?int(this.i2):int(this.i1); this.i2 = this.i2 + 1; this.i3 = this.i7; continue loop18; } case 9: mstate.esp = mstate.esp + 12; continue loop22; case 10: mstate.esp = mstate.esp + 12; continue loop23; case 11: mstate.esp = mstate.esp + 12; this.i5 = li32(mstate.ebp + -8); this.i6 = this.i2 << 2; this.i7 = 13; this.i5 = this.i5 + this.i6; si32(this.i7,this.i5); this.i5 = this.i2 + 1; this.i2 = this.i5; continue loop14; case 12: mstate.esp = mstate.esp + 12; this.i5 = li32(mstate.ebp + -8); this.i6 = this.i2 << 2; this.i7 = 11; this.i5 = this.i5 + this.i6; si32(this.i7,this.i5); this.i5 = this.i2 + 1; this.i2 = this.i5; continue loop14; case 13: mstate.esp = mstate.esp + 12; this.i5 = li32(mstate.ebp + -8); this.i6 = this.i2 << 2; this.i5 = this.i5 + this.i6; this.i6 = 8; si32(this.i6,this.i5); this.i5 = this.i2 + 1; this.i2 = this.i5; continue loop14; case 14: mstate.esp = mstate.esp + 12; this.i1 = li32(mstate.ebp + -8); this.i6 = this.i2 << 2; this.i7 = 5; this.i1 = this.i1 + this.i6; si32(this.i7,this.i1); this.i2 = this.i2 + 1; this.i1 = this.i5; continue loop14; case 15: mstate.esp = mstate.esp + 12; continue loop24; case 16: mstate.esp = mstate.esp + 12; continue loop25; case 17: mstate.esp = mstate.esp + 12; continue loop26; case 18: mstate.esp = mstate.esp + 12; continue loop27; case 19: mstate.esp = mstate.esp + 12; continue loop28; case 20: mstate.esp = mstate.esp + 12; continue loop29; case 21: mstate.esp = mstate.esp + 12; continue loop30; case 22: mstate.esp = mstate.esp + 12; continue loop31; case 23: mstate.esp = mstate.esp + 12; continue loop32; case 24: mstate.esp = mstate.esp + 12; continue loop33; case 25: mstate.esp = mstate.esp + 12; continue loop34; case 26: mstate.esp = mstate.esp + 12; this.i5 = li32(mstate.ebp + -8); this.i6 = this.i2 << 2; this.i7 = 13; this.i5 = this.i5 + this.i6; si32(this.i7,this.i5); this.i5 = this.i2 + 1; this.i2 = this.i5; continue loop14; case 27: mstate.esp = mstate.esp + 12; this.i5 = li32(mstate.ebp + -8); this.i6 = this.i2 << 2; this.i7 = 11; this.i5 = this.i5 + this.i6; si32(this.i7,this.i5); this.i5 = this.i2 + 1; this.i2 = this.i5; continue loop14; case 28: mstate.esp = mstate.esp + 12; this.i5 = li32(mstate.ebp + -8); this.i6 = this.i2 << 2; this.i7 = 9; this.i5 = this.i5 + this.i6; si32(this.i7,this.i5); this.i5 = this.i2 + 1; this.i2 = this.i5; continue loop14; case 29: mstate.esp = mstate.esp + 12; this.i1 = li32(mstate.ebp + -8); this.i6 = this.i2 << 2; this.i7 = 6; this.i1 = this.i1 + this.i6; si32(this.i7,this.i1); this.i2 = this.i2 + 1; this.i1 = this.i5; continue loop14; case 30: mstate.esp = mstate.esp + 12; continue loop35; case 31: mstate.esp = mstate.esp + 12; continue loop36; case 32: mstate.esp = mstate.esp + 12; continue loop37; case 33: mstate.esp = mstate.esp + 12; continue loop38; case 34: mstate.esp = mstate.esp + 12; this.i5 = li32(mstate.ebp + -8); this.i6 = this.i2 << 2; this.i7 = 13; this.i5 = this.i5 + this.i6; si32(this.i7,this.i5); this.i2 = this.i2 + 1; continue loop14; case 35: mstate.esp = mstate.esp + 12; this.i5 = li32(mstate.ebp + -8); this.i6 = this.i2 << 2; this.i7 = 11; this.i5 = this.i5 + this.i6; si32(this.i7,this.i5); this.i2 = this.i2 + 1; continue loop14; case 36: mstate.esp = mstate.esp + 12; this.i5 = li32(mstate.ebp + -8); this.i6 = this.i2 << 2; this.i7 = 9; this.i5 = this.i5 + this.i6; si32(this.i7,this.i5); this.i2 = this.i2 + 1; continue loop14; case 37: mstate.esp = mstate.esp + 12; this.i5 = li32(mstate.ebp + -8); this.i6 = this.i2 << 2; this.i7 = 6; this.i5 = this.i5 + this.i6; si32(this.i7,this.i5); this.i2 = this.i2 + 1; continue loop14; case 38: mstate.esp = mstate.esp + 12; continue loop39; case 39: this.i0 = mstate.eax; mstate.esp = mstate.esp + 8; } mstate.esp = mstate.ebp; mstate.ebp = li32(mstate.esp); mstate.esp = mstate.esp + 4; mstate.esp = mstate.esp + 4; mstate.gworker = caller; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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 { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Graphics; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.MovieClip; import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageQuality; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.EventPhase; import flash.events.FocusEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.system.ApplicationDomain; import flash.text.Font; import flash.text.TextFormat; import flash.ui.Keyboard; import flash.utils.Dictionary; import flash.utils.Timer; import flash.utils.getQualifiedClassName; import mx.core.FlexSprite; import mx.core.IChildList; import mx.core.IFlexDisplayObject; import mx.core.IFlexModuleFactory; import mx.core.IInvalidating; import mx.core.IRawChildrenContainer; import mx.core.IUIComponent; import mx.core.RSLData; import mx.core.RSLItem; import mx.core.Singleton; import mx.core.mx_internal; import mx.events.DynamicEvent; import mx.events.FlexEvent; import mx.events.RSLEvent; import mx.events.Request; import mx.events.SandboxMouseEvent; import mx.preloaders.Preloader; import mx.utils.DensityUtil; import mx.utils.LoaderUtil; // NOTE: Minimize the non-Flash classes you import here. // Any dependencies of SystemManager have to load in frame 1, // before the preloader, or anything else, can be displayed. use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched when the application has finished initializing * * @eventType mx.events.FlexEvent.APPLICATION_COMPLETE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name="applicationComplete", type="mx.events.FlexEvent")] /** * Dispatched every 100 milliseconds when there has been no keyboard * or mouse activity for 1 second. * * @eventType mx.events.FlexEvent.IDLE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name="idle", type="mx.events.FlexEvent")] /** * Dispatched when the Stage is resized. * * @eventType flash.events.Event.RESIZE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name="resize", type="flash.events.Event")] /** * The SystemManager class manages an application window. * Every application that runs on the desktop or in a browser * has an area where the visuals of the application are * displayed. * It may be a window in the operating system * or an area within the browser. That area is an application window * and different from an instance of <code>mx.core.Application</code>, which * is the main, or top-level, window within an application. * * <p>Every application has a SystemManager. * The SystemManager sends an event if * the size of the application window changes (you cannot change it from * within the application, but only through interaction with the operating * system window or browser). It parents all displayable things within the * application like the main mx.core.Application instance and all popups, * tooltips, cursors, and so on. Any object parented by the SystemManager is * considered to be a top-level window, even tooltips and cursors.</p> * * <p>The SystemManager also switches focus between top-level windows if there * are more than one IFocusManagerContainer displayed and users are interacting * with components within the IFocusManagerContainers. </p> * * <p>All keyboard and mouse activity that is not expressly trapped is seen by * the SystemManager, making it a good place to monitor activity should you need * to do so.</p> * * <p>If an application is loaded into another application, a SystemManager * will still be created, but will not manage an application window, * depending on security and domain rules. * Instead, it will be the <code>content</code> of the <code>Loader</code> * that loaded it and simply serve as the parent of the sub-application</p> * * <p>The SystemManager maintains multiple lists of children, one each for tooltips, cursors, * popup windows. This is how it ensures that popup windows "float" above the main * application windows and that tooltips "float" above that and cursors above that. * If you simply examine the <code>numChildren</code> property or * call the <code>getChildAt()</code> method on the SystemManager, you are accessing * the main application window and any other windows that aren't popped up. To get the list * of all windows, including popups, tooltips and cursors, use * the <code>rawChildren</code> property.</p> * * <p>The SystemManager is the first display class created within an application. * It is responsible for creating an <code>mx.preloaders.Preloader</code> that displays and * <code>mx.preloaders.SparkDownloadProgressBar</code> while the application finishes loading, * then creates the <code>mx.core.Application</code> instance.</p> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class SystemManager extends MovieClip implements IChildList, IFlexDisplayObject, IFlexModuleFactory, ISystemManager { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @private * The number of milliseconds that must pass without any user activity * before SystemManager starts dispatching 'idle' events. */ private static const IDLE_THRESHOLD:Number = 1000; /** * @private * The number of milliseconds between each 'idle' event. */ private static const IDLE_INTERVAL:Number = 100; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- /** * @private * An array of SystemManager instances loaded as child app domains */ mx_internal static var allSystemManagers:Dictionary = new Dictionary(true); //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * <p>This is the starting point for all Flex applications. * This class is set to be the root class of a Flex SWF file. * Flash Player instantiates an instance of this class, * causing this constructor to be called.</p> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function SystemManager() { CONFIG::performanceInstrumentation { var perfUtil:mx.utils.PerfUtil = mx.utils.PerfUtil.getInstance(); perfUtil.startSampling("Application Startup", true /*absoluteTime*/); perfUtil.markTime("SystemManager c-tor"); } super(); // Loaded SWFs don't get a stage right away // and shouldn't override the main SWF's setting anyway. if (stage) { stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.quality = StageQuality.HIGH; } // If we don't have a stage then we are not top-level, // unless there are no other top-level managers, in which // case we got loaded by a non-Flex shell or are sandboxed. if (SystemManagerGlobals.topLevelSystemManagers.length > 0 && !stage) topLevel = false; if (!stage) isStageRoot = false; if (topLevel) SystemManagerGlobals.topLevelSystemManagers.push(this); // Make sure to stop the playhead on the current frame. stop(); // Listen for the last frame (param is 0-indexed) to be executed. //addFrameScript(totalFrames - 1, frameEndHandler); if (root && root.loaderInfo) root.loaderInfo.addEventListener(Event.INIT, initHandler); } /** * @private */ private function deferredNextFrame():void { if (currentFrame + 1 > totalFrames) return; if (currentFrame + 1 <= framesLoaded) { CONFIG::performanceInstrumentation { var perfUtil:mx.utils.PerfUtil = mx.utils.PerfUtil.getInstance(); perfUtil.markTime("SystemManager.nextFrame().start"); } nextFrame(); CONFIG::performanceInstrumentation { perfUtil.markTime("SystemManager.nextFrame().end"); } } else { // Next frame isn't baked yet, so we'll check back... nextFrameTimer = new Timer(100); nextFrameTimer.addEventListener(TimerEvent.TIMER, nextFrameTimerHandler); nextFrameTimer.start(); } } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Whether we are in the top-level list or not; * top-level means we are the highest level SystemManager * for this stage. */ mx_internal var topLevel:Boolean = true; /** * @private * * true if redipatching a resize event. */ private var isDispatchingResizeEvent:Boolean; /** * @private * Whether we are the stage root or not. * We are only the stage root if we were the root * of the first SWF that got loaded by the player. * Otherwise we could be top level but not stage root * if we are loaded by some other non-Flex shell * or are sandboxed. */ mx_internal var isStageRoot:Boolean = true; /** * @private * Whether we are the first SWF loaded into a bootstrap * and therefore, the topLevelRoot */ mx_internal var isBootstrapRoot:Boolean = false; /** * @private * If we're not top level, then we delegate many things * to the top level SystemManager. */ private var _topLevelSystemManager:ISystemManager; /** * @private * The childAdded/removed code */ mx_internal var childManager:ISystemManagerChildManager; /** * cached value of the stage. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ private var _stage:Stage; /** * Depth of this object in the containment hierarchy. * This number is used by the measurement and layout code. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var nestLevel:int = 0; /** * @private * A reference to the preloader. */ mx_internal var preloader:Preloader; /** * @private * The mouseCatcher is the 0th child of the SystemManager, * behind the application, which is child 1. * It is the same size as the stage and is filled with * transparent pixels; i.e., they've been drawn, but with alpha 0. * * Its purpose is to make every part of the stage * able to detect the mouse. * For example, a Button puts a mouseUp handler on the SystemManager * in order to capture mouseUp events that occur outside the Button. * But if the children of the SystemManager don't have "drawn-on" * pixels everywhere, the player won't dispatch the mouseUp. * We can't simply fill the SystemManager itself with * transparent pixels, because the player's pixel detection * logic doesn't look at pixels drawn into the root DisplayObject. * * Here is an example of what would happen without the mouseCatcher: * Run a fixed-size Application (e.g. width="600" height="600") * in the standalone player. Make the player window larger * to reveal part of the stage. Press a Button, drag off it * into the stage area, and release the mouse button. * Without the mouseCatcher, the Button wouldn't return to its "up" state. */ private var mouseCatcher:Sprite; /** * @private * The top level window. */ mx_internal var topLevelWindow:IUIComponent; /** * @private * Number of frames since the last mouse or key activity. */ mx_internal var idleCounter:int = 0; /** * @private * The Timer used to determine when to dispatch idle events. */ private var idleTimer:Timer; /** * @private * A timer used when it is necessary to wait before incrementing the frame */ private var nextFrameTimer:Timer = null; /** * @private * Track which frame was last processed */ private var lastFrame:int; /** * @private * A boolean as to whether we've seen COMPLETE event from preloader */ private var readyForKickOff:Boolean; /** * @private * * This variable exists only to provide a reference to this * app's resource bundles. This application is opting * into referencing its own resource bundles so the * ResourceManager does not need to do it. This * arrangement keeps the ResourceManager from pinning * the application in memory. * * If this is the main app, then this variable will be null. * If this is a sub-app then ResourceManagerImpl set * this variable to the apps resource bundles. This variable * is public so it is visible to ResourceManagerImpl but starts * with an underscore to hint that it is an implementation detail * and should not be relied on. */ public var _resourceBundles:Array; /** * @private * Array of RSLData objects that represent the list of RSLs this * module factory is loading. Each element of the Array is an * Array of RSLData. */ private var rslDataList:Array //-------------------------------------------------------------------------- // // Overridden properties: DisplayObject // //-------------------------------------------------------------------------- //---------------------------------- // height //---------------------------------- /** * @private */ private var _height:Number; /** * The height of this object. For the SystemManager * this should always be the width of the stage unless the application was loaded * into another application. If the application was not loaded * into another application, setting this value has no effect. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function get height():Number { return _height; } //---------------------------------- // stage //---------------------------------- /** * @private * get the main stage if we're loaded into another swf in the same sandbox */ override public function get stage():Stage { if (_stage) return _stage; var s:Stage = super.stage; if (s) { _stage = s; return s; } if (!topLevel && _topLevelSystemManager) { _stage = _topLevelSystemManager.stage; return _stage; } // Case for version skew, we are a top level system manager, but // a child of the top level root system manager and we have access // to the stage. if (!isStageRoot && topLevel) { var root:DisplayObject = getTopLevelRoot(); if (root) { _stage = root.stage; return _stage; } } return null; } //---------------------------------- // width //---------------------------------- /** * @private */ private var _width:Number; /** * The width of this object. For the SystemManager * this should always be the width of the stage unless the application was loaded * into another application. If the application was not loaded * into another application, setting this value will have no effect. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function get width():Number { return _width; } //-------------------------------------------------------------------------- // // Overridden properties: DisplayObjectContainer // //-------------------------------------------------------------------------- //---------------------------------- // numChildren //---------------------------------- /** * The number of non-floating windows. This is the main application window * plus any other windows added to the SystemManager that are not popups, * tooltips or cursors. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function get numChildren():int { return noTopMostIndex - applicationIndex; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // allowDomainsInNewRSLs //---------------------------------- /** * @private */ private var _allowDomainsInNewRSLs:Boolean = true; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Flex 4.5 */ public function get allowDomainsInNewRSLs():Boolean { return _allowDomainsInNewRSLs; } /** * @private */ public function set allowDomainsInNewRSLs(value:Boolean):void { _allowDomainsInNewRSLs = value; } //---------------------------------- // allowInsecureDomainsInNewRSLs //---------------------------------- /** * @private */ private var _allowInsecureDomainsInNewRSLs:Boolean = true; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Flex 4.5 */ public function get allowInsecureDomainsInNewRSLs():Boolean { return _allowInsecureDomainsInNewRSLs; } /** * @private */ public function set allowInsecureDomainsInNewRSLs(value:Boolean):void { _allowInsecureDomainsInNewRSLs = value; } //---------------------------------- // application //---------------------------------- /** * The application parented by this SystemManager. * SystemManagers create an instance of an Application * even if they are loaded into another Application. * Thus, this may not match mx.core.Application.application * if the SWF has been loaded into another application. * <p>Note that this property is not typed as mx.core.Application * because of load-time performance considerations * but can be coerced into an mx.core.Application.</p> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get application():IUIComponent { return IUIComponent(_document); } //---------------------------------- // applicationIndex //---------------------------------- /** * @private * Storage for the applicationIndex property. */ private var _applicationIndex:int = 1; /** * @private * The index of the main mx.core.Application window, which is * effectively its z-order. */ mx_internal function get applicationIndex():int { return _applicationIndex; } /** * @private */ mx_internal function set applicationIndex(value:int):void { _applicationIndex = value; } //---------------------------------- // cursorChildren //---------------------------------- /** * @private * Storage for the cursorChildren property. */ private var _cursorChildren:SystemChildrenList; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get cursorChildren():IChildList { if (!topLevel) return _topLevelSystemManager.cursorChildren; if (!_cursorChildren) { _cursorChildren = new SystemChildrenList(this, new QName(mx_internal, "toolTipIndex"), new QName(mx_internal, "cursorIndex")); } return _cursorChildren; } //---------------------------------- // cursorIndex //---------------------------------- /** * @private * Storage for the toolTipIndex property. */ private var _cursorIndex:int = 0; /** * @private * The index of the highest child that is a cursor. */ mx_internal function get cursorIndex():int { return _cursorIndex; } /** * @private */ mx_internal function set cursorIndex(value:int):void { var delta:int = value - _cursorIndex; _cursorIndex = value; } //---------------------------------- // densityScale //---------------------------------- /** * @private * Storage for the densityScale property */ private var _densityScale:Number = NaN; /** * The density scale factor of the application. * * When density scaling is enabled, Flex applies a scale factor based on * the application author density and the density of the current device * that Flex is running on. * * Returns 1.0 when there is no scaling. * * @see spark.components.Application#applicationDPI * @see mx.core.DensityUtil * * @private */ mx_internal function get densityScale():Number { if (isNaN(_densityScale)) { var applicationDPI:Number = info()["applicationDPI"]; var runtimeDPI:Number = DensityUtil.getRuntimeDPI(); _densityScale = DensityUtil.getDPIScale(applicationDPI, runtimeDPI); if (isNaN(_densityScale)) _densityScale = 1; } return _densityScale; } //---------------------------------- // document //---------------------------------- /** * @private * Storage for the document property. */ private var _document:Object; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get document():Object { return _document; } /** * @private */ public function set document(value:Object):void { _document = value; } //---------------------------------- // embeddedFontList //---------------------------------- /** * @private * Storage for the fontList property. */ private var _fontList:Object = null; /** * A table of embedded fonts in this application. The * object is a table indexed by the font name. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get embeddedFontList():Object { if (_fontList == null) { _fontList = {}; var o:Object = info()["fonts"]; var p:String; for (p in o) { _fontList[p] = o[p]; } // Top level systemManager may not be defined if SWF is loaded // as a background image in download progress bar. if (!topLevel && _topLevelSystemManager) { var fl:Object = _topLevelSystemManager.embeddedFontList; for (p in fl) { _fontList[p] = fl[p]; } } } return _fontList; } //---------------------------------- // explicitHeight //---------------------------------- /** * @private */ private var _explicitHeight:Number; /** * The explicit width of this object. For the SystemManager * this should always be NaN unless the application was loaded * into another application. If the application was not loaded * into another application, setting this value has no effect. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get explicitHeight():Number { return _explicitHeight; } /** * @private */ public function set explicitHeight(value:Number):void { _explicitHeight = value; } //---------------------------------- // explicitWidth //---------------------------------- /** * @private */ private var _explicitWidth:Number; /** * The explicit width of this object. For the SystemManager * this should always be NaN unless the application was loaded * into another application. If the application was not loaded * into another application, setting this value has no effect. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get explicitWidth():Number { return _explicitWidth; } /** * @private */ public function set explicitWidth(value:Number):void { _explicitWidth = value; } //---------------------------------- // focusPane //---------------------------------- /** * @private */ private var _focusPane:Sprite; /** * @copy mx.core.UIComponent#focusPane * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get focusPane():Sprite { return _focusPane; } /** * @private */ public function set focusPane(value:Sprite):void { if (value) { addChild(value); value.x = 0; value.y = 0; value.scrollRect = null; _focusPane = value; } else { removeChild(_focusPane); _focusPane = null; } } //---------------------------------- // isProxy //---------------------------------- /** * True if SystemManager is a proxy and not a root class */ public function get isProxy():Boolean { return false; } //---------------------------------- // measuredHeight //---------------------------------- /** * The measuredHeight is the explicit or measuredHeight of * the main mx.core.Application window * or the starting height of the SWF if the main window * has not yet been created or does not exist. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get measuredHeight():Number { return topLevelWindow ? topLevelWindow.getExplicitOrMeasuredHeight() : loaderInfo.height; } //---------------------------------- // measuredWidth //---------------------------------- /** * The measuredWidth is the explicit or measuredWidth of * the main mx.core.Application window, * or the starting width of the SWF if the main window * has not yet been created or does not exist. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get measuredWidth():Number { return topLevelWindow ? topLevelWindow.getExplicitOrMeasuredWidth() : loaderInfo.width; } //---------------------------------- // noTopMostIndex //---------------------------------- /** * @private * Storage for the noTopMostIndex property. */ private var _noTopMostIndex:int = 0; /** * @private * The index of the highest child that isn't a topmost/popup window */ mx_internal function get noTopMostIndex():int { return _noTopMostIndex; } /** * @private */ mx_internal function set noTopMostIndex(value:int):void { var delta:int = value - _noTopMostIndex; _noTopMostIndex = value; topMostIndex += delta; } //---------------------------------- // $numChildren //---------------------------------- /** * @private * This property allows access to the Player's native implementation * of the numChildren property, which can be useful since components * can override numChildren and thereby hide the native implementation. * Note that this "base property" is final and cannot be overridden, * so you can count on it to reflect what is happening at the player level. */ mx_internal final function get $numChildren():int { return super.numChildren; } //---------------------------------- // numModalWindows //---------------------------------- /** * @private * Storage for the numModalWindows property. */ private var _numModalWindows:int = 0; /** * The number of modal windows. Modal windows don't allow * clicking in another windows which would normally * activate the FocusManager in that window. The PopUpManager * modifies this count as it creates and destroys modal windows. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get numModalWindows():int { return _numModalWindows; } /** * @private */ public function set numModalWindows(value:int):void { _numModalWindows = value; } //---------------------------------- // preloadedRSLs //---------------------------------- /** * @inheritDoc * */ public function get preloadedRSLs():Dictionary { // Overridden by compiler generate code. return null; } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 4.5 */ public function addPreloadedRSL(loaderInfo:LoaderInfo, rsl:Vector.<RSLData>):void { preloadedRSLs[loaderInfo] = rsl; if (hasEventListener(RSLEvent.RSL_ADD_PRELOADED)) { var rslEvent:RSLEvent = new RSLEvent(RSLEvent.RSL_ADD_PRELOADED); rslEvent.loaderInfo = loaderInfo; dispatchEvent(rslEvent); } } //---------------------------------- // preloaderBackgroundAlpha //---------------------------------- /** * The background alpha used by the child of the preloader. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get preloaderBackgroundAlpha():Number { return info()["backgroundAlpha"]; } //---------------------------------- // preloaderBackgroundColor //---------------------------------- /** * The background color used by the child of the preloader. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get preloaderBackgroundColor():uint { var value:* = info()["backgroundColor"]; if (value == undefined) return 0xFFFFFFFF; else return value; } //---------------------------------- // preloaderBackgroundImage //---------------------------------- /** * The background color used by the child of the preloader. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get preloaderBackgroundImage():Object { return info()["backgroundImage"]; } //---------------------------------- // preloaderBackgroundSize //---------------------------------- /** * The background size used by the child of the preloader. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get preloaderBackgroundSize():String { return info()["backgroundSize"]; } //---------------------------------- // popUpChildren //---------------------------------- /** * @private * Storage for the popUpChildren property. */ private var _popUpChildren:SystemChildrenList; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get popUpChildren():IChildList { if (!topLevel) return _topLevelSystemManager.popUpChildren; if (!_popUpChildren) { _popUpChildren = new SystemChildrenList(this, new QName(mx_internal, "noTopMostIndex"), new QName(mx_internal, "topMostIndex")); } return _popUpChildren; } //---------------------------------- // rawChildren //---------------------------------- /** * @private * Storage for the rawChildren property. */ private var _rawChildren:SystemRawChildrenList; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get rawChildren():IChildList { //if (!topLevel) // return _topLevelSystemManager.rawChildren; if (!_rawChildren) _rawChildren = new SystemRawChildrenList(this); return _rawChildren; } //-------------------------------------------------------------------------- // screen //-------------------------------------------------------------------------- /** * @private * Storage for the screen property. */ mx_internal var _screen:Rectangle; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get screen():Rectangle { if (!_screen) Stage_resizeHandler(); if (!isStageRoot) { Stage_resizeHandler(); } return _screen; } //---------------------------------- // toolTipChildren //---------------------------------- /** * @private * Storage for the toolTipChildren property. */ private var _toolTipChildren:SystemChildrenList; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get toolTipChildren():IChildList { if (!topLevel) return _topLevelSystemManager.toolTipChildren; if (!_toolTipChildren) { _toolTipChildren = new SystemChildrenList(this, new QName(mx_internal, "topMostIndex"), new QName(mx_internal, "toolTipIndex")); } return _toolTipChildren; } //---------------------------------- // toolTipIndex //---------------------------------- /** * @private * Storage for the toolTipIndex property. */ private var _toolTipIndex:int = 0; /** * @private * The index of the highest child that is a tooltip */ mx_internal function get toolTipIndex():int { return _toolTipIndex; } /** * @private */ mx_internal function set toolTipIndex(value:int):void { var delta:int = value - _toolTipIndex; _toolTipIndex = value; cursorIndex += delta; } //---------------------------------- // topLevelSystemManager //---------------------------------- /** * Returns the SystemManager responsible for the application window. This will be * the same SystemManager unless this application has been loaded into another * application. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get topLevelSystemManager():ISystemManager { if (topLevel) return this; return _topLevelSystemManager; } //---------------------------------- // topMostIndex //---------------------------------- /** * @private * Storage for the topMostIndex property. */ private var _topMostIndex:int = 0; /** * @private * The index of the highest child that is a topmost/popup window */ mx_internal function get topMostIndex():int { return _topMostIndex; } mx_internal function set topMostIndex(value:int):void { var delta:int = value - _topMostIndex; _topMostIndex = value; toolTipIndex += delta; } //-------------------------------------------------------------------------- // // Overridden methods: EventDispatcher // //-------------------------------------------------------------------------- /** * @private * allows marshal implementation to add events * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal final function $addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { super.addEventListener(type, listener, useCapture, priority, useWeakReference); } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get childAllowsParent():Boolean { try { return loaderInfo.childAllowsParent; } catch (error:Error) { //Error #2099: The loading object is not sufficiently loaded to provide this information. } return false; // assume the worst } /** * @copy mx.core.ISWFBridgeProvider#parentAllowsChild * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get parentAllowsChild():Boolean { try { return loaderInfo.parentAllowsChild; } catch (error:Error) { //Error #2099: The loading object is not sufficiently loaded to provide this information. } return false; // assume the worst } /** * @private * Only create idle events if someone is listening. */ override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { if (type == MouseEvent.MOUSE_MOVE || type == MouseEvent.MOUSE_UP || type == MouseEvent.MOUSE_DOWN || type == Event.ACTIVATE || type == Event.DEACTIVATE) { // also listen to stage if allowed try { if (stage) { // Use weak listener because we don't always know when we // no longer need this listener stage.addEventListener(type, stageEventHandler, false, 0, true); } } catch (error:SecurityError) { } } if (hasEventListener("addEventListener")) { var request:DynamicEvent = new DynamicEvent("addEventListener", false, true); request.eventType = type; request.listener = listener; request.useCapture = useCapture; request.priority = priority; request.useWeakReference = useWeakReference; if (!dispatchEvent(request)) return; } if (type == SandboxMouseEvent.MOUSE_UP_SOMEWHERE) { // If someone wants this event, also listen for mouseLeave. // Use weak listener because we don't always know when we // no longer need this listener try { if (stage) { stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler, false, 0, true); } else { super.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler, false, 0, true); } } catch (error:SecurityError) { super.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler, false, 0, true); } } // These two events will dispatched to applications in sandboxes. if (type == FlexEvent.RENDER || type == FlexEvent.ENTER_FRAME) { if (type == FlexEvent.RENDER) type = Event.RENDER; else type = Event.ENTER_FRAME; try { if (stage) stage.addEventListener(type, listener, useCapture, priority, useWeakReference); else super.addEventListener(type, listener, useCapture, priority, useWeakReference); } catch (error:SecurityError) { super.addEventListener(type, listener, useCapture, priority, useWeakReference); } if (stage && type == Event.RENDER) stage.invalidate(); return; } // When the first listener registers for 'idle' events, // create a Timer that will fire every IDLE_INTERVAL. if (type == FlexEvent.IDLE && !idleTimer) { idleTimer = new Timer(IDLE_INTERVAL); idleTimer.addEventListener(TimerEvent.TIMER, idleTimer_timerHandler); idleTimer.start(); // Make sure we get all activity // in case someone calls stopPropagation(). addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler, true); } super.addEventListener(type, listener, useCapture, priority, useWeakReference); } /** * @private */ mx_internal final function $removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { super.removeEventListener(type, listener, useCapture); } /** * @private */ override public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { if (hasEventListener("removeEventListener")) { var request:DynamicEvent = new DynamicEvent("removeEventListener", false, true); request.eventType = type; request.listener = listener; request.useCapture = useCapture; if (!dispatchEvent(request)) return; } // These two events will dispatched to applications in sandboxes. if (type == FlexEvent.RENDER || type == FlexEvent.ENTER_FRAME) { if (type == FlexEvent.RENDER) type = Event.RENDER; else type = Event.ENTER_FRAME; try { if (stage) stage.removeEventListener(type, listener, useCapture); } catch (error:SecurityError) { } // Remove both listeners in case the system manager was added // or removed from the stage after the listener was added. super.removeEventListener(type, listener, useCapture); return; } // When the last listener unregisters for 'idle' events, // stop and release the Timer. if (type == FlexEvent.IDLE) { super.removeEventListener(type, listener, useCapture); if (!hasEventListener(FlexEvent.IDLE) && idleTimer) { idleTimer.stop(); idleTimer = null; removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } } else { super.removeEventListener(type, listener, useCapture); } if (type == MouseEvent.MOUSE_MOVE || type == MouseEvent.MOUSE_UP || type == MouseEvent.MOUSE_DOWN || type == Event.ACTIVATE || type == Event.DEACTIVATE) { if (!hasEventListener(type)) { // also listen to stage if allowed try { if (stage) { stage.removeEventListener(type, stageEventHandler, false); } } catch (error:SecurityError) { } } } if (type == SandboxMouseEvent.MOUSE_UP_SOMEWHERE) { if (!hasEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE)) { // nobody wants this event any more for now try { if (stage) { stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler); } } catch (error:SecurityError) { } // Remove both listeners in case the system manager was added // or removed from the stage after the listener was added. super.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler); } } } //-------------------------------------------------------------------------- // // Overridden methods: DisplayObjectContainer // //-------------------------------------------------------------------------- /** * @private */ override public function addChild(child:DisplayObject):DisplayObject { var addIndex:int = numChildren; if (child.parent == this) addIndex--; return addChildAt(child, addIndex); } /** * @private */ override public function addChildAt(child:DisplayObject, index:int):DisplayObject { // Adjust the partition indexes before the // "added" event is dispatched. noTopMostIndex = noTopMostIndex + 1; var oldParent:DisplayObjectContainer = child.parent; if (oldParent) oldParent.removeChild(child); return rawChildren_addChildAt(child, applicationIndex + index); } /** * @private * * Used by SystemManagerProxy to add a mouse catcher as a child. */ mx_internal final function $addChildAt(child:DisplayObject, index:int):DisplayObject { return super.addChildAt(child, index); } /** * @private * * Companion to $addChildAt. */ mx_internal final function $removeChildAt(index:int):DisplayObject { return super.removeChildAt(index); } /** * @private */ override public function removeChild(child:DisplayObject):DisplayObject { // Adjust the partition indexes // before the "removed" event is dispatched. noTopMostIndex = noTopMostIndex - 1; return rawChildren_removeChild(child); } /** * @private */ override public function removeChildAt(index:int):DisplayObject { // Adjust the partition indexes // before the "removed" event is dispatched. noTopMostIndex = noTopMostIndex - 1; return rawChildren_removeChildAt(applicationIndex + index); } /** * @private */ override public function getChildAt(index:int):DisplayObject { return super.getChildAt(applicationIndex + index) } /** * @private */ override public function getChildByName(name:String):DisplayObject { return super.getChildByName(name); } /** * @private */ override public function getChildIndex(child:DisplayObject):int { return super.getChildIndex(child) - applicationIndex; } /** * @private */ override public function setChildIndex(child:DisplayObject, newIndex:int):void { super.setChildIndex(child, applicationIndex + newIndex) } /** * @private */ override public function getObjectsUnderPoint(point:Point):Array { var children:Array = []; // Get all the children that aren't tooltips and cursors. var n:int = topMostIndex; for (var i:int = 0; i < n; i++) { var child:DisplayObject = super.getChildAt(i); if (child is DisplayObjectContainer) { var temp:Array = DisplayObjectContainer(child).getObjectsUnderPoint(point); if (temp) children = children.concat(temp); } } return children; } /** * @private */ override public function contains(child:DisplayObject):Boolean { if (super.contains(child)) { if (child.parent == this) { var childIndex:int = super.getChildIndex(child); if (childIndex < noTopMostIndex) return true; } else { for (var i:int = 0; i < noTopMostIndex; i++) { var myChild:DisplayObject = super.getChildAt(i); if (myChild is IRawChildrenContainer) { if (IRawChildrenContainer(myChild).rawChildren.contains(child)) return true; } if (myChild is DisplayObjectContainer) { if (DisplayObjectContainer(myChild).contains(child)) return true; } } } } return false; } //-------------------------------------------------------------------------- // // Methods: IFlexModuleFactory // //-------------------------------------------------------------------------- /** * @private * This method is overridden in the autogenerated subclass. * It is part of TLF's ISWFContext interface. * Although this class does not declare that it implements this interface, * the autogenerated subclass does. */ public function callInContext(fn:Function, thisArg:Object, argArray:Array, returns:Boolean = true):* { return undefined; } /** * A factory method that requests an instance of a * definition known to the module. * * You can provide an optional set of parameters to let building * factories change what they create based on the * input. Passing null indicates that the default definition * is created, if possible. * * This method is overridden in the autogenerated subclass. * * @param params An optional list of arguments. You can pass * any number of arguments, which are then stored in an Array * called <code>parameters</code>. * * @return An instance of the module, or <code>null</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function create(... params):Object { var mainClassName:String = info()["mainClassName"]; if (mainClassName == null) { var url:String = loaderInfo.loaderURL; var dot:int = url.lastIndexOf("."); var slash:int = url.lastIndexOf("/"); mainClassName = url.substring(slash + 1, dot); } var mainClass:Class = Class(getDefinitionByName(mainClassName)); return mainClass ? new mainClass() : null; } /** * @private */ public function info():Object { return {}; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * Creates an instance of the preloader, adds it as a child, and runs it. * This is needed by Flash Builder. Do not modify this function. */ mx_internal function initialize():void { var runtimeDPIProviderClass:Class = info()["runtimeDPIProvider"] as Class; if (runtimeDPIProviderClass) Singleton.registerClass("mx.core::RuntimeDPIProvider", runtimeDPIProviderClass); if (isStageRoot) { // TODO: Finalize scaling behavior Stage_resizeHandler(); // _width = stage.stageWidth; // _height = stage.stageHeight; } else { _width = loaderInfo.width; _height = loaderInfo.height; } // Create an instance of the preloader and add it to the stage preloader = new Preloader(); // Listen for preloader events // preloader notifes when it is ok to go to frame2 preloader.addEventListener(FlexEvent.PRELOADER_DOC_FRAME_READY, preloader_preloaderDocFrameReadyHandler); // wait for a complete event. This gives the preloader // a chance to load resource modules before // everything really gets kicked off preloader.addEventListener(Event.COMPLETE, preloader_completeHandler); // when the app is fully backed remove the preloader and show the app preloader.addEventListener(FlexEvent.PRELOADER_DONE, preloader_preloaderDoneHandler); preloader.addEventListener(RSLEvent.RSL_COMPLETE, preloader_rslCompleteHandler); // Add the preloader as a child. Use backing variable because when loaded // we redirect public API to parent systemmanager if (!_popUpChildren) { _popUpChildren = new SystemChildrenList( this, new QName(mx_internal, "noTopMostIndex"), new QName(mx_internal, "topMostIndex")); } _popUpChildren.addChild(preloader); var rsls:Array = info()["rsls"]; var cdRsls:Array = info()["cdRsls"]; var usePreloader:Boolean = true; if (info()["usePreloader"] != undefined) usePreloader = info()["usePreloader"]; var preloaderDisplayClass:Class = info()["preloader"] as Class; // Put cross-domain RSL information in the RSL list. var rslItemList:Array = []; var n:int; var i:int; if (cdRsls && cdRsls.length > 0) { if (isTopLevel()) rslDataList = cdRsls; else rslDataList = LoaderUtil.processRequiredRSLs(this, cdRsls); var normalizedURL:String = LoaderUtil.normalizeURL(this.loaderInfo); var crossDomainRSLItem:Class = Class(getDefinitionByName("mx.core::CrossDomainRSLItem")); n = rslDataList.length; for (i = 0; i < n; i++) { var rslWithFailovers:Array = rslDataList[i]; // If crossDomainRSLItem is null, then this is a compiler error. It should not be null. var cdNode:Object = new crossDomainRSLItem(rslWithFailovers, normalizedURL, this); rslItemList.push(cdNode); } } // Append RSL information in the RSL list. if (rsls != null && rsls.length > 0) { if (rslDataList == null) rslDataList = []; if (normalizedURL == null) normalizedURL = LoaderUtil.normalizeURL(this.loaderInfo); n = rsls.length; for (i = 0; i < n; i++) { var node:RSLItem = new RSLItem(rsls[i].url, normalizedURL, this); rslItemList.push(node); rslDataList.push([new RSLData(rsls[i].url, null, null, null, false, false, "current")]); } } // They can also specify a comma-separated list of URLs // for resource modules to be preloaded during frame 1. var resourceModuleURLList:String = loaderInfo.parameters["resourceModuleURLs"]; var resourceModuleURLs:Array = resourceModuleURLList ? resourceModuleURLList.split(",") : null; var domain:ApplicationDomain = !topLevel && parent is Loader ? Loader(parent).contentLoaderInfo.applicationDomain : info()["currentDomain"] as ApplicationDomain; // Initialize the preloader. preloader.initialize( usePreloader, preloaderDisplayClass, preloaderBackgroundColor, preloaderBackgroundAlpha, preloaderBackgroundImage, preloaderBackgroundSize, isStageRoot ? stage.stageWidth : loaderInfo.width, isStageRoot ? stage.stageHeight : loaderInfo.height, null, null, rslItemList, resourceModuleURLs, domain); } //-------------------------------------------------------------------------- // // Methods: Support for rawChildren access // //-------------------------------------------------------------------------- /** * @private */ mx_internal function rawChildren_addChild(child:DisplayObject):DisplayObject { childManager.addingChild(child); super.addChild(child); childManager.childAdded(child); // calls child.createChildren() return child; } /** * @private */ mx_internal function rawChildren_addChildAt(child:DisplayObject, index:int):DisplayObject { // preloader goes through here before childManager is set up if (childManager) childManager.addingChild(child); super.addChildAt(child, index); if (childManager) childManager.childAdded(child); // calls child.createChildren() return child; } /** * @private */ mx_internal function rawChildren_removeChild(child:DisplayObject):DisplayObject { childManager.removingChild(child); super.removeChild(child); childManager.childRemoved(child); return child; } /** * @private */ mx_internal function rawChildren_removeChildAt(index:int):DisplayObject { var child:DisplayObject = super.getChildAt(index); childManager.removingChild(child); super.removeChildAt(index); childManager.childRemoved(child); return child; } /** * @private */ mx_internal function rawChildren_getChildAt(index:int):DisplayObject { return super.getChildAt(index); } /** * @private */ mx_internal function rawChildren_getChildByName(name:String):DisplayObject { return super.getChildByName(name); } /** * @private */ mx_internal function rawChildren_getChildIndex(child:DisplayObject):int { return super.getChildIndex(child); } /** * @private */ mx_internal function rawChildren_setChildIndex(child:DisplayObject, newIndex:int):void { super.setChildIndex(child, newIndex); } /** * @private */ mx_internal function rawChildren_getObjectsUnderPoint(pt:Point):Array { return super.getObjectsUnderPoint(pt); } /** * @private */ mx_internal function rawChildren_contains(child:DisplayObject):Boolean { return super.contains(child); } //-------------------------------------------------------------------------- // // Methods: Security // //-------------------------------------------------------------------------- /** * Calls Security.allowDomain() for the SWF associated with this SystemManager * plus all the SWFs assocatiated with RSLs preloaded by this SystemManager. * */ public function allowDomain(... domains):void { // Overridden by compiler generated code. } /** * Calls Security.allowInsecureDomain() for the SWF associated with this SystemManager * plus all the SWFs assocatiated with RSLs preloaded by this SystemManager. * */ public function allowInsecureDomain(... domains):void { // Overridden by compiler generated code. } //-------------------------------------------------------------------------- // // Methods: Measurement and Layout // //-------------------------------------------------------------------------- /** * A convenience method for determining whether to use the * explicit or measured width. * * @return A Number that is the <code>explicitWidth</code> if defined, * or the <code>measuredWidth</code> property if not. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function getExplicitOrMeasuredWidth():Number { return !isNaN(explicitWidth) ? explicitWidth : measuredWidth; } /** * A convenience method for determining whether to use the * explicit or measured height. * * @return A Number that is the <code>explicitHeight</code> if defined, * or the <code>measuredHeight</code> property if not. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function getExplicitOrMeasuredHeight():Number { return !isNaN(explicitHeight) ? explicitHeight : measuredHeight; } /** * Calling the <code>move()</code> method * has no effect as it is directly mapped * to the application window or the loader. * * @param x The new x coordinate. * * @param y The new y coordinate. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function move(x:Number, y:Number):void { } /** * Calling the <code>setActualSize()</code> method * has no effect if it is directly mapped * to the application window and if it is the top-level window. * Otherwise attempts to resize itself, clipping children if needed. * * @param newWidth The new width. * * @param newHeight The new height. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function setActualSize(newWidth:Number, newHeight:Number):void { if (isStageRoot) return; // mouseCatcher is a mask if not stage root // sometimes it is not in sync so we always // sync it up if (mouseCatcher) { mouseCatcher.width = newWidth; mouseCatcher.height = newHeight; } if (_width != newWidth || _height != newHeight) { _width = newWidth; _height = newHeight; dispatchEvent(new Event(Event.RESIZE)); } } //-------------------------------------------------------------------------- // // Methods: Other // //-------------------------------------------------------------------------- /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function getDefinitionByName(name:String):Object { var domain:ApplicationDomain = !topLevel && parent is Loader ? Loader(parent).contentLoaderInfo.applicationDomain : info()["currentDomain"] as ApplicationDomain; //trace("SysMgr.getDefinitionByName domain",domain,"currentDomain",info()["currentDomain"]); var definition:Object; if (domain.hasDefinition(name)) { definition = domain.getDefinition(name); //trace("SysMgr.getDefinitionByName got definition",definition,"name",name); } return definition; } /** * Returns the root DisplayObject of the SWF that contains the code * for the given object. * * @param object Any Object. * * @return The root DisplayObject * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function getSWFRoot(object:Object):DisplayObject { var className:String = getQualifiedClassName(object); for (var p:* in allSystemManagers) { var sm:ISystemManager = p as ISystemManager; var domain:ApplicationDomain = sm.loaderInfo.applicationDomain; try { var cls:Class = Class(domain.getDefinition(className)); if (object is cls) return sm as DisplayObject; } catch(e:Error) { } } return null; } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function isTopLevel():Boolean { return topLevel; } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function isTopLevelRoot():Boolean { return isStageRoot || isBootstrapRoot; } /** * Determines if the given DisplayObject is the * top-level window. * * @param object The DisplayObject to test. * * @return <code>true</code> if the given DisplayObject is the * top-level window. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function isTopLevelWindow(object:DisplayObject):Boolean { return object is IUIComponent && IUIComponent(object) == topLevelWindow; } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function isFontFaceEmbedded(textFormat:TextFormat):Boolean { var fontName:String = textFormat.font; var bold:Boolean = textFormat.bold; var italic:Boolean = textFormat.italic; var fontList:Array = Font.enumerateFonts(); var n:int = fontList.length; for (var i:int = 0; i < n; i++) { var font:Font = Font(fontList[i]); if (font.fontName == fontName) { var style:String = "regular"; if (bold && italic) style = "boldItalic"; else if (bold) style = "bold"; else if (italic) style = "italic"; if (font.fontStyle == style) return true; } } if (!fontName || !embeddedFontList || !embeddedFontList[fontName]) { return false; } var info:Object = embeddedFontList[fontName]; return !((bold && !info.bold) || (italic && !info.italic) || (!bold && !italic && !info.regular)); } /** * @private * Makes the mouseCatcher the same size as the stage, * filling it with transparent pixels. */ private function resizeMouseCatcher():void { if (mouseCatcher) { try { var g:Graphics = mouseCatcher.graphics; var s:Rectangle = screen; g.clear(); g.beginFill(0x000000, 0); g.drawRect(0, 0, s.width, s.height); g.endFill(); } catch (e:SecurityError) { // trace("resizeMouseCatcher: ignoring security error " + e); } } } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function initHandler(event:Event):void { CONFIG::performanceInstrumentation { var perfUtil:mx.utils.PerfUtil = mx.utils.PerfUtil.getInstance(); perfUtil.markTime("SystemManager.initHandler().start"); } // we can still be the top level root if we can access our // parent and get a positive response to the query or // or there is not a listener for the new application event // that SWFLoader always adds. if (!isStageRoot) { if (root.loaderInfo.parentAllowsChild) { try { if (!parent.dispatchEvent(new Event("mx.managers.SystemManager.isBootstrapRoot", false, true)) || // use string literal to avoid link dependency on SWFBridgeEvent.BRIDGE_NEW_APPLICATION !root.loaderInfo.sharedEvents.hasEventListener("bridgeNewApplication")) isBootstrapRoot = true; } catch (e:Error) { } } } allSystemManagers[this] = this.loaderInfo.url; root.loaderInfo.removeEventListener(Event.INIT, initHandler); if (!SystemManagerGlobals.info) SystemManagerGlobals.info = info(); if (!SystemManagerGlobals.parameters) SystemManagerGlobals.parameters = loaderInfo.parameters; var docFrame:int = (totalFrames == 1)? 0 : 1; addEventListener(Event.ENTER_FRAME, docFrameListener); /* addFrameScript(docFrame, docFrameHandler); for (var f:int = docFrame + 1; f < totalFrames; ++f) { addFrameScript(f, extraFrameHandler); } */ initialize(); CONFIG::performanceInstrumentation { perfUtil.markTime("SystemManager.initHandler().end"); } } private function docFrameListener(event:Event):void { if (currentFrame == 2) { removeEventListener(Event.ENTER_FRAME, docFrameListener); if (totalFrames > 2) addEventListener(Event.ENTER_FRAME, extraFrameListener); docFrameHandler(); } } private function extraFrameListener(event:Event):void { if (lastFrame == currentFrame) return; lastFrame = currentFrame; if (currentFrame + 1 > totalFrames) removeEventListener(Event.ENTER_FRAME, extraFrameListener); extraFrameHandler(); } /** * @private * Once the swf has been fully downloaded, * advance the playhead to the next frame. * This will cause the framescript to run, which runs frameEndHandler(). */ private function preloader_preloaderDocFrameReadyHandler(event:Event):void { // Advance the next frame preloader.removeEventListener(FlexEvent.PRELOADER_DOC_FRAME_READY, preloader_preloaderDocFrameReadyHandler); deferredNextFrame(); } /** * @private * Remove the preloader and add the application as a child. */ private function preloader_preloaderDoneHandler(event:Event):void { var app:IUIComponent = topLevelWindow; // Once the preloader dispatches the PRELOADER_DONE event, remove the preloader // and add the application as the child preloader.removeEventListener(FlexEvent.PRELOADER_DONE, preloader_preloaderDoneHandler); preloader.removeEventListener(RSLEvent.RSL_COMPLETE, preloader_rslCompleteHandler); _popUpChildren.removeChild(preloader); preloader = null; // Add the mouseCatcher as child 0. mouseCatcher = new FlexSprite(); mouseCatcher.name = "mouseCatcher"; // Must use addChildAt because a creationComplete handler can create a // dialog and insert it at 0. noTopMostIndex = noTopMostIndex + 1; super.addChildAt(mouseCatcher, 0); resizeMouseCatcher(); if (!topLevel) { mouseCatcher.visible = false; mask = mouseCatcher; } // Add the application as child 1. noTopMostIndex = noTopMostIndex + 1; super.addChildAt(DisplayObject(app), 1); CONFIG::performanceInstrumentation { var perfUtil:mx.utils.PerfUtil = mx.utils.PerfUtil.getInstance(); perfUtil.markTime("APPLICATION_COMPLETE"); perfUtil.finishSampling("Application Startup"); } // Dispatch the applicationComplete event from the Application // and then agaom from the SystemManager // (so that loading apps know we're done). app.dispatchEvent(new FlexEvent(FlexEvent.APPLICATION_COMPLETE)); dispatchEvent(new FlexEvent(FlexEvent.APPLICATION_COMPLETE)); } /** * @private * The preloader has completed loading an RSL. */ private function preloader_rslCompleteHandler(event:RSLEvent):void { if (!event.isResourceModule && event.loaderInfo) { var rsl:Vector.<RSLData> = Vector.<RSLData>(rslDataList[event.rslIndex]); var moduleFactory:IFlexModuleFactory = this; if (rsl && rsl[0].moduleFactory) moduleFactory = rsl[0].moduleFactory; if (moduleFactory == this) preloadedRSLs[event.loaderInfo] = rsl; else moduleFactory.addPreloadedRSL(event.loaderInfo, rsl); } } /** * @private * This is attached as the framescript at the end of frame 2. * When this function is called, we know that the application * class has been defined and read in by the Player. */ mx_internal function docFrameHandler(event:Event = null):void { if (readyForKickOff) kickOff(); } /** * @private * kick off if we're ready */ mx_internal function preloader_completeHandler(event:Event):void { preloader.removeEventListener(Event.COMPLETE, preloader_completeHandler); readyForKickOff = true; if (currentFrame >= 2) kickOff(); } /** * @private * kick off */ mx_internal function kickOff():void { // already been here if (document) return; CONFIG::performanceInstrumentation { var perfUtil:mx.utils.PerfUtil = mx.utils.PerfUtil.getInstance(); perfUtil.markTime("SystemManager.kickOff().start"); } if (!isTopLevel()) SystemManagerGlobals.topLevelSystemManagers[0]. // dispatch a FocusEvent so we can pass ourselves along dispatchEvent(new FocusEvent(FlexEvent.NEW_CHILD_APPLICATION, false, false, this)); // Generated code will bring in EmbeddedFontRegistry Singleton.registerClass("mx.core::IEmbeddedFontRegistry", Class(getDefinitionByName("mx.core::EmbeddedFontRegistry"))); Singleton.registerClass("mx.styles::IStyleManager", Class(getDefinitionByName("mx.styles::StyleManagerImpl"))); Singleton.registerClass("mx.styles::IStyleManager2", Class(getDefinitionByName("mx.styles::StyleManagerImpl"))); // Register other singleton classes. // Note: getDefinitionByName() will return null // if the class can't be found. Singleton.registerClass("mx.managers::IBrowserManager", Class(getDefinitionByName("mx.managers::BrowserManagerImpl"))); Singleton.registerClass("mx.managers::ICursorManager", Class(getDefinitionByName("mx.managers::CursorManagerImpl"))); Singleton.registerClass("mx.managers::IHistoryManager", Class(getDefinitionByName("mx.managers::HistoryManagerImpl"))); Singleton.registerClass("mx.managers::ILayoutManager", Class(getDefinitionByName("mx.managers::LayoutManager"))); Singleton.registerClass("mx.managers::IPopUpManager", Class(getDefinitionByName("mx.managers::PopUpManagerImpl"))); Singleton.registerClass("mx.managers::IToolTipManager2", Class(getDefinitionByName("mx.managers::ToolTipManagerImpl"))); var dragManagerClass:Class = null; // Make this call to create a new instance of the DragManager singleton. // Try to link in the NativeDragManager first. This will allow the // application to receive NativeDragEvents that originate from the // desktop. If it can't be found, then we're // not in AIR, and it can't be linked in, so we should just work off of // the regular Flex DragManager. var dmInfo:Object = info()["useNativeDragManager"]; var useNative:Boolean = dmInfo == null ? true : String(dmInfo) == "true"; if (useNative) dragManagerClass = Class(getDefinitionByName("mx.managers::NativeDragManagerImpl")); if (dragManagerClass == null) dragManagerClass = Class(getDefinitionByName("mx.managers::DragManagerImpl")); Singleton.registerClass("mx.managers::IDragManager", dragManagerClass); Singleton.registerClass("mx.core::ITextFieldFactory", Class(getDefinitionByName("mx.core::TextFieldFactory"))); var mixinList:Array = info()["mixins"]; if (mixinList && mixinList.length > 0) { var n:int = mixinList.length; for (var i:int = 0; i < n; ++i) { CONFIG::performanceInstrumentation { var token:int = perfUtil.markStart(); } // trace("initializing mixin " + mixinList[i]); var c:Class = Class(getDefinitionByName(mixinList[i])); c["init"](this); CONFIG::performanceInstrumentation { perfUtil.markEnd(mixinList[i], token); } } } c = Singleton.getClass("mx.managers::IActiveWindowManager"); if (c) { registerImplementation("mx.managers::IActiveWindowManager", new c(this)); } // depends on having IActiveWindowManager installed first c = Singleton.getClass("mx.managers::IMarshalSystemManager"); if (c) { registerImplementation("mx.managers::IMarshalSystemManager", new c(this)); } CONFIG::performanceInstrumentation { // Finish here, since initializeTopLevelWidnow is instrumented separately??? perfUtil.markTime("SystemManager.kickOff().end"); } initializeTopLevelWindow(null); deferredNextFrame(); } /** * @private * The Flash Player dispatches KeyboardEvents with cancelable=false. * We'd like to be able to use the preventDefault() method on some * KeyBoard events to record the fact that they've been handled. * This method stops propagation of the original event and redispatches * the new one from the original event's target. * * We're only handling a small subset of keyboard events, to * avoid unnecessary copying. Most of events in the subset are * handled by both Scroller and by Spark classes like TextArea or * or List that include a Scroller in their skin. */ private function keyDownHandler(e:KeyboardEvent):void { if (!e.cancelable) { switch (e.keyCode) { case Keyboard.UP: case Keyboard.DOWN: case Keyboard.PAGE_UP: case Keyboard.PAGE_DOWN: case Keyboard.HOME: case Keyboard.END: case Keyboard.LEFT: case Keyboard.RIGHT: case Keyboard.ENTER: { e.stopImmediatePropagation(); var cancelableEvent:KeyboardEvent = new KeyboardEvent(e.type, e.bubbles, true, e.charCode, e.keyCode, e.keyLocation, e.ctrlKey, e.altKey, e.shiftKey) e.target.dispatchEvent(cancelableEvent); } } } } /** * @private * Similar to keyDownHandler above. We want to re-dispatch * mouse events that are cancellable. Currently we are only doing * this for a few mouse events and not all of them (MOUSE_WHEEL and * MOUSE_DOWN). */ private function mouseEventHandler(e:MouseEvent):void { if (!e.cancelable && e.eventPhase != EventPhase.BUBBLING_PHASE) { e.stopImmediatePropagation(); var cancelableEvent:MouseEvent = null; if ("clickCount" in e) { // AIR MouseEvent. We need to use a constructor so we can // pass in clickCount because it is a read-only property. var mouseEventClass:Class = MouseEvent; cancelableEvent = new mouseEventClass(e.type, e.bubbles, true, e.localX, e.localY, e.relatedObject, e.ctrlKey, e.altKey, e.shiftKey, e.buttonDown, e.delta, e["commandKey"], e["controlKey"], e["clickCount"]); } else { cancelableEvent = new MouseEvent(e.type, e.bubbles, true, e.localX, e.localY, e.relatedObject, e.ctrlKey, e.altKey, e.shiftKey, e.buttonDown, e.delta); } e.target.dispatchEvent(cancelableEvent); } } private function extraFrameHandler(event:Event = null):void { var frameList:Object = info()["frames"]; if (frameList && frameList[currentLabel]) { var c:Class = Class(getDefinitionByName(frameList[currentLabel])); c["frame"](this); } deferredNextFrame(); } /** * @private * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ private function nextFrameTimerHandler(event:TimerEvent):void { if (currentFrame + 1 <= framesLoaded) { nextFrame(); nextFrameTimer.removeEventListener(TimerEvent.TIMER, nextFrameTimerHandler); // stop the timer nextFrameTimer.reset(); } } /** * @private * Instantiates an instance of the top level window * and adds it as a child of the SystemManager. */ private function initializeTopLevelWindow(event:Event):void { // This listener is intended to run before any other KeyboardEvent listeners // so that it can redispatch a cancelable=true copy of the event. if (getSandboxRoot() == this) { addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler, true, 1000); addEventListener(MouseEvent.MOUSE_WHEEL, mouseEventHandler, true, 1000); addEventListener(MouseEvent.MOUSE_DOWN, mouseEventHandler, true, 1000); } if (isTopLevelRoot() && stage) { stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler, false, 1000); stage.addEventListener(MouseEvent.MOUSE_WHEEL, mouseEventHandler, false, 1000); stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseEventHandler, false, 1000); } // Parent may be null if in another sandbox and don't have // access to our parent. Add a check for this case. if (!parent && parentAllowsChild) return; if (!topLevel) { // We are not top-level and don't have a parent. This can happen // when the application has already been unloaded by the time // we get to this point. if (!parent) return; var obj:DisplayObjectContainer = parent.parent; // if there is no grandparent at this point, we might have been removed and // are about to be killed so just bail. Other code that runs after // this point expects us to be grandparented. Another scenario // is that someone loaded us but not into a parented loader, but that // is not allowed. if (!obj) return; while (obj) { if (obj is IUIComponent) { var sm:ISystemManager = IUIComponent(obj).systemManager; if (sm && !sm.isTopLevel()) sm = sm.topLevelSystemManager; _topLevelSystemManager = sm; break; } obj = obj.parent; } } if (isTopLevelRoot() && stage) stage.addEventListener(Event.RESIZE, Stage_resizeHandler, false, 0, true); else if (topLevel && stage) { // listen to resizes on the sandbox root var sandboxRoot:DisplayObject = getSandboxRoot(); if (sandboxRoot != this) sandboxRoot.addEventListener(Event.RESIZE, Stage_resizeHandler, false, 0, true); } var w:Number; var h:Number; if (isStageRoot && stage) { // stageWidth/stageHeight may have changed between initialize() and now, // so refresh our _width and _height here. // TODO: finalize scaling behavior Stage_resizeHandler(); //_width = stage.stageWidth; //_height = stage.stageHeight; // Detect and account for special case where our stage in some // contexts has not actually been initialized fully, as is the // case with IE if the window is fully obscured upon loading. if (_width == 0 && _height == 0 && loaderInfo.width != _width && loaderInfo.height != _height) { _width = loaderInfo.width; _height = loaderInfo.height; } w = _width; h = _height; } else { w = loaderInfo.width; h = loaderInfo.height; } childManager.initializeTopLevelWindow(w, h); } /** * listen for creationComplete" on the application * if you want to perform any logic * when the application has finished initializing itself. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ private function appCreationCompleteHandler(event:FlexEvent):void { invalidateParentSizeAndDisplayList(); } /** * Attempts to notify the parent SWFLoader that the * Application's size has changed. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function invalidateParentSizeAndDisplayList():void { if (!topLevel && parent) { var obj:DisplayObjectContainer = parent.parent; while (obj) { if (obj is IInvalidating) { IInvalidating(obj).invalidateSize(); IInvalidating(obj).invalidateDisplayList(); return; } obj = obj.parent; } } // re-dispatch from here so MarshallPlan mixins can see it dispatchEvent(new Event("invalidateParentSizeAndDisplayList")); } /** * @private * Keep track of the size and position of the stage. */ private function Stage_resizeHandler(event:Event = null):void { if (isDispatchingResizeEvent) return; var w:Number = 0; var h:Number = 0; var m:Number; var n:Number; try { m = loaderInfo.width; n = loaderInfo.height; } catch (error:Error) { // Error #2099: The loading object is not sufficiently loaded to provide this information. // We get this error because an old Event.RESIZE listener with a weak reference // is being called but the SWF has been unloaded. if (!_screen) _screen = new Rectangle(); return; } var align:String = StageAlign.TOP_LEFT; // If we don't have access to the stage, then use the size of // the sandbox root and align to StageAlign.TOP_LEFT. try { if (stage) { w = stage.stageWidth; h = stage.stageHeight; align = stage.align; } } catch (error:SecurityError) { if (hasEventListener("getScreen")) { dispatchEvent(new Event("getScreen")); if (_screen) { w = _screen.width; h = _screen.height; } } } var x:Number = (m - w) / 2; var y:Number = (n - h) / 2; if (align == StageAlign.TOP) { y = 0; } else if (align == StageAlign.BOTTOM) { y = n - h; } else if (align == StageAlign.LEFT) { x = 0; } else if (align == StageAlign.RIGHT) { x = m - w; } else if (align == StageAlign.TOP_LEFT || align == "LT") // player bug 125020 { y = 0; x = 0; } else if (align == StageAlign.TOP_RIGHT) { y = 0; x = m - w; } else if (align == StageAlign.BOTTOM_LEFT) { y = n - h; x = 0; } else if (align == StageAlign.BOTTOM_RIGHT) { y = n - h; x = m - w; } if (!_screen) _screen = new Rectangle(); _screen.x = x; _screen.y = y; _screen.width = w; _screen.height = h; if (isStageRoot) { var scale:Number = densityScale; root.scaleX = root.scaleY = scale; _width = stage.stageWidth / scale; _height = stage.stageHeight / scale; // Update the screen _screen.x /= scale; _screen.y /= scale; _screen.width /= scale; _screen.height /= scale; } if (event) { resizeMouseCatcher(); isDispatchingResizeEvent = true; dispatchEvent(event); isDispatchingResizeEvent = false; } } /** * @private * * Get the index of an object in a given child list. * * @return index of f in childList, -1 if f is not in childList. */ private static function getChildListIndex(childList:IChildList, f:Object):int { var index:int = -1; try { index = childList.getChildIndex(DisplayObject(f)); } catch (e:ArgumentError) { // index has been preset to -1 so just continue. } return index; } /** * @private * Track mouse moves in order to determine idle */ private function mouseMoveHandler(event:MouseEvent):void { // Reset the idle counter. idleCounter = 0; } /** * @private * Track mouse moves in order to determine idle. */ private function mouseUpHandler(event:MouseEvent):void { // Reset the idle counter. idleCounter = 0; } /** * @private * Called every IDLE_INTERVAL after the first listener * registers for 'idle' events. * After IDLE_THRESHOLD goes by without any user activity, * we dispatch an 'idle' event. */ private function idleTimer_timerHandler(event:TimerEvent):void { idleCounter++; if (idleCounter * IDLE_INTERVAL > IDLE_THRESHOLD) dispatchEvent(new FlexEvent(FlexEvent.IDLE)); } // fake out mouseX/mouseY mx_internal var _mouseX:*; mx_internal var _mouseY:*; /** * @private */ override public function get mouseX():Number { if (_mouseX === undefined) return super.mouseX; return _mouseX; } /** * @private */ override public function get mouseY():Number { if (_mouseY === undefined) return super.mouseY; return _mouseY; } private function getTopLevelSystemManager(parent:DisplayObject):ISystemManager { var localRoot:DisplayObjectContainer = DisplayObjectContainer(parent.root); var sm:ISystemManager; // If the parent isn't rooted yet, // Or the root is the stage (which is the case in a second AIR window) // use the global system manager instance. if ((!localRoot || localRoot is Stage) && parent is IUIComponent) localRoot = DisplayObjectContainer(IUIComponent(parent).systemManager); if (localRoot is ISystemManager) { sm = ISystemManager(localRoot); if (!sm.isTopLevel()) sm = sm.topLevelSystemManager; } return sm; } /** * Override parent property to handle the case where the parent is in * a differnt sandbox. If the parent is in the same sandbox it is returned. * If the parent is in a diffent sandbox, then null is returned. * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function get parent():DisplayObjectContainer { try { return super.parent; } catch (e:SecurityError) { // trace("parent: ignoring security error"); } return null; } /** * Go up the parent chain to get the top level system manager. * * Returns <code>null</code> if not on the display list or we don't have * access to the top-level system manager. * * @return The root system manager. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function getTopLevelRoot():DisplayObject { // work our say up the parent chain to the root. This way we // don't have to rely on this object being added to the stage. try { var sm:ISystemManager = this; if (sm.topLevelSystemManager) sm = sm.topLevelSystemManager; var parent:DisplayObject = DisplayObject(sm).parent; var lastParent:DisplayObject = DisplayObject(sm); while (parent) { if (parent is Stage) return lastParent; lastParent = parent; parent = parent.parent; } } catch (error:SecurityError) { } return null; } /** * Go up the parent chain to get the top level system manager in this * SecurityDomain. * * @return The root system manager in this SecurityDomain. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function getSandboxRoot():DisplayObject { // work our say up the parent chain to the root. This way we // don't have to rely on this object being added to the stage. var sm:ISystemManager = this; try { if (sm.topLevelSystemManager) sm = sm.topLevelSystemManager; var parent:DisplayObject = DisplayObject(sm).parent; if (parent is Stage) return DisplayObject(sm); // test to see if parent is a Bootstrap if (parent && !parent.dispatchEvent(new Event("mx.managers.SystemManager.isBootstrapRoot", false, true))) return this; var lastParent:DisplayObject = this; while (parent) { if (parent is Stage) return lastParent; // test to see if parent is a Bootstrap if (!parent.dispatchEvent(new Event("mx.managers.SystemManager.isBootstrapRoot", false, true))) return lastParent; // Test if the childAllowsParent so we know there is mutual trust between // the sandbox root and this sm. // The parentAllowsChild is taken care of by the player because it returns null // for the parent if we do not have access. if (parent is Loader) { var loader:Loader = Loader(parent); var loaderInfo:LoaderInfo = loader.contentLoaderInfo; if (!loaderInfo.childAllowsParent) return loaderInfo.content; } // If an object is listening for system manager request we assume it is a sandbox // root. If not, don't assign lastParent to this parent because it may be a // non-Flex application. We only want Flex apps to be returned as sandbox roots. // use constant to avoid link dependency on InterManagerRequest.SYSTEM_MANAGER_REQUEST if (parent.hasEventListener("systemManagerRequest" )) lastParent = parent; parent = parent.parent; } } catch (error:Error) { // Either we don't have security access to a parent or // the swf is unloaded and loaderInfo.childAllowsParent is throwing Error #2099. } return lastParent != null ? lastParent : DisplayObject(sm); } /** * @private * A map of fully-qualified interface names, * such as "mx.managers::IPopUpManager", * to instances, */ private var implMap:Object = {}; /** * @private * Adds an interface-name-to-implementation-class mapping to the registry, * if a class hasn't already been registered for the specified interface. * The class must implement a getInstance() method which returns * its singleton instance. */ public function registerImplementation(interfaceName:String, impl:Object):void { var c:Object = implMap[interfaceName]; if (!c) implMap[interfaceName] = impl; } /** * @private * Returns the singleton instance of the implementation class * that was registered for the specified interface, * by looking up the class in the registry * and calling its getInstance() method. * * This method should not be called at static initialization time, * because the factory class may not have called registerClass() yet. */ public function getImplementation(interfaceName:String):Object { var c:Object = implMap[interfaceName]; return c; } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function getVisibleApplicationRect(bounds:Rectangle = null, skipToSandboxRoot:Boolean = false):Rectangle { if (hasEventListener("getVisibleApplicationRect")) { var request:Request = new Request("getVisibleApplicationRect", false, true); request.value = { bounds: bounds, skipToSandboxRoot: skipToSandboxRoot }; if (!dispatchEvent(request)) return Rectangle(request.value); } if (skipToSandboxRoot && !topLevel) return topLevelSystemManager.getVisibleApplicationRect(bounds, skipToSandboxRoot); if (!bounds) { bounds = getBounds(DisplayObject(this)); var sandboxRoot:DisplayObject = getSandboxRoot(); var s:Rectangle = screen.clone(); s.topLeft = sandboxRoot.localToGlobal(screen.topLeft); s.bottomRight = sandboxRoot.localToGlobal(screen.bottomRight); var pt:Point = new Point(Math.max(0, bounds.x), Math.max(0, bounds.y)); pt = localToGlobal(pt); bounds.x = pt.x; bounds.y = pt.y; bounds.width = s.width; bounds.height = s.height; // No backwards compatibility // See https://bugs.adobe.com/jira/browse/SDK-31377 // FlexVersion.compatibilityVersion >= FlexVersion.VERSION_4_6 // softKeyboardRect is in global coordinates. // Keyboard size may change size while active. Listen for // SoftKeyboardEvents on the stage and call // getVisibleApplicationRect() to get updated visible bounds. var softKeyboardRect:Rectangle = stage.softKeyboardRect; bounds.height = bounds.height - softKeyboardRect.height; } if (!topLevel) { var obj:DisplayObjectContainer = parent.parent; if ("getVisibleApplicationRect" in obj) { var visibleRect:Rectangle = obj["getVisibleApplicationRect"](true); bounds = bounds.intersection(visibleRect); } } return bounds; } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function deployMouseShields(deploy:Boolean):void { if (hasEventListener("deployMouseShields")) { var dynamicEvent:DynamicEvent = new DynamicEvent("deployMouseShields"); dynamicEvent.deploy = deploy; dispatchEvent(dynamicEvent); } } /** * @private * dispatch certain stage events from sandbox root */ private function stageEventHandler(event:Event):void { if (event.target is Stage && mouseCatcher) { // need to fix up the coordinate space before re-dispatching the mouse event // to put it in the same coordinate space as the mouseCatcher since the // mouseCatcher may be scaled while outside of the stage, we are not if (event is MouseEvent) { var mouseEvent:MouseEvent = MouseEvent(event); var stagePoint:Point = new Point(mouseEvent.stageX, mouseEvent.stageY); var mouesCatcherLocalPoint:Point = mouseCatcher.globalToLocal(stagePoint); mouseEvent.localX = mouesCatcherLocalPoint.x; mouseEvent.localY = mouesCatcherLocalPoint.y; } // dispatch them from mouseCatcher so capture phase listeners on // systemManager will work mouseCatcher.dispatchEvent(event); } } /** * @private * convert MOUSE_LEAVE to MOUSE_UP_SOMEWHERE */ private function mouseLeaveHandler(event:Event):void { dispatchEvent(new SandboxMouseEvent(SandboxMouseEvent.MOUSE_UP_SOMEWHERE)); } } }
package store.forge.wishBead { import bagAndInfo.cell.BagCell; import baglocked.BaglockedManager; import com.pickgliss.events.FrameEvent; import com.pickgliss.ui.AlertManager; import com.pickgliss.ui.ComponentFactory; import com.pickgliss.ui.LayerManager; import com.pickgliss.ui.controls.BaseButton; import com.pickgliss.ui.controls.SelectedCheckButton; import com.pickgliss.ui.controls.SimpleBitmapButton; import com.pickgliss.ui.controls.alert.BaseAlerFrame; import com.pickgliss.ui.core.Disposeable; import com.pickgliss.ui.image.ScaleFrameImage; import com.pickgliss.ui.text.FilterFrameText; import com.pickgliss.utils.ObjectUtils; import ddt.data.BagInfo; import ddt.data.goods.InventoryItemInfo; import ddt.events.BagEvent; import ddt.events.CellEvent; import ddt.events.CrazyTankSocketEvent; import ddt.manager.LanguageMgr; import ddt.manager.MessageTipManager; import ddt.manager.PlayerManager; import ddt.manager.SocketManager; import ddt.manager.SoundManager; import ddt.utils.PositionUtils; import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; import flash.utils.Dictionary; import store.HelpFrame; import store.HelpPrompt; import store.StoreBagBgWHPoint; public class WishBeadMainView extends Sprite implements Disposeable { private var _bg:Bitmap; private var _bagList:WishBeadBagListView; private var _proBagList:WishBeadBagListView; private var _leftDrapSprite:WishBeadLeftDragSprite; private var _rightDrapSprite:WishBeadRightDragSprite; private var _itemCell:WishBeadItemCell; private var _equipCell:WishBeadEquipCell; private var _continuousBtn:SelectedCheckButton; private var _doBtn:SimpleBitmapButton; private var _tip:WishTips; private var _helpBtn:BaseButton; private var _isDispose:Boolean = false; private var _equipBagInfo:BagInfo; public var msg_txt:ScaleFrameImage; private var bagBg:ScaleFrameImage; private var _bgShape:Shape; private var _bgPoint:StoreBagBgWHPoint; public function WishBeadMainView() { super(); this.mouseEnabled = false; this.initView(); this.initEvent(); this.createAcceptDragSprite(); } private function initView() : void { this.bagBg = ComponentFactory.Instance.creatComponentByStylename("store.bagBG"); this._bgPoint = ComponentFactory.Instance.creatCustomObject("store.bagBGWHPoint"); this._bgShape = new Shape(); this.bagBg.addChild(this._bgShape); this.bagBg.x = 368; this.bagBg.y = 15; addChild(this.bagBg); this._bgShape.graphics.clear(); this._bgShape.graphics.beginFill(int(this._bgPoint.pointArr[0])); this._bgShape.graphics.drawRect(Number(this._bgPoint.pointArr[1]),Number(this._bgPoint.pointArr[2]),Number(this._bgPoint.pointArr[3]),Number(this._bgPoint.pointArr[4])); this._bgShape.graphics.drawRect(Number(this._bgPoint.pointArr[5]),Number(this._bgPoint.pointArr[6]),Number(this._bgPoint.pointArr[7]),Number(this._bgPoint.pointArr[8])); this._bg = ComponentFactory.Instance.creatBitmap("asset.wishBead.leftViewBg"); this.msg_txt = ComponentFactory.Instance.creatComponentByStylename("store.bagMsg1"); this.msg_txt.x = 452; this.msg_txt.y = 17; addChild(this.msg_txt); this.msg_txt.setFrame(1); this._bagList = new WishBeadBagListView(BagInfo.EQUIPBAG,7,21); PositionUtils.setPos(this._bagList,"wishBeadMainView.bagListPos"); this.refreshBagList(); this._proBagList = new WishBeadBagListView(BagInfo.PROPBAG,7,21); PositionUtils.setPos(this._proBagList,"wishBeadMainView.proBagListPos"); this._proBagList.setData(WishBeadManager.instance.getWishBeadItemData()); this._equipCell = new WishBeadEquipCell(0,null,true,new Bitmap(new BitmapData(60,60,true,0)),false); this._equipCell.BGVisible = false; PositionUtils.setPos(this._equipCell,"wishBeadMainView.equipCellPos"); this._equipCell.setContentSize(68,68); this._equipCell.PicPos = new Point(-3,-5); this._itemCell = new WishBeadItemCell(0,null,true,new Bitmap(new BitmapData(60,60,true,0)),false); PositionUtils.setPos(this._itemCell,"wishBeadMainView.itemCellPos"); this._itemCell.BGVisible = false; this._continuousBtn = ComponentFactory.Instance.creatComponentByStylename("wishBeadMainView.continuousBtn"); this._doBtn = ComponentFactory.Instance.creatComponentByStylename("wishBeadMainView.doBtn"); this._doBtn.enable = false; var _loc1_:FilterFrameText = ComponentFactory.Instance.creatComponentByStylename("wishBeadMainView.tipTxt"); _loc1_.text = LanguageMgr.GetTranslation("wishBeadMainView.tipTxt"); this._helpBtn = ComponentFactory.Instance.creatComponentByStylename("wishBead.NodeBtn"); addChild(this._bg); addChild(this._bagList); addChild(this._proBagList); addChild(this._equipCell); addChild(this._itemCell); addChild(_loc1_); addChild(this._continuousBtn); addChild(this._doBtn); addChild(this._helpBtn); this._tip = ComponentFactory.Instance.creat("store.forge.wishBead.WishTip"); LayerManager.Instance.getLayerByType(LayerManager.STAGE_TOP_LAYER).addChild(this._tip); } public function hide() : void { this.visible = false; } private function refreshBagList() : void { this._equipBagInfo = WishBeadManager.instance.getCanWishBeadData(); this._bagList.setData(this._equipBagInfo); } private function initEvent() : void { this._bagList.addEventListener(CellEvent.ITEM_CLICK,this.cellClickHandler,false,0,true); this._bagList.addEventListener(CellEvent.DOUBLE_CLICK,this.__cellDoubleClick,false,0,true); this._equipCell.addEventListener(Event.CHANGE,this.itemEquipChangeHandler,false,0,true); this._proBagList.addEventListener(CellEvent.ITEM_CLICK,this.cellClickHandler,false,0,true); this._proBagList.addEventListener(CellEvent.DOUBLE_CLICK,this.__cellDoubleClick,false,0,true); this._itemCell.addEventListener(Event.CHANGE,this.itemEquipChangeHandler,false,0,true); this._doBtn.addEventListener(MouseEvent.CLICK,this.doHandler,false,0,true); SocketManager.Instance.addEventListener(CrazyTankSocketEvent.WISHBEADEQUIP,this.__showTip); PlayerManager.Instance.Self.PropBag.addEventListener(BagEvent.UPDATE,this.propInfoChangeHandler); PlayerManager.Instance.Self.Bag.addEventListener(BagEvent.UPDATE,this.bagInfoChangeHandler); this._helpBtn.addEventListener(MouseEvent.CLICK,this.__clickHelp,false,0,true); } private function bagInfoChangeHandler(param1:BagEvent) : void { var _loc3_:InventoryItemInfo = null; var _loc4_:InventoryItemInfo = null; var _loc6_:BagInfo = null; var _loc2_:Dictionary = param1.changedSlots; for each(_loc4_ in _loc2_) { _loc3_ = _loc4_; } if(_loc3_ && !PlayerManager.Instance.Self.Bag.items[_loc3_.Place]) { if(this._equipCell.info && (this._equipCell.info as InventoryItemInfo).Place == _loc3_.Place) { this._equipCell.info = null; } else { this.refreshBagList(); } } else { _loc6_ = WishBeadManager.instance.getCanWishBeadData(); if(_loc6_.items.length != this._equipBagInfo.items.length) { this._equipBagInfo = _loc6_; this._bagList.setData(this._equipBagInfo); } } var _loc5_:InventoryItemInfo = this._equipCell.itemInfo; if(_loc5_ && _loc5_.isGold) { this._equipCell.info = null; this._equipCell.info = _loc5_; } } private function __clickHelp(param1:MouseEvent) : void { SoundManager.instance.play("008"); param1.stopImmediatePropagation(); var _loc2_:HelpPrompt = ComponentFactory.Instance.creat("wishBead.wishBeadHelp"); var _loc3_:HelpFrame = ComponentFactory.Instance.creat("wishBead.helpFrame"); _loc3_.setView(_loc2_); _loc3_.titleText = LanguageMgr.GetTranslation("wishBead.wishBeadHelp.say"); _loc3_.setButtonPos(174,442); LayerManager.Instance.addToLayer(_loc3_,LayerManager.STAGE_DYANMIC_LAYER,true,LayerManager.BLCAK_BLOCKGOUND); } private function propInfoChangeHandler(param1:BagEvent) : void { var _loc3_:InventoryItemInfo = null; var _loc4_:InventoryItemInfo = null; var _loc5_:InventoryItemInfo = null; var _loc2_:Dictionary = param1.changedSlots; for each(_loc4_ in _loc2_) { _loc3_ = _loc4_; } if(_loc3_ && !PlayerManager.Instance.Self.PropBag.items[_loc3_.Place]) { if(this._itemCell.info && (this._itemCell.info as InventoryItemInfo).Place == _loc3_.Place) { this._itemCell.info = null; } else { this._proBagList.setData(WishBeadManager.instance.getWishBeadItemData()); } } else { if(!this._itemCell || !this._itemCell.info) { return; } _loc5_ = this._itemCell.info as InventoryItemInfo; if(!PlayerManager.Instance.Self.PropBag.items[_loc5_.Place]) { this._itemCell.info = null; } else { this._itemCell.setCount(_loc5_.Count); } } } private function __showTip(param1:CrazyTankSocketEvent) : void { this._tip.isDisplayerTip = true; var _loc2_:int = param1.pkg.readInt(); switch(_loc2_) { case 0: this._continuousBtn.selected = false; this._tip.showSuccess(this.judgeAgain); break; case 1: this._tip.showFail(this.judgeAgain); break; case 5: MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("wishBead.notCanWish")); this.judgeDoBtnStatus(false); break; case 6: MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("wishBead.equipIsGold")); this.judgeDoBtnStatus(false); break; case 8: MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("wishBead.remainTimeShort")); this.judgeDoBtnStatus(false); break; default: this.judgeDoBtnStatus(false); } } private function judgeAgain() : void { if(this._isDispose) { return; } if(this._continuousBtn.selected) { if((this._itemCell.info as InventoryItemInfo).Count <= 0) { MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("wishBead.noBead")); return; } this.sendMess(); } else { this.judgeDoBtnStatus(false); } } private function doHandler(param1:MouseEvent) : void { var _loc2_:BaseAlerFrame = null; SoundManager.instance.play("008"); if(PlayerManager.Instance.Self.bagLocked) { BaglockedManager.Instance.show(); return; } if(!this._equipCell.info) { return; } if(!this._itemCell.info) { return; } if((this._itemCell.info as InventoryItemInfo).Count <= 0) { MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("wishBead.noBead")); return; } if(!(this._equipCell.info as InventoryItemInfo).IsBinds) { _loc2_ = AlertManager.Instance.simpleAlert(LanguageMgr.GetTranslation("AlertDialog.Info"),LanguageMgr.GetTranslation("tank.view.bagII.BagIIView.BindsInfo"),LanguageMgr.GetTranslation("ok"),LanguageMgr.GetTranslation("cancel"),true,true,true,LayerManager.BLCAK_BLOCKGOUND); _loc2_.moveEnable = false; _loc2_.addEventListener(FrameEvent.RESPONSE,this.__confirm,false,0,true); } else { this.sendMess(); } } private function __confirm(param1:FrameEvent) : void { SoundManager.instance.play("008"); var _loc2_:BaseAlerFrame = param1.currentTarget as BaseAlerFrame; _loc2_.removeEventListener(FrameEvent.RESPONSE,this.__confirm); if(param1.responseCode == FrameEvent.SUBMIT_CLICK || param1.responseCode == FrameEvent.ENTER_CLICK) { this.sendMess(); } } private function sendMess() : void { this._doBtn.enable = false; var _loc1_:InventoryItemInfo = this._equipCell.info as InventoryItemInfo; var _loc2_:InventoryItemInfo = this._itemCell.info as InventoryItemInfo; SocketManager.Instance.out.sendWishBeadEquip(_loc1_.Place,_loc1_.BagType,_loc1_.TemplateID,_loc2_.Place,_loc2_.BagType,_loc2_.TemplateID); } private function itemEquipChangeHandler(param1:Event) : void { this._continuousBtn.selected = false; this.judgeDoBtnStatus(true); } private function judgeDoBtnStatus(param1:Boolean) : void { if(this._equipCell.info && this._itemCell.info) { if(WishBeadManager.instance.getIsEquipMatchWishBead(this._itemCell.info.TemplateID,this._equipCell.info.CategoryID,param1)) { this._doBtn.enable = true; } else { this._doBtn.enable = false; } } else { this._doBtn.enable = false; } } protected function __cellDoubleClick(param1:CellEvent) : void { SoundManager.instance.play("008"); if(PlayerManager.Instance.Self.bagLocked) { BaglockedManager.Instance.show(); return; } var _loc2_:String = ""; if(param1.target == this._proBagList) { _loc2_ = WishBeadManager.ITEM_MOVE; } else { _loc2_ = WishBeadManager.EQUIP_MOVE; } var _loc3_:WishBeadEvent = new WishBeadEvent(_loc2_); var _loc4_:BagCell = param1.data as BagCell; _loc3_.info = _loc4_.info as InventoryItemInfo; _loc3_.moveType = 1; WishBeadManager.instance.dispatchEvent(_loc3_); } private function cellClickHandler(param1:CellEvent) : void { SoundManager.instance.play("008"); var _loc2_:BagCell = param1.data as BagCell; _loc2_.dragStart(); } private function createAcceptDragSprite() : void { this._leftDrapSprite = new WishBeadLeftDragSprite(); this._leftDrapSprite.mouseEnabled = false; this._leftDrapSprite.mouseChildren = false; this._leftDrapSprite.graphics.beginFill(0,0); this._leftDrapSprite.graphics.drawRect(0,0,347,404); this._leftDrapSprite.graphics.endFill(); PositionUtils.setPos(this._leftDrapSprite,"wishBeadMainView.leftDrapSpritePos"); addChild(this._leftDrapSprite); this._rightDrapSprite = new WishBeadRightDragSprite(); this._rightDrapSprite.mouseEnabled = false; this._rightDrapSprite.mouseChildren = false; this._rightDrapSprite.graphics.beginFill(0,0); this._rightDrapSprite.graphics.drawRect(0,0,374,407); this._rightDrapSprite.graphics.endFill(); PositionUtils.setPos(this._rightDrapSprite,"wishBeadMainView.rightDrapSpritePos"); addChild(this._rightDrapSprite); } override public function set visible(param1:Boolean) : void { super.visible = param1; if(param1) { if(!this._isDispose) { this.refreshListData(); PlayerManager.Instance.Self.PropBag.addEventListener(BagEvent.UPDATE,this.propInfoChangeHandler); PlayerManager.Instance.Self.Bag.addEventListener(BagEvent.UPDATE,this.bagInfoChangeHandler); } } else { this.clearCellInfo(); PlayerManager.Instance.Self.PropBag.removeEventListener(BagEvent.UPDATE,this.propInfoChangeHandler); PlayerManager.Instance.Self.Bag.removeEventListener(BagEvent.UPDATE,this.bagInfoChangeHandler); } } public function clearCellInfo() : void { if(this._equipCell) { this._equipCell.clearInfo(); } if(this._itemCell) { this._itemCell.clearInfo(); } } public function refreshListData() : void { if(this._bagList) { this.refreshBagList(); } if(this._proBagList) { this._proBagList.setData(WishBeadManager.instance.getWishBeadItemData()); } } private function removeEvent() : void { this._bagList.removeEventListener(CellEvent.ITEM_CLICK,this.cellClickHandler); this._bagList.removeEventListener(CellEvent.DOUBLE_CLICK,this.__cellDoubleClick); this._equipCell.removeEventListener(Event.CHANGE,this.itemEquipChangeHandler); this._proBagList.removeEventListener(CellEvent.ITEM_CLICK,this.cellClickHandler); this._proBagList.removeEventListener(CellEvent.DOUBLE_CLICK,this.__cellDoubleClick); this._itemCell.removeEventListener(Event.CHANGE,this.itemEquipChangeHandler); this._doBtn.removeEventListener(MouseEvent.CLICK,this.doHandler); SocketManager.Instance.removeEventListener(CrazyTankSocketEvent.WISHBEADEQUIP,this.__showTip); PlayerManager.Instance.Self.PropBag.removeEventListener(BagEvent.UPDATE,this.propInfoChangeHandler); PlayerManager.Instance.Self.Bag.removeEventListener(BagEvent.UPDATE,this.bagInfoChangeHandler); this._helpBtn.removeEventListener(MouseEvent.CLICK,this.__clickHelp); } public function dispose() : void { this.removeEvent(); ObjectUtils.disposeAllChildren(this); ObjectUtils.disposeObject(this._tip); this._tip = null; this._bg = null; this._bagList = null; this._proBagList = null; this._leftDrapSprite = null; this._rightDrapSprite = null; this._itemCell = null; this._equipCell = null; this._continuousBtn = null; this._doBtn = null; this._helpBtn = null; this._equipBagInfo = null; if(parent) { parent.removeChild(this); } this._isDispose = true; } } }
// makeswf -v 7 -s 200x150 -r 1 -o definefunction-target.swf definefunction-target.as trace ("Check which target DefineFunction uses"); createEmptyMovieClip ("a", 0); setTarget ("a"); function foo () { trace (_target); }; foo = function () { trace (_target); }; setTarget (""); foo (); a.foo (); loadMovie ("FSCommand:quit", "");
/* ***** 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 ***** */ /* * Default Interface DefaultInterface * Interface methods * */ package DefClassImpDefIntname{ //package name interface DefaultInt{ function deffunc():String; } }
function doWildlifeAI(monster:MovieClip):void { var lvl_mc:MovieClip = game.mc.getChildByName("gamelevel"); var num_children:int = lvl_mc.numChildren; for (var j:int = 0; j < num_children; j++) { if (!num_children) { break; } var mc = lvl_mc.getChildAt(j); if (mc.name.indexOf("collideBox") != -1) { hit_test(monster, mc, false); } if (monster.aiMode == undefined) { monster.aiMode = MODE_THINK; } } switch (monster.aiMode) {//We do certain things based on our AI case MODE_THINK : monster.thinkTime++; if (monster.inPain) { monster.aiMode = MODE_CHASE; } monster.rotation++; break; case MODE_CHASE : var a = hero.mc.y - monster.y; var b = hero.mc.x - monster.x; var radians = Math.atan2(a,b); var degrees = radians / (Math.PI / 180); monster.rotation = degrees; monster.rotation += monster.rotationOffset; if (monster.x <= hero.mc.x) { monster..x++; } else if (monster.x >= hero.mc.x) { monster.x--; } if (monster.y <= hero.mc.y) { monster.y++; } else if (monster.y >= hero.mc.y) { monster.y--; } if (!inRadiusOf(hero.mc, monster, 350)) { //We're outside the radius. monster.aiMode = MODE_THINK; } else if (inRadiusOf(hero.mc, monster, 30)) { //We're in attack range. Start attacking. monster.aiMode = MODE_ATTACK; } break; case MODE_ATTACK : if (!inRadiusOf(hero.mc, monster, 40)) { //We're now outside of attack range. Chase 'dem! monster.aiMode = MODE_CHASE; } else { if (monster.health <= 0) { return;//We are in the middle of an AI cycle when we died, so return immediately. //This will override any AI params! } //Attack. monster.attackDelay++; if (monster.attackDelay >= 100) { monsterAttack(monster, hero); monster.attackDelay = 0; } } break; } if (monster.inPain) { monster.painTime--; if (monster.painTime >= 0) { monster.inPain = false; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.jewel { import org.apache.royale.core.IBinaryImage; import org.apache.royale.core.IBinaryImageModel; import org.apache.royale.core.ValuesManager; import org.apache.royale.core.IBinaryImageLoader; import org.apache.royale.utils.BinaryData; /** * The Image class is a component that displays a bitmap. The Image uses * the following beads: * * org.apache.royale.core.IBeadModel: the data model for the Image, including the url/binary property. * org.apache.royale.core.IBeadView: constructs the visual elements of the component. * * @toplevel * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public class BinaryImage extends Image implements IBinaryImage { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public function BinaryImage() { super(); } /** * @royaleemitcoercion org.apache.royale.core.IBinaryImageLoader */ override public function addedToParent():void { var c:Class = ValuesManager.valuesImpl.getValue(this, "iBinaryImageLoader") as Class; if (c) { var loader:IBinaryImageLoader = (new c()) as IBinaryImageLoader; addBead(loader); } super.addedToParent(); } /** * The binary bitmap data. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 * @royaleignorecoercion org.apache.royale.core.IBinaryImageModel */ public function get binary():BinaryData { return (model as IBinaryImageModel).binary; } /** * @royaleignorecoercion org.apache.royale.core.IBinaryImageModel */ public function set binary(value:BinaryData):void { (model as IBinaryImageModel).binary = value; } } }
package citrus.physics.box2d { import Box2D.Collision.b2Manifold; import Box2D.Dynamics.Contacts.b2Contact; import Box2D.Dynamics.b2Body; import Box2D.Dynamics.b2ContactImpulse; /** * An interface used by each Box2D object. It helps to enable interaction between entity/component object and "normal" object. */ public interface IBox2DPhysicsObject { function handleBeginContact(contact:b2Contact):void; function handleEndContact(contact:b2Contact):void; function handlePreSolve(contact:b2Contact, oldManifold:b2Manifold):void; function handlePostSolve(contact:b2Contact, impulse:b2ContactImpulse):void; function get x():Number; function set x(value:Number):void; function get y():Number; function set y(value:Number):void; function get z():Number; function get rotation():Number; function set rotation(value:Number):void; function get width():Number; function set width(value:Number):void; function get height():Number; function set height(value:Number):void; function get depth():Number; function get radius():Number; function set radius(value:Number):void; function get body():b2Body; function getBody():*; } }
/** * RSAKey * * An ActionScript 3 implementation of RSA + PKCS#1 (light version) * Copyright (c) 2007 Henri Torgemane * * Derived from: * The jsbn library, Copyright (c) 2003-2005 Tom Wu * * See LICENSE.txt for full license information. */ package com.hurlant.crypto.rsa { import com.hurlant.crypto.prng.Random; import com.hurlant.math.BigInteger; import com.hurlant.util.Memory; import flash.utils.ByteArray; /** * Current limitations: * exponent must be smaller than 2^31. */ public class RSAKey { // public key public var e:int; // public exponent. must be <2^31 public var n:BigInteger; // modulus // private key public var d:BigInteger; // extended private key public var p:BigInteger; public var q:BigInteger; public var dmp1:BigInteger public var dmq1:BigInteger; public var coeff:BigInteger; // flags. flags are cool. protected var canDecrypt:Boolean; protected var canEncrypt:Boolean; public function RSAKey(N:BigInteger, E:int, D:BigInteger=null, P:BigInteger = null, Q:BigInteger=null, DP:BigInteger=null, DQ:BigInteger=null, C:BigInteger=null) { this.n = N; this.e = E; this.d = D; this.p = P; this.q = Q; this.dmp1 = DP; this.dmq1 = DQ; this.coeff = C; // adjust a few flags. canEncrypt = (n!=null&&e!=0); canDecrypt = (canEncrypt&&d!=null); } public static function parsePublicKey(N:String, E:String):RSAKey { return new RSAKey(new BigInteger(N, 16), parseInt(E,16)); } public static function parsePrivateKey(N:String, E:String, D:String, P:String=null,Q:String=null, DMP1:String=null, DMQ1:String=null, IQMP:String=null):RSAKey { if (P==null) { return new RSAKey(new BigInteger(N,16), parseInt(E,16), new BigInteger(D,16)); } else { return new RSAKey(new BigInteger(N,16), parseInt(E,16), new BigInteger(D,16), new BigInteger(P,16), new BigInteger(Q,16), new BigInteger(DMP1,16), new BigInteger(DMQ1), new BigInteger(IQMP)); } } public function getBlockSize():uint { return (n.bitLength()+7)/8; } public function dispose():void { e = 0; n.dispose(); n = null; Memory.gc(); } public function encrypt(src:ByteArray, dst:ByteArray, length:uint, pad:Function=null):void { // adjust pad if needed if (pad==null) pad = pkcs1pad; // convert src to BigInteger if (src.position >= src.length) { src.position = 0; } var bl:uint = getBlockSize(); var end:int = src.position + length; while (src.position<end) { var block:BigInteger = new BigInteger(pad(src, end, bl), bl); var chunk:BigInteger = doPublic(block); chunk.toArray(dst); } } public function decrypt(src:ByteArray, dst:ByteArray, length:uint, pad:Function=null):void { // adjust pad if needed if (pad==null) pad = pkcs1unpad; // convert src to BigInteger if (src.position >= src.length) { src.position = 0; } var bl:uint = getBlockSize(); var end:int = src.position + length; while (src.position<end) { var block:BigInteger = new BigInteger(src, length); var chunk:BigInteger = doPrivate2(block); var b:ByteArray = pad(chunk, bl); dst.writeBytes(b); } } /** * PKCS#1 pad. type 2, random. * puts as much data from src into it, leaves what doesn't fit alone. */ private function pkcs1pad(src:ByteArray, end:int, n:uint):ByteArray { var out:ByteArray = new ByteArray; var p:uint = src.position; end = Math.min(end, src.length, p+n-11); src.position = end; var i:int = end-1; while (i>=p && n>11) { out[--n] = src[i--]; } out[--n] = 0; var rng:Random = new Random; while (n>2) { var x:int = 0; while (x==0) x = rng.nextByte(); out[--n] = x; } out[--n] = 2; out[--n] = 0; return out; } private function pkcs1unpad(src:BigInteger, n:uint):ByteArray { var b:ByteArray = src.toByteArray(); var out:ByteArray = new ByteArray; var i:int = 0; while (i<b.length && b[i]==0) ++i; if (b.length-i != n-1 || b[i]!=2) { trace("PKCS#1 unpad: i="+i+", expected b[i]==2, got b[i]="+b[i]); return null; } ++i; while (b[i]!=0) { if (++i>=b.length) { trace("PKCS#1 unpad: i="+i+", b[i-1]!=0 (="+b[i-1]+")"); return null; } } while (++i < b.length) { out.writeByte(b[i]); } return out; } /** * Raw pad. */ private function rawpad(src:ByteArray, end:int, n:uint):ByteArray { return src; } public function toString():String { return "rsa"; } public function dump():String { var s:String= "N="+n.toString(16)+"\n"+ "E="+e.toString(16)+"\n"; if (canDecrypt) { s+="D="+d.toString(16)+"\n"; if (p!=null && q!=null) { s+="P="+p.toString(16)+"\n"; s+="Q="+q.toString(16)+"\n"; s+="DMP1="+dmp1.toString(16)+"\n"; s+="DMQ1="+dmq1.toString(16)+"\n"; s+="IQMP="+coeff.toString(16)+"\n"; } } return s; } /** * * note: We should have a "nice" variant of this function that takes a callback, * and perform the computation is small fragments, to keep the web browser * usable. * * @param B * @param E * @return a new random private key B bits long, using public expt E * */ public static function generate(B:uint, E:String):RSAKey { var rng:Random = new Random; var qs:uint = B>>1; var key:RSAKey = new RSAKey(null,0,null); key.e = parseInt(E, 16); var ee:BigInteger = new BigInteger(E,16); for (;;) { for (;;) { key.p = bigRandom(B-qs, rng); if (key.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE)==0 && key.p.isProbablePrime(10)) break; } for (;;) { key.q = bigRandom(qs, rng); if (key.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE)==0 && key.q.isProbablePrime(10)) break; } if (key.p.compareTo(key.q)<=0) { var t:BigInteger = key.p; key.p = key.q; key.q = t; } var p1:BigInteger = key.p.subtract(BigInteger.ONE); var q1:BigInteger = key.q.subtract(BigInteger.ONE); var phi:BigInteger = p1.multiply(q1); if (phi.gcd(ee).compareTo(BigInteger.ONE)==0) { key.n = key.p.multiply(key.q); key.d = ee.modInverse(phi); key.dmp1 = key.d.mod(p1); key.dmq1 = key.d.mod(q1); key.coeff = key.q.modInverse(key.p); break; } } return key; } protected static function bigRandom(bits:int, rnd:Random):BigInteger { if (bits<2) return BigInteger.nbv(1); var x:ByteArray = new ByteArray; rnd.nextBytes(x, (bits>>3)); x.position = 0; var b:BigInteger = new BigInteger(x); b.primify(bits, 1); return b; } protected function doPublic(x:BigInteger):BigInteger { return x.modPowInt(e, n); } protected function doPrivate2(x:BigInteger):BigInteger { if (p==null && q==null) { return x.modPow(d,n); } var xp:BigInteger = x.mod(p).modPow(dmp1, p); var xq:BigInteger = x.mod(q).modPow(dmq1, q); while (xp.compareTo(xq)<0) { xp = xp.add(p); } var r:BigInteger = xp.subtract(xq).multiply(coeff).mod(p).multiply(q).add(xq); return r; } protected function doPrivate(x:BigInteger):BigInteger { if (p==null || q==null) { return x.modPow(d, n); } // TODO: re-calculate any missing CRT params var xp:BigInteger = x.mod(p).modPow(dmp1, p); var xq:BigInteger = x.mod(q).modPow(dmq1, q); while (xp.compareTo(xq)<0) { xp = xp.add(p); } return xp.subtract(xq).multiply(coeff).mod(p).multiply(q).add(xq); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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 flashx.textLayout.conversion { import flash.display.Shape; import flash.text.engine.TextRotation; import flash.utils.Dictionary; import flashx.textLayout.TextLayoutVersion; import flashx.textLayout.container.ContainerController; import flashx.textLayout.debug.assert; import flashx.textLayout.elements.BreakElement; import flashx.textLayout.elements.DivElement; import flashx.textLayout.elements.FlowElement; import flashx.textLayout.elements.FlowGroupElement; import flashx.textLayout.elements.GlobalSettings; import flashx.textLayout.elements.IConfiguration; import flashx.textLayout.elements.InlineGraphicElement; import flashx.textLayout.elements.LinkElement; import flashx.textLayout.elements.ListElement; import flashx.textLayout.elements.ListItemElement; import flashx.textLayout.elements.ParagraphElement; import flashx.textLayout.elements.SpanElement; import flashx.textLayout.elements.SubParagraphGroupElement; import flashx.textLayout.elements.TCYElement; import flashx.textLayout.elements.TabElement; import flashx.textLayout.elements.TextFlow; import flashx.textLayout.formats.ITextLayoutFormat; import flashx.textLayout.formats.ListMarkerFormat; import flashx.textLayout.formats.TextLayoutFormat; import flashx.textLayout.property.Property; import flashx.textLayout.tlf_internal; use namespace tlf_internal; [ExcludeClass] /** * @private * TextLayoutImporter converts from XML to TextLayout data structures and back. */ public class TextLayoutImporter extends BaseTextLayoutImporter implements ITextLayoutImporter { private static var _defaultConfiguration:ImportExportConfiguration; /** Default ImportExportConfiguration to use when none specified * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 */ public static function get defaultConfiguration():ImportExportConfiguration { // The first call will force the import/export to include the standard components if (!_defaultConfiguration) { _defaultConfiguration = new ImportExportConfiguration(); // elements _defaultConfiguration.addIEInfo("TextFlow", TextFlow, BaseTextLayoutImporter.parseTextFlow, BaseTextLayoutExporter.exportTextFlow); _defaultConfiguration.addIEInfo("br", BreakElement, BaseTextLayoutImporter.parseBreak, BaseTextLayoutExporter.exportFlowElement); _defaultConfiguration.addIEInfo("p", ParagraphElement, BaseTextLayoutImporter.parsePara, BaseTextLayoutExporter.exportParagraphFormattedElement); _defaultConfiguration.addIEInfo("span", SpanElement, BaseTextLayoutImporter.parseSpan, BaseTextLayoutExporter.exportSpan); _defaultConfiguration.addIEInfo("tab", TabElement, BaseTextLayoutImporter.parseTab, BaseTextLayoutExporter.exportFlowElement); _defaultConfiguration.addIEInfo("list", ListElement, BaseTextLayoutImporter.parseList, BaseTextLayoutExporter.exportList); _defaultConfiguration.addIEInfo("li", ListItemElement, BaseTextLayoutImporter.parseListItem, BaseTextLayoutExporter.exportListItem); _defaultConfiguration.addIEInfo("g", SubParagraphGroupElement, TextLayoutImporter.parseSPGE, TextLayoutExporter.exportSPGE); _defaultConfiguration.addIEInfo("tcy", TCYElement, TextLayoutImporter.parseTCY, TextLayoutExporter.exportTCY); _defaultConfiguration.addIEInfo("a", LinkElement, TextLayoutImporter.parseLink, TextLayoutExporter.exportLink); _defaultConfiguration.addIEInfo("div", DivElement, TextLayoutImporter.parseDivElement, TextLayoutExporter.exportDiv); _defaultConfiguration.addIEInfo("img", InlineGraphicElement, TextLayoutImporter.parseInlineGraphic, TextLayoutExporter.exportImage); // validate the defaultTypeName values. They are to match the TLF format export xml names CONFIG::debug { for (var name:String in _defaultConfiguration.flowElementInfoList) { var info:FlowElementInfo = _defaultConfiguration.flowElementInfoList[name]; assert(name == (new info.flowClass).defaultTypeName,"Bad defaultTypeName in "+info.flowClass); } } // customized link formats _defaultConfiguration.addIEInfo(LinkElement.LINK_NORMAL_FORMAT_NAME,null,TextLayoutImporter.parseLinkNormalFormat,null); _defaultConfiguration.addIEInfo(LinkElement.LINK_ACTIVE_FORMAT_NAME,null,TextLayoutImporter.parseLinkActiveFormat,null); _defaultConfiguration.addIEInfo(LinkElement.LINK_HOVER_FORMAT_NAME, null,TextLayoutImporter.parseLinkHoverFormat, null); // list marker format _defaultConfiguration.addIEInfo(ListElement.LIST_MARKER_FORMAT_NAME,null,TextLayoutImporter.parseListMarkerFormat,null); } return _defaultConfiguration; } /** Set the default configuration back to its original value * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 */ public static function restoreDefaults():void { _defaultConfiguration = null; } static private const _formatImporter:TLFormatImporter = new TLFormatImporter(TextLayoutFormat,TextLayoutFormat.description); static private const _idImporter:SingletonAttributeImporter = new SingletonAttributeImporter("id"); static private const _typeNameImporter:SingletonAttributeImporter = new SingletonAttributeImporter("typeName"); static private const _customFormatImporter:CustomFormatImporter = new CustomFormatImporter(); static private const _flowElementFormatImporters:Array = [ _formatImporter,_idImporter,_typeNameImporter,_customFormatImporter ]; private var _imageSourceResolveFunction:Function; /** Constructor */ public function TextLayoutImporter() { super(new Namespace("flow", "http://ns.adobe.com/textLayout/2008"), defaultConfiguration); } /** @copy ITextLayoutImporter#imageSourceResolveFunction * * @playerversion Flash 10.0 * @playerversion AIR 2.0 * @langversion 3.0 */ public function get imageSourceResolveFunction():Function { return _imageSourceResolveFunction; } public function set imageSourceResolveFunction(resolver:Function):void { _imageSourceResolveFunction = resolver; } /** @private */ override protected function parseContent(rootStory:XML):TextFlow { // Capture all the top-level tags of interest that can be "bound" // We have to do this because the attributes are applied at the point // of calling something like: // span.charAttrs = characterAttrs; // At one time, we just set the variable to the parameter (in the setter), // but now we're copying the data into a new object. This change does // not allow for us to parse the bindings in any order. Hence, we // will process the potential bindings objects first, then the // TextFlow objects. // // Also note the use of "..*" below. We are using this to traverse the // XML structure looking for particular tags and at the same time allow for // any namespace. So, you might see something like <flow:TextContainer> or // <TextContainer> and this code will capture both cases. var rootName:String = rootStory.name().localName; var textFlowElement:XML = rootName == "TextFlow" ? rootStory : rootStory..*::TextFlow[0]; if (!textFlowElement) { reportError(GlobalSettings.resourceStringFunction("missingTextFlow")); return null; } if (!checkNamespace(textFlowElement)) return null; return parseTextFlow(this, textFlowElement); } private function parseStandardFlowElementAttributes(flowElem:FlowElement,xmlToParse:XML,importers:Array = null):void { if (importers == null) importers = _flowElementFormatImporters; // all the standard ones have to be in importers - some check needed parseAttributes(xmlToParse,importers); var textFormat:TextLayoutFormat = extractTextFormatAttributesHelper(flowElem.format,_formatImporter) as TextLayoutFormat; if (textFormat) { CONFIG::debug { assert(textFormat.getStyles() != null,"Bad TextFormat in parseStandardFlowElementAttributes"); } flowElem.format = textFormat; } if (_idImporter.result) flowElem.id = _idImporter.result as String; if (_typeNameImporter.result) flowElem.typeName = _typeNameImporter.result as String; if (_customFormatImporter.result) { for (var styleName:String in _customFormatImporter.result) flowElem.setStyle(styleName,_customFormatImporter.result[styleName]); } } override public function createTextFlowFromXML(xmlToParse:XML, textFlow:TextFlow = null):TextFlow { // allocate the TextFlow and set the TextContainer's rootElement to it. var newFlow:TextFlow = null; if (!checkNamespace(xmlToParse)) return newFlow; if (xmlToParse.hasOwnProperty("@version")) { var version:String = xmlToParse.@["version"]; if (version == "3.0.0") _importVersion = TextLayoutVersion.VERSION_3_0; else if (version == "2.0.0") _importVersion = TextLayoutVersion.VERSION_2_0; else if (version == "1.1.0" || version == "1.0.0") _importVersion = TextLayoutVersion.VERSION_1_0; else { reportError(GlobalSettings.resourceStringFunction("unsupportedVersion",[ xmlToParse.@["version"] ])); _importVersion = TextLayoutVersion.CURRENT_VERSION; } } else // we must be the first version _importVersion = TextLayoutVersion.VERSION_1_0; // allocate the TextFlow and initialize the container attributes if (!newFlow) newFlow = new TextFlow(_textFlowConfiguration); // parse formatting parseStandardFlowElementAttributes(newFlow,xmlToParse); // descend into children parseFlowGroupElementChildren(xmlToParse, newFlow); CONFIG::debug { newFlow.debugCheckNormalizeAll() ; } newFlow.normalize(); newFlow.applyWhiteSpaceCollapse(null); return newFlow; } public function createDivFromXML(xmlToParse:XML):DivElement { // add the div element to the parent var divElem:DivElement = new DivElement(); parseStandardFlowElementAttributes(divElem,xmlToParse); return divElem; } public override function createParagraphFromXML(xmlToParse:XML):ParagraphElement { var paraElem:ParagraphElement = new ParagraphElement(); parseStandardFlowElementAttributes(paraElem,xmlToParse); return paraElem; } public function createSubParagraphGroupFromXML(xmlToParse:XML):SubParagraphGroupElement { var elem:SubParagraphGroupElement = new SubParagraphGroupElement(); parseStandardFlowElementAttributes(elem,xmlToParse); return elem; } public function createTCYFromXML(xmlToParse:XML):TCYElement { var tcyElem:TCYElement = new TCYElement(); parseStandardFlowElementAttributes(tcyElem,xmlToParse); return tcyElem; } static internal const _linkDescription:Object = { href : Property.NewStringProperty("href",null, false, null), target : Property.NewStringProperty("target",null, false, null) } static private const _linkFormatImporter:TLFormatImporter = new TLFormatImporter(Dictionary,_linkDescription); static private const _linkElementFormatImporters:Array = [ _linkFormatImporter, _formatImporter,_idImporter,_typeNameImporter,_customFormatImporter ]; /** Parse a LinkElement Block. * * @param - importFilter:BaseTextLayoutImporter - parser object * @param - xmlToParse:XML - the xml describing the Link * @param - parent:FlowBlockElement - the parent of the new Link * @return LinkElement - a new LinkElement and its children */ public function createLinkFromXML(xmlToParse:XML):LinkElement { var linkElem:LinkElement = new LinkElement(); parseStandardFlowElementAttributes(linkElem,xmlToParse,_linkElementFormatImporters); if (_linkFormatImporter.result) { linkElem.href = _linkFormatImporter.result["href"] as String; linkElem.target = _linkFormatImporter.result["target"] as String; } return linkElem; } public override function createSpanFromXML(xmlToParse:XML):SpanElement { var spanElem:SpanElement = new SpanElement(); parseStandardFlowElementAttributes(spanElem,xmlToParse); return spanElem; } static private const _imageDescription:Object = { height:InlineGraphicElement.heightPropertyDefinition, width:InlineGraphicElement.widthPropertyDefinition, source: Property.NewStringProperty("source", null, false, null), float: Property.NewStringProperty("float", null, false, null), rotation: InlineGraphicElement.rotationPropertyDefinition } static private const _ilgFormatImporter:TLFormatImporter = new TLFormatImporter(Dictionary,_imageDescription); static private const _ilgElementFormatImporters:Array = [ _ilgFormatImporter, _formatImporter, _idImporter, _typeNameImporter, _customFormatImporter ]; public function createInlineGraphicFromXML(xmlToParse:XML):InlineGraphicElement { var imgElem:InlineGraphicElement = new InlineGraphicElement(); parseStandardFlowElementAttributes(imgElem,xmlToParse,_ilgElementFormatImporters); if (_ilgFormatImporter.result) { var source:String = _ilgFormatImporter.result["source"]; imgElem.source = _imageSourceResolveFunction != null ? _imageSourceResolveFunction(source) : source; // if not defined then let InlineGraphic set its own default imgElem.height = _ilgFormatImporter.result["height"]; imgElem.width = _ilgFormatImporter.result["width"]; /* We don't support rotation yet because of bugs in the player. */ // imgElem.rotation = InlineGraphicElement.heightPropertyDefinition.setHelper(imgElem.rotation,_ilgFormatImporter.result["rotation"]); imgElem.float = _ilgFormatImporter.result["float"]; } return imgElem; } public override function createListFromXML(xmlToParse:XML):ListElement { var rslt:ListElement = new ListElement; parseStandardFlowElementAttributes(rslt,xmlToParse); return rslt; } public override function createListItemFromXML(xmlToParse:XML):ListItemElement { var rslt:ListItemElement = new ListItemElement; parseStandardFlowElementAttributes(rslt,xmlToParse); return rslt; } public function extractTextFormatAttributesHelper(curAttrs:Object, importer:TLFormatImporter):Object { return extractAttributesHelper(curAttrs,importer); } /** Parse an SPGE element * * @param - importFilter:BaseTextLayoutImporter - parser object * @param - xmlToParse:XML - the xml describing the TCY Block * @param - parent:FlowBlockElement - the parent of the new TCY Block * @return SubParagraphGroupElement - a new TCYBlockElement and its children */ static public function parseSPGE(importFilter:BaseTextLayoutImporter, xmlToParse:XML, parent:FlowGroupElement):void { var elem:SubParagraphGroupElement = TextLayoutImporter(importFilter).createSubParagraphGroupFromXML(xmlToParse); if (importFilter.addChild(parent, elem)) { importFilter.parseFlowGroupElementChildren(xmlToParse, elem); //if parsing an empty tcy, create a Span for it. if (elem.numChildren == 0) elem.addChild(new SpanElement()); } } /** Parse a TCY Block. * * @param - importFilter:BaseTextLayoutImporter - parser object * @param - xmlToParse:XML - the xml describing the TCY Block * @param - parent:FlowBlockElement - the parent of the new TCY Block * @return TCYBlockElement - a new TCYBlockElement and its children */ static public function parseTCY(importFilter:BaseTextLayoutImporter, xmlToParse:XML, parent:FlowGroupElement):void { var tcyElem:TCYElement = TextLayoutImporter(importFilter).createTCYFromXML(xmlToParse); if (importFilter.addChild(parent, tcyElem)) { importFilter.parseFlowGroupElementChildren(xmlToParse, tcyElem); //if parsing an empty tcy, create a Span for it. if (tcyElem.numChildren == 0) tcyElem.addChild(new SpanElement()); } } /** Parse a LinkElement Block. * * @param - importFilter:BaseTextLayoutImporter - parser object * @param - xmlToParse:XML - the xml describing the Link * @param - parent:FlowBlockElement - the parent of the new Link * @return LinkElement - a new LinkElement and its children */ static public function parseLink(importFilter:BaseTextLayoutImporter, xmlToParse:XML, parent:FlowGroupElement):void { var linkElem:LinkElement = TextLayoutImporter(importFilter).createLinkFromXML(xmlToParse); if (importFilter.addChild(parent, linkElem)) { importFilter.parseFlowGroupElementChildren(xmlToParse, linkElem); //if parsing an empty link, create a Span for it. if (linkElem.numChildren == 0) linkElem.addChild(new SpanElement()); } } public function createDictionaryFromXML(xmlToParse:XML):Dictionary { var formatImporters:Array = [ _customFormatImporter ]; // parse the TextLayoutFormat child object var formatList:XMLList = xmlToParse..*::TextLayoutFormat; if (formatList.length() != 1) reportError(GlobalSettings.resourceStringFunction("expectedExactlyOneTextLayoutFormat",[ xmlToParse.name() ])); var parseThis:XML = formatList.length() > 0 ? formatList[0] : xmlToParse; parseAttributes(parseThis,formatImporters); return _customFormatImporter.result as Dictionary; } static public function parseLinkNormalFormat(importFilter:BaseTextLayoutImporter, xmlToParse:XML, parent:FlowGroupElement):void { parent.linkNormalFormat = TextLayoutImporter(importFilter).createDictionaryFromXML(xmlToParse); } static public function parseLinkActiveFormat(importFilter:BaseTextLayoutImporter, xmlToParse:XML, parent:FlowGroupElement):void { parent.linkActiveFormat = TextLayoutImporter(importFilter).createDictionaryFromXML(xmlToParse); } static public function parseLinkHoverFormat(importFilter:BaseTextLayoutImporter, xmlToParse:XML, parent:FlowGroupElement):void { parent.linkHoverFormat = TextLayoutImporter(importFilter).createDictionaryFromXML(xmlToParse); } public function createListMarkerFormatDictionaryFromXML(xmlToParse:XML):Dictionary { var formatImporters:Array = [ _customFormatImporter ]; // parse the TextLayoutFormat child object var formatList:XMLList = xmlToParse..*::ListMarkerFormat; if (formatList.length() != 1) reportError(GlobalSettings.resourceStringFunction("expectedExactlyOneListMarkerFormat",[ xmlToParse.name() ])); var parseThis:XML = formatList.length() > 0 ? formatList[0] : xmlToParse; parseAttributes(parseThis,formatImporters); return _customFormatImporter.result as Dictionary; } static public function parseListMarkerFormat(importFilter:BaseTextLayoutImporter, xmlToParse:XML, parent:FlowGroupElement):void { parent.listMarkerFormat = TextLayoutImporter(importFilter).createListMarkerFormatDictionaryFromXML(xmlToParse); } /** Parse the <div ...> tag and all its children * * @param - importFilter:BaseTextLayoutImportFilter - parser object * @param - xmlToParse:XML - the xml describing the Div * @param - parent:FlowBlockElement - the parent of the new Div */ static public function parseDivElement(importFilter:BaseTextLayoutImporter, xmlToParse:XML, parent:FlowGroupElement):void { var divElem:DivElement = TextLayoutImporter(importFilter).createDivFromXML(xmlToParse); if (importFilter.addChild(parent, divElem)) { importFilter.parseFlowGroupElementChildren(xmlToParse, divElem); // we can't have a <div> tag w/no children... so, add an empty paragraph if (divElem.numChildren == 0) divElem.addChild(new ParagraphElement()); } } /** Parse a leaf element, the <img ...> tag. * * @param - importFilter:BaseTextLayoutImporter - parser object * @param - xmlToParse:XML - the xml describing the InlineGraphic FlowElement * @param - parent:FlowBlockElement - the parent of the new image FlowElement */ static public function parseInlineGraphic(importFilter:BaseTextLayoutImporter, xmlToParse:XML, parent:FlowGroupElement):void { var ilg:InlineGraphicElement = TextLayoutImporter(importFilter).createInlineGraphicFromXML(xmlToParse); importFilter.addChild(parent, ilg); } } }
package io.decagames.rotmg.supportCampaign.tooltips { import io.decagames.rotmg.supportCampaign.data.SupporterCampaignModel; import robotlegs.bender.bundles.mvcs.Mediator; public class PointsTooltipMediator extends Mediator { [Inject] public var view:PointsTooltip; [Inject] public var model:SupporterCampaignModel; public function PointsTooltipMediator() { super(); } override public function initialize() : void { this.view.updatePoints(this.view.shopButton.price * this.model.shopPurchasePointsRatio); } override public function destroy() : 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 { import mx.modules.ModuleBase; public class CoverageDataModule extends ModuleBase { public function get data():Object { return { firstName:"Bill", lastName: "Sahlas" }; } } }
/* * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ package Box2D.Collision{ import Box2D.Collision.*; import Box2D.Common.Math.*; import Box2D.Common.*; import Box2D.Common.b2internal; use namespace b2internal; /** * A manifold for two touching convex shapes. * Box2D supports multiple types of contact: * - clip point versus plane with radius * - point versus point with radius (circles) * The local point usage depends on the manifold type: * -e_circles: the local center of circleA * -e_faceA: the center of faceA * -e_faceB: the center of faceB * Similarly the local normal usage: * -e_circles: not used * -e_faceA: the normal on polygonA * -e_faceB: the normal on polygonB * We store contacts in this way so that position correction can * account for movement, which is critical for continuous physics. * All contact scenarios must be expressed in one of these types. * This structure is stored across time steps, so we keep it small. */ public class b2Manifold { public function b2Manifold(){ m_points = new Array/*b2ManifoldPoint*/(b2Settings.b2_maxManifoldPoints); for (var i:int = 0; i < b2Settings.b2_maxManifoldPoints; i++){ m_points[i] = new b2ManifoldPoint(); } m_localPlaneNormal = new b2Vec2(); m_localPoint = new b2Vec2(); } public function Reset() : void{ for (var i:int = 0; i < b2Settings.b2_maxManifoldPoints; i++){ (m_points[i] as b2ManifoldPoint).Reset(); } m_localPlaneNormal.SetZero(); m_localPoint.SetZero(); m_type = 0; m_pointCount = 0; } public function Set(m:b2Manifold) : void{ m_pointCount = m.m_pointCount; for (var i:int = 0; i < b2Settings.b2_maxManifoldPoints; i++){ (m_points[i] as b2ManifoldPoint).Set(m.m_points[i]); } m_localPlaneNormal.SetV(m.m_localPlaneNormal); m_localPoint.SetV(m.m_localPoint); m_type = m.m_type; } public function Copy():b2Manifold { var copy:b2Manifold = new b2Manifold(); copy.Set(this); return copy; } /** The points of contact */ public var m_points:Array/*b2ManifoldPoint*/; /** Not used for Type e_points*/ public var m_localPlaneNormal:b2Vec2; /** Usage depends on manifold type */ public var m_localPoint:b2Vec2; public var m_type:int; /** The number of manifold points */ public var m_pointCount:int = 0; //enum Type public static const e_circles:int = 0x0001; public static const e_faceA:int = 0x0002; public static const e_faceB:int = 0x0004; }; }
package com.illuzor.circles.ui { import adobe.utils.CustomActions; import com.greensock.TweenLite; import starling.display.Image; import starling.display.Sprite; import starling.textures.Texture; /** * ... * @author illuzor // illuzor.com */ internal class LiveCircle extends Sprite { private var circle:Image; private var texture:Texture; private var newCircle:Image; public function LiveCircle(texture:Texture, color:uint) { this.texture = texture; circle = new Image(texture); addChild(circle); circle.color = color; } public function changeColor(color:uint):void { newCircle = new Image(texture); addChild(newCircle); newCircle.color = color; newCircle.alpha = 0; TweenLite.to(newCircle, .25, { alpha:1 } ); TweenLite.to(circle, .25, { alpha:0, onComplete:changeCircles } ); } private function changeCircles():void { removeChild(circle); circle.dispose(); circle = newCircle; } } }
package feathers.examples.transitionsExplorer.screens { import feathers.controls.Button; import feathers.controls.Header; import feathers.controls.List; import feathers.controls.PanelScreen; import feathers.controls.renderers.DefaultListItemRenderer; import feathers.controls.renderers.IListItemRenderer; import feathers.data.ArrayCollection; import feathers.data.ListCollection; import feathers.layout.AnchorLayout; import feathers.layout.AnchorLayoutData; import feathers.motion.Fade; import starling.display.DisplayObject; import starling.events.Event; public class FadeTransitionScreen extends PanelScreen { public static const TRANSITION:String = "transition"; public function FadeTransitionScreen() { super(); } private var _list:List; private var _backButton:Button; override protected function initialize():void { //never forget to call super.initialize() super.initialize(); this.title = "Fade"; this.layout = new AnchorLayout(); this._list = new List(); this._list.dataProvider = new ArrayCollection( [ { label: "Fade In", transition: Fade.createFadeInTransition() }, { label: "Fade Out", transition: Fade.createFadeOutTransition() }, { label: "Crossfade", transition: Fade.createCrossfadeTransition() }, ]); this._list.layoutData = new AnchorLayoutData(0, 0, 0, 0); this._list.clipContent = false; this._list.autoHideBackground = true; this._list.itemRendererFactory = function():IListItemRenderer { var renderer:DefaultListItemRenderer = new DefaultListItemRenderer(); //enable the quick hit area to optimize hit tests when an item //is only selectable and doesn't have interactive children. renderer.isQuickHitAreaEnabled = true; renderer.labelField = "label"; return renderer; }; this._list.addEventListener(Event.TRIGGERED, list_triggeredHandler); this._list.revealScrollBars(); this.addChild(this._list); this.headerFactory = this.customHeaderFactory; } private function customHeaderFactory():Header { var header:Header = new Header(); this._backButton = new Button(); this._backButton.styleNameList.add(Button.ALTERNATE_STYLE_NAME_BACK_BUTTON); this._backButton.label = "Transitions"; this._backButton.addEventListener(Event.TRIGGERED, backButton_triggeredHandler); header.leftItems = new <DisplayObject>[this._backButton]; return header; } private function list_triggeredHandler(event:Event, item:Object):void { var transition:Function = item.transition as Function; this.dispatchEventWith(TRANSITION, false, transition); } private function backButton_triggeredHandler(event:Event):void { this.dispatchEventWith(Event.COMPLETE); } } }
package{ import flash.utils.Dictionary; public class SettingGroup{ public var title:String; public var userCreated:Boolean; private var _settings:Dictionary; public function SettingGroup(title:String=null, userCreated:Boolean=false){ this.title = title; this.userCreated = userCreated; _settings = new Dictionary(); } public function setSetting(name:String, value:*):void{ _settings[name] = value; } public function getSetting(name:String):*{ return _settings[name]; } } }
package utils.color { /** * Convert hue to RGB values using a linear transformation. * @param min of R,G,B. * @param max of R,G,B. * @param hue value angle hue. * @return Object with R,G,B properties on 0-1 scale. */ public function HueToRGB(min:Number, max:Number, hue:Number):Object { const HUE_MAX:uint = 360; var mu:Number, md:Number, F:Number, n:Number; while (hue < 0) { hue += HUE_MAX; } n = Math.floor(hue / 60); F = (hue - n * 60) / 60; n %= 6; mu = min + ((max - min) * F); md = max - ((max - min) * F); switch (n) { case 0: return { r: max, g: mu, b: min }; case 1: return { r: md, g: max, b: min }; case 2: return { r: min, g: max, b: mu }; case 3: return { r: min, g: md, b: max }; case 4: return { r: mu, g: min, b: max }; case 5: return { r: max, g: min, b: md }; } return null; } }
//------------------------------------------------------------------------------ // Copyright (c) 2012 the original author or authors. All Rights Reserved. // // NOTICE: You are permitted to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. //------------------------------------------------------------------------------ package robotlegs.starling.extensions.viewManager { import robotlegs.bender.framework.api.IContext; import robotlegs.bender.framework.api.IExtension; import robotlegs.bender.framework.api.IInjector; import robotlegs.bender.framework.api.ILogger; import robotlegs.starling.extensions.contextView.ContextView; import robotlegs.starling.extensions.viewManager.api.IViewManager; import robotlegs.starling.extensions.viewManager.impl.ContainerBinding; import robotlegs.starling.extensions.viewManager.impl.ContainerRegistry; import robotlegs.starling.extensions.viewManager.impl.StageCrawler; import starling.display.DisplayObjectContainer; /** * View Handlers (like the MediatorMap) handle views as they land on stage. * * This extension checks for views that might already be on the stage * after context initialization and ensures that those views are handled. */ public class StageCrawlerExtension implements IExtension { /*============================================================================*/ /* Private Properties */ /*============================================================================*/ private var _logger:ILogger; private var _injector:IInjector; private var _containerRegistry:ContainerRegistry; /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function extend(context:IContext):void { _injector = context.injector; _logger = context.getLogger(this); context.afterInitializing(afterInitializing); } /*============================================================================*/ /* Private Functions */ /*============================================================================*/ private function afterInitializing():void { _containerRegistry = _injector.getInstance(ContainerRegistry); _injector.hasDirectMapping(IViewManager) ? scanViewManagedContainers() : scanContextView(); } private function scanViewManagedContainers():void { _logger.debug("ViewManager is installed. Checking for managed containers..."); const viewManager:IViewManager = _injector.getInstance(IViewManager); for each (var container:DisplayObjectContainer in viewManager.containers) { container.stage && scanContainer(container); } } private function scanContextView():void { _logger.debug("ViewManager is not installed. Checking the ContextView..."); const contextView:ContextView = _injector.getInstance(ContextView); contextView.view.stage && scanContainer(contextView.view.stage); } private function scanContainer(container:DisplayObjectContainer):void { var binding:ContainerBinding = _containerRegistry.getBinding(container); _logger.debug("StageCrawler scanning container {0} ...", [container]); new StageCrawler(binding).scan(container); _logger.debug("StageCrawler finished scanning {0}", [container]); } } }
package com.axiomalaska.charts.axes.utilities { public class AxisIntervalCalculator { public function AxisIntervalCalculator() { } } }
package com.epologee.navigator.transition { import com.epologee.navigator.NavigationState; import com.epologee.navigator.Navigator; import com.epologee.navigator.behaviors.IHasStateValidation; import com.epologee.navigator.behaviors.IHasStateValidationAsync; import com.epologee.navigator.namespaces.validation; /** * @author Eric-Paul Lecluse (c) epologee.com */ public class ValidationPreparedDelegate { private var _navigator : Navigator; private var _validator : IHasStateValidationAsync; private var _truncated : NavigationState; private var _full : NavigationState; public function ValidationPreparedDelegate(validator : IHasStateValidation, truncated : NavigationState, full : NavigationState, navigator : Navigator) { _validator = IHasStateValidationAsync(validator); _truncated = truncated; _full = full; _navigator = navigator; } /** * The reason this method has rest parameter, is because * then you can either call it by using call() or bind it * to an event handler that will send an event argument. * * The arguments are ignored. */ validation function call(...ignoreParameters) : void { _navigator.validation::notifyValidationPrepared(_validator, _truncated, _full); _validator = null; _truncated = null; _full = null; _navigator = null; } } }
namespace RaspberryBush { class Bush { Node@ node; float lifetime; StaticModel@ model; uint stage; Array<Node@> berries; } Array<Bush@> trees; uint STAGE_SUMMER = 0; uint STAGE_AUTUMN = 1; Node@ Create(Vector3 position) { position.y = NetworkHandler::terrain.GetHeight(position); if (position.y < 100) { return null; } Node@ treeNode = scene_.CreateChild("Bush"); treeNode.temporary = true; treeNode.AddTag("Bush"); treeNode.position = position; StaticModel@ object = treeNode.CreateComponent("StaticModel"); object.model = cache.GetResource("Model", "Models/Models/Raspberry_bush.mdl"); treeNode.SetScale(1.8f + Random(0.5f)); object.castShadows = true; object.materials[0] = cache.GetResource("Material", "Materials/TreeGreen.xml"); // Create rigidbody, and set non-zero mass so that the body becomes dynamic RigidBody@ body = treeNode.CreateComponent("RigidBody"); body.collisionLayer = COLLISION_TREE_LEVEL; body.collisionMask = COLLISION_PACMAN_LEVEL | COLLISION_SNAKE_BODY_LEVEL | COLLISION_SNAKE_HEAD_LEVEL | COLLISION_PLAYER_LEVEL | COLLISION_FOOD_LEVEL; body.mass = 0.0f; // Set zero angular factor so that physics doesn't turn the character on its own. // Instead we will control the character yaw manually body.angularFactor = Vector3::ZERO; // Set the rigidbody to signal collision also when in rest, so that we get ground collisions properly body.collisionEventMode = COLLISION_ALWAYS; // Set a capsule shape for collision CollisionShape@ shape = treeNode.CreateComponent("CollisionShape"); shape.SetTriangleMesh(object.model); Bush tree; tree.node = treeNode; tree.lifetime = 20.0f + Random(20.0f); tree.stage = STAGE_SUMMER; tree.model = object; Spawn::Create(treeNode.worldPosition, 5, 100, 100, 2 + RandomInt(2), 5, Spawn::SPAWN_UNIT_RASPBERRY); trees.Push(tree); return treeNode; } void HandleUpdate(StringHash eventType, VariantMap& eventData) { float timeStep = eventData["TimeStep"].GetFloat(); for (uint i = 0; i < trees.length; i++) { Bush@ tree = trees[i]; tree.lifetime -= timeStep; if (tree.lifetime < 0) { tree.stage++; tree.lifetime = 20.0f + Random(20.0f); if (tree.stage > STAGE_AUTUMN) { tree.stage = STAGE_SUMMER; } if (tree.stage == STAGE_SUMMER) { tree.model.materials[0] = cache.GetResource("Material", "Materials/TreeGreen.xml"); } else if (tree.stage == STAGE_AUTUMN) { tree.model.materials[0] = cache.GetResource("Material", "Materials/TreeYellow.xml"); } } } } }
package cmodule.decry { const _environ:int = gstaticInitter.alloc(4,4); }
package com.ui.games { import flash.display.*; import flash.events.Event; public class OrderArray extends MovieClip { private var dragdrops:Array; private var numOfMatches:uint = 0; private var _vidAAnswer:String = "A"; private var _vidBAnswer:String = "B"; private var _vidCAnswer:String = "C"; private var _vidASource:String; private var _vidBSource:String; private var _vidCSource:String; public function OrderArray() { // constructor code reset(); } public function match(currentMovie:newOrderMovie = null):void { numOfMatches++; trace(currentMovie.target.name + " = Current target for this movie"); getChildByName(currentMovie.target.name + "_check").visible = true; getChildByName(currentMovie.target.name + "_ans").visible = true; currentMovie.visible = false; trace("Match!"); Object(parent.parent).addAllClickItem("Match " + numOfMatches); if (numOfMatches >= dragdrops.length) { //Show winning screen dispatchEvent(new Event(Event.COMPLETE)); } } public function reset():void { dragdrops = [orderA_vdo, orderB_vdo, orderC_vdo]; var answers:Array = [_vidAAnswer, _vidBAnswer, _vidCAnswer] var currentObject:newOrderMovie; for (var i:uint = 0; i < dragdrops.length; i++) { currentObject = dragdrops[i]; currentObject.target = getChildByName("box" + answers[i]); currentObject.visible = true; getChildByName("box" + answers[i] + "_check").visible = false; getChildByName("box" + answers[i] + "_ans").visible = false; } numOfMatches = 0; } public function vidASource(s:String, ans:String):void { _vidASource = s; _vidAAnswer = ans; orderA_vdo.updateSource(_vidASource); Object(getChildByName("box" + _vidAAnswer + "_ans")).updateSource(_vidASource); Object(getChildByName("box" + _vidAAnswer + "_ans")).turnOffDrag = true; } public function get vidAAnswer():String { return vidAAnswer; } public function vidBSource(s:String, a:String):void { _vidBSource = s; _vidBAnswer = a; orderB_vdo.updateSource(_vidBSource); Object(getChildByName("box" + _vidBAnswer + "_ans")).updateSource(_vidBSource); Object(getChildByName("box" + _vidAAnswer + "_ans")).turnOffDrag = true; } public function get vidBAnswer():String { return vidBAnswer; } public function vidCSource(s:String, a:String):void { _vidCSource = s; _vidCAnswer = a; orderC_vdo.updateSource(_vidCSource); Object(getChildByName("box" + _vidCAnswer + "_ans")).updateSource(_vidCSource); Object(getChildByName("box" + _vidCAnswer + "_ans")).turnOffDrag = true; } public function get vidCAnswer():String { return vidCAnswer; } } }
package com.ankamagames.dofus.network.types.game.look { import com.ankamagames.jerakine.network.ICustomDataInput; import com.ankamagames.jerakine.network.ICustomDataOutput; import com.ankamagames.jerakine.network.INetworkType; import com.ankamagames.jerakine.network.utils.FuncTree; public class EntityLook implements INetworkType { public static const protocolId:uint = 5925; public var bonesId:uint = 0; public var skins:Vector.<uint>; public var indexedColors:Vector.<int>; public var scales:Vector.<int>; public var subentities:Vector.<SubEntity>; private var _skinstree:FuncTree; private var _indexedColorstree:FuncTree; private var _scalestree:FuncTree; private var _subentitiestree:FuncTree; public function EntityLook() { this.skins = new Vector.<uint>(); this.indexedColors = new Vector.<int>(); this.scales = new Vector.<int>(); this.subentities = new Vector.<SubEntity>(); super(); } public function getTypeId() : uint { return 5925; } public function initEntityLook(bonesId:uint = 0, skins:Vector.<uint> = null, indexedColors:Vector.<int> = null, scales:Vector.<int> = null, subentities:Vector.<SubEntity> = null) : EntityLook { this.bonesId = bonesId; this.skins = skins; this.indexedColors = indexedColors; this.scales = scales; this.subentities = subentities; return this; } public function reset() : void { this.bonesId = 0; this.skins = new Vector.<uint>(); this.indexedColors = new Vector.<int>(); this.scales = new Vector.<int>(); this.subentities = new Vector.<SubEntity>(); } public function serialize(output:ICustomDataOutput) : void { this.serializeAs_EntityLook(output); } public function serializeAs_EntityLook(output:ICustomDataOutput) : void { if(this.bonesId < 0) { throw new Error("Forbidden value (" + this.bonesId + ") on element bonesId."); } output.writeVarShort(this.bonesId); output.writeShort(this.skins.length); for(var _i2:uint = 0; _i2 < this.skins.length; _i2++) { if(this.skins[_i2] < 0) { throw new Error("Forbidden value (" + this.skins[_i2] + ") on element 2 (starting at 1) of skins."); } output.writeVarShort(this.skins[_i2]); } output.writeShort(this.indexedColors.length); for(var _i3:uint = 0; _i3 < this.indexedColors.length; _i3++) { output.writeInt(this.indexedColors[_i3]); } output.writeShort(this.scales.length); for(var _i4:uint = 0; _i4 < this.scales.length; _i4++) { output.writeVarShort(this.scales[_i4]); } output.writeShort(this.subentities.length); for(var _i5:uint = 0; _i5 < this.subentities.length; _i5++) { (this.subentities[_i5] as SubEntity).serializeAs_SubEntity(output); } } public function deserialize(input:ICustomDataInput) : void { this.deserializeAs_EntityLook(input); } public function deserializeAs_EntityLook(input:ICustomDataInput) : void { var _val2:uint = 0; var _val3:int = 0; var _val4:int = 0; var _item5:SubEntity = null; this._bonesIdFunc(input); var _skinsLen:uint = input.readUnsignedShort(); for(var _i2:uint = 0; _i2 < _skinsLen; _i2++) { _val2 = input.readVarUhShort(); if(_val2 < 0) { throw new Error("Forbidden value (" + _val2 + ") on elements of skins."); } this.skins.push(_val2); } var _indexedColorsLen:uint = input.readUnsignedShort(); for(var _i3:uint = 0; _i3 < _indexedColorsLen; _i3++) { _val3 = input.readInt(); this.indexedColors.push(_val3); } var _scalesLen:uint = input.readUnsignedShort(); for(var _i4:uint = 0; _i4 < _scalesLen; _i4++) { _val4 = input.readVarShort(); this.scales.push(_val4); } var _subentitiesLen:uint = input.readUnsignedShort(); for(var _i5:uint = 0; _i5 < _subentitiesLen; _i5++) { _item5 = new SubEntity(); _item5.deserialize(input); this.subentities.push(_item5); } } public function deserializeAsync(tree:FuncTree) : void { this.deserializeAsyncAs_EntityLook(tree); } public function deserializeAsyncAs_EntityLook(tree:FuncTree) : void { tree.addChild(this._bonesIdFunc); this._skinstree = tree.addChild(this._skinstreeFunc); this._indexedColorstree = tree.addChild(this._indexedColorstreeFunc); this._scalestree = tree.addChild(this._scalestreeFunc); this._subentitiestree = tree.addChild(this._subentitiestreeFunc); } private function _bonesIdFunc(input:ICustomDataInput) : void { this.bonesId = input.readVarUhShort(); if(this.bonesId < 0) { throw new Error("Forbidden value (" + this.bonesId + ") on element of EntityLook.bonesId."); } } private function _skinstreeFunc(input:ICustomDataInput) : void { var length:uint = input.readUnsignedShort(); for(var i:uint = 0; i < length; i++) { this._skinstree.addChild(this._skinsFunc); } } private function _skinsFunc(input:ICustomDataInput) : void { var _val:uint = input.readVarUhShort(); if(_val < 0) { throw new Error("Forbidden value (" + _val + ") on elements of skins."); } this.skins.push(_val); } private function _indexedColorstreeFunc(input:ICustomDataInput) : void { var length:uint = input.readUnsignedShort(); for(var i:uint = 0; i < length; i++) { this._indexedColorstree.addChild(this._indexedColorsFunc); } } private function _indexedColorsFunc(input:ICustomDataInput) : void { var _val:int = input.readInt(); this.indexedColors.push(_val); } private function _scalestreeFunc(input:ICustomDataInput) : void { var length:uint = input.readUnsignedShort(); for(var i:uint = 0; i < length; i++) { this._scalestree.addChild(this._scalesFunc); } } private function _scalesFunc(input:ICustomDataInput) : void { var _val:int = input.readVarShort(); this.scales.push(_val); } private function _subentitiestreeFunc(input:ICustomDataInput) : void { var length:uint = input.readUnsignedShort(); for(var i:uint = 0; i < length; i++) { this._subentitiestree.addChild(this._subentitiesFunc); } } private function _subentitiesFunc(input:ICustomDataInput) : void { var _item:SubEntity = new SubEntity(); _item.deserialize(input); this.subentities.push(_item); } } }
package com.d_project.qrcode { /** * RSBlock * @author Kazuhiko Arase */ internal class RSBlock { private static var RS_BLOCK_TABLE : Array = [ // L // M // Q // H // 1 [1, 26, 19], [1, 26, 16], [1, 26, 13], [1, 26, 9], // 2 [1, 44, 34], [1, 44, 28], [1, 44, 22], [1, 44, 16], // 3 [1, 70, 55], [1, 70, 44], [2, 35, 17], [2, 35, 13], // 4 [1, 100, 80], [2, 50, 32], [2, 50, 24], [4, 25, 9], // 5 [1, 134, 108], [2, 67, 43], [2, 33, 15, 2, 34, 16], [2, 33, 11, 2, 34, 12], // 6 [2, 86, 68], [4, 43, 27], [4, 43, 19], [4, 43, 15], // 7 [2, 98, 78], [4, 49, 31], [2, 32, 14, 4, 33, 15], [4, 39, 13, 1, 40, 14], // 8 [2, 121, 97], [2, 60, 38, 2, 61, 39], [4, 40, 18, 2, 41, 19], [4, 40, 14, 2, 41, 15], // 9 [2, 146, 116], [3, 58, 36, 2, 59, 37], [4, 36, 16, 4, 37, 17], [4, 36, 12, 4, 37, 13], // 10 [2, 86, 68, 2, 87, 69], [4, 69, 43, 1, 70, 44], [6, 43, 19, 2, 44, 20], [6, 43, 15, 2, 44, 16] ]; private var totalCount : int; private var dataCount : int; public function RSBlock(totalCount : int, dataCount : int) { this.totalCount = totalCount; this.dataCount = dataCount; } public function getDataCount() : int { return dataCount; } public function getTotalCount() : int { return totalCount; } public static function getRSBlocks(typeNumber : int, errorCorrectLevel : int) : Array { var rsBlock : Array = getRsBlockTable(typeNumber, errorCorrectLevel); var length : int = Math.floor(rsBlock.length / 3); var list : Array = new Array(); for (var i : int = 0; i < length; i++) { var count : int = rsBlock[i * 3 + 0]; var totalCount : int = rsBlock[i * 3 + 1]; var dataCount : int = rsBlock[i * 3 + 2]; for (var j : int = 0; j < count; j++) { list.push(new RSBlock(totalCount, dataCount) ); } } return list; } private static function getRsBlockTable(typeNumber : int, errorCorrectLevel : int) : Array { try { switch(errorCorrectLevel) { case ErrorCorrectLevel.L : return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0]; case ErrorCorrectLevel.M : return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1]; case ErrorCorrectLevel.Q : return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2]; case ErrorCorrectLevel.H : return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3]; default : break; } } catch(e : Error) { } throw new Error("tn:" + typeNumber + "/ecl:" + errorCorrectLevel); } } }
/* Copyright 2007-2011 by the authors of asaplibrary, http://asaplibrary.org Copyright 2005-2007 by the authors of asapframework, http://asapframework.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.util.actionqueue { import org.asaplibrary.util.FramePulse; import flash.events.*; import flash.utils.getQualifiedClassName; import flash.utils.getTimer; /** A TimedAction is an Action that performs a function during a set time period. */ public class TimedAction extends Action implements ITimedAction { protected var mDuration : Number; /**< Duration of the animation in seconds. */ protected var mEffect : Function; /**< An effect function, for instance one of the fl.motion.easing methods. */ protected var mStart : Number = 1; /**< Percentage start value to get returned. */ protected var mEnd : Number = 0; /**< Percentage end value to get returned. */ protected var mRange : Number; protected var mPercentage : Number; protected var mValue : Number; protected var mLoop : Boolean; protected var mLoopCount : int; protected var mLoopCounter : int = 0; protected var mEndTime : Number; protected var mDurationFactor : Number; protected var mIsRunning : Boolean; protected var mDurationLeft : Number; /** Creates a new TimedAction. @param inMethod: function reference @param inDuration: (optional) duration of the time period in seconds; the duration may be set to 0 - the action will then last indefinite @param inUndoMethod: (optional) not implemented yet @param inUndoArgs: (optional) not implemented yet */ public function TimedAction(inMethod : Function, inDuration : Number = Number.NaN, inEffect : Function = null, inUndoMethod : Function = null, inUndoArgs : Array = null) { super(inMethod, null, inUndoMethod, inUndoArgs); mDuration = inDuration; mRange = mEnd - mStart; mEffect = inEffect; mIsRunning = false; } /** Stops the running action. @sends ActionEvent#STOPPED */ public function stop() : void { unRegister(); mIsRunning = false; dispatchEvent(new ActionEvent(ActionEvent.STOPPED, this)); } public function reset() : void { stop(); } /** Stops the running action and sends out a "finished" message. @sends ActionEvent#FINISHED */ public function finish() : void { unRegister(); mIsRunning = false; dispatchEvent(new ActionEvent(ActionEvent.FINISHED, this)); } /** Sets the looping state of the action. @param inState: true: the action is looping; default false */ public function setLoop(inState : Boolean) : void { mLoop = inState; } /** Sets the number of loops this action will perform. @param inLoopCount: the number of loops this action will perform; use 0 to loop indefinitely */ public function setLoopCount(inLoopCount : uint) : void { mLoop = true; mLoopCount = inLoopCount; } /** @exclude */ override public function toString() : String { return getQualifiedClassName(this) + "; duration=" + mDuration + "; start=" + mStart + "; end=" + mEnd; } /** @return True if the action loop state is set to true and the action is still running inside a loop; otherwise false */ public function doesLoop() : Boolean { if (mLoop) { if (mLoopCount == 0) return true; if (mLoopCounter <= mLoopCount) return true; return false; } return false; } /** @return True if the action is still running; otherwise false. */ override public function isRunning() : Boolean { return mIsRunning; } /** Starts invoking the action method. @return null. */ public override function run() : * { register(); var msduration : Number = mDuration * 1000; // translate to milliseconds mDurationFactor = 1 / msduration; mEndTime = getTimer() + msduration; mIsRunning = true; return null; } /** Pauses the action method. @param inContinueWhereLeftOff: (optional) whether the action should continue where it left off when the action is resumed */ public function pause(inContinueWhereLeftOff : Boolean = true) : void { unRegister(); if (inContinueWhereLeftOff) { mDurationLeft = mEndTime - getTimer(); } else { // remove old value mDurationLeft = Number.NaN; } } /** Resumes a paused action. */ public function resume() : void { if (!isNaN(mDurationLeft)) { mEndTime = getTimer() + mDurationLeft; } mIsRunning = true; register(); } /** Called each {@link FramePulse} event. Calls {@link #run} on the action method while the end time has not been reached. Calls {@link #finish} as soon as the end time has been reached. Calls {@link #stop} if the invoked method returns false. @param e: not used */ protected function step(e : Event) : void { if (!mIsRunning) return; var msNow : Number = getTimer(); if (mDuration != 0) { // calculate percentage (1 to 0) if (msNow < mEndTime) { mPercentage = (mEndTime - msNow) * mDurationFactor; } else { mPercentage = 0; } if (mEffect != null) { mValue = Number(mEffect(1 - mPercentage, mStart, mRange, 1)); } else { mValue = mEnd - (mPercentage * mRange); } } var result : Boolean = mMethod(mValue); if (mDuration != 0) { if (msNow >= mEndTime) { if (mLoop) { mLoopCounter++; } if (doesLoop()) { run(); } else { finish(); } } } // stop when the action returns false if (!result) { stop(); } } /** Registers to listen for {@link FramePulse} events. */ protected function register() : void { FramePulse.addEnterFrameListener(step); } /** Unregisters for {@link FramePulse} events. */ protected function unRegister() : void { FramePulse.removeEnterFrameListener(step); } } }
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2005-2007 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package flexlib.baseClasses { import flash.events.Event; import flash.events.MouseEvent; import mx.collections.ICollectionView; import mx.collections.IViewCursor; import mx.collections.CursorBookmark; import mx.controls.listClasses.IListItemRenderer; import mx.controls.menuClasses.IMenuDataDescriptor; import mx.controls.treeClasses.DefaultDataDescriptor; import mx.core.IUIComponent; import mx.core.mx_internal; import mx.events.FlexEvent; import mx.events.ListEvent; import mx.events.MenuEvent; import mx.managers.PopUpManager; import mx.controls.PopUpButton; import mx.controls.Menu; use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched when a user selects an item from the pop-up menu. * * @eventType mx.events.MenuEvent.ITEM_CLICK */ [Event(name="itemClick", type="mx.events.MenuEvent")] /** * The name of a CSS style declaration used by the dropdown menu. * This property allows you to control the appearance of the dropdown menu. * The default value sets the <code>fontWeight</code> to <code>normal</code> and * the <code>textAlign</code> to <code>left</code>. * * @default "popUpMenu" */ [Style(name="popUpStyleName", type="String", inherit="no")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name="toggle", kind="property")] [Exclude(name="selectedDisabledIcon", kind="style")] [Exclude(name="selectedDisabledSkin", kind="style")] [Exclude(name="selectedDownIcon", kind="style")] [Exclude(name="selectedDownSkin", kind="style")] [Exclude(name="selectedOverIcon", kind="style")] [Exclude(name="selectedOverSkin", kind="style")] [Exclude(name="selectedUpIcon", kind="style")] [Exclude(name="selectedUpSkin", kind="style")] //-------------------------------------- // Other metadata //-------------------------------------- //[IconFile("PopUpMenuButton.png")] [RequiresDataBinding(true)] /** * PopUpMenuButtonBase is a copy/paste version of the original PopUpMenuButton class in the Flex framework. * * <p>The only modifications made to this class were to change some properties and * methods from private to protected so we can override them in a subclass.</p> * * <p>The PopUpMenuButton control creates a PopUpButton control with a main * sub-button and a secondary sub-button. * Clicking on the secondary (right) sub-button drops down a menu that * can be popluated through a <code>dataProvider</code> property. * Unlike the Menu and MenuBar controls, the PopUpMenuButton control * supports only a single-level menu. This means that the menu cannot contain * cascading submenus.</p> * * <p>The main sub-button of the PopUpMenuButton control can have a * text label, an icon, or both on its face. * When a user selects an item from the drop-down menu or clicks * the main button of the PopUpMenuButton control, the control * dispatches an <code>itemClick</code> event. * When a user clicks the main button of the * control, the control also dispatches a <code>click</code> event. * You can customize the look of a PopUpMenuButton control.</p> * * <p>The PopUpMenuButton control has the following sizing * characteristics:</p> * <table class="innertable"> * <tr> * <th>Characteristic</th> * <th>Description</th> * </tr> * <tr> * <td>Default size</td> * <td>Sufficient to accommodate the label and any icon on * the main button, and the icon on the pop-up button. * The control does not reserve space for the menu.</td> * </tr> * <tr> * <td>Minimum size</td> * <td>0 pixels.</td> * </tr> * <tr> * <td>Maximum size</td> * <td>10000 by 10000.</td> * </tr> * </table> * * @mxml * * <p>The <code>&lt;mx:PopUpMenuButton&gt;</code> tag inherits all of the tag * attributes of its superclass, and adds the following tag attributes:</p> * * <pre> * &lt;mx:PopUpMenuButton * <strong>Properties</strong> * dataDescriptor="<i>instance of DefaultDataDescriptor</i>" * dataProvider="undefined" * iconField="icon" * iconFunction="undefined" * labelField="label" * labelFunction="undefined" * showRoot="false|true" * &nbsp; * <strong>Event</strong> * change=<i>No default</i> * /&gt; * </pre> * * * * @see mx.controls.Menu * @see mx.controls.MenuBar * * @tiptext Provides ability to pop up a menu and act as a button * @helpid 3441 */ public class PopUpMenuButtonBase extends PopUpButton { //include "../core/Version.as"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. */ public function PopUpMenuButtonBase() { super(); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private */ private var dataProviderChanged:Boolean = false; /** * @private */ private var labelSet:Boolean = false; /** * @private */ protected var popUpMenu:Menu = null; /** * @private */ private var selectedIndex:int = -1; /** * @private */ private var itemRenderer:IListItemRenderer = null; /** * @private */ private var explicitIcon:Class = null; /** * @private */ private var menuSelectedStyle:Boolean = false; //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- /** * A reference to the pop-up Menu object. * * <p>This property is read-only, and setting it has no effect. * Set the <code>dataProvider</code> property, instead. * (The write-only indicator appears in the syntax summary because the * property in the superclass is read-write and this class overrides * the setter with an empty implementation.)</p> */ override public function set popUp(value:IUIComponent):void { super.popUp = value; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // dataDescriptor //-------------------------------------------------------------------------- /** * @private * Storage for the dataDescriptor property. */ private var _dataDescriptor:IMenuDataDescriptor = new DefaultDataDescriptor(); /** * The data descriptor accesses and manipulates data in the data provider. * <p>When you specify this property as an attribute in MXML, you must * use a reference to the data descriptor, not the string name of the * descriptor. Use the following format for the property:</p> * * <pre>&lt;mx:PopUpMenuButton id="menubar" dataDescriptor="{new MyCustomDataDescriptor()}"/&gt;</pre> * * <p>Alternatively, you can specify the property in MXML as a nested * subtag, as the following example shows:</p> * * <pre>&lt;mx:PopUpMenuButton&gt; * &lt;mx:dataDescriptor&gt; * &lt;myCustomDataDescriptor&gt; * &lt;/mx:dataDescriptor&gt; * ...</pre> * * <p>The default value is an internal instance of the * DefaultDataDescriptor class.</p> */ public function get dataDescriptor():IMenuDataDescriptor { return IMenuDataDescriptor(_dataDescriptor); } /** * @private */ public function set dataDescriptor(value:IMenuDataDescriptor):void { _dataDescriptor = value; } //-------------------------------------------------------------------------- // dataProvider //-------------------------------------------------------------------------- /** * @private * Storage for dataProvider property. */ private var _dataProvider:Object = null; [Bindable("collectionChange")] [Inspectable(category="Data", defaultValue="null")] /** * DataProvider for popUpMenu. * * @default null */ public function get dataProvider():Object { if (popUpMenu) return Menu(popUpMenu).dataProvider; return _dataProvider; } /** * @private */ public function set dataProvider(value:Object):void { _dataProvider = value; dataProviderChanged = true; invalidateProperties(); } //-------------------------------------------------------------------------- // iconField //-------------------------------------------------------------------------- /** * @private * Storage for the iconField property. */ private var _iconField:String = "icon"; [Bindable("iconFieldChanged")] [Inspectable(category="Data", defaultValue="icon")] /** * Name of the field in the <code>dataProvider</code> Array that contains the icon to * show for each menu item. * The <code>iconFunction</code> property, if set, overrides this property. * * <p>The renderers will look in the data provider object for a property of * the name supplied as the iconField. If the value of the property is a * Class, it will instantiate that class and expect it to be an instance * of an IFlexDisplayObject. If the value of the property is a String, * it will look to see if a Class exists with that name in the application, * and if it can't find one, it will also look for a property on the * document with that name and expect that property to map to a Class.</p> * * If the data provider is an E4X XML object, you must set this property * explicitly; for example, use &#064;icon to specify the <code>icon</code> attribute. * * @default "icon" */ public function get iconField():String { return _iconField; } /** * @private */ public function set iconField(value:String):void { if (_iconField != value) { _iconField = value; if (popUpMenu) popUpMenu.iconField = _iconField; dispatchEvent(new Event("iconFieldChanged")); } } //-------------------------------------------------------------------------- // iconFunction //-------------------------------------------------------------------------- /** * @private * Storage for the iconFunction property. */ private var _iconFunction:Function; [Inspectable(category="Data")] /** * A function that determines the icon to display for each menu item. * If you omit this property, Flex uses the contents of the field or attribute * determined by the <code>iconField</code> property. * If you specify this property, Flex ignores any <code>iconField</code> * property value. * * By default the menu does not try to display icons with the text * in the rows. However, by specifying an icon function, you can specify * a Class for a graphic that will be created and displayed as an icon * in the row. * * <p>The iconFunction takes a single argument which is the item * in the data provider and returns a Class.</p> * * <blockquote> * <code>iconFunction(item:Object):Class</code> * </blockquote> * * @default null */ public function get iconFunction():Function { return _iconFunction; } /** * @private */ public function set iconFunction(value:Function):void { if (_iconFunction != value) { _iconFunction = value; if (popUpMenu) popUpMenu.iconFunction = _iconFunction; } } //-------------------------------------------------------------------------- // label //-------------------------------------------------------------------------- /** * @private * Storage for the label property. */ private var _label:String = ""; [Inspectable(category="General", defaultValue="")] /** * @private */ override public function set label(value:String):void { // labelSet is different from labelChanged as it is never unset. labelSet = true; _label = value; super.label = _label; } //-------------------------------------------------------------------------- // labelField //-------------------------------------------------------------------------- /** * @private * Storage for the labelField property. */ private var _labelField:String = "label"; [Bindable("labelFieldChanged")] [Inspectable(category="Data", defaultValue="label")] /** * Name of the field in the <code>dataProvider</code> Array that contains the text to * show for each menu item. * The <code>labelFunction</code> property, if set, overrides this property. * If the data provider is an Array of Strings, Flex uses each String * value as the label. * If the data provider is an E4X XML object, you must set this property * explicitly; for example, use &#064;label to specify the <code>label</code> attribute. * * @default "label" */ public function get labelField():String { return _labelField; } /** * @private */ public function set labelField(value:String):void { if (_labelField != value) { _labelField = value; if (popUpMenu) popUpMenu.labelField = _labelField; dispatchEvent(new Event("labelFieldChanged")); } } //-------------------------------------------------------------------------- // labelFunction //-------------------------------------------------------------------------- /** * @private * Storage for the labelFunction property. */ private var _labelFunction:Function; [Inspectable(category="Data")] /** * A function that determines the text to display for each menu item. * If you omit this property, Flex uses the contents of the field or attribute * determined by the <code>labelField</code> property. * If you specify this property, Flex ignores any <code>labelField</code> * property value. * * <p>If you specify this property, the label function must find the * appropriate field or fields and return a displayable string. * The <code>labelFunction</code> property is good for handling formatting * and localization.</p> * * <p>The label function must take a single argument which is the item * in the dataProvider and return a String.</p> * * <blockquote> * <code>labelFunction(item:Object):String</code> * </blockquote> * * @default null */ public function get labelFunction():Function { return _labelFunction; } /** * @private */ public function set labelFunction(value:Function):void { if (_labelFunction != value) { _labelFunction = value; if (popUpMenu) popUpMenu.labelFunction = _labelFunction; } } //-------------------------------------------------------------------------- // showRoot //-------------------------------------------------------------------------- /** * @private * Storage for the showRoot property. */ mx_internal var _showRoot:Boolean = true; /** * @private */ private var _showRootChanged:Boolean = false; [Inspectable(category="Data", enumeration="true,false", defaultValue="true")] /** * Specifies whether to display the top-level node or nodes of the data provider. * * If this is set to <code>false</code>, the control displays * only descendants of the first top-level node. * Any other top-level nodes are ignored. * You normally set this property to <code>false</code> for * E4X format XML data providers, where the top-level node is the document * object. * * @default true */ public function get showRoot():Boolean { return _showRoot; } /** * @private */ public function set showRoot(value:Boolean):void { if (_showRoot != value) { _showRoot = value; _showRootChanged = true; invalidateProperties(); } } //-------------------------------------------------------------------------- // // Overridden methods: UIComponent // //-------------------------------------------------------------------------- /** * @private */ override protected function commitProperties():void { if (dataProviderChanged && !popUpMenu) { // In general we shouldn't create the popUp until // they are actually popped up. However, in this case // the initial label, icon and action on the main button's // click are to be borrowed from the popped menu. // Moreover since PopUpMenuButton doesn't expose selectedIndex // selectedItem etc., one should be able to access them // prior to popping up the menu. getPopUp(); } if (_showRootChanged) { _showRootChanged = false; if (popUpMenu != null) popUpMenu.showRoot = _showRoot; invalidateDisplayList(); } if (popUpMenu && dataProviderChanged) { popUpMenu.dataProvider = _dataProvider; popUpMenu.validateNow(); if (dataProvider.length) { selectedIndex = 0; var cursor:IViewCursor = dataProvider.createCursor() cursor.seek(CursorBookmark.FIRST, 0); var item:* = cursor.current; // Set button label. if (labelSet) super.label = _label; else super.label = popUpMenu.itemToLabel(item); // Set button icon, setSafeIcon(popUpMenu.itemToIcon(item)); } else { selectedIndex = -1; if (labelSet) super.label = _label; else super.label = ""; clearStyle("icon"); } dataProviderChanged = false; } super.commitProperties(); } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); //style is actually set here already. if (styleProp == "icon" || styleProp == null || styleProp == "styleName" ) { if (menuSelectedStyle) { if (explicitIcon) { menuSelectedStyle = false; setStyle("icon", explicitIcon); } } else { explicitIcon = getStyle("icon"); } } } //-------------------------------------------------------------------------- // // Overridden methods: PopUpButton // //-------------------------------------------------------------------------- /** * @private */ override mx_internal function getPopUp():IUIComponent { super.getPopUp(); if (!popUpMenu || !super.popUp) { popUpMenu = new Menu(); popUpMenu.iconField = _iconField; popUpMenu.iconFunction = _iconFunction; popUpMenu.labelField = _labelField; popUpMenu.labelFunction = _labelFunction; popUpMenu.showRoot = _showRoot; popUpMenu.dataDescriptor = _dataDescriptor; popUpMenu.dataProvider = _dataProvider; popUpMenu.addEventListener(MenuEvent.ITEM_CLICK, menuChangeHandler); popUpMenu.addEventListener(FlexEvent.VALUE_COMMIT, menuValueCommitHandler); super.popUp = popUpMenu; // Add PopUp to PopUpManager here so that // commitProperties of Menu gets called even // before the PopUp is opened. This is // necessary to get the initial label and dp. PopUpManager.addPopUp(super.popUp, this, false); super.popUp.owner = this; } return popUpMenu; } //-------------------------------------------------------------------------- // // private helper methods // //-------------------------------------------------------------------------- /** * @private */ private function setSafeIcon(iconClass:Class):void { menuSelectedStyle = true; setStyle("icon", iconClass); menuSelectedStyle = false; } //-------------------------------------------------------------------------- // // Overridden event handlers: Button // //-------------------------------------------------------------------------- /** * @private */ override protected function clickHandler(event:MouseEvent):void { super.clickHandler(event); if (!overArrowButton(event)) menuClickHandler(event); } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function menuClickHandler(event:MouseEvent):void { if (selectedIndex >= 0) { var menuEvent:MenuEvent = new MenuEvent(MenuEvent.ITEM_CLICK); menuEvent.menu = popUpMenu; menuEvent.menu.selectedIndex = selectedIndex; var cursor:IViewCursor = dataProvider.createCursor(); cursor.seek(CursorBookmark.FIRST, selectedIndex); menuEvent.item = cursor.current menuEvent.itemRenderer = itemRenderer; menuEvent.index = selectedIndex; menuEvent.label = popUpMenu.itemToLabel(cursor.current); dispatchEvent(menuEvent); // Reset selection after the change event is dispatched // just like in a menu. popUpMenu.selectedIndex = -1; } } /** * @private */ protected function menuValueCommitHandler(event:FlexEvent):void { // Change label/icon if selectedIndex is changed programatically. if (popUpMenu.selectedIndex >= 0) { var cursor:IViewCursor = dataProvider.createCursor(); cursor.seek(CursorBookmark.FIRST, selectedIndex); selectedIndex = popUpMenu.selectedIndex; if (labelSet) super.label = _label; else super.label = popUpMenu.itemToLabel(cursor.current); setSafeIcon(popUpMenu.itemToIcon(cursor.current)); } } /** * @private */ protected function menuChangeHandler(event:MenuEvent):void { if (event.index >= 0) { var menuEvent:MenuEvent = new MenuEvent(MenuEvent.ITEM_CLICK); menuEvent.label = popUpMenu.itemToLabel(event.item); if (labelSet) super.label = _label; else super.label = popUpMenu.itemToLabel(event.item); setSafeIcon(popUpMenu.itemToIcon(event.item)); menuEvent.menu = popUpMenu; menuEvent.menu.selectedIndex = menuEvent.index = selectedIndex = event.index; menuEvent.item = event.item; itemRenderer = menuEvent.itemRenderer = event.itemRenderer; dispatchEvent(menuEvent); } } } }
/* Copyright (c) 2011 Taro Hanamura See LICENSE.txt for full license information. */ package org.typefest.time.tick { import flash.display.Bitmap; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import flash.utils.Dictionary; import org.typefest.core.Num; public class Tick extends EventDispatcher { ///// prop protected var _interval:Number = 0; protected var _base:Date = null; public function get interval():Number { return _interval } public function get base():Date { return new Date(_base.time) } ///// containers protected var _dict:Dictionary = null; protected var _items:Array = null; public function get length():int { return _items.length } ///// engine protected var _engine:IEventDispatcher = null; protected var _last:Date = null; public function get date():Date { if (active) { return new Date(_last.time); } else { return null; } } public function get position():Number { if (active) { return Num.loop(_last.time - _base.time, 0, _interval); } else { return NaN; } } ///// active public function get active():Boolean { return !!_engine } public function set active(bool:Boolean):void { if (bool && !_engine) { _last = new Date(); _engine = new Bitmap(); _engine.addEventListener(Event.ENTER_FRAME, _check, false, 0, true); } else if (!bool && _engine) { _last = null; _engine.removeEventListener(Event.ENTER_FRAME, _check, false); _engine = null; } } ///// arrays public function get keys():Array { var _:Array = []; for each (var item:TickItem in _items) { _.push(item.time); } return _; } public function get values():Array { var _:Array = []; for each (var item:TickItem in _items) { _.push(item.data); } return _; } public function get items():Array { var _:Array = []; for each (var item:TickItem in _items) { _.push(item.clone()); } return _; } //--------------------------------------- // constructor //--------------------------------------- public function Tick(interval:Number, base:Date = null) { super(); _interval = interval; _base = base || new Date(); _init(); } //--------------------------------------- // init //--------------------------------------- protected function _init():void { _dict = new Dictionary(); _items = []; } //--------------------------------------- // operations //--------------------------------------- public function set(time:Number, data:* = null):void { if (time < 0 || time >= _interval) { throw new ArgumentError("Out of range."); } del(time); var item:TickItem = new TickItem(time, data); var i:int; for (i = 0; i < _items.length; i++) { if (_items[i].time > time) { break } } _items.splice(i, 0, item); for (; i < _items.length; i++) { _dict[_items[i].time] = i; } } public function get(time:Number):* { if (time in _dict) { return _items[_dict[time]].data; } else { return undefined; } } public function del(time:Number):Boolean { if (time in _dict) { var i:int = _dict[time]; _items.splice(i, 1); for (; i < _items.length; i++) { _dict[_items[i].time] = i; } return delete _dict[time]; } else { return false; } } public function has(time:Number):Boolean { return time in _dict; } public function clear():void { _dict = new Dictionary(); _items = []; } //--------------------------------------- // each //--------------------------------------- public function each(fn:Function):void { for each (var item:TickItem in _items) { fn(item.time, item.data); } } //--------------------------------------- // check //--------------------------------------- protected function _check(e:Event):void { ///// now var now:Date = new Date(); var from:Number = Num.loop(_last.time - _base.time, 0, _interval); var to:Number = from + (now.time - _last.time); _last = now; ///// construct targets var loops:int = Math.ceil(to / _interval); var targets:Array = []; var i:int; var item:TickItem; var offset:Number; for (i = 0; i < loops; i++) { offset = _interval * i; for each (item in _items) { targets.push(new Target(item, item.time + offset)); } } ///// define start & end var start:int = targets.length; var end:int = targets.length; for (i = 0; i < targets.length; i++) { if (targets[i].altTime > from) { start = i; break; } } for (i = 0; i < targets.length; i++) { if (targets[i].altTime > to) { end = i; break; } } ///// dispatch var triggers:Array = targets.slice(start, end); if (triggers.length) { var items:Array = []; for each (var target:Target in triggers) { items.push(target.item); } dispatchEvent(new TickEvent( TickEvent.TICK, false, false, items, now, position )); } } } } import org.typefest.time.tick.TickItem; internal class Target extends Object { public var item:TickItem = null; public var altTime:Number = 0; public function Target(item:TickItem, altTime:Number) { this.item = item; this.altTime = altTime; } }
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2009 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package mx.automation.delegates.controls { import flash.display.DisplayObject; import flash.events.Event; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TextEvent; import flash.ui.Keyboard; import flash.utils.getTimer; import mx.automation.Automation; import mx.automation.AutomationIDPart; import mx.automation.IAutomationObject; import mx.automation.IAutomationObjectHelper; import mx.automation.events.AutomationRecordEvent; import mx.automation.events.ListItemSelectEvent; import mx.automation.events.TextSelectionEvent; import mx.controls.ComboBase; import mx.controls.ComboBox; import mx.controls.List; import mx.core.EventPriority; import mx.core.mx_internal; import mx.core.UIComponent; import mx.events.DropdownEvent; import mx.events.ScrollEvent; import mx.automation.AutomationManager; use namespace mx_internal; [Mixin] /** * * Defines methods and properties required to perform instrumentation for the * ComboBox control. * * @see mx.controls.ComboBox * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class ComboBoxAutomationImpl extends ComboBaseAutomationImpl { include "../../../core/Version.as"; //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- /** * @private * Registers the delegate class for a component class with automation manager. * * @param root The SystemManger of the application. */ public static function init(root:DisplayObject):void { Automation.registerDelegateClass(ComboBox, ComboBoxAutomationImpl); } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param obj The ComboBox to be automated. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function ComboBoxAutomationImpl(obj:ComboBox) { super(obj); obj.addEventListener(DropdownEvent.CLOSE, openCloseHandler, false, 0, true); obj.addEventListener(DropdownEvent.OPEN, openCloseHandler, false, 0, true); } /** * @private * storage for the owner component */ protected function get comboBox():ComboBox { return uiComponent as ComboBox; } /** * @private * Replays the event specified by the parameter if possible. * * @param interaction The event to replay. * * @return Whether or not a replay was successful. */ override public function replayAutomatableEvent(event:Event):Boolean { var completeTime:Number; var help:IAutomationObjectHelper = Automation.automationObjectHelper; var textReplayer:IAutomationObject = comboBox.getTextInput() as IAutomationObject; var aoDropDown:IAutomationObject = comboBox.dropdown as IAutomationObject; if (event is ListItemSelectEvent) { var result:Boolean = aoDropDown.replayAutomatableEvent(event); // selection closes the comboBox. // We need to wait for the dropDown to close. if (result) { completeTime = getTimer() + comboBox.getStyle("closeDuration"); help.addSynchronization(function():Boolean { return getTimer() >= completeTime; }); } return result; } else if (event is KeyboardEvent) { var keyEvent:KeyboardEvent = event as KeyboardEvent; if (comboBox.getTextInput() && comboBox.editable) { if (keyEvent.keyCode == Keyboard.UP || keyEvent.keyCode == Keyboard.DOWN || keyEvent.keyCode == Keyboard.PAGE_UP || keyEvent.keyCode == Keyboard.PAGE_DOWN) return help.replayKeyboardEvent(uiComponent, KeyboardEvent(event)); else return textReplayer.replayAutomatableEvent(event); } else { // if comboBox is closing due to either selection or escape we need to wait // and sync up if (keyEvent.keyCode == Keyboard.ENTER || keyEvent.keyCode == Keyboard.ESCAPE) { completeTime = getTimer() + comboBox.getStyle("closeDuration"); help.addSynchronization(function():Boolean { return getTimer() >= completeTime; }); } return help.replayKeyboardEvent(uiComponent, KeyboardEvent(event)); } } else if (event is DropdownEvent) { var cbdEvent:DropdownEvent = DropdownEvent(event); if (cbdEvent.triggerEvent is KeyboardEvent) { var kbEvent:KeyboardEvent = new KeyboardEvent(KeyboardEvent.KEY_DOWN); kbEvent.keyCode = (cbdEvent.type == DropdownEvent.OPEN ? Keyboard.DOWN : Keyboard.UP); kbEvent.ctrlKey = true; help.replayKeyboardEvent(uiComponent, kbEvent); } else //triggerEvent is MouseEvent { if ((cbdEvent.type == DropdownEvent.OPEN && !comboBox.isShowingDropdown) || (cbdEvent.type == DropdownEvent.CLOSE && comboBox.isShowingDropdown)) help.replayClick(comboBox.ComboDownArrowButton); } completeTime = getTimer() + comboBox.getStyle(cbdEvent.type == DropdownEvent.OPEN ? "openDuration" : "closeDuration"); help.addSynchronization(function():Boolean { return getTimer() >= completeTime; }); return true; } else if (comboBox.getTextInput() && (event is TextEvent || event is TextSelectionEvent) ) { return textReplayer.replayAutomatableEvent(event); } else if (event is ScrollEvent) { return aoDropDown.replayAutomatableEvent(event); } return super.replayAutomatableEvent(event); } /** * @private * Provide a set of properties that identify the child within * this container. These values should not change during the * lifespan of the application. * * @param child the child for which to provide the id. * @return a set of properties describing the child which can * later be used to resolve the component. */ override public function createAutomationIDPart(child:IAutomationObject):Object { var delegate:IAutomationObject = comboBox.dropdown as IAutomationObject; return delegate.createAutomationIDPart(child); } /** * @private */ override public function createAutomationIDPartWithRequiredProperties(child:IAutomationObject, properties:Array):Object { var delegate:IAutomationObject = comboBox.dropdown as IAutomationObject; if(delegate) return delegate.createAutomationIDPartWithRequiredProperties(child,properties); /* var delegateObj:Object = delegate as Object; if(delegateObj &&(delegateObj.hasOwnProperty("createAutomationIDPartWithRequiredProperties"))) return delegateObj.createAutomationIDPartWithRequiredProperties(child,properties); if(delegate && delegate.automationDelegate &&(delegate.automationDelegate.hasOwnProperty("createAutomationIDPartWithRequiredProperties"))) return delegate.automationDelegate.createAutomationIDPartWithRequiredProperties(child,properties); */ return null; } /**; * @private * * Resolve a child using the id provided. The id is a set * of properties as provided by createAutomationID. * * @param criteria a set of properties describing the child. * The criteria can contain regular expression values * resulting in multiple children being matched. * @return the an array of children that matched the criteria * or <tt>null</tt> if no children could not be resolved. */ override public function resolveAutomationIDPart(criteria:Object):Array { var delegate:IAutomationObject = comboBox.dropdown as IAutomationObject; return delegate.resolveAutomationIDPart(criteria); } /** * @private * Provides the automation object at the specified index. This list * should not include any children that are composites. * * @param index the index of the child to return * @return the child at the specified index. */ override public function getAutomationChildAt(index:int):IAutomationObject { var delegate:IAutomationObject = comboBox.dropdown as IAutomationObject; return delegate.getAutomationChildAt(index); } /** * @private */ override public function getAutomationChildren():Array { var delegate:IAutomationObject = comboBox.dropdown as IAutomationObject; return delegate.getAutomationChildren(); } /** * @private * Provides the number of automation children this container has. * This sum should not include any composite children, though * it does include those children not signficant within the * automation hierarchy. * * @return the number of automation children this container has. */ override public function get numAutomationChildren():int { if(comboBox.hasDropdown()) { var delegate:IAutomationObject = comboBox.dropdown as IAutomationObject; return delegate.numAutomationChildren; } return 0; } /** * @private * A matrix containing the automation values of all parts of the components. * Should be row-major (return value is an array of rows, each of which is * an array of "items"). * * @return A matrix containing the automation values of all parts of the components. */ override public function get automationTabularData():Object { var delegate:IAutomationObject = comboBox.dropdown as IAutomationObject; return delegate.automationTabularData; } /** * @private */ override protected function setupEditHandler():void { super.setupEditHandler(); var text:DisplayObject = comboBase.getTextInput() as DisplayObject; if (!text) return; // If comboBox is editable we setup a listener for the textInput control. if(comboBox.editable) text.addEventListener(KeyboardEvent.KEY_DOWN, textKeyDownHandler, false, EventPriority.DEFAULT+1); else text.removeEventListener(KeyboardEvent.KEY_DOWN, textKeyDownHandler, false); } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function openCloseHandler(event:DropdownEvent):void { var textInput:DisplayObject = comboBox.getTextInput() as DisplayObject; if (event.triggerEvent) recordAutomatableEvent(event); if (event.type == DropdownEvent.OPEN) { comboBox.dropdown.addEventListener(AutomationRecordEvent.RECORD, dropdown_recordHandler, false, 0, true); } else { if (comboBox.hasDropdown()) comboBox.dropdown.removeEventListener(AutomationRecordEvent.RECORD, dropdown_recordHandler); } } /** * @private */ private function dropdown_recordHandler(event:AutomationRecordEvent):void { var re:Event = event.replayableEvent; if ((re is ListItemSelectEvent || re is ScrollEvent) && event.target is List ) recordAutomatableEvent(event.replayableEvent, event.cacheable); } /** * @private * Keyboard events like up/down/page_up/page_down/enter are * recorded here. They are not recorded by textInput control but * we require them to be recorded. */ private function textKeyDownHandler(event:KeyboardEvent):void { // we do not record key events with modifiers // open/close events with ctrl key are recorded seperately. if (event.ctrlKey) return; // record keys which are of used for navigation in the dropdown list if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN || event.keyCode == Keyboard.PAGE_UP || event.keyCode == Keyboard.PAGE_DOWN || event.keyCode == Keyboard.ESCAPE || event.keyCode == Keyboard.ENTER) recordAutomatableEvent(event); } /** * @private */ override protected function keyDownHandler(event:KeyboardEvent):void { // if editable we have a different keydown handler if (comboBox.editable) return; // we do not record key events with modifiers if (event.ctrlKey) return; if(event.target == comboBox && event.keyCode != Keyboard.ENTER && event.keyCode != Keyboard.SPACE) recordAutomatableEvent(event); super.keyDownHandler(event); } /** * @private */ public function getItemsCount():int { if (comboBox.dataProvider) return comboBox.dataProvider.length; return 0; } } }
/////////////////////////////////////////////////////////////////////////// // Copyright (c) 2011 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// package widgets.Geoprocessing.parameters { import com.esri.ags.tasks.supportClasses.LinearUnit; import widgets.Geoprocessing.supportClasses.UnitMappingUtil; public class LinearUnitParameter extends BaseParameter { //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- private function linearUnitString():String { return _defaultValue.distance + ":" + UnitMappingUtil.toPrettyUnits(_defaultValue.units); } //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- //---------------------------------- // defaultValue //---------------------------------- private var _defaultValue:LinearUnit; override public function get defaultValue():Object { return _defaultValue; } override public function set defaultValue(value:Object):void { _defaultValue = new LinearUnit(value.distance, value.units); } //---------------------------------- // type //---------------------------------- override public function get type():String { return GPParameterTypes.LINEAR_UNIT; } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- override public function defaultValueFromString(description:String):void { var linearUnitTokens:Array = description.split(':'); _defaultValue = new LinearUnit(linearUnitTokens[0], UnitMappingUtil.toEsriUnits((linearUnitTokens[1]))); } } }
//------------------------------------------------------------------------------ // Copyright (c) 2009-2013 the original author or authors. All Rights Reserved. // // NOTICE: You are permitted to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. //------------------------------------------------------------------------------ package robotlegs.bender.extensions.viewProcessorMap.utils { import org.swiftsuspenders.Injector; /** * Avoids view reflection by using a provided map * of property names to dependency values */ public class PropertyValueInjector { /*============================================================================*/ /* Private Properties */ /*============================================================================*/ private var _valuesByPropertyName:Object; /*============================================================================*/ /* Constructor */ /*============================================================================*/ /** * Creates a Value Property Injection Processor * * <code> * new PropertyValueInjector({ * userService: myUserService, * userPM: myUserPM * }) * </code> * * @param valuesByPropertyName A map of property names to dependency values */ public function PropertyValueInjector(valuesByPropertyName:Object) { _valuesByPropertyName = valuesByPropertyName; } /*============================================================================*/ /* Public Functions */ /*============================================================================*/ /** * @private */ public function process(view:Object, type:Class, injector:Injector):void { for (var propName:String in _valuesByPropertyName) { view[propName] = _valuesByPropertyName[propName]; } } /** * @private */ public function unprocess(view:Object, type:Class, injector:Injector):void { } } }
package nid.xfl.compiler.swf.data.actions { import nid.xfl.compiler.swf.SWFData; public class Action implements IAction { protected var _code:uint; protected var _length:uint; public function Action(code:uint, length:uint) { _code = code; _length = length; } public function get code():uint { return _code; } public function get length():uint { return _length; } public function parse(data:SWFData):void { // Do nothing. Many Actions don't have a payload. // For the ones that have one we override this method. } public function publish(data:SWFData):void { write(data); } public function clone():IAction { return new Action(code, length); } protected function write(data:SWFData, body:SWFData = null):void { data.writeUI8(code); if (code >= 0x80) { if (body != null && body.length > 0) { _length = body.length; data.writeUI16(_length); data.writeBytes(body); } else { _length = 0; throw(new Error("Action body null or empty.")); } } else { _length = 0; } } public function toString(indent:uint = 0):String { return "[Action] Code: " + _code.toString(16) + ", Length: " + _length; } } }
package com.swipethrough { import flash.utils.setTimeout; public class AnimationBase extends RewindableMovieClip { private var lastTime : uint; private var pauseTimeout : uint; public function AnimationBase() { lastTime = 0; /*this.addEventListener(MouseEvent.CLICK, this.didClick);*/ // addEventListener(Event.ENTER_FRAME, updateDirection); } public function pause(duration:uint) : void { trace("duration: " + duration); stop(); this.pauseTimeout = setTimeout(this.play, duration); } } }
/* * Temple Library for ActionScript 3.0 * Copyright © MediaMonks B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by MediaMonks B.V. * 4. Neither the name of MediaMonks B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY MEDIAMONKS B.V. ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL MEDIAMONKS B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Note: This license does not apply to 3rd party classes inside the Temple * repository with their own license! */ package temple.codecomponents.graphics { import temple.codecomponents.style.CodeStyle; /** * @author Thijs Broerse */ public class CodeBackground extends CodeGraphicsRectangle { public function CodeBackground(width:Number = 14, height:Number = 14) { super(width, height, CodeStyle.backgroundColor, CodeStyle.backgroundAlpha); filters = CodeStyle.backgroundFilters; } } }
/** * --------------------------------------------------------------------------- * Copyright (C) 2008 0x6e6562 * * 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.amqp { import flash.utils.IDataInput; import flash.utils.ByteArray; public interface LongString { function length():int; /** * Get the content stream. * Repeated calls to this function return the same stream, * which may not support rewind. * @return An input stream the reads the content * @throws IOException */ function getStream():IDataInput; /** * Get the content as a byte array. * Repeated calls to this function return the same array. * This function will fail if getContentLength() > Integer.MAX_VALUE * throwing an IllegalStateException. * @return the content as an array * @throws IOException */ function getBytes():ByteArray; } }
/** * * AirMobileFramework * * https://github.com/AbsolutRenal * * Copyright (c) 2012 AbsolutRenal (Renaud Cousin). All rights reserved. * * This ActionScript source code is free. * You can redistribute and/or modify it in accordance with the * terms of the accompanying Simplified BSD License Agreement. * * This framework also include some third party free Classes like Greensocks Tweening engine, Text and Fonts manager, Audio manager, Stats manager (by mrdoob) **/ package fwk.components { import com.greensock.easing.Cubic; import flash.geom.Rectangle; import com.greensock.TweenNano; import com.greensock.easing.Strong; import flash.display.DisplayObject; import flash.display.MovieClip; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.events.TransformGestureEvent; /** * @author renaud.cousin */ public class SlidingPanel extends Sprite { // ON STAGE public var slidingBackground:Sprite; public var bottomBtn:MovieClip; // END ON STAGE private var _isOpenned:Boolean = false; private var buttonDown:Boolean = false; private var _contentObj:DisplayObject; private var closedY:int; private var _buttonVisibility:Boolean; private var _openByDraging:Boolean = true; private var isDragging:Boolean; private var dragingOffset:int = NaN; private var previousPos:int = NaN; public function SlidingPanel(contentObj:DisplayObject) { addEventListener(Event.ADDED_TO_STAGE, onAddedToStage); _contentObj = contentObj; } //---------------------------------------------------------------------- // E V E N T S //---------------------------------------------------------------------- private function onAddedToStage(event:Event):void { removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); if(_contentObj != null) addChild(_contentObj); defineClosedY(); y = closedY; } private function onStageDown(event:MouseEvent):void { if(event.stageY < bottomBtn.height && !_isOpenned){ event.stopImmediatePropagation(); if(!_buttonVisibility){ TweenNano.killTweensOf(this); TweenNano.to(this, .2, {y:-slidingBackground.height + bottomBtn.height, ease:Strong.easeOut}); } onDown(null); } else if(_isOpenned){ event.stopImmediatePropagation(); } } private function onStageUp(event:MouseEvent):void { buttonDown = false; bottomBtn.background.gotoAndStop(1); if(isDragging){ stopDrag(); isDragging = false; removeEventListener(Event.ENTER_FRAME, checkDraggingOffset); // XXX if(dragingOffset > 0){ _isOpenned = true; TweenNano.to(this, .3, {y:0, ease:Cubic.easeInOut}); } else { _isOpenned = false; TweenNano.to(this, .3, {y:closedY, ease:Cubic.easeInOut}); } previousPos = NaN; dragingOffset = NaN; return; } if(_isOpenned){ if(event != null) event.stopPropagation(); // TweenNano.killTweensOf(this); // TweenNano.to(this, .4, {y:0, ease:Strong.easeOut}); } else { TweenNano.killTweensOf(this); TweenNano.to(this, .3, {y:closedY, ease:Strong.easeIn}); } } private function onDown(event:MouseEvent):void { buttonDown = true; bottomBtn.background.gotoAndStop(2); if(_openByDraging){ isDragging = true; previousPos = y; startDrag(false, new Rectangle(x, -slidingBackground.height + bottomBtn.height, 0, slidingBackground.height)); addEventListener(Event.ENTER_FRAME, checkDraggingOffset); } } private function checkDraggingOffset(event:Event):void { dragingOffset = y - previousPos; previousPos = y; } private function onSwipe(event:TransformGestureEvent):void{ if(buttonDown && event.offsetY == 1){ open(); } else if(buttonDown && event.offsetY == -1){ // onStageUp(null); close(); } else if(!_isOpenned){ // TweenNano.killTweensOf(this); // TweenNano.to(this, .2, {y:-debugBackground.height, ease:Strong.easeOut}); } } //---------------------------------------------------------------------- // P R I V A T E //---------------------------------------------------------------------- private function open():void{ if(!_isOpenned){ onStageUp(null); _isOpenned = true; TweenNano.killTweensOf(this); TweenNano.to(this, .4, {y:0, ease:Strong.easeOut}); } } private function defineClosedY():void { if(_buttonVisibility){ closedY = -slidingBackground.height + bottomBtn.height; } else { closedY = -slidingBackground.height; } } //---------------------------------------------------------------------- // P U B L I C //---------------------------------------------------------------------- public function close():void{ if(_isOpenned){ onStageUp(null); _isOpenned = false; TweenNano.killTweensOf(this); TweenNano.to(this, .4, {y:closedY, ease:Strong.easeIn}); } } public function active():void{ bottomBtn.addEventListener(MouseEvent.MOUSE_DOWN, onDown); stage.addEventListener(MouseEvent.MOUSE_DOWN, onStageDown); stage.addEventListener(MouseEvent.MOUSE_UP, onStageUp); if(!_openByDraging) stage.addEventListener(TransformGestureEvent.GESTURE_SWIPE, onSwipe); } public function desactive():void{ bottomBtn.removeEventListener(MouseEvent.MOUSE_DOWN, onDown); stage.removeEventListener(MouseEvent.MOUSE_DOWN, onStageDown); stage.removeEventListener(MouseEvent.MOUSE_UP, onStageUp); if(!_openByDraging) stage.removeEventListener(TransformGestureEvent.GESTURE_SWIPE, onSwipe); } public function resizePanel(w:int, h:int):void{ slidingBackground.width = w; slidingBackground.height = h; defineClosedY(); if(isOpenned) y = 0; else y = closedY; bottomBtn.y = h; bottomBtn.background.width = w; bottomBtn.circles.x = w / 2; } //---------------------------------------------------------------------- // G E T T E R / S E T T E R //---------------------------------------------------------------------- public function get isOpenned():Boolean { return _isOpenned; } public function set buttonAlwaysVisible(visibility:Boolean):void{ _buttonVisibility = visibility; } public function set openByDraging(value:Boolean):void{ _openByDraging = value; } } }
// Copyright 2020 Cadic AB. All Rights Reserved. // @URL https://github.com/Temaran/Feather // @Author Fredrik Lindh [Temaran] (temaran@gmail.com) //////////////////////////////////////////////////////////// #if !RELEASE import Feather.DebugInterface.FeatherDebugInterfaceOperation; import Feather.FeatherSettings; import Feather.FeatherUtils; struct FAbilitySystemDebugSaveState { bool bShowingDebug; }; // Adds a more user friendly way of interacting with the ability system debugger. class UFeatherAbilitySystemDebugOperation : UFeatherDebugInterfaceOperation { default OperationTags.Add(n"GAS"); UPROPERTY(Category = "Ability System Debug", NotEditable) UFeatherCheckBoxStyle ShowAbilitySystemDebugCheckBox; UPROPERTY(Category = "Ability System Debug", NotEditable) UFeatherButtonStyle PreviousActorButton; UPROPERTY(Category = "Ability System Debug", NotEditable) UFeatherButtonStyle NextActorButton; UPROPERTY(Category = "Ability System Debug", NotEditable) UFeatherButtonStyle ChangeCategoryButton; UFUNCTION(BlueprintOverride) void Execute(FString Context) { ShowAbilitySystemDebugCheckBox.SetIsChecked(!ShowAbilitySystemDebugCheckBox.IsChecked()); } UFUNCTION(BlueprintOverride) void SaveOperationToString(FString& InOutSaveString) { FAbilitySystemDebugSaveState SaveState; SaveState.bShowingDebug = ShowAbilitySystemDebugCheckBox.IsChecked(); FJsonObjectConverter::AppendUStructToJsonObjectString(SaveState, InOutSaveString); } UFUNCTION(BlueprintOverride) void LoadOperationFromString(const FString& InSaveString) { FAbilitySystemDebugSaveState SaveState; if(FJsonObjectConverter::JsonObjectStringToUStruct(InSaveString, SaveState)) { if(SaveState.bShowingDebug) { // Only call this if it's actually saved to be on. Since this is using the hidden state in-engine, it's a bit wonky. ShowAbilitySystemDebugCheckBox.SetIsChecked(true); } } } UFUNCTION(BlueprintOverride) void Reset() { Super::Reset(); if(ShowAbilitySystemDebugCheckBox.IsChecked()) { ShowAbilitySystemDebugCheckBox.SetIsChecked(false); } } UFUNCTION(BlueprintOverride) void ConstructOperation(UNamedSlot OperationRoot) { FMargin LeftPadding; LeftPadding.Left = 10.0f; FMargin RightPadding; RightPadding.Right = 10.0f; // Setup widget hierarchy UHorizontalBox HorizontalLayout = Cast<UHorizontalBox>(ConstructWidget(UHorizontalBox::StaticClass())); OperationRoot.SetContent(HorizontalLayout); ShowAbilitySystemDebugCheckBox = CreateCheckBox(); UHorizontalBoxSlot CheckBoxSlot = HorizontalLayout.AddChildToHorizontalBox(ShowAbilitySystemDebugCheckBox); ShowAbilitySystemDebugCheckBox.GetCheckBoxWidget().OnCheckStateChanged.AddUFunction(this, n"OnShowAbilityCheckBoxStateChanged"); CheckBoxSlot.SetPadding(RightPadding); CheckBoxSlot.SetVerticalAlignment(EVerticalAlignment::VAlign_Center); UFeatherTextBlockStyle CheckBoxLabel = CreateTextBlock(); UHorizontalBoxSlot LabelSlot = HorizontalLayout.AddChildToHorizontalBox(CheckBoxLabel); FSlateChildSize FillSize; FillSize.SizeRule = ESlateSizeRule::Fill; LabelSlot.SetSize(FillSize); LabelSlot.SetVerticalAlignment(EVerticalAlignment::VAlign_Center); CheckBoxLabel.GetTextWidget().SetText(FText::FromString("Show Ability System Debug")); CheckBoxLabel.GetTextWidget().SetToolTipText(FText::FromString("Toggles the engine ability system debugger")); PreviousActorButton = CreateButton(); HorizontalLayout.AddChildToHorizontalBox(PreviousActorButton); PreviousActorButton.GetButtonWidget().OnClicked.AddUFunction(this, n"OnPreviousActor"); UFeatherTextBlockStyle PreviousActorText = CreateTextBlock(); PreviousActorButton.GetButtonWidget().SetContent(PreviousActorText); PreviousActorButton.SetToolTipText(FText::FromString("Go to the previous actor")); PreviousActorText.GetTextWidget().SetText(FText::FromString(" ^ ")); NextActorButton = CreateButton(); UHorizontalBoxSlot NextActorSlot = HorizontalLayout.AddChildToHorizontalBox(NextActorButton); NextActorButton.GetButtonWidget().OnClicked.AddUFunction(this, n"OnNextActor"); NextActorSlot.SetPadding(LeftPadding); UFeatherTextBlockStyle NextActorText = CreateTextBlock(); NextActorButton.GetButtonWidget().SetContent(NextActorText); NextActorButton.SetToolTipText(FText::FromString("Go to the next actor")); NextActorText.GetTextWidget().SetText(FText::FromString(" ^ ")); NextActorButton.SetRenderTransformAngle(180.0f); ChangeCategoryButton = CreateButton(); UHorizontalBoxSlot ChangeCategorySlot = HorizontalLayout.AddChildToHorizontalBox(ChangeCategoryButton); ChangeCategoryButton.GetButtonWidget().OnClicked.AddUFunction(this, n"OnChangeCategory"); ChangeCategorySlot.SetPadding(LeftPadding); UFeatherTextBlockStyle ChangeCategoryText = CreateTextBlock(); ChangeCategoryButton.GetButtonWidget().SetContent(ChangeCategoryText); ChangeCategoryButton.SetToolTipText(FText::FromString("Cycle the debugging category")); ChangeCategoryText.GetTextWidget().SetText(FText::FromString(" Category ")); } UFUNCTION() void OnShowAbilityCheckBoxStateChanged(bool bNewCheckState) { System::ExecuteConsoleCommand(bNewCheckState ? "ShowDebug AbilitySystem" : "ShowDebug"); SaveSettings(); } UFUNCTION() void OnPreviousActor() { System::ExecuteConsoleCommand("AbilitySystem.Debug.PrevTarget"); } UFUNCTION() void OnNextActor() { System::ExecuteConsoleCommand("AbilitySystem.Debug.NextTarget"); } UFUNCTION() void OnChangeCategory() { System::ExecuteConsoleCommand("AbilitySystem.Debug.NextCategory"); } }; #endif // RELEASE
/* --------------------------------------------------------- XMLadapter class modify the parseData method if your XML specification differs --------------------------------------------------------- */ XMLadapter=function(owner){ this.owner=owner; this.firstCall=true; } XMLadapter.prototype.loadAndParseData=function(d){ trace("loading XML "+d); RelationBrowserApp.setState("loading XML"); this.XMLObj = new XML(); this.XMLObj.ignoreWhite = true; this.XMLObj.load(d); this.XMLObj.owner = this; this.XMLObj.onLoad = function(success){ trace("XML loaded.") if(success){ this.owner.parseData(); } else{ this.owner.owner.setState("error"); } }; } XMLadapter.prototype.loadMoreData=function (url){ this.firstCall=false; RelationBrowserApp.setState("loading XML"); trace("--> loading XML "+url); this.XMLObj = new XML(); this.XMLObj.ignoreWhite = true; // this.XMLObj.load(url); this.XMLObj.owner = this; this.XMLObj.onLoad = function(success){ if(success){ trace("... XML loaded."); this.owner.parseData(); } else{ this.owner.owner.setState("error"); } }; }; _mainTimeLine=this; XMLadapter.prototype.parseData=function(){ trace ("starting to parse the data"); RelationBrowserApp.setState("XMLloaded"); // get root node var indexNode = this.XMLObj.byName ("RelationViewerData"); // temporarily store node types var nodeTypesDict={}; // collect different node types var nodeTypes=[]; // collect node objects in dictionary by id // (and the _type property determines class and symbol ID!) var nodesResult = {}; // collect relation objects (_type property determines class and symbol ID) var relationsResult = []; // get settings if(this.firstCall){ var settingsNode=indexNode.byName("Settings"); var o=settingsNode.makeObj(); RelationBrowserSettings.adoptProps(o); RelationBrowserSettings.maxRadius=Number(o.maxRadius); RelationBrowserSettings.defaultRadius=Number(o.defaultRadius); // startID handed over by embed will override XML startID if(startID){ RelationBrowserSettings.startID=startID; } // copy settings into corresponding class objects (Relation, Node, etc.) var o=settingsNode.firstChild.byName("RelationTypes").makeObj().children; for (var i in o){ _root[o[i]._type].adoptProps(o[i]); } var o=settingsNode.firstChild.byName("NodeTypes").makeObj().children; for (var i in o){ _root[o[i]._type].adoptProps(o[i]); nodeTypes.push(o[i]._type); } } // get nodes var nodes=indexNode.byName("Nodes").makeObj().children; for(var i in nodes) { //trace(i+" "+nodes[i].name); nodesResult[nodes[i].id] = nodes[i]; nodeTypesDict[nodes[i]._type]=true; } // get relations // relationsResult=indexNode.byName("Relations").makeObj().children; for (var i in indexNode.childNodes){ //trace(i+" "+indexNode.childNodes[i].nodeName); if(indexNode.childNodes[i].nodeName=="Relations"){ var list=indexNode.childNodes[i].childNodes; for(var j in list) relationsResult.push(list[j].makeObj()); } } trace(relationsResult.length+" relations parsed."); // free space delete(this.XMLObj); if(this.firstCall){ RelationBrowserApp.startDisplay(nodesResult, relationsResult, nodeTypes); } else { gModel.onMoreDataLoaded(nodesResult, relationsResult); } }
//------------------------------------------------------------------------------ // Copyright (c) 2009-2013 the original author or authors. All Rights Reserved. // // NOTICE: You are permitted to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. //------------------------------------------------------------------------------ package robotlegs.bender.extensions.eventDispatcher { import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import robotlegs.bender.extensions.eventDispatcher.impl.LifecycleEventRelay; import robotlegs.bender.framework.api.IContext; import robotlegs.bender.framework.api.IExtension; /** * This extension maps an IEventDispatcher into a context's injector. */ public class EventDispatcherExtension implements IExtension { /*============================================================================*/ /* Private Properties */ /*============================================================================*/ private var _context:IContext; private var _eventDispatcher:IEventDispatcher; private var _lifecycleRelay:LifecycleEventRelay; /*============================================================================*/ /* Constructor */ /*============================================================================*/ /** * Creates an Event Dispatcher Extension * @param eventDispatcher Optional IEventDispatcher instance to share */ public function EventDispatcherExtension(eventDispatcher:IEventDispatcher = null) { _eventDispatcher = eventDispatcher || new EventDispatcher(); } /*============================================================================*/ /* Public Functions */ /*============================================================================*/ /** * @inheritDoc */ public function extend(context:IContext):void { _context = context; _context.injector.map(IEventDispatcher).toValue(_eventDispatcher); _context.beforeInitializing(configureLifecycleEventRelay); _context.afterDestroying(destroyLifecycleEventRelay); } /*============================================================================*/ /* Private Functions */ /*============================================================================*/ private function configureLifecycleEventRelay():void { _lifecycleRelay = new LifecycleEventRelay(_context, _eventDispatcher); } private function destroyLifecycleEventRelay():void { _lifecycleRelay.destroy(); } } }
package com.percentjuice.utils.timelineWrappers.builder { import com.percentjuice.utils.timelineWrappers.ITimelineWrapperQueueSetDefault; public interface ITimelineWrapperFinish { function build():ITimelineWrapperQueueSetDefault; } }
package { import core.GameCore; import flash.desktop.NativeApplication; import flash.events.Event; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.ui.Multitouch; import flash.ui.MultitouchInputMode; import scene.LobbyScene; import starling.core.Starling; import org.gestouch.core.Gestouch; import org.gestouch.input.NativeInputAdapter; import org.gestouch.extensions.starling.StarlingDisplayListAdapter; import org.gestouch.extensions.starling.StarlingTouchHitTester import starling.display.DisplayObject; import utils.SqliteUtil; /** * ... * @author Max */ public class Main extends Sprite { private var _starling:Starling; public function Main():void { stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.addEventListener(Event.DEACTIVATE, deactivate); // touch or gesture? Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; // entry point // new to AIR? please read *carefully* the readme.txt files! //GameCore.container = this; GameCore.CONTAINER = this; _starling = new Starling(GameCore, stage); _starling.start(); Gestouch.inputAdapter = new NativeInputAdapter(stage); Gestouch.addDisplayListAdapter(DisplayObject, new StarlingDisplayListAdapter()); Gestouch.addTouchHitTester(new StarlingTouchHitTester(_starling), -1); } private function deactivate(e:Event):void { // make sure the app behaves well (or exits) when in background SqliteUtil.updateHP(LobbyScene.HP, LobbyScene.RECOVERTIME, (new Date()).time); NativeApplication.nativeApplication.exit(); } } }
package ldmAs { import flash.display.InteractiveObject; import flash.display.MovieClip; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.media.Sound; import flash.media.SoundChannel; import flash.utils.getDefinitionByName; import com.greensock.TweenLite; import com.greensock.easing.Back; import com.greensock.easing.Linear; import com.effect.CardEffect; import flash.geom.Point; import flash.filters.GlowFilter; import flash.filters.BitmapFilterQuality; /** * ... * @author 厉得明 */ public class DanciGame extends Sprite { private var currentPage:int = 1; private var pageNum:int = 5;//每页的数量 private var maxPage:int; private var pageIndex:int; private var tempPageIndex:int; private var myPrevBtn:InteractiveObject; private var myNextBtn:InteractiveObject; private var mySoundChannel:SoundChannel; private var currentSoundBtn:MovieClip; private var list:Array; private var curItem:MovieClip; private var frameArr:Array; private var effect:MovieClip; private var filter:GlowFilter; public function DanciGame() { frameArr=new Array(); init(); } private function init():void { initFrameArr(); myPrevBtn = this["prevBtn"] as InteractiveObject; myNextBtn = this["nextBtn"] as InteractiveObject; var myBoxGroup:MovieClip = this["boxGroup"] as MovieClip; myBoxGroup.mouseEnabled = false; pageNum = myBoxGroup.numChildren / 2;//每页个数 var myBox:MovieClip = myBoxGroup.getChildAt(0) as MovieClip; maxPage = Math.ceil(myBox.totalFrames / pageNum);//页数 effect=new CardEffect(); addChild(effect); effect.visible=false; effect.gotoAndStop(1); filter= new GlowFilter(0xFFD528); filter.blurX = 2; filter.blurY = 2; filter.strength = 255; filter.quality = BitmapFilterQuality.MEDIUM; filter.knockout = false; list = []; var i:int; var it0:MovieClip,it1:MovieClip; var startFrame:int; startFrame = (currentPage - 1) * pageNum + 1; for (i= 0; i < pageNum; i++) { it0 = myBoxGroup["item" + i + "0"]; it1 = myBoxGroup["item" + i + "1"]; it0["zhedang"].mouseEnabled=false; it1["zhedang"].mouseEnabled=false; it0.oldx = it0.x; it0.oldy = it0.y; it1.oldx = it1.x; it1.oldy = it1.y; list.push([it0,it1]); } initItems(); (myPrevBtn as MovieClip).gotoAndStop(3); (myPrevBtn as MovieClip).buttonMode=true; (myNextBtn as MovieClip).buttonMode=true; myBoxGroup.addEventListener(MouseEvent.CLICK, panelClickHandler); myPrevBtn.addEventListener(MouseEvent.CLICK, prevPageHandler); myNextBtn.addEventListener(MouseEvent.CLICK, nextPageHandler); } private function initFrameArr():void { var myBoxGroup:MovieClip = this["boxGroup"] as MovieClip; var myBox:MovieClip = myBoxGroup.getChildAt(0) as MovieClip; var num:int = myBox.totalFrames; var i:int; for (i= 1; i <= num; i++) { frameArr.push(i); } } private function initItems():void { var startFrame:int; startFrame = (currentPage - 1) * pageNum; var arr1:Array = frameArr.slice(startFrame,startFrame + pageNum); var arr2:Array = arr1.slice(); arr1 = randomArr5(arr1); arr2 = randomArr5(arr2); var i:int; for (i= 0; i < pageNum; i++) { list[i][0]["zhedang"].visible=false; list[i][1]["zhedang"].visible=false; list[i][0].gotoAndStop(arr1[i]); list[i][1].gotoAndStop(arr2[i]); list[i][0].x = list[i][0].oldx; list[i][0].y = list[i][0].oldy; list[i][1].x = list[i][1].oldx; list[i][1].y = list[i][1].oldy; } } private function randomArr5(arr:Array):Array { var outputArr:Array = arr.slice(); outputArr.sort(function():int{return Math.random()>.5?1:-1}); return outputArr; } private function panelClickHandler(e:MouseEvent):void { var tname:String = e.target.name; tname = tname.substr(0,2); if (tname=="it") { if (curItem) { curItem.filters=[]; var num:String = e.target.name.substr(-1,1); if (curItem!=e.target && curItem.currentFrame==e.target.currentFrame) { if (num=="1") { TweenLite.to(e.target, 0.3, {x:curItem.x+103,y:curItem.y,ease:Linear.easeOut,onComplete:onComplete, onCompleteParams:[e.target,curItem]}); } else { TweenLite.to(curItem, 0.3, {x:e.target.x+103,y:e.target.y,ease:Linear.easeOut,onComplete:onComplete, onCompleteParams:[curItem,e.target]}); } } } curItem = e.target as MovieClip; curItem.filters=[filter]; } else if (tname=="so") { var myClickSoundBtn:MovieClip = e.target as MovieClip; var frameId:int = (myClickSoundBtn.parent as MovieClip).currentFrame; currentSoundBtn = myClickSoundBtn; soundBtnClickHandler(frameId); } } private function onComplete(item:MovieClip,item2:MovieClip):void { currentSoundBtn = item["soundBtn"]; soundBtnClickHandler(item.currentFrame); item["zhedang"].visible=true; item2["zhedang"].visible=true; effect.visible=true; var pt:Point=new Point(item2.x,item2.y); pt=item2.parent.localToGlobal(pt); pt=this.globalToLocal(pt); effect.x=pt.x+119; effect.y=pt.y+55.85; effect.card.item0.gotoAndStop(item.currentFrame); effect.card.item1.gotoAndStop(item.currentFrame); effect.gotoAndPlay(1); effect.addFrameScript(effect.totalFrames - 1, onFrameEnd); curItem.filters=[]; } private function onFrameEnd():void { effect.visible=false; effect.gotoAndStop(1); } private function prevPageHandler(evt:MouseEvent):void { stopSound(); (myNextBtn as MovieClip).gotoAndStop(1); if (currentPage <= 1) { (myPrevBtn as MovieClip).gotoAndStop(3); currentPage=1; } else if(currentPage==2) { currentPage--; (myPrevBtn as MovieClip).gotoAndStop(3); initItems(); } else { currentPage--; initItems(); } /* var frameId:int = pageIndex * (currentPage-2)+1; var myBoxGroup:MovieClip = this["boxGroup"] as MovieClip; for (var i:int = 0; i < myBoxGroup.numChildren; i++) { var myBox:MovieClip = myBoxGroup.getChildAt(i) as MovieClip; myBox.gotoAndStop(frameId + i); var myTxtMask:MovieClip = myBox.getChildByName("txtMask") as MovieClip; myTxtMask.gotoAndStop(1); if(currentPage == maxPage&&i>=tempPageIndex)myBox.visible = true; }*/ } private function nextPageHandler(evt:MouseEvent):void { stopSound(); (myPrevBtn as MovieClip).gotoAndStop(1); if (currentPage>=maxPage) { currentPage=maxPage; (myNextBtn as MovieClip).gotoAndStop(3); } else if(currentPage==maxPage-1) { currentPage++; (myNextBtn as MovieClip).gotoAndStop(3); initItems(); } else { currentPage++; initItems(); } /*var myBoxGroup:MovieClip = this["boxGroup"] as MovieClip; for (var i:int = 0; i < myBoxGroup.numChildren; i++) { var myBox:MovieClip = myBoxGroup.getChildAt(i) as MovieClip; myBox.gotoAndStop(frameId + i); var myTxtMask:MovieClip = myBox.getChildByName("txtMask") as MovieClip; myTxtMask.gotoAndStop(1); if (currentPage==maxPage&&i >= tempPageIndex) myBox.visible = false; }*/ } private function soundBtnClickHandler(frameId:int):void { stopSound(); var soundId:String = frameId < 10?String("Sound0" + frameId):String("Sound" + frameId); var SoundClass:Class = getDefinitionByName(soundId) as Class; var mySound:Sound = new SoundClass() as Sound; currentSoundBtn.gotoAndStop(2); mySoundChannel = mySound.play(); mySoundChannel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler); } private function txtMaskClickHandler(evt:MouseEvent):void { var myClickTxtmask:MovieClip = evt.target as MovieClip; if (myClickTxtmask.currentFrame == 1) { myClickTxtmask.gotoAndStop(2); } else { myClickTxtmask.gotoAndStop(1); } } private function stopSound():void { if (currentSoundBtn) { currentSoundBtn.gotoAndStop(1); } if (mySoundChannel) { mySoundChannel.stop(); mySoundChannel.removeEventListener(Event.SOUND_COMPLETE, soundCompleteHandler); } } private function soundCompleteHandler(evt:Event):void { currentSoundBtn.gotoAndStop(1); mySoundChannel.removeEventListener(Event.SOUND_COMPLETE, soundCompleteHandler); } } }
package uieditor.editor.util { import starling.display.Quad; public class DrawUtil { public static function makeLine( x1 : Number, y1 : Number, x2 : Number, y2 : Number ) : Quad { var len : Number = MathUtil.distance( x1, y1, x2, y2 ); if ( len == 0 ) { len = 1; } var quad : Quad = new Quad( len, 1, 0xff0000 ); quad.pivotY = quad.height * 0.5; quad.x = x1; quad.y = y1; quad.rotation = Math.atan2( y2 - y1, x2 - x1 ); return quad; } } }
// ================================================================================================= // // Starling Framework // Copyright 2011 Gamua OG. 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 starling.events { import flash.geom.Matrix; import flash.geom.Point; import starling.core.starling_internal; import starling.display.DisplayObject; import starling.utils.MatrixUtil; import starling.utils.formatString; use namespace starling_internal; /** A Touch object contains information about the presence or movement of a finger * or the mouse on the screen. * * <p>You receive objects of this type from a TouchEvent. When such an event is triggered, you can * query it for all touches that are currently present on the screen. One Touch object contains * information about a single touch. A touch object always moves through a series of * TouchPhases. Have a look at the TouchPhase class for more information.</p> * * <strong>The position of a touch</strong> * * <p>You can get the current and previous position in stage coordinates with the corresponding * properties. However, you'll want to have the position in a different coordinate system * most of the time. For this reason, there are methods that convert the current and previous * touches into the local coordinate system of any object.</p> * * @see TouchEvent * @see TouchPhase */ public class Touch { private var mID:int; private var mGlobalX:Number; private var mGlobalY:Number; private var mPreviousGlobalX:Number; private var mPreviousGlobalY:Number; private var mTapCount:int; private var mPhase:String; private var mTarget:DisplayObject; private var mTimestamp:Number; private var mPressure:Number; private var mWidth:Number; private var mHeight:Number; private var mBubbleChain:Vector.<EventDispatcher>; /** Helper object. */ private static var sHelperMatrix:Matrix = new Matrix(); /** Creates a new Touch object. */ public function Touch(id:int, globalX:Number, globalY:Number, phase:String, target:DisplayObject) { mID = id; mGlobalX = mPreviousGlobalX = globalX; mGlobalY = mPreviousGlobalY = globalY; mTapCount = 0; mPhase = phase; mTarget = target; mPressure = mWidth = mHeight = 1.0; mBubbleChain = new <EventDispatcher>[]; updateBubbleChain(); } /** Converts the current location of a touch to the local coordinate system of a display * object. If you pass a 'resultPoint', the result will be stored in this point instead * of creating a new object.*/ public function getLocation(space:DisplayObject, resultPoint:Point=null):Point { if (resultPoint == null) resultPoint = new Point(); space.base.getTransformationMatrix(space, sHelperMatrix); return MatrixUtil.transformCoords(sHelperMatrix, mGlobalX, mGlobalY, resultPoint); } /** Converts the previous location of a touch to the local coordinate system of a display * object. If you pass a 'resultPoint', the result will be stored in this point instead * of creating a new object.*/ public function getPreviousLocation(space:DisplayObject, resultPoint:Point=null):Point { if (resultPoint == null) resultPoint = new Point(); space.base.getTransformationMatrix(space, sHelperMatrix); return MatrixUtil.transformCoords(sHelperMatrix, mPreviousGlobalX, mPreviousGlobalY, resultPoint); } /** Returns the movement of the touch between the current and previous location. * If you pass a 'resultPoint', the result will be stored in this point instead * of creating a new object. */ public function getMovement(space:DisplayObject, resultPoint:Point=null):Point { if (resultPoint == null) resultPoint = new Point(); getLocation(space, resultPoint); var x:Number = resultPoint.x; var y:Number = resultPoint.y; getPreviousLocation(space, resultPoint); resultPoint.setTo(x - resultPoint.x, y - resultPoint.y); return resultPoint; } /** Indicates if the target or one of its children is touched. */ public function isTouching(target:DisplayObject):Boolean { return mBubbleChain.indexOf(target) != -1; } /** Returns a description of the object. */ public function toString():String { return formatString("Touch {0}: globalX={1}, globalY={2}, phase={3}", mID, mGlobalX, mGlobalY, mPhase); } /** Creates a clone of the Touch object. */ public function clone():Touch { var clone:Touch = new Touch(mID, mGlobalX, mGlobalY, mPhase, mTarget); clone.mPreviousGlobalX = mPreviousGlobalX; clone.mPreviousGlobalY = mPreviousGlobalY; clone.mTapCount = mTapCount; clone.mTimestamp = mTimestamp; clone.mPressure = mPressure; clone.mWidth = mWidth; clone.mHeight = mHeight; return clone; } // helper methods private function updateBubbleChain():void { if (mTarget) { var length:int = 1; var element:DisplayObject = mTarget; mBubbleChain.length = 1; mBubbleChain[0] = element; while ((element = element.parent) != null) mBubbleChain[int(length++)] = element; } else { mBubbleChain.length = 0; } } // properties /** The identifier of a touch. '0' for mouse events, an increasing number for touches. */ public function get id():int { return mID; } /** The x-position of the touch in stage coordinates. */ public function get globalX():Number { return mGlobalX; } /** The y-position of the touch in stage coordinates. */ public function get globalY():Number { return mGlobalY; } /** The previous x-position of the touch in stage coordinates. */ public function get previousGlobalX():Number { return mPreviousGlobalX; } /** The previous y-position of the touch in stage coordinates. */ public function get previousGlobalY():Number { return mPreviousGlobalY; } /** The number of taps the finger made in a short amount of time. Use this to detect * double-taps / double-clicks, etc. */ public function get tapCount():int { return mTapCount; } /** The current phase the touch is in. @see TouchPhase */ public function get phase():String { return mPhase; } /** The display object at which the touch occurred. */ public function get target():DisplayObject { return mTarget; } /** The moment the touch occurred (in seconds since application start). */ public function get timestamp():Number { return mTimestamp; } /** A value between 0.0 and 1.0 indicating force of the contact with the device. * If the device does not support detecting the pressure, the value is 1.0. */ public function get pressure():Number { return mPressure; } /** Width of the contact area. * If the device does not support detecting the pressure, the value is 1.0. */ public function get width():Number { return mWidth; } /** Height of the contact area. * If the device does not support detecting the pressure, the value is 1.0. */ public function get height():Number { return mHeight; } // internal methods /** @private * Dispatches a touch event along the current bubble chain (which is updated each time * a target is set). */ starling_internal function dispatchEvent(event:TouchEvent):void { if (mTarget) event.dispatch(mBubbleChain); } /** @private */ starling_internal function get bubbleChain():Vector.<EventDispatcher> { return mBubbleChain.concat(); } /** @private */ starling_internal function setTarget(value:DisplayObject):void { mTarget = value; updateBubbleChain(); } /** @private */ starling_internal function setPosition(globalX:Number, globalY:Number):void { mPreviousGlobalX = mGlobalX; mPreviousGlobalY = mGlobalY; mGlobalX = globalX; mGlobalY = globalY; } /** @private */ starling_internal function setSize(width:Number, height:Number):void { mWidth = width; mHeight = height; } /** @private */ starling_internal function setPhase(value:String):void { mPhase = value; } /** @private */ starling_internal function setTapCount(value:int):void { mTapCount = value; } /** @private */ starling_internal function setTimestamp(value:Number):void { mTimestamp = value; } /** @private */ starling_internal function setPressure(value:Number):void { mPressure = value; } } }
package game.manager { import com.singleton.Singleton; import game.net.data.IData; import game.net.data.vo.BattleVo; import org.osflash.signals.ISignal; import org.osflash.signals.Signal; public class CommandSet { private var _set : Vector.<IData>; private var _currentIndex : int; private var _lenght : int; private var _copySet : Vector.<IData>; public var onSkip : ISignal = new Signal(); public function init(battleCommands : Vector.<IData>) : void { _set = battleCommands; _copySet = _set.concat(); _currentIndex = 0; _lenght = _set.length; } public function replay() : void { _set = _copySet.concat(); _currentIndex = 0; _lenght = _set.length; } public function pop() : BattleVo { if (_currentIndex >= _lenght) return null; var command : BattleVo = _set[_currentIndex++] as BattleVo; if (_currentIndex >= 5) { onSkip.dispatch(); } return command; } public function getCommand() : BattleVo { if (_currentIndex >= _lenght) return null; var command : BattleVo = _set[_currentIndex] as BattleVo; return command; } private var end_count : int = -1; public function getEndCount() : int { return 30; if (end_count == -1) return BattleVo(_set[_set.length - 2]).bout; else return end_count; } public function getIndexCount() : int { var command : BattleVo = getCommand(); return command ? command.bout : -1; } public function get originalLen() : int { return _lenght; } public function get lenght() : int { return _lenght - 1 - _currentIndex; } public function get currentIndex() : int { return _currentIndex; } public static function get instance() : CommandSet { return Singleton.getInstance(CommandSet) as CommandSet; } } }
package io.decagames.rotmg.fame { import com.company.assembleegameclient.objects.ObjectLibrary; import com.company.assembleegameclient.parameters.Parameters; import com.company.assembleegameclient.ui.tooltip.TextToolTip; import flash.utils.Dictionary; import io.decagames.rotmg.characterMetrics.tracker.CharactersMetricsTracker; import io.decagames.rotmg.fame.data.FameTracker; import io.decagames.rotmg.fame.data.TotalFame; import io.decagames.rotmg.fame.data.bonus.FameBonus; import io.decagames.rotmg.fame.data.bonus.FameBonusConfig; import io.decagames.rotmg.ui.buttons.BaseButton; import io.decagames.rotmg.ui.buttons.SliceScalingButton; import io.decagames.rotmg.ui.popups.signals.ClosePopupSignal; import io.decagames.rotmg.ui.texture.TextureParser; import io.decagames.rotmg.utils.date.TimeSpan; import kabam.rotmg.core.model.PlayerModel; import kabam.rotmg.core.signals.HideTooltipsSignal; import kabam.rotmg.core.signals.ShowTooltipSignal; import kabam.rotmg.text.view.stringBuilder.LineBuilder; import kabam.rotmg.text.view.stringBuilder.StaticStringBuilder; import kabam.rotmg.text.view.stringBuilder.StringBuilder; import kabam.rotmg.tooltips.HoverTooltipDelegate; import kabam.rotmg.ui.model.HUDModel; import robotlegs.bender.bundles.mvcs.Mediator; public class FameContentPopupMediator extends Mediator { public function FameContentPopupMediator() { super(); } [Inject] public var view:FameContentPopup; [Inject] public var closePopupSignal:ClosePopupSignal; [Inject] public var showTooltipSignal:ShowTooltipSignal; [Inject] public var hideTooltipSignal:HideTooltipsSignal; [Inject] public var fameTracker:FameTracker; [Inject] public var player:PlayerModel; [Inject] public var metrics:CharactersMetricsTracker; [Inject] public var hudModel:HUDModel; private var closeButton:SliceScalingButton; private var toolTip:TextToolTip = null; private var hoverTooltipDelegate:HoverTooltipDelegate; private var totalFame:TotalFame; private var bonuses:Dictionary; private var bonusesList:Vector.<FameBonus>; private var characterID:int; override public function initialize():void { var _loc3_:* = null; var _loc2_:* = null; this.closeButton = new SliceScalingButton(TextureParser.instance.getSliceScalingBitmap("UI", "close_button")); this.closeButton.clickSignal.addOnce(this.onClose); this.view.header.addButton(this.closeButton, "right_button"); this.characterID = this.view.characterId == -1 ? this.hudModel.gameSprite.gsc_.charId_ : int(this.view.characterId); this.totalFame = this.fameTracker.getCurrentTotalFame(this.characterID); this.bonuses = this.totalFame.bonuses; this.bonusesList = new Vector.<FameBonus>(); var _loc4_:String = ""; if (!this.player.getCharacterById(this.characterID)) { _loc4_ = ""; } else { _loc4_ = this.player.getCharacterById(this.characterID).bornOn(); } this.showInfo(); this.view.fameOnDeath = this.totalFame.currentFame; if (this.view.characterId == -1) { _loc3_ = this.hudModel.gameSprite.map.player_; this.view.setCharacterData(this.totalFame.baseFame, _loc3_.name_, _loc3_.level_, ObjectLibrary.typeToDisplayId_[_loc3_.objectType_], _loc4_, _loc3_.getFamePortrait(200)); } else { _loc2_ = this.player.getCharacterById(this.characterID); this.view.setCharacterData(this.totalFame.baseFame, _loc2_.name(), _loc2_.level(), ObjectLibrary.typeToDisplayId_[_loc2_.objectType()], _loc4_, _loc2_.getIcon(100)); } this.toolTip = new TextToolTip(3552822, 10197915, "Fame calculation", "Refreshes when returning to the Nexus or main menu.", 230); this.hoverTooltipDelegate = new HoverTooltipDelegate(); this.hoverTooltipDelegate.setShowToolTipSignal(this.showTooltipSignal); this.hoverTooltipDelegate.setHideToolTipsSignal(this.hideTooltipSignal); this.hoverTooltipDelegate.setDisplayObject(this.view.infoButton); this.hoverTooltipDelegate.tooltip = this.toolTip; this.showTooltipSignal.add(this.onShowTooltip); Parameters.data["clicked_on_fame_ui"] = true; } override public function destroy():void { this.closeButton.dispose(); this.hoverTooltipDelegate = null; this.toolTip = null; this.showTooltipSignal.remove(this.onShowTooltip); } public function getTotalDungeonCompleted():int { var _loc2_:int = 0; var _loc1_:int = 21; while (_loc1_ <= 52) { _loc2_ = _loc2_ + this.metrics.getCharacterStat(this.characterID, _loc1_); _loc1_++; } return this.metrics.getCharacterStat(this.characterID, 13) + this.metrics.getCharacterStat(this.characterID, 14) + this.metrics.getCharacterStat(this.characterID, 15) + this.metrics.getCharacterStat(this.characterID, 16) + this.metrics.getCharacterStat(this.characterID, 17) + this.metrics.getCharacterStat(this.characterID, 18) + _loc2_; } private function onShowTooltip(param1:TextToolTip):void { var _loc2_:StringBuilder = param1.titleText_.getStringBuilder(); if (this.fameTracker.metrics.lastUpdate && _loc2_ is LineBuilder && LineBuilder(_loc2_).key == "Fame calculation") { param1.setTitle(new StaticStringBuilder("Updated " + TimeSpan.distanceOfTimeInWords(this.fameTracker.metrics.lastUpdate, new Date(), true) + ".")); } } private function onClose(param1:BaseButton):void { this.closePopupSignal.dispatch(this.view); } private function getBonusValue(param1:int):int { if (!this.totalFame.bonuses[param1]) { return 0; } return this.totalFame.bonuses[param1].fameAdded; } private function showCompletedDungeons():void { var _loc1_:* = null; var _loc3_:Vector.<StatsLine> = new Vector.<StatsLine>(); this.view.addDungeonLine(new StatsLine("Dungeons", "", "", 2)); _loc3_.push(new DungeonLine("Pirate Cave", "Pirate Cave", this.metrics.getCharacterStat(this.characterID, 13) + "")); _loc3_.push(new DungeonLine("Undead Lair", "Undead Lair", this.metrics.getCharacterStat(this.characterID, 14) + "")); _loc3_.push(new DungeonLine("Abyss of Demons", "Abyss of Demons", this.metrics.getCharacterStat(this.characterID, 15) + "")); _loc3_.push(new DungeonLine("Snake Pit", "Snake Pit", this.metrics.getCharacterStat(this.characterID, 16) + "")); _loc3_.push(new DungeonLine("Spider Den", "Spider Den", this.metrics.getCharacterStat(this.characterID, 17) + "")); _loc3_.push(new DungeonLine("Sprite World", "Sprite World", this.metrics.getCharacterStat(this.characterID, 18) + "")); _loc3_.push(new DungeonLine("Tomb of the Ancients", "Tomb of the Ancients", this.metrics.getCharacterStat(this.characterID, 21) + "")); _loc3_.push(new DungeonLine("Ocean Trench", "Ocean Trench", this.metrics.getCharacterStat(this.characterID, 22) + "")); _loc3_.push(new DungeonLine("Forbidden Jungle", "Forbidden Jungle", this.metrics.getCharacterStat(this.characterID, 23) + "")); _loc3_.push(new DungeonLine("Manor of the Immortals", "Manor of the Immortals", this.metrics.getCharacterStat(this.characterID, 24) + "")); _loc3_.push(new DungeonLine("Forest Maze", "Forest Maze", this.metrics.getCharacterStat(this.characterID, 25) + "")); _loc3_.push(new DungeonLine("Lair of Draconis", "Lair of Draconis", this.metrics.getCharacterStat(this.characterID, 26) + this.metrics.getCharacterStat(this.characterID, 46) + "")); _loc3_.push(new DungeonLine("Haunted Cemetery", "Haunted Cemetery", this.metrics.getCharacterStat(this.characterID, 28) + "")); _loc3_.push(new DungeonLine("Cave of a Thousand Treasures", "Cave of A Thousand Treasures", this.metrics.getCharacterStat(this.characterID, 29) + "")); _loc3_.push(new DungeonLine("Mad Lab", "Mad Lab", this.metrics.getCharacterStat(this.characterID, 30) + "")); _loc3_.push(new DungeonLine("Davy Jones\' Locker", "Davy Jones\' Locker", this.metrics.getCharacterStat(this.characterID, 31) + "")); _loc3_.push(new DungeonLine("Ice Cave", "Ice Cave", this.metrics.getCharacterStat(this.characterID, 34) + "")); _loc3_.push(new DungeonLine("Deadwater Docks", "Deadwater Docks", this.metrics.getCharacterStat(this.characterID, 35) + "")); _loc3_.push(new DungeonLine("The Crawling Depths", "The Crawling Depths", this.metrics.getCharacterStat(this.characterID, 36) + "")); _loc3_.push(new DungeonLine("Woodland Labyrinth", "Woodland Labyrinth", this.metrics.getCharacterStat(this.characterID, 37) + "")); _loc3_.push(new DungeonLine("Battle for the Nexus", "Battle for the Nexus", this.metrics.getCharacterStat(this.characterID, 38) + "")); _loc3_.push(new DungeonLine("The Shatters", "The Shatters", this.metrics.getCharacterStat(this.characterID, 39) + "")); _loc3_.push(new DungeonLine("Belladonna\'s Garden", "Belladonna\'s Garden", this.metrics.getCharacterStat(this.characterID, 40) + "")); _loc3_.push(new DungeonLine("Puppet Master\'s Theatre", "Puppet Master\'s Theatre", this.metrics.getCharacterStat(this.characterID, 41) + "")); _loc3_.push(new DungeonLine("Toxic Sewers", "Toxic Sewers", this.metrics.getCharacterStat(this.characterID, 42) + "")); _loc3_.push(new DungeonLine("The Hive", "The Hive", this.metrics.getCharacterStat(this.characterID, 43) + "")); _loc3_.push(new DungeonLine("Mountain Temple", "Mountain Temple", this.metrics.getCharacterStat(this.characterID, 44) + "")); _loc3_.push(new DungeonLine("The Nest", "The Nest", this.metrics.getCharacterStat(this.characterID, 45) + "")); _loc3_.push(new DungeonLine("Lost Halls", "Lost Halls", this.metrics.getCharacterStat(this.characterID, 47) + "")); _loc3_.push(new DungeonLine("Cultist Hideout", "Cultist Hideout", this.metrics.getCharacterStat(this.characterID, 48) + "")); _loc3_.push(new DungeonLine("The Void", "The Void", this.metrics.getCharacterStat(this.characterID, 49) + "")); _loc3_.push(new DungeonLine("Puppet Master\'s Encore", "Puppet Master\'s Encore", this.metrics.getCharacterStat(this.characterID, 50) + "")); _loc3_.push(new DungeonLine("Lair of Shaitan", "Lair of Shaitan", this.metrics.getCharacterStat(this.characterID, 51) + "")); _loc3_.push(new DungeonLine("Parasite Chambers", "Parasite Chambers", this.metrics.getCharacterStat(this.characterID, 52) + "")); _loc3_.push(new DungeonLine("Magic Woods", "Magic Woods", this.metrics.getCharacterStat(this.characterID, 53) + "")); _loc3_.push(new DungeonLine("Cnidarian Reef", "Cnidarian Reef", this.metrics.getCharacterStat(this.characterID, 54) + "")); _loc3_.push(new DungeonLine("Secluded Thicket", "Secluded Thicket", this.metrics.getCharacterStat(this.characterID, 55) + "")); _loc3_.push(new DungeonLine("Cursed Library", "Cursed Library", this.metrics.getCharacterStat(this.characterID, 56) + "")); _loc3_.push(new DungeonLine("Fungal Cavern", "Fungal Cavern", this.metrics.getCharacterStat(this.characterID, 57) + "")); _loc3_.push(new DungeonLine("Crystal Cavern", "Crystal Cavern", this.metrics.getCharacterStat(this.characterID, 58) + "")); _loc3_.push(new DungeonLine("Ancient Ruins", "Ancient Ruins", this.metrics.getCharacterStat(this.characterID, 59) + "")); _loc3_ = _loc3_.sort(this.dungeonNameSort); var _loc2_:* = _loc3_; var _loc6_:int = 0; var _loc5_:* = _loc3_; for each(_loc1_ in _loc3_) { this.view.addDungeonLine(_loc1_); } } private function dungeonNameSort(param1:StatsLine, param2:StatsLine):int { if (param1.labelText > param2.labelText) { return 1; } return -1; } private function showStats():void { var _loc1_:* = 0; if (this.metrics.getCharacterStat(this.characterID, 1) > 0 && this.metrics.getCharacterStat(this.characterID, 0) > 0) { _loc1_ = this.metrics.getCharacterStat(this.characterID, 1) / this.metrics.getCharacterStat(this.characterID, 0) * 100; } this.view.addStatLine(new StatsLine("Statistics", "", "", 2)); this.view.addStatLine(new StatsLine("Shots Fired", this.metrics.getCharacterStat(this.characterID, 0).toString(), "The total number of shots fired by this character.", 1)); this.view.addStatLine(new StatsLine("Shots Hit", this.metrics.getCharacterStat(this.characterID, 1).toString(), "The total number of enemy hitting shots fired by this character.", 1)); this.view.addStatLine(new StatsLine("Potions Drunk", this.metrics.getCharacterStat(this.characterID, 5).toString(), "The number of potions this character has consumed.", 1)); this.view.addStatLine(new StatsLine("Abilities Used", this.metrics.getCharacterStat(this.characterID, 2).toString(), "The number of times this character used their abilities.", 1)); this.view.addStatLine(new StatsLine("Teleported", this.metrics.getCharacterStat(this.characterID, 4).toString(), "The number of times this character has teleported.", 1)); this.view.addStatLine(new StatsLine("Dungeons Completed", this.getTotalDungeonCompleted().toString(), "The number of dungeons completed by this character.", 1)); this.view.addStatLine(new StatsLine("Monster Kills", this.metrics.getCharacterStat(this.characterID, 6).toString(), "Total number of monsters killed by this character.", 1)); this.view.addStatLine(new StatsLine("God Kills", this.metrics.getCharacterStat(this.characterID, 8).toString(), "Total number of Gods killed by this character.", 1)); this.view.addStatLine(new StatsLine("Oryx Kills", this.metrics.getCharacterStat(this.characterID, 11).toString(), "Total number of Oryx kills for this character.", 1)); this.view.addStatLine(new StatsLine("Monster Assists", this.metrics.getCharacterStat(this.characterID, 7).toString(), "Total number of monster kills assisted by this character.", 1)); this.view.addStatLine(new StatsLine("God Assists", this.metrics.getCharacterStat(this.characterID, 9).toString(), "Total number of God kills assisted by this character.", 1)); this.view.addStatLine(new StatsLine("Party Level Ups", this.metrics.getCharacterStat(this.characterID, 19).toString(), "Total number of level ups assisted by this character.", 1)); this.view.addStatLine(new StatsLine("Quests Completed", this.metrics.getCharacterStat(this.characterID, 12).toString(), "Total number of quests completed by this character.", 1)); this.view.addStatLine(new StatsLine("Cube Kills", this.metrics.getCharacterStat(this.characterID, 10).toString(), "Total number of Cube Enemies killed by this character.", 1)); this.view.addStatLine(new StatsLine("Accuracy", _loc1_.toFixed(2) + "%", "", 1)); this.view.addStatLine(new StatsLine("Tiles Seen", this.metrics.getCharacterStat(this.characterID, 3).toString(), "", 1)); this.view.addStatLine(new StatsLine("Minutes Active", this.metrics.getCharacterStat(this.characterID, 20).toString(), "Time spent actively defeating Oryx\'s minions.", 1)); } private function sortBonusesByLevel(param1:FameBonus, param2:FameBonus):int { if (param1.level > param2.level) { return 1; } return -1; } private function sortBonusesByFame(param1:FameBonus, param2:FameBonus):int { if (param1.fameAdded > param2.fameAdded) { return -1; } return 1; } private function showBonuses():void { var i:int = 1; while (i <= 14) { var bonusConfig:FameBonus = this.totalFame.bonuses[i]; if (bonusConfig == null) { this.bonusesList.push(FameBonusConfig.getBonus(i)); } else { this.bonusesList.push(bonusConfig); } i = Number(i) + 1; } bonusConfig = this.totalFame.bonuses[16]; if (bonusConfig == null) { this.bonusesList.push(FameBonusConfig.getBonus(16)); } else { this.bonusesList.push(bonusConfig); } i = 18; while (i <= 22) { bonusConfig = this.totalFame.bonuses[i]; if (bonusConfig == null) { this.bonusesList.push(FameBonusConfig.getBonus(i)); } else { this.bonusesList.push(bonusConfig); } i = Number(i) + 1; } if (this.view.characterId == -1) { var level:int = this.hudModel.gameSprite.map.player_.level_; } else { level = this.player.getCharacterById(this.characterID).level(); } this.bonusesList = this.bonusesList.sort(this.sortBonusesByLevel); var unlocked:Vector.<FameBonus> = this.bonusesList.filter(function (param1:FameBonus, param2:int, param3:Vector.<FameBonus>):Boolean { return level >= param1.level; }); unlocked = unlocked.sort(this.sortBonusesByFame); var locked:Vector.<FameBonus> = this.bonusesList.filter(function (param1:FameBonus, param2:int, param3:Vector.<FameBonus>):Boolean { return level < param1.level; }); this.bonusesList = unlocked.concat(locked); this.view.addStatLine(new StatsLine("Bonuses", "", "", 2)); for each(var bonus:FameBonus in this.bonusesList) { this.view.addStatLine(new StatsLine(LineBuilder.getLocalizedStringFromKey("FameBonus." + bonus.name), bonus.fameAdded.toString(), LineBuilder.getLocalizedStringFromKey("FameBonus." + bonus.name + "Description") + "\n" + LineBuilder.getLocalizedStringFromKey("FameBonus.LevelRequirement", {"level": bonus.level}), 0, level < bonus.level)); } } private function showInfo():void { this.showStats(); this.showBonuses(); this.showCompletedDungeons(); } } }
// Decompiled by AS3 Sorcerer 6.08 // www.as3sorcerer.com //com.company.assembleegameclient.objects.TextureDataFactory package com.company.assembleegameclient.objects { public class TextureDataFactory { public function create(_arg_1:XML):TextureData { return (new TextureDataConcrete(_arg_1)); } } }//package com.company.assembleegameclient.objects
///////////////////////////////////////////////////////////////////////////////////// // // Simplified BSD License // ====================== // // Copyright 2013-2014 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.utils.constants { // ----------------------------------------------------------- // MetadataConstant.as // ----------------------------------------------------------- /** * @author Pascal ECHEMANN * @version 1.0.1, 05/07/2013 20:18 * @see http://www.flashapi.org/ */ /** * The <code>MetadataConstant</code> class is an enumeration of constant values * that specify the metadata properties of the Hummingbird framework. */ public class MetadataConstant { //-------------------------------------------------------------------------- // // Public constants // //-------------------------------------------------------------------------- /** * Represents the <code>RegisterClass</code> metadata. */ public static const REGISTER_CLASS:String = "RegisterClass"; /** * Represents the <code>Model</code> metadata. */ public static const MODEL:String = "Model"; /** * Represents the <code>Controller</code> metadata. */ public static const CONTROLLER:String = "Controller"; /** * Represents the <code>Orchestrator</code> metadata. */ public static const ORCHESTRATOR:String = "Orchestrator"; /** * Represents the <code>Service</code> metadata. */ public static const SERVICE:String = "Service"; /** * Represents the <code>Qualifier</code> metadata. */ public static const QUALIFIER:String = "Qualifier"; /** * Represents the <code>type</code> metadata property. */ public static const TYPE:String = "type"; /** * Represents the <code>alias</code> metadata property. */ public static const ALIAS:String = "alias"; } }
package fl.events { import flash.events.Event; /** * The ListEvent class defines events for list-based components including the List, DataGrid, TileList, and ComboBox components. * These events include the following: * <ul> * <li><code>ListEvent.ITEM_CLICK</code>: dispatched after the user clicks the mouse over an item in the component.</li> * <li><code>ListEvent.ITEM_DOUBLE_CLICK</code>: dispatched after the user clicks the mouse twice in rapid succession * over an item in the component.</li> * <li><code>ListEvent.ITEM_ROLL_OUT</code>: dispatched after the user rolls the mouse pointer out of an item in the component.</li> * <li><code>ListEvent.ITEM_ROLL_OVER</code>: dispatched after the user rolls the mouse pointer over an item in the component.</li> * </ul> * * @see fl.controls.List List * @see fl.controls.SelectableList SelectableList * * @includeExample examples/ListEventExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public class ListEvent extends Event { /** * Defines the value of the <code>type</code> property of an * <code>itemRollOut</code> event object. * * <p>This event has the following properties:</p> * <table class="innertable" width="100%"> * <tr> * <th>Property</th> * <th>Value</th> * </tr> * <tr> * <td><code>bubbles</code></td> * <td><code>false</code></td></tr> * <tr><td><code>cancelable</code></td><td><code>false</code>; there is * no default behavior to cancel.</td></tr> * <tr><td><code>columnIndex</code></td><td>The zero-based index of the column that * contains the renderer.</td></tr> * <tr><td><code>currentTarget</code></td><td>The object that is actively processing * the event object with an event listener.</td></tr> * <tr><td><code>index</code></td><td>The zero-based index in the DataProvider * that contains the renderer.</td></tr> * <tr><td><code>item</code></td><td>A reference to the data that belongs to the renderer.</td></tr> * <tr><td><code>rowIndex</code></td><td>The zero-based index of the row that * contains the renderer.</td></tr> * <tr><td><code>target</code></td><td>The object that dispatched the event. The target is * not always the object listening for the event. Use the <code>currentTarget</code> * property to access the object that is listening for the event.</td></tr> * </table> * * @eventType itemRollOut * * @see #ITEM_ROLL_OVER * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public static const ITEM_ROLL_OUT : String = "itemRollOut"; /** * Defines the value of the <code>type</code> property of an <code>itemRollOver</code> * event object. * * <p>This event has the following properties:</p> * <table class="innertable" width="100%"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td><code>false</code></td></tr> * <tr><td><code>cancelable</code></td><td><code>false</code>; there is * no default behavior to cancel.</td></tr> * <tr><td><code>columnIndex</code></td><td>The zero-based index of the column that * contains the renderer.</td></tr> * <tr><td><code>currentTarget</code></td><td>The object that is actively processing * the event object with an event listener.</td></tr> * <tr><td><code>index</code></td><td>The zero-based index in the DataProvider * that contains the renderer.</td></tr> * <tr><td><code>item</code></td><td>A reference to the data that belongs to the renderer.</td></tr> * <tr><td><code>rowIndex</code></td><td>The zero-based index of the row that * contains the renderer.</td></tr> * <tr><td><code>target</code></td><td>The object that dispatched the event. The target is * not always the object listening for the event. Use the <code>currentTarget</code> * property to access the object that is listening for the event.</td></tr> * </table> * * @eventType itemRollOver * * @see #ITEM_ROLL_OUT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public static const ITEM_ROLL_OVER : String = "itemRollOver"; /** * Defines the value of the <code>type</code> property of an <code>itemClick</code> * event object. * * <p>This event has the following properties:</p> * <table class="innertable" width="100%"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td><code>false</code></td></tr> * <tr><td><code>cancelable</code></td><td><code>true</code></td></tr> * <tr><td><code>columnIndex</code></td><td>The zero-based index of the column that * contains the renderer.</td></tr> * <tr><td><code>currentTarget</code></td><td>The object that is actively processing * the event object with an event listener.</td></tr> * <tr><td><code>index</code></td><td>The zero-based index in the DataProvider * that contains the renderer.</td></tr> * <tr><td><code>item</code></td><td>A reference to the data that belongs to the renderer. * </td></tr> * <tr><td><code>rowIndex</code></td><td>The zero-based index of the row that * contains the renderer.</td></tr> * <tr><td><code>target</code></td><td>The object that dispatched the event. The target is * not always the object listening for the event. Use the <code>currentTarget</code> * property to access the object that is listening for the event.</td></tr> * </table> * * @eventType itemClick * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public static const ITEM_CLICK : String = "itemClick"; /** * Defines the value of the <code>type</code> property of an <code>itemDoubleClick</code> * event object. * * <p>This event has the following properties:</p> * <table class="innertable" width="100%"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td><code>false</code></td></tr> * <tr><td><code>cancelable</code></td><td><code>true</code></td></tr> * <tr><td><code>columnIndex</code></td><td>The zero-based index of the column that * contains the renderer.</td></tr> * <tr><td><code>currentTarget</code></td><td>The object that is actively processing * the event object with an event listener.</td></tr> * <tr><td><code>index</code></td><td>The zero-based index in the DataProvider * that contains the renderer.</td></tr> * <tr><td><code>item</code></td><td>A reference to the data that belongs to the renderer. * </td></tr> * <tr><td><code>rowIndex</code></td><td>The zero-based index of the row that * contains the renderer.</td></tr> * <tr><td><code>target</code></td><td>The object that dispatched the event. The target is * not always the object listening for the event. Use the <code>currentTarget</code> * property to access the object that is listening for the event.</td></tr> * </table> * * @eventType itemDoubleClick * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public static const ITEM_DOUBLE_CLICK : String = "itemDoubleClick"; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ protected var _rowIndex : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ protected var _columnIndex : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ protected var _index : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ protected var _item : Object; /** * Gets the row index of the item that is associated with this event. * * @see #columnIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public function get rowIndex () : Object; /** * Gets the column index of the item that is associated with this event. * * @see #rowIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public function get columnIndex () : int; /** * Gets the zero-based index of the cell that contains the renderer. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public function get index () : int; /** * Gets the data that belongs to the current cell renderer. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public function get item () : Object; /** * Creates a new ListEvent object with the specified parameters. * * @param type The event type; this value identifies the action that caused the event. * * @param bubbles Indicates whether the event can bubble up the display list hierarchy. * * @param cancelable Indicates whether the behavior associated with the event can be * prevented. * * @param columnIndex The zero-based index of the column that contains the renderer or visual * representation of the data in the column. * * @param rowIndex The zero-based index of the row that contains the renderer or visual * representation of the data in the row. * * @param index The zero-based index of the item in the DataProvider. * * @param item A reference to the data that belongs to the renderer. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public function ListEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, columnIndex:int = -1, rowIndex:int = -1, index:int = -1, item:Object = null); /** * Returns a string that contains all the properties of the ListEvent object. The string * is in the following format: * * <p>[<code>ListEvent type=<em>value</em> bubbles=<em>value</em> * cancelable=<em>value</em> columnIndex=<em>value</em> * rowIndex=<em>value</em></code>]</p> * * @return A string representation of the ListEvent object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public function toString () : String; /** * Creates a copy of the ListEvent object and sets the value of each parameter to match * the original. * * @return A new ListEvent object with parameter values that match those of the original. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public function clone () : Event; } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.royale.html.beads.controllers { import org.apache.royale.core.IBeadController; import org.apache.royale.core.IIndexedItemRenderer; import org.apache.royale.core.IItemRendererOwnerView; import org.apache.royale.core.IMultiSelectionModel; import org.apache.royale.core.IRollOverModel; 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.ItemAddedEvent; import org.apache.royale.events.ItemRemovedEvent; import org.apache.royale.events.MultiSelectionItemClickedEvent; import org.apache.royale.html.beads.IListView; import org.apache.royale.utils.getSelectionRenderBead; import org.apache.royale.utils.sendEvent; import org.apache.royale.core.Bead; /** * The ListMultiSelectionMouseController class is a controller for * org.apache.royale.html.List. Controllers * watch for events from the interactive portions of a View and * update the data model or dispatch a semantic event. * This controller watches for events from the item renderers * and updates an IMultiSelectionModel (which supports multi * selection). * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9.7 */ public class ListMultiSelectionMouseController extends Bead implements IBeadController { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9.7 */ public function ListMultiSelectionMouseController() { } /** * The model. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9.7 */ protected var listModel:IMultiSelectionModel; /** * The view. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9.7 */ protected var listView:IListView; /** * The parent of the item renderers. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9.7 */ protected var dataGroup:IItemRendererOwnerView; /** * @copy org.apache.royale.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9.7 * @royaleignorecoercion org.apache.royale.core.IMultiSelectionModel * @royaleignorecoercion org.apache.royale.html.beads.IListView */ override public function set strand(value:IStrand):void { _strand = value; listModel = value.getBeadByType(IMultiSelectionModel) as IMultiSelectionModel; listView = value.getBeadByType(IListView) as IListView; listenOnStrand("itemAdded", handleItemAdded); listenOnStrand("itemRemoved", handleItemRemoved); } /** * @royaleignorecoercion org.apache.royale.events.IEventDispatcher */ protected function handleItemAdded(event:ItemAddedEvent):void { IEventDispatcher(event.item).addEventListener("itemClicked", selectedHandler); IEventDispatcher(event.item).addEventListener("itemRollOver", rolloverHandler); IEventDispatcher(event.item).addEventListener("itemRollOut", rolloutHandler); } /** * @royaleignorecoercion org.apache.royale.events.IEventDispatcher */ protected function handleItemRemoved(event:ItemRemovedEvent):void { IEventDispatcher(event.item).removeEventListener("itemClicked", selectedHandler); IEventDispatcher(event.item).removeEventListener("itemRollOver", rolloverHandler); IEventDispatcher(event.item).removeEventListener("itemRollOut", rolloutHandler); } protected function selectedHandler(event:MultiSelectionItemClickedEvent):void { var selectedIndices:Array = []; var newIndices:Array; if (!(event.ctrlKey || event.shiftKey) || !listModel.selectedIndices || listModel.selectedIndices.length == 0) { newIndices = [event.index]; } else if (event.ctrlKey) { // concat is so we have a new instance, avoiding code that might presume no change was made according to instance newIndices = listModel.selectedIndices.concat(); var locationInSelectionList:int = newIndices.indexOf(event.index); if (locationInSelectionList < 0) { newIndices.push(event.index); } else { newIndices.removeAt(locationInSelectionList); } } else if (event.shiftKey) { newIndices = []; var min:int = getMin(listModel.selectedIndices); var max:int = getMax(listModel.selectedIndices); var from:int = Math.min(min, event.index); var to:int = event.index > min ? event.index : min; while (from <= to) { newIndices.push(from++); } } listModel.selectedIndices = newIndices; sendEvent(listView.host,"change"); } private function getMin(value:Array):int { var result:int = int(value[0]); for (var i:int = 0; i < value.length; i++) { if (value[i] < result) { result = value[i]; } } return result; } private function getMax(value:Array):int { var result:int = int(value[0]); for (var i:int = 0; i < value.length; i++) { if (value[i] > result) { result = value[i]; } } return result; } /** * @royaleemitcoercion org.apache.royale.core.IIndexedItemRenderer * @royaleignorecoercion org.apache.royale.core.IRollOverModel */ protected function rolloverHandler(event:Event):void { var renderer:IIndexedItemRenderer = event.currentTarget as IIndexedItemRenderer; if (renderer) { IRollOverModel(listModel).rollOverIndex = renderer.index; } } /** * @royaleemitcoercion org.apache.royale.core.IIndexedItemRenderer * @royaleignorecoercion org.apache.royale.core.IRollOverModel */ protected function rolloutHandler(event:Event):void { var renderer:IIndexedItemRenderer = event.currentTarget as IIndexedItemRenderer; if (renderer) { if (renderer is IStrand) { var selectionBead:ISelectableItemRenderer = getSelectionRenderBead(renderer); if (selectionBead) { selectionBead.hovered = false; selectionBead.down = false; } } IRollOverModel(listModel).rollOverIndex = -1; } } } }
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2005-2007 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package mx.events { import flash.events.Event; /** * The CuePointEvent class represents the event object passed to the event listener for * cue point events dispatched by the VideoDisplay control. * * @see mx.controls.VideoDisplay * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class CuePointEvent extends Event { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * The <code>CuePointEvent.CUE_POINT</code> constant defines the value of the * <code>type</code> property of the event object for a <code>cuePoint</code> event. * * <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>cancelable</code></td><td>false</td></tr> * <tr><td><code>cuePointName</code></td><td>The name of the cue point.</td></tr> * <tr><td><code>cuePointTime</code></td><td>The time of the cue point, in seconds.</td></tr> * <tr><td><code>cuePointType</code></td><td>The string * <code>"actionscript"</code>.</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>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 cuePoint * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const CUE_POINT:String = "cuePoint"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param type The event type; indicates the action that caused the event. * * @param bubbles Specifies whether the event can bubble up the display list hierarchy. * * @param cancelable Specifies whether the behavior associated with * the event can be prevented. * * @param cuePointName The name of the cue point. * * @param cuePointTime The time of the cue point, in seconds. * * @param cuePointType The string <code>"actionscript"</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function CuePointEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false, cuePointName:String = null, cuePointTime:Number = NaN, cuePointType:String = null) { super(type, bubbles, cancelable); this.cuePointName = cuePointName; this.cuePointTime = cuePointTime; this.cuePointType = cuePointType; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // cuePointName //---------------------------------- /** * The name of the cue point that caused the event. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var cuePointName:String; //---------------------------------- // cuePointTime //---------------------------------- /** * The time of the cue point that caused the event, in seconds. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var cuePointTime:Number; //---------------------------------- // cuePointType //---------------------------------- /** * The string <code>"actionscript"</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var cuePointType:String; //-------------------------------------------------------------------------- // // Overridden methods: Event // //-------------------------------------------------------------------------- /** * @private */ override public function clone():Event { return new CuePointEvent(type, bubbles, cancelable, cuePointName, cuePointTime, cuePointType); } } }
/* Feathers Copyright 2012-2014 Joshua Tynjala. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.skins { import feathers.core.IToggle; import flash.utils.Dictionary; /** * Maps a component's states to values, perhaps for one of the component's * properties such as a skin or text format. */ public class StateWithToggleValueSelector { /** * Constructor. */ public function StateWithToggleValueSelector() { } /** * @private * Stores the values for each state. */ protected var stateToValue:Dictionary = new Dictionary(true); /** * @private * Stores the values for each state where isSelected is true. */ protected var stateToSelectedValue:Dictionary = new Dictionary(true); /** * If there is no value for the specified state, a default value can * be used as a fallback. */ public var defaultValue:Object; /** * If the target is a selected IToggle instance, and if there is no * value for the specified state, a default value may be used as a * fallback (with a higher priority than the regular default fallback). * * @see feathers.core.IToggle */ public var defaultSelectedValue:Object; /** * Stores a value for a specified state to be returned from * getValueForState(). */ public function setValueForState(value:Object, state:Object, isSelected:Boolean = false):void { if(isSelected) { this.stateToSelectedValue[state] = value; } else { this.stateToValue[state] = value; } } /** * Clears the value stored for a specific state. */ public function clearValueForState(state:Object, isSelected:Boolean = false):Object { if(isSelected) { var value:Object = this.stateToSelectedValue[state]; delete this.stateToSelectedValue[state]; } else { value = this.stateToValue[state]; delete this.stateToValue[state]; } return value; } /** * Returns the value stored for a specific state. */ public function getValueForState(state:Object, isSelected:Boolean = false):Object { if(isSelected) { return this.stateToSelectedValue[state]; } return this.stateToValue[state]; } /** * Returns the value stored for a specific state. May generate a value, * if none is present. * * @param target The object receiving the stored value. The manager may query properties on the target to customize the returned value. * @param state The current state. * @param oldValue The previous value. May be reused for the new value. */ public function updateValue(target:Object, state:Object, oldValue:Object = null):Object { var value:Object; if(target is IToggle && IToggle(target).isSelected) { value = this.stateToSelectedValue[state]; if(value === null) { value = this.defaultSelectedValue; } } else { value = this.stateToValue[state]; } if(value === null) { value = this.defaultValue; } return value; } } }
package openfl.events { /** * @externs * The Accelerometer class dispatches AccelerometerEvent objects when * acceleration updates are obtained from the Accelerometer sensor installed * on the device. * */ public class AccelerometerEvent extends Event { /** * Defines the value of the `type` property of a * `AccelerometerEvent` event object. * * This event has the following properties: */ public static const UPDATE:String = "update"; /** * Acceleration along the x-axis, measured in Gs.(1 G is roughly 9.8 * m/sec/sec.) The x-axis runs from the left to the right of the device when * it is in the upright position. The acceleration is positive if the device * moves towards the right. */ public var accelerationX:Number; /** * Acceleration along the y-axis, measured in Gs.(1 G is roughly 9.8 * m/sec/sec.). The y-axis runs from the bottom to the top of the device when * it is in the upright position. The acceleration is positive if the device * moves up relative to this axis. */ public var accelerationY:Number; /** * Acceleration along the z-axis, measured in Gs.(1 G is roughly 9.8 * m/sec/sec.). The z-axis runs perpendicular to the face of the device. The * acceleration is positive if you move the device so that the face moves * higher. */ public var accelerationZ:Number; /** * The number of milliseconds at the time of the event since the runtime was * initialized. For example, if the device captures accelerometer data 4 * seconds after the application initializes, then the `timestamp` * property of the event is set to 4000. */ public var timestamp:Number; /** * Creates an AccelerometerEvent object that contains information about * acceleration along three dimensional axis. Event objects are passed as * parameters to event listeners. * * @param type The type of the event. Event listeners can access * this information through the inherited * `type` property. There is only one type of * update event: `AccelerometerEvent.UPDATE`. * @param bubbles Determines whether the Event object bubbles. Event * listeners can access this information through the * inherited `bubbles` property. * @param cancelable Determines whether the Event object can be canceled. * Event listeners can access this information through * the inherited `cancelable` property. * @param timestamp The timestamp of the Accelerometer update. * @param accelerationX The acceleration value in Gs(9.8m/sec/sec) along the * x-axis. * @param accelerationY The acceleration value in Gs(9.8m/sec/sec) along the * y-axis. * @param accelerationZ The acceleration value in Gs(9.8m/sec/sec) along the * z-axis. */ public function AccelerometerEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, timestamp:Number = 0, accelerationX:Number = 0, accelerationY:Number = 0, accelerationZ:Number = 0) { super (type); } } }
package manager.resource { import common.debug.Debug; import common.events.BooleanEvent; import common.resources.SlotitemResourceLoader; import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.EventDispatcher; public class SlotitemImgAttacher extends EventDispatcher implements ISlotitemAttacher { private var _stackList:Vector.<SlotitemResourceLoader> = null; public function SlotitemImgAttacher() { super(); _stackList = new Vector.<SlotitemResourceLoader>(); } public function get nowLoading() : Boolean { return _stackList.length > 0 && _stackList[0].nowLoading; } public function stackCard(param1:int, param2:DisplayObjectContainer) : void { var _loc3_:String = "card"; _stack(param1,_loc3_,param2); } public function stackItemOn(param1:int, param2:DisplayObjectContainer) : void { var _loc3_:String = "item_on"; _stack(param1,_loc3_,param2); } public function stackItemCharacter(param1:int, param2:DisplayObjectContainer) : void { var _loc3_:String = "item_character"; _stack(param1,_loc3_,param2); } public function stackItemUp(param1:int, param2:DisplayObjectContainer) : void { var _loc3_:String = "item_up"; _stack(param1,_loc3_,param2); } public function stackStatusTop(param1:int, param2:DisplayObjectContainer) : void { var _loc3_:String = "statustop_item"; _stack(param1,_loc3_,param2); } public function stackRemodel(param1:int, param2:DisplayObjectContainer) : void { var _loc3_:String = "remodal"; _stack(param1,_loc3_,param2); } public function stackBtxt(param1:int, param2:DisplayObjectContainer, param3:Boolean = true) : void { var _loc4_:String = !!param3?"btxt_flat":"btxt_tilt"; _stack(param1,_loc4_,param2); } public function stackAirUnitName(param1:int, param2:DisplayObjectContainer) : void { var _loc3_:String = "airunit_name"; _stack(param1,_loc3_,param2); } public function stackAirUnitBanner(param1:int, param2:DisplayObjectContainer) : void { var _loc3_:String = "airunit_banner"; _stack(param1,_loc3_,param2); } public function stackAirUnitFairy(param1:int, param2:DisplayObjectContainer) : void { var _loc3_:String = "airunit_fairy"; _stack(param1,_loc3_,param2); } public function load() : void { if(_stackList.length == 0) { dispatchEvent(new Event("complete")); } else { Debug.log("[SlotitemImgAttacher] Load Start"); _nextLoad(); } } public function cancel() : void { if(_stackList.length) { Debug.log("[SlotitemImgAttacher] cancel."); } if(nowLoading) { _stackList[0].cancel(); } _stackList = new Vector.<SlotitemResourceLoader>(); } private function _stack(param1:int, param2:String, param3:DisplayObjectContainer, param4:Class = null) : void { var _loc5_:SlotitemResourceLoader = new SlotitemResourceLoader(param1,param2,param3,param4); _stackList.push(_loc5_); } private function _nextLoad() : void { if(nowLoading || !_stackList.length) { return; } var _loc1_:SlotitemResourceLoader = _stackList[0]; _loc1_.addEventListener("complete",_handleLoadEnd); _loc1_.load(); } private function _handleLoadEnd(param1:BooleanEvent) : void { if(nowLoading) { return; } var _loc3_:SlotitemResourceLoader = param1.target as SlotitemResourceLoader; if(_loc3_ != _stackList.shift()) { return; } _loc3_.removeEventListener("complete",_handleLoadEnd); var _loc2_:String = !!param1.data?"Complete":"Error"; _loc2_ = "[SlotitemResourceLoader] Load " + _loc2_ + "(残り" + _stackList.length + ")"; Debug.log(_loc2_ + " " + _loc3_.url); if(_stackList.length > 0) { _nextLoad(); } else { Debug.log("[SlotitemImgAttacher] Load Complete ALL."); dispatchEvent(new Event("complete")); } } } }
package com.ludicast.foursquare.models { public class Contact { public var phone:String; } }
// ================================================================================================= // // Starling Framework // Copyright 2011-2014 Gamua. 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 starling.core { import com.adobe.utils.AGALMiniAssembler; import flash.display3D.Context3D; import flash.display3D.Context3DCompareMode; import flash.display3D.Context3DProgramType; import flash.display3D.Context3DStencilAction; import flash.display3D.Context3DTextureFormat; import flash.display3D.Context3DTriangleFace; import flash.display3D.Program3D; import flash.geom.Matrix; import flash.geom.Matrix3D; import flash.geom.Point; import flash.geom.Rectangle; import flash.geom.Vector3D; import starling.display.BlendMode; import starling.display.DisplayObject; import starling.display.Quad; import starling.display.QuadBatch; import starling.display.Stage; import starling.errors.MissingContextError; import starling.textures.Texture; import starling.textures.TextureSmoothing; import starling.utils.Color; import starling.utils.MatrixUtil; import starling.utils.RectangleUtil; import starling.utils.SystemUtil; /** A class that contains helper methods simplifying Stage3D rendering. * * A RenderSupport instance is passed to any "render" method of display objects. * It allows manipulation of the current transformation matrix (similar to the matrix * manipulation methods of OpenGL 1.x) and other helper methods. */ public class RenderSupport { private static const RENDER_TARGET_NAME:String = "Starling.renderTarget"; // members private var mProjectionMatrix:Matrix; private var mModelViewMatrix:Matrix; private var mMvpMatrix:Matrix; private var mMatrixStack:Vector.<Matrix>; private var mMatrixStackSize:int; private var mProjectionMatrix3D:Matrix3D; private var mModelViewMatrix3D:Matrix3D; private var mMvpMatrix3D:Matrix3D; private var mMatrixStack3D:Vector.<Matrix3D>; private var mMatrixStack3DSize:int; private var mDrawCount:int; private var mBlendMode:String; private var mClipRectStack:Vector.<Rectangle>; private var mClipRectStackSize:int; private var mQuadBatches:Vector.<QuadBatch>; private var mCurrentQuadBatchID:int; /** helper objects */ private static var sPoint:Point = new Point(); private static var sPoint3D:Vector3D = new Vector3D(); private static var sClipRect:Rectangle = new Rectangle(); private static var sBufferRect:Rectangle = new Rectangle(); private static var sScissorRect:Rectangle = new Rectangle(); private static var sAssembler:AGALMiniAssembler = new AGALMiniAssembler(); private static var sMatrix3D:Matrix3D = new Matrix3D(); private static var sMatrixData:Vector.<Number> = new <Number>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // construction /** Creates a new RenderSupport object with an empty matrix stack. */ public function RenderSupport() { mProjectionMatrix = new Matrix(); mModelViewMatrix = new Matrix(); mMvpMatrix = new Matrix(); mMatrixStack = new <Matrix>[]; mMatrixStackSize = 0; mProjectionMatrix3D = new Matrix3D(); mModelViewMatrix3D = new Matrix3D(); mMvpMatrix3D = new Matrix3D(); mMatrixStack3D = new <Matrix3D>[]; mMatrixStack3DSize = 0; mDrawCount = 0; mBlendMode = BlendMode.NORMAL; mClipRectStack = new <Rectangle>[]; mCurrentQuadBatchID = 0; mQuadBatches = new <QuadBatch>[new QuadBatch(true)]; loadIdentity(); setProjectionMatrix(0, 0, 400, 300); } /** Disposes all quad batches. */ public function dispose():void { for each (var quadBatch:QuadBatch in mQuadBatches) quadBatch.dispose(); } // matrix manipulation /** Sets up the projection matrices for 2D and 3D rendering. * * <p>The first 4 parameters define which area of the stage you want to view. The camera * will 'zoom' to exactly this region. The perspective in which you're looking at the * stage is determined by the final 3 parameters.</p> * * <p>The stage is always on the rectangle that is spawned up between x- and y-axis (with * the given size). All objects that are exactly on that rectangle (z equals zero) will be * rendered in their true size, without any distortion.</p> */ public function setProjectionMatrix(x:Number, y:Number, width:Number, height:Number, stageWidth:Number=0, stageHeight:Number=0, cameraPos:Vector3D=null):void { if (stageWidth <= 0) stageWidth = width; if (stageHeight <= 0) stageHeight = height; if (cameraPos == null) { cameraPos = sPoint3D; cameraPos.setTo( stageWidth / 2, stageHeight / 2, // -> center of stage stageWidth / Math.tan(0.5) * 0.5); // -> fieldOfView = 1.0 rad } // set up 2d (orthographic) projection mProjectionMatrix.setTo(2.0/width, 0, 0, -2.0/height, -(2*x + width) / width, (2*y + height) / height); const focalLength:Number = Math.abs(cameraPos.z); const offsetX:Number = cameraPos.x - stageWidth / 2; const offsetY:Number = cameraPos.y - stageHeight / 2; const far:Number = focalLength * 20; const near:Number = 1; const scaleX:Number = stageWidth / width; const scaleY:Number = stageHeight / height; // set up general perspective sMatrixData[ 0] = 2 * focalLength / stageWidth; // 0,0 sMatrixData[ 5] = -2 * focalLength / stageHeight; // 1,1 [negative to invert y-axis] sMatrixData[10] = far / (far - near); // 2,2 sMatrixData[14] = -far * near / (far - near); // 2,3 sMatrixData[11] = 1; // 3,2 // now zoom in to visible area sMatrixData[0] *= scaleX; sMatrixData[5] *= scaleY; sMatrixData[8] = scaleX - 1 - 2 * scaleX * (x - offsetX) / stageWidth; sMatrixData[9] = -scaleY + 1 + 2 * scaleY * (y - offsetY) / stageHeight; mProjectionMatrix3D.copyRawDataFrom(sMatrixData); mProjectionMatrix3D.prependTranslation( -stageWidth /2.0 - offsetX, -stageHeight/2.0 - offsetY, focalLength); applyClipRect(); } /** Sets up the projection matrix for ortographic 2D rendering. */ [Deprecated(replacement="setProjectionMatrix")] public function setOrthographicProjection(x:Number, y:Number, width:Number, height:Number):void { var stage:Stage = Starling.current.stage; sClipRect.setTo(x, y, width, height); setProjectionMatrix(x, y, width, height, stage.stageWidth, stage.stageHeight, stage.cameraPosition); } /** Changes the modelview matrix to the identity matrix. */ public function loadIdentity():void { mModelViewMatrix.identity(); mModelViewMatrix3D.identity(); } /** Prepends a translation to the modelview matrix. */ public function translateMatrix(dx:Number, dy:Number):void { MatrixUtil.prependTranslation(mModelViewMatrix, dx, dy); } /** Prepends a rotation (angle in radians) to the modelview matrix. */ public function rotateMatrix(angle:Number):void { MatrixUtil.prependRotation(mModelViewMatrix, angle); } /** Prepends an incremental scale change to the modelview matrix. */ public function scaleMatrix(sx:Number, sy:Number):void { MatrixUtil.prependScale(mModelViewMatrix, sx, sy); } /** Prepends a matrix to the modelview matrix by multiplying it with another matrix. */ public function prependMatrix(matrix:Matrix):void { MatrixUtil.prependMatrix(mModelViewMatrix, matrix); } /** Prepends translation, scale and rotation of an object to the modelview matrix. */ public function transformMatrix(object:DisplayObject):void { MatrixUtil.prependMatrix(mModelViewMatrix, object.transformationMatrix); } /** Pushes the current modelview matrix to a stack from which it can be restored later. */ public function pushMatrix():void { if (mMatrixStack.length < mMatrixStackSize + 1) mMatrixStack.push(new Matrix()); mMatrixStack[int(mMatrixStackSize++)].copyFrom(mModelViewMatrix); } /** Restores the modelview matrix that was last pushed to the stack. */ public function popMatrix():void { mModelViewMatrix.copyFrom(mMatrixStack[int(--mMatrixStackSize)]); } /** Empties the matrix stack, resets the modelview matrix to the identity matrix. */ public function resetMatrix():void { mMatrixStackSize = 0; mMatrixStack3DSize = 0; loadIdentity(); } /** Prepends translation, scale and rotation of an object to a custom matrix. */ public static function transformMatrixForObject(matrix:Matrix, object:DisplayObject):void { MatrixUtil.prependMatrix(matrix, object.transformationMatrix); } /** Calculates the product of modelview and projection matrix. * CAUTION: Use with care! Each call returns the same instance. */ public function get mvpMatrix():Matrix { mMvpMatrix.copyFrom(mModelViewMatrix); mMvpMatrix.concat(mProjectionMatrix); return mMvpMatrix; } /** Returns the current modelview matrix. * CAUTION: Use with care! Each call returns the same instance. */ public function get modelViewMatrix():Matrix { return mModelViewMatrix; } /** Returns the current projection matrix. * CAUTION: Use with care! Each call returns the same instance. */ public function get projectionMatrix():Matrix { return mProjectionMatrix; } public function set projectionMatrix(value:Matrix):void { mProjectionMatrix.copyFrom(value); applyClipRect(); } // 3d transformations /** Prepends translation, scale and rotation of an object to the 3D modelview matrix. * The current contents of the 2D modelview matrix is stored in the 3D modelview matrix * before doing so; the 2D modelview matrix is then reset to the identity matrix. */ public function transformMatrix3D(object:DisplayObject):void { mModelViewMatrix3D.prepend(MatrixUtil.convertTo3D(mModelViewMatrix, sMatrix3D)); mModelViewMatrix3D.prepend(object.transformationMatrix3D); mModelViewMatrix.identity(); } /** Pushes the current 3D modelview matrix to a stack from which it can be restored later. */ public function pushMatrix3D():void { if (mMatrixStack3D.length < mMatrixStack3DSize + 1) mMatrixStack3D.push(new Matrix3D()); mMatrixStack3D[int(mMatrixStack3DSize++)].copyFrom(mModelViewMatrix3D); } /** Restores the 3D modelview matrix that was last pushed to the stack. */ public function popMatrix3D():void { mModelViewMatrix3D.copyFrom(mMatrixStack3D[int(--mMatrixStack3DSize)]); } /** Calculates the product of modelview and projection matrix and stores it in a 3D matrix. * Different to 'mvpMatrix', this also takes 3D transformations into account. * CAUTION: Use with care! Each call returns the same instance. */ public function get mvpMatrix3D():Matrix3D { if (mMatrixStack3DSize == 0) { MatrixUtil.convertTo3D(mvpMatrix, mMvpMatrix3D); } else { mMvpMatrix3D.copyFrom(mProjectionMatrix3D); mMvpMatrix3D.prepend(mModelViewMatrix3D); mMvpMatrix3D.prepend(MatrixUtil.convertTo3D(mModelViewMatrix, sMatrix3D)); } return mMvpMatrix3D; } /** Returns the current 3D projection matrix. * CAUTION: Use with care! Each call returns the same instance. */ public function get projectionMatrix3D():Matrix3D { return mProjectionMatrix3D; } public function set projectionMatrix3D(value:Matrix3D):void { mProjectionMatrix3D.copyFrom(value); } // blending /** Activates the current blend mode on the active rendering context. */ public function applyBlendMode(premultipliedAlpha:Boolean):void { setBlendFactors(premultipliedAlpha, mBlendMode); } /** The blend mode to be used on rendering. To apply the factor, you have to manually call * 'applyBlendMode' (because the actual blend factors depend on the PMA mode). */ public function get blendMode():String { return mBlendMode; } public function set blendMode(value:String):void { if (value != BlendMode.AUTO) mBlendMode = value; } // render targets /** The texture that is currently being rendered into, or 'null' to render into the * back buffer. If you set a new target, it is immediately activated. */ public function get renderTarget():Texture { return Starling.current.contextData[RENDER_TARGET_NAME]; } public function set renderTarget(target:Texture):void { setRenderTarget(target); } /** Changes the the current render target. * @param target Either a texture or 'null' to render into the back buffer. * @param antiAliasing Only supported for textures, beginning with AIR 13, and only on * Desktop. Values range from 0 (no antialiasing) to 4 (best quality). */ public function setRenderTarget(target:Texture, antiAliasing:int=0):void { Starling.current.contextData[RENDER_TARGET_NAME] = target; applyClipRect(); if (target) Starling.context.setRenderToTexture(target.base, SystemUtil.supportsDepthAndStencil, antiAliasing); else Starling.context.setRenderToBackBuffer(); } // clipping /** The clipping rectangle can be used to limit rendering in the current render target to * a certain area. This method expects the rectangle in stage coordinates. Internally, * it uses the 'scissorRectangle' of stage3D, which works with pixel coordinates. * Per default, any pushed rectangle is intersected with the previous rectangle; * the method returns that intersection. */ public function pushClipRect(rectangle:Rectangle, intersectWithCurrent:Boolean=true):Rectangle { if (mClipRectStack.length < mClipRectStackSize + 1) mClipRectStack.push(new Rectangle()); mClipRectStack[mClipRectStackSize].copyFrom(rectangle); rectangle = mClipRectStack[mClipRectStackSize]; // intersect with the last pushed clip rect if (intersectWithCurrent && mClipRectStackSize > 0) RectangleUtil.intersect(rectangle, mClipRectStack[mClipRectStackSize-1], rectangle); ++mClipRectStackSize; applyClipRect(); // return the intersected clip rect so callers can skip draw calls if it's empty return rectangle; } /** Restores the clipping rectangle that was last pushed to the stack. */ public function popClipRect():void { if (mClipRectStackSize > 0) { --mClipRectStackSize; applyClipRect(); } } /** Updates the context3D scissor rectangle using the current clipping rectangle. This * method is called automatically when either the render target, the projection matrix, * or the clipping rectangle changes. */ public function applyClipRect():void { finishQuadBatch(); var context:Context3D = Starling.context; if (context == null) return; if (mClipRectStackSize > 0) { var width:int, height:int; var rect:Rectangle = mClipRectStack[mClipRectStackSize-1]; var renderTarget:Texture = this.renderTarget; if (renderTarget) { width = renderTarget.root.nativeWidth; height = renderTarget.root.nativeHeight; } else { width = Starling.current.backBufferWidth; height = Starling.current.backBufferHeight; } // convert to pixel coordinates (matrix transformation ends up in range [-1, 1]) MatrixUtil.transformCoords(mProjectionMatrix, rect.x, rect.y, sPoint); sClipRect.x = (sPoint.x * 0.5 + 0.5) * width; sClipRect.y = (0.5 - sPoint.y * 0.5) * height; MatrixUtil.transformCoords(mProjectionMatrix, rect.right, rect.bottom, sPoint); sClipRect.right = (sPoint.x * 0.5 + 0.5) * width; sClipRect.bottom = (0.5 - sPoint.y * 0.5) * height; sBufferRect.setTo(0, 0, width, height); RectangleUtil.intersect(sClipRect, sBufferRect, sScissorRect); // an empty rectangle is not allowed, so we set it to the smallest possible size if (sScissorRect.width < 1 || sScissorRect.height < 1) sScissorRect.setTo(0, 0, 1, 1); context.setScissorRectangle(sScissorRect); } else { context.setScissorRectangle(null); } } // stencil masks private var mMasks:Vector.<DisplayObject> = new <DisplayObject>[]; private var mStencilReferenceValue:uint = 0; /** Draws a display object into the stencil buffer, incrementing the buffer on each * used pixel. The stencil reference value is incremented as well; thus, any subsequent * stencil tests outside of this area will fail. * * <p>If 'mask' is part of the display list, it will be drawn at its conventional stage * coordinates. Otherwise, it will be drawn with the current modelview matrix.</p> */ public function pushMask(mask:DisplayObject):void { mMasks[mMasks.length] = mask; mStencilReferenceValue++; var context:Context3D = Starling.context; if (context == null) return; finishQuadBatch(); context.setStencilActions(Context3DTriangleFace.FRONT_AND_BACK, Context3DCompareMode.EQUAL, Context3DStencilAction.INCREMENT_SATURATE); drawMask(mask); context.setStencilReferenceValue(mStencilReferenceValue); context.setStencilActions(Context3DTriangleFace.FRONT_AND_BACK, Context3DCompareMode.EQUAL, Context3DStencilAction.KEEP); } /** Redraws the most recently pushed mask into the stencil buffer, decrementing the * buffer on each used pixel. This effectively removes the object from the stencil buffer, * restoring the previous state. The stencil reference value will be decremented. */ public function popMask():void { var mask:DisplayObject = mMasks.pop(); mStencilReferenceValue--; var context:Context3D = Starling.context; if (context == null) return; finishQuadBatch(); context.setStencilActions(Context3DTriangleFace.FRONT_AND_BACK, Context3DCompareMode.EQUAL, Context3DStencilAction.DECREMENT_SATURATE); drawMask(mask); context.setStencilReferenceValue(mStencilReferenceValue); context.setStencilActions(Context3DTriangleFace.FRONT_AND_BACK, Context3DCompareMode.EQUAL, Context3DStencilAction.KEEP); } private function drawMask(mask:DisplayObject):void { pushMatrix(); var stage:Stage = mask.stage; if (stage) mask.getTransformationMatrix(stage, mModelViewMatrix); else transformMatrix(mask); mask.render(this, 0.0); finishQuadBatch(); popMatrix(); } /** The current stencil reference value, which is per default the depth of the current * stencil mask stack. Only change this value if you know what you're doing. */ public function get stencilReferenceValue():uint { return mStencilReferenceValue; } public function set stencilReferenceValue(value:uint):void { mStencilReferenceValue = value; if (Starling.current.contextValid) Starling.context.setStencilReferenceValue(value); } // optimized quad rendering /** Adds a quad to the current batch of unrendered quads. If there is a state change, * all previous quads are rendered at once, and the batch is reset. */ public function batchQuad(quad:Quad, parentAlpha:Number, texture:Texture=null, smoothing:String=null):void { if (mQuadBatches[mCurrentQuadBatchID].isStateChange(quad.tinted, parentAlpha, texture, smoothing, mBlendMode)) { finishQuadBatch(); } mQuadBatches[mCurrentQuadBatchID].addQuad(quad, parentAlpha, texture, smoothing, mModelViewMatrix, mBlendMode); } /** Adds a batch of quads to the current batch of unrendered quads. If there is a state * change, all previous quads are rendered at once. * * <p>Note that copying the contents of the QuadBatch to the current "cumulative" * batch takes some time. If the batch consists of more than just a few quads, * you may be better off calling the "render(Custom)" method on the batch instead. * Otherwise, the additional CPU effort will be more expensive than what you save by * avoiding the draw call. (Rule of thumb: no more than 16-20 quads.)</p> */ public function batchQuadBatch(quadBatch:QuadBatch, parentAlpha:Number):void { if (mQuadBatches[mCurrentQuadBatchID].isStateChange( quadBatch.tinted, parentAlpha, quadBatch.texture, quadBatch.smoothing, mBlendMode, quadBatch.numQuads)) { finishQuadBatch(); } mQuadBatches[mCurrentQuadBatchID].addQuadBatch(quadBatch, parentAlpha, mModelViewMatrix, mBlendMode); } /** Renders the current quad batch and resets it. */ public function finishQuadBatch():void { var currentBatch:QuadBatch = mQuadBatches[mCurrentQuadBatchID]; if (currentBatch.numQuads != 0) { if (mMatrixStack3DSize == 0) { currentBatch.renderCustom(mProjectionMatrix3D); } else { mMvpMatrix3D.copyFrom(mProjectionMatrix3D); mMvpMatrix3D.prepend(mModelViewMatrix3D); currentBatch.renderCustom(mMvpMatrix3D); } currentBatch.reset(); ++mCurrentQuadBatchID; ++mDrawCount; if (mQuadBatches.length <= mCurrentQuadBatchID) mQuadBatches.push(new QuadBatch(true)); } } /** Resets matrix stack, blend mode, quad batch index, and draw count. */ public function nextFrame():void { resetMatrix(); trimQuadBatches(); mMasks.length = 0; mCurrentQuadBatchID = 0; mBlendMode = BlendMode.NORMAL; mDrawCount = 0; } /** Disposes redundant quad batches if the number of allocated batches is more than * twice the number of used batches. Only executed when there are at least 16 batches. */ private function trimQuadBatches():void { var numUsedBatches:int = mCurrentQuadBatchID + 1; var numTotalBatches:int = mQuadBatches.length; if (numTotalBatches >= 16 && numTotalBatches > 2*numUsedBatches) { var numToRemove:int = numTotalBatches - numUsedBatches; for (var i:int=0; i<numToRemove; ++i) mQuadBatches.pop().dispose(); } } // other helper methods /** Deprecated. Call 'setBlendFactors' instead. */ public static function setDefaultBlendFactors(premultipliedAlpha:Boolean):void { setBlendFactors(premultipliedAlpha); } /** Sets up the blending factors that correspond with a certain blend mode. */ public static function setBlendFactors(premultipliedAlpha:Boolean, blendMode:String="normal"):void { var blendFactors:Array = BlendMode.getBlendFactors(blendMode, premultipliedAlpha); Starling.context.setBlendFactors(blendFactors[0], blendFactors[1]); } /** Clears the render context with a certain color and alpha value. */ public static function clear(rgb:uint=0, alpha:Number=0.0):void { Starling.context.clear( Color.getRed(rgb) / 255.0, Color.getGreen(rgb) / 255.0, Color.getBlue(rgb) / 255.0, alpha); } /** Clears the render context with a certain color and alpha value. */ public function clear(rgb:uint=0, alpha:Number=0.0):void { RenderSupport.clear(rgb, alpha); } /** Assembles fragment- and vertex-shaders, passed as Strings, to a Program3D. If you * pass a 'resultProgram', it will be uploaded to that program; otherwise, a new program * will be created on the current Stage3D context. */ public static function assembleAgal(vertexShader:String, fragmentShader:String, resultProgram:Program3D=null):Program3D { if (resultProgram == null) { var context:Context3D = Starling.context; if (context == null) throw new MissingContextError(); resultProgram = context.createProgram(); } resultProgram.upload( sAssembler.assemble(Context3DProgramType.VERTEX, vertexShader), sAssembler.assemble(Context3DProgramType.FRAGMENT, fragmentShader)); return resultProgram; } /** Returns the flags that are required for AGAL texture lookup, * including the '&lt;' and '&gt;' delimiters. */ public static function getTextureLookupFlags(format:String, mipMapping:Boolean, repeat:Boolean=false, smoothing:String="bilinear"):String { var options:Array = ["2d", repeat ? "repeat" : "clamp"]; if (format == Context3DTextureFormat.COMPRESSED) options.push("dxt1"); else if (format == "compressedAlpha") options.push("dxt5"); if (smoothing == TextureSmoothing.NONE) options.push("nearest", mipMapping ? "mipnearest" : "mipnone"); else if (smoothing == TextureSmoothing.BILINEAR) options.push("linear", mipMapping ? "mipnearest" : "mipnone"); else options.push("linear", mipMapping ? "miplinear" : "mipnone"); return "<" + options.join() + ">"; } // statistics /** Raises the draw count by a specific value. Call this method in custom render methods * to keep the statistics display in sync. */ public function raiseDrawCount(value:uint=1):void { mDrawCount += value; } /** Indicates the number of stage3D draw calls. */ public function get drawCount():int { return mDrawCount; } } }
/* ***** 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 ***** */ var SECTION = "6-1"; var VERSION = "ECMA_1"; startTest(); var TITLE = "Source Text"; writeHeaderToLog( SECTION + " "+ TITLE); var testcases = getTestCases(); test(); function getTestCases() { var array = new Array(); var item = 0; array[item++] = new TestCase( SECTION, "// the following character should not be interpreted as a line terminator in a comment: \u000A", 'PASSED', "PASSED" ); // \u000A array[item++].actual = "FAILED!"; array[item++] = new TestCase( SECTION, "// the following character should not be interpreted as a line terminator in a comment: \\n 'FAILED'", 'PASSED', 'PASSED' ); // the following character should not be interpreted as a line terminator: \\n array[item++].actual = "FAILED" array[item++] = new TestCase( SECTION, "// the following character should not be interpreted as a line terminator in a comment: \\u000A 'FAILED'", 'PASSED', 'PASSED' ) // the following character should not be interpreted as a line terminator: \u000A array[item++].actual = "FAILED" array[item++] = new TestCase( SECTION, "// the following character should not be interpreted as a line terminator in a comment: \n 'PASSED'", 'PASSED', 'PASSED' ) // the following character should not be interpreted as a line terminator: \n array[item++].actual = 'FAILED' array[item++] = new TestCase( SECTION, "// the following character should not be interpreted as a line terminator in a comment: u000D", 'PASSED', 'PASSED' ) // the following character should not be interpreted as a line terminator: \u000D array[item++].actual = "FAILED" array[item++] = new TestCase( SECTION, "// the following character should not be interpreted as a line terminator in a comment: u2028", 'PASSED', 'PASSED' ) // the following character should not be interpreted as a line terminator: \u2028 array[item++].actual = "FAILED" array[item++] = new TestCase( SECTION, "// the following character should not be interpreted as a line terminator in a comment: u2029", 'PASSED', 'PASSED' ) // the following character should not be interpreted as a line terminator: \u2029 array[item++].actual = "FAILED" array[item++] = new TestCase( SECTION, "the following character should be interpreted as backspace in a string: \u0008",'abc\bdef', 'abc\u0008def' ) array[item++] = new TestCase( SECTION, "the following character should be interpreted as whitespace(Tab) in a string: \u0009",'abc\tdef', 'abc\u0009def' ) array[item++] = new TestCase( SECTION, "the following character should be interpreted as vertical tab in a string: \u000B",'abc\vdef', 'abc\u000Bdef' ) array[item++] = new TestCase( SECTION, "the following character should be interpreted as form feed in a string: \u000C",'abc\fdef','abc\u000Cdef' ) array[item++] = new TestCase( SECTION, "the following character should be interpreted as double quotes in a string and should not terminate a string but should just add a character to the string: \u0022",'abc\"def', 'abc\u0022def' ) array[item++] = new TestCase( SECTION, "the following character should be interpreted as single quote in a string and should not terminate a string but should just add a character to the string : \u0027",'abc\'def', 'abc\u0027def' ) array[item++] = new TestCase( SECTION, "the following character should be interpreted as single blackslash in a string : \u005C",'abc\\def','abc\u005Cdef' ) array[item++] = new TestCase( SECTION, "the following character should be interpreted as space in a string : \u0020",'abc def','abc\u0020def' ) return array; }
package ten_seconds_to_live.com.five_ants.ten_secs { import flash.display.MovieClip; import ten_seconds_to_live.com.five_ants.ten_secs.object_actions.ObjectActionBase; import ten_seconds_to_live.com.five_ants.ten_secs.object_actions.PlaySound; import ten_seconds_to_live.com.five_ants.ten_secs.object_actions.RemoveItemFromInventory; import ten_seconds_to_live.com.five_ants.ten_secs.object_actions.ShowDialog; import ten_seconds_to_live.com.five_ants.ten_secs.object_actions.ShowPopUp; import ten_seconds_to_live.com.five_ants.ten_secs.xml.TextManager; /** * ... * @author Miguel Santirso */ public class SimpleCat extends InteractiveObject { private var _finished:Boolean; public function SimpleCat(visualObject:MovieClip, roomUtils:RoomUtils) { super(visualObject, roomUtils); } public override function executeAllActions():void { if (_gameplay.hud.inventory.checkItemByID(Items.CATNIP) && PlayerKnowledge.getKnowledge("cat_has_antidote")) { (new ShowPopUp(Items.CAT, "cat")).execute(); (new PlaySound(Sounds.CAT_ANGRY)).execute(); (new RemoveItemFromInventory(Items.CATNIP)).execute(); _gameplay.disableTime(); GameplayState.survived = true; } else if (_gameplay.hud.inventory.checkItemByID(Items.CATNIP)) { (new ShowPopUp(Items.CAT, "cat_noK")).execute(); (new PlaySound(Sounds.CAT_PURRING)).execute(); } else { (new ShowPopUp(Items.CAT, "cat_noI_noK")).execute(); (new PlaySound(Sounds.CAT_PURRING)).execute(); } } } }
package fairygui { import flash.utils.ByteArray; public interface IUIPackageReader { function readDescFile(fileName:String):String; function readResFile(fileName:String):ByteArray; } }
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2008 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package spark.components.supportClasses { import flash.display.Sprite; import spark.core.ISharedDisplayObject; [ExcludeClass] /** * @private * <code>GraphicElement</code> creates shared <code>DsiplayObject</code> of type * <code>InvalidatingSprite</code>. This class does not support mouse interaction. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public class InvalidatingSprite extends Sprite implements ISharedDisplayObject { public function InvalidatingSprite() { super(); mouseChildren = false; mouseEnabled = false; } private var _redrawRequested:Boolean = false; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get redrawRequested():Boolean { return _redrawRequested; } /** * @private */ public function set redrawRequested(value:Boolean):void { _redrawRequested = value; } } }
/* * =BEGIN CLOSED LICENSE * * Copyright (c) 2013-2014 Andras Csizmadia * http://www.vpmedia.eu * * For information about the licensing and copyright please * contact Andras Csizmadia at andras@vpmedia.eu * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * =END CLOSED LICENSE */ package { import flash.utils.ByteArray; /** * RC4 encryption implementation * * @see http://en.wikipedia.org/wiki/RC4 */ public class ARC4 { /** * @private */ private var i:int; /** * @private */ private var j:int; /** * @private */ private var t:int; /** * @private */ private var dp:Vector.<uint>; //---------------------------------- // Constructor //---------------------------------- /** * Constructor */ public function ARC4(key:ByteArray = null) { if (key) setKey(key); } //---------------------------------- // API //---------------------------------- /** * (Re) Initialize with a key */ public function setKey(key:ByteArray):void { // create dp if necessary if (!dp) dp = new Vector.<uint>(); // fill with default values for (i = 0; i < 256; ++i) { dp[i] = i; } // save key j = 0; for (i = 0; i < 256; ++i) { j = (j + dp[i] + key[i % key.length]) & 255; t = dp[i]; dp[i] = dp[j]; dp[j] = t; } // set indexes to start i = 0; j = 0; } /** * Encrypts a byte array data */ public function encrypt(block:ByteArray):void { // get data size const n:uint = block.length; // do xor operation for (var pt:uint = 0; pt < n; pt++) block[pt] ^= next(); } /** * Decrypts a byte array data */ public function decrypt(block:ByteArray):void { // the beauty of XOR. encrypt(block); } /** * Disposes the object */ public function dispose():void { if (dp) dp.length = 0; i = 0; j = 0; } /** * Step encrypt to next block */ public function next():uint { i = (i + 1) & 255; j = (j + dp[i]) & 255; t = dp[i]; dp[i] = dp[j]; dp[j] = t; return dp[(t + dp[i]) & 255]; } //---------------------------------- // Static methods //---------------------------------- /** * Encrypt/Decrypt ByteArray to ByteArray * * @param key The encryption key * @param content The encrypted content ByteArray * * @return Decrypted ByteArray * * Tip: To use string as content: Hex.toArray(Hex.fromString(contentStr)) */ public static function encrypt(key:String, content:ByteArray):ByteArray { const keyHex:String = Hex.fromString(key); const keyByteArray:ByteArray = Hex.toArray(keyHex); const result:ByteArray = content; const rc4:ARC4 = new ARC4(keyByteArray); rc4.decrypt(result); return result; } } }
/////////////////////////////////////////////////////////////////////////// // Copyright (c) 2011 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// package widgets.Geoprocessing.parameters { public class GPParameterFactory { public static function getGPParamFromType(type:String):IGPParameter { var gpParam:IGPParameter; switch (type) { case GPParameterTypes.BOOLEAN: { gpParam = new BooleanParameter(); break; } case GPParameterTypes.DATA_FILE: { gpParam = new DataFileParameter(); break; } case GPParameterTypes.DATE: { gpParam = new DateParameter(); break; } case GPParameterTypes.DOUBLE: { gpParam = new DoubleParameter(); break; } case GPParameterTypes.FEATURE_RECORD_SET_LAYER: { gpParam = new FeatureLayerParameter(); break; } case GPParameterTypes.LINEAR_UNIT: { gpParam = new LinearUnitParameter(); break; } case GPParameterTypes.LONG: { gpParam = new LongParameter(); break; } case GPParameterTypes.MULTI_VALUE_STRING: { gpParam = new MultiValueStringParameter(); break; } case GPParameterTypes.RASTER_DATA_LAYER: { gpParam = new RasterDataLayerParam(); break; } case GPParameterTypes.RECORD_SET: { gpParam = new RecordSetParameter(); break; } case GPParameterTypes.STRING: { gpParam = new StringParameter(); break; } } return gpParam; } } }
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** /* 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; function START(summary) { // print out bugnumber /*if ( BUGNUMBER ) { writeLineToLog ("BUGNUMBER: " + BUGNUMBER ); }*/ XML.setSettings (null); testcases = new Array(); // text field for results tc = 0; /*this.addChild ( tf ); tf.x = 30; tf.y = 50; tf.width = 200; tf.height = 400;*/ //_print(summary); var summaryParts = summary.split(" "); //_print("section: " + summaryParts[0] + "!"); //fileName = summaryParts[0]; } function TEST(section, expected, actual) { AddTestCase(section, expected, actual); } function TEST_XML(section, expected, actual) { var actual_t = typeof actual; var expected_t = typeof expected; if (actual_t != "xml") { // force error on type mismatch TEST(section, new XML(), actual); return; } if (expected_t == "string") { TEST(section, expected, actual.toXMLString()); } else if (expected_t == "number") { TEST(section, String(expected), actual.toXMLString()); } else { reportFailure ("", 'Bad TEST_XML usage: type of expected is "+expected_t+", should be number or string'); } } function reportFailure (section, msg) { trace("~FAILURE: " + section + " | " + msg); } function AddTestCase( description, expect, actual ) { testcases[tc++] = Assert.expectEq(description, "|"+expect+"|", "|"+actual+"|" ); } function myGetNamespace (obj, ns) { if (ns != undefined) { return obj.namespace(ns); } else { return obj.namespace(); } } function NL() { //return java.lang.System.getProperty("line.separator"); return "\n"; } function BUG(arg){ // nothing here } function END() { //test(); } START("13.4.4.37 - XML text()"); //TEST(1, true, XML.prototype.hasOwnProperty("text")); x1 = <alpha> <bravo>one</bravo> <charlie> <bravo>two</bravo> </charlie> </alpha>; TEST_XML(2, "one", x1.bravo.text()); correct = new XMLList(); correct += new XML("one"); correct += new XML("two"); TEST(3, correct, x1..bravo.text()); TEST_XML(4, "", x1.charlie.text()); TEST_XML(5, "", x1.foobar.text()); TEST_XML(6, "one", x1.*.text()); XML.prettyPrinting = false; var xmlDoc = "<employee id='1'>foo<firstname>John</firstname>bar<lastname>Walton</lastname>still<age>25</age>reading</employee>" // propertyName as a string Assert.expectEq( "MYXML = new XML(xmlDoc), MYXML.text().toString()", "foobarstillreading", (MYXML = new XML(xmlDoc), MYXML.text().toString())); Assert.expectEq( "MYXML = new XML(xmlDoc), MYXML.text() instanceof XMLList", true, (MYXML = new XML(xmlDoc), MYXML.text() instanceof XMLList)); Assert.expectEq( "MYXML = new XML('<XML></XML>'), MYXML.text().toString()", "", (MYXML = new XML('<XML></XML>'), MYXML.text().toString())); Assert.expectEq( "MYXML = new XML('<XML></XML>'), MYXML.text() instanceof XMLList", true, (MYXML = new XML('<XML></XML>'), MYXML.text() instanceof XMLList)); xmlDoc = <a>b</a>; Assert.expectEq( "MYXML = new XML(xmlDoc), MYXML.text().toString()", "b", (MYXML = new XML(xmlDoc), MYXML.text().toString())); Assert.expectEq( "MYXML = new XML(xmlDoc), MYXML.text().toString()", "b", (MYXML = new XML(xmlDoc), MYXML.setName('c'), MYXML.text().toString())); END();
package view.localpic { import flash.display.*; import flash.events.*; import flash.geom.*; import flash.ui.*; import model.*; import view.*; import view.avatar.*; import view.ui.*; import fl.controls.Button; import flash.events.MouseEvent; /* * 处理头像选区、缩放、旋转等操作类 */ public class LocalPicArea extends Sprite { public var tip:MovieClip; private var swfStage:Stage; public var cutBox:CutBox; private var cutBox_minW:Number = 30; private var cutBox_minH:Number = 30; private var TurnLeft:SK_TurnLeft; private var TurnRight:SK_TurnRight; private var cutAreaBg:RectBox; private var flagCurX:Number; private var flagCurY:Number; private var flagVX:Number; private var flagVY:Number; private var picRate:Number; private var _cursorScale:SK_CursorScale; public var _sourceBMD:BitmapData; private var _cursorMove:SK_CursorMove; private var _picX:Number; private var _picY:Number; private var _pic_minX:Number = 100; private var _pic_minY:Number = 100; private var _pic_maxX:Number = Param.pSize[0] - 100; private var _pic_maxY:Number = Param.pSize[1] - 100; private var _picW:Number; private var _picH:Number; private var _cutX:Number; private var _cutY:Number; private var _cutW:Number; private var _cutH:Number; private var _picContainer:Sprite; private var _avatar:AvatarArea; public var loaddingUI:MovieClip; public function LocalPicArea() { init(); return; } // 控件初始化 private function init() : void { cutAreaBg = new RectBox(Param.pSize[0], Param.pSize[1]); _picContainer = new Sprite(); _picContainer.addEventListener(MouseEvent.MOUSE_DOWN, moveImg); _picContainer.buttonMode = true; _cursorMove = new SK_CursorMove(); _cursorMove.mouseEnabled = _cursorMove.visible = false; _cursorScale = new SK_CursorScale(); _cursorScale.mouseEnabled = _cursorScale.visible = false; tip = new SK_Tip() as MovieClip; tip.y = tip.x = 1; tip.stop(); tip.mouseEnabled = false; //左右旋转 TurnLeft = new SK_TurnLeft(); TurnRight = new SK_TurnRight(); TurnLeft.y = TurnRight.y = Param.pSize[1] + 12; TurnRight.x = 220; TurnLeft.addEventListener(MouseEvent.CLICK, rotationPicLeft); TurnRight.addEventListener(MouseEvent.CLICK, rotationPicRight); showTunBtns(false); createLoaddingUI(); addChild(cutAreaBg); addChild(tip); addChild(_picContainer); addChild(TurnLeft); addChild(TurnRight); addChild(loaddingUI); addEventListener(Event.ADDED_TO_STAGE, addedToStage); var btnZoomIn = new Button(); var btnZoomOut = new Button(); btnZoomIn.label = "缩小"; btnZoomOut.label = "放大"; btnZoomIn.width = btnZoomOut.width = 50; btnZoomIn.y = btnZoomOut.y = Param.pSize[1] + 12; btnZoomIn.x = 100; btnZoomOut.x = 150; btnZoomIn.addEventListener(MouseEvent.CLICK, zoomIn); btnZoomOut.addEventListener(MouseEvent.CLICK, zoomOut); addChild(btnZoomIn); addChild(btnZoomOut); //底图遮罩 var _picMask:Sprite = new Sprite(); _picMask.graphics.beginFill(0xFF); _picMask.graphics.drawRect(0, 0, Param.pSize[0], Param.pSize[1]); _picMask.graphics.endFill(); _picMask.x = _picMask.y = 1; addChild(_picMask); _picContainer.mask = _picMask; return; } private function resetCursor(event:MouseEvent) : void { Mouse.show(); _cursorMove.visible = _cursorScale.visible = false; cutBox.removeEventListener(MouseEvent.ROLL_OUT, resetCursor); cutBox.removeEventListener(MouseEvent.MOUSE_MOVE, moveCursor); cutBox.removeEventListener(MouseEvent.MOUSE_DOWN, changeCutBox); return; } // 左旋转/右旋转 按钮状态 public function showTunBtns(s:Boolean) : void { TurnRight.visible = TurnLeft.visible = s; return; } private function moveCursor(event:MouseEvent) : void { var sprite:Sprite = null; var tgt = event.target as Sprite; switch(tgt) { case cutBox.cutArea: { sprite = _cursorMove as Sprite; break; } case cutBox.flag: { sprite = _cursorScale as Sprite; break; } default: { break; } } cursorFollow(sprite); event.updateAfterEvent(); return; } private function createLoaddingUI() : void { loaddingUI = new SK_Loading() as MovieClip; loaddingUI.x = Math.ceil(Param.pSize[0] / 2); loaddingUI.y = Math.ceil(Param.pSize[1] / 2); loaddingUI.stop(); loaddingUI.visible = false; return; } // 缩略结束 private function stopResizeCutBox(event:MouseEvent) : void { Mouse.show(); _cursorScale.visible = false; cutBox.addEventListener(MouseEvent.MOUSE_OVER, changeCursor); swfStage.removeEventListener(Event.ENTER_FRAME, resizeCutBox); swfStage.removeEventListener(MouseEvent.MOUSE_UP, stopResizeCutBox); return; } private function addedToStage(event:Event) : void { swfStage = stage; var _cutview = parent as CutView; _avatar = _cutview.avatarArea; removeEventListener(Event.ADDED_TO_STAGE, addedToStage); return; } private function changeCursor(event:MouseEvent) : void { var tgt = event.target as Sprite; if (tgt == cutBox.cutArea) { Mouse.hide(); _cursorMove.visible = true; _cursorScale.visible = false; _cursorMove.x = mouseX; _cursorMove.y = mouseY; } else if (tgt == cutBox.flag) { Mouse.hide(); _cursorScale.visible = true; _cursorMove.visible = false; _cursorScale.x = mouseX; _cursorScale.y = mouseY; } cutBox.addEventListener(MouseEvent.MOUSE_MOVE, moveCursor); cutBox.addEventListener(MouseEvent.MOUSE_DOWN, changeCutBox); cutBox.addEventListener(MouseEvent.MOUSE_OUT, resetCursor); return; } private function cursorFollow(param1:Sprite) : void { param1.x = mouseX; param1.y = mouseY; return; } // 创建 剪切选择框 public function addCutBox(pic:Bitmap) : void { var _w:Number = NaN; var _h:Number = NaN; if (cutBox != null) { removeChild(cutBox); cutBox = null; } if(_cutW && _cutH){ _w = _cutW; _h = _cutH; } else if (pic.width < Param.pSize[2] || pic.height < Param.pSize[3]) { // 原版 _w = pic.width > pic.height ? (pic.height) : (pic.width); if(pic.width/pic.height >= Param.pSize[2]/Param.pSize[3]){ _h = pic.height; _w = _h * Param.pSize[2] / Param.pSize[3]; } else{ _w = pic.width; _h = _w * Param.pSize[3] / Param.pSize[2]; } } else { _w = Param.pSize[2]; _h = Param.pSize[3]; } cutBox = new CutBox(_w, _h); if(_cutX && _cutY){ cutBox.x = _cutX; cutBox.y = _cutY; }else{ cutBox.x = _picContainer.x + (_picContainer.width - cutBox.cutArea.width) * 0.5; cutBox.y = _picContainer.y + (_picContainer.height - cutBox.cutArea.height) * 0.5; } addChild(cutBox); addChild(_cursorMove); addChild(_cursorScale); pic.mask = cutBox.maskArea; cutBox.addEventListener(MouseEvent.MOUSE_OVER, changeCursor); freshAvatar(); return; } public function setLocalPicSize(bmd:BitmapData) : void { var _pic:Bitmap = null; if (tip != null) { removeChild(tip); tip = null; } _sourceBMD = bmd; var _sourcePic:Bitmap = new Bitmap(bmd); var _widthRate = Param.pSize[0] / _sourcePic.width; var _heightRate = Param.pSize[1] / _sourcePic.height; picRate = _widthRate < _heightRate ? (_widthRate) : (_heightRate); //缩略时取最小长宽比 _sourcePic.width = _sourcePic.width * picRate; _sourcePic.scaleY = _sourcePic.scaleX; picZoomPos(); while (_picContainer.numChildren) { _pic = _picContainer.removeChildAt((_picContainer.numChildren - 1)) as Bitmap; _pic = null; } _sourceBMD = _sourcePic.bitmapData; var albumPic = new Bitmap(bmd); // 原图缩略 albumPic.width = _sourcePic.width; albumPic.scaleY = albumPic.scaleX; _sourcePic.alpha = 0.5; _picContainer.addChild(_sourcePic); _picContainer.addChild(albumPic); if(_picX == 0 && _picY == 0){ _picX = _picContainer.x = (Param.pSize[0] - _sourcePic.width) * 0.5 + 1; _picY = _picContainer.y = (Param.pSize[1] - _sourcePic.height) * 0.5 + 1; }else{ picZoomPos(true); } addCutBox(albumPic); showTunBtns(true); return; } /* **************** 左右旋转 **************** */ // 左旋转 private function rotationPicLeft(event:MouseEvent) : void { _sourceBMD = changeBmdLeft(_sourceBMD); setLocalPicSize(_sourceBMD); return; } private function changeBmdLeft(bmd:BitmapData) : BitmapData { var _w = bmd.width; var _h = bmd.height; var newBmd = new BitmapData(_h, _w, false); var _tmp = new Matrix(); _tmp.rotate((-Math.PI) * 0.5); _tmp.translate(0, _w); newBmd.draw(bmd, _tmp); return newBmd; } // 右旋转 private function rotationPicRight(event:MouseEvent) : void { _sourceBMD = changeBmdRight(_sourceBMD); setLocalPicSize(_sourceBMD); return; } private function changeBmdRight(bmd:BitmapData) : BitmapData { var _w = bmd.width; var _h = bmd.height; var newBmd = new BitmapData(_h, _w, false); var _tmp = new Matrix(); _tmp.rotate(Math.PI * 0.5); _tmp.translate(_h, 0); newBmd.draw(bmd, _tmp); return newBmd; } /* **************** 剪切框动作 **************** */ private function getAvatarBMD(_x:Number, _y:Number, picRate:Number, cutbox:CutBox) : BitmapData { picRate *= _picContainer.scaleX; var _w = cutbox.maskArea.width / picRate; var _h = cutbox.maskArea.height / picRate; var _bmd = new BitmapData(_w, _h, false); var _RectangleX = (int((cutbox.x - _x) / picRate) + 0.5) - ((_picContainer.x - _picX) / picRate); var _RectangleY = (int((cutbox.y - _y) / picRate) + 0.5) - ((_picContainer.y - _picY) / picRate); _bmd.copyPixels(_sourceBMD, new Rectangle(_RectangleX, _RectangleY, _w, _h), new Point(0, 0)); return _bmd; } // 拖动 private function moveCutBox(event:MouseEvent) : void { //cutBox.startDrag(false, new Rectangle(_picContainer.x, _picContainer.y, _picContainer.width - cutBox.maskArea.width, _picContainer.height - cutBox.maskArea.height)); cutBox.startDrag(false, new Rectangle(0, 0, Param.pSize[0] - cutBox.maskArea.width, Param.pSize[1] - cutBox.maskArea.height)); _cutX = cutBox.x; _cutY = cutBox.y; freshAvatar(); return; } // 结束拖动 private function stopMoveCutBox(event:Event) : void { cutBox.stopDrag(); swfStage.removeEventListener(MouseEvent.MOUSE_MOVE, moveCutBox); swfStage.removeEventListener(MouseEvent.MOUSE_UP, stopMoveCutBox); return; } // 改变大小 private function changeCutBox(event:MouseEvent) : void { var tgt = event.target as Sprite; switch(tgt) { case cutBox.cutArea: { swfStage.addEventListener(MouseEvent.MOUSE_MOVE, moveCutBox); swfStage.addEventListener(MouseEvent.MOUSE_UP, stopMoveCutBox); break; } case cutBox.flag: { flagVY = mouseY - cutBox.y - cutBox.maskArea.height; flagVX = mouseX - cutBox.x - cutBox.maskArea.width; flagCurX = mouseX; flagCurY = mouseY; cutBox.removeEventListener(MouseEvent.MOUSE_OVER, changeCursor); swfStage.addEventListener(Event.ENTER_FRAME, resizeCutBox); swfStage.addEventListener(MouseEvent.MOUSE_UP, stopResizeCutBox); break; } default: { break; } } return; } private function resizeCutBox(event:Event) : void { var _currW:Number = NaN; var _currH:Number = NaN; var _loc_4:Number = NaN; var _loc_5:Number = NaN; var bmd:BitmapData = null; Mouse.hide(); _cursorScale.x = mouseX; _cursorScale.y = mouseY; _cursorScale.visible = true; if (mouseX != flagCurX || mouseY != flagCurY) { _currW = mouseX - cutBox.x - flagVX; _currH = mouseY - cutBox.y - flagVY; if((cutBox.y + _currH) >= Param.pSize[1]) //if (_currH > _picContainer.y + _picContainer.height - cutBox.y) { //_currH = _picContainer.y + _picContainer.height - cutBox.y; _currH = Param.pSize[1] - cutBox.y; } if (_currH < cutBox_minH) { _currH = cutBox_minH; } if((cutBox.x + _currW) >= Param.pSize[0]) //if (_currW > _picContainer.x + _picContainer.width - cutBox.x) { //_currW = _picContainer.x + _picContainer.width - cutBox.x; _currW = Param.pSize[0] - cutBox.x; } if (_currW < cutBox_minW) { _currW = cutBox_minW; } _loc_4 = _currW - cutBox.maskArea.width; _loc_5 = _currH - cutBox.maskArea.height; if(_loc_4/_loc_5 >= Param.pSize[2]/Param.pSize[3]){ cutBox.maskArea.height = _currH; cutBox.maskArea.width = _currH * Param.pSize[2] / Param.pSize[3]; } else{ cutBox.maskArea.width = _currW; cutBox.maskArea.height = _currW * Param.pSize[3] / Param.pSize[2]; } cutBox.cutArea.width = cutBox.maskArea.width; cutBox.cutArea.height = cutBox.maskArea.height; cutBox.flag.x = cutBox.maskArea.width; cutBox.flag.y = cutBox.maskArea.height; cutBox.border.height = cutBox.maskArea.height - 1; cutBox.border.width = cutBox.maskArea.width - 1; _cutW = cutBox.maskArea.width; _cutH = cutBox.maskArea.height; freshAvatar(); } return; } /* **************** 底图动作 **************** */ // 拖动 private function moveImg(event:MouseEvent) : void { stage.addEventListener(MouseEvent.MOUSE_UP, stopMoveImg); stage.addEventListener(MouseEvent.MOUSE_MOVE, moveCutImg); _picContainer.startDrag(false); return; } private function moveCutImg(event:MouseEvent) : void{ with(_picContainer){ if(x > _pic_maxX) x = _pic_maxX; if((x + width) < _pic_minX) x = _pic_minX - width; if(y > _pic_maxY) y = _pic_maxY; if((y + height) < _pic_minY) y = _pic_minY - height; } freshAvatar(); } // 结束拖动 private function stopMoveImg(event:Event) : void { with(_picContainer){ if(x > _pic_maxX) x = _pic_maxX; if((x + width) < _pic_minX) x = _pic_minX - width; if(y > _pic_maxY) y = _pic_maxY; if((y + height) < _pic_minY) y = _pic_minY - height; } stage.removeEventListener(MouseEvent.MOUSE_MOVE, moveCutImg); stage.removeEventListener(MouseEvent.MOUSE_UP, stopMoveImg); _picContainer.stopDrag(); return; } //底图缩小 private function zoomIn(event:MouseEvent) : void{ if(_picContainer.scaleX < 0.4) return; picZoomPos(); _picContainer.scaleX = _picContainer.scaleY -= 0.1; picZoomPos(true); freshAvatar(); } //底图放大 private function zoomOut(event:MouseEvent) : void{ if(_picContainer.scaleX > 2.5) return; picZoomPos(); _picContainer.scaleX = _picContainer.scaleY += 0.1; picZoomPos(true); freshAvatar(); } //缩放时保持当前中心点 private function picZoomPos(e:Boolean = false){ if(e){ _picContainer.x -= ((_picContainer.width - _picW) / 2); _picContainer.y -= ((_picContainer.height - _picH) / 2); } _picX = _picContainer.x; _picY = _picContainer.y; _picW = _picContainer.width; _picH = _picContainer.height; } //刷新头像预览 private function freshAvatar(){ var avatar = getAvatarBMD(_picX, _picY, picRate, cutBox); _avatar.changeAvatars(avatar); } } }
package com.mintdigital.hemlock.widgets.drawing{ import com.mintdigital.hemlock.Logger; import com.mintdigital.hemlock.display.HemlockSprite; import com.mintdigital.hemlock.events.AppEvent; import com.mintdigital.hemlock.events.DrawEvent; import com.mintdigital.hemlock.utils.ArrayUtils; import com.mintdigital.hemlock.utils.HashUtils; import com.mintdigital.hemlock.widgets.HemlockWidget; import flash.utils.clearInterval; public class DrawingWidget extends HemlockWidget{ // NOTE: This widget's drawing abilities are much smoother when // DebugWidget is disabled. public const COORD_QUEUE_INTERVAL_DELAY:Number = 250; // milliseconds public const BRUSH_COLORS:Array /* of uints */ = [ 0xCC0000, // Red 0xFF9900, // Orange 0xFFFF33, // Yellow 0x00CC00, // Green 0x66CCFF, // Sky blue 0x0000CC, // Blue 0xCC00CC, // Purple 0x663300, // Brown 0xFFECCF, // Flesh 0x999999, // Gray 0x010101 // Black; 0x000000 can't be sent for some reason ]; public const BRUSH_THICKNESSES:Array /* of uints */ = [5, 10, 20]; public const DEFAULT_BRUSH_COLOR:uint = 0x999999; public const DEFAULT_BRUSH_THICKNESS:uint = 5; internal var brushes:Object = {}; // Key: JID string // Value: Object of brush data (e.g., color, thickness) internal var coordQueues:Object = {}; // Key: JID string // Value: Array of [x,y] coordinates for that user internal var coordQueueIntervals:Object = {}; // Key: JID string // Value: uint ID of an interval for processing user's coordQueue public function DrawingWidget(parentSprite:HemlockSprite, options:Object = null){ // super(parentSprite, options); super(parentSprite, HashUtils.merge({ delegates: { views: new DrawingWidgetViews(this), events: new DrawingWidgetEvents(this) } }, options)); // Send intro text to ChatroomWidget, if any var intro:String = 'This is a demo of DrawingWidget, which lets people ' + 'draw together on a single canvas.'; dispatcher.dispatchEvent(new AppEvent(AppEvent.CHATROOM_STATUS, { message: intro })); // Prepare coordinate queue for current user coordQueues[jid.toString()] = []; // Prepare brush for current user brushes[jid.toString()] = { color: DEFAULT_BRUSH_COLOR, thickness: DEFAULT_BRUSH_THICKNESS }; delegates.views.highlightBrushColor(DEFAULT_BRUSH_COLOR); delegates.views.highlightBrushThickness(DEFAULT_BRUSH_THICKNESS); } //-------------------------------------- // Internal helpers //-------------------------------------- internal function boundCoords(coords:Array /* of [x,y] */):Array /* of [x,y] */{ // Modifies `coords` if either x or y is out of bounds, and // returns the result. if(!views.canvas){ return coords; } // Set margin to radius of widest brush so that, when the brush is // used, its outer edges don't extend past canvas. const MARGIN:uint = ArrayUtils.max(BRUSH_THICKNESSES) * 0.5; var minX:uint = MARGIN, minY:uint = MARGIN, maxX:uint = views.canvas.width - MARGIN, maxY:uint = views.canvas.height - 50 - MARGIN; coords[0] = Math.max(minX, Math.min(maxX, coords[0])); coords[1] = Math.max(minY, Math.min(maxY, coords[1])); return coords; } internal function sendBrushData(key:String = null):void{ // Sends a DataMessage containing the current user's brush data. // If `key` is provided, only the matching brush data is sent. Logger.debug('DrawingWidget::sendBrushData()'); var jidString:String = jid.toString(), brush:Object = brushes[jidString], payload:Object = { from: jidString }; if(key){ payload[key] = brush[key]; }else{ payload = HashUtils.merge(payload, brush); } sendDataMessage(DrawEvent.BRUSH, payload); } internal function sendCoordQueue(limit:uint = 0):void{ // `limit` determines how many coordinate pairs to send from // `coordQueue`. If `limit` is 0, all coordinate pairs are // sent. Logger.debug('DrawingWidget::sendCoordQueue() : limit = ' + limit); var jidString:String = jid.toString(), finalCoords:Array /* [x,y] */, coordQueue:Array /* of [x,y]s */ = coordQueues[jidString]; if(limit < 1 || limit >= coordQueue.length){ limit = coordQueue.length; finalCoords = coordQueue[limit - 1]; } var coords:Array /* of [x,y]s */ = coordQueues[jidString].splice(0, limit); sendDataMessage(DrawEvent.COORDS, { from: jidString, coords: coords }); if(finalCoords){ if(finalCoords[0] != -1 || finalCoords[1] != -1){ // Preserve final coords as start of next line coordQueues[jidString] = [finalCoords]; }else{ // User signaled end-of-path clearCoordQueue(jidString); } } } internal function processCoordQueue(jidString:String):void{ // Draws the next line in the coordinate queue for the given user. Logger.debug('DrawingWidget::processCoordQueue() : jidString = ' + jidString); var coordQueue:Array /* of [x,y]s */ = coordQueues[jidString], brush:Object = brushes[jidString]; if(coordQueue.length == 0){ clearCoordQueue(jidString); return; } // Check if sender ended path while(coordQueue.length > 0 && (coordQueue[0] && coordQueue[0][0] == -1 && coordQueue[0][1] == -1 || coordQueue[1] && coordQueue[1][0] == -1 && coordQueue[1][1] == -1) ){ while(coordQueue[0] && coordQueue[0][0] == -1 && coordQueue[0][1] == -1){ coordQueues[jidString].shift(); // Remove end-of-path coord coordQueue = coordQueues[jidString]; } while(coordQueue[1] && coordQueue[1][0] == -1 && coordQueue[1][1] == -1){ delegates.views.drawDot({ x: coordQueue[0][0], y: coordQueue[0][1], color: brush.color, thickness: brush.thickness }); coordQueues[jidString].shift(); // Remove dot coord coordQueues[jidString].shift(); // Remove end-of-path coord coordQueue = coordQueues[jidString]; } } if(coordQueue.length > 1){ delegates.views.drawLine({ fromX: coordQueue[0][0], fromY: coordQueue[0][1], toX: coordQueue[1][0], toY: coordQueue[1][1], color: brush.color, thickness: brush.thickness }); coordQueues[jidString].shift(); coordQueue = coordQueues[jidString]; }else if(coordQueue.length == 0){ clearCoordQueue(jidString); } } internal function clearCoordQueue(jidString:String):void{ // Clears the coordinate queue for given user. coordQueues[jidString] = []; clearInterval(coordQueueIntervals[jidString]); coordQueueIntervals[jidString] = NaN; } internal function clearCoordQueues():void{ // Clears coordinate queues for all users and stops drawing. Logger.debug('DrawingWidget::clearCoordQueues()'); for(var jidString:String in coordQueues){ clearCoordQueue(jidString); } } } }
package org.fatlib.interfaces { /** * Objects that implement this object iterate linearly through some data set */ public interface IIterator { /** * Are there any elements left to iterate through? */ function get hasNext():Boolean; /** * Get the next element */ function get next():*; /** * Get the iterator's current position within the dataset, starting at 0 */ function get position():int } }
/* ***** 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 NoExtraArgFunction { class TestObjInner{ public function returnRest(... rest):Number { return rest.length; } } public class TestObj extends TestObjInner {} }
package sh.saqoo.motion { import caurina.transitions.Tweener; import flash.display.Sprite; public class TweenerMotionProvider implements IMotionProvider { private var _dummy:Sprite; private var _running:Boolean; public function TweenerMotionProvider() { super(); this._running = false; } public function addTween(opt:Object):void { Tweener.addTween(this, opt); } public function get currnet():Number { return 0; } } }
/* * Copyright 2014 Mozilla Foundation * * 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 flash.system { import flash.events.EventDispatcher; [native(cls='AuthorizedFeaturesLoaderClass')] public final class AuthorizedFeaturesLoader extends EventDispatcher { public function AuthorizedFeaturesLoader() {} public native function get authorizedFeatures():AuthorizedFeatures; public native function loadAuthorizedFeatures():void; internal native function makeGlobal():void; } }
// Decompiled by AS3 Sorcerer 6.08 // www.as3sorcerer.com //kabam.rotmg.assets.EmbeddedAssets_candyColWholeEmbed_ package kabam.rotmg.assets { import mx.core.ByteArrayAsset; [Embed(source="EmbeddedAssets_candyColWhole.dat", mimeType="application/octet-stream")] public class EmbeddedAssets_candyColWholeEmbed_ extends ByteArrayAsset { } }//package kabam.rotmg.assets
package com.company.assembleegameclient.objects { import com.company.assembleegameclient.engine3d.ObjectFace3D; import com.company.assembleegameclient.parameters.Parameters; import com.company.util.AssetLibrary; import flash.display.BitmapData; import flash.geom.Vector3D; import kabam.rotmg.stage3D.GraphicsFillExtra; public class ConnectedWall extends ConnectedObject { protected var objectXML_:XML; protected var bI_:Number = 0.5; protected var tI_:Number = 0.25; protected var h_:Number = 1; protected var wallRepeat_:Boolean; protected var topRepeat_:Boolean; public function ConnectedWall(_arg_1:XML) { super(_arg_1); this.objectXML_ = _arg_1; if (_arg_1.hasOwnProperty("BaseIndent")) { this.bI_ = (0.5 - Number(_arg_1.BaseIndent)); } if (_arg_1.hasOwnProperty("TopIndent")) { this.tI_ = (0.5 - Number(_arg_1.TopIndent)); } if (_arg_1.hasOwnProperty("Height")) { this.h_ = Number(_arg_1.Height); } this.wallRepeat_ = !(_arg_1.hasOwnProperty("NoWallTextureRepeat")); this.topRepeat_ = !(_arg_1.hasOwnProperty("NoTopTextureRepeat")); } override protected function buildDot():void { var _local_1:Vector3D = new Vector3D(-(this.bI_), -(this.bI_), 0); var _local_2:Vector3D = new Vector3D(this.bI_, -(this.bI_), 0); var _local_3:Vector3D = new Vector3D(this.bI_, this.bI_, 0); var _local_4:Vector3D = new Vector3D(-(this.bI_), this.bI_, 0); var _local_5:Vector3D = new Vector3D(-(this.tI_), -(this.tI_), this.h_); var _local_6:Vector3D = new Vector3D(this.tI_, -(this.tI_), this.h_); var _local_7:Vector3D = new Vector3D(this.tI_, this.tI_, this.h_); var _local_8:Vector3D = new Vector3D(-(this.tI_), this.tI_, this.h_); this.addQuad(_local_6, _local_5, _local_1, _local_2, texture_, true, true); this.addQuad(_local_7, _local_6, _local_2, _local_3, texture_, true, true); this.addQuad(_local_5, _local_8, _local_4, _local_1, texture_, true, true); this.addQuad(_local_8, _local_7, _local_3, _local_4, texture_, true, true); var _local_9:BitmapData = texture_; if (this.objectXML_.hasOwnProperty("DotTexture")) { _local_9 = AssetLibrary.getImageFromSet(String(this.objectXML_.DotTexture.File), int(this.objectXML_.DotTexture.Index)); } this.addTop([_local_5, _local_6, _local_7, _local_8], new <Number>[0.25, 0.25, 0.75, 0.25, 0.25, 0.75], _local_9); } override protected function buildShortLine():void { var _local_1:Vector3D = new Vector3D(-(this.bI_), -0.5, 0); var _local_2:Vector3D = new Vector3D(this.bI_, -0.5, 0); var _local_3:Vector3D = new Vector3D(this.bI_, this.bI_, 0); var _local_4:Vector3D = new Vector3D(-(this.bI_), this.bI_, 0); var _local_5:Vector3D = new Vector3D(-(this.tI_), -0.5, this.h_); var _local_6:Vector3D = new Vector3D(this.tI_, -0.5, this.h_); var _local_7:Vector3D = new Vector3D(this.tI_, this.tI_, this.h_); var _local_8:Vector3D = new Vector3D(-(this.tI_), this.tI_, this.h_); this.addQuad(_local_7, _local_6, _local_2, _local_3, texture_, true, false); this.addQuad(_local_5, _local_8, _local_4, _local_1, texture_, false, true); this.addQuad(_local_8, _local_7, _local_3, _local_4, texture_, true, true); var _local_9:BitmapData = texture_; if (this.objectXML_.hasOwnProperty("ShortLineTexture")) { _local_9 = AssetLibrary.getImageFromSet(String(this.objectXML_.ShortLineTexture.File), int(this.objectXML_.ShortLineTexture.Index)); } this.addTop([_local_5, _local_6, _local_7, _local_8], new <Number>[0.25, 0, 0.75, 0, 0.25, 0.75], _local_9); } override protected function buildL():void { var _local_1:Vector3D = new Vector3D(-(this.bI_), -0.5, 0); var _local_2:Vector3D = new Vector3D(this.bI_, -0.5, 0); var _local_3:Vector3D = new Vector3D(this.bI_, -(this.bI_), 0); var _local_4:Vector3D = new Vector3D(0.5, -(this.bI_), 0); var _local_5:Vector3D = new Vector3D(0.5, this.bI_, 0); var _local_6:Vector3D = new Vector3D(-(this.bI_), this.bI_, 0); var _local_7:Vector3D = new Vector3D(-(this.tI_), -0.5, this.h_); var _local_8:Vector3D = new Vector3D(this.tI_, -0.5, this.h_); var _local_9:Vector3D = new Vector3D(this.tI_, -(this.tI_), this.h_); var _local_10:Vector3D = new Vector3D(0.5, -(this.tI_), this.h_); var _local_11:Vector3D = new Vector3D(0.5, this.tI_, this.h_); var _local_12:Vector3D = new Vector3D(-(this.tI_), this.tI_, this.h_); this.addBit(_local_9, _local_8, _local_2, _local_3, texture_, N2, true, true, true); this.addBit(_local_10, _local_9, _local_3, _local_4, texture_, N2, false, true, false); this.addQuad(_local_12, _local_11, _local_5, _local_6, texture_, true, false); this.addQuad(_local_7, _local_12, _local_6, _local_1, texture_, false, true); var _local_13:BitmapData = texture_; if (this.objectXML_.hasOwnProperty("LTexture")) { _local_13 = AssetLibrary.getImageFromSet(String(this.objectXML_.LTexture.File), int(this.objectXML_.LTexture.Index)); } this.addTop([_local_7, _local_8, _local_9, _local_10, _local_11, _local_12], new <Number>[0.25, 0, 0.75, 0, 0.25, 0.75], _local_13); } override protected function buildLine():void { var _local_1:Vector3D = new Vector3D(-(this.bI_), -0.5, 0); var _local_2:Vector3D = new Vector3D(this.bI_, -0.5, 0); var _local_3:Vector3D = new Vector3D(this.bI_, 0.5, 0); var _local_4:Vector3D = new Vector3D(-(this.bI_), 0.5, 0); var _local_5:Vector3D = new Vector3D(-(this.tI_), -0.5, this.h_); var _local_6:Vector3D = new Vector3D(this.tI_, -0.5, this.h_); var _local_7:Vector3D = new Vector3D(this.tI_, 0.5, this.h_); var _local_8:Vector3D = new Vector3D(-(this.tI_), 0.5, this.h_); this.addQuad(_local_7, _local_6, _local_2, _local_3, texture_, false, false); this.addQuad(_local_5, _local_8, _local_4, _local_1, texture_, false, false); var _local_9:BitmapData = texture_; if (this.objectXML_.hasOwnProperty("LineTexture")) { _local_9 = AssetLibrary.getImageFromSet(String(this.objectXML_.LineTexture.File), int(this.objectXML_.LineTexture.Index)); } this.addTop([_local_5, _local_6, _local_7, _local_8], new <Number>[0.25, 0, 0.75, 0, 0.25, 1], _local_9); } override protected function buildT():void { var _local_1:Vector3D = new Vector3D(-(this.bI_), -0.5, 0); var _local_2:Vector3D = new Vector3D(this.bI_, -0.5, 0); var _local_3:Vector3D = new Vector3D(this.bI_, -(this.bI_), 0); var _local_4:Vector3D = new Vector3D(0.5, -(this.bI_), 0); var _local_5:Vector3D = new Vector3D(0.5, this.bI_, 0); var _local_6:Vector3D = new Vector3D(-0.5, this.bI_, 0); var _local_7:Vector3D = new Vector3D(-0.5, -(this.bI_), 0); var _local_8:Vector3D = new Vector3D(-(this.bI_), -(this.bI_), 0); var _local_9:Vector3D = new Vector3D(-(this.tI_), -0.5, this.h_); var _local_10:Vector3D = new Vector3D(this.tI_, -0.5, this.h_); var _local_11:Vector3D = new Vector3D(this.tI_, -(this.tI_), this.h_); var _local_12:Vector3D = new Vector3D(0.5, -(this.tI_), this.h_); var _local_13:Vector3D = new Vector3D(0.5, this.tI_, this.h_); var _local_14:Vector3D = new Vector3D(-0.5, this.tI_, this.h_); var _local_15:Vector3D = new Vector3D(-0.5, -(this.tI_), this.h_); var _local_16:Vector3D = new Vector3D(-(this.tI_), -(this.tI_), this.h_); this.addBit(_local_11, _local_10, _local_2, _local_3, texture_, N2, true); this.addBit(_local_12, _local_11, _local_3, _local_4, texture_, N2, false); this.addQuad(_local_14, _local_13, _local_5, _local_6, texture_, false, false); this.addBit(_local_16, _local_15, _local_7, _local_8, texture_, N0, true); this.addBit(_local_9, _local_16, _local_8, _local_1, texture_, N0, false); var _local_17:BitmapData = texture_; if (this.objectXML_.hasOwnProperty("TTexture")) { _local_17 = AssetLibrary.getImageFromSet(String(this.objectXML_.TTexture.File), int(this.objectXML_.TTexture.Index)); } this.addTop([_local_9, _local_10, _local_11, _local_12, _local_13, _local_14, _local_15, _local_16], new <Number>[0.25, 0, 0.75, 0, 0.25, 0.25], _local_17); } override protected function buildCross():void { var _local_1:Vector3D = new Vector3D(-(this.bI_), -0.5, 0); var _local_2:Vector3D = new Vector3D(this.bI_, -0.5, 0); var _local_3:Vector3D = new Vector3D(this.bI_, -(this.bI_), 0); var _local_4:Vector3D = new Vector3D(0.5, -(this.bI_), 0); var _local_5:Vector3D = new Vector3D(0.5, this.bI_, 0); var _local_6:Vector3D = new Vector3D(this.bI_, this.bI_, 0); var _local_7:Vector3D = new Vector3D(this.bI_, 0.5, 0); var _local_8:Vector3D = new Vector3D(-(this.bI_), 0.5, 0); var _local_9:Vector3D = new Vector3D(-(this.bI_), this.bI_, 0); var _local_10:Vector3D = new Vector3D(-0.5, this.bI_, 0); var _local_11:Vector3D = new Vector3D(-0.5, -(this.bI_), 0); var _local_12:Vector3D = new Vector3D(-(this.bI_), -(this.bI_), 0); var _local_13:Vector3D = new Vector3D(-(this.tI_), -0.5, this.h_); var _local_14:Vector3D = new Vector3D(this.tI_, -0.5, this.h_); var _local_15:Vector3D = new Vector3D(this.tI_, -(this.tI_), this.h_); var _local_16:Vector3D = new Vector3D(0.5, -(this.tI_), this.h_); var _local_17:Vector3D = new Vector3D(0.5, this.tI_, this.h_); var _local_18:Vector3D = new Vector3D(this.tI_, this.tI_, this.h_); var _local_19:Vector3D = new Vector3D(this.tI_, 0.5, this.h_); var _local_20:Vector3D = new Vector3D(-(this.tI_), 0.5, this.h_); var _local_21:Vector3D = new Vector3D(-(this.tI_), this.tI_, this.h_); var _local_22:Vector3D = new Vector3D(-0.5, this.tI_, this.h_); var _local_23:Vector3D = new Vector3D(-0.5, -(this.tI_), this.h_); var _local_24:Vector3D = new Vector3D(-(this.tI_), -(this.tI_), this.h_); this.addBit(_local_15, _local_14, _local_2, _local_3, texture_, N2, true); this.addBit(_local_16, _local_15, _local_3, _local_4, texture_, N2, false); this.addBit(_local_18, _local_17, _local_5, _local_6, texture_, N4, true); this.addBit(_local_19, _local_18, _local_6, _local_7, texture_, N4, false); this.addBit(_local_21, _local_20, _local_8, _local_9, texture_, N6, true); this.addBit(_local_22, _local_21, _local_9, _local_10, texture_, N6, false); this.addBit(_local_24, _local_23, _local_11, _local_12, texture_, N0, true); this.addBit(_local_13, _local_24, _local_12, _local_1, texture_, N0, false); var _local_25:BitmapData = texture_; if (this.objectXML_.hasOwnProperty("CrossTexture")) { _local_25 = AssetLibrary.getImageFromSet(String(this.objectXML_.CrossTexture.File), int(this.objectXML_.CrossTexture.Index)); } this.addTop([_local_13, _local_14, _local_15, _local_16, _local_17, _local_18, _local_19, _local_20, _local_21, _local_22, _local_23, _local_24], new <Number>[0.25, 0, 0.75, 0, 0.25, 0.25], _local_25); } protected function addQuad(_arg_1:Vector3D, _arg_2:Vector3D, _arg_3:Vector3D, _arg_4:Vector3D, _arg_5:BitmapData, _arg_6:Boolean, _arg_7:Boolean):void { var _local_11:Number; var _local_12:Number; var _local_13:Vector.<Number>; var _local_8:int = (obj3D_.vL_.length / 3); obj3D_.vL_.push(_arg_1.x, _arg_1.y, _arg_1.z, _arg_2.x, _arg_2.y, _arg_2.z, _arg_3.x, _arg_3.y, _arg_3.z, _arg_4.x, _arg_4.y, _arg_4.z); var _local_9:Number = ((_arg_6) ? (-((this.bI_ - this.tI_)) / ((1 - (this.bI_ - this.tI_)) - ((_arg_7) ? (this.bI_ - this.tI_) : 0))) : 0); obj3D_.uvts_.push(0, 0, 0, 1, 0, 0, 1, 1, 0, _local_9, 1, 0); var _local_10:ObjectFace3D = new ObjectFace3D(obj3D_, new <int>[_local_8, (_local_8 + 1), (_local_8 + 2), (_local_8 + 3)]); _local_10.texture_ = _arg_5; _local_10.bitmapFill_.repeat = this.wallRepeat_; obj3D_.faces_.push(_local_10); if ((((GraphicsFillExtra.getVertexBuffer(_local_10.bitmapFill_) == null)) && (Parameters.isGpuRender()))) { _local_11 = 0; _local_12 = 0; if (_arg_6) { _local_11 = _local_9; } if (_arg_7) { _local_12 = -(_local_9); } if ((((((((_local_12 == 0)) && ((_local_11 == 0)))) && (_arg_7))) && ((_arg_4.x == -0.5)))) { _local_12 = 0.34; } _local_13 = Vector.<Number>([-0.5, 0.5, 0, 0, 0, 0.5, 0.5, 0, 1, 0, (-0.5 + _local_11), -0.5, 0, 0, 1, (0.5 + _local_12), -0.5, 0, 1, 1]); GraphicsFillExtra.setVertexBuffer(_local_10.bitmapFill_, _local_13); } } protected function addBit(_arg_1:Vector3D, _arg_2:Vector3D, _arg_3:Vector3D, _arg_4:Vector3D, _arg_5:BitmapData, _arg_6:Vector3D, _arg_7:Boolean, _arg_8:Boolean = false, _arg_9:Boolean = false):void { var _local_12:Vector.<Number>; var _local_10:int = (obj3D_.vL_.length / 3); obj3D_.vL_.push(_arg_1.x, _arg_1.y, _arg_1.z, _arg_2.x, _arg_2.y, _arg_2.z, _arg_3.x, _arg_3.y, _arg_3.z, _arg_4.x, _arg_4.y, _arg_4.z); if (_arg_7) { obj3D_.uvts_.push((-0.5 + this.tI_), 0, 0, 0, 0, 0, 0, 0, 0, (-0.5 + this.bI_), 1, 0); } else { obj3D_.uvts_.push(1, 0, 0, (1.5 - this.tI_), 0, 0, 0, 0, 0, 1, 1, 0); } var _local_11:ObjectFace3D = new ObjectFace3D(obj3D_, new <int>[_local_10, (_local_10 + 1), (_local_10 + 2), (_local_10 + 3)]); _local_11.texture_ = _arg_5; _local_11.bitmapFill_.repeat = this.wallRepeat_; _local_11.normalL_ = _arg_6; if (((!(Parameters.isGpuRender())) && (!(_arg_8)))) { obj3D_.faces_.push(_local_11); } else { if (_arg_8) { if (_arg_9) { _local_12 = Vector.<Number>([-0.75, 0.5, 0, 0, 0, -0.5, 0.5, 0, 1, 0, -0.75, -0.5, 0, 0, 1, -0.5, -0.5, 0, 1, 1]); } else { _local_12 = Vector.<Number>([0.5, 0.5, 0, 0, 0, 0.75, 0.5, 0, 1, 0, 0.5, -0.5, 0, 0, 1, 0.75, -0.5, 0, 1, 1]); } GraphicsFillExtra.setVertexBuffer(_local_11.bitmapFill_, _local_12); obj3D_.faces_.push(_local_11); } } } protected function addTop(_arg_1:Array, _arg_2:Vector.<Number>, _arg_3:BitmapData):void { var _local_8:ObjectFace3D; var _local_10:Vector.<Number>; var _local_11:int; var _local_12:Array; var _local_13:Array; var _local_14:Array; var _local_15:int; var _local_16:int; var _local_17:int; var _local_4:int = (obj3D_.vL_.length / 3); var _local_5:Vector.<int> = new Vector.<int>(); var _local_6:uint; while (_local_6 < _arg_1.length) { obj3D_.vL_.push(_arg_1[_local_6].x, _arg_1[_local_6].y, _arg_1[_local_6].z); _local_5.push((_local_4 + _local_6)); if (_local_6 == 0) { obj3D_.uvts_.push(_arg_2[0], _arg_2[1], 0); } else { if (_local_6 == 1) { obj3D_.uvts_.push(_arg_2[2], _arg_2[3], 0); } else { if (_local_6 == (_arg_1.length - 1)) { obj3D_.uvts_.push(_arg_2[4], _arg_2[5], 0); } else { obj3D_.uvts_.push(0, 0, 0); } } } _local_6++; } var _local_7:ObjectFace3D = new ObjectFace3D(obj3D_, _local_5); _local_7.texture_ = _arg_3; _local_7.bitmapFill_.repeat = this.topRepeat_; obj3D_.faces_.push(_local_7); if ((((_local_5.length == 6)) && (Parameters.isGpuRender()))) { _local_8 = new ObjectFace3D(obj3D_, _local_5); _local_8.texture_ = _arg_3; _local_8.bitmapFill_.repeat = this.topRepeat_; obj3D_.faces_.push(_local_8); } var _local_9:int; if ((((((_local_5.length == 4)) && ((GraphicsFillExtra.getVertexBuffer(_local_7.bitmapFill_) == null)))) && (Parameters.isGpuRender()))) { _local_10 = new Vector.<Number>(); _local_9 = 0; while (_local_9 < _local_5.length) { if (_local_9 == 3) { _local_11 = 2; } else { if (_local_9 == 2) { _local_11 = 3; } else { _local_11 = _local_9; } } _local_10.push(obj3D_.vL_[(_local_5[_local_11] * 3)], (obj3D_.vL_[((_local_5[_local_11] * 3) + 1)] * -1), obj3D_.vL_[((_local_5[_local_11] * 3) + 2)], obj3D_.uvts_[(_local_5[(((_local_11) != 2) ? _local_11 : (_local_11 - 1))] * 3)], obj3D_.uvts_[((_local_5[(((_local_11) != 2) ? _local_11 : (_local_11 + 1))] * 3) + 1)]); _local_9++; } GraphicsFillExtra.setVertexBuffer(_local_7.bitmapFill_, _local_10); } else { if ((((((_local_5.length == 6)) && ((GraphicsFillExtra.getVertexBuffer(_local_7.bitmapFill_) == null)))) && (Parameters.isGpuRender()))) { _local_12 = [0, 1, 5, 2]; _local_13 = [2, 3, 5, 4]; _local_14 = [5, 0, 2, 1]; _local_15 = 0; while (_local_15 < 2) { if (_local_15 == 1) { _local_12 = _local_13; } _local_10 = new Vector.<Number>(); _local_16 = 0; _local_17 = 0; for each (_local_9 in _local_12) { if (_local_15 == 1) { _local_17 = _local_14[_local_16]; } else { _local_17 = _local_9; } _local_10.push(obj3D_.vL_[(_local_5[_local_9] * 3)], (obj3D_.vL_[((_local_5[_local_9] * 3) + 1)] * -1), obj3D_.vL_[((_local_5[_local_9] * 3) + 2)], obj3D_.uvts_[(_local_5[(((_local_17) != 2) ? _local_17 : (_local_17 - 1))] * 3)], obj3D_.uvts_[((_local_5[(((_local_17) != 2) ? _local_17 : (_local_17 + 1))] * 3) + 1)]); _local_16++; } if (_local_15 == 1) { GraphicsFillExtra.setVertexBuffer(_local_8.bitmapFill_, _local_10); } else { GraphicsFillExtra.setVertexBuffer(_local_7.bitmapFill_, _local_10); } _local_15++; } } } } } }//package com.company.assembleegameclient.objects
/** * * Main game logic and user interface controls. * * (C)opyright 2016 * * This source code is protected by copyright and distributed under license. * Please see the root LICENSE file for terms and conditions. * */ package { import HTTPComm; import crypto.RNG; import flash.display.MovieClip; import flash.text.TextFormat; import interfaces.ICommunication; import flash.display.NativeWindow; import flash.display.NativeWindowInitOptions; import flash.display.NativeWindowSystemChrome; import flash.display.NativeWindowType; import flash.text.TextField; import ui.DialogManager; import FaucetWindow; import events.FaucetWindowEvent; import ui.Paytable; import HelpWindow; import HostInfoWindow; import org.xxtea.XXTEA; import org.xxtea.Base64;; import flash.events.Event; import flash.events.FocusEvent; import flash.utils.ByteArray; import ui.ColourSquare; import ui.LayoutController; import SoundController; import ui.Reel; import ui.ResultsSelector; import flash.events.MouseEvent; import ui.ReelController; import events.ReelControllerEvent; import flash.net.SharedObject; import flash.utils.setTimeout; import com.greensock.TweenLite; import com.greensock.easing.Strong; import flash.filters.ColorMatrixFilter; import AddressValidator; public class GameController { public static const _gameInfo:Object = {name:"Faucet Slot", ID:1}; private var _demoMode:Boolean = false; //local "demo" mode or live private var _config:XML; private var _reelController:ReelController; private var _demoKey:String; //Base64-encoded private var _faucetWindow:FaucetWindow; private var _paytable:Paytable; private var _helpWindow:HelpWindow; private var _rng:RNG = new RNG(128); private var _comm:ICommunication; private var _balance:Number = 0; private var _shares:Number = 0; private var _wager:Number = 1000; private var _accountAddressOriginalY:Number = 0; private var _lastGameResults:Object = null; public function GameController(config:XML) { this._config = config; this._reelController = ReelController(LayoutController.element("reels")); this._reelController.addEventListener(ReelControllerEvent.REELS_STOPPED, this.onReelAnimationFinished); trace ("Reel configuration JSON:"); trace (this._reelController.JSONdefinition); this._accountAddressOriginalY = LayoutController.element("payoutAddress").y; this.hidePayoutAddress(); ResultsSelector.hideSelectors(0); LayoutController.element("soundToggle").addEventListener(MouseEvent.CLICK, this.onToggleSounds); if (this.soundsEnabled) { trace ("Enabling sounds"); LayoutController.element("soundToggle").selected = true; SoundController.volume=1; } else { trace ("Disabling sounds"); LayoutController.element("soundToggle").selected = false; SoundController.volume=0; } LayoutController.element("spinButton").addEventListener(MouseEvent.CLICK, this.onSpinClick); //LayoutController.element("submitButton").enabled = false; this.disableElement(LayoutController.element("spinButton")); LayoutController.element("submitButton").addEventListener(MouseEvent.CLICK, this.onSubmitClick); this.disableElement(LayoutController.element("submitButton")); LayoutController.element("submitButton").visible = false; LayoutController.element("payoutAddressToggle").addEventListener(MouseEvent.CLICK, this.showPayoutAddress); this.disableElement(LayoutController.element("addFunds")); LayoutController.element("addFunds").addEventListener(MouseEvent.CLICK, this.onAddFundsClick); LayoutController.element("helpButton").addEventListener(MouseEvent.CLICK, this.openHelp); LayoutController.element("payoutAddress").addEventListener(FocusEvent.FOCUS_OUT, this.onPayoutAddressLoseFocus); LayoutController.element("payoutAddress").border = true; LayoutController.element("payoutAddress").background = true; LayoutController.element("payoutAddress").text = payoutAddress; LayoutController.element("payoutAddress").stage.addEventListener(MouseEvent.MOUSE_DOWN, this.onMouseDown); this._paytable = new Paytable(LayoutController.element("paytable")); this._paytable.hide(true); LayoutController.element("shareholder_icon").content.addEventListener(MouseEvent.MOUSE_DOWN, this.getShareholderInfo); LayoutController.element("thresholdPercent").useHandCursor = true; LayoutController.element("thresholdPercent").buttonMode = true; LayoutController.element("thresholdPercent").addEventListener(MouseEvent.MOUSE_DOWN, this.getShareholderInfo); this.connectToHost(); } private function displayPayoutAddressError(errString:String):void { var format:TextFormat = new TextFormat(); format.color = 0xFFFFFF; TextField(LayoutController.element("payoutAddress")).backgroundColor = 0xFF0000; TextField(LayoutController.element("payoutAddress")).addEventListener(Event.CHANGE, this.onPayoutAddressUpdate); LayoutController.element("payoutAddress").text = errString; TextField(LayoutController.element("payoutAddress")).setTextFormat(format); } private function onPayoutAddressUpdate(eventObj:Event):void { eventObj.target.removeEventListener(Event.CHANGE, this.onPayoutAddressUpdate); var format:TextFormat = new TextFormat(); format.color = 0x000000; TextField(LayoutController.element("payoutAddress")).setTextFormat(format); TextField(LayoutController.element("payoutAddress")).backgroundColor = 0xFFFFFF; } private function get payoutAddress():String { var so:SharedObject = SharedObject.getLocal("cypherslot"); if ((so.data["payoutAddress"] == null) || (so.data["payoutAddress"] == null)) { so.data.payoutAddress = ""; so.flush(); } return (so.data.payoutAddress); } private function set payoutAddress(addrSet:String):void { trace ("Storing new payout address: " + addrSet); var so:SharedObject = SharedObject.getLocal("cypherslot"); so.data.payoutAddress = addrSet; so.flush(); } private function get soundsEnabled():Boolean { var so:SharedObject = SharedObject.getLocal("cypherslot"); if ((so.data["soundsEnabled"] == null) || (so.data["soundsEnabled"] == null)) { so.data.soundsEnabled = true; so.flush(); } return (so.data.soundsEnabled); } private function set soundsEnabled(enabledSet:Boolean):void { var so:SharedObject = SharedObject.getLocal("cypherslot"); so.data.soundsEnabled = enabledSet; so.flush(); } private function onToggleSounds(eventObj:MouseEvent):void { this.soundsEnabled = LayoutController.element("soundToggle").selected; if (this.soundsEnabled) { trace ("Enabling sounds"); SoundController.volume=1; } else { trace ("Disabling sounds"); SoundController.volume=0; } } private function onMouseDown(eventObj:MouseEvent):void { var addressObj:* = LayoutController.element("payoutAddress"); var addressButton:* = LayoutController.element("payoutAddressToggle"); if (!addressObj.hitTestPoint(eventObj.stageX, eventObj.stageY) && !addressButton.hitTestPoint(eventObj.stageX, eventObj.stageY) && (addressObj.y < addressObj.stage.stageHeight)) { trace ("Updating payout address"); this.updatePayoutAddress(); } } private function updatePayoutAddress():void { var address:String = LayoutController.element("payoutAddress").text; if (AddressValidator.validateAddress(address) == null) { //support additional address types in the future this.disableElement(LayoutController.element("spinButton")); this.displayPayoutAddressError(address); this.showPayoutAddress(null); return; } this.hidePayoutAddress(); if (address != payoutAddress) { payoutAddress = address; this.disableElement(LayoutController.element("spinButton")); this.disableElement(LayoutController.element("addFunds")); this.requestAccountBalance(this.payoutAddress); } else { this.enableElement(LayoutController.element("spinButton")); this.enableElement(LayoutController.element("addFunds")); this.enableElement(LayoutController.element("payoutAddressToggle")); } } private function enableElement(uiElement:*):void { try { uiElement.enabled = true; } catch (err:*) { } uiElement.filters = []; } private function disableElement(uiElement:*):void { try { uiElement.enabled = false; } catch (err:*) { } var rLum : Number = 0.2225; var gLum : Number = 0.7169; var bLum : Number = 0.0606; var matrix:Array = [ rLum, gLum, bLum, 0, 0, rLum, gLum, bLum, 0, 0, rLum, gLum, bLum, 0, 0, 0, 0, 0, 1, 0 ]; var filter:ColorMatrixFilter = new ColorMatrixFilter( matrix ); uiElement.filters = [filter]; } private function connectToHost():void { //var hostURL:String = this._config.network.host.toString(); var hostURL:String = this._config.network.anonhost.toString(); var proxy:String = this._config.network.anonproxy.toString(); var proxyIP:String = proxy.split(":")[0]; var proxyPort:uint = uint(proxy.split(":")[1]); if (!_demoMode){ trace ("GameController.connectToHost: " + hostURL); trace ("Using Tor proxy: " + proxy); //this._comm = new HTTPComm(hostURL); this._comm = new TorComm(hostURL, proxyIP, proxyPort); this._comm.gameInfo = _gameInfo; this._comm.connect(this.onConnectHost); } } private function onConnectHost():void { DialogManager.hide("info"); this.requestAccountBalance(this.payoutAddress); } private function requestAccountBalance(accountAddress:String):void { this.disableElement(LayoutController.element("spinButton")); this.disableElement(LayoutController.element("addFunds")); this.disableElement(LayoutController.element("payoutAddressToggle")); if ((this.payoutAddress == null) || (this.payoutAddress == "")) { this.displayPayoutAddressError("Enter Ethereum wallet address for winning payouts"); this.showPayoutAddress(null); } else { trace ("Requesting balance for account " + accountAddress); this._comm.request("balance", {account:accountAddress}, this.onReceiveAccountBalance); } } private function getShareholderInfo(eventObj:MouseEvent):void { /* var hostURL:String = this._config.network.anonhost.toString(); var proxy:String = this._config.network.anonproxy.toString(); var proxyIP:String = proxy.split(":")[0]; var proxyPort:uint = uint(proxy.split(":")[1]); var comm:TorComm = new TorComm(hostURL, proxyIP, proxyPort); comm.request("shareholderinfo", {account:this.payoutAddress}, this.onReceiveShareholderInfo); */ this._comm.request("shareholderinfo", {account:this.payoutAddress}, this.onReceiveShareholderInfo); } private function onReceiveShareholderInfo(eventObj:Event):void { trace ("onReceiveShareholderInfo=" + eventObj.target.data); var htmlContent:String = JSON.parse(eventObj.target.data).data; var options:NativeWindowInitOptions = new NativeWindowInitOptions(); options.transparent = false; options.systemChrome = NativeWindowSystemChrome.STANDARD; options.type = NativeWindowType.NORMAL; //if already open, existing window will get focus var helpWindow:HostInfoWindow = new HostInfoWindow(options, htmlContent, 600, 300); } private function onReceiveAccountBalance(eventObj:Event):void { eventObj.target.removeEventListener(Event.COMPLETE, this.onReceiveAccountBalance); var responseData:Object = JSON.parse(eventObj.target.data).data; trace ("onReceiveAccountBalance=" + eventObj.target.data); this._balance = responseData.balance; this._shares = responseData.shares; LayoutController.element("balance").text = String(this._balance); LayoutController.element("shares").text = String(this._shares); LayoutController.element("thresholdPercent").percent = responseData.thresholdPercent; this.enableElement(LayoutController.element("spinButton")); this.enableElement(LayoutController.element("addFunds")); this.enableElement(LayoutController.element("payoutAddressToggle")); } private function requestReelResults():void { this._paytable.hide(); if (_demoMode) { this.generateResults(); } else { //server will return error if the number of icons don't match server settings var reelSizes:Array = [this._reelController.reels[0].icons.length, this._reelController.reels[1].icons.length, this._reelController.reels[2].icons.length]; this._comm.request("genreelres", {reels:reelSizes, account:this.payoutAddress}, this.onReceiveReelResults); } } private function onPayoutAddressLoseFocus(eventObj:FocusEvent):void { this.updatePayoutAddress(); //this.hidePayoutAddress(); } private function onReceiveReelResults(eventObj:Event):void { eventObj.target.removeEventListener(Event.COMPLETE, this.onReceiveReelResults); var resultObject:Object = JSON.parse(eventObj.target.data).data; if ((resultObject.error==undefined) || (resultObject.errNum==0)) { processReelResults(resultObject); } else { trace ("Server response error: " + resultObject.error); } } private function submitSelectedResults(results:Array):void { if (_demoMode) { this.sendKey(); } else { this._paytable.show(); this._comm.request("select", {selections:results, account:this.payoutAddress}, this.onReceiveGameResults); } } private function toHex(input:uint):String { var digits:String = "0123456789ABCDEF"; var hex:String = new String(""); while (input > 0) { var charIndex:uint = input & 0xF; input = input >>> 4; hex = digits.charAt(charIndex) + hex; } if (hex.length == 0) { hex = '0'; } return (hex); } private function generateResults():void { var key:ByteArray = new ByteArray(); var keyArr:Array = new Array(); for (var count:uint = 0; count < 4; count++) { var rand:uint = _rng.getRandomUint(); key.writeUnsignedInt(rand); } var resultsObj:Object = new Object(); resultsObj.reels = new Array(); var resultStrings:Vector.<String> = new Vector.<String>(); this._demoKey = Base64.encode(key); for (var reelCount:uint = 0; reelCount < 3; reelCount++) { resultsObj.reels[reelCount] = new Array(); var currentReelData:XML = this.getReelConfig(reelCount); trace ("Encrypting " + currentReelData.children().length() + " stop positions for reel " + reelCount); for (count = 0; count < currentReelData.children().length(); count++) { //blocks are 64 bits var block:String = new String() block = toHex(_rng.getRandomUint()); //32 random bits var stopVal:uint = (_rng.getRandomUint() << 16) | count; //16 random bits + stop position block += toHex (stopVal); var encStop:String=Base64.encode(XXTEA.encrypt(block, key)); resultStrings.push(encStop); } resultStrings = shuffle(resultStrings); resultsObj.reels[reelCount] = this.vectorToArray(resultStrings); resultStrings = new Vector.<String>(); } trace (JSON.stringify(resultsObj)); processReelResults(resultsObj); } private function vectorToArray(input:Vector.<String>):Array { var output:Array = new Array(); for (var count:uint = 0; count < input.length; count++) { output.push(input[count]); } return (output); } private function sendKey():void { var gameObj:Object = new Object(); gameObj.win = 0; gameObj.key = this._demoKey; this.processGameResults(gameObj); } private function appendResults(targetNode:XML, results:Vector.<String>):void { for (var count:uint = 0; count < results.length; count++) { targetNode.appendChild(new XML("<result>" + results[count] + "</result>")); } } private function shuffle(input:Vector.<String>):Vector.<String> { var returnVec:Vector.<String> = new Vector.<String>(); while (input.length > 0) { var splicePos:int = Math.floor((_rng.getRandomInt() / int.MAX_VALUE) * input.length); returnVec.push(input.splice(splicePos, 1)); } return (returnVec); } private function getReelConfig(reelID:uint):XML { var reelNodes:XMLList = _config.reels.children(); for (var count:uint = 0; count < reelNodes.length(); count++) { if (uint(reelNodes[count].@id) == reelID) { return (reelNodes[count] as XML); } } return (null); } private function processReelResults(resultsData:Object):void { var reelsArray:Array = resultsData.reels; for (var count:uint = 0; count < reelsArray.length; count++) { var currentReel:Array = reelsArray[count]; for (var count2:uint = 0; count2 < currentReel.length; count2++) { var encodedValue:String = currentReel[count2]; var renderValue:String = Base64.decodeToHex(encodedValue); ResultsSelector.getSelectorByID(count).addResultItem(new ColourSquare(renderValue, encodedValue)); } } if (LayoutController.element("autoselect").selected) { this.autoSelectResults(); } else { ResultsSelector.showSelectors(0.5, 0.3); LayoutController.element("spinButton").visible = false; this.disableElement(LayoutController.element("submitButton")); LayoutController.element("submitButton").visible = true; this.enableElement(LayoutController.element("submitButton")); } } private function autoSelectResults():void { for (var count:uint = 0; count < 3; count++) { ResultsSelector.getSelectorByID(count).autoSelect(); } var selections:Array = new Array(); for (count = 0; count < 3; count++) { selections.push(ResultsSelector.getSelectorByID(count).currentSelection); } this._balance-= this._wager; LayoutController.element("balance").text = String(this._balance); setTimeout(submitSelectedResults, 1500, selections); } private function onReceiveGameResults(eventObj:Event):void { eventObj.target.removeEventListener(Event.COMPLETE, this.onReceiveGameResults); trace ("onReceiveGameResults: " + eventObj.target.data); var resultObject:Object = JSON.parse(eventObj.target.data).data; this.processGameResults(resultObject); } private function processGameResults(resultsObj:Object):void { var winAmountStr:String = resultsObj.win; var keyStr:String = resultsObj.key; this._balance = resultsObj.balance; this._shares = resultsObj.shares; this._lastGameResults = resultsObj; //process after animation has completed //LayoutController.element("balance").text = String(this._balance); //LayoutController.element("shares").text = String(this._shares); LayoutController.element("thresholdPercent").percent = resultsObj.thresholdPercent; var key:ByteArray = Base64.decode(keyStr); trace ("Received encryption key: " + keyStr); var stopPositions:Array = new Array(); for (var count:uint = 0; count < 3; count++) { var reelSelection:String = ResultsSelector.getSelectorByID(count).currentSelection; var plaintextSelection:String = XXTEA.decryptToString(reelSelection, key); var stopPosition:int = uint("0x" + plaintextSelection.substring(plaintextSelection.length - 4)); //last 4 digits of string (16 bits) stopPosition--; //stop position is for icon on payline if (stopPosition < 0) { stopPosition = _reelController.reels[count].icons.length - 1; } stopPositions.push(uint(stopPosition)); } _reelController.stopAllReels(stopPositions, false, 1500); } private function onReelAnimationFinished(eventObj:ReelControllerEvent):void { if (this._lastGameResults.winningStops.length > 0) { if (this._lastGameResults.win > 0) { SoundController.playSound("bigWin", 0.3); } else { SoundController.playSound("win", 0.3); } } ResultsSelector.clearAllSelectors(); this.animateWinningIcons(this._lastGameResults.winningStops); this.enableElement(LayoutController.element("addFunds")); this.enableElement(LayoutController.element("payoutAddressToggle")); LayoutController.element("balance").text = String(this._balance); LayoutController.element("shares").text = String(this._shares); LayoutController.element("spinButton").visible = true; this.enableElement(LayoutController.element("spinButton")); LayoutController.element("submitButton").visible = false; this.disableElement(LayoutController.element("submitButton")); } private function animateWinningIcons(stopPositions:Array):void { for (var count:int = 0; count < stopPositions.length; count++) { var currentReel:Reel = this._reelController.reels[count]; for (var iconCount:int = 0; iconCount < stopPositions[count].length; iconCount++) { currentReel.icons[stopPositions[count][iconCount]].animateWin(); } } } private function onSpinClick(eventObj:MouseEvent):void { if (LayoutController.element("spinButton").enabled == false) { return; } this._reelController.clearAllWinAnimations(); if (this._balance < 1000) { this.getFaucetData(); return; } if (!_reelController.reelsSpinning) { this.disableElement(LayoutController.element("payoutAddressToggle")); this.disableElement(LayoutController.element("spinButton")); this.disableElement(LayoutController.element("addFunds")); if (!LayoutController.element("autoselect").selected) { LayoutController.element("submitButton").visible = true; LayoutController.element("spinButton").visible = false; } _reelController.spinAllReels(true, 0.3, 100); this.requestReelResults(); } } private function onSubmitClick(eventObj:MouseEvent):void { if (LayoutController.element("submitButton").enabled == false) { return; } var selections:Array = new Array(); for (var count:uint = 0; count < 3; count++) { var currentSelector:ResultsSelector = ResultsSelector.getSelectorByID(count); if (currentSelector.currentSelection!=null) { selections.push(currentSelector.currentSelection); } } if (selections.length == 3) { //LayoutController.element("submitButton").enabled = false; this.disableElement(LayoutController.element("submitButton")); this._balance-= this._wager; LayoutController.element("balance").text = String(this._balance); ResultsSelector.hideSelectors(0.5, 0); submitSelectedResults(selections); } else { //play some animation here trace ("Not all results selected!"); } } private function onAddFundsClick(eventObj:MouseEvent):void { if (LayoutController.element("addFunds").enabled!=false) { this.getFaucetData(); } } private function getFaucetData():void { this.disableElement(LayoutController.element("spinButton")); this.disableElement(LayoutController.element("addFunds")); this.disableElement(LayoutController.element("payoutAddressToggle")); if (this._faucetWindow==null) { this._comm.request("getfaucet", {account:this.payoutAddress}, this.onGetFaucetData); } else { this._faucetWindow.activate(); } } private function onGetFaucetData(eventObj:Event):void { eventObj.target.removeEventListener(Event.COMPLETE, this.onGetFaucetData); var wfData:Object = JSON.parse(eventObj.target.data).data; //wallet/faucet data if (wfData!=null) { this.openFaucetWindow(wfData); } else { this.enableElement(LayoutController.element("spinButton")); this.enableElement(LayoutController.element("addFunds")); this.enableElement(LayoutController.element("payoutAddressToggle")); //no faucets currently available! } } public function openFaucetWindow(wfData:Object) :void { var options:NativeWindowInitOptions = new NativeWindowInitOptions(); options.transparent = false; options.systemChrome = NativeWindowSystemChrome.STANDARD; options.type = NativeWindowType.NORMAL; _faucetWindow = new FaucetWindow(options, "Add credits to account "+this.payoutAddress, 800, 600); _faucetWindow.addEventListener(FaucetWindowEvent.COMPLETE, this.onFaucetClaimComplete); _faucetWindow.addEventListener(FaucetWindowEvent.CLOSING, this.onFaucetWindowClosing); _faucetWindow.load(wfData); } private function onFaucetClaimComplete(eventObj:FaucetWindowEvent):void { eventObj.target.addEventListener(FaucetWindowEvent.COMPLETE, this.onFaucetClaimComplete); var requestObj:Object = new Object(); requestObj.faucet = eventObj.wfData.faucet; requestObj.wallet = eventObj.wfData.wallet; requestObj.account = this.payoutAddress; requestObj.claimAmount = eventObj.claimAmount; this._comm.request("claim", requestObj, this.onFaucetClaimVerified); trace ("New faucet amount claimed: " + eventObj.claimAmount); } private function onFaucetClaimVerified(eventObj:Event):void { trace ("onFauceClaimVerified: " + eventObj.target.data); eventObj.target.removeEventListener(Event.COMPLETE, this.onFaucetClaimVerified); var replyObj:Object = JSON.parse(eventObj.target.data).data; if (isNaN(replyObj.balance) || isNaN(replyObj.shares)) { //claim couln't be verified var claimMsg:String = "<font color='#00FF10' size='24'><br><br><br><br><b>The faucet claim couldn't be verified. Please try again.</b></font>"; DialogManager.show("info", claimMsg); LayoutController.layoutTarget.stage.addEventListener(MouseEvent.CLICK, this.hideInfoDialog); } else { this._balance = replyObj.balance; this._shares = replyObj.shares; this._faucetWindow = null; LayoutController.element("balance").text = String(this._balance); LayoutController.element("shares").text = String(this._shares); LayoutController.element("thresholdPercent").percent = replyObj.thresholdPercent; } } private function hideInfoDialog(eventObj:MouseEvent):void { DialogManager.hide("info"); LayoutController.layoutTarget.stage.addEventListener(MouseEvent.CLICK, this.hideInfoDialog); } private function onFaucetWindowClosing(eventObj:FaucetWindowEvent):void { this.enableElement(LayoutController.element("spinButton")); this.enableElement(LayoutController.element("addFunds")); this.enableElement(LayoutController.element("payoutAddressToggle")); eventObj.target.removeEventListener(FaucetWindowEvent.CLOSING, this.onFaucetWindowClosing); this._faucetWindow = null; } private function showPayoutAddress(eventObj:MouseEvent):void { var addressObj:*=LayoutController.element("payoutAddress"); //may be any type of display object TweenLite.killTweensOf(addressObj); this.disableElement(LayoutController.element("spinButton")); this.disableElement(LayoutController.element("addFunds")); this.disableElement(LayoutController.element("payoutAddressToggle")); if (addressObj.y != this._accountAddressOriginalY) { TweenLite.to(addressObj, 1, {y:this._accountAddressOriginalY, alpha:1, ease:Strong.easeOut}); } } private function hidePayoutAddress():void { var addressObj:*=LayoutController.element("payoutAddress"); //may be any type of display object TweenLite.killTweensOf(addressObj); if (addressObj.y != addressObj.stage.stageHeight) { TweenLite.to(addressObj, 1, {y:addressObj.stage.stageHeight, alpha:0, ease:Strong.easeOut}); } } private function openHelp(eventObj:MouseEvent):void { trace ("openHelp: " + this._config.help.toString()); var options:NativeWindowInitOptions = new NativeWindowInitOptions(); options.transparent = false; options.systemChrome = NativeWindowSystemChrome.STANDARD; options.type = NativeWindowType.NORMAL; //if already open, existing window will get focus var helpWindow:HelpWindow = new HelpWindow(options, this._config.help.toString(), 600, 700); } public function destroy():void { this._comm.disconnect(); this._comm = null; } } }
package ssen.flexkit.components.chart { import mx.charts.LinearAxis; import mx.charts.chartClasses.CartesianChart; import mx.charts.chartClasses.ChartElement; /** CartesianChart의 ChartElement 구현을 위한 Base Class */ // TODO LogAxis, CategoryAxis 를 위한 구현들을 한다. // Axis 내에 뭔가 위치값 계산을 위한 기능들이 있지 않을까? public class CartesianChartElement extends ChartElement { protected function getCartesianChart():CartesianChart { return chart as CartesianChart; } /** 시각적 Y좌표에 해당하는 값을 가져온다 */ protected function getVerticalValue(y:Number):Number { var vaxis:LinearAxis=getVerticalAxis(); return vaxis.maximum - ((vaxis.maximum - vaxis.minimum) * (y / unscaledHeight)); } /** 시각적 X좌표에 해당하는 값을 가져온다 */ protected function getHorizontalValue(x:Number):Number { var haxis:LinearAxis=getHorizontalAxis(); return ((haxis.maximum - haxis.minimum) * (x / unscaledWidth)) + haxis.minimum; } /** Bubble Chart의 가로Axis를 가져온다 */ protected function getHorizontalAxis():LinearAxis { return getCartesianChart().horizontalAxis as LinearAxis; } /** Bubble Chart의 세로Axis를 가져온다 */ protected function getVerticalAxis():LinearAxis { return getCartesianChart().verticalAxis as LinearAxis; } /** 논리적 가로축 값에 해당하는 X 위치를 가져온다 */ protected function getHorizontalPosition(h:Number):Number { var haxis:LinearAxis=getHorizontalAxis(); return ((h - haxis.minimum) / (haxis.maximum - haxis.minimum)) * unscaledWidth; } /** 논리적 세로축 값에 해당하는 Y 위치를 가져온다 */ protected function getVerticalPosition(v:Number):Number { var vaxis:LinearAxis=getVerticalAxis(); return unscaledHeight - (((v - vaxis.minimum) / (vaxis.maximum - vaxis.minimum)) * unscaledHeight); } } }
package { import com.greensock.TweenLite; import com.tuarua.BackBtn; import com.tuarua.CancelBtn; import com.tuarua.CaptureBtn; import com.tuarua.DevToolsBtn; import com.tuarua.ForwardBtn; import com.tuarua.FreSharp; import com.tuarua.FreSwift; import com.tuarua.FullscreenBtn; import com.tuarua.JsBtn; import com.tuarua.RefreshBtn; import com.tuarua.WebBtn; import com.tuarua.WebView; import com.tuarua.ZoominBtn; import com.tuarua.ZoomoutBtn; import com.tuarua.fre.ANEError; import com.tuarua.utils.os; import com.tuarua.webview.ActionscriptCallback; import com.tuarua.webview.DownloadProgress; import com.tuarua.webview.JavascriptResult; import com.tuarua.webview.LogSeverity; import com.tuarua.webview.Settings; import com.tuarua.webview.WebEngine; import com.tuarua.webview.WebViewEvent; import com.tuarua.webview.popup.Behaviour; import events.TabEvent; import flash.desktop.NativeApplication; import flash.display.BitmapData; import flash.display.NativeWindowDisplayState; import flash.display.PNGEncoderOptions; import flash.display.SimpleButton; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageDisplayState; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.FullScreenEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.NativeWindowDisplayStateEvent; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.geom.Rectangle; import flash.net.URLRequest; import flash.net.URLRequestHeader; import flash.net.URLRequestMethod; import flash.system.Capabilities; import flash.text.Font; import flash.utils.ByteArray; import flash.utils.setTimeout; import views.BasicButton; import views.Input; import views.Progress; import views.StatusText; import views.TabBar; [SWF(width="1280", height="800", frameRate="60", backgroundColor="#F1F1F1")] public class WebViewANESample extends Sprite { public static const FONT:Font = new FiraSansSemiBold(); private var freSharpANE:FreSharp = new FreSharp(); // must create before all others private var freSwiftANE:FreSwift = new FreSwift(); // must create before all others private var webView:WebView; private var backBtn:SimpleButton = new BackBtn(); private var fwdBtn:SimpleButton = new BackBtn(); private var refreshBtn:SimpleButton = new RefreshBtn(); private var cancelBtn:SimpleButton = new CancelBtn(); private var zoomInBtn:SimpleButton = new ZoominBtn(); private var zoomOutBtn:SimpleButton = new ZoomoutBtn(); private var fullscreenBtn:SimpleButton = new FullscreenBtn(); private var devToolsBtn:SimpleButton = new DevToolsBtn(); private var jsBtn:SimpleButton = new JsBtn(); private var webBtn:SimpleButton = new WebBtn(); private var capureBtn:SimpleButton = new CaptureBtn(); private var as_js_as_Btn:BasicButton = new BasicButton("AS->JS->AS with Callback"); private var eval_js_Btn:BasicButton = new BasicButton("AS->JS- with no Callback"); private var statusTxt:StatusText = new StatusText(); private var progress:Progress = new Progress(); private var urlInput:Input = new Input(); private var tabBar:TabBar = new TabBar(); private var hasActivated:Boolean; private var _appWidth:uint = 1280; private var _appHeight:uint = 800; private static const newTabUrls:Vector.<String> = new <String>["https://www.bing.com", "https://www.bbc.co.uk", null, "https://www.github.com", "https://forum.starling-framework.org/"]; public function WebViewANESample() { super(); stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; this.addEventListener(Event.ACTIVATE, onActivated); NativeApplication.nativeApplication.executeInBackground = true; } protected function onActivated(event:Event):void { if (hasActivated) return; setTimeout(init, 0); // this is handle the HARMAN splash screen hasActivated = true; } protected function init():void { stage.addEventListener(Event.RESIZE, onResize); stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullScreenEvent); NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExiting); NativeApplication.nativeApplication.activeWindow.addEventListener( NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE, onWindowMiniMaxi); webView = WebView.shared(); webView.addCallback("js_to_as", jsToAsCallback); webView.addCallback("forceWebViewFocus", forceWebViewFocus); //for Windows touch - see jsTest.html webView.addEventListener(WebViewEvent.ON_PROPERTY_CHANGE, onPropertyChange); webView.addEventListener(WebViewEvent.ON_FAIL, onFail); webView.addEventListener(WebViewEvent.ON_DOWNLOAD_PROGRESS, onDownloadProgress); webView.addEventListener(WebViewEvent.ON_DOWNLOAD_COMPLETE, onDownloadComplete); webView.addEventListener(WebViewEvent.ON_URL_BLOCKED, onUrlBlocked); webView.addEventListener(WebViewEvent.ON_POPUP_BLOCKED, onPopupBlocked); webView.addEventListener(WebViewEvent.ON_PDF_PRINTED, onPdfPrinted); //webView.printToPdf("C:\\path\\to\file.pdf"); /*webView.addEventListener(KeyboardEvent.KEY_UP, onKeyUp); //KeyboardEvent of webview captured webView.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown); //KeyboardEvent of webview captured*/ var settings:Settings = new Settings(); settings.popup.behaviour = Behaviour.NEW_WINDOW; //Behaviour.BLOCK //Behaviour.SAME_WINDOW //Behaviour.REPLACE settings.popup.dimensions.width = 600; settings.popup.dimensions.height = 800; settings.persistRequestHeaders = true; //only use settings.userAgent if you are running your own site. //google.com for eg displays different sites based on user agent //settings.userAgent = "WebViewANE"; settings.cacheEnabled = true; // enable Edge View on Windows if available /*settings.engine = (os.isWindows && os.majorVersion >= 10 && os.buildVersion >= 17134) ? WebEngine.EDGE : WebEngine.DEFAULT;*/ settings.enableDownloads = true; settings.contextMenu.enabled = true; //enable/disable right click settings.useTransparentBackground = true; // See https://github.com/cefsharp/CefSharp/blob/master/CefSharp.Example/CefExample.cs#L37 for more examples settings.cef.commandLineArgs.push({ key: "disable-direct-write", value: "1" }); settings.cef.enablePrintPreview = true; settings.cef.userDataPath = File.applicationStorageDirectory.nativePath; settings.cef.logSeverity = LogSeverity.DISABLE; // settings.urlWhiteList.push("html5test.com", "macromedia.","google.", "YouTUBE.", "adobe.com", "chrome-devtools://"); //to restrict urls - simple string matching // settings.urlBlackList.push(".pdf"); var viewPort:Rectangle = new Rectangle(0, 90, _appWidth, _appHeight - 140); // trace(os.isWindows, os.majorVersion, os.minorVersion, os.buildVersion); webView.init(stage, viewPort, new URLRequest("https://html5test.com"), settings, 1.0, 0xFFF1F1F1); //webView.init(stage, viewPort, null, settings, 1.0, 0xFFF1F1F1); // when using loadHTMLString webView.visible = true; webView.injectScript("function testInject(){console.log('yo yo')}"); /*trace("loading html"); webView.loadHTMLString('<!DOCTYPE html>' + '<html>' + '<head><meta charset="UTF-8">' + '<title>Mocked HTML file 1</title>' + '</head>' + '<body bgColor="#33FF00">' + //must give the body a bg color otherwise it loads black '<p>with UTF-8: Björk Guðmundsdóttir Sinéad O’Connor 久保田 利伸 Михаил Горбачёв Садриддин Айнӣ Tor Åge Bringsværd 章子怡 €</p>' + '</body>' + '</html>', new URLRequest("http://rendering/"));*/ backBtn.x = 20; backBtn.addEventListener(MouseEvent.CLICK, onBack); fwdBtn.x = 80; fwdBtn.scaleX = -1; fwdBtn.addEventListener(MouseEvent.CLICK, onForward); fwdBtn.alpha = backBtn.alpha = 0.4; refreshBtn.x = 100; refreshBtn.addEventListener(MouseEvent.CLICK, onRefresh); cancelBtn.x = 100; cancelBtn.addEventListener(MouseEvent.CLICK, onCancel); zoomInBtn.x = 980; zoomInBtn.addEventListener(MouseEvent.CLICK, onZoomIn); zoomOutBtn.x = zoomInBtn.x + 40; zoomOutBtn.addEventListener(MouseEvent.CLICK, onZoomOut); fullscreenBtn.x = zoomOutBtn.x + 40; fullscreenBtn.addEventListener(MouseEvent.CLICK, onFullScreen); devToolsBtn.y = fullscreenBtn.y = zoomInBtn.y = zoomOutBtn.y = backBtn.y = fwdBtn.y = refreshBtn.y = cancelBtn.y = capureBtn.y = 50; devToolsBtn.x = fullscreenBtn.x + 40; devToolsBtn.addEventListener(MouseEvent.CLICK, onDevTools); jsBtn.x = webBtn.x = devToolsBtn.x + 60; jsBtn.y = webBtn.y = 48; capureBtn.x = jsBtn.x + 60; capureBtn.useHandCursor = backBtn.useHandCursor = fwdBtn.useHandCursor = refreshBtn.useHandCursor = cancelBtn.useHandCursor = zoomInBtn.useHandCursor = zoomOutBtn.useHandCursor = devToolsBtn.useHandCursor = fullscreenBtn.useHandCursor = webBtn.useHandCursor = jsBtn.useHandCursor = true; jsBtn.addEventListener(MouseEvent.CLICK, onJS); webBtn.addEventListener(MouseEvent.CLICK, onWeb); capureBtn.addEventListener(MouseEvent.CLICK, onCapture); webBtn.visible = false; cancelBtn.visible = false; as_js_as_Btn.addEventListener(MouseEvent.CLICK, onAsJsAsBtn); eval_js_Btn.addEventListener(MouseEvent.CLICK, onEvalJsBtn); as_js_as_Btn.x = 200; eval_js_Btn.x = as_js_as_Btn.x + 200; as_js_as_Btn.y = eval_js_Btn.y = 42; eval_js_Btn.useHandCursor = as_js_as_Btn.useHandCursor = true; as_js_as_Btn.visible = eval_js_Btn.visible = false; jsBtn.cacheAsBitmap = capureBtn.cacheAsBitmap = cancelBtn.cacheAsBitmap = webBtn.cacheAsBitmap = true; urlInput.addEventListener(Input.ENTER, onUrlEnter); urlInput.x = 148; urlInput.y = 48; progress.scaleX = 0; progress.x = 150; progress.y = 70; statusTxt.x = 12; statusTxt.y = _appHeight - 36; tabBar.addEventListener(TabEvent.ON_NEW_TAB, onNewTab); tabBar.addEventListener(TabEvent.ON_SWITCH_TAB, onSwitchTab); tabBar.addEventListener(TabEvent.ON_CLOSE_TAB, onCloseTab); addChild(tabBar); addChild(statusTxt); addChild(backBtn); addChild(fwdBtn); addChild(refreshBtn); addChild(cancelBtn); addChild(zoomInBtn); addChild(zoomOutBtn); addChild(fullscreenBtn); addChild(devToolsBtn); addChild(capureBtn); addChild(jsBtn); addChild(webBtn); addChild(as_js_as_Btn); addChild(eval_js_Btn); addChild(urlInput); addChild(progress); } private function onEvalJsBtn(event:MouseEvent):void { //this is without a callback webView.evaluateJavascript('document.getElementsByTagName("body")[0].style.backgroundColor = "yellow";'); //this is with a callback //webView.evaluateJavascript("document.getElementById('output').innerHTML;", onJsEvaluated) } private function onAsJsAsBtn(event:MouseEvent):void { webView.callJavascriptFunction("as_to_js", asToJsCallback, 1, "é", 77); // this is how to use without a callback // webView.callJavascriptFunction("console.log",null,"hello console. The is AIR"); } private function onUrlEnter(event:Event):void { webView.load(new URLRequest(urlInput.text)); } private function onCapture(event:MouseEvent):void { webView.capture(function (bitmapData:BitmapData):void { if (bitmapData) { var ba:ByteArray = new ByteArray(); var encodingOptions:PNGEncoderOptions = new PNGEncoderOptions(true); bitmapData.encode(new Rectangle(0, 0, bitmapData.width, bitmapData.height), encodingOptions, ba); var file:File = File.desktopDirectory.resolvePath("webViewANE_capture.png"); var fs:FileStream = new FileStream(); fs.open(file, FileMode.WRITE); fs.writeBytes(ba); fs.close(); trace("webViewANE_capture.png written to desktop") } }, new Rectangle(100, 100, 400, 200)); } private function onWeb(event:MouseEvent):void { jsBtn.visible = true; webBtn.visible = false; progress.visible = true; urlInput.visible = true; as_js_as_Btn.visible = eval_js_Btn.visible = false; webView.load(new URLRequest("http://www.adobe.com")); } private function onJS(event:MouseEvent):void { jsBtn.visible = false; webBtn.visible = true; progress.visible = false; urlInput.visible = false; as_js_as_Btn.visible = eval_js_Btn.visible = true; var localHTML:File = File.applicationDirectory.resolvePath("jsTest.html"); if (localHTML.exists) { webView.loadFileURL(localHTML.nativePath, File.applicationDirectory.nativePath); } } private function onDevTools(event:MouseEvent):void { webView.showDevTools(); //webView.closeDevTools(); } private function onFullScreen(event:MouseEvent):void { onFullScreenApp(); } private function onZoomOut(event:MouseEvent):void { webView.zoomOut(); } private function onZoomIn(event:MouseEvent):void { webView.zoomIn(); } private function onCancel(event:MouseEvent):void { webView.stopLoading(); } private function onRefresh(event:MouseEvent):void { cancelBtn.visible = true; refreshBtn.visible = false; webView.reload(); } private function loadWithRequestHeaders(event:MouseEvent):void { var req:URLRequest = new URLRequest("http://www.google.com"); req.requestHeaders.push(new URLRequestHeader("Cookie", "BROWSER=WebViewANE;")); webView.load(req); } private function onForward(event:MouseEvent):void { webView.goForward(); /*var obj:BackForwardList = webView.backForwardList(); trace("back list length",obj.backList.length) trace("forward list length",obj.forwardList.length)*/ } private function onBack(event:MouseEvent):void { webView.goBack(); } private function onPdfPrinted(event:WebViewEvent):void { trace(event); } private function onKeyDown(event:KeyboardEvent):void { trace(event); } private function onKeyUp(event:KeyboardEvent):void { trace(event); } private function onPopupBlocked(event:WebViewEvent):void { stage.dispatchEvent(new MouseEvent(MouseEvent.CLICK)); //this prevents touch getting trapped on Windows } private function onPropertyChange(event:WebViewEvent):void { // read list of tabs and their details like this: /*var tabList:Vector.<TabDetails> = webView.tabDetails; if (tabList && tabList.length > 0) { trace(tabList[webView.currentTab].index, tabList[webView.currentTab].title, tabList[webView.currentTab].url); }*/ switch (event.params.propertyName) { case "url": if (event.params.tab == webView.currentTab) { urlInput.text = event.params.value; } break; case "title": tabBar.setTabTitle(event.params.tab, event.params.value); break; case "isLoading": if (event.params.tab == webView.currentTab) { refreshBtn.visible = !event.params.value; cancelBtn.visible = event.params.value; } break; case "canGoBack": if (event.params.tab == webView.currentTab) { backBtn.alpha = event.params.value ? 1.0 : 0.4; backBtn.enabled = event.params.value; } break; case "canGoForward": if (event.params.tab == webView.currentTab) { fwdBtn.alpha = event.params.value ? 1.0 : 0.4; fwdBtn.enabled = event.params.value; } break; case "estimatedProgress": var p:Number = event.params.value; if (event.params.tab == webView.currentTab) { progress.scaleX = p; if (p > 0.99) { TweenLite.to(progress, 0.5, {alpha: 0}); } else { progress.alpha = 1; } } break; case "statusMessage": if (event.params.tab == webView.currentTab) { statusTxt.text = event.params.value; } break; } } private function onNewTab(event:TabEvent):void { fwdBtn.alpha = backBtn.alpha = 0.4; fwdBtn.enabled = backBtn.enabled = false; progress.scaleX = 0.0; urlInput.text = ""; webView.addTab(new URLRequest(newTabUrls[tabBar.tabs.length - 2])); tabBar.setActiveTab(webView.currentTab); } private function onSwitchTab(event:TabEvent):void { webView.currentTab = event.params.index; tabBar.setActiveTab(webView.currentTab); } private function onCloseTab(event:TabEvent):void { webView.closeTab(event.params.index); tabBar.closeTab(event.params.index); tabBar.setActiveTab(webView.currentTab); } private static function onUrlBlocked(event:WebViewEvent):void { trace(event.params.url, "does not match our urlWhiteList or is on urlBlackList", "tab is:", event.params.tab); } private function onWindowMiniMaxi(event:NativeWindowDisplayStateEvent):void { if (event.afterDisplayState != NativeWindowDisplayState.MINIMIZED) { webView.viewPort = new Rectangle(0, 90, _appWidth, _appHeight - 140); } } private static function onDownloadComplete(event:WebViewEvent):void { trace(event.params, "complete"); } private static function onDownloadProgress(event:WebViewEvent):void { var progress:DownloadProgress = event.params as DownloadProgress; trace("progress.id", progress.id); trace("progress.url", progress.url); trace("progress.percent", progress.percent); trace("progress.speed", progress.speed); trace("progress.bytesLoaded", progress.bytesLoaded); trace("progress.bytesTotal", progress.bytesTotal); } private function onJsEvaluated(jsResult:JavascriptResult):void { trace("Evaluate JS -> AS reached WebViewANESample.as"); trace("jsResult.error:", jsResult.error); trace("jsResult.result:", jsResult.result); trace("jsResult.message:", jsResult.message); trace("jsResult.success:", jsResult.success); } public function forceWebViewFocus(asCallback:ActionscriptCallback):void { webView.focus(); } public function jsToAsCallback(asCallback:ActionscriptCallback):void { trace("JS -> AS reached WebViewANESample.as"); trace("asCallback.args", asCallback.args); trace("asCallback.functionName", asCallback.functionName); trace("asCallback.callbackName", asCallback.callbackName); if (asCallback.args && asCallback.args.length > 0) { var paramA:int = asCallback.args[0] + 33; var paramB:String = asCallback.args[1].replace("I am", "You are"); var paramC:Boolean = !asCallback.args[2]; trace("paramA", paramA); trace("paramB", paramB); trace("paramC", paramC); trace("we have a callbackName") } if (asCallback.callbackName) { //if we have a callbackName it means we have a further js call to make webView.callJavascriptFunction(asCallback.callbackName, null, paramA, paramB, paramC); } } public static function asToJsCallback(jsResult:JavascriptResult):void { trace("asToJsCallback"); trace("jsResult.error", jsResult.error); trace("jsResult.result", jsResult.result); trace("jsResult.message", jsResult.message); trace("jsResult.success", jsResult.success); var testObject:Object = JSON.parse(jsResult.result); trace(testObject); } private static function onFail(event:WebViewEvent):void { trace(event.params.url); trace(event.params.errorCode); trace(event.params.errorText); if (event.params.hasOwnProperty("tab")) { trace(event.params.tab); } } public function onFullScreenApp():void { if (stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE) { stage.displayState = StageDisplayState.NORMAL; _appWidth = 1280; _appHeight = 800; } else { _appWidth = Capabilities.screenResolutionX; _appHeight = Capabilities.screenResolutionY; stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; } } private function onFullScreenEvent(event:FullScreenEvent):void { if (webView) { webView.viewPort = new Rectangle(0, 90, _appWidth, _appHeight - 140); } } public function updateWebViewOnResize():void { if (webView) { webView.viewPort = new Rectangle(0, 90, _appWidth, _appHeight - 140); } } private function onResize(e:Event):void { _appWidth = this.stage.stageWidth; _appHeight = this.stage.stageHeight; updateWebViewOnResize(); } /** * It's very important to call WebView.dispose(); when the app is exiting. */ private function onExiting(event:Event):void { WebView.dispose(); FreSwift.dispose(); FreSharp.dispose(); } } }
package com.pranav.db.sqlite.statements { public class Insert { public function Insert() { } } }
package childsifoundation.ui { import flash.geom.ColorTransform; import childsifoundation.assets.BrickAsset; import childsifoundation.vo.BrickVO; import childsifoundation.model.ChildsFoundationModel; import flash.display.Sprite; import flash.display.MovieClip; import flash.text.TextField; // public class BrickUI extends Sprite { private var model : ChildsFoundationModel; private var brick : BrickAsset; public var vo : BrickVO; // public function BrickUI( vo:BrickVO ) { super(); // this.vo = vo; model = ChildsFoundationModel.getInstance(); // createChildren(); } protected function createChildren ( ) : void { if ( this.brick == null ) { this.brick = new BrickAsset ( ) ; //TextField(this.brick.getChildByName("id")).text = "" + vo.loopIndex + ""; deselect(); this.addChild ( this.brick ); } } public function select() : void { //this.brick.gotoAndStop( "over" ); // Set brick colour if(model.applicationParams[vo.colour]){ var colorTransform : ColorTransform = MovieClip(this.brick.getChildByName("brickColour")).transform.colorTransform; colorTransform.color = uint(model.applicationParams[vo.colour+"_rollover"]); MovieClip(this.brick.getChildByName("brickColour")).transform.colorTransform = colorTransform; } } public function deselect() : void { //this.brick.gotoAndStop( vo.brickFrame+ "_brick" ); // Set brick colour if(model.applicationParams[vo.colour]){ var colorTransform : ColorTransform = MovieClip(this.brick.getChildByName("brickColour")).transform.colorTransform; colorTransform.color = uint(model.applicationParams[vo.colour]); MovieClip(this.brick.getChildByName("brickColour")).transform.colorTransform = colorTransform; } } } }
package serverProto.saveJinchuuriki { import com.netease.protobuf.Message; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_MESSAGE; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_STRING; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_UINT32; 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; import flash.errors.IOError; public final class ProtoSaveJinchuurikiRankInfo extends Message { public static const PLAYER_ID:FieldDescriptor$TYPE_MESSAGE = new FieldDescriptor$TYPE_MESSAGE("serverProto.saveJinchuuriki.ProtoSaveJinchuurikiRankInfo.player_id","playerId",1 << 3 | WireType.LENGTH_DELIMITED,ProtoPlayerKey); public static const PLAYER_NAME:FieldDescriptor$TYPE_STRING = new FieldDescriptor$TYPE_STRING("serverProto.saveJinchuuriki.ProtoSaveJinchuurikiRankInfo.player_name","playerName",2 << 3 | WireType.LENGTH_DELIMITED); public static const TIMES:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.saveJinchuuriki.ProtoSaveJinchuurikiRankInfo.times","times",3 << 3 | WireType.VARINT); public static const TEAM_ID:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.saveJinchuuriki.ProtoSaveJinchuurikiRankInfo.team_id","teamId",4 << 3 | WireType.VARINT); private var player_id$field:ProtoPlayerKey; private var player_name$field:String; private var times$field:uint; private var hasField$0:uint = 0; private var team_id$field:uint; public function ProtoSaveJinchuurikiRankInfo() { super(); } public function clearPlayerId() : void { this.player_id$field = null; } public function get hasPlayerId() : Boolean { return this.player_id$field != null; } public function set playerId(param1:ProtoPlayerKey) : void { this.player_id$field = param1; } public function get playerId() : ProtoPlayerKey { return this.player_id$field; } public function clearPlayerName() : void { this.player_name$field = null; } public function get hasPlayerName() : Boolean { return this.player_name$field != null; } public function set playerName(param1:String) : void { this.player_name$field = param1; } public function get playerName() : String { return this.player_name$field; } public function clearTimes() : void { this.hasField$0 = this.hasField$0 & 4.294967294E9; this.times$field = new uint(); } public function get hasTimes() : Boolean { return (this.hasField$0 & 1) != 0; } public function set times(param1:uint) : void { this.hasField$0 = this.hasField$0 | 1; this.times$field = param1; } public function get times() : uint { return this.times$field; } public function clearTeamId() : void { this.hasField$0 = this.hasField$0 & 4.294967293E9; this.team_id$field = new uint(); } public function get hasTeamId() : Boolean { return (this.hasField$0 & 2) != 0; } public function set teamId(param1:uint) : void { this.hasField$0 = this.hasField$0 | 2; this.team_id$field = param1; } public function get teamId() : uint { return this.team_id$field; } override final function writeToBuffer(param1:WritingBuffer) : void { var _loc2_:* = undefined; if(this.hasPlayerId) { WriteUtils.writeTag(param1,WireType.LENGTH_DELIMITED,1); WriteUtils.write$TYPE_MESSAGE(param1,this.player_id$field); } if(this.hasPlayerName) { WriteUtils.writeTag(param1,WireType.LENGTH_DELIMITED,2); WriteUtils.write$TYPE_STRING(param1,this.player_name$field); } if(this.hasTimes) { WriteUtils.writeTag(param1,WireType.VARINT,3); WriteUtils.write$TYPE_UINT32(param1,this.times$field); } if(this.hasTeamId) { WriteUtils.writeTag(param1,WireType.VARINT,4); WriteUtils.write$TYPE_UINT32(param1,this.team_id$field); } for(_loc2_ in this) { super.writeUnknown(param1,_loc2_); } } override final function readFromSlice(param1:IDataInput, param2:uint) : void { /* * Decompilation error * Code may be obfuscated * Tip: You can try enabling "Automatic deobfuscation" in Settings * Error type: IndexOutOfBoundsException (Index: 4, Size: 4) */ throw new flash.errors.IllegalOperationError("Not decompiled due to error"); } } }
package { public class PacketIn { protected var _type:String; public function get type( ):String { return _type; } } }
package io.decagames.rotmg.ui.popups { import io.decagames.rotmg.ui.popups.signals.CloseAllPopupsSignal; import io.decagames.rotmg.ui.popups.signals.CloseCurrentPopupSignal; import io.decagames.rotmg.ui.popups.signals.ClosePopupByClassSignal; import io.decagames.rotmg.ui.popups.signals.ClosePopupSignal; import io.decagames.rotmg.ui.popups.signals.RemoveLockFade; import io.decagames.rotmg.ui.popups.signals.ShowLockFade; import io.decagames.rotmg.ui.popups.signals.ShowPopupSignal; import robotlegs.bender.bundles.mvcs.Mediator; public class PopupMediator extends Mediator { public function PopupMediator() { super(); this.popups = new Vector.<BasePopup>(); } [Inject] public var view:PopupView; [Inject] public var showPopupSignal:ShowPopupSignal; [Inject] public var closePopupSignal:ClosePopupSignal; [Inject] public var closePopupByClassSignal:ClosePopupByClassSignal; [Inject] public var closeCurrentPopupSignal:CloseCurrentPopupSignal; [Inject] public var closeAllPopupsSignal:CloseAllPopupsSignal; [Inject] public var removeLockFade:RemoveLockFade; [Inject] public var showLockFade:ShowLockFade; private var popups:Vector.<BasePopup>; override public function initialize():void { this.showPopupSignal.add(this.showPopupHandler); this.closePopupSignal.add(this.closePopupHandler); this.closePopupByClassSignal.add(this.closeByClassHandler); this.closeCurrentPopupSignal.add(this.closeCurrentPopupHandler); this.closeAllPopupsSignal.add(this.closeAllPopupsHandler); this.removeLockFade.add(this.onRemoveLock); this.showLockFade.add(this.onShowLock); } override public function destroy():void { this.showPopupSignal.remove(this.showPopupHandler); this.closePopupSignal.remove(this.closePopupHandler); this.closePopupByClassSignal.remove(this.closeByClassHandler); this.closeCurrentPopupSignal.remove(this.closeCurrentPopupHandler); this.removeLockFade.remove(this.onRemoveLock); this.showLockFade.remove(this.onShowLock); } private function closeCurrentPopupHandler():void { var _loc1_:BasePopup = this.popups.pop(); this.view.removeChild(_loc1_); } private function onShowLock():void { this.view.showFade(); } private function onRemoveLock():void { this.view.removeFade(); } private function closeAllPopupsHandler():void { var _loc3_:* = null; var _loc1_:* = this.popups; var _loc5_:int = 0; var _loc4_:* = this.popups; for each(_loc3_ in this.popups) { this.view.removeChild(_loc3_); } this.popups = new Vector.<BasePopup>(); } private function showPopupHandler(param1:BasePopup):void { this.view.addChild(param1); this.popups.push(param1); if (param1.showOnFullScreen) { if (param1.overrideSizePosition != null) { param1.x = Math.round((800 - param1.overrideSizePosition.width) / 2); param1.y = Math.round((600 - param1.overrideSizePosition.height) / 2); } else { param1.x = Math.round((800 - param1.width) / 2); param1.y = Math.round((600 - param1.height) / 2); } } this.drawPopupBackground(param1); } private function closePopupHandler(param1:BasePopup):void { var _loc2_:int = this.popups.indexOf(param1); if (_loc2_ >= 0) { this.view.removeChild(this.popups[_loc2_]); this.popups.splice(_loc2_, 1); } } private function closeByClassHandler(param1:Class):void { var _loc2_:int = this.popups.length - 1; while (_loc2_ >= 0) { if (this.popups[_loc2_] is param1) { this.view.removeChild(this.popups[_loc2_]); this.popups.splice(_loc2_, 1); } _loc2_--; } } private function drawPopupBackground(param1:BasePopup):void { if (param1.disablePopupBackground) { return; } param1.graphics.beginFill(param1.popupFadeColor, param1.popupFadeAlpha); param1.graphics.drawRect(-param1.x, -param1.y, 800, 600); param1.graphics.endFill(); } } }
package org.casalib.control { public interface IRunnable { function start() : void; function stop() : void; } }
/* * Copyright the original author or authors. * * Licensed under 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/MPL-1.1.html * * 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.bourre.load { /** * The FileLoaderEvent class represents the event object passed * to the event listener for <code>FileLoader</code> events. * * @author Francis Bourre * * @see FileLoader */ public class FileLoaderEvent extends LoaderEvent { //-------------------------------------------------------------------- // Events //-------------------------------------------------------------------- /** * Defines the value of the <code>type</code> property of the event * object for a <code>onLoadStart</code> event. * * <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>type</code></td> * <td>Dispatched event type</td> * </tr> * * <tr><th>Method</th><th>Value</th></tr> * <tr> * <td><code>getFileLoader()</code> * </td><td>The loader object</td> * </tr> * </table> * * @eventType onLoadStart */ public static const onLoadStartEVENT : String = LoaderEvent.onLoadStartEVENT; /** * Defines the value of the <code>type</code> property of the event * object for a <code>onLoadInit</code> event. * * <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>type</code></td> * <td>Dispatched event type</td> * </tr> * * <tr><th>Method</th><th>Value</th></tr> * <tr> * <td><code>getFileLoader()</code> * </td><td>The loader object</td> * </tr> * <tr> * <td><code>getFileContent()</code> * </td><td>The loaded file content</td> * </tr> * </table> * * @eventType onLoadInit */ public static const onLoadInitEVENT : String = LoaderEvent.onLoadInitEVENT; /** * Defines the value of the <code>type</code> property of the event * object for a <code>onLoadProgress</code> event. * * <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>type</code></td> * <td>Dispatched event type</td> * </tr> * * <tr><th>Method</th><th>Value</th></tr> * <tr> * <td><code>getFileLoader()</code> * </td><td>The loader object</td> * </tr> * </table> * * @eventType onLoadProgress */ public static const onLoadProgressEVENT : String = LoaderEvent.onLoadProgressEVENT; /** * Defines the value of the <code>type</code> property of the event * object for a <code>onLoadTimeOut</code> event. * * <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>type</code></td> * <td>Dispatched event type</td> * </tr> * * <tr><th>Method</th><th>Value</th></tr> * <tr> * <td><code>getFileLoader()</code> * </td><td>The loader object</td> * </tr> * </table> * * @eventType onLoadTimeOut */ public static const onLoadTimeOutEVENT : String = LoaderEvent.onLoadTimeOutEVENT; /** * Defines the value of the <code>type</code> property of the event * object for a <code>onLoadError</code> event. * * <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>type</code></td> * <td>Dispatched event type</td> * </tr> * * <tr><th>Method</th><th>Value</th></tr> * <tr> * <td><code>getFileLoader()</code> * </td><td>The loader object</td> * </tr> * </table> * * @eventType onLoadError */ public static const onLoadErrorEVENT : String = LoaderEvent.onLoadErrorEVENT; //-------------------------------------------------------------------- // Public API //-------------------------------------------------------------------- /** * Creates a new <code>FileLoaderEvent</code> object. * * @param type Name of the event type * @param fl FileLoader object carried by this event * @param errorMessage (optional) Error message carried by this event */ public function FileLoaderEvent( type : String, fl : FileLoader, errorMessage : String = "" ) { super( type, fl, errorMessage ); } /** * Returns the file loader object carried by this event. * * @return The file loader value carried by this event. */ public function getFileLoader() : FileLoader { return getLoader( ) as FileLoader; } /** * Returns the file content object carried by this event. * * @return The file content value carried by this event. */ public function getFileContent() : Object { return getFileLoader( ).getContent( ); } } }
package com.choa.fitbit.events { import flash.events.Event; /** * ... * @author Michael-Bryant Choa */ public class FitbitOAuthEvent extends Event { public static const CONSUMER_ERROR:String = "consumerError"; public static const PIN_ERROR:String = "pinError"; public static const REQUEST_TOKEN:String = "requestToken"; public static const ACCESS_TOKEN:String = "accessToken"; public function FitbitOAuthEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); } public override function clone():Event { return new FitbitOAuthEvent(type, bubbles, cancelable); } public override function toString():String { return formatToString("FitbitOAuthEvent", "type", "bubbles", "cancelable", "eventPhase"); } } }
package factories { import mx.core.FlexGlobals; public class AstrophysicsTechFactory extends ResourceFactory { /* Constructor is not used... */ public function AstrophysicsTechFactory():* { } [Bindable] public static var name:String = 'astrophysicstech'; private static var level_rates:Array = [ 100, 500, 2500, ]; private static var level_costs:Array = [ 300, 1500, 7500, ]; private static var __current_level__:int = 0; public static function get current_level():int { return __current_level__; } public static function set current_level(level:int):void { if (__current_level__ != level) { __current_level__ = level; } } public static function next_level():void { __current_level__++; var app:GalaxyWars = FlexGlobals.topLevelApplication as GalaxyWars; app.mySO.data.__solar_resource_level__ = __current_level__; app.mySO.flush(); } public static function get current_level_production_rate():Number { try { return level_rates[current_level]; } catch (err:Error) {} return -1; } public static function get current_level_upgrade_cost():Number { try { return level_costs[current_level]; } catch (err:Error) {} return -1; } public static function get current_level_upgrade_time():Number { return ResourceFactory.current_level_upgrade_time(current_level); } } }