CombinedText
stringlengths
4
3.42M
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.charts.chartClasses { import flash.text.TextFormat; import mx.core.ClassFactory; import mx.core.ContextualClassFactory; import mx.core.IFactory; import mx.core.IFlexModuleFactory; import mx.core.IUITextField; /** * InstanceCache is a utility that governs the task of creating and managing * a set of <i>n</i> object instances, where <i>n</i> changes frequently. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class InstanceCache { include "../../core/Version.as"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param type The type of object to construct. * This can be either a Class or an IFactory. * * @param parent An optional DisplayObject to add new instances to. * * @param insertPosition Where in the parent's child list * to insert instances. Set to -1 to add the children to the end of the child list. * * @param moduleFactory The context for using embedded fonts and for * finding the style manager that controls the styles for this component. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function InstanceCache(type:Object, parent:Object = null, insertPosition:int = -1, moduleFactory:IFlexModuleFactory = null) { super(); _parent = parent; if (type is IFactory) { _factory = IFactory(type); } else if (type is Class) { _class = Class(type); _factory = new ContextualClassFactory(Class(type), moduleFactory); } _insertPosition = insertPosition; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private */ private var _parent:Object; /** * @private */ private var _class:Class = null; /** * @private */ private var _insertPosition:int; /** * @private */ private var _count:int = 0; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // count //---------------------------------- [Inspectable(environment="none")] /** * The number of items currently required in the cache. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get count():int { return _count; } /** * @private */ public function set count(value:int):void { if (value == _count) return; var newInstanceCount:int = value; var oldInstanceCount:int = _count; var availableInstanceCount:int = _instances.length; var insertBase:int; if (_parent != null) { insertBase = Math.min(_insertPosition, _parent.numChildren - availableInstanceCount); } if (newInstanceCount> oldInstanceCount) { if (!_factory) { value = 0; } else { for (var i:int = oldInstanceCount; i < newInstanceCount && i < availableInstanceCount; i++) { if (hide) _instances[i].visible = true; if (_parent && remove) { if (insertBase >= 0) _parent.addChildAt(_instances[i],insertBase + i); else _parent.addChild(_instances[i]); } } for (; i < newInstanceCount; i++) { var newInst:Object = _factory.newInstance(); if (_parent) { if (insertBase > 0) _parent.addChildAt(newInst, insertBase + i); else _parent.addChild(newInst); } if (creationCallback != null) creationCallback(newInst,this); _instances.push(newInst); } applyProperties(availableInstanceCount, newInstanceCount); if (_format) applyFormat(availableInstanceCount, newInstanceCount); } } else if (newInstanceCount < oldInstanceCount) { if (remove) { for (i = newInstanceCount; i < oldInstanceCount; i++) { _parent.removeChild(_instances[i]); } } if (hide) { for (i = newInstanceCount; i < oldInstanceCount; i++) { _instances[i].visible = false; } } if (discard) _instances = _instances.slice(0, newInstanceCount); } _count = value; } //---------------------------------- // creationCallback //---------------------------------- [Inspectable(environment="none")] /** * A callback invoked when new instances are created. * This callback has the following signature: * <pre> * function creationCallback(<i>newInstance</i>:Object, <i>cache</i>:InstanceCache):void; * </pre> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var creationCallback:Function; //---------------------------------- // discard //---------------------------------- [Inspectable(environment="none")] /** * Determines if unneeded instances are discarded. * If set to <code>true</code>, extra elements are discarded * when the cache count is reduced. * Otherwise, extra elements are kept in a separate cache * and reused when the count is increased. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var discard:Boolean = false; //---------------------------------- // factory //---------------------------------- /** * @private */ private var _factory:IFactory; [Inspectable(environment="none")] /** * A factory that generates the type of object to cache. * Assigning to this discards all current instances * and recreate new instances of the correct type. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get factory():IFactory { return _factory; } /** * @private */ public function set factory(value:IFactory):void { if (value == _factory || ((value is ClassFactory) && (_factory is ClassFactory) && (ClassFactory(_factory).generator == ClassFactory(value).generator) && (!(value is ContextualClassFactory)))) return; _factory = value; _class = null; var instanceCount:Number = _count; count = 0; count = instanceCount; } //---------------------------------- // format //---------------------------------- /** * @private */ private var _format:TextFormat; [Inspectable(environment="none")] /** * A TextFormat to apply to any instances created. * If set, this format is applied as the current and default format * for the contents of any instances created. * This property is only relevant if the factory * generates TextField instances. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get format():TextFormat { return _format; } /** * @private */ public function set format(value:TextFormat):void { _format = value; if (_format) applyFormat(0, _instances.length); } //---------------------------------- // hide //---------------------------------- [Inspectable(environment="none")] /** * Determines if unneeded instances should be hidden. * If <code>true</code>, the <code>visible</code> property * is set to <code>false</code> on each extra element * when the cache count is reduced, and set to <code>true</code> * when the count is increased. * * <p>This property is only relevant when the factory * generates DisplayObjects. * Setting this property to <code>true</code> for other factory types * generates a run-time error.</p> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var hide:Boolean = true; //---------------------------------- // insertPosition //---------------------------------- [Inspectable(environment="none")] /** * The position of the instance in the parent's child list. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function set insertPosition(value:int):void { if (value != _insertPosition) { _insertPosition = value; if (_parent) { var n:int = _instances.length; for (var i:int = 0; i < n; i++) { _parent.setChildIndex(_instances[i], i + _insertPosition); } } } } //---------------------------------- // instances //---------------------------------- /** * @private */ private var _instances:Array /* of Object */= []; [Inspectable(environment="none")] /** * The Array of cached instances. * There may be more instances in this Array than currently requested. * You should rely on the <code>count</code> property * of the instance cache rather than the length of this Array. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get instances():Array /* of Object */ { return _instances; } //---------------------------------- // properties //---------------------------------- /** * @private */ private var _properties:Object = {}; [Inspectable(environment="none")] /** * A hashmap of properties to assign to new instances. * Each key/value pair in this hashmap is assigned * to each new instance created. * The property hashmap is assigned to any existing instances when set. * * <p>The values in the hashmap are not cloned; * object values are shared by all instances.</p> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get properties():Object { return _properties; } /** * @private */ public function set properties(value:Object):void { _properties = value; applyProperties(0, _instances.length); } //---------------------------------- // remove //---------------------------------- [Inspectable(environment="none")] /** * Determines if unneeded instances should be removed from their parent. * If <code>true</code>, the <code>removeChild()</code> method * is called on the parent for each extra element * when the cache count is reduced. * * <p>This property is only relevant when the factory * generates DisplayObjects. * Setting this property to <code>true</code> for other factory types * generates a run-time error.</p> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var remove:Boolean = false; //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private */ private function applyProperties(start:int, end:int):void { for (var i:int = start; i < end; i++) { var newInst:Object = _instances[i]; for (var p:String in _properties) { newInst[p] = _properties[p]; } } } /** * @private */ private function applyFormat(start:int, end:int):void { for (var i:int = start; i < end; i++) { var newField:IUITextField = _instances[i]; newField.setTextFormat(_format); newField.defaultTextFormat = _format; } } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.automation.delegates.controls { import flash.display.DisplayObject; import flash.events.Event; import flash.events.KeyboardEvent; import mx.automation.Automation; import mx.controls.LinkBar; import mx.core.EventPriority; [Mixin] /** * * Defines methods and properties required to perform instrumentation for the * LinkBar control. * * @see mx.controls.LinkBar * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class LinkBarAutomationImpl extends NavBarAutomationImpl { include "../../../core/Version.as"; //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- /** * Registers the delegate class for a component class with automation manager. * * @param root The SystemManger of the application. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function init(root:DisplayObject):void { Automation.registerDelegateClass(LinkBar, LinkBarAutomationImpl); } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * @param obj LinkBar object to be automated. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function LinkBarAutomationImpl(obj:LinkBar) { super(obj); } /** * @private * storage for the owner component */ protected function get linkBar():LinkBar { return uiComponent as LinkBar; } /** * @private */ private var preventRecording:Boolean = false; /** * @private */ override public function recordAutomatableEvent(event:Event, cacheable:Boolean = false):void { if (!preventRecording) super.recordAutomatableEvent(event, cacheable); preventRecording = false; } /** * @private */ override protected function keyDownHandler(event:KeyboardEvent):void { preventRecording = true; } } }
package test { public class ASCompleteTest {} } class A { public function set foo(v:Function/*(v1:*):int*/):void { } } class B extends A { override $(EntryPoint) }
package cmodule.lua_wrapper { public const ___s2b_D2A:int = regFunc(FSM___s2b_D2A.start); }
/** BulkLoader: manage multiple loadings in Actioncript 3. * * * @author Arthur Debert */ /** * Licensed under the MIT License * * Copyright (c) 2006-2007 Arthur Debert * * 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. * * http://code.google.com/p/bulk-loader/ * http://www.opensource.org/licenses/mit-license.php * */ package br.com.stimuli.loading { import br.com.stimuli.loading.loadingtypes.*; import flash.display.*; import flash.events.*; import flash.media.Sound; import flash.net.*; import flash.utils.*; /** * Dispatched on download progress by any of the items to download. * * @eventType br.com.stimuli.loading.BulkProgressEvent.PROGRESS */ [Event(name="progress", type="br.com.stimuli.loading.BulkProgressEvent")] /** * Dispatched when all items have been downloaded and parsed. Note that this event only fires if there are no errors. * * @eventType br.com.stimuli.loading.BulkProgressEvent.COMPLETE */ [Event(name="complete", type="br.com.stimuli.loading.BulkProgressEvent")] /** * Manages loading for simultaneous items and multiple formats. * Exposes a simpler interface, with callbacks instead of events for each item to be loaded (but still dispatched "global" events). * The number of simultaneous connections is configurable. * * @example Basic usage:<listing version="3.0"> import br.com.stimuli.loading.BulkLoader; / /instantiate a BulkLoader with a name : a way to reference this instance from another classes without having to set a expolicit reference on many places var bulkLoader : BulkLoader = new BulkLoader("main loading"); // add items to be loaded bulkLoader.add("my_xml_file.xml"); bulkLoader.add("main.swf"); // you can also use a URLRequest object var backgroundURL : URLRequest = new URLRequest("background.jpg"); bulkLoader.add(backgroundURL); // add event listeners for the loader itself : // event fired when all items have been loaded and nothing has failed! bulkLoader.addEventListener(BulkLoader.COMPLETE, onCompleteHandler); // event fired when loading progress has been made: bulkLoader.addEventListener(BulkLoader.PROGRESS, _onProgressHandler); // start loading all items bulkLoader.start(); function _onProgressHandler(evt : ProgressEvent) : void{ trace("Loaded" , evt.bytesLoaded," of ", evt.bytesTotal); } function onCompleteHandler(evt : ProgressEvent) : void{ trace("All items are loaeded and ready to consume"); // grab the main movie clip: var mainMovie : MovieClip = bulkLoader.getMovieClip("main.swf"); // Get the xml object: var mXML : XML = bulkLoader.getXML("my_xml_file.xml"); // grab the bitmap for the background image by a string: var myBitmap : Bitmap = bulkLoader.getBitmap("background.jpg"); // grab the bitmap for the background image using the url rquest object: var myBitmap : Bitmap = bulkLoader.getBitmap(backgroundURL); } // In any other class you can access those assets without having to pass around references to the bulkLoader instance. // In another class you get get a reference to the "main loading" bulkLoader: var mainLoader : BulkLoader = BulkLoader.getLoader("main loading"); // now grab the xml: var mXML : XML = mainLoader.getXML("my_xml_file.xml"); // or shorter: var mXML : XML = BulkLoader.getLoader("main loading").getXML("my_xml_file.xml"); * </listing> * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * * @author Arthur Debert * @since 15.09.2007 */ public class BulkLoader extends EventDispatcher { private static var _bundles:Dictionary; public static function get bundles():Dictionary { if( !_bundles ) _bundles = new Dictionary(); return _bundles; } /** Version. Useful for debugging. */ public static const VERSION : String = "$Id$"; /** Tells this class to use a <code>Loader</code> object to load the item.*/ public static const TYPE_BINARY : String = "binary"; /** Tells this class to use a <code>Loader</code> object to load the item.*/ public static const TYPE_IMAGE : String = "image"; /** Tells this class to use a <code>Loader</code> object to load the item.*/ public static const TYPE_MOVIECLIP : String = "movieclip"; /** Tells this class to use a <code>Sound</code> object to load the item.*/ public static const TYPE_SOUND : String = "sound"; /** Tells this class to use a <code>URLRequest</code> object to load the item.*/ public static const TYPE_TEXT : String = "text"; /** Tells this class to use a <code>XML</code> object to load the item.*/ public static const TYPE_XML : String = "xml"; /** Tells this class to use a <code>NetStream</code> object to load the item.*/ public static const TYPE_VIDEO : String = "video"; public static const AVAILABLE_TYPES : Array = [TYPE_VIDEO, TYPE_XML, TYPE_TEXT, TYPE_SOUND, TYPE_MOVIECLIP, TYPE_IMAGE, TYPE_BINARY] /** List of all file extensions that the <code>BulkLoader</code> knows how to guess. * Availabe types: swf, jpg, jpeg, gif, png. */ public static var AVAILABLE_EXTENSIONS : Array = ["swf", "jpg", "jpeg", "gif", "png", "flv", "mp3", "xml", "txt", "js" ]; /** List of file extensions that will be automagically use a <code>Loader</code> object for loading. * Availabe types: swf, jpg, jpeg, gif, png, image. */ public static var IMAGE_EXTENSIONS : Array = [ "jpg", "jpeg", "gif", "png"]; public static var MOVIECLIP_EXTENSIONS : Array = ['swf']; /** List of file extensions that will be automagically treated as text for loading. * Availabe types: txt, js, xml, php, asp . */ public static var TEXT_EXTENSIONS : Array = ["txt", "js", "php", "asp", "py" ]; /** List of file extensions that will be automagically treated as video for loading. * Availabe types: flv, f4v, f4p. */ public static var VIDEO_EXTENSIONS : Array = ["flv", "f4v", "f4p", "mp4"]; /** List of file extensions that will be automagically treated as sound for loading. * Availabe types: mp3, f4a, f4b. */ public static var SOUND_EXTENSIONS : Array = ["mp3", "f4a", "f4b"]; public static var XML_EXTENSIONS : Array = ["xml"]; /** @private */ public static var _customTypesExtensions : Object ; /** * The name of the event * @eventType progress */ public static const PROGRESS : String = "progress"; /** * The name of the event * @eventType complete */ public static const COMPLETE : String = "complete"; /** * The name of the event * @eventType httpStatus */ public static const HTTP_STATUS : String = "httpStatus"; /** * The name of the event * @eventType error */ public static const ERROR : String = "error"; /** * The name of the event * @eventType securityError */ public static const SECURITY_ERROR : String = "securityError"; /** * The name of the event * @eventType error */ public static const OPEN : String = "open"; /** * The name of the event * @eventType error */ public static const CAN_BEGIN_PLAYING : String = "canBeginPlaying"; public static const CHECK_POLICY_FILE : String = "checkPolicyFile" // properties on adding a new url: /** If <code>true</code> a random query (or post data parameter) will be added to prevent caching. Checked when adding a new item to load. * @see #add() */ public static const PREVENT_CACHING : String = "preventCache"; /** An array of RequestHeader objects to be used when contructing the <code>URLRequest</code> object. If the <code>url</code> parameter is passed as a <code>URLRequest</code> object it will be ignored. Checked when adding a new item to load. * @see #add() */ public static const HEADERS : String = "headers"; /** An object definig the loading context for this load operario. If this item is of <code>TYPE_SOUND</code>, a <code>SoundLoaderContext</code> is expected. If it's a <code>TYPE_IMAGE</code> a LoaderContext should be passed. Checked when adding a new item to load. * @see #add() */ public static const CONTEXT : String = "context"; /** A <code>String</code> to be used to identify an item to load, can be used in any method that fetches content (as the key parameters), stops, removes and resume items. Checked when adding a new item to load. * @see #add() * @see #getContent() * @see #pause() * @see #resume() * @see #removeItem() */ public static const ID : String = "id"; /** An <code>int</code> that controls which items are loaded first. Items with a higher <code>PRIORITY</code> will load first. If more than one item has the same <code>PRIORITY</code> number, the order in which they are added will be taken into consideration. Checked when adding a new item to load. * @see #add() */ public static const PRIORITY : String = "priority"; /** The number, as an <code>int</code>, to retry downloading an item in case it fails. Checked when adding a new item to load. * @default 3 * @see #add() */ public static const MAX_TRIES : String = "maxTries"; /* An <code>int</code> that sets a relative size of this item. It's used on the <code>BulkProgressEvent.weightPercent</code> property. This allows bulk downloads with more items that connections and with widely varying file sizes to give a more accurate progress information. Checked when adding a new item to load. * @see #add() * @default 3 */ public static const WEIGHT : String = "weight"; /* An <code>Boolean</code> that if true and applied on a video item will pause the video on the start of the loading operation. * @see #add() * @default false */ public static const PAUSED_AT_START : String = "pausedAtStart"; public static const GENERAL_AVAILABLE_PROPS : Array = [ WEIGHT, MAX_TRIES, HEADERS, ID, PRIORITY, PREVENT_CACHING, "type"]; /** @private */ public var _name : String; /** @private */ public var _id : int; /** @private */ public static var _instancesCreated : int = 0; /** @private */ public var _items : Array = []; /** @private */ public var _contents : Dictionary = new Dictionary(true); /** @private */ public static var _allLoaders : Object = {}; /** @private */ public var _additionIndex : int = 0; // Maximum number of simultaneous open requests public static const DEFAULT_NUM_CONNECTIONS : int = 12; /** @private */ public var _numConnections : int = DEFAULT_NUM_CONNECTIONS; public var maxConnectionsPerHost : int = 2; /** @private */ public var _connections : Object; /** * @private **/ public var _loadedRatio : Number = 0; /** @private */ public var _itemsTotal : int = 0; /** @private */ public var _itemsLoaded : int = 0; /** @private */ public var _totalWeight : int = 0; /** @private */ public var _bytesTotal : int = 0; /** @private */ public var _bytesTotalCurrent : int = 0; /** @private */ public var _bytesLoaded : int = 0; /** @private */ public var _percentLoaded : Number = 0; /** @private */ public var _weightPercent : Number; /**The average latency (in miliseconds) for the entire loading.*/ public var avgLatency : Number; /**The average speed (in kb/s) for the entire loading.*/ public var speedAvg : Number; /** @private */ public var _speedTotal : Number; /** @private */ public var _startTime : int ; /** @private */ public var _endTIme : int; /** @private */ public var _lastSpeedCheck : int; /** @private */ public var _lastBytesCheck : int; /** @private */ public var _speed : Number; /**Time in seconds for the whole loading. Only available after everything is laoded*/ public var totalTime : Number; /** LogLevel: Outputs everything that is happening. Usefull for debugging. */ public static const LOG_VERBOSE : int = 0; /**Ouputs noteworthy events such as when an item is started / finished loading.*/ public static const LOG_INFO : int = 2; /**Ouputs noteworthy events such as when an item is started / finished loading.*/ public static const LOG_WARNINGS : int = 3; /**Will only trace errors. Defaut level*/ public static const LOG_ERRORS : int = 4; /**Nothing will be logged*/ public static const LOG_SILENT : int = 10; /**The logging level <code>BulkLoader</code> will use. * @see #LOG_VERBOSE * @see #LOG_SILENT * @see #LOG_ERRORS * @see #LOG_INFO */ public static const DEFAULT_LOG_LEVEL : int = LOG_ERRORS; /** @private */ public var logLevel: int = DEFAULT_LOG_LEVEL; /** @private */ public var _allowsAutoIDFromFileName : Boolean = false; /** @private */ public var _isRunning : Boolean; /** @private */ public var _isFinished : Boolean; /** @private */ public var _isPaused : Boolean = true; /** @private */ public var _logFunction : Function = trace; /** @private */ public var _stringSubstitutions : Object; /** @private */ public static var _typeClasses : Object = { image: ImageItem, movieclip: ImageItem, xml: XMLItem, video: VideoItem, sound: SoundItem, text: URLItem, binary: BinaryItem } /** Creates a new BulkLoader object identifiable by the <code>name</code> parameter. The <code>name</code> parameter must be unique, else an Error will be thrown. * * @param name A name that can be used later to reference this loader in a static context, * @param numConnections The number of maximum simultaneous connections to be open. * @param logLevel At which level should traces be outputed. By default only errors will be traced. * * @see #numConnections * @see #log() */ public function BulkLoader(name : String, numConnections : int = BulkLoader.DEFAULT_NUM_CONNECTIONS, logLevel : int = BulkLoader.DEFAULT_LOG_LEVEL){ if (Boolean(_allLoaders[name])){ __debug_print_loaders(); throw new Error ("BulkLoader with name'" + name +"' has already been created."); }else if (!name ){ throw new Error ("Cannot create a BulkLoader instance without a name"); } _allLoaders[name] = this; if (numConnections > 0){ this._numConnections = numConnections; } this.logLevel = logLevel; _name = name; _instancesCreated ++; _id = _instancesCreated; _additionIndex = 0; // we create a mock event listener for errors, else Unhandled errors will bubble and display an stack trace to the end user: addEventListener(BulkLoader.ERROR, function (e:Event):void{}, false, 1, true); } /** Creates a BulkLoader instance with an unique name. This is useful for situations where you might be creating * many BulkLoader instances and it gets tricky to garantee that no other instance is using that name. * @param numConnections The number of maximum simultaneous connections to be open. * @param logLevel At which level should traces be outputed. By default only errors will be traced. * @return A BulkLoader intance, with an unique name. */ public static function createUniqueNamedLoader( numConnections : int=BulkLoader.DEFAULT_NUM_CONNECTIONS, logLevel : int = BulkLoader.DEFAULT_LOG_LEVEL) : BulkLoader{ return new BulkLoader(BulkLoader.getUniqueName(), numConnections, logLevel); } public static function getUniqueName() : String{ return "BulkLoader-" + _instancesCreated; } /** Fetched a <code>BulkLoader</code> object created with the <code>name</code> parameter. * This is usefull if you must access loades assets from another scope, without having to pass direct references to this loader. * @param name The name of the loader to be fetched. * @return The BulkLoader instance that was registred with that name. Returns null if none is found. */ public static function getLoader(name :String) : BulkLoader{ return BulkLoader._allLoaders[name] as BulkLoader; } /** @private */ public static function _hasItemInBulkLoader(key : *, atLoader : BulkLoader) : Boolean{ var item : LoadingItem = atLoader.get(key); if (item) { return true; } return false; } /** Checks if there is <b>loaded</b> item in this <code>BulkLoader</code>. * @param The url (as a <code>String</code> or a <code>URLRequest</code> object)or an id (as a <code>String</code>) by which the item is identifiable. * @param searchAll If true will search through all <code>BulkLoader</code> instances. Else will only search this one. * @return True if a loader has a <b>loaded</b> item stored. */ public function hasItem(key : *, searchAll : Boolean = true) : Boolean{ var loaders : *; if (searchAll){ loaders = _allLoaders; }else{ loaders = [this]; } for each (var l : BulkLoader in loaders){ if (_hasItemInBulkLoader(key, l )) return true; } return false; } /** Checks which <code>BulkLoader</code> has an item by the given key. * @param The url (as a <code>String</code> or a <code>URLRequest</code> object)or an id (as a <code>String</code>) by which the item is identifiable. * @return The <code>BulkLoader</code> instance that has the given key or <code>null</code> if no key if found in any loader. */ public static function whichLoaderHasItem(key : *) : BulkLoader{ for each (var l : BulkLoader in _allLoaders){ if (BulkLoader._hasItemInBulkLoader(key, l )) return l; } return null; } /** Adds a new assets to be loaded. The <code>BulkLoader</code> object will manage diferent assets type. If the right type cannot be infered from the url termination (e.g. the url ends with ".swf") the BulkLoader will relly on the <code>type</code> property of the <code>props</code> parameter. If both are set, the <code>type</code> property of the props object will overrite the one defined in the <code>url</code>. In case none is specified and the url won't hint at it, the type <code>TYPE_TEXT</code> will be used. * * @param url String OR URLRequest A <code>String</code> or a <code>URLRequest</code> instance. * @param props An object specifing extra data for this loader. The following properties are supported:<p/> * <table> * <th>Property name</th> * <th>Class constant</th> * <th>Data type</th> * <th>Description</th> * <tr> * <td>preventCache</td> * <td><a href="#PREVENT_CACHING">PREVENT_CACHING</a></td> * <td><code>Boolean</code></td> * <td>If <code>true</code> a random query string will be added to the url (or a post param in case of post reuquest).</td> * </tr> * <tr> * <td>id</td> * <td><a href="#ID">ID</a></td> * <td><code>String</code></td> * <td>A string to identify this item. This id can be used in any method that uses the <code>key</code> parameter, such as <code>pause, removeItem, resume, getContent, getBitmap, getBitmapData, getXML, getMovieClip and getText</code>.</td> * </tr> * <tr> * <td>priority</td. * <td><a href="#PRIORITY">PRIORITY</a></td> * <td><code>int</code></td> * <td>An <code>int</code> used to order which items till be downloaded first. Items with a higher priority will download first. For items with the same priority they will be loaded in the same order they've been added.</td> * </tr> * <tr> * <td>maxTries</td. * <td><a href="#MAX_TRIES">MAX_TRIES</a></td> * <td><code>int</code></td> * <td>The number of retries in case the lading fails, defaults to 3.</td> * </tr> * <tr> * <td>weight</td. * <td><a href="#WEIGHT">WEIGHT</a></td> * <td><code>int</code></td> * <td>A number that sets an arbitrary relative size for this item. See #weightPercent.</td> * </tr> * <tr> * <td>headers</td. * <td><a href="#HEADERS">HEADERS</a></td> * <td><code>Array</code></td> * <td>An array of <code>RequestHeader</code> objects to be used when constructing the URL. If the <code>url</code> parameter is passed as a string, <code>BulkLoader</code> will use these request headers to construct the url.</td> * </tr> * <tr> * <td>context</td. * <td><a href="#CONTEXT">CONTEXT</a></td> * <td><code>LoaderContext or SoundLoaderContext</code></td> * <td>An object definig the loading context for this load operario. If this item is of <code>TYPE_SOUND</code>, a <code>SoundLoaderContext</code> is expected. If it's a <code>TYPE_IMAGE</code> a LoaderContext should be passed.</td> * </tr> * <tr> * <td>pausedAtStart</td. * <td><a href="#PAUSED_AT_START">PAUSED_AT_START</a></td> * <td><code>Boolean</code></td> * <td>If true, the nestream will be paused when loading has begun.</td> * </tr> * </table> * You can use string substitutions (variable expandsion). * @example Retriving contents:<listing version="3.0"> import br.stimuli.loaded.BulkLoader; var bulkLoader : BulkLoader = new BulkLoader("main"); // simple item: bulkLoader.add("config.xml"); // use an id that can be retirved latterL bulkLoader.add("background.jpg", {id:"bg"}); // or use a static var to have auto-complete and static checks on your ide: bulkLoader.add("background.jpg", {BulkLoader.ID:"bg"}); // loads the languages.xml file first and parses before all items are done: public function parseLanguages() : void{ var theLangXML : XML = bulkLoader.getXML("langs"); // do something wih the xml: doSomething(theLangXML); } bulkLoader.add("languages.xml", {priority:10, onComplete:parseLanguages, id:"langs"}); // Start the loading operation with only 3 simultaneous connections: bulkLoader.start(3) </listing> * @see #stringSubstitutions * */ public function add(url : *, props : Object= null ) : LoadingItem { if(!_name){ throw new Error("[BulkLoader] Cannot use an instance that has been cleared from memory (.clear())"); } if(!url || !String(url)){ throw new Error("[BulkLoader] Cannot add an item with a null url") } props = props || {}; if (url is String){ url = new URLRequest(BulkLoader.substituteURLString(url, _stringSubstitutions)); if(props[HEADERS]){ url.requestHeaders = props[HEADERS]; } }else if (!url is URLRequest){ throw new Error("[BulkLoader] cannot add object with bad type for url:'" + url.url); } var item : LoadingItem = get(props[ID]); // have already loaded this? if( item ){ log("Add received an already added id: " + props[ID] + ", not adding a new item"); return item; } var type : String; if (props["type"]) { type = props["type"].toLowerCase(); // does this type exist? if (AVAILABLE_TYPES.indexOf(type)==-1){ log("add received an unknown type:", type, "and will cast it to text", LOG_WARNINGS); } } if (!type){ type = guessType(url.url); } _additionIndex ++; item = new _typeClasses[type] (url, type , _instancesCreated + "_" + String(_additionIndex)); if (!props["id"] && _allowsAutoIDFromFileName){ props["id"] = getFileName(url.url); log("Adding automatic id from file name for item:", item , "( id= " + props["id"] + " )"); } var errors : Array = item._parseOptions(props); for each (var error : String in errors){ log(error, LOG_WARNINGS); } log("Added",item, LOG_VERBOSE); // properties from the props argument item._addedTime = getTimer(); item._additionIndex = _additionIndex; // add a lower priority than default, else the event for all items complete will fire before // individual listerners attached to the item item.addEventListener(Event.COMPLETE, _onItemComplete, false, int.MIN_VALUE, true); // need an extra event listener to increment items loaded, because this must happen // **before** the item's normal event, or else client code will get a dummy value for it item.addEventListener(Event.COMPLETE, _incrementItemsLoaded, false, int.MAX_VALUE, true); item.addEventListener(ERROR, _onItemError, false, 0, true); item.addEventListener(Event.OPEN, _onItemStarted, false, 0, true); item.addEventListener(ProgressEvent.PROGRESS, _onProgress, false, 0, true); _items.push(item); _itemsTotal += 1; _totalWeight += item.weight; sortItemsByPriority(); _isFinished = false; if (!_isPaused){ _loadNext(); } return item; } /** Start loading all items added previously * @param withConnections [optional]The maximum number of connections to make at the same time. If specified, will override the parameter passed (if any) to the constructor. * @see #numConnections * @see #see #BulkLoader() */ public function start(withConnections : int = -1 ) : void{ if (withConnections > 0){ _numConnections = withConnections; } if(_connections){ _loadNext(); return; } _startTime = getTimer(); _connections = {}; _loadNext(); _isRunning = true; _lastBytesCheck = 0; _lastSpeedCheck = getTimer(); _isPaused = false; } /** Forces the item specified by key to be reloaded right away. This will stop any open connection as needed. * @param key The url request, url as a string or a id from which the asset was created. * @return <code>True</code> if an item with that key is found, <code>false</code> otherwise. */ public function reload(key : *) : Boolean{ var item : LoadingItem = get(key); if(!item){ return false; } _removeFromItems(item); _removeFromConnections(item); item.stop(); item.cleanListeners(); item.status = null; _isFinished = false; item._addedTime = getTimer(); item._additionIndex = _additionIndex ++; item.addEventListener(Event.COMPLETE, _onItemComplete, false, int.MIN_VALUE, true); item.addEventListener(Event.COMPLETE, _incrementItemsLoaded, false, int.MAX_VALUE, true); item.addEventListener(ERROR, _onItemError, false, 0, true); item.addEventListener(Event.OPEN, _onItemStarted, false, 0, true); item.addEventListener(ProgressEvent.PROGRESS, _onProgress, false, 0, true); _items.push(item); _itemsTotal += 1; _totalWeight += item.weight; sortItemsByPriority(); _isFinished = false; loadNow(item); return true; } /** Forces the item specified by key to be loaded right away. This will stop any open connection as needed. * If needed, the connection to be closed will be the one with the lower priority. In case of a tie, the one * that has more bytes to complete will be removed. The item to load now will be automatically be set the highest priority value in this BulkLoader instance. * @param key The url request, url as a string or a id from which the asset was created. * @return <code>True</code> if an item with that key is found, <code>false</code> otherwise. */ public function loadNow(key : *) : Boolean{ var item : LoadingItem = get(key); if(!item){ return false; } if(!_connections){ _connections = {}; } // is this item already loaded or loading? if (item.status == LoadingItem.STATUS_FINISHED || item.status == LoadingItem.STATUS_STARTED){ return true; } // do we need to remove an item from the open connections? if (_getNumConnections() >= numConnections || _getNumConnectionsForItem(item) >= maxConnectionsPerHost ){ //which item should we remove? var itemToRemove : LoadingItem = _getLeastUrgentOpenedItem(); pause(itemToRemove); _removeFromConnections(itemToRemove); itemToRemove.status = null; } // update the item's piority so that subsequent calls to loadNow don't close a // connection we've just started to load item._priority = highestPriority; _loadNext(item); return true; } /** @private * Figures out which item to remove from open connections, comparation is done by priority * and then by bytes remaining */ public function _getLeastUrgentOpenedItem() : LoadingItem{ var itemsToLoad : Array = _getAllConnections(); itemsToLoad.sortOn(["priority", "bytesRemaining", "_additionIndex"], [Array.NUMERIC, Array.DESCENDING , Array.NUMERIC, Array.NUMERIC]) var toRemove : LoadingItem = LoadingItem(itemsToLoad[0]); return toRemove; } /** Register a new file extension to be loaded as a given type. This is used both in the guessing of types from the url and affects how loading is done for each type. * If you are adding an extension to be of a type you are creating, you must pass the <code>withClass</code> parameter, which should be a class that extends LoadingItem. * @param extension The file extension to be used (can include the dot or not) * @param atType Which type this extension will be associated with. * @param withClass For new types (not new extensions) wich class that extends LoadingItem should be used to mange this item. * @see #TYPE_IMAGE * @see #TYPE_VIDEO * @see #TYPE_SOUND * @see #TYPE_TEXT * @see #TYPE_XML * @see #TYPE_MOVIECLIP * @see #LoadingItem * * @return A <code>Boolean</code> indicating if the new extension was registered. */ public static function registerNewType( extension : String, atType : String, withClass : Class = null) : Boolean { // Normalize extension if (extension.charAt(0) == ".") extension = extension.substring(1); if(!_customTypesExtensions) _customTypesExtensions = {}; // Is this a new type? if (AVAILABLE_TYPES.indexOf(atType) == -1){ // new type: we need a class for that: if (!Boolean(withClass) ){ throw new Error("[BulkLoader]: When adding a new type and extension, you must determine which class to use"); } // add that class to the available classes _typeClasses[atType] = withClass; if(!_customTypesExtensions[atType]){ _customTypesExtensions[atType] = []; AVAILABLE_TYPES.push(atType); } _customTypesExtensions[atType].push( extension); return true; }else{ // do have this exension registred for this type? if(_customTypesExtensions[atType]) _customTypesExtensions[atType].push( extension); } var extensions : Array ; var options : Object = { }; options[TYPE_IMAGE] = IMAGE_EXTENSIONS, options[TYPE_MOVIECLIP] = MOVIECLIP_EXTENSIONS, options[TYPE_VIDEO] = VIDEO_EXTENSIONS, options[TYPE_SOUND] = SOUND_EXTENSIONS, options[TYPE_TEXT] = TEXT_EXTENSIONS, options[TYPE_XML] = XML_EXTENSIONS, extensions = options[atType]; if (extensions && extensions.indexOf(extension) == -1){ extensions.push(extension); return true; } return false; } public function _getNextItemToLoad() : LoadingItem{ // check for "stale items" _getAllConnections().forEach(function(i : LoadingItem, ...rest) : void{ if(i.status == LoadingItem.STATUS_ERROR && i.numTries == i.maxTries){ _removeFromConnections(i); } }); for each (var checkItem:LoadingItem in _items){ if (!checkItem._isLoading && checkItem.status != LoadingItem.STATUS_STOPPED && _canOpenConnectioForItem(checkItem)){ return checkItem; } } return null; } // if toLoad is specified it will take precedence over whoever is queued cut line /** @private */ public function _loadNext(toLoad : LoadingItem = null) : Boolean{ if(_isFinished){ return false; }if (!_connections){ _connections = {}; } var next : Boolean = false; toLoad = toLoad || _getNextItemToLoad(); if (toLoad){ next = true; _isRunning = true; // need to check again, as _loadNext might have been called with an item to be loaded forcefully. if(_canOpenConnectioForItem(toLoad)){ var connectionsForItem : Array = _getConnectionsForHostName(toLoad.hostName) connectionsForItem.push(toLoad); toLoad.load(); //trace("begun loading", toLoad.url.url);//, _getNumConnectionsForItem(toLoad) + "/" + maxConnectionsPerHost, _getNumConnections() + "/" + numConnections); log("Will load item:", toLoad, LOG_INFO); } // if we've got any more connections to open, load the next item if(_getNextItemToLoad()){ _loadNext(); } } return next; } /** @private */ public function _onItemComplete(evt : Event) : void { var item : LoadingItem = evt.target as LoadingItem; _removeFromConnections(item); log("Loaded ", item, LOG_INFO); log("Items to load", getNotLoadedItems(), LOG_VERBOSE); item.cleanListeners(); _contents[item.url.url] = item.content; var next : Boolean= _loadNext(); var allDone : Boolean = _isAllDoneP(); if(allDone) { _onAllLoaded(); } evt.stopPropagation(); } /** @private */ public function _incrementItemsLoaded(evt : Event) : void{ _itemsLoaded ++; } /** @private */ public function _updateStats() : void { avgLatency = 0; speedAvg = 0; var totalLatency : Number = 0; var totalBytes : int = 0; _speedTotal = 0; var num : Number = 0; for each(var item : LoadingItem in _items){ if (item._isLoaded && item.status != LoadingItem.STATUS_ERROR){ totalLatency += item.latency; totalBytes += item.bytesTotal; num ++; } } _speedTotal = (totalBytes/1024) / totalTime; avgLatency = totalLatency / num; speedAvg = _speedTotal / num; } /** @private */ public function _removeFromItems(item : LoadingItem) : Boolean{ var removeIndex : int = _items.indexOf(item); if(removeIndex > -1){ _items.splice( removeIndex, 1); }else{ return false; } if(item._isLoaded){ _itemsLoaded --; } _itemsTotal --; _totalWeight -= item.weight; log("Removing " + item, LOG_VERBOSE); item.removeEventListener(Event.COMPLETE, _onItemComplete, false) item.removeEventListener(Event.COMPLETE, _incrementItemsLoaded, false) item.removeEventListener(ERROR, _onItemError, false); item.removeEventListener(Event.OPEN, _onItemStarted, false); item.removeEventListener(ProgressEvent.PROGRESS, _onProgress, false); return true; } /** @private */ public function _removeFromConnections(item : *) : Boolean{ if(!_connections || _getNumConnectionsForItem(item) == 0) return false; var connectionsForHost : Array = _getConnectionsForHostName(item.hostName);(item); var removeIndex : int = connectionsForHost.indexOf(item) if(removeIndex > -1){ connectionsForHost.splice( removeIndex, 1); return true; } return false; } public function _getNumConnectionsForHostname(hostname :String) : int{ var conns : Array = _getConnectionsForHostName(hostname); if (!conns) { return 0; } return conns.length; } /** @private */ public function _getNumConnectionsForItem(item :LoadingItem) : int{ var conns : Array = _getConnectionsForHostName(item.hostName);(item); if (!conns) { return 0; } return conns.length; } /** @private */ public function _getAllConnections() : Array { var conns : Array = []; for (var hostname : String in _connections){ conns = conns.concat ( _connections[hostname] ) ; } return conns; } /** @private **/ public function _getNumConnections() : int{ var connections : int = 0; for (var hostname : String in _connections){ connections += _connections[hostname].length; } return connections; } public function _getConnectionsForHostName (hostname : String) : Array { if (_connections[hostname] == null ){ _connections[hostname] = []; } return _connections[hostname]; } public function _canOpenConnectioForItem(item :LoadingItem) : Boolean{ if (_getNumConnections() >= numConnections) return false; if (_getNumConnectionsForItem(item) >= maxConnectionsPerHost) return false; return true; } /** @private */ public function _onItemError(evt : ErrorEvent) : void{ var item : LoadingItem = evt.target as LoadingItem; _removeFromConnections(item); log("After " + item.numTries + " I am giving up on " + item.url.url, LOG_ERRORS); log("Error loading", item, evt.text, LOG_ERRORS); _loadNext(); //evt.stopPropagation(); //evt.currentTarget = item; dispatchEvent(evt); } /** @private */ public function _onItemStarted(evt : Event) : void{ var item : LoadingItem = evt.target as LoadingItem; log("Started loading", item, LOG_INFO); dispatchEvent(evt); } /** @private */ public function _onProgress(evt : Event = null) : void{ // TODO: check these values are correct! tough _onProgress var e : BulkProgressEvent = getProgressForItems(_items); // update values: _bytesLoaded = e.bytesLoaded; _bytesTotal = e.bytesTotal; _weightPercent = e.weightPercent; _percentLoaded = e.percentLoaded; _bytesTotalCurrent = e.bytesTotalCurrent; _loadedRatio = e.ratioLoaded; dispatchEvent(e); } /** Calculates the progress for a specific set of items. * @param keys An <code>Array</code> containing keys (ids or urls) or <code>LoadingItem</code> objects to measure progress of. * @return A <code>BulkProgressEvent</code> object with the current progress status. * @see BulkProgressEvent */ public function getProgressForItems(keys : Array) : BulkProgressEvent{ _bytesLoaded = _bytesTotal = _bytesTotalCurrent = 0; var localWeightPercent : Number = 0; var localWeightTotal : int = 0; var itemsStarted : int = 0; var localWeightLoaded : Number = 0; var localItemsTotal : int = 0; var localItemsLoaded : int = 0; var localBytesLoaded : int = 0; var localBytesTotal : int = 0; var localBytesTotalCurrent : int = 0; var item : LoadingItem; var theseItems : Array = []; for each (var key: * in keys){ item = get(key); if (!item) continue; localItemsTotal ++; localWeightTotal += item.weight; if (item.status == LoadingItem.STATUS_STARTED || item.status == LoadingItem.STATUS_FINISHED || item.status == LoadingItem.STATUS_STOPPED){ localBytesLoaded += item._bytesLoaded; localBytesTotalCurrent += item._bytesTotal; localWeightLoaded += (item._bytesLoaded / item._bytesTotal) * item.weight; if(item.status == LoadingItem.STATUS_FINISHED) { localItemsLoaded ++; } itemsStarted ++; } } // only set bytes total if all items have begun loading if (itemsStarted != localItemsTotal){ localBytesTotal = Number.POSITIVE_INFINITY; }else{ localBytesTotal = localBytesTotalCurrent; } localWeightPercent = localWeightLoaded / localWeightTotal; if(localWeightTotal == 0) localWeightPercent = 0; var e : BulkProgressEvent = new BulkProgressEvent(PROGRESS); e.setInfo(localBytesLoaded, localBytesTotal, localBytesTotal, localItemsLoaded, localItemsTotal, localWeightPercent); return e; } /** The number of simultaneous connections to use. This is per <code>BulkLoader</code> instance. * @return The number of connections used. * @see #start() */ public function get numConnections() : int { return _numConnections; } /** Returns an object where the urls are the keys(as strings) and the loaded contents are the value for that key. * Each value is typed as * an the client must check for the right typing. * @return An object hashed by urls, where values are the downloaded content type of each url. The user mut cast as apropriate. */ public function get contents() : Object { return _contents; } /** Returns a copy of all <code>LoadingItem</code> in this intance. This function makes a copy to avoid * users messing with _items (removing items and so forth). Those can be done through functions in BulkLoader. * @return A array that is a shallow copy of all items in the BulkLoader. */ public function get items() : Array { return _items.slice(); } /** * The name by which this loader instance can be identified. * This property is used so you can get a reference to this instance from other classes in your code without having to save and pass it yourself, throught the static method BulkLoader.getLoader(name) .<p/> * Each name should be unique, as instantiating a BulkLoader with a name already taken will throw an error. * @see #getLoaders() */ public function get name() : String { return _name; } /** * The ratio (0->1) of items to load / items total. * This number is always reliable. **/ public function get loadedRatio() : Number { return _loadedRatio; } /** Total number of items to load.*/ public function get itemsTotal() : int { return items.length; } /** * Number of items alrealdy loaded. * Failed or canceled items are not taken into consideration */ public function get itemsLoaded() : int { return _itemsLoaded; } public function set itemsLoaded(value:int) : void { _itemsLoaded = value; } /** The sum of weights in all items to load. * Each item's weight default to 1 */ public function get totalWeight() : int { return _totalWeight; } /** The total bytes to load. * If the number of items to load is larger than the number of simultaneous connections, bytesTotal will be 0 untill all connections are opened and the number of bytes for all items is known. * @see #bytesTotalCurrent */ public function get bytesTotal() : int { return _bytesTotal; } /** The sum of all bytesLoaded for each item. */ public function get bytesLoaded() : int { return _bytesLoaded; } /** The sum of all bytes loaded so far. * If itemsTotal is less than the number of connections, this will be the same as bytesTotal. Else, bytesTotalCurrent will be available as each loading is started. * @see #bytesTotal */ public function get bytesTotalCurrent() : int { return _bytesTotalCurrent; } /** The percentage (0->1) of bytes loaded. * Until all connections are opened this number is not reliable . If you are downloading more items than the number of simultaneous connections, use loadedRatio or weightPercent instead. * @see #loadedRatio * @see #weightPercent */ public function get percentLoaded() : Number { return _percentLoaded; } /** The weighted percent of items loaded(0->1). * This always returns a reliable value. */ public function get weightPercent() : Number { return _weightPercent; } /** A boolean indicating if the instace has started and has not finished loading all items */ public function get isRunning() : Boolean { return _isRunning; } public function get isFinished() : Boolean{ return _isFinished; } /** Returns the highest priority for all items in this BulkLoader instance. This will check all items, * including cancelled items and already downloaded items. */ public function get highestPriority() : int{ var highest : int = int.MIN_VALUE; for each (var item : LoadingItem in _items){ if (item.priority > highest) highest = item.priority; } return highest; } /** The function to be used in logging. By default it's the same as the global function <code>trace</code>. The log function signature is: * <pre> * public function myLogFunction(msg : String) : void{} * </pre> */ public function get logFunction() : Function { return _logFunction; } /** Determines if an autmatic id created from the file name. If true, when adding and item and NOT specifing an "id" props * for its properties, an id with the file name will be created altomatically. * @example Automatic id:<listing version="3.0"> * bulkLoader.allowsAutoIDFromFileName = false; * var item : LoadingItem = bulkLoader.add("background.jpg") * trace(item.id) // outputs: null * // now if allowsAutoIDFromFileName is set to true: * bulkLoader.allowsAutoIDFromFileName = true; * var item : LoadingItem = bulkLoader.add("background.jpg") * trace(item.id) // outputs: background * // if you pass an id on the props, it will take precedence over auto created ids: * bulkLoader.allowsAutoIDFromFileName = id; * var item : LoadingItem = bulkLoader.add("background.jpg", {id:"small-bg"}) * trace(item.id) // outputs: small-bg * </listing> */ public function get allowsAutoIDFromFileName() : Boolean { return _allowsAutoIDFromFileName; } public function set allowsAutoIDFromFileName(value:Boolean) : void { _allowsAutoIDFromFileName = value; } /** Returns items that haven't been fully loaded. * @return An array with all LoadingItems not fully loaded. */ public function getNotLoadedItems () : Array{ return _items.filter(function(i : LoadingItem, ...rest):Boolean{ return i.status != LoadingItem.STATUS_FINISHED; }); } /* Returns the speed in kilobytes / second for all loadings */ public function get speed() : Number{ // TODO: test get speed var timeElapsed : int = getTimer() - _lastSpeedCheck; var bytesDelta : int = (bytesLoaded - _lastBytesCheck) / 1024; var speed : int = bytesDelta / (timeElapsed/1000); _lastSpeedCheck = timeElapsed; _lastBytesCheck = bytesLoaded; return speed; } /** The function to be called for loggin. The loggin function should receive one parameter, the string to be logged. The <code>logFunction</code> defaults to flash's regular trace function. You can use the logFunction to route traces to an alternative place (such as a textfield or some text component in your application). If the <code>logFunction</code> is set to something else that the global <code>trace</code> function, nothing will be traced. A custom <code>logFunction</code> messages will still be filtered by the <code>logLevel</code> setting. * @param func The function to be used on loggin. */ public function set logFunction(func:Function) : void { _logFunction = func; } /** The id of this bulkLoader instance */ public function get id() : int { return _id; } /** The object, used as a hashed to substitute variables specified on the url used in <code>add</code>. * Allows to keep common part of urls on one spot only. If later the server path changes, you can * change only the stringSubstitutions object to update all items. * This has to be set before the <code>add</code> calls are made, or else strings won't be expanded. * @example Variable sustitution:<listing version="3.0"> * // All webservices will be at a common path: * bulkLoader.stringSubstitutions = { * "web_services": "http://somesite.com/webservices" * } * bulkLoader.add("{web_services}/getTime"); * // this will be expanded to http://somesite.com/webservices/getTime * * </listing> * The format expected is {var_name} , where var_name is composed of alphanumeric characters and the underscore. Other characters (., *, [, ], etc) won't work, as they'll clash with the regex used in matching. * @see #add */ public function get stringSubstitutions() : Object { return _stringSubstitutions; } public function set stringSubstitutions(value:Object) : void { _stringSubstitutions = value; } /** Updates the priority of item identified by key with a new value, the queue will be re resorted right away. * Changing priorities will not stop currently opened connections. * @param key The url request, url as a string or a id from which the asset was loaded. * @param new The priority to assign to the item. * @return The <code>true</code> if an item with that key was found, <code>false</code> othersiwe. */ public function changeItemPriority(key : String, newPriority : int) : Boolean{ var item : LoadingItem = get(key); if (!item){ return false; } item._priority = newPriority; sortItemsByPriority(); return true; } /** Updates the priority queue */ public function sortItemsByPriority() : void{ // addedTime might not be precise, if subsequent add() calls are whithin getTimer precision // range, so we use _additionIndex _items.sortOn(["priority", "_additionIndex"], [Array.NUMERIC | Array.DESCENDING, Array.NUMERIC ]); } /* ============================================================================== */ /* = Acessing content functions = */ /* ============================================================================== */ /** @private Helper functions to get loaded content. All helpers will be casted to the specific types. If a cast fails it will throw an error. * */ public function _getContentAsType(key : *, type : Class, clearMemory : Boolean = false) : *{ if(!_name){ throw new Error("[BulkLoader] Cannot use an instance that has been cleared from memory (.clear())"); } var item : LoadingItem = get(key); if(!item){ return null; } try{ if (item._isLoaded || item.isStreamable() && item.status == LoadingItem.STATUS_STARTED) { var res : * = item.content as type; if (res == null){ throw new Error("bad cast"); } if(clearMemory){ remove(key); // this needs to try to load a next item, because this might get called inside a // complete handler and if it's on the last item on the open connections, it might stale if (!_isPaused){ _loadNext(); } } return res; } }catch(e : Error){ log("Failed to get content with url: '"+ key + "'as type:", type, LOG_ERRORS); } return null; } /** Returns an untyped object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The content retrived from that url */ public function getContent(key : String, clearMemory : Boolean = false) : *{ return _getContentAsType(key, Object, clearMemory); } /** Returns an XML object with the downloaded asset for the given key. * @param key String OR URLRequest The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a XML object. Returns null if the cast fails. */ public function getXML(key : *, clearMemory : Boolean = false) : XML{ return XML(_getContentAsType(key, XML, clearMemory)); } /** Returns a String object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a String object. Returns null if the cast fails. */ public function getText(key : *, clearMemory : Boolean = false) : String{ return String(_getContentAsType(key, String, clearMemory)); } /** Returns a Sound object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory Boolean If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a Sound object. Returns null if the cast fails. */ public function getSound(key : *, clearMemory : Boolean = false) : Sound{ return Sound(_getContentAsType(key, Sound,clearMemory)); } /** Returns a Bitmap object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a Bitmap object. Returns null if the cast fails. */ public function getBitmap(key : String, clearMemory : Boolean = false) : Bitmap{ return Bitmap(_getContentAsType(key, Bitmap, clearMemory) ); } /** Returns a Loader object with the downloaded asset for the given key. * Had to pick this ugly name since <code>getLoader</code> is currently used for getting a BulkLoader instance. * This is useful if you are loading images but do not have a crossdomain to grant you permissions. In this case, while you * will still find restrictions to how you can use that loaded asset (no BitmapData for it, for example), you still can use it as content. * * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a Loader object. Returns null if the cast fails. */ public function getDisplayObjectLoader(key : String, clearMemory : Boolean = false) : Loader{ return Loader(_getContentAsType(key, Loader, clearMemory)); } /** Returns a <code>MovieClip</code> object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a MovieClip object. Returns null if the cast fails. */ public function getMovieClip(key : String, clearMemory : Boolean = false) : MovieClip{ return MovieClip(_getContentAsType(key, MovieClip, clearMemory)); } /** Returns a <code>Sprite</code> object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a Sprite object. Returns null if the cast fails. */ public function getSprite(key : String, clearMemory : Boolean = false) : Sprite{ return Sprite(_getContentAsType(key, Sprite, clearMemory)); } /** Returns a <code>AVM1Movie</code> object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a AVM1Movie object. Returns null if the cast fails. */ public function getAVM1Movie(key : String, clearMemory : Boolean = false) : AVM1Movie{ return AVM1Movie(_getContentAsType(key, AVM1Movie, clearMemory)); } /** Returns a <code>NetStream</code> object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a NetStream object. Returns null if the cast fails. */ public function getNetStream(key : String, clearMemory : Boolean = false) : NetStream{ return NetStream(_getContentAsType(key, NetStream, clearMemory)); } /** Returns a <code>Object</code> with meta data information for a given <code>NetStream</code> key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The meta data object downloaded with this NetStream. Returns null if the given key does not resolve to a NetStream. */ public function getNetStreamMetaData(key : String, clearMemory : Boolean = false) : Object{ var netStream : NetStream = getNetStream(key, clearMemory); return (Boolean(netStream) ? (get(key) as Object).metaData : null); } /** Returns an BitmapData object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails. Does not clone the original bitmap data from the bitmap asset. * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a BitmapData object. Returns null if the cast fails. */ public function getBitmapData(key : *, clearMemory : Boolean = false) : BitmapData{ try{ return getBitmap(key, clearMemory).bitmapData; }catch (e : Error){ log("Failed to get bitmapData with url:", key, LOG_ERRORS); } return null; } /** Returns an ByteArray object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails. * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a ByteArray object. Returns null if the cast fails. */ public function getBinary(key : *, clearMemory : Boolean = false) :ByteArray{ return ByteArray(_getContentAsType(key, ByteArray, clearMemory)); } /** Returns a object decoded from a string, by a given encoding function. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the encoding fails * @param clearMemory If this <code>BulkProgressEvent</code> instance should clear all references to the content of this asset. * @param encodingFunction A <code>Function</code> object to be passed the string and be encoded into an object. * @return The content retrived from that url encoded by encodingFunction */ public function getSerializedData(key : *, clearMemory : Boolean = false, encodingFunction : Function = null) : *{ try{ var raw : * = _getContentAsType(key, Object, clearMemory); var parsed : * = encodingFunction.apply(null, [raw]); return parsed; }catch (e : Error){ log("Failed to parse key:", key, "with encodingFunction:" + encodingFunction, LOG_ERRORS); } return null; } /** Gets a class definition from a fully qualified path. Note that this will only work if you've loaded the swf with the same LoaderContext of the other swf (using "context" prop on "add"). Else you should use <code><imageItem>.getClassByName</code> instead. @param className The fully qualified class name as a string. @return The <code>Class</code> object with that name or null of not found. */ // public function getClassByName(className : String) : Class{ // try{ // return getDefinitionByName(className) as Class; // }catch(e : Error){ // // } // return null; // } /** Gets the http status code for the loading item identified by key. * @param key The url request, url as a string or a id from which the asset was loaded. * @return The Http status as an integer. If no item is found returns -1. If the http status cannot be determined but the item was found, returns 0. */ public function getHttpStatus(key : *) : int{ var item : LoadingItem = get(key); if(item){ return item.httpStatus; } return -1; } /** @private */ public function _isAllDoneP() : Boolean{ return _items.every(function(item : LoadingItem, ...rest):Boolean{ return item._isLoaded; }); } /** @private */ public function _onAllLoaded() : void { if(_isFinished){ return; } var eComplete : BulkProgressEvent = new BulkProgressEvent(COMPLETE); eComplete.setInfo(bytesLoaded, bytesTotal, bytesTotalCurrent, _itemsLoaded, itemsTotal, weightPercent); var eProgress : BulkProgressEvent = new BulkProgressEvent(PROGRESS); eProgress.setInfo(bytesLoaded, bytesTotal, bytesTotalCurrent, _itemsLoaded, itemsTotal, weightPercent); _isRunning = false; _endTIme = getTimer(); totalTime = BulkLoader.truncateNumber((_endTIme - _startTime) /1000); _updateStats(); _connections = {}; getStats(); _isFinished = true; log("Finished all", LOG_INFO); dispatchEvent(eProgress); dispatchEvent(eComplete); } /** If the <code>logLevel</code> if lower that <code>LOG_ERRORS</code>(3). Outputs a host of statistics about the loading operation * @return A formated string with loading statistics. * @see #LOG_ERRORS * @see #logLevel */ public function getStats() : String{ var stats : Array = []; stats.push("\n************************************"); stats.push("All items loaded(" + itemsTotal + ")"); stats.push("Total time(s): " + totalTime); stats.push("Average latency(s): " + truncateNumber(avgLatency)); stats.push("Average speed(kb/s): " + truncateNumber(speedAvg)); stats.push("Median speed(kb/s): " + truncateNumber(_speedTotal)); stats.push("KiloBytes total: " + truncateNumber(bytesTotal/1024)); var itemsInfo : Array = _items.map(function(item :LoadingItem, ...rest) : String{ return "\t" + item.getStats(); }) stats.push(itemsInfo.join("\n")) stats.push("************************************"); var statsString : String = stats.join("\n"); log(statsString, LOG_VERBOSE); return statsString; } /** @private * Outputs with a trace operation a message. * Depending on <code>logLevel</code> diferrent levels of messages will be outputed: * <ul>logLevel = LOG_VERBOSE (0) : Everything is logged. Useful for debugging. * <ul>logLevel = LOG_INFO (1) : Every load operation is logged (loading finished, started, statistics). * <ul>logLevel = LOG_ERRORS (3) : Only loading errors and callback erros will be traced. Useful in production. * @see #logLevel * @see #LOG_ERRORS * @see #LOG_INFO * @see #LOG_VERBOSE */ public function log(...msg) : void{ var messageLevel : int = isNaN(msg[msg.length -1] ) ? 3 : int(msg.pop()); if (messageLevel >= logLevel ){ _logFunction("[BulkLoader] " + msg.join(" ")); } } /** Used to fetch an item with a given key. The returned <code>LoadingItem</code> can be used to attach event listeners for the individual items (<code>Event.COMPLETE, ProgressEvent.PROGRESS, Event.START</code>). * @param key A url (as a string or urlrequest) or an id to fetch * @return The corresponding <code>LoadingItem</code> or null if one isn't found. */ public function get(key : *) : LoadingItem{ if(!key) return null; if(key is LoadingItem) return key; for each (var item : LoadingItem in _items){ if(item._id == key || item._parsedURL.rawString == key || item.url == key || (key is URLRequest && item.url.url == key.url) ){ return item; } } return null; } /** This will delete this item from memory. It's content will be inaccessible after that. * @param key A url (as a string or urlrequest) or an id to fetch * @param internalCall If <code>remove</code> has been called internally. End user code should ignore this. * @return <code>True</code> if an item with that key has been removed, and <code>false</code> othersiwe. * */ public function remove(key : *, internalCall : Boolean = false) : Boolean{ try{ var item : LoadingItem = get(key); if(!item) { return false; } _removeFromItems(item); _removeFromConnections(item); item.destroy(); delete _contents[item.url.url]; // this has to be checked, else a removeAll will trigger events for completion if (internalCall){ return true; } item = null; // checks is removing this item we are done? _onProgress(); var allDone : Boolean = _isAllDoneP(); if(allDone) { _onAllLoaded(); } return true; }catch(e : Error){ log("Error while removing item from key:" + key, e.getStackTrace(), LOG_ERRORS); } return false; } /** Deletes all loading and loaded objects. This will stop all connections and delete from the cache all of it's items (no content will be accessible if <code>removeAll</code> is executed). */ public function removeAll() : void{ for each (var item : LoadingItem in _items.slice()){ remove(item, true); } _items = []; _connections = {}; _contents = new Dictionary(); _percentLoaded = _weightPercent = _loadedRatio = 0; } /** Removes this instance from the static Register of instances. After a clear method has been called for a given instance, nothing else should work */ public function clear() : void{ removeAll(); delete _allLoaders[name]; _name = null; } /** Deletes all content from all instances of <code>BulkLoader</code> class. This will stop any pending loading operations as well as free memory. * @see #removeAll() */ public static function removeAllLoaders() : void{ for each (var atLoader : BulkLoader in _allLoaders){ atLoader.removeAll(); atLoader.clear(); atLoader = null; } _allLoaders = {}; } /** Removes all items that have been stopped. * After removing, it will try to restart loading if there are still items to load. * @ return <code>True</code> if any items have been removed, <code>false</code> otherwise. */ public function removePausedItems() : Boolean{ var stoppedLoads : Array = _items.filter(function (item : LoadingItem, ...rest) : Boolean{ return (item.status == LoadingItem.STATUS_STOPPED); }); stoppedLoads.forEach(function(item : LoadingItem, ...rest):void{ remove(item); }); _loadNext(); return stoppedLoads.length > 0; } /** Removes all items that have not succesfully loaded. * After removing, it will try to restart loading if there are still items to load. * @ return In any items have been removed. */ public function removeFailedItems(): int{ var numCleared : int = 0; var badItems : Array = _items.filter(function (item : LoadingItem, ...rest) : Boolean{ return (item.status == LoadingItem.STATUS_ERROR); }); numCleared = badItems.length; badItems.forEach(function (item : LoadingItem, ...rest) : void{ remove(item); }); _loadNext(); return numCleared; } /** Get all items that have an error (either IOError or SecurityError). * @ return An array with the LoadingItem objects that have failed. */ public function getFailedItems() : Array{ return _items.filter(function (item : LoadingItem, ...rest) : Boolean{ return (item.status == LoadingItem.STATUS_ERROR); }); } /** Stop loading the item identified by <code>key</code>. This will not remove the item from the <code>BulkLoader</code>. Note that progress notification will jump around, as the stopped item will still count as something to load, but it's byte count will be 0. * @param key The key (url as a string, url as a <code>URLRequest</code> or an id as a <code>String</code>). * @param loadsNext If it should start loading the next item. * @return A <code>Boolean</code> indicating if the object has been stopped. */ public function pause(key : *, loadsNext : Boolean = false) : Boolean{ var item : LoadingItem = get(key); if(!item) { return false; } if (item.status != LoadingItem.STATUS_FINISHED) { item.stop(); } log("STOPPED ITEM:" , item, LOG_INFO) var result : Boolean = _removeFromConnections(item); if(loadsNext){ _loadNext(); } return result; } /** Stops loading all items of this <code>BulkLoader</code> instance. This does not clear or remove items from the qeue. */ public function pauseAll() : void{ for each(var item : LoadingItem in _items){ pause(item); } _isRunning = false; _isPaused = true; log("Stopping all items", LOG_INFO); } /** Stops loading all items from all <code>BulkLoader</code> instances. * @see #stopAllItems() * @see #stopItem() */ public static function pauseAllLoaders() : void{ for each (var atLoader : BulkLoader in _allLoaders){ atLoader.pauseAll(); } } /** Resumes loading of the item. Depending on the environment the player is running, resumed items will be able to use partialy downloaded content. * @param key The url request, url as a string or a id from which the asset was loaded. * @return If a item with that key has resumed loading. */ public function resume(key : *) : Boolean{ var item : LoadingItem = key is LoadingItem ? key : get(key); _isPaused = false; if(item && item.status == LoadingItem.STATUS_STOPPED ){ item.status = null; _loadNext(); return true; } return false; } /** Resumes all loading operations that were stopped. * @return <code>True</code> if any item was stopped and resumed, false otherwise */ public function resumeAll() : Boolean{ log("Resuming all items", LOG_VERBOSE); var affected : Boolean = false; _items.forEach(function(item : LoadingItem, ...rest):void{ if(item.status == LoadingItem.STATUS_STOPPED){ resume(item); affected = true; } }); _loadNext(); return affected; } /** @private * Utility function to truncate a number to the given number of decimal places. * @description * Number is truncated using the <code>Math.round</code> function. * * @param The number to truncate * @param The number of decimals place to preserve. * @return The truncated number. */ public static function truncateNumber(raw : Number, decimals :int =2) : Number { var power : int = Math.pow(10, decimals); return Math.round(raw * ( power )) / power; } /** * Returns a string identifing this loaded instace. */ override public function toString() : String{ return "[BulkLoader] name:"+ name + ", itemsTotal: " + itemsTotal + ", itemsLoaded: " + _itemsLoaded; } /** @private * Simply tries to guess the type from the file extension. Will remove query strings on urls. * If no extension is found, will default to type "text" and will trace a warning (must have LOG_WARNINGS or lower set). */ public static function guessType(urlAsString : String) : String{ // no type is given, try to guess from the url var searchString : String = urlAsString.indexOf("?") > -1 ? urlAsString.substring(0, urlAsString.indexOf("?")) : urlAsString; // split on "/" as an url can have a dot as part of a directory name var finalPart : String = searchString.substring(searchString.lastIndexOf("/"));; var extension : String = finalPart.substring(finalPart.lastIndexOf(".") + 1).toLowerCase(); var type : String; if(!Boolean(extension) ){ extension = BulkLoader.TYPE_TEXT; } if(extension == BulkLoader.TYPE_IMAGE || BulkLoader.IMAGE_EXTENSIONS.indexOf(extension) > -1){ type = BulkLoader.TYPE_IMAGE; }else if (extension == BulkLoader.TYPE_SOUND ||BulkLoader.SOUND_EXTENSIONS.indexOf(extension) > -1){ type = BulkLoader.TYPE_SOUND; }else if (extension == BulkLoader.TYPE_VIDEO ||BulkLoader.VIDEO_EXTENSIONS.indexOf(extension) > -1){ type = BulkLoader.TYPE_VIDEO; }else if (extension == BulkLoader.TYPE_XML ||BulkLoader.XML_EXTENSIONS.indexOf(extension) > -1){ type = BulkLoader.TYPE_XML; }else if (extension == BulkLoader.TYPE_MOVIECLIP ||BulkLoader.MOVIECLIP_EXTENSIONS.indexOf(extension) > -1){ type = BulkLoader.TYPE_MOVIECLIP; }else{ // is this on a new extension? for(var checkType : String in _customTypesExtensions){ for each(var checkExt : String in _customTypesExtensions[checkType]){ if (checkExt == extension){ type = checkType; break; } if(type) break; } } if (!type) type = BulkLoader.TYPE_TEXT; } return type; } /** @private */ public static function substituteURLString(raw : String, substitutions : Object) : String{ if(!substitutions) return raw; var subRegex : RegExp = /(?P<var_name>\{\s*[^\}]*\})/g; var result : Object = subRegex.exec(raw); var var_name : String = result? result.var_name : null; var matches : Array = []; var numRuns : int = 0; while(Boolean(result ) && Boolean(result.var_name)){ if(result.var_name){ var_name = result.var_name; var_name = var_name.replace("{", ""); var_name = var_name.replace("}", ""); var_name = var_name.replace( /\s*/g, ""); } matches.push({ start : result.index, end: result.index + result.var_name.length , changeTo: substitutions[var_name] }); // be paranoid so we don't hang the player if the matching goes cockos numRuns ++; if(numRuns > 400) { break; } result = subRegex.exec(raw); var_name = result? result.var_name : null; } if (matches.length == 0){ return raw;}; var buffer : Array = []; var lastMatch : Object, match : Object; // beggininf os string, if it doesn't start with a substitition var previous : String = raw.substr(0, matches[0].start); var subs : String; for each(match in matches){ // finds out the previous string part and the next substitition if (lastMatch){ previous = raw.substring(lastMatch.end , match.start); } buffer.push(previous); buffer.push(match.changeTo); lastMatch = match; } // buffer the tail of the string: text after the last substitution buffer.push(raw.substring(match.end)); return buffer.join(""); } /** @private */ public static function getFileName(text : String) : String{ if (text.lastIndexOf("/") == text.length -1){ return getFileName(text.substring(0, text.length-1)); } var startAt : int = text.lastIndexOf("/") + 1; //if (startAt == -1) startAt = 0; var croppedString : String = text.substring(startAt); var lastIndex :int = croppedString.indexOf("."); if (lastIndex == -1 ){ if (croppedString.indexOf("?") > -1){ lastIndex = croppedString.indexOf("?") ; }else{ lastIndex = croppedString.length; } } var finalPath : String = croppedString.substring(0, lastIndex); return finalPath; } /** @private */ public static function __debug_print_loaders() : void{ var theNames : Array = [] for each(var instNames : String in BulkLoader._allLoaders){ theNames.push(instNames); } theNames.sort(); trace("All loaders"); theNames.forEach(function(item:*, ...rest):void{trace("\t", item)}) trace("==========="); } /** @private */ public static function __debug_print_num_loaders() : void{ var num : int = 0; for each(var instNames : String in BulkLoader._allLoaders){ num ++; } trace("BulkLoader has ", num, "instances"); } /** @private */ public static function __debug_printStackTrace() : void{ try{ throw new Error("stack trace"); }catch(e : Error){ trace(e.getStackTrace()); } } } }
/**************************************************************** TITLE: Constants AUTHOR: Julio Lopez LAST UPDATED: 2010-03-30 DESCRIPTION: Static object that will contain most of the constants required in the program. ****************************************************************/ package ca.juliolopez.variables { public final class Constants extends Object { /******************************* Properties ********************************/ /* Constants: ****************************************************************/ // Default Asset Paths public static const SWF_PATH = "./assets/swfs/"; // Path to swf assets public static const XML_PATH = "./assets/xml/"; // Path to xml assets public static const JPG_PATH = "./assets/jpgs/"; // Path to jpg assets public static const GIF_PATH = "./assets/gifs/"; // Path to gif assets public static const PNG_PATH = "./assets/pngs/"; // Path to png assets public static const VID_PATH = "assets/video/"; // Path to video assets public static const SND_PATH = "./assets/audio/"; // Path to audio assets public static const SKN_PATH = "./assets/skins/"; // Path to skin assets public static const PDF_PATH = "./assets/pdfs/"; // Path to PDF assets // Default paths to home and modules public static const HOME_PATH = "./assets/swfs/home.swf"; // Path to home swf public static const MOD_PATH = "./assets/swfs/main.swf"; // Path to default module swf public static const MOD_XML_PATH = "./assets/xml/main.xml"; // Path to default module xml /******************************** Methods **********************************/ /* Constructor: **************************************************************/ public function Constants() { } } }
package com.playata.application.data.constants { import com.playata.framework.core.TypedObject; import com.playata.framework.data.constants.ConstantsData; public class CItemSetTemplateBonus extends ConstantsData { public static const ID_NAME:String = "bonus"; public function CItemSetTemplateBonus(param1:TypedObject) { super(param1); } public function get bonus() : int { return getInt("bonus"); } public function get type() : int { return getInt("type"); } public function get value() : Number { return getNumber("value"); } } }
package serverProto.user { import com.netease.protobuf.Message; import com.netease.protobuf.fieldDescriptors.RepeatedFieldDescriptor$TYPE_SINT32; import com.netease.protobuf.WireType; import com.netease.protobuf.WritingBuffer; import com.netease.protobuf.WriteUtils; import flash.utils.IDataInput; import com.netease.protobuf.ReadUtils; public final class ProtoNinjaImportantOperate extends Message { public static const NINJA_CARD_ID:RepeatedFieldDescriptor$TYPE_SINT32 = new RepeatedFieldDescriptor$TYPE_SINT32("serverProto.user.ProtoNinjaImportantOperate.ninja_card_id","ninjaCardId",1 << 3 | WireType.VARINT); public static const STRENGTH_NINJA_ID:RepeatedFieldDescriptor$TYPE_SINT32 = new RepeatedFieldDescriptor$TYPE_SINT32("serverProto.user.ProtoNinjaImportantOperate.strength_ninja_id","strengthNinjaId",2 << 3 | WireType.VARINT); public static const AWAKE_NINJA_ID:RepeatedFieldDescriptor$TYPE_SINT32 = new RepeatedFieldDescriptor$TYPE_SINT32("serverProto.user.ProtoNinjaImportantOperate.awake_ninja_id","awakeNinjaId",3 << 3 | WireType.VARINT); public static const UPGRADE_STAR_NINJA_ID:RepeatedFieldDescriptor$TYPE_SINT32 = new RepeatedFieldDescriptor$TYPE_SINT32("serverProto.user.ProtoNinjaImportantOperate.upgrade_star_ninja_id","upgradeStarNinjaId",4 << 3 | WireType.VARINT); [ArrayElementType("int")] public var ninjaCardId:Array; [ArrayElementType("int")] public var strengthNinjaId:Array; [ArrayElementType("int")] public var awakeNinjaId:Array; [ArrayElementType("int")] public var upgradeStarNinjaId:Array; public function ProtoNinjaImportantOperate() { this.ninjaCardId = []; this.strengthNinjaId = []; this.awakeNinjaId = []; this.upgradeStarNinjaId = []; super(); } override final function writeToBuffer(param1:WritingBuffer) : void { var _loc6_:* = undefined; var _loc2_:uint = 0; while(_loc2_ < this.ninjaCardId.length) { WriteUtils.writeTag(param1,WireType.VARINT,1); WriteUtils.write$TYPE_SINT32(param1,this.ninjaCardId[_loc2_]); _loc2_++; } var _loc3_:uint = 0; while(_loc3_ < this.strengthNinjaId.length) { WriteUtils.writeTag(param1,WireType.VARINT,2); WriteUtils.write$TYPE_SINT32(param1,this.strengthNinjaId[_loc3_]); _loc3_++; } var _loc4_:uint = 0; while(_loc4_ < this.awakeNinjaId.length) { WriteUtils.writeTag(param1,WireType.VARINT,3); WriteUtils.write$TYPE_SINT32(param1,this.awakeNinjaId[_loc4_]); _loc4_++; } var _loc5_:uint = 0; while(_loc5_ < this.upgradeStarNinjaId.length) { WriteUtils.writeTag(param1,WireType.VARINT,4); WriteUtils.write$TYPE_SINT32(param1,this.upgradeStarNinjaId[_loc5_]); _loc5_++; } for(_loc6_ in this) { super.writeUnknown(param1,_loc6_); } } 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"); } } }
/* Feathers Copyright 2012-2014 Joshua Tynjala. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.controls { import feathers.controls.supportClasses.IScreenNavigatorItem; import starling.display.DisplayObject; /** * Data for an individual screen that will be displayed by a * <code>StackScreenNavigator</code> component. * * <p>The following example creates a new * <code>StackScreenNavigatorItem</code> using the * <code>SettingsScreen</code> class to instantiate the screen instance. * When the screen is shown, its <code>settings</code> property will be set. * When the screen instance dispatches the * <code>SettingsScreen.SHOW_ADVANCED_SETTINGS</code> event, the * <code>StackScreenNavigator</code> will push a screen with the ID * <code>"advancedSettings"</code> onto its stack. When the screen instance * dispatches <code>Event.COMPLETE</code>, the <code>StackScreenNavigator</code> * will pop the screen instance from its stack.</p> * * <listing version="3.0"> * var settingsData:Object = { volume: 0.8, difficulty: "hard" }; * var item:StackScreenNavigatorItem = new StackScreenNavigatorItem( SettingsScreen ); * item.properties.settings = settingsData; * item.setScreenIDForPushEvent( SettingsScreen.SHOW_ADVANCED_SETTINGS, "advancedSettings" ); * item.addPopEvent( Event.COMPLETE ); * navigator.addScreen( "settings", item );</listing> * * @see http://wiki.starling-framework.org/feathers/stack-screen-navigator * @see feathers.controls.StackScreenNavigator */ public class StackScreenNavigatorItem implements IScreenNavigatorItem { /** * Constructor. * * @param screen The screen to display. Must be a <code>Class</code>, <code>Function</code>, or Starling display object. * @param pushEvents The screen navigator push a new screen when these events are dispatched. * @param popEvent An event that pops the screen from the top of the stack. * @param properties A set of key-value pairs to pass to the screen when it is shown. */ public function StackScreenNavigatorItem(screen:Object, pushEvents:Object = null, popEvent:String = null, properties:Object = null) { this._screen = screen; this._pushEvents = pushEvents ? pushEvents : {}; if(popEvent) { this.addPopEvent(popEvent); } this._properties = properties ? properties : {}; } /** * @private */ protected var _screen:Object; /** * The screen to be displayed by the <code>ScreenNavigator</code>. It * may be one of several possible types: * * <ul> * <li>a <code>Class</code> that may be instantiated to create a <code>DisplayObject</code></li> * <li>a <code>Function</code> that returns a <code>DisplayObject</code></li> * <li>a Starling <code>DisplayObject</code> that is already instantiated</li> * </ul> * * <p>If the screen is a <code>Class</code> or a <code>Function</code>, * a new instance of the screen will be instantiated every time that it * is shown by the <code>ScreenNavigator</code>. The screen's state * will not be saved automatically. The screen's state may be saved in * <code>properties</code>, if needed.</p> * * <p>If the screen is a <code>DisplayObject</code>, the same instance * will be reused every time that it is shown by the * <code>ScreenNavigator</code> When the screen is shown again, its * state will remain the same as when it was previously hidden. However, * the screen will also be kept in memory even when it isn't visible, * limiting the resources that are available for other screens.</p> * * @default null */ public function get screen():Object { return this._screen; } /** * @private */ public function set screen(value:Object):void { this._screen = value; } /** * @private */ protected var _pushEvents:Object; /** * A set of key-value pairs representing actions that should be * triggered when events are dispatched by the screen when it is shown. * A pair's key is the event type to listen for (or the property name of * an <code>ISignal</code> instance), and a pair's value is one of two * possible types. When this event is dispatched, and a pair's value * is a <code>String</code>, the <code>StackScreenNavigator</code> will * show another screen with an ID equal to the string value. When this * event is dispatched, and the pair's value is a <code>Function</code>, * the function will be called as if it were a listener for the event. * * @see #setFunctionForPushEvent() * @see #setScreenIDForPushEvent() */ public function get pushEvents():Object { return this._pushEvents; } /** * @private */ public function set pushEvents(value:Object):void { if(!value) { value = {}; } this._pushEvents = value; } /** * @private */ protected var _popEvents:Vector.<String>; /** * A list of events that will cause the screen navigator to pop this * screen off the top of the stack. * * @see #addPopEvent() * @see #removePopEvent() */ public function get popEvents():Vector.<String> { return this._popEvents; } /** * @private */ public function set popEvents(value:Vector.<String>):void { if(!value) { value = new <String>[]; } this._popEvents = value; } /** * @private */ protected var _popToRootEvents:Vector.<String>; /** * A list of events that will cause the screen navigator to clear its * stack and show the first screen added to the stack. * * @see #addPopToRootEvent() * @see #removePopToRootEvent() */ public function get popToRootEvents():Vector.<String> { return this._popToRootEvents; } /** * @private */ public function set popToRootEvents(value:Vector.<String>):void { this._popToRootEvents = value; } /** * @private */ protected var _properties:Object; /** * A set of key-value pairs representing properties to be set on the * screen when it is shown. A pair's key is the name of the screen's * property, and a pair's value is the value to be passed to the * screen's property. */ public function get properties():Object { return this._properties; } /** * @private */ public function set properties(value:Object):void { if(!value) { value = {}; } this._properties = value; } /** * @inheritDoc */ public function get canDispose():Boolean { return !(this._screen is DisplayObject); } /** * Specifies a function to call when an event is dispatched by the * screen. * * <p>If the screen is currently being displayed by a * <code>StackScreenNavigator</code>, and you call * <code>setFunctionForPushEvent()</code> on the <code>StackScreenNavigatorItem</code>, * the <code>StackScreenNavigator</code> won't listen for the event * until the next time that the screen is shown.</p> * * @see #setScreenIDForPushEvent() * @see #clearEvent() * @see #events */ public function setFunctionForPushEvent(eventType:String, action:Function):void { this._pushEvents[eventType] = action; } /** * Specifies another screen to push on the stack when an event is * dispatched by this screen. The other screen should be specified by * its ID that was registered with a call to <code>addScreen()</code> on * the <code>StackScreenNavigator</code>. * * <p>If the screen is currently being displayed by a * <code>StackScreenNavigator</code>, and you call * <code>setScreenIDForPushEvent()</code> on the <code>StackScreenNavigatorItem</code>, * the <code>StackScreenNavigator</code> won't listen for the event * until the next time that the screen is shown.</p> * * @see #setFunctionForPushEvent() * @see #clearPushEvent() * @see #pushEvents */ public function setScreenIDForPushEvent(eventType:String, screenID:String):void { this._pushEvents[eventType] = screenID; } /** * Cancels the action previously registered to be triggered when the * screen dispatches an event. * * @see #pushEvents */ public function clearPushEvent(eventType:String):void { delete this._pushEvents[eventType]; } /** * Specifies an event dispatched by the screen that will cause the * <code>StackScreenNavigator</code> to pop the screen off the top of * the stack and return to the previous screen. * * <p>If the screen is currently being displayed by a * <code>StackScreenNavigator</code>, and you call * <code>addPopEvent()</code> on the <code>StackScreenNavigatorItem</code>, * the <code>StackScreenNavigator</code> won't listen for the event * until the next time that the screen is shown.</p> * * @see #removePopEvent() * @see #popEvents */ public function addPopEvent(eventType:String):void { if(!this._popEvents) { this._popEvents = new <String>[]; } var index:int = this._popEvents.indexOf(eventType); if(index >= 0) { return; } this._popEvents[this._popEvents.length] = eventType; } /** * Removes an event that would cause the <code>StackScreenNavigator</code> * to remove this screen from the top of the stack. * * <p>If the screen is currently being displayed by a * <code>StackScreenNavigator</code>, and you call * <code>removePopEvent()</code> on the <code>StackScreenNavigatorItem</code>, * the <code>StackScreenNavigator</code> won't remove the listener for * the event on the currently displayed screen. The event listener won't * be added the next time that the screen is shown.</p> * * @see #addPopEvent() * @see #popEvents */ public function removePopEvent(eventType:String):void { if(!this._popEvents) { return; } var index:int = this._popEvents.indexOf(eventType); if(index >= 0) { return; } this._popEvents.splice(index, 1); } /** * Specifies an event dispatched by the screen that will cause the * <code>StackScreenNavigator</code> to pop the screen off the top of * the stack and return to the previous screen. * * <p>If the screen is currently being displayed by a * <code>StackScreenNavigator</code>, and you call * <code>addPopToRootEvent()</code> on the <code>StackScreenNavigatorItem</code>, * the <code>StackScreenNavigator</code> won't listen for the event * until the next time that the screen is shown.</p> * * @see #removePopToRootEvent() * @see #popToRootEvents */ public function addPopToRootEvent(eventType:String):void { if(!this._popToRootEvents) { this._popToRootEvents = new <String>[]; } var index:int = this._popToRootEvents.indexOf(eventType); if(index >= 0) { return; } this._popToRootEvents[this._popToRootEvents.length] = eventType; } /** * Removes an event that would have cause the <code>StackScreenNavigator</code> * to clear its stack to show the first screen added to the stack. * * <p>If the screen is currently being displayed by a * <code>StackScreenNavigator</code>, and you call * <code>removePopEvent()</code> on the <code>StackScreenNavigatorItem</code>, * the <code>StackScreenNavigator</code> won't remove the listener for * the event on the currently displayed screen. The event listener won't * be added the next time that the screen is shown.</p> * * @see #addPopToRootEvent() * @see #popToRootEvents */ public function removePopToRootEvent(eventType:String):void { if(!this._popToRootEvents) { return; } var index:int = this._popToRootEvents.indexOf(eventType); if(index >= 0) { return; } this._popToRootEvents.splice(index, 1); } /** * @inheritDoc */ public function getScreen():DisplayObject { var screenInstance:DisplayObject; if(this._screen is Class) { var ScreenType:Class = Class(this._screen); screenInstance = new ScreenType(); } else if(this._screen is Function) { screenInstance = DisplayObject((this._screen as Function)()); } else { screenInstance = DisplayObject(this._screen); } if(!(screenInstance is DisplayObject)) { throw new ArgumentError("ScreenNavigatorItem \"getScreen()\" must return a Starling display object."); } if(this._properties) { for(var propertyName:String in this._properties) { screenInstance[propertyName] = this._properties[propertyName]; } } return screenInstance; } } }
package flair.logging { /** * @author SamYStudiO ( contact@samystudio.net ) */ public class TraceHandler extends AHandler { /** * */ public function TraceHandler() { } /** * @inheritDoc */ override public function publish( record : LogRecord ) : void { if( isLoggable( record ) ) trace( formatter.format( record ) ); } } }
/* Adobe Systems Incorporated(r) Source Code License Agreement Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. Please read this Source Code License Agreement carefully before using the source code. Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license, to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute this source code and such derivative works in source or object code form without any attribution requirements. The name "Adobe Systems Incorporated" must not be used to endorse or promote products derived from the source code without prior written permission. You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and against any loss, damage, claims or lawsuits, including attorney's fees that arise or result from your use or distribution of the source code. THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA OR ITS SUPPLIERS 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 SOURCE CODE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.adobe.serialization.json { /** * This class provides encoding and decoding of the JSON format. * * Example usage: * <code> * // create a JSON string from an internal object * JSON.encode( myObject ); * * // read a JSON string into an internal object * var myObject:Object = JSON.decode( jsonString ); * </code> */ public class JSON10 { /** * Encodes a object into a JSON string. * * @param o The object to create a JSON string for * @return the JSON string representing o * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public static function encode( o:Object ):String { var encoder:JSONEncoder = new JSONEncoder( o ); return encoder.getString(); } /** * Decodes a JSON string into a native object. * * @param s The JSON string representing the object * @return A native object as specified by s * @throw JSONParseError * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public static function decode( s:String ):* { var decoder:JSONDecoder = new JSONDecoder( s ) return decoder.getValue(); } } }
package fairygui { import flash.display.DisplayObject; import flash.display.Sprite; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.MouseEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.text.TextField; import flash.text.TextFieldType; import flash.ui.Mouse; import flash.utils.getTimer; import fairygui.event.GTouchEvent; import fairygui.utils.GTimers; import fairygui.utils.ToolSet; [Event(name = "scroll", type = "flash.events.Event")] [Event(name = "scrollEnd", type = "flash.events.Event")] [Event(name = "pullDownRelease", type = "flash.events.Event")] [Event(name = "pullUpRelease", type = "flash.events.Event")] public class ScrollPane extends EventDispatcher { private var _owner:GComponent; private var _container:Sprite; private var _maskContainer:Sprite; private var _alignContainer:Sprite; private var _scrollType:int; private var _scrollStep:int; private var _mouseWheelStep:int; private var _decelerationRate:Number; private var _scrollBarMargin:Margin; private var _bouncebackEffect:Boolean; private var _touchEffect:Boolean; private var _scrollBarDisplayAuto:Boolean; private var _vScrollNone:Boolean; private var _hScrollNone:Boolean; private var _needRefresh:Boolean; private var _refreshBarAxis:String; private var _displayOnLeft:Boolean; private var _snapToItem:Boolean; private var _displayInDemand:Boolean; private var _mouseWheelEnabled:Boolean; private var _pageMode:Boolean; private var _inertiaDisabled:Boolean; private var _xPos:Number; private var _yPos:Number; private var _viewSize:Point; private var _contentSize:Point; private var _overlapSize:Point; private var _pageSize:Point; private var _containerPos:Point; private var _beginTouchPos:Point; private var _lastTouchPos:Point; private var _lastTouchGlobalPos:Point; private var _velocity:Point; private var _velocityScale:Number; private var _lastMoveTime:Number; private var _isHoldAreaDone:Boolean; private var _aniFlag:int; private var _scrollBarVisible:Boolean; internal var _loop:int; private var _headerLockedSize:int; private var _footerLockedSize:int; private var _refreshEventDispatching:Boolean; private var _tweening:int; private var _tweenTime:Point; private var _tweenDuration:Point; private var _tweenStart:Point; private var _tweenChange:Point; private var _pageController:Controller; private var _hzScrollBar:GScrollBar; private var _vtScrollBar:GScrollBar; private var _header:GComponent; private var _footer:GComponent; public var isDragged:Boolean; public static var draggingPane:ScrollPane; private static var _gestureFlag:int = 0; private static var sHelperPoint:Point = new Point(); private static var sHelperRect:Rectangle = new Rectangle(); private static var sEndPos:Point = new Point(); private static var sOldChange:Point = new Point(); public static const SCROLL_END:String = "scrollEnd"; public static const PULL_DOWN_RELEASE:String = "pullDownRelease"; public static const PULL_UP_RELEASE:String = "pullUpRelease"; public static const TWEEN_TIME_GO:Number = 0.5; //调用SetPos(ani)时使用的缓动时间 public static const TWEEN_TIME_DEFAULT:Number = 0.3; //惯性滚动的最小缓动时间 public static const PULL_RATIO:Number = 0.5; //下拉过顶或者上拉过底时允许超过的距离占显示区域的比例 public function ScrollPane(owner:GComponent, scrollType:int, scrollBarMargin:Margin, scrollBarDisplay:int, flags:int, vtScrollBarRes:String, hzScrollBarRes:String, headerRes:String, footerRes:String):void { _owner = owner; owner.opaque = true; _maskContainer = new Sprite(); _maskContainer.mouseEnabled = false; _owner._rootContainer.addChild(_maskContainer); _container = _owner._container; _container.x = 0; _container.y = 0; _container.mouseEnabled = false; _maskContainer.addChild(_container); _scrollBarMargin = scrollBarMargin; _scrollType = scrollType; _scrollStep = UIConfig.defaultScrollStep; _mouseWheelStep = _scrollStep*2; _decelerationRate = UIConfig.defaultScrollDecelerationRate; _displayOnLeft = (flags & 1)!=0; _snapToItem = (flags & 2)!=0; _displayInDemand = (flags & 4)!=0; _pageMode = (flags & 8)!=0; if(flags & 16) _touchEffect = true; else if(flags & 32) _touchEffect = false; else _touchEffect = UIConfig.defaultScrollTouchEffect; if(flags & 64) _bouncebackEffect = true; else if(flags & 128) _bouncebackEffect = false; else _bouncebackEffect = UIConfig.defaultScrollBounceEffect; _inertiaDisabled = (flags & 256)!=0; if((flags & 512) == 0) _maskContainer.scrollRect = new Rectangle(); _scrollBarVisible = true; _mouseWheelEnabled = true; _xPos = 0; _yPos = 0; _aniFlag = 0; _footerLockedSize = 0; _headerLockedSize = 0; if(scrollBarDisplay==ScrollBarDisplayType.Default) scrollBarDisplay = UIConfig.defaultScrollBarDisplay; _viewSize = new Point(); _contentSize = new Point(); _pageSize = new Point(1,1); _overlapSize = new Point(); _tweenTime = new Point(); _tweenStart = new Point(); _tweenDuration = new Point(); _tweenChange = new Point(); _velocity = new Point(); _containerPos = new Point(); _beginTouchPos = new Point(); _lastTouchPos = new Point(); _lastTouchGlobalPos = new Point(); if(scrollBarDisplay!=ScrollBarDisplayType.Hidden) { if(_scrollType==ScrollType.Both || _scrollType==ScrollType.Vertical) { var res:String = vtScrollBarRes?vtScrollBarRes:UIConfig.verticalScrollBar; if(res) { _vtScrollBar = UIPackage.createObjectFromURL(res) as GScrollBar; if(!_vtScrollBar) throw new Error("cannot create scrollbar from " + res); _vtScrollBar.setScrollPane(this, true); _owner._rootContainer.addChild(_vtScrollBar.displayObject); } } if(_scrollType==ScrollType.Both || _scrollType==ScrollType.Horizontal) { res = hzScrollBarRes?hzScrollBarRes:UIConfig.horizontalScrollBar; if(res) { _hzScrollBar = UIPackage.createObjectFromURL(res) as GScrollBar; if(!_hzScrollBar) throw new Error("cannot create scrollbar from " + res); _hzScrollBar.setScrollPane(this, false); _owner._rootContainer.addChild(_hzScrollBar.displayObject); } } _scrollBarDisplayAuto = scrollBarDisplay==ScrollBarDisplayType.Auto; if(_scrollBarDisplayAuto) { _scrollBarVisible = false; if(_vtScrollBar) _vtScrollBar.displayObject.visible = false; if(_hzScrollBar) _hzScrollBar.displayObject.visible = false; if(Mouse.supportsCursor) { _owner._rootContainer.addEventListener(MouseEvent.ROLL_OVER, __rollOver); _owner._rootContainer.addEventListener(MouseEvent.ROLL_OUT, __rollOut); } } } else _mouseWheelEnabled = false; if (headerRes) { _header = UIPackage.createObjectFromURL(headerRes) as GComponent; if (_header == null) throw new Error("FairyGUI: cannot create scrollPane header from " + headerRes); } if (footerRes) { _footer = UIPackage.createObjectFromURL(footerRes) as GComponent; if (_footer == null) throw new Error("FairyGUI: cannot create scrollPane footer from " + footerRes); } if (_header != null || _footer != null) _refreshBarAxis = (_scrollType == ScrollType.Both || _scrollType == ScrollType.Vertical) ? "y" : "x"; setSize(owner.width, owner.height); _owner._rootContainer.addEventListener(MouseEvent.MOUSE_WHEEL, __mouseWheel); _owner.addEventListener(GTouchEvent.BEGIN, __mouseDown); _owner.addEventListener(GTouchEvent.END, __mouseUp); } public function dispose():void { if (_tweening != 0) GTimers.inst.remove(tweenUpdate); _pageController = null; if (_hzScrollBar != null) _hzScrollBar.dispose(); if (_vtScrollBar != null) _vtScrollBar.dispose(); if (_header != null) _header.dispose(); if (_footer != null) _footer.dispose(); } public function get owner():GComponent { return _owner; } public function get hzScrollBar(): GScrollBar { return this._hzScrollBar; } public function get vtScrollBar(): GScrollBar { return this._vtScrollBar; } public function get header():GComponent { return _header; } public function get footer():GComponent { return _footer; } public function get bouncebackEffect():Boolean { return _bouncebackEffect; } public function set bouncebackEffect(sc:Boolean):void { _bouncebackEffect = sc; } public function get touchEffect():Boolean { return _touchEffect; } public function set touchEffect(sc:Boolean):void { _touchEffect = sc; } [Deprecated(replacement="ScrollPane.scrollStep")] public function set scrollSpeed(val:int):void { this.scrollStep = val; } [Deprecated(replacement="ScrollPane.scrollStep")] public function get scrollSpeed():int { return this.scrollStep; } public function set scrollStep(val:int):void { _scrollStep = val; if(_scrollStep==0) _scrollStep = UIConfig.defaultScrollStep; _mouseWheelStep = _scrollStep*2; } public function get scrollStep():int { return _scrollStep; } public function get snapToItem():Boolean { return _snapToItem; } public function set snapToItem(value:Boolean):void { _snapToItem = value; } public function get mouseWheelEnabled():Boolean { return _mouseWheelEnabled; } public function set mouseWheelEnabled(value:Boolean):void { _mouseWheelEnabled = value; } public function get decelerationRate():Number { return _decelerationRate; } public function set decelerationRate(value:Number):void { _decelerationRate = value; } public function get percX():Number { return _overlapSize.x == 0 ? 0 : _xPos / _overlapSize.x; } public function set percX(value:Number):void { setPercX(value, false); } public function setPercX(value:Number, ani:Boolean=false):void { _owner.ensureBoundsCorrect(); setPosX(_overlapSize.x * ToolSet.clamp01(value), ani); } public function get percY():Number { return _overlapSize.y == 0 ? 0 : _yPos / _overlapSize.y; } public function set percY(value:Number):void { setPercY(value, false); } public function setPercY(value:Number, ani:Boolean=false):void { _owner.ensureBoundsCorrect(); setPosY(_overlapSize.y * ToolSet.clamp01(value), ani); } public function get posX():Number { return _xPos; } public function set posX(value:Number):void { setPosX(value, false); } public function setPosX(value:Number, ani:Boolean=false):void { _owner.ensureBoundsCorrect(); if (_loop == 1) value = loopCheckingNewPos(value, "x"); value = ToolSet.clamp(value, 0, _overlapSize.x); if (value != _xPos) { _xPos = value; posChanged(ani); } } public function get posY():Number { return _yPos; } public function set posY(value:Number):void { setPosY(value, false); } public function setPosY(value:Number, ani:Boolean=false):void { _owner.ensureBoundsCorrect(); if (_loop == 1) value = loopCheckingNewPos(value, "y"); value = ToolSet.clamp(value, 0, _overlapSize.y); if (value != _yPos) { _yPos = value; posChanged(ani); } } public function get contentWidth():Number { return _contentSize.x; } public function get contentHeight():Number { return _contentSize.y; } public function get viewWidth():int { return _viewSize.x; } public function set viewWidth(value:int):void { value = value + _owner.margin.left + _owner.margin.right; if (_vtScrollBar != null) value += _vtScrollBar.width; _owner.width = value; } public function get viewHeight():int { return _viewSize.y; } public function set viewHeight(value:int):void { value = value + _owner.margin.top + _owner.margin.bottom; if (_hzScrollBar != null) value += _hzScrollBar.height; _owner.height = value; } public function get currentPageX():int { if (!_pageMode) return 0; var page:int = Math.floor(_xPos / _pageSize.x); if (_xPos - page * _pageSize.x > _pageSize.x * 0.5) page++; return page; } public function set currentPageX(value:int):void { setCurrentPageX(value, false); } public function get currentPageY():int { if (!_pageMode) return 0; var page:int = Math.floor(_yPos / _pageSize.y); if (_yPos - page * _pageSize.y > _pageSize.y * 0.5) page++; return page; } public function set currentPageY(value:int):void { setCurrentPageY(value, false); } public function setCurrentPageX(value:int, ani:Boolean):void { if (_pageMode && _overlapSize.x>0) this.setPosX(value * _pageSize.x, ani); } public function setCurrentPageY(value:int, ani:Boolean):void { if (_pageMode && _overlapSize.y>0) this.setPosY(value * _pageSize.y, ani); } public function get isBottomMost():Boolean { return _yPos == _overlapSize.y || _overlapSize.y == 0; } public function get isRightMost():Boolean { return _xPos == _overlapSize.x || _overlapSize.x == 0; } public function get pageController():Controller { return _pageController; } public function set pageController(value:Controller):void { _pageController = value; } public function get scrollingPosX():Number { return ToolSet.clamp(-_container.x, 0, _overlapSize.x); } public function get scrollingPosY():Number { return ToolSet.clamp(-_container.y, 0, _overlapSize.y); } public function scrollTop(ani:Boolean=false):void { this.setPercY(0, ani); } public function scrollBottom(ani:Boolean=false):void { this.setPercY(1, ani); } public function scrollUp(ratio:Number=1, ani:Boolean=false):void { if (_pageMode) setPosY(_yPos - _pageSize.y * ratio, ani); else setPosY(_yPos - _scrollStep * ratio, ani);; } public function scrollDown(ratio:Number=1, ani:Boolean=false):void { if (_pageMode) setPosY(_yPos + _pageSize.y * ratio, ani); else setPosY(_yPos + _scrollStep * ratio, ani); } public function scrollLeft(ratio:Number=1, ani:Boolean=false):void { if (_pageMode) setPosX(_xPos - _pageSize.x * ratio, ani); else setPosX(_xPos - _scrollStep * ratio, ani); } public function scrollRight(ratio:Number=1, ani:Boolean=false):void  { if (_pageMode) setPosX(_xPos + _pageSize.x * ratio, ani); else setPosX(_xPos + _scrollStep * ratio, ani); } /** * @param target GObject: can be any object on stage, not limited to the direct child of this container. * or Rectangle: Rect in local coordinates * @param ani If moving to target position with animation * @param setFirst If true, scroll to make the target on the top/left; If false, scroll to make the target any position in view. */ public function scrollToView(target:*, ani:Boolean=false, setFirst:Boolean=false):void { _owner.ensureBoundsCorrect(); if(_needRefresh) refresh(); var rect:Rectangle; if(target is GObject) { if (target.parent != _owner) { GObject(target).parent.localToGlobalRect(target.x, target.y, target.width, target.height, sHelperRect); rect = _owner.globalToLocalRect(sHelperRect.x, sHelperRect.y, sHelperRect.width, sHelperRect.height, sHelperRect); } else { rect = sHelperRect; rect.setTo(target.x, target.y, target.width, target.height); } } else rect = Rectangle(target); if(_overlapSize.y>0) { var bottom:Number = _yPos+_viewSize.y; if(setFirst || rect.y<=_yPos || rect.height>=_viewSize.y) { if(_pageMode) this.setPosY(Math.floor(rect.y/_pageSize.y)*_pageSize.y, ani); else this.setPosY(rect.y, ani); } else if(rect.y+rect.height>bottom) { if(_pageMode) this.setPosY(Math.floor(rect.y/_pageSize.y)*_pageSize.y, ani); else if (rect.height <= _viewSize.y/2) this.setPosY(rect.y+rect.height*2-_viewSize.y, ani); else this.setPosY(rect.y+rect.height-_viewSize.y, ani); } } if(_overlapSize.x>0) { var right:Number = _xPos+_viewSize.x; if(setFirst || rect.x<=_xPos || rect.width>=_viewSize.x) { if(_pageMode) this.setPosX(Math.floor(rect.x/_pageSize.x)*_pageSize.x, ani); else this.setPosX(rect.x, ani); } else if(rect.x+rect.width>right) { if(_pageMode) this.setPosX(Math.floor(rect.x/_pageSize.x)*_pageSize.x, ani); else if (rect.width <= _viewSize.x/2) this.setPosX(rect.x+rect.width*2-_viewSize.x, ani); else this.setPosX(rect.x+rect.width-_viewSize.x, ani); } } if(!ani && _needRefresh) refresh(); } /** * @param obj obj must be the direct child of this container */ public function isChildInView(obj:GObject):Boolean { if(_overlapSize.y>0) { var dist:Number = obj.y+_container.y; if(dist<-obj.height || dist>_viewSize.y) return false; } if(_overlapSize.x>0) { dist = obj.x + _container.x; if(dist<-obj.width || dist>_viewSize.x) return false; } return true; } public function cancelDragging():void { _owner.removeEventListener(GTouchEvent.DRAG, __mouseMove); if (draggingPane == this) draggingPane = null; _gestureFlag = 0; isDragged = false; _maskContainer.mouseChildren = true; } public function lockHeader(size:int):void { if (_headerLockedSize == size) return; _headerLockedSize = size; if (!_refreshEventDispatching && _container[_refreshBarAxis] >= 0) { _tweenStart.setTo(_container.x, _container.y); _tweenChange.setTo(0,0); _tweenChange[_refreshBarAxis] = _headerLockedSize - _tweenStart[_refreshBarAxis]; _tweenDuration.setTo(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); _tweenTime.setTo(0,0); _tweening = 2; GTimers.inst.callBy60Fps(tweenUpdate); } } public function lockFooter(size:int):void { if (_footerLockedSize == size) return; _footerLockedSize = size; if (!_refreshEventDispatching && _container[_refreshBarAxis] <= -_overlapSize[_refreshBarAxis]) { _tweenStart.setTo(_container.x, _container.y); _tweenChange.setTo(0,0); var max:Number = _overlapSize[_refreshBarAxis]; if (max == 0) max = Math.max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); else max += _footerLockedSize; _tweenChange[_refreshBarAxis] = -max - _tweenStart[_refreshBarAxis]; _tweenDuration.setTo(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); _tweenTime.setTo(0,0); _tweening = 2; GTimers.inst.callBy60Fps(tweenUpdate); } } internal function onOwnerSizeChanged():void { setSize(_owner.width, _owner.height); posChanged(false); } internal function handleControllerChanged(c:Controller):void { if (_pageController == c) { if (_scrollType == ScrollType.Horizontal) this.setCurrentPageX(c.selectedIndex, true); else this.setCurrentPageY(c.selectedIndex, true); } } private function updatePageController():void { if (_pageController != null && !_pageController.changing) { var index:int; if (_scrollType == ScrollType.Horizontal) index = this.currentPageX; else index = this.currentPageY; if (index < _pageController.pageCount) { var c:Controller = _pageController; _pageController = null; //防止HandleControllerChanged的调用 c.selectedIndex = index; _pageController = c; } } } internal function adjustMaskContainer():void { var mx:Number, my:Number; if (_displayOnLeft && _vtScrollBar != null) mx = Math.floor(_owner.margin.left + _vtScrollBar.width); else mx = Math.floor(_owner.margin.left); my = Math.floor(_owner.margin.top); _maskContainer.x = mx; _maskContainer.y = my; if(_owner._alignOffset.x!=0 || _owner._alignOffset.y!=0) { if(_alignContainer==null) { _alignContainer = new Sprite(); _alignContainer.mouseEnabled = false; _maskContainer.addChild(_alignContainer); _alignContainer.addChild(_container); } _alignContainer.x = _owner._alignOffset.x; _alignContainer.y = _owner._alignOffset.y; } else if(_alignContainer) { _alignContainer.x = _alignContainer.y = 0; } } private function setSize(aWidth:Number, aHeight:Number):void { adjustMaskContainer(); if(_hzScrollBar) { _hzScrollBar.y = aHeight - _hzScrollBar.height; if(_vtScrollBar) { _hzScrollBar.width = aWidth - _vtScrollBar.width - _scrollBarMargin.left - _scrollBarMargin.right; if(_displayOnLeft) _hzScrollBar.x = _scrollBarMargin.left + _vtScrollBar.width; else _hzScrollBar.x = _scrollBarMargin.left; } else { _hzScrollBar.width = aWidth - _scrollBarMargin.left - _scrollBarMargin.right; _hzScrollBar.x = _scrollBarMargin.left; } } if(_vtScrollBar) { if(!_displayOnLeft) _vtScrollBar.x = aWidth - _vtScrollBar.width; if(_hzScrollBar) _vtScrollBar.height = aHeight - _hzScrollBar.height - _scrollBarMargin.top - _scrollBarMargin.bottom; else _vtScrollBar.height = aHeight - _scrollBarMargin.top - _scrollBarMargin.bottom; _vtScrollBar.y = _scrollBarMargin.top; } _viewSize.x = aWidth; _viewSize.y = aHeight; if(_hzScrollBar && !_hScrollNone) _viewSize.y -= _hzScrollBar.height; if(_vtScrollBar && !_vScrollNone) _viewSize.x -= _vtScrollBar.width; _viewSize.x -= (_owner.margin.left+_owner.margin.right); _viewSize.y -= (_owner.margin.top+_owner.margin.bottom); _viewSize.x = Math.max(1, _viewSize.x); _viewSize.y = Math.max(1, _viewSize.y); _pageSize.x = _viewSize.x; _pageSize.y = _viewSize.y; handleSizeChanged(); } internal function setContentSize(aWidth:Number, aHeight:Number):void { if(_contentSize.x==aWidth && _contentSize.y==aHeight) return; _contentSize.x = aWidth; _contentSize.y = aHeight; handleSizeChanged(); } internal function changeContentSizeOnScrolling(deltaWidth:Number, deltaHeight:Number, deltaPosX:Number, deltaPosY:Number):void { var isRightmost:Boolean = _xPos == _overlapSize.x; var isBottom:Boolean = _yPos == _overlapSize.y; _contentSize.x += deltaWidth; _contentSize.y += deltaHeight; handleSizeChanged(); if (_tweening == 1) { //如果原来滚动位置是贴边,加入处理继续贴边。 if (deltaWidth != 0 && isRightmost && _tweenChange.x < 0) { _xPos = _overlapSize.x; _tweenChange.x = -_xPos - _tweenStart.x; } if (deltaHeight != 0 && isBottom && _tweenChange.y < 0) { _yPos = _overlapSize.y; _tweenChange.y = -_yPos - _tweenStart.y; } } else if (_tweening == 2) { //重新调整起始位置,确保能够顺滑滚下去 if (deltaPosX != 0) { _container.x -= deltaPosX; _tweenStart.x -= deltaPosX; _xPos = -_container.x; } if (deltaPosY != 0) { _container.y -= deltaPosY; _tweenStart.y -= deltaPosY; _yPos = -_container.y; } } else if (isDragged) { if (deltaPosX != 0) { _container.x -= deltaPosX; _containerPos.x -= deltaPosX; _xPos = -_container.x; } if (deltaPosY != 0) { _container.y -= deltaPosY; _containerPos.y -= deltaPosY; _yPos = -_container.y; } } else { //如果原来滚动位置是贴边,加入处理继续贴边。 if (deltaWidth != 0 && isRightmost) { _xPos = _overlapSize.x; _container.x = -_xPos; } if (deltaHeight != 0 && isBottom) { _yPos = _overlapSize.y; _container.y = -_yPos; } } if (_pageMode) updatePageController(); } private function handleSizeChanged(onScrolling:Boolean=false):void { if(_displayInDemand) { if(_vtScrollBar) { if(_contentSize.y<=_viewSize.y) { if(!_vScrollNone) { _vScrollNone = true; _viewSize.x += _vtScrollBar.width; } } else { if(_vScrollNone) { _vScrollNone = false; _viewSize.x -= _vtScrollBar.width; } } } if(_hzScrollBar) { if(_contentSize.x<=_viewSize.x) { if(!_hScrollNone) { _hScrollNone = true; _viewSize.y += _hzScrollBar.height; } } else { if(_hScrollNone) { _hScrollNone = false; _viewSize.y -= _hzScrollBar.height; } } } } if(_vtScrollBar) { if(_viewSize.y<_vtScrollBar.minSize) //没有使用_vtScrollBar.visible是因为ScrollBar用了一个trick,它并不在owner的DisplayList里,因此_vtScrollBar.visible是无效的 _vtScrollBar.displayObject.visible = false; else { _vtScrollBar.displayObject.visible = _scrollBarVisible && !_vScrollNone; if(_contentSize.y==0) _vtScrollBar.displayPerc = 0; else _vtScrollBar.displayPerc = Math.min(1, _viewSize.y/_contentSize.y); } } if(_hzScrollBar) { if(_viewSize.x<_hzScrollBar.minSize) _hzScrollBar.displayObject.visible = false; else { _hzScrollBar.displayObject.visible = _scrollBarVisible && !_hScrollNone; if(_contentSize.x==0) _hzScrollBar.displayPerc = 0; else _hzScrollBar.displayPerc = Math.min(1, _viewSize.x/_contentSize.x); } } var rect:Rectangle = _maskContainer.scrollRect; if (rect) { rect.width = _viewSize.x; rect.height = _viewSize.y; _maskContainer.scrollRect = rect; } if (_scrollType == ScrollType.Horizontal || _scrollType == ScrollType.Both) _overlapSize.x = Math.ceil(Math.max(0, _contentSize.x - _viewSize.x)); else _overlapSize.x = 0; if (_scrollType == ScrollType.Vertical || _scrollType == ScrollType.Both) _overlapSize.y = Math.ceil(Math.max(0, _contentSize.y - _viewSize.y)); else _overlapSize.y = 0; //边界检查 _xPos = ToolSet.clamp(_xPos, 0, _overlapSize.x); _yPos = ToolSet.clamp(_yPos, 0, _overlapSize.y); if(_refreshBarAxis!=null) { var max:Number = _overlapSize[_refreshBarAxis]; if (max == 0) max = Math.max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); else max += _footerLockedSize; if (_refreshBarAxis == "x") { _container.x = ToolSet.clamp(_container.x, -max, _headerLockedSize); _container.y = ToolSet.clamp(_container.y, -_overlapSize.y, 0); } else { _container.x = ToolSet.clamp(_container.x, -_overlapSize.x, 0); _container.y = ToolSet.clamp(_container.y, -max, _headerLockedSize); } if (_header != null) { if (_refreshBarAxis == "x") _header.height = _viewSize.y; else _header.width = _viewSize.x; } if (_footer != null) { if (_refreshBarAxis == "y") _footer.height = _viewSize.y; else _footer.width = _viewSize.x; } } else { _container.x = ToolSet.clamp(_container.x, -_overlapSize.x, 0); _container.y = ToolSet.clamp(_container.y, -_overlapSize.y, 0); } syncScrollBar(true); checkRefreshBar(); if (_pageMode) updatePageController(); } private function posChanged(ani:Boolean):void { if (_aniFlag == 0) _aniFlag = ani ? 1 : -1; else if (_aniFlag == 1 && !ani) _aniFlag = -1; _needRefresh = true; GTimers.inst.callLater(refresh); } private function refresh():void { _needRefresh = false; GTimers.inst.remove(refresh); if (_pageMode || _snapToItem) { sEndPos.setTo(-_xPos, -_yPos); alignPosition(sEndPos, false); _xPos = -sEndPos.x; _yPos = -sEndPos.y; } refresh2(); dispatchEvent(new Event(Event.SCROLL)); if (_needRefresh) //在onScroll事件里开发者可能修改位置,这里再刷新一次,避免闪烁 { _needRefresh = false; GTimers.inst.remove(refresh); refresh2(); } syncScrollBar(); _aniFlag = 0; } private function refresh2():void { if (_aniFlag == 1 && !isDragged) { var posX:Number; var posY:Number; if (_overlapSize.x > 0) posX = -int(_xPos); else { if (_container.x != 0) _container.x = 0; posX = 0; } if (_overlapSize.y > 0) posY = -int(_yPos); else { if (_container.y != 0) _container.y = 0; posY = 0; } if (posX != _container.x || posY != _container.y) { _tweening = 1; _tweenTime.setTo(0,0); _tweenDuration.setTo(TWEEN_TIME_GO, TWEEN_TIME_GO); _tweenStart.setTo(_container.x, _container.y); _tweenChange.setTo(posX - _tweenStart.x, posY - _tweenStart.y); GTimers.inst.callBy60Fps(tweenUpdate); } else if (_tweening != 0) killTween(); } else { if (_tweening != 0) killTween(); _container.x = int(-_xPos); _container.y = int(-_yPos); loopCheckingCurrent(); } if (_pageMode) updatePageController(); } private function syncScrollBar(end:Boolean=false):void { if (_vtScrollBar != null) { _vtScrollBar.scrollPerc = _overlapSize.y == 0 ? 0 : ToolSet.clamp(-_container.y, 0, _overlapSize.y) / _overlapSize.y; if (_scrollBarDisplayAuto) showScrollBar(!end); } if (_hzScrollBar != null) { _hzScrollBar.scrollPerc = _overlapSize.x == 0 ? 0 : ToolSet.clamp(-_container.x, 0, _overlapSize.x) / _overlapSize.x; if (_scrollBarDisplayAuto) showScrollBar(!end); } if(end) _maskContainer.mouseChildren = true; } private function __mouseDown(evt:GTouchEvent):void { if(!_touchEffect) return; if(_tweening!=0) { killTween(); isDragged = true; } else isDragged = false; var pt:Point = _owner.globalToLocal(evt.stageX, evt.stageY); _containerPos.setTo(_container.x, _container.y); _beginTouchPos.copyFrom(pt); _lastTouchPos.copyFrom(pt); _lastTouchGlobalPos.setTo(evt.stageX, evt.stageY); _isHoldAreaDone = false; _velocity.setTo(0,0); _velocityScale = 1; _lastMoveTime = getTimer()/1000; _owner.addEventListener(GTouchEvent.DRAG, __mouseMove); } private function __mouseMove(evt:GTouchEvent):void { if(!_touchEffect) return; if (draggingPane != null && draggingPane != this || GObject.draggingObject != null) //已经有其他拖动 return; var pt:Point = _owner.globalToLocal(evt.stageX, evt.stageY); var sensitivity:int; if (GRoot.touchScreen) sensitivity = UIConfig.touchScrollSensitivity; else sensitivity = 8; var diff:Number, diff2:Number; var sv:Boolean, sh:Boolean, st:Boolean; if (_scrollType == ScrollType.Vertical) { if (!_isHoldAreaDone) { //表示正在监测垂直方向的手势 _gestureFlag |= 1; diff = Math.abs(_beginTouchPos.y - pt.y); if (diff < sensitivity) return; if ((_gestureFlag & 2) != 0) //已经有水平方向的手势在监测,那么我们用严格的方式检查是不是按垂直方向移动,避免冲突 { diff2 = Math.abs(_beginTouchPos.x - pt.x); if (diff < diff2) //不通过则不允许滚动了 return; } } sv = true; } else if (_scrollType == ScrollType.Horizontal) { if (!_isHoldAreaDone) { _gestureFlag |= 2; diff = Math.abs(_beginTouchPos.x - pt.x); if (diff < sensitivity) return; if ((_gestureFlag & 1) != 0) { diff2 = Math.abs(_beginTouchPos.y - pt.y); if (diff < diff2) return; } } sh = true; } else { _gestureFlag = 3; if (!_isHoldAreaDone) { diff = Math.abs(_beginTouchPos.y - pt.y); if (diff < sensitivity) { diff = Math.abs(_beginTouchPos.x - pt.x); if (diff < sensitivity) return; } } sv = sh = true; } var newPosX:Number = int(_containerPos.x + pt.x - _beginTouchPos.x); var newPosY:Number = int(_containerPos.y + pt.y - _beginTouchPos.y); if (sv) { if (newPosY > 0) { if (!_bouncebackEffect) _container.y = 0; else if (_header != null && _header.maxHeight != 0) _container.y = int(Math.min(newPosY * 0.5, _header.maxHeight)); else _container.y = int(Math.min(newPosY * 0.5, _viewSize.y * PULL_RATIO)); } else if (newPosY < -_overlapSize.y) { if (!_bouncebackEffect) _container.y = -_overlapSize.y; else if (_footer != null && _footer.maxHeight > 0) _container.y = int(Math.max((newPosY + _overlapSize.y) * 0.5, -_footer.maxHeight) - _overlapSize.y); else _container.y = int(Math.max((newPosY + _overlapSize.y) * 0.5, -_viewSize.y * PULL_RATIO) - _overlapSize.y); } else _container.y = newPosY; } if (sh) { if (newPosX > 0) { if (!_bouncebackEffect) _container.x = 0; else if (_header != null && _header.maxWidth != 0) _container.x = int(Math.min(newPosX * 0.5, _header.maxWidth)); else _container.x = int(Math.min(newPosX * 0.5, _viewSize.x * PULL_RATIO)); } else if (newPosX < 0 - _overlapSize.x) { if (!_bouncebackEffect) _container.x = -_overlapSize.x; else if (_footer != null && _footer.maxWidth > 0) _container.x = int(Math.max((newPosX + _overlapSize.x) * 0.5, -_footer.maxWidth) - _overlapSize.x); else _container.x = int(Math.max((newPosX + _overlapSize.x) * 0.5, -_viewSize.x * PULL_RATIO) - _overlapSize.x); } else _container.x = newPosX; } //更新速度 var frameRate:Number = _owner.displayObject.stage.frameRate; var now:Number = getTimer()/1000; var deltaTime:Number = Math.max(now - _lastMoveTime, 1/frameRate); var deltaPositionX:Number = pt.x - _lastTouchPos.x; var deltaPositionY:Number = pt.y - _lastTouchPos.y; if (!sh) deltaPositionX = 0; if (!sv) deltaPositionY = 0; if(deltaTime!=0) { var elapsed:Number = deltaTime * frameRate - 1; if (elapsed > 1) //速度衰减 { var factor:Number = Math.pow(0.833, elapsed); _velocity.x = _velocity.x * factor; _velocity.y = _velocity.y * factor; } _velocity.x = ToolSet.lerp(_velocity.x, deltaPositionX * 60 / frameRate / deltaTime, deltaTime * 10); _velocity.y = ToolSet.lerp(_velocity.y, deltaPositionY * 60 / frameRate / deltaTime, deltaTime * 10); } /*速度计算使用的是本地位移,但在后续的惯性滚动判断中需要用到屏幕位移,所以这里要记录一个位移的比例。 */ var deltaGlobalPositionX:Number = _lastTouchGlobalPos.x - evt.stageX; var deltaGlobalPositionY:Number = _lastTouchGlobalPos.y - evt.stageY; if (deltaPositionX != 0) _velocityScale = Math.abs(deltaGlobalPositionX / deltaPositionX); else if (deltaPositionY != 0) _velocityScale = Math.abs(deltaGlobalPositionY / deltaPositionY); _lastTouchPos.setTo(pt.x, pt.y); _lastTouchGlobalPos.setTo(evt.stageX, evt.stageY); _lastMoveTime = now; //同步更新pos值 if (_overlapSize.x > 0) _xPos = ToolSet.clamp(-_container.x, 0, _overlapSize.x); if (_overlapSize.y > 0) _yPos = ToolSet.clamp(-_container.y, 0, _overlapSize.y); //循环滚动特别检查 if (_loop != 0) { newPosX = _container.x; newPosY = _container.y; if (loopCheckingCurrent()) { _containerPos.x += _container.x - newPosX; _containerPos.y += _container.y - newPosY; } } draggingPane = this; _isHoldAreaDone = true; isDragged = true; _maskContainer.mouseChildren = false; syncScrollBar(); checkRefreshBar(); if (_pageMode) updatePageController(); dispatchEvent(new Event(Event.SCROLL)); } private function __mouseUp(e:Event):void { _owner.removeEventListener(GTouchEvent.DRAG, __mouseMove); if (draggingPane == this) draggingPane = null; _gestureFlag = 0; if (!isDragged || !_touchEffect) { isDragged = false; _maskContainer.mouseChildren = true; return; } isDragged = false; _maskContainer.mouseChildren = true; _tweenStart.setTo(_container.x, _container.y); sEndPos.copyFrom(_tweenStart); var flag:Boolean = false; if (_container.x > 0) { sEndPos.x = 0; flag = true; } else if (_container.x < -_overlapSize.x) { sEndPos.x = -_overlapSize.x; flag = true; } if (_container.y > 0) { sEndPos.y = 0; flag = true; } else if (_container.y < -_overlapSize.y) { sEndPos.y = -_overlapSize.y; flag = true; } if (flag) { _tweenChange.setTo(sEndPos.x - _tweenStart.x, sEndPos.y - _tweenStart.y); if (_tweenChange.x < -UIConfig.touchDragSensitivity || _tweenChange.y < -UIConfig.touchDragSensitivity) { _refreshEventDispatching = true; dispatchEvent(new Event(ScrollPane.PULL_DOWN_RELEASE)); _refreshEventDispatching = false; } else if (_tweenChange.x > UIConfig.touchDragSensitivity || _tweenChange.y > UIConfig.touchDragSensitivity) { _refreshEventDispatching = true; dispatchEvent(new Event(ScrollPane.PULL_UP_RELEASE)); _refreshEventDispatching = false; } if (_headerLockedSize > 0 && sEndPos[_refreshBarAxis] == 0) { sEndPos[_refreshBarAxis] = _headerLockedSize; _tweenChange.x = sEndPos.x - _tweenStart.x; _tweenChange.y = sEndPos.y - _tweenStart.y; } else if (_footerLockedSize > 0 && sEndPos[_refreshBarAxis] == -_overlapSize[_refreshBarAxis]) { var max:Number = _overlapSize[_refreshBarAxis]; if (max == 0) max = Math.max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); else max += _footerLockedSize; sEndPos[_refreshBarAxis] = -max; _tweenChange.x = sEndPos.x - _tweenStart.x; _tweenChange.y = sEndPos.y - _tweenStart.y; } _tweenDuration.setTo(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); } else { //更新速度 if (!_inertiaDisabled) { var frameRate:Number = _owner.displayObject.stage.frameRate; var elapsed:Number = (getTimer()/1000 - _lastMoveTime) * frameRate - 1; if (elapsed > 1) { var factor:Number = Math.pow(0.833, elapsed); _velocity.x = _velocity.x * factor; _velocity.y = _velocity.y * factor; } //根据速度计算目标位置和需要时间 updateTargetAndDuration(_tweenStart, sEndPos); } else _tweenDuration.setTo(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); sOldChange.setTo(sEndPos.x - _tweenStart.x, sEndPos.y - _tweenStart.y); //调整目标位置 loopCheckingTarget(sEndPos); if (_pageMode || _snapToItem) alignPosition(sEndPos, true); _tweenChange.x = sEndPos.x - _tweenStart.x; _tweenChange.y = sEndPos.y - _tweenStart.y; if (_tweenChange.x == 0 && _tweenChange.y == 0) { if (_scrollBarDisplayAuto) showScrollBar(false); return; } //如果目标位置已调整,随之调整需要时间 if (_pageMode || _snapToItem) { fixDuration("x", sOldChange.x); fixDuration("y", sOldChange.y); } } _tweening = 2; _tweenTime.setTo(0,0); GTimers.inst.callBy60Fps(tweenUpdate); } private function __mouseWheel(evt:MouseEvent):void { if(!_mouseWheelEnabled && (!_vtScrollBar || !_vtScrollBar._rootContainer.hitTestObject(DisplayObject(evt.target))) && (!_hzScrollBar || !_hzScrollBar._rootContainer.hitTestObject(DisplayObject(evt.target))) ) return; var focus:DisplayObject = _owner.displayObject.stage.focus; if((focus is TextField) && TextField(focus).type==TextFieldType.INPUT) return; var delta:Number = evt.delta; delta = delta>0?-1:(delta<0?1:0); if (_overlapSize.x > 0 && _overlapSize.y == 0) { if (_pageMode) setPosX(_xPos + _pageSize.x * delta, false); else setPosX(_xPos + _mouseWheelStep * delta, false); } else { if (_pageMode) setPosY(_yPos + _pageSize.y * delta, false); else setPosY(_yPos + _mouseWheelStep * delta, false); } } private function __rollOver(evt:Event):void { showScrollBar(true); } private function __rollOut(evt:Event):void { showScrollBar(false); } private function showScrollBar(val:Boolean):void { if(val) { __showScrollBar(true); GTimers.inst.remove(__showScrollBar); } else GTimers.inst.add(500, 1, __showScrollBar, val); } private function __showScrollBar(val:Boolean):void { _scrollBarVisible = val && _viewSize.x>0 && _viewSize.y>0; if(_vtScrollBar) _vtScrollBar.displayObject.visible = _scrollBarVisible && !_vScrollNone; if(_hzScrollBar) _hzScrollBar.displayObject.visible = _scrollBarVisible && !_hScrollNone; } private function getLoopPartSize(division:Number, axis:String):Number { return (_contentSize[axis] + (axis == "x" ? GList(_owner).columnGap : GList(_owner).lineGap)) / division; } private function loopCheckingCurrent():Boolean { var changed:Boolean = false; if (_loop == 1 && _overlapSize.x > 0) { if (_xPos < 0.001) { _xPos += getLoopPartSize(2, "x"); changed = true; } else if (_xPos >= _overlapSize.x) { _xPos -= getLoopPartSize(2, "x"); changed = true; } } else if (_loop == 2 && _overlapSize.y > 0) { if (_yPos < 0.001) { _yPos += getLoopPartSize(2, "y"); changed = true; } else if (_yPos >= _overlapSize.y) { _yPos -= getLoopPartSize(2, "y"); changed = true; } } if (changed) { _container.x = int(-_xPos); _container.y = int(-_yPos); } return changed; } private function loopCheckingTarget(endPos:Point):void { if (_loop == 1) loopCheckingTarget2(endPos, "x"); if (_loop == 2) loopCheckingTarget2(endPos, "y"); } private function loopCheckingTarget2(endPos:Point, axis:String):void { var halfSize:Number; var tmp:Number; if (endPos[axis] > 0) { halfSize = getLoopPartSize(2, axis); tmp = _tweenStart[axis] - halfSize; if (tmp <= 0 && tmp >= -_overlapSize[axis]) { endPos[axis] -= halfSize; _tweenStart[axis] = tmp; } } else if (endPos[axis] < -_overlapSize[axis]) { halfSize = getLoopPartSize(2, axis); tmp = _tweenStart[axis] + halfSize; if (tmp <= 0 && tmp >= -_overlapSize[axis]) { endPos[axis] += halfSize; _tweenStart[axis] = tmp; } } } private function loopCheckingNewPos(value:Number, axis:String):Number { if (_overlapSize[axis] == 0) return value; var pos:Number = axis == "x" ? _xPos : _yPos; var changed:Boolean = false; var v:Number; if (value < 0.001) { value += getLoopPartSize(2, axis); if (value > pos) { v = getLoopPartSize(6, axis); v = Math.ceil((value - pos) / v) * v; pos = ToolSet.clamp(pos + v, 0, _overlapSize[axis]); changed = true; } } else if (value >= _overlapSize[axis]) { value -= getLoopPartSize(2, axis); if (value < pos) { v = getLoopPartSize(6, axis); v = Math.ceil((pos - value) / v) * v; pos = ToolSet.clamp(pos - v, 0, _overlapSize[axis]); changed = true; } } if (changed) { if (axis == "x") _container.x = -int(pos); else _container.y = -int(pos); } return value; } private function alignPosition(pos:Point, inertialScrolling:Boolean):void { if (_pageMode) { pos.x = alignByPage(pos.x, "x", inertialScrolling); pos.y = alignByPage(pos.y, "y", inertialScrolling); } else if (_snapToItem) { var pt:Point = _owner.getSnappingPosition(-pos.x, -pos.y, sHelperPoint); if (pos.x < 0 && pos.x > -_overlapSize.x) pos.x = -pt.x; if (pos.y < 0 && pos.y > -_overlapSize.y) pos.y = -pt.y; } } private function alignByPage(pos:Number, axis:String, inertialScrolling:Boolean):Number { var page:int; if (pos > 0) page = 0; else if (pos < -_overlapSize[axis]) page = Math.ceil(_contentSize[axis] / _pageSize[axis]) - 1; else { page = Math.floor(-pos / _pageSize[axis]); var change:Number = inertialScrolling ? (pos - _containerPos[axis]) : (pos - _container[axis]); var testPageSize:Number = Math.min(_pageSize[axis], _contentSize[axis] - (page + 1) * _pageSize[axis]); var delta:Number = -pos - page * _pageSize[axis]; //页面吸附策略 if (Math.abs(change) > _pageSize[axis])//如果滚动距离超过1页,则需要超过页面的一半,才能到更下一页 { // if (delta > testPageSize * 0.5) if (delta > UIConfig.pageScrollMinDistance) page++; } else //否则只需要页面的1/3,当然,需要考虑到左移和右移的情况 { // if (delta > testPageSize * (change < 0 ? 0.3 : 0.7)) if (delta > (change < 0 ? UIConfig.pageScrollMinDistance : testPageSize-UIConfig.pageScrollMinDistance)) page++; } //重新计算终点 pos = -page * _pageSize[axis]; if (pos < -_overlapSize[axis]) //最后一页未必有pageSize那么大 pos = -_overlapSize[axis]; } //惯性滚动模式下,会增加判断尽量不要滚动超过一页 if (inertialScrolling) { var oldPos:Number = _tweenStart[axis]; var oldPage:int; if (oldPos > 0) oldPage = 0; else if (oldPos < -_overlapSize[axis]) oldPage = Math.ceil(_contentSize[axis] / _pageSize[axis]) - 1; else oldPage = Math.floor(-oldPos / _pageSize[axis]); var startPage:int = Math.floor(-_containerPos[axis] / _pageSize[axis]); if (Math.abs(page - startPage) > 1 && Math.abs(oldPage - startPage) <= 1) { if (page > startPage) page = startPage + 1; else page = startPage - 1; pos = -page * _pageSize[axis]; } } return pos; } private function updateTargetAndDuration(orignPos:Point, resultPos:Point):void { resultPos.x = updateTargetAndDuration2(orignPos.x, "x"); resultPos.y = updateTargetAndDuration2(orignPos.y, "y"); } private function updateTargetAndDuration2(pos:Number, axis:String):Number { var v:Number = _velocity[axis]; var duration:Number = 0; if (pos > 0) pos = 0; else if (pos < -_overlapSize[axis]) pos = -_overlapSize[axis]; else { //以屏幕像素为基准 var v2:Number = Math.abs(v) * _velocityScale; //在移动设备上,需要对不同分辨率做一个适配,我们的速度判断以1136分辨率为基准 if(GRoot.touchPointInput) v2 *= 1136 / Math.max(GRoot.inst.nativeStage.stageWidth, GRoot.inst.nativeStage.stageHeight); //这里有一些阈值的处理,因为在低速内,不希望产生较大的滚动(甚至不滚动) var ratio:Number = 0; if (_pageMode || !GRoot.touchPointInput) { if (v2 > 500) ratio = Math.pow((v2 - 500) / 500, 2); } else { if (v2 > 1000) ratio = Math.pow((v2 - 1000) / 1000, 2); } if (ratio != 0) { if (ratio > 1) ratio = 1; v2 *= ratio; v *= ratio; _velocity[axis] = v; //算法:v*(_decelerationRate的n次幂)= 60,即在n帧后速度降为60(假设每秒60帧)。 duration = Math.log(60 / v2)/Math.log(_decelerationRate) / 60; //计算距离要使用本地速度 //理论公式貌似滚动的距离不够,改为经验公式 //var change:int = (v/ 60 - 1) / (1 - _decelerationRate); var change:int = int(v * duration * 0.4); pos += change; } } if (duration < TWEEN_TIME_DEFAULT) duration = TWEEN_TIME_DEFAULT; _tweenDuration[axis] = duration; return pos; } private function fixDuration(axis:String, oldChange:Number):void { if (_tweenChange[axis] == 0 || Math.abs(_tweenChange[axis]) >= Math.abs(oldChange)) return; var newDuration:Number = Math.abs(_tweenChange[axis] / oldChange) * _tweenDuration[axis]; if (newDuration < TWEEN_TIME_DEFAULT) newDuration = TWEEN_TIME_DEFAULT; _tweenDuration[axis] = newDuration; } private function killTween():void { if (_tweening == 1) //取消类型为1的tween需立刻设置到终点 { _container.x = _tweenStart.x + _tweenChange.x; _container.y = _tweenStart.y + _tweenChange.y; dispatchEvent(new Event(Event.SCROLL)); } _tweening = 0; GTimers.inst.remove(tweenUpdate); dispatchEvent(new Event(SCROLL_END)); } private function checkRefreshBar():void { if (_header == null && _footer == null) return; var pos:Number = _container[_refreshBarAxis]; if (_header != null) { if (pos > 0) { if (_header.displayObject.parent == null) _maskContainer.addChildAt(_header.displayObject, 0); var pt:Point = sHelperPoint; pt.setTo(_header.width, _header.height); pt[_refreshBarAxis] = pos; _header.setSize(pt.x, pt.y); } else { if (_header.displayObject.parent != null) _maskContainer.removeChild(_header.displayObject); } } if (_footer != null) { var max:Number = _overlapSize[_refreshBarAxis]; if (pos < -max || max == 0 && _footerLockedSize > 0) { if (_footer.displayObject.parent == null) _maskContainer.addChildAt(_footer.displayObject, 0); pt = sHelperPoint; pt.setTo(_footer.x, _footer.y); if (max > 0) pt[_refreshBarAxis] = pos + _contentSize[_refreshBarAxis]; else pt[_refreshBarAxis] = Math.max(Math.min(pos + _viewSize[_refreshBarAxis], _viewSize[_refreshBarAxis] - _footerLockedSize), _viewSize[_refreshBarAxis] - _contentSize[_refreshBarAxis]); _footer.setXY(pt.x, pt.y); pt.setTo(_footer.width, _footer.height); if (max > 0) pt[_refreshBarAxis] = -max - pos; else pt[_refreshBarAxis] = _viewSize[_refreshBarAxis] - _footer[_refreshBarAxis]; _footer.setSize(pt.x, pt.y); } else { if (_footer.displayObject.parent != null) _maskContainer.removeChild(_footer.displayObject); } } } private function tweenUpdate():void { var nx:Number = runTween("x"); var ny:Number = runTween("y"); _container.x = nx; _container.y = ny; if (_tweening == 2) { if (_overlapSize.x > 0) _xPos = ToolSet.clamp(-nx, 0, _overlapSize.x); if (_overlapSize.y > 0) _yPos = ToolSet.clamp(-ny, 0, _overlapSize.y); if (_pageMode) updatePageController(); } if (_tweenChange.x == 0 && _tweenChange.y == 0) { _tweening = 0; GTimers.inst.remove(tweenUpdate); loopCheckingCurrent(); syncScrollBar(true); checkRefreshBar(); dispatchEvent(new Event(Event.SCROLL)); dispatchEvent(new Event(SCROLL_END)); } else { syncScrollBar(false); checkRefreshBar(); dispatchEvent(new Event(Event.SCROLL)); } } private function runTween(axis:String):Number { var newValue:Number; if (_tweenChange[axis] != 0) { _tweenTime[axis] += GTimers.deltaTime/1000; if (_tweenTime[axis] >= _tweenDuration[axis]) { newValue = _tweenStart[axis] + _tweenChange[axis]; _tweenChange[axis] = 0; } else { var ratio:Number = easeFunc(_tweenTime[axis], _tweenDuration[axis]); newValue = _tweenStart[axis] + int(_tweenChange[axis] * ratio); } var threshold1:Number = 0; var threshold2:Number = -_overlapSize[axis]; if (_headerLockedSize > 0 && _refreshBarAxis == axis) threshold1 = _headerLockedSize; if (_footerLockedSize > 0 && _refreshBarAxis == axis) { var max:Number = _overlapSize[_refreshBarAxis]; if (max == 0) max = Math.max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); else max += _footerLockedSize; threshold2 = -max; } if (_tweening == 2 && _bouncebackEffect) { if (newValue > 20 + threshold1 && _tweenChange[axis] > 0 || newValue > threshold1 && _tweenChange[axis] == 0)//开始回弹 { _tweenTime[axis] = 0; _tweenDuration[axis] = TWEEN_TIME_DEFAULT; _tweenChange[axis] = -newValue + threshold1; _tweenStart[axis] = newValue; } else if (newValue < threshold2 - 20 && _tweenChange[axis] < 0 || newValue < threshold2 && _tweenChange[axis] == 0)//开始回弹 { _tweenTime[axis] = 0; _tweenDuration[axis] = TWEEN_TIME_DEFAULT; _tweenChange[axis] = threshold2 - newValue; _tweenStart[axis] = newValue; } } else { if (newValue > threshold1) { newValue = threshold1; _tweenChange[axis] = 0; } else if (newValue < threshold2) { newValue = threshold2; _tweenChange[axis] = 0; } } } else newValue = _container[axis]; return newValue; } private static function easeFunc(t:Number, d:Number):Number { return (t = t / d - 1) * t * t + 1;//cubicOut } } }
/* * Licensed under the MIT License * * Copyright 2010 (c) Flávio Silva, http://flsilva.com * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * http://www.opensource.org/licenses/mit-license.php */ package org.as3collections { import org.as3collections.IIterator; /** * An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. * <p>Note that the <code>remove</code> and <code>set</code> methods are defined to operate on the last element returned by a call to <code>next</code> or <code>previous</code>.</p> * * @author Flávio Silva */ public interface IListIterator extends IIterator { /** * Inserts the specified element into the list (optional operation). The element is inserted immediately before the next element that would be returned by <code>next</code>, if any, and after the next element that would be returned by <code>previous</code>, if any. (If the list contains no elements, the new element becomes the sole element on the list.) The new element is inserted before the implicit cursor: a subsequent call to <code>next</code> would be unaffected, and a subsequent call to <code>previous</code> would return the new element. (This call increases by one the value that would be returned by a call to <code>nextIndex</code> or <code>previousIndex</code>.) * * @param element the element to add. * @throws org.as3collections.errors.ConcurrentModificationError if the list was changed directly (without using the iterator) during iteration. * @return <code>true</code> if the list has changed as a result of the call. Returns <code>false</code> if the list does not permit duplicates and already contains the specified element. */ function add(element:*): Boolean; /** * Returns <code>true</code> if the iteration has more elements when traversing the list in the reverse direction. * * @return <code>true</code> if the iteration has more elements when traversing the list in the reverse direction. */ function hasPrevious(): Boolean; /** * Returns the index of the element that would be returned by a subsequent call to <code>next</code>. (Returns list size if the list iterator is at the end of the list.) * * @return the index of the element that would be returned by a subsequent call to <code>next</code>, or list size if list iterator is at end of list. */ function nextIndex(): int; /** * Returns the previous element in the iteration. * * @throws org.as3collections.errors.NoSuchElementError if the iteration has no previous elements. * @throws org.as3collections.errors.ConcurrentModificationError if the list was changed directly (without using the iterator) during iteration. * @return the previous element in the iteration. */ function previous(): *; /** * Returns the index of the element that would be returned by a subsequent call to <code>previous</code>. (Returns -1 if the list iterator is at the beginning of the list.) * * @return the index of the element that would be returned by a subsequent call to <code>previous</code>, or -1 if list iterator is at beginning of list. */ function previousIndex(): int; /** * Replaces the last element returned by <code>next</code> or <code>previous</code> with the specified element (optional operation). This call can be made only if neither <code>IListIterator.remove</code> nor <code>IListIterator.add</code> have been called after the last call to <code>next</code> or <code>previous</code>. * * @param element the element with which to replace the last element returned by <code>next</code> or <code>previous</code>. * @throws org.as3coreaddendum.errors.UnsupportedOperationError if the <code>set</code> operation is not supported by this iterator. * @throws org.as3coreaddendum.errors.ClassCastError if the class of the specified element prevents it from being added to this list. * @throws org.as3coreaddendum.errors.IllegalStateError if neither <code>next</code> or <code>previous</code> have been called, or <code>remove</code> or <code>add</code> have been called after the last call to <code>next</code> or <code>previous</code>. */ function set(element:*): void; } }
package gs.preloading { import gs.events.AssetCompleteEvent; import gs.events.AssetErrorEvent; import gs.events.AssetOpenEvent; import gs.events.AssetProgressEvent; import gs.events.AssetStatusEvent; import gs.events.PreloadProgressEvent; import gs.managers.AssetManager; import gs.preloading.workers.Worker; import flash.events.Event; import flash.events.EventDispatcher; import flash.system.ApplicationDomain; import flash.system.LoaderContext; import flash.utils.setTimeout; /** * Dispatched for each asset that has completed downloading. * * @eventType gs.events.AssetCompleteEvent */ [Event("assetComplete", type="gs.events.AssetCompleteEvent")] /** * Dispatched for each asset that has started downloading. * * @eventType gs.events.AssetOpenEvent */ [Event("assetOpen", type="gs.events.AssetOpenEvent")] /** * Dispatched for each asset that has has stopped downloading because of an error. * * @eventType gs.events.AssetErrorEvent */ [Event("assetError", type="gs.events.AssetErrorEvent")] /** * Dispatched for each asset that is downloading. * * @eventType gs.support.preloading.events.AssetProgressEvent */ [Event("assetProgress", type="gs.support.preloading.events.AssetProgressEvent")] /** * Dispatched for each asset that generated an http status code other than 0 or 200. * * @eventType gs.events.AssetStatusEvent */ [Event("assetStatus", type="gs.events.AssetStatusEvent")] /** * Dispatched on progress of the entire Preloader progress. * * @eventType gs.events.PreloadProgressEvent */ [Event("preloadProgress", type="gs.events.PreloadProgressEvent")] /** * Dispatched when the Preloader completes downloading all assets in the queue. * * @eventType flash.events.Event */ [Event("complete", type="flash.events.Event")] /** * The Preloader class is a controller you use for loading assets. * * <p>It provides you with methods for starting, stopping, pausing, resuming * and prioritizing of assets, and registers all loaded assets with the asset manager.</p> * * <p>By default, the Preloader loads all swf's and bitmap's into the same * application domain. Unless specified otherwise in the constructor.</p> * * <p><b>Examples</b> are in the guttershark repository.</p> * * @see gs.managers.AssetManager */ final public class Preloader extends EventDispatcher { /** * The number of loaded items in this instance of the Preloader. */ private var loaded:int; /** * Number of errors in this instance. */ private var loadErrors:int; /** * An array of items to be loaded. */ private var loadItems:Array; /** * A duplicate of the original load items. Used internally. */ private var loadItemsDuplicate:Array; /** * The currently loading item. */ private var currentItem:Asset; /** * A pool of total bytes from each item that is loading * in this instance. */ private var bytesTotalPool:Array; /** * A loading pool, each item that is loading has an * entry in this pool, the entry is it's bytesLoaded. */ private var bytesLoadedPool:Array; /** * Stores loading item info (bl / bt) */ private var loadingItemsPool:Array; /** * The total pixels to fill for this preloader. */ private var totalPixelsToFill:int; /** * Flag used for pausing and resuming */ private var _working:Boolean; /** * The last percent update that was dispatched. */ private var lastPercentUpdate:Number; /** * The last pixel update that was dispatched. */ private var lastPixelUpdate:Number; /** * The last asset that loaded. */ private var lastCompleteAsset:Asset; /** * The loader context for all loading. */ private var loaderContext:LoaderContext; /** * How many pixels are full. */ private var _pixelsFull:Number; private var _percentLoaded:Number; /** * Last calculated kbps. */ private var lastkbps:Number; /** * Constructor for Preloader instances. * * @param pixelsToFill The total number of pixels this preloader needs to fill - this is used in calculating both pixels and percent. * @param loaderContext The loader context for all assets being loaded with this Preloader. */ public function Preloader(pixelsToFill:int=100,loaderContext:LoaderContext=null) { if(pixelsToFill<=0)throw new ArgumentError("Pixels to fill must be greater than zero."); Worker.RegisterDefaultWorkers(); if(!loaderContext)this.loaderContext=new LoaderContext(false,ApplicationDomain.currentDomain); else this.loaderContext=loaderContext; this.loaderContext.checkPolicyFile=true; totalPixelsToFill=pixelsToFill; bytesTotalPool=[]; bytesLoadedPool=[]; loadingItemsPool=[]; loadItems=[]; loaded=0; loadErrors=0; _working=false; _pixelsFull=0; _percentLoaded=0; } /** * Kilobytes per second of the currently loading asset. */ public function get kbps():Number { if(!currentItem&&lastkbps)return lastkbps; if(!currentItem&&isNaN(lastkbps))return -1; lastkbps=currentItem.kbps; return lastkbps; } /** * Add items to the controller to load - if the preloader is currently working, * these items will be appended to the items to load. * * @param items An array of Asset instances. */ public function addItems(items:Array):void { if(!items)return; if(!items[0])return; if(!this.loadItems[0])this.loadItems=items.concat(); else this.loadItems = this.loadItems.concat(items.concat()); loadItemsDuplicate=loadItems.concat(); } /** * Add items to the controller to load, with top priority. * * @param items An array of Asset instances. */ public function addPrioritizedItems(items:Array):void { if(!items)return; if(!items[0])return; if(!this.loadItems[0])this.loadItems=items.concat(); else { var l:int=items.length; var i:int=0; for(;i<l;i++)this.loadItems.unshift(items[int(i)]); } loadItemsDuplicate=loadItems.concat(); } /** * Starts loading the assets, and resumes loading from a stopped state. */ public function start():void { if(!loadItems[0]) { trace("WARNING: No assets are in the preloader, no preloading will start."); return; } _working=true; load(); } /** * Stops the preloader and closes the current loading assets. */ public function stop():void { currentItem=null; _working=false; } /** * Pause the preloader. * * <p>The current item will finish loading but not continue until you start it again.</p> */ public function pause():void { _working=false; } /** * Indicates whether or not this controller is doing any preloading. */ public function get working():Boolean { return _working; } /** * The number of items left in the preload queue. */ public function get numLeft():int { return (currentItem?1:0)+loadItems.length; } /** * @private */ public function set pixelsFull(pixels:Number):void { if(_pixelsFull==pixels)return; _pixelsFull=pixels; } /** * Returns the pixels full, based off of how much * has downloaded, and how many pixelsToFill. For * example - if the pixels to fill is 100, and 10% * of the download is complete, this will return 10. */ public function get pixelsFull():Number { return _pixelsFull; } public function get percentLoaded():Number { return _percentLoaded; } /** * Set the number of pixels to fill, useful if * the pixel calculations need to change. */ public function set pixelsToFill(px:int):void { totalPixelsToFill=px; } /** * The number of pixels that should be filled. */ public function get pixelsToFill():int { return totalPixelsToFill; } /** * The last completed asset. */ public function get lastCompletedAsset():Asset { return lastCompleteAsset; } /** * Prioritize an asset. * * @param asset An asset instance that's in the queue to be loaded. */ public function prioritize(asset:Asset):void { if(!asset)return; if(!asset.source||!asset.libraryName)throw new Error("Both a source and an id must be provided on the Asset to prioritize."); var l:int=loadItems.length; var i:int=0; for(;i<l;i++) { var item:Asset=Asset(loadItems[int(i)]); if(item.source==asset.source) { var litem:Asset=loadItems.splice(int(i),1)[0] as Asset; loadItems.unshift(litem); return; } } } /** * Recursively called to load each item in the queue. */ private function load():void { if(!_working)return; var item:Asset=Asset(this.loadItems.shift()); currentItem=item; loadingItemsPool[item.source]=item; item.load(this,loaderContext); } /** * Internal method used to send out updates. */ private function updateStatus():void { var pixelPool:Number=0; var pixelContributionPerItem:Number=Math.ceil(totalPixelsToFill/(loadItemsDuplicate.length-loadErrors)); var pixelUpdate:Number; var percentUpdate:Number; var key:String; for(key in loadingItemsPool) { var bl:* =bytesLoadedPool[key]; var bt:* =bytesTotalPool[key]; if(bl==undefined||bt==undefined)continue; var pixelsForItem:Number=Math.ceil((bl/bt)*pixelContributionPerItem); //trace("update: key: " + key + " bl: " + bl.toString() + " bt: " + bt.toString() + " pixelsForItem: " + pixelsForItem); pixelPool+=pixelsForItem; } pixelUpdate=pixelPool; percentUpdate=Math.ceil((pixelPool/totalPixelsToFill)*100); if(lastPixelUpdate>0&&lastPercentUpdate>0&&lastPixelUpdate==pixelUpdate&&lastPercentUpdate==percentUpdate)return; if(pixelUpdate>=pixelsToFill)return; lastPixelUpdate=pixelUpdate; lastPercentUpdate=percentUpdate; this.pixelsFull=pixelUpdate; this._percentLoaded=percentUpdate; dispatchEvent(new PreloadProgressEvent(PreloadProgressEvent.PROGRESS,pixelUpdate,percentUpdate)); } /** * This is used to check the status of this preloader. */ private function updateLoading():void { if(loadItems.length>0)load(); else if((loaded+loadErrors)>=(loadItems.length)) { _working=false; pixelsFull=totalPixelsToFill; currentItem = null; dispatchEvent(new PreloadProgressEvent(PreloadProgressEvent.PROGRESS,totalPixelsToFill,100)); dispatchEvent(new Event(Event.COMPLETE)); setTimeout(reset,150); //new FrameDelay(reset,2); } } /** * Resets internal state so the Preloader * can be re-used if needed. */ public function reset():void { loadErrors=0; loaded=0; loadItems=[]; loadItemsDuplicate=[]; bytesTotalPool=[]; bytesLoadedPool=[]; currentItem=null; lastCompleteAsset=null; } /** * Dispose of this preloader. */ public function dispose():void { loadErrors=0; loaded=0; loadItems=null; loadItemsDuplicate=null; bytesTotalPool=null; bytesLoadedPool=null; currentItem=null; lastCompleteAsset=null; loaderContext=null; } /** * @private * * Every Asset in the queue calls this method on it's progress event. * * @param pe AssetProgressEvent */ public function progress(pe:AssetProgressEvent):void { var item:Asset=Asset(pe.asset); var source:String=pe.asset.source; if(item.bytesTotal<0||isNaN(item.bytesTotal))return; else if(item.bytesLoaded<0||isNaN(item.bytesLoaded))return; bytesTotalPool[source]=item.bytesTotal; bytesLoadedPool[source]=item.bytesLoaded; dispatchEvent(new AssetProgressEvent(AssetProgressEvent.PROGRESS,pe.asset)); updateStatus(); } /** * @private * * Each item calls this method on it's complete. * * @param e AssetCompleteEvent */ public function complete(e:AssetCompleteEvent):void { loaded++; lastCompleteAsset=e.asset; AssetManager.addAsset(e.asset.libraryName,e.asset.data,e.asset.source); dispatchEvent(new AssetCompleteEvent(AssetCompleteEvent.COMPLETE,e.asset)); updateStatus(); updateLoading(); currentItem=null; } /** * @private * * Each item calls this method on any load errors. * * @param e AssetErrorEvent */ public function error(e:AssetErrorEvent):void { trace("Error loading: "+e.asset.source); loadErrors++; updateStatus(); updateLoading(); dispatchEvent(new AssetErrorEvent(AssetErrorEvent.ERROR,e.asset)); } /** * @private * * Each item calls this method on an http status that is * not 0 or 200. * * @param e AssetStatusEvent */ public function httpStatus(e:AssetStatusEvent):void { trace("Error loading: "+e.asset.source); loadErrors++; updateStatus(); updateLoading(); dispatchEvent(new AssetStatusEvent(AssetStatusEvent.STATUS,e.asset,e.status)); } /** * @private * * Each item calls this method when it starts downloading. * * @param e AssetOpenEvent */ public function open(e:AssetOpenEvent):void { dispatchEvent(new AssetOpenEvent(AssetOpenEvent.OPEN,e.asset)); } } }
/* */ package elements.axis { import flash.display.Sprite; import flash.text.TextField; import flash.geom.Rectangle; public class AxisLabel extends TextField { public var xAdj:Number = 0; public var yAdj:Number = 0; public var leftOverhang:Number = 0; public var rightOverhang:Number = 0; public var xVal:Number = NaN; public var yVal:Number = NaN; public function AxisLabel() {} /** * Rotate the label and align it to the X Axis tick * * @param rotation */ public function rotate_and_align( rotation:Number, align:String, parent:Sprite ): void { rotation = rotation % 360; if (rotation < 0) rotation += 360; var myright:Number = this.width * Math.cos(rotation * Math.PI / 180); var myleft:Number = this.height * Math.cos((90 - rotation) * Math.PI / 180); var mytop:Number = this.height * Math.sin((90 - rotation) * Math.PI / 180); var mybottom:Number = this.width * Math.sin(rotation * Math.PI / 180); if (((rotation % 90) == 0) || (align == "center")) { this.xAdj = (myleft - myright) / 2; } else { this.xAdj = (rotation < 180) ? myleft / 2 : -myright + (myleft / 2); } if (rotation > 90) { this.yAdj = -mytop; } if (rotation > 180) { this.yAdj = -mytop - mybottom; } if (rotation > 270) { this.yAdj = - mybottom; } this.rotation = rotation; var titleRect:Rectangle = this.getBounds(parent); this.leftOverhang = Math.abs(titleRect.x + this.xAdj); this.rightOverhang = Math.abs(titleRect.x + titleRect.width + this.xAdj); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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 skins.spark.mobile { import spark.components.ActionBar; import spark.components.Group; import spark.components.ViewNavigator; import spark.skins.mobile.supportClasses.MobileSkin; /** * The ActionScript-based skin for view navigators in mobile * applications. This skin lays out the action bar and content * group in a vertical fashion, where the action bar is on top. * This skin also supports navigator overlay modes. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class ViewNavigatorSkin extends MobileSkin { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function ViewNavigatorSkin() { super(); } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** * @copy spark.components.SkinnableContainer#contentGroup */ public var contentGroup:Group; /** * @copy spark.components.ViewNavigator#actionBar */ public var actionBar:ActionBar; //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- /** * @copy spark.skins.spark.ApplicationSkin#hostComponent */ public var hostComponent:ViewNavigator; //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- private var _isOverlay:Boolean; /** * @private */ override protected function createChildren():void { contentGroup = new Group(); contentGroup.id = "contentGroup"; actionBar = new ActionBar(); actionBar.id = "actionBar"; addChild(contentGroup); addChild(actionBar); } /** * @private */ override protected function measure():void { super.measure(); measuredWidth = Math.max(actionBar.getPreferredBoundsWidth(), contentGroup.getPreferredBoundsWidth()); if (currentState == "portraitAndOverlay" || currentState == "landscapeAndOverlay") { measuredHeight = Math.max(actionBar.getPreferredBoundsHeight(), contentGroup.getPreferredBoundsHeight()); } else { measuredHeight = actionBar.getPreferredBoundsHeight() + contentGroup.getPreferredBoundsHeight(); } } /** * @private */ override protected function commitCurrentState():void { super.commitCurrentState(); _isOverlay = (currentState.indexOf("Overlay") >= 1); // Force a layout pass on the components invalidateProperties(); invalidateSize(); invalidateDisplayList(); } /** * @private */ override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void { super.layoutContents(unscaledWidth, unscaledHeight); var actionBarHeight:Number = 0; // The action bar is always placed at 0,0 and stretches the entire // width of the navigator if (actionBar.includeInLayout) { actionBarHeight = Math.min(actionBar.getPreferredBoundsHeight(), unscaledHeight); actionBar.setLayoutBoundsSize(unscaledWidth, actionBarHeight); actionBar.setLayoutBoundsPosition(0, 0); actionBarHeight = actionBar.getLayoutBoundsHeight(); // update ActionBar backgroundAlpha when in overlay mode var backgroundAlpha:Number = (_isOverlay) ? 0.75 : 1; actionBar.setStyle("backgroundAlpha", backgroundAlpha); } if (contentGroup.includeInLayout) { // If the hostComponent is in overlay mode, the contentGroup extends // the entire bounds of the navigator and the alpha for the action // bar changes // If this changes, also update validateEstimatedSizesOfChild var contentGroupHeight:Number = (_isOverlay) ? unscaledHeight : Math.max(unscaledHeight - actionBarHeight, 0); var contentGroupPosition:Number = (_isOverlay) ? 0 : actionBarHeight; contentGroup.setLayoutBoundsSize(unscaledWidth, contentGroupHeight); contentGroup.setLayoutBoundsPosition(0, contentGroupPosition); } } } }
package com.axiomalaska.crks.dto { // Generated May 25, 2011 4:36:19 PM by Hibernate Tools 3.2.2.GA [Bindable] [RemoteClass(alias="com.axiomalaska.crks.dto.SupportedEpsgDTO")] public class SupportedEpsg extends SupportedEpsgGenerated{ } }
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.geom.Rectangle; import robotlegs.bender.bundles.mvcs.MVCSBundle; import robotlegs.bender.extensions.contextView.ContextView; import robotlegs.bender.extensions.signalCommandMap.SignalCommandMapExtension; import robotlegs.bender.extensions.starling.StarlingExtension; import robotlegs.bender.framework.api.IContext; import robotlegs.bender.framework.impl.Context; import starling.core.Starling; import starling.events.Event; import zenith.commons.ZenithConfig; import zenith.context.game.GameConfig; import zenith.context.title.TitleConfig; public class Zenith extends Sprite { private var _context:IContext; private var _starling:Starling; public function Zenith() { super(); stage.frameRate = 60; stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; _starling = new Starling(StarlingRootSprite, stage, new Rectangle(0, 0, stage.fullScreenWidth, stage.fullScreenHeight)); _starling.stage.stageWidth = 640; _starling.stage.stageHeight = 640 * (stage.fullScreenHeight / stage.fullScreenWidth); _starling.start(); var root:Sprite = this; _starling.addEventListener(starling.events.Event.ROOT_CREATED, function():void { _context = new Context() .install(MVCSBundle) .install(SignalCommandMapExtension) .install(StarlingExtension) .configure(_starling, ZenithConfig, TitleConfig, GameConfig) .configure(new ContextView(root)); _context.initialize(); }); } } }
/** * MultiTween by Grant Skinner. August 12, 2005 * Visit www.gskinner.com/blog for documentation, updates and more free code. * * You may distribute this class freely, provided it is not modified in any way (including * removing this header or changing the package path). * * Please contact info@gskinner.com prior to distributing modified versions of this class. */ class com.gskinner.transitions.MultiTween { // public properties: public var props:Object; // private properties: private var _position:Number; private var propList:Array; private var startVals:Object; private var targetObj:Object; private var endVals:Object; // initialization: public function MultiTween(p_targetObj:Object,p_endVals:Object,p_propList:Array,p_props:Object) { props = p_props; if (p_propList == undefined) { p_propList = []; if (p_targetObj instanceof Array) { var l:Number = p_endVals.length; for (var i:Number=0;i<l;i++) { p_propList.push(i.toString()); } } else { for (var n:String in p_endVals) { p_propList.push(n); } } } targetObj = p_targetObj; startVals = {}; endVals = {}; var l:Number = p_propList.length; propList = []; for (var i:Number=0;i<l;i++) { var prop:String = p_propList[i]; var sv:Number = (p_targetObj[prop] == undefined)?0:Number(p_targetObj[prop]); var ev:Number = (p_endVals[prop] == undefined)?0:Number(p_endVals[prop]); if (isNaN(sv) || isNaN(ev) || sv == ev) { continue; } startVals[prop] = sv; endVals[prop] = ev; propList.push(prop); } _position = 0; } // public methods: public function setPosition(p_position:Number):Void { _position = p_position; // move objects to local scope to make them faster to work with: var targObj:Object = targetObj; var svs:Object = startVals; var evs:Object = endVals; var pl:Array = propList; var l:Number = propList.length; for (var i:Number=0;i<l;i++) { var prop:String = propList[i]; var sv:Number = svs[prop]; targObj[prop] = sv+(evs[prop]-sv)*_position; } } // getter / setters: public function get position():Number { return _position; } public function set position(p_position:Number):Void { setPosition(p_position); } }
package { public class Foo { public function foo() : void { new <int>[].$(EntryPoint) } } }
package laya.d3.component { import laya.ani.AnimationPlayer; import laya.ani.AnimationState; import laya.ani.AnimationTemplet; import laya.d3.animation.AnimationClip; import laya.d3.component.animation.SkinAnimations; import laya.d3.core.Sprite3D; import laya.d3.core.render.RenderState; import laya.d3.math.Matrix4x4; import laya.events.Event; /**完成挂点更新时调度。 * @eventType Event.COMPLETE * */ [Event(name = "complete", type = "laya.events.Event")] /** * <code>AttachPoint</code> 类用于创建挂点组件。 */ public class AttachPoint extends Component3D { /** @private */ protected var _attachSkeleton:SkinAnimations; /** @private */ protected var _extenData:Float32Array; /**挂点骨骼的名称。*/ public var attachBones:Vector.<String>; /**挂点骨骼的变换矩阵。*/ public var matrixs:Vector.<Matrix4x4>; /** * 创建一个新的 <code>AttachPoint</code> 实例。 */ public function AttachPoint() { attachBones = new Vector.<String>(); matrixs = new Vector.<Matrix4x4>(); } /** * @private * 初始化载入挂点组件。 * @param owner 所属精灵对象。 */ override public function _load(owner:Sprite3D):void { super._load(owner); _attachSkeleton = owner.getComponentByType(SkinAnimations) as SkinAnimations; } /** * @private * 更新挂点组件。 * @param state 渲染状态。 */ public override function _update(state:RenderState):void { if (!_attachSkeleton||_attachSkeleton.destroyed || _attachSkeleton.player.state === AnimationState.stopped || !_attachSkeleton.curBonesDatas) return; var player:AnimationPlayer = _attachSkeleton.player; var templet:AnimationTemplet = _attachSkeleton.templet; matrixs.length = attachBones.length; var boneDatas:Float32Array = _attachSkeleton.curBonesDatas; var worldMatrix:Matrix4x4 = owner.transform.worldMatrix; for (var i:int, n:int = attachBones.length; i < n; i++) { var startIndex:int = templet.getNodeIndexWithName(player.currentAnimationClipIndex, attachBones[i]) * 16; var matrix:Matrix4x4 = matrixs[i]; matrix || (matrix = matrixs[i] = new Matrix4x4()); var matrixE:Float32Array = matrix.elements; for (var j:int = 0; j < 16; j++) matrixE[j] = boneDatas[startIndex + j]; Matrix4x4.multiply(worldMatrix, matrix, matrix); } event(Event.COMPLETE); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.printing { import flash.events.KeyboardEvent; import mx.collections.CursorBookmark; import mx.controls.AdvancedDataGrid; import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn; import mx.core.EdgeMetrics; import mx.core.ScrollPolicy; import mx.core.mx_internal; import mx.events.AdvancedDataGridEvent; use namespace mx_internal; //-------------------------------------- // Excluded APIs //-------------------------------------- //-------------------------------------- // public properties //-------------------------------------- [Exclude(name="allowDragSelection", kind="property")] [Exclude(name="allowMultipleSelection", kind="property")] [Exclude(name="dataTipField", kind="property")] [Exclude(name="dataTipFunction", kind="property")] [Exclude(name="doubleClickEnabled", kind="property")] [Exclude(name="dragEnabled", kind="property")] [Exclude(name="draggableColumns", kind="property")] [Exclude(name="dragMoveEnabled", kind="property")] [Exclude(name="dropEnabled", kind="property")] [Exclude(name="dropTarget", kind="property")] [Exclude(name="editable", kind="property")] [Exclude(name="editedItemPosition", kind="property")] [Exclude(name="editedItemRenderer", kind="property")] [Exclude(name="horizontalScrollBar", kind="property")] [Exclude(name="horizontalScrollPolicy", kind="property")] [Exclude(name="maxHorizontalScrollPosition", kind="property")] [Exclude(name="maxVerticalScrollPosition", kind="property")] [Exclude(name="scrollTipFunction", kind="property")] [Exclude(name="selectable", kind="property")] [Exclude(name="selectedIndex", kind="property")] [Exclude(name="selectedIndices", kind="property")] [Exclude(name="selectedItem", kind="property")] [Exclude(name="selectedItems", kind="property")] [Exclude(name="showScrollTips", kind="property")] [Exclude(name="toolTip", kind="property")] [Exclude(name="useHandCursor", kind="property")] [Exclude(name="verticalScrollBar", kind="property")] [Exclude(name="verticalScrollPolicy", kind="property")] //-------------------------------------- // protected properties //-------------------------------------- [Exclude(name="anchorBookmark", kind="property")] [Exclude(name="anchorIndex", kind="property")] [Exclude(name="caretBookmark", kind="property")] [Exclude(name="caretIndex", kind="property")] [Exclude(name="caretIndicator", kind="property")] [Exclude(name="caretItemRenderer", kind="property")] [Exclude(name="caretUID", kind="property")] [Exclude(name="dragImage", kind="property")] [Exclude(name="dragImageOffsets", kind="property")] [Exclude(name="highlightIndicator", kind="property")] [Exclude(name="highlightUID", kind="property")] [Exclude(name="keySelectionPending", kind="property")] [Exclude(name="lastDropIndex", kind="property")] [Exclude(name="selectionLayer", kind="property")] [Exclude(name="selectionTweens", kind="property")] [Exclude(name="showCaret", kind="property")] //-------------------------------------- // public methods //-------------------------------------- [Exclude(name="calculateDropIndex", kind="method")] [Exclude(name="createItemEditor", kind="method")] [Exclude(name="destroyItemEditor", kind="method")] [Exclude(name="effectFinished", kind="method")] [Exclude(name="effectStarted", kind="method")] [Exclude(name="endEffectStarted", kind="method")] [Exclude(name="hideDropFeedback", kind="method")] [Exclude(name="isItemHighlighted", kind="method")] [Exclude(name="isItemSelected", kind="method")] [Exclude(name="showDropFeedback", kind="method")] [Exclude(name="startDrag", kind="method")] //-------------------------------------- // protected methods //-------------------------------------- [Exclude(name="dragCompleteHandler", kind="method")] [Exclude(name="dragDropHandler", kind="method")] [Exclude(name="dragEnterHandler", kind="method")] [Exclude(name="dragExitHandler", kind="method")] [Exclude(name="dragOverHandler", kind="method")] [Exclude(name="dragScroll", kind="method")] [Exclude(name="drawCaretIndicator", kind="method")] [Exclude(name="drawHighlightIndicator", kind="method")] [Exclude(name="drawSelectionIndicator", kind="method")] [Exclude(name="mouseClickHandler", kind="method")] [Exclude(name="mouseDoubleClickHandler", kind="method")] [Exclude(name="mouseDownHandler", kind="method")] [Exclude(name="mouseEventToItemRenderer", kind="method")] [Exclude(name="mouseMoveHandler", kind="method")] [Exclude(name="mouseOutHandler", kind="method")] [Exclude(name="mouseOverHandler", kind="method")] [Exclude(name="mouseUpHandler", kind="method")] [Exclude(name="mouseWheelHandler", kind="method")] [Exclude(name="moveSelectionHorizontally", kind="method")] [Exclude(name="moveSelectionVertically", kind="method")] [Exclude(name="placeSortArrow", kind="method")] [Exclude(name="removeIndicators", kind="method")] [Exclude(name="selectItem", kind="method")] [Exclude(name="setScrollBarProperties", kind="method")] [Exclude(name="expandItemHandler", kind="method")] //-------------------------------------- // events //-------------------------------------- [Exclude(name="click", kind="event")] [Exclude(name="doubleClick", kind="event")] [Exclude(name="dragComplete", kind="event")] [Exclude(name="dragDrop", kind="event")] [Exclude(name="dragEnter", kind="event")] [Exclude(name="dragExit", kind="event")] [Exclude(name="dragOver", kind="event")] [Exclude(name="effectEnd", kind="event")] [Exclude(name="effectStart", kind="event")] [Exclude(name="headerRelease", kind="event")] [Exclude(name="itemClick", kind="event")] [Exclude(name="itemDoubleClick", kind="event")] [Exclude(name="itemEditBegin", kind="event")] [Exclude(name="itemEditBeginning", kind="event")] [Exclude(name="itemEditEnd", kind="event")] [Exclude(name="itemFocusIn", kind="event")] [Exclude(name="itemFocusOut", kind="event")] [Exclude(name="itemRollOut", kind="event")] [Exclude(name="itemRollOver", kind="event")] [Exclude(name="keyDown", kind="event")] [Exclude(name="keyUp", kind="event")] [Exclude(name="mouseDown", kind="event")] [Exclude(name="mouseDownOutside", kind="event")] [Exclude(name="mouseFocusChange", kind="event")] [Exclude(name="mouseMove", kind="event")] [Exclude(name="mouseOut", kind="event")] [Exclude(name="mouseOver", kind="event")] [Exclude(name="mouseUp", kind="event")] [Exclude(name="mouseWheel", kind="event")] [Exclude(name="mouseWheelOutside", kind="event")] [Exclude(name="rollOut", kind="event")] [Exclude(name="rollOver", kind="event")] [Exclude(name="toolTipCreate", kind="event")] [Exclude(name="toolTipEnd", kind="event")] [Exclude(name="toolTipHide", kind="event")] [Exclude(name="toolTipShow", kind="event")] [Exclude(name="toolTipShown", kind="event")] [Exclude(name="toolTipStart", kind="event")] //-------------------------------------- // styles //-------------------------------------- [Exclude(name="columnDropIndicatorSkin", kind="style")] [Exclude(name="columnResizeSkin", kind="style")] [Exclude(name="dropIndicatorSkin", kind="style")] [Exclude(name="headerDragProxyStyleName", kind="style")] [Exclude(name="horizontalScrollBarStyleName", kind="style")] [Exclude(name="rollOverColor", kind="style")] [Exclude(name="selectionColor", kind="style")] [Exclude(name="selectionDisabledColor", kind="style")] [Exclude(name="selectionDuration", kind="style")] [Exclude(name="selectionEasingFunction", kind="style")] [Exclude(name="strechCursor", kind="style")] [Exclude(name="textRollOverColor", kind="style")] [Exclude(name="textSelectedColor", kind="style")] [Exclude(name="useRollOver", kind="style")] [Exclude(name="verticalScrollBarStyleName", kind="style")] //-------------------------------------- // effects //-------------------------------------- [Exclude(name="addedEffect", kind="effect")] [Exclude(name="creationCompleteEffect", kind="effect")] [Exclude(name="focusInEffect", kind="effect")] [Exclude(name="focusOutEffect", kind="effect")] [Exclude(name="hideEffect", kind="effect")] [Exclude(name="mouseDownEffect", kind="effect")] [Exclude(name="mouseUpEffect", kind="effect")] [Exclude(name="moveEffect", kind="effect")] [Exclude(name="removedEffect", kind="effect")] [Exclude(name="resizeEffect", kind="effect")] [Exclude(name="rollOutEffect", kind="effect")] [Exclude(name="rollOverEffect", kind="effect")] [Exclude(name="showEffect", kind="effect")] /** * The PrintAdvancedDataGrid control is an AdvancedDataGrid subclass that is styled * to show a table with line borders and is optimized for printing. * It can automatically size to properly fit its container, and removes * any partially displayed rows. * * @mxml * * <p>The <code>&lt;mx:PrintAdvancedDataGrid&gt;</code> tag inherits the tag attributes * of its superclass; however, you do not use the properties, styles, events, * and effects (or methods) associated with user interaction. * The <code>&lt;mx:PrintAdvancedDataGrid&gt;</code> tag adds the following tag attribute: * </p> * <pre> * &lt;mx:PrintAdvancedDataGrid * <b>Properties</b> * allowInteraction="true|false" * displayIcons="true|false" * sizeToPage="true|false" * source="null" * &gt; * ... * &lt;/mx:PrintAdvancedDataGrid&gt; * </pre> * * @see mx.printing.FlexPrintJob * @see mx.printing.PrintDataGrid * @see mx.controls.AdvancedDataGrid * * @includeExample examples/AdvancedPrintDataGridExample.mxml * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class PrintAdvancedDataGrid extends AdvancedDataGrid { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * <p>Constructs a PrintAdvancedDataGrid control with no scroll bars, user interactivity, * column sorting, resizing, drag scrolling, selection, or keyboard * interaction. * The default height is 100% of the container height, or the height * required to display all the data provider rows, whichever is smaller.</p> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function PrintAdvancedDataGrid() { super(); horizontalScrollPolicy = ScrollPolicy.OFF; verticalScrollPolicy = ScrollPolicy.OFF; sortableColumns = false; selectable = false; // to disable dragScrolling dragEnabled = true; resizableColumns = false; mouseChildren = false; super.percentHeight = 100; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Previous Page row count. */ private var previousPageRowCount:int = 0; /** * @private * Variable for storing the folderClosedIcon. */ private var folderClosedIconClass:Class; /** * @private * Variable for storing the folderOpenIcon. */ private var folderOpenIconClass:Class; /** * @private * Variable for storing the defaultLeafIcon. */ private var defaultLeafIconClass:Class; /** * @private * Storage variable for changes to displayIcons. */ private var displayIconsChanged:Boolean; //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- //---------------------------------- // height //---------------------------------- [Bindable("heightChanged")] [Inspectable(category="General")] [PercentProxy("percentHeight")] /** * @private * Getter needs to be overridden if setter is overridden. */ override public function get height():Number { return super.height; } /** * @private * Height setter needs to be overridden to update _originalHeight. */ override public function set height(value:Number):void { _originalHeight = value; if (!isNaN(percentHeight)) { super.percentHeight = NaN; measure(); value = measuredHeight; } super.height = value; invalidateDisplayList(); if (sizeToPage && !isNaN(explicitHeight)) explicitHeight = NaN; } //---------------------------------- // percentHeight //---------------------------------- [Bindable("resize")] [Inspectable(category="Size", defaultValue="NaN")] /** * @private * Getter needs to be overridden if setter is overridden. */ override public function get percentHeight():Number { return super.percentHeight; } /** * @private * percentHeight setter needs to be overridden to update _originalHeight. */ override public function set percentHeight(value:Number):void { _originalHeight = NaN; super.percentHeight = value; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // currentPageHeight //---------------------------------- /** * @private * Storage for the currentPageHeight property. */ private var _currentPageHeight:Number; /** * The height that the PrintAdvancedDataGrid would be if the <code>sizeToPage</code> * property is <code>true</code>, meaning that the PrintAdvancedDataGrid displays only completely * viewable rows and displays no partial rows. * If the <code>sizeToPage</code> property * is <code>false</code>, the value of this property equals * the <code>height</code> property. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get currentPageHeight():Number { return _currentPageHeight; } //---------------------------------- // displayIcons //---------------------------------- /** * @private * Indicates that the folder/leaf icons will be displayed or not. */ private var _displayIcons:Boolean = true; /** * If <code>true</code>, display the folder and leaf icons in the navigation tree. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get displayIcons():Boolean { return _displayIcons; } public function set displayIcons(value:Boolean):void { if (value != _displayIcons) { _displayIcons = value; displayIconsChanged = true; itemsSizeChanged = true; invalidateProperties(); invalidateSize(); invalidateDisplayList(); } } //---------------------------------- // allowInteraction //---------------------------------- /** * Storage for the allowInteraction property. * @private */ private var _allowInteraction:Boolean; /** * If <code>true</code>, allows some interactions with the control, * such as column resizing, column reordering, and expanding or collapsing nodes. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get allowInteraction():Boolean { return _allowInteraction; } public function set allowInteraction(value:Boolean):void { _allowInteraction = value; if(value) { mouseChildren = true; resizableColumns = true; } else { mouseChildren = false; resizableColumns = false; } } //---------------------------------- // originalHeight //---------------------------------- /** * Storage for the originalHeight property. * @private */ private var _originalHeight:Number; /** * The height of the PrintAdvancedDataGrid as set by the user. * If the <code>sizeToPage</code> property is <code>false</code>, * the value of this property equals the <code>height</code> property. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get originalHeight():Number { return _originalHeight; } //---------------------------------- // sizeToPage //---------------------------------- /** * If <code>true</code>, the PrintAdvancedDataGrid readjusts its height to display * only completely viewable rows. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var sizeToPage:Boolean = true; //---------------------------------- // source //---------------------------------- /** * @private * Source ADG. */ private var _source:AdvancedDataGrid; /** * Initializes the PrintAdvancedDataGrid control and all of its properties * from the specified AdvancedDataGrid control. * * <p><b>Note:</b> The width and height of the PrintAdvancedDataGrid control * are not taken from the source AdvancedDataGrid control. * Changes to the source AdvancedDataGrid control are not automatically reflected * in the PrintAdvancedDataGrid instance. * Therefore, you must reset the <code>source</code> property after changing * the source AdvancedDataGrid control.</p> * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get source():AdvancedDataGrid { return _source; } /** * @private */ public function set source(value:AdvancedDataGrid):void { _source = value; this.dataProvider = value.dataProvider; // set the dataProvider var i:int = 0; var n:int = 0; // assign groupedColumns only if Column Grouping // is present in the source AdvancedDataGrid if (value.groupedColumns != null) { var groupColumnsArray:Array = []; n = value.groupedColumns.length; for (i = 0; i < n; i++) { groupColumnsArray.push(value.groupedColumns[i].clone()); } this.groupedColumns = groupColumnsArray; } else { // assign the columns var columnArray:Array = []; n = value.columns != null ? value.columns.length : 0; for (i = 0; i < n; i++) { var sourceColumn:AdvancedDataGridColumn = value.columns[i]; var col:AdvancedDataGridColumn = sourceColumn.clone(); // check for treeColumn if (sourceColumn == value.treeColumn) this.treeColumn = col; columnArray.push(col); } this.columns = columnArray; } this.itemRenderer = value.itemRenderer; // set the itemRenderer this.headerRenderer = value.headerRenderer; // set the headerRenderer this.groupItemRenderer = value.groupItemRenderer; // set the groupItemRenderer this.rendererProviders = value.rendererProviders; // set the rendererProviders this.labelField = value.labelField; // set the labelField this.labelFunction = value.labelFunction; // set the labelFunction this.groupIconFunction = value.groupIconFunction; // set the groupIconFunction this.groupLabelFunction = value.groupLabelFunction; // set the groupLabelFunction this.displayDisclosureIcon = value.displayDisclosureIcon; // set displayDisclosureIcon this.displayItemsExpanded = value.displayItemsExpanded; // set displayItemsExpanded this.itemIcons = value.itemIcons; // set the itemsIcons this.lockedColumnCount = value.lockedColumnCount; // set lockecColumnCount this.lockedRowCount = value.lockedRowCount; // set lockedRowCount this.wordWrap = value.wordWrap; // set wordWrap this.variableRowHeight = value.variableRowHeight; // set variableRowHeight columnsInvalid = true; itemsSizeChanged = true; // invalidate everything invalidateProperties(); invalidateSize(); invalidateDisplayList(); } //---------------------------------- // validNextPage //---------------------------------- /** * Indicates that the data provider contains additional data rows that follow * the rows that the PrintAdvancedDataGrid control currently displays. * * @return A Boolean value of <code>true</code> if a set of rows is * available else <code>false</false>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get validNextPage():Boolean { var vPos:int = verticalScrollPosition + rowCount ; return dataProvider && vPos < dataProvider.length ? true : false; } //---------------------------------- // validPreviousPage //---------------------------------- /** * Indicates that the data provider contains data rows that precede * the rows that the PrintAdvancedDataGrid control currently displays. * * @return A Boolean value of <code>true</code> if a set of rows is * available else <code>false</false>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get validPreviousPage():Boolean { var vPos:int = verticalScrollPosition - previousPageRowCount ; return dataProvider && vPos >= 0 ? true : false; } //-------------------------------------------------------------------------- // // Overridden methods: UIComponent // //-------------------------------------------------------------------------- /** * @private * Checks the changes in displayIcons and update the display. */ override protected function commitProperties():void { super.commitProperties(); // set treeColumn in case of a column grouped AdvacnedDataGrid if (source && source.groupedColumns && source.treeColumn) { var n:int = source.columns.length; for (var i:int = 0; i < n; i++) { var sourceColumn:AdvancedDataGridColumn = source.columns[i]; if (sourceColumn == source.treeColumn) { this.treeColumn = this.columns[i]; break; } } } if(displayIconsChanged) { displayIconsChanged = false; if(displayIcons) { setStyle("defaultLeafIcon",defaultLeafIconClass); setStyle("folderClosedIcon",folderClosedIconClass); setStyle("folderOpenIcon",folderOpenIconClass); } else { // get the styles and store them folderClosedIconClass = getStyle("folderClosedIcon"); folderOpenIconClass = getStyle("folderOpenIcon"); defaultLeafIconClass = getStyle("defaultLeafIcon"); // set the folder/leaf icons to null setStyle("defaultLeafIcon",null); setStyle("folderClosedIcon",null); setStyle("folderOpenIcon",null); } } } /** * @private * Sets the default number of display rows to dataProvider.length. */ override protected function measure():void { var oldRowCount:uint = rowCount; var count:uint; count = (dataProvider) ? dataProvider.length : 0; // Headers should show even if there is no dataProvider if (count == 0 && headerVisible) count++; if (count >= verticalScrollPosition) count -= verticalScrollPosition; else count = 0; setRowCount(count); // need to calculate rowCount before super() super.measure(); measureHeight(); if (isNaN(_originalHeight)) _originalHeight = measuredHeight; _currentPageHeight = measuredHeight; if (!sizeToPage) { setRowCount(oldRowCount); super.measure(); } } /** * @private * setActualSize() is overridden to update _originalHeight. */ override public function setActualSize(w:Number, h:Number):void { if (!isNaN(percentHeight)) { _originalHeight = h; super.percentHeight = NaN; measure(); h = measuredHeight; } super.setActualSize(w, h); invalidateDisplayList(); if (sizeToPage && !isNaN(explicitHeight)) explicitHeight = NaN; } //-------------------------------------------------------------------------- // // Overridden methods: ListBase // //-------------------------------------------------------------------------- /** * @private * Overridden configureScrollBars to disable autoScrollUp. */ override protected function configureScrollBars():void { } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Puts the next set of data rows in view; * that is, it sets the PrintAdvancedDataGrid <code>verticalScrollPosition</code> * property to equal <code>verticalScrollPosition</code> + (number of scrollable rows). * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function nextPage():void { previousPageRowCount = rowCount - lockedRowCount; if (verticalScrollPosition < dataProvider.length) { verticalScrollPosition += rowCount - lockedRowCount; // TODO: can this be avoided? itemsSizeChanged = true; invalidateSize(); invalidateDisplayList(); } } /** * Puts the previous set of data rows in view; * that is, it sets the PrintAdvancedDataGrid <code>verticalScrollPosition</code> * property to equal <code>verticalScrollPosition</code> - (number of rows in the previous page). * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function previousPage():void { if (verticalScrollPosition > 0) { verticalScrollPosition = Math.max(0, (verticalScrollPosition - previousPageRowCount)); invalidateSize(); invalidateDisplayList(); } } /** * @private * ListBase.measure() does'nt calculate measuredHeight in required way * so have to add the code here. */ private function measureHeight():void { if( dataProvider && dataProvider.length > 0 && (verticalScrollPosition >= dataProvider.length)) { setRowCount(0); measuredHeight = 0; measuredMinHeight = 0; return; } var o:EdgeMetrics = viewMetrics; var rc:int = (explicitRowCount < 1) ? rowCount : explicitRowCount; var maxHeight:Number = isNaN(_originalHeight) ? -1 : _originalHeight - o.top - o.bottom; measuredHeight = measureHeightOfItemsUptoMaxHeight( -1, rc, maxHeight) + o.top + o.bottom; measuredMinHeight = measureHeightOfItemsUptoMaxHeight( -1, Math.min(rc, 2), maxHeight) + o.top + o.bottom; } /** * Moves to the first page of the PrintAdvancedDataGrid control, * which corresponds to the first set of visible rows. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function moveToFirstPage():void { // move the iterator to the first position // this is done because when nextPage() is called without // checking for validNextPage(), listItems becomes empty after the last page // and the iterator is not seeked to the desired position. iterator.seek(CursorBookmark.FIRST); verticalScrollPosition = 0; invalidateSize(); invalidateDisplayList(); } //-------------------------------------------------------------------------- // // Overridden event handlers: UIComponent // //-------------------------------------------------------------------------- /** * @private * Overridden keyDown to disable keyboard functionality. */ override protected function keyDownHandler(event:KeyboardEvent):void { } /** * @private * Overridden expandItemHandler to disable animation * and recalculate the height * when allowInteraction is false. */ override mx_internal function expandItemHandler(event:AdvancedDataGridEvent):void { event.animate = false; // no animation super.expandItemHandler(event); // we have to recalculate the height itemsSizeChanged = true; invalidateDisplayList(); invalidateSize(); invalidateProperties(); } } }
/* 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 service { import org.apache.royale.events.Event; import org.apache.royale.events.EventDispatcher; import org.apache.royale.net.HTTPConstants; import org.apache.royale.net.HTTPService; [Event(name="success", type="org.apache.royale.events.Event")] public class RobotService extends EventDispatcher { private var remoteService:HTTPService; private var _url:String = null; /** * constructor */ public function RobotService() { remoteService = new HTTPService(); remoteService.addEventListener(HTTPConstants.COMPLETE, completeHandler); _url = "api/robot/move"; } private function completeHandler(event:Event):void { dispatchEvent(new Event("success")); } public function moveForwardLeft():void { remoteService.url = _url + "?direction=forward-left"; remoteService.send(); } public function moveForward():void { remoteService.url = _url + "?direction=forward"; remoteService.send(); } public function moveForwardRight():void { remoteService.url = _url + "?direction=forward-right"; remoteService.send(); } public function turnLeft():void { remoteService.url = _url + "?direction=left"; remoteService.send(); } public function stop():void { remoteService.url = _url + "?direction=stop"; remoteService.send(); } public function turnRight():void { remoteService.url = _url + "?direction=right"; remoteService.send(); } public function moveBackwardLeft():void { remoteService.url = _url + "?direction=backward-left"; remoteService.send(); } public function moveBackward():void { remoteService.url = _url + "?direction=backward"; remoteService.send(); } public function moveBackwardRight():void { remoteService.url = _url + "?direction=backward-right"; remoteService.send(); } } }
/** * DesKeyTest * * A test class for DesKey * Copyright (c) 2007 Henri Torgemane * * See LICENSE.txt for full license information. */ package com.hurlant.crypto.tests { import com.hurlant.crypto.symmetric.DESKey; import com.hurlant.util.Hex; import flash.utils.ByteArray; public class DESKeyTest extends TestCase { public function DESKeyTest(h:ITestHarness) { super(h, "DESKey Test"); runTest(testECB,"DES ECB Test Vectors"); h.endTestCase(); } /** * Test vectors mostly grabbed from * http://csrc.nist.gov/publications/nistpubs/800-17/800-17.pdf * (Appendix A and B) * incomplete. */ public function testECB():void { var keys:Array = [ "3b3898371520f75e", // grabbed from the output of some js implementation out there "10316E028C8F3B4A", // appendix A vector "0101010101010101", // appendix B Table 1, round 0 "0101010101010101", // round 1 "0101010101010101", // 2 "0101010101010101", "0101010101010101", "0101010101010101", "0101010101010101", "0101010101010101", "0101010101010101", // round 8 "8001010101010101", // app B, tbl 2, round 0 "4001010101010101", "2001010101010101", "1001010101010101", "0801010101010101", "0401010101010101", "0201010101010101", "0180010101010101", "0140010101010101", // round 8 ]; var pts:Array = [ "0000000000000000", // js "0000000000000000", // App A "8000000000000000", // App B, tbl 1, rnd0 "4000000000000000", "2000000000000000", "1000000000000000", "0800000000000000", // rnd 4 "0400000000000000", "0200000000000000", "0100000000000000", "0080000000000000", // round 8 "0000000000000000", // App B, tbl2, rnd0 "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", // rnd 8 ]; var cts:Array = [ "83A1E814889253E0", // js "82DCBAFBDEAB6602", // App A "95F8A5E5DD31D900", // App b, tbl 1, rnd 0 "DD7F121CA5015619", "2E8653104F3834EA", "4BD388FF6CD81D4F", "20B9E767B2FB1456", "55579380D77138EF", "6CC5DEFAAF04512F", "0D9F279BA5D87260", "D9031B0271BD5A0A", // rnd 8 "95A8D72813DAA94D", // App B, tbl 2, rnd 0 "0EEC1487DD8C26D5", "7AD16FFB79C45926", "D3746294CA6A6CF3", "809F5F873C1FD761", "C02FAFFEC989D1FC", "4615AA1D33E72F10", "2055123350C00858", "DF3B99D6577397C8", // rnd 8 ]; for (var i:uint=0;i<keys.length;i++) { var key:ByteArray = Hex.toArray(keys[i]); var pt:ByteArray = Hex.toArray(pts[i]); var des:DESKey = new DESKey(key); des.encrypt(pt); var out:String = Hex.fromArray(pt).toUpperCase(); assert("comparing "+cts[i]+" to "+out, cts[i]==out); // now go back to plaintext des.decrypt(pt); out = Hex.fromArray(pt).toUpperCase(); assert("comparing "+pts[i]+" to "+out, pts[i]==out); } } } }
package com.catalystapps.gaf.data.config { /** * @author Programmer */ public class CStage { public var fps: uint; public var color: int; public var width: int; public var height: int; public function clone(source: Object): CStage { fps = source.fps; color = source.color; width = source.width; height = source.height; return this; } } }
package starline.player.panels.skin { import flash.display.*; import flash.net.URLRequest; import flash.text.TextField; import flash.text.TextFormat; import flash.text.TextFieldAutoSize; import flash.utils.Timer; import flash.filters.GlowFilter; import flash.events.*; import starline.player.components.ApplyBtn; import starline.player.components.BuyBtn; import starline.player.components.EyeBtn; /* * Guzhva Andrey * http://starline-studio.com * 07.01.2011 * MusicBox player | radio */ public class SkinLine extends Sprite { private var _parent:*; private var _root:*; // Vars public var n:uint; public var bid:uint; public var url:String; public var prev_url:String; public var price:uint; public var order:uint; public var teg:String; // Loader private var loader:Loader = new Loader(); private var request:URLRequest = new URLRequest(); // Interface private var rollOverBg_sp:Sprite = new Sprite(); private var square:Sprite = new Sprite(); private var loader_mc:Sprite = new Sprite(); public var buy_btn:BuyBtn = new BuyBtn(); public var apply_btn:ApplyBtn = new ApplyBtn(); private var eye_btn:EyeBtn = new EyeBtn(); public function SkinLine(_root:*, _parent:*, n:int, p:*):void { this._root = _root; this._parent = _parent; this.n = n; this.bid = p.bid; this.url= p.url; this.prev_url = p.prev_url; this.price = p.price; this.order = p.order; this.teg = p.teg; createInterface(); request.url = _root.server_url + "skins/" + prev_url; loader.load(request); loader.contentLoaderInfo.addEventListener(Event.COMPLETE,displayImage); // Listener addEventListener(MouseEvent.ROLL_OVER, selectOver); addEventListener(MouseEvent.ROLL_OUT, selectOut); buy_btn.addEventListener(MouseEvent.MOUSE_UP, onBuy); apply_btn.addEventListener(MouseEvent.MOUSE_UP, onApply); eye_btn.addEventListener(MouseEvent.MOUSE_UP, onEye); } // -------------------------------------------------------- loader private function displayImage(evt:Event):void { loader.alpha = 0; loader_mc.addChild(loader); addEventListener(Event.ENTER_FRAME, vanishing); } private function vanishing(event:Event):void { if (loader.alpha < 1) { loader.alpha += 0.1; }else { removeEventListener(Event.ENTER_FRAME, vanishing); } } // ---------------------------------------------------------------------------------Listener private function onBuy(e:MouseEvent): void { _root.player_mc.payBgFunction(bid, price); } private function onApply(e:MouseEvent): void { _root.player_mc.bg_mc.imgLoader(url); _root.send_server.saveBg(bid); } private function onEye(e:MouseEvent): void { _root.player_mc.bg_mc.eyeImgLoader(url); } // наведене мышки private function selectOver(event:MouseEvent):void { rollOverBg_sp.alpha = 0; } // отвидение мышки private function selectOut(event:MouseEvent):void { rollOverBg_sp.alpha = 0.1; } // ------------------------------------------------------------------------------- Interface private function createInterface():void { addChild(loader_mc); square.graphics.beginFill(0x0099FF); square.graphics.drawRoundRect(0, 0, 100, 100, 5); square.graphics.endFill(); addChild(square); loader_mc.mask = square; rollOverBg_sp.graphics.beginFill(0x000000); rollOverBg_sp.graphics.drawRoundRect(0, 0, 100, 100, 5); rollOverBg_sp.graphics.endFill(); rollOverBg_sp.alpha = 0.1; addChild(rollOverBg_sp); apply_btn.visible = (order == 1)? true: false; apply_btn.y = 74; addChild(apply_btn); buy_btn.visible = (order == 0)? true: false; buy_btn.price_txt.mouseEnabled = false; buy_btn.price_txt.height = 20; buy_btn.price_txt.htmlText = '<b>'+String(price)+'</b>'; buy_btn.y = 74; addChild(buy_btn); eye_btn.x = 70; eye_btn.y = 5; addChild(eye_btn); } } }
package com.arduino.boards { import flash.desktop.NativeProcessStartupInfo; import flash.filesystem.File; import com.arduino.BoardInfo; public class BoardLeonardo extends BoardInfo { public function BoardLeonardo() { super("atmega32u4", "avr109", 57600); } override public function getLibList(rootDir:File, result:Array):void { result.push(rootDir.resolvePath("hardware/arduino/avr/variants/leonardo")); } override public function getCompileArgList(result:Vector.<String>):void { result.push("-DARDUINO_AVR_LEONARDO"); result.push("-DUSB_VID=0x2341"); result.push("-DUSB_PID=0x8036"); result.push('-DUSB_MANUFACTURER="Unknown"'); result.push('-DUSB_PRODUCT="Arduino Leonardo"'); } override public function prepareUpload(taskList:Array, port:String):String { var info:NativeProcessStartupInfo = new NativeProcessStartupInfo(); info.executable = new File("C:/Windows/System32/cmd.exe"); info.arguments = new <String>["/c", "MODE " + port + ": BAUD=1200 PARITY=N DATA=8 STOP=1"]; taskList.push(info); return port; } } }
package core.mediator { import core.events.ModelEvent; import core.model.ParsedModel; import core.suppotClass._BaseMediator; import core.view.AnimationControlView; import flash.events.Event; import flash.events.MouseEvent; import mx.binding.utils.BindingUtils; public final class AnimationControlViewMediator extends _BaseMediator { [Inject] public var parsedModel:ParsedModel; [Inject] public var view:AnimationControlView; override public function initialize():void { super.initialize(); this.addContextListener(ModelEvent.PARSED_MODEL_DATA_CHANGE, modelHandler); this.addContextListener(ModelEvent.PARSED_MODEL_ARMATURE_CHANGE, modelHandler); this.addContextListener(ModelEvent.PARSED_MODEL_ANIMATION_CHANGE, modelHandler); resetUI(); BindingUtils.bindProperty(view.animationList, "selectedItem", parsedModel, "animationSelected", false); BindingUtils.bindProperty(parsedModel, "animationSelected", view.animationList, "selectedItem", false); view.numFadeInTime.addEventListener(Event.CHANGE, animationControlHandler); view.numAnimationScale.addEventListener(Event.CHANGE, animationControlHandler); view.numLoop.addEventListener(Event.CHANGE, animationControlHandler); view.checkAutoTween.addEventListener(Event.CHANGE, animationControlHandler); //view.numTweenEasing.addEventListener(Event.CHANGE, animationControlHandler); //view.checkTweenEasing.addEventListener(Event.CHANGE, animationControlHandler); } override public function destroy():void { super.destroy(); this.removeContextListener(ModelEvent.PARSED_MODEL_DATA_CHANGE, modelHandler); this.removeContextListener(ModelEvent.PARSED_MODEL_ANIMATION_CHANGE, modelHandler) view.numFadeInTime.removeEventListener(Event.CHANGE, animationControlHandler); view.numAnimationScale.removeEventListener(Event.CHANGE, animationControlHandler); view.numLoop.removeEventListener(Event.CHANGE, animationControlHandler); view.checkAutoTween.removeEventListener(Event.CHANGE, animationControlHandler); //view.numTweenEasing.addEventListener(Event.CHANGE, animationControlHandler); //view.checkTweenEasing.addEventListener(Event.CHANGE, animationControlHandler); } private function resetUI():void { view.enabled = false; view.animationList.dataProvider = parsedModel.animationsAC; view.animationList.selectedItem = null; } private function modelHandler(e:ModelEvent):void { if(parsedModel != e.model) { return; } switch(e.type) { case ModelEvent.PARSED_MODEL_DATA_CHANGE: break; case ModelEvent.PARSED_MODEL_ARMATURE_CHANGE: if(!parsedModel.armatureSelected) { resetUI(); } break; case ModelEvent.PARSED_MODEL_ANIMATION_CHANGE: if(parsedModel.animationSelected) { view.enabled = true; var isMultipleFrameAnimation:Boolean = parsedModel.isMultipleFrameAnimation; view.numFadeInTime.value = parsedModel.fadeInTime; if(isMultipleFrameAnimation) { view.numAnimationScale.value = parsedModel.animationScale * 100; view.numAnimationScale.enabled = true; view.numAnimationTotalTime.text = parsedModel.durationScaled.toString(); view.numLoop.enabled = true; view.numLoop.value = parsedModel.playTimes; view.checkAutoTween.enabled = true; view.checkAutoTween.selected = parsedModel.autoTween; /*view.checkTweenEasing.enabled = true; if(isNaN(tweenEasing)) { view.checkTweenEasing.selected = false; view.numTweenEasing.enabled = false; view.numTweenEasing.value = 0; } else { view.checkTweenEasing.selected = true; view.numTweenEasing.enabled = true; view.numTweenEasing.value = tweenEasing; }*/ } else { view.numAnimationScale.enabled = false; view.numAnimationScale.value = 100; view.numAnimationTotalTime.text = "0"; view.numLoop.enabled = false; view.numLoop.value = 1; view.checkAutoTween.enabled = false; view.checkAutoTween.selected = false; //view.checkTweenEasing.enabled = false; //view.numTweenEasing.enabled = false; } } else { view.enabled = false; } break; } } private function animationControlHandler(e:Event):void { switch(e.target) { case view.numFadeInTime: parsedModel.fadeInTime = view.numFadeInTime.value; view.numFadeInTime.value = parsedModel.fadeInTime; break; case view.numAnimationScale: parsedModel.animationScale = view.numAnimationScale.value * 0.01; view.numAnimationScale.value = parsedModel.animationScale * 100; view.numAnimationTotalTime.text = parsedModel.durationScaled.toString();; break; case view.numLoop: parsedModel.playTimes = view.numLoop.value; view.numLoop.value = parsedModel.playTimes; break; case view.checkAutoTween: parsedModel.autoTween = view.checkAutoTween.selected; break; /* case view.numTweenEasing: model.tweenEasing = view.numTweenEasing.value; break; case view.checkTweenEasing: if(view.checkTweenEasing.selected) { model.tweenEasing = 0; } else { model.tweenEasing = NaN; } break; */ } } } }
package com.playata.framework.localization { import com.playata.application.AppConfig; import com.playata.framework.application.Environment; import com.playata.framework.assets.IAsset; import com.playata.framework.core.Core; import com.playata.framework.core.TypedObject; import com.playata.framework.core.collection.StringMap; import com.playata.framework.core.error.Exception; import com.playata.framework.core.logging.Logger; import com.playata.framework.core.util.StringUtil; public class LocText implements IAsset { public static var current:LocText = null; private var _gender:int = 0; private var _textCache:StringMap; private var _locale:String = null; private var _data:TypedObject = null; public function LocText(param1:TypedObject, param2:String) { _textCache = new StringMap(); super(); Logger.debug("[LocText] Init text localization..."); setData(param1,param2); } public function dispose() : void { Logger.debug("[LocText] Destroy localization..."); _data = null; _locale = null; } public function set gender(param1:int) : void { _gender = param1; } public function get gender() : int { return _gender; } public function setData(param1:TypedObject, param2:String) : void { Logger.debug("[LocText] Setting new data for localization system..."); _data = param1; _locale = param2; _textCache = new StringMap(); } public function addData(param1:TypedObject) : void { var _loc4_:int = 0; var _loc3_:* = param1.rawData; for(var _loc2_ in param1.rawData) { _data.setData(_loc2_,param1.rawData[_loc2_]); if(_textCache.exists(_loc2_)) { _textCache.remove(_loc2_); } } } public function hasText(param1:String) : Boolean { return _data.hasData(param1); } public function text(param1:String, ... rest) : String { var _loc12_:int = 0; var _loc15_:* = null; var _loc19_:* = null; var _loc16_:* = null; var _loc5_:int = 0; var _loc21_:Number = NaN; var _loc17_:Boolean = false; var _loc20_:* = null; var _loc10_:* = null; var _loc22_:* = null; var _loc18_:* = null; var _loc13_:* = null; var _loc9_:* = null; var _loc4_:* = null; var _loc3_:* = null; var _loc7_:* = null; var _loc8_:int = 0; if(_data == null) { throw new Exception("Error in LocText! No text data has been set!"); } if(!_data.hasData(param1)) { return param1; } var _loc14_:String = null; var _loc11_:String = _data.getString(param1); if(Environment.platform.isNaughtyEmpire) { _loc11_ = StringUtil.replace(_loc11_,"Playata GmbH","3X Entertainment Ltd."); } if(rest.length == 0 && _loc11_.indexOf("[m:") == -1 && _loc11_.indexOf("[f:") == -1 && _loc11_.indexOf("[touch:") == -1 && _loc11_.indexOf("[desktop:") == -1 && _loc11_.indexOf("<font color=\"quality") == -1 && _loc11_.indexOf("[APPLICATION_NAME]") == -1) { if(_textCache.exists(param1)) { return _textCache.getData(param1); } _loc14_ = new String(_data.getString(param1)); if(Environment.platform.isNaughtyEmpire) { _loc14_ = StringUtil.replace(_loc14_,"Playata GmbH","3X Entertainment Ltd."); } _loc14_ = StringUtil.replace(_loc14_,"[percent]","%"); _textCache.setData(param1,_loc14_); return _loc14_; } _loc14_ = new String(_data.getString(param1)); if(Environment.platform.isNaughtyEmpire) { _loc14_ = StringUtil.replace(_loc14_,"Playata GmbH","3X Entertainment Ltd."); } _loc12_ = rest.length; while(_loc12_ > 0) { if(_loc14_.search("%" + _loc12_) == -1) { Logger.debug("[LocText] Error in LocText! [Key: " + param1 + "][Value: " + _data.getString(param1) + "] Parameter %" + _loc12_ + " does not exist."); } else if(_loc14_.indexOf("[v:%" + _loc12_) == -1) { _loc15_ = rest[_loc12_ - 1].toString(); _loc15_ = StringUtil.replace(_loc15_,"%","___%___"); _loc14_ = _loc14_.split("%" + _loc12_).join(_loc15_); } else { _loc19_ = "[v:%" + _loc12_; while(_loc14_.indexOf(_loc19_) != -1) { _loc16_ = getParameterString(_loc14_,_loc12_); _loc5_ = parseInt(StringUtil.replace(StringUtil.replace(rest[_loc12_ - 1].toString(),text("base/numbers/comma_separator"),""),text("base/numbers/thousands_separator"),"")); _loc21_ = parseFloat(StringUtil.replace(StringUtil.replace(rest[_loc12_ - 1].toString(),text("base/numbers/comma_separator"),"."),text("base/numbers/thousands_separator"),"")); _loc17_ = !!(_loc21_ % 1)?true:false; _loc20_ = ""; if(_loc17_ || isNaN(_loc21_)) { _loc20_ = getPluralForm(_loc16_,_loc5_,rest[_loc12_ - 1].toString()); } else { _loc20_ = getPluralForm(_loc16_,_loc5_,formatHugeNumber(_loc21_)); } _loc14_ = _loc14_.replace(_loc16_,_loc20_); } } _loc12_--; } _loc14_ = StringUtil.replace(_loc14_,"___%___","%"); var _loc6_:int = _gender; while(_loc14_.indexOf("[m:") != -1 || _loc14_.indexOf("[f:") != -1) { _loc10_ = null; _loc22_ = ""; _loc18_ = ""; if(_loc14_.indexOf("[m:") != -1) { _loc10_ = _loc14_.substring(_loc14_.indexOf("[m:")); _loc22_ = _loc14_.substring(_loc14_.indexOf("[m:") + 3); if(_loc22_.indexOf("|f:") != -1 && _loc22_.indexOf("]") != -1) { _loc18_ = _loc22_.substring(_loc22_.indexOf("|f:") + 3); _loc18_ = _loc18_.substring(0,_loc18_.indexOf("]")); _loc22_ = _loc22_.substring(0,_loc22_.indexOf("|f:")); } else if(_loc22_.indexOf("]") != -1) { _loc22_ = _loc22_.substring(0,_loc22_.indexOf("]")); } else { break; } } else { _loc10_ = _loc14_.substring(_loc14_.indexOf("[f:")); _loc18_ = _loc14_.substring(_loc14_.indexOf("[f:") + 3); if(_loc18_.indexOf("|m:") != -1 && _loc18_.indexOf("]") != -1) { _loc22_ = _loc18_.substring(_loc18_.indexOf("|m:") + 3); _loc22_ = _loc22_.substring(0,_loc22_.indexOf("]")); _loc18_ = _loc18_.substring(0,_loc18_.indexOf("|m:")); } else if(_loc18_.indexOf("]") != -1) { _loc18_ = _loc18_.substring(0,_loc18_.indexOf("]")); } else { break; } } _loc10_ = _loc10_.substring(0,_loc10_.indexOf("]") + 1); if(_loc6_ == 2) { _loc14_ = StringUtil.replace(_loc14_,_loc10_,_loc18_); } else { _loc14_ = StringUtil.replace(_loc14_,_loc10_,_loc22_); } } while(_loc14_.indexOf("[touch:") != -1 || _loc14_.indexOf("[desktop:") != -1) { _loc13_ = null; _loc9_ = ""; _loc4_ = ""; if(_loc14_.indexOf("[touch:") != -1) { _loc13_ = _loc14_.substring(_loc14_.indexOf("[touch:")); _loc9_ = _loc14_.substring(_loc14_.indexOf("[touch:") + "[touch:".length); if(_loc9_.indexOf("|desktop:") != -1 && _loc9_.indexOf("]") != -1) { _loc4_ = _loc9_.substring(_loc9_.indexOf("|desktop:") + "[desktop:".length); _loc4_ = _loc4_.substring(0,_loc4_.indexOf("]")); _loc9_ = _loc9_.substring(0,_loc9_.indexOf("|desktop:")); } else if(_loc9_.indexOf("]") != -1) { _loc9_ = _loc9_.substring(0,_loc9_.indexOf("]")); } else { break; } } else { _loc13_ = _loc14_.substring(_loc14_.indexOf("[desktop:")); _loc4_ = _loc14_.substring(_loc14_.indexOf("[desktop:") + "[desktop:".length); if(_loc4_.indexOf("|touch:") != -1 && _loc4_.indexOf("]") != -1) { _loc9_ = _loc4_.substring(_loc4_.indexOf("|touch:") + "|touch:".length); _loc9_ = _loc9_.substring(0,_loc9_.indexOf("]")); _loc4_ = _loc4_.substring(0,_loc4_.indexOf("|touch:")); } else if(_loc4_.indexOf("]") != -1) { _loc4_ = _loc4_.substring(0,_loc4_.indexOf("]")); } else { break; } } _loc13_ = _loc13_.substring(0,_loc13_.indexOf("]") + 1); if(!Core.current.info.isTouchScreen) { _loc14_ = StringUtil.replace(_loc14_,_loc13_,_loc4_); } else { _loc14_ = StringUtil.replace(_loc14_,_loc13_,_loc9_); } } while(_loc14_.indexOf("<font color=\"quality") != -1) { _loc3_ = null; _loc7_ = ""; _loc8_ = 0; if(_loc14_.indexOf("\"quality_common\"") != -1) { _loc3_ = _loc14_.substring(_loc14_.indexOf("\"quality_common\"")); _loc8_ = 16; _loc7_ = "\"#DADADA\""; } else if(_loc14_.indexOf("\"quality_rare\"") != -1) { _loc3_ = _loc14_.substring(_loc14_.indexOf("\"quality_rare\"")); _loc8_ = 14; _loc7_ = "\"#0066FF\""; } else if(_loc14_.indexOf("\"quality_epic\"") != -1) { _loc3_ = _loc14_.substring(_loc14_.indexOf("\"quality_epic\"")); _loc8_ = 14; _loc7_ = "\"#C800D0\""; } else { throw new Error("Error in LocText! Invalid Qualaity Parameter " + _loc14_.substring(_loc14_.indexOf("\"quality_"),_loc14_.indexOf(">"))); } _loc3_ = _loc3_.substring(0,_loc8_); _loc14_ = StringUtil.replace(_loc14_,_loc3_,_loc7_); } _loc14_ = StringUtil.replace(_loc14_,"[percent]","%"); _loc14_ = StringUtil.replace(_loc14_,"[APPLICATION_NAME]",AppConfig.appName); if(_locale == "cs_CZ") { if(_loc11_.indexOf(" v %") != -1 && _loc11_.indexOf(" hodin") != -1) { _loc14_ = StringUtil.replace(_loc14_," v 12"," ve 12"); _loc14_ = StringUtil.replace(_loc14_," v 13"," ve 13"); _loc14_ = StringUtil.replace(_loc14_," v 14"," ve 14"); _loc14_ = StringUtil.replace(_loc14_," v 20"," ve 20"); _loc14_ = StringUtil.replace(_loc14_," v 21"," ve 21"); _loc14_ = StringUtil.replace(_loc14_," v 22"," ve 22"); _loc14_ = StringUtil.replace(_loc14_," v 23"," ve 23"); } } return _loc14_; } public function getParameterString(param1:String, param2:int, param3:String = null) : String { var _loc8_:int = 0; var _loc7_:* = null; var _loc9_:String = "[v:%" + param2; if(param3 != null) { _loc9_ = "[v:" + param3; } if(param1.indexOf(_loc9_) == -1) { throw new Exception("Error in LocText! Value Parameter " + param2 + " not found!"); } var _loc4_:String = param1.substr(param1.indexOf(_loc9_)); var _loc5_:int = 0; var _loc6_:int = _loc9_.length; _loc8_ = _loc9_.length; while(_loc8_ < _loc4_.length) { _loc7_ = _loc4_.charAt(_loc8_); if(_loc7_ == "[") { _loc5_++; } else if(_loc7_ == "]" && _loc5_ > 0) { _loc5_--; } else if(_loc7_ == "]" && _loc5_ == 0) { break; } _loc6_++; _loc8_++; } _loc4_ = _loc4_.substr(0,_loc6_ + 1); return _loc4_; } public function getPluralForm(param1:String, param2:int, param3:String = null) : String { var _loc8_:int = 0; var _loc7_:* = null; if(_data == null) { throw new Exception("Error in LocText! No text data has been set!"); } if(param3 == null) { param3 = param2.toString(); } var _loc9_:String = null; if(_locale == "pl_PL") { if(param2 == 0) { _loc9_ = "p2"; } else if(param2 == 1) { _loc9_ = "s"; } else if(param2 % 10 >= 2 && param2 % 10 <= 4 && (param2 % 100 < 10 || param2 % 100 >= 20)) { _loc9_ = "p"; } else { _loc9_ = "p2"; } } else if(_locale == "cs_CZ") { if(param2 == 1) { _loc9_ = "s"; } else if(param2 >= 2 && param2 <= 4) { _loc9_ = "p"; } else { _loc9_ = "p2"; } } else if(_locale == "ru_RU") { if(param2 % 10 == 1 && param2 % 100 != 11) { _loc9_ = "s"; } else if(param2 % 10 >= 2 && param2 % 10 <= 4 && (param2 % 100 < 10 || param2 % 100 >= 20)) { _loc9_ = "p"; } else { _loc9_ = "p2"; } } else if(_locale == "fr_FR") { if(param2 <= 1) { _loc9_ = "s"; } else { _loc9_ = "p"; } } else if(param2 == 1) { _loc9_ = "s"; } else { _loc9_ = "p"; } if(param1.indexOf("|" + _loc9_ + ":") == -1) { if(_loc9_ == "p2" && param1.indexOf("|p:") != -1) { _loc9_ = "p"; } else { throw new Exception("Error in LocText! No plural data for key \'" + _loc9_ + "\' has been set!"); } } var _loc4_:String = param1.substr(param1.indexOf("|" + _loc9_ + ":") + 2 + _loc9_.length); var _loc5_:int = 0; var _loc6_:int = 0; _loc8_ = 0; while(_loc8_ < _loc4_.length) { _loc7_ = _loc4_.charAt(_loc8_); if(_loc7_ == "[") { _loc5_++; } else if(_loc7_ == "]" && _loc5_ > 0) { _loc5_--; } else if(_loc7_ == "]" || _loc7_ == "|" && _loc5_ == 0) { break; } _loc6_++; _loc8_++; } _loc4_ = _loc4_.substr(0,_loc6_); _loc4_ = _loc4_.replace("$v",param3); return _loc4_; } public function formatHugeNumber(param1:*, param2:Boolean = false) : String { var _loc8_:int = 0; if(_data == null) { throw new Exception("Error in LocText! No text data has been set!"); } if(!_data.hasData("base/numbers/thousands_separator")) { throw new Exception("Error in LocText! Could not find mandatory key \'base/numbers/thousands_separator\' for current locale to apply number formatting!"); } var _loc4_:String = ""; if(param1 is int) { _loc8_ = param1; } else { _loc8_ = Math.floor(param1); _loc4_ = getDecimalString(param1); } var _loc5_:String = _loc8_.toString(); if(param2 && _loc8_ > 0) { _loc5_ = "+" + _loc8_.toString(); } if(param2 && _loc5_.length <= 4) { return _loc5_ + _loc4_; } if(_loc5_.length <= 3) { return _loc5_ + _loc4_; } _loc5_ = Math.abs(_loc8_).toString(); var _loc9_:String = text("base/numbers/thousands_separator"); var _loc6_:String = ""; var _loc3_:uint = _loc5_.length % 3; var _loc7_:int = _loc3_; if(_loc3_ > 0) { _loc6_ = _loc5_.slice(0,_loc3_) + _loc9_; } while(_loc7_ < _loc5_.length) { _loc6_ = _loc6_ + _loc5_.slice(_loc7_,_loc7_ + 3); _loc7_ = _loc7_ + 3; if(_loc7_ < _loc5_.length) { _loc6_ = _loc6_ + _loc9_; } } if(param2 && _loc8_ > 0) { _loc6_ = "+" + _loc6_; } else if(_loc8_ < 0) { _loc6_ = "-" + _loc6_; } return _loc6_ + _loc4_; } private function getDecimalString(param1:Number) : String { if(Math.floor(param1) == param1) { return ""; } var _loc2_:String = text("base/numbers/comma_separator"); var _loc4_:String = param1.toString(); var _loc3_:int = parseInt(_loc4_.substr(_loc4_.indexOf(_loc2_))); return _loc2_ + formatHugeNumber(_loc3_); } public function shortenHugeNumber(param1:Number) : String { if(_data == null) { throw new Exception("Error in LocText! No text data has been set!"); } if(!_data.hasData("base/numbers/comma_separator")) { throw new Exception("Error in LocText! Could not find mandatory key \'base/numbers/comma_separator\' for current locale to apply number formatting!"); } if(!_data.hasData("base/numbers/thousands_short")) { throw new Exception("Error in LocText! Could not find mandatory key \'base/numbers/thousands_short\' for current locale to apply number formatting!"); } if(!_data.hasData("base/numbers/millions_short")) { throw new Exception("Error in LocText! Could not find mandatory key \'base/numbers/millions_short\' for current locale to apply number formatting!"); } if(!_data.hasData("base/numbers/billions_short")) { throw new Exception("Error in LocText! Could not find mandatory key \'base/numbers/billions_short\' for current locale to apply number formatting!"); } param1 = Math.floor(param1); var _loc4_:String = text("base/numbers/comma_separator"); var _loc2_:String = param1.toString(); var _loc3_:* = ""; if(param1 < 0 && _loc2_.length < 5) { return _loc2_; } if(_loc2_.length < 4) { return _loc2_; } if(_loc2_.length == 4) { _loc3_ = text("base/numbers/thousands_short",_loc2_.charAt(0) + _loc4_ + _loc2_.charAt(1)); } else if(_loc2_.length == 5) { _loc3_ = text("base/numbers/thousands_short",_loc2_.slice(0,2) + _loc4_ + _loc2_.charAt(2)); } else if(_loc2_.length == 6) { _loc3_ = text("base/numbers/thousands_short",_loc2_.slice(0,3)); } else if(_loc2_.length == 7) { _loc3_ = text("base/numbers/millions_short",_loc2_.charAt(0) + _loc4_ + _loc2_.charAt(1)); } else if(_loc2_.length == 8) { _loc3_ = text("base/numbers/millions_short",_loc2_.slice(0,2) + _loc4_ + _loc2_.charAt(2)); } else if(_loc2_.length == 9) { _loc3_ = text("base/numbers/millions_short",_loc2_.slice(0,3)); } else if(_loc2_.length == 10) { _loc3_ = text("base/numbers/billions_short",_loc2_.charAt(0) + _loc4_ + _loc2_.charAt(1)); } else if(_loc2_.length == 11) { _loc3_ = text("base/numbers/billions_short",_loc2_.slice(0,2) + _loc4_ + _loc2_.charAt(2)); } else if(_loc2_.length == 12) { _loc3_ = text("base/numbers/billions_short",_loc2_.slice(0,3)); } else { _loc3_ = _loc2_; } return _loc3_; } public function get locale() : String { return _locale; } } }
package org.ro.view { import org.ro.core.Globals; import org.ro.view.tab.RoTabBar; import spark.components.HGroup; import spark.components.VGroup; public class RoView extends VGroup { private const PADDING:int = -24; private var menuBar:RoMenuBar; private var dock:Dock; private var tabs:RoTabBar; private var statusBar:RoStatusBar; private var body:HGroup; public function RoView() { percentWidth = 100; percentHeight = 100; paddingTop = PADDING; paddingLeft = PADDING; paddingRight = PADDING; paddingBottom = PADDING; initMenu(); initBody(); initStatus(); new Globals(this); } private function initMenu():void { menuBar = new RoMenuBar(); this.addElement(menuBar); } private function initBody():void { body = new HGroup(); body.percentHeight = 100; body.percentWidth = 100; this.addElement(body); // initDock(); initTabs(); } private function initDock():void { dock = new Dock(); body.addElementAt(dock, 0); } private function initTabs():void { tabs = new RoTabBar(); body.addElement(tabs); } private function initStatus():void { statusBar = new RoStatusBar(); this.addElement(statusBar); } public function showDock(toggle:Boolean):void { if (toggle) { initDock(); } else { body.removeChild(dock); body.invalidateDisplayList(); } } public function showStatus(toggle:Boolean):void { if (toggle) { initStatus(); } else { this.removeChild(statusBar); this.invalidateDisplayList(); } } public function getTabs():RoTabBar { return tabs; } public function getMenuBar():RoMenuBar { return menuBar; } public function getStatusBar():RoStatusBar { return statusBar; } public function getDock():Dock { return dock; } } }
/* * Licensed under the MIT License * * Copyright 2010 (c) Flávio Silva, http://flsilva.com * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * http://www.opensource.org/licenses/mit-license.php */ package org.as3collections.lists { import org.as3collections.IList; import org.as3collections.ISortedList; import org.as3coreaddendum.system.IComparator; import org.as3utils.ReflectionUtil; /** * <code>UniqueSortedList</code> works as a wrapper for a <code>ISortedList</code> object. * It does not allow duplicated elements in the collection. * It stores the <code>wrapList</code> constructor's argument in the <code>wrappedList</code> variable. * So every method call to this class is forwarded to the <code>wrappedList</code> object. * The methods that need to be checked for duplication are previously validated before forward the call. * No error is thrown by the validation of duplication. * The calls that are forwarded to the <code>wrappedList</code> returns the return of the <code>wrappedList</code> call. * <p>You can also create unique and typed sorted lists. * See below the link "ListUtil.getUniqueTypedSortedList()".</p> * * @example * * <listing version="3.0"> * import org.as3collections.ISortedList; * import org.as3collections.IListIterator; * import org.as3collections.lists.SortedArrayList; * import org.as3collections.lists.UniqueSortedList; * import org.as3collections.utils.ListUtil; * * var l1:ISortedList = new SortedArrayList([3, 5, 1, 7], null, Array.NUMERIC); * * var list1:ISortedList = new UniqueSortedList(l1); // you can use this way * * //var list1:ISortedList = ListUtil.getUniqueSortedList(l1); // or you can use this way * * list1 // [1,3,5,7] * list1.size() // 4 * * list1.addAt(1, 4) // true * list1 // [1,3,4,5,7] * list1.size() // 5 * * list1.addAt(2, 3) // false * list1 // [1,3,4,5,7] * list1.size() // 5 * * list1.add(5) // false * list1 // [1,3,4,5,7] * list1.size() // 5 * </listing> * * @see org.as3collections.utils.ListUtil#getUniqueSortedList() ListUtil.getUniqueSortedList() * @see org.as3collections.utils.ListUtil#getUniqueTypedSortedList() ListUtil.getUniqueTypedSortedList() * @author Flávio Silva */ public class UniqueSortedList extends UniqueList implements ISortedList { /** * Defines the <code>wrappedList</code> comparator object to be used automatically to sort. * <p>If this value change the <code>wrappedList</code> is automatically reordered with the new value.</p> */ public function get comparator(): IComparator { return wrappedSortedList.comparator; } public function set comparator(value:IComparator): void { wrappedSortedList.comparator = value; } /** * Defines the <code>wrappedList</code> options to be used automatically to sort. * <p>If this value change the list is automatically reordered with the new value.</p> */ public function get options(): uint { return wrappedSortedList.options; } public function set options(value:uint): void { wrappedSortedList.options = value; } /** * @private */ protected function get wrappedSortedList(): ISortedList { return wrappedList as ISortedList; } /** * Constructor, creates a new <code>TypedList</code> object. * * @param wrapList the target list to wrap. * @param type the type of the elements allowed by this list. * @throws ArgumentError if the <code>wrapList</code> argument is <code>null</code>. * @throws ArgumentError if the <code>type</code> argument is <code>null</code>. * @throws org.as3coreaddendum.errors.ClassCastError if the types of one or more elements in the <code>wrapList</code> argument are incompatible with the <code>type</code> argument. */ public function UniqueSortedList(wrapList:ISortedList) { super(wrapList); } /** * Creates and return a new <code>UniqueSortedList</code> object with the clone of the <code>wrappedMap</code> object. * * @return a new <code>UniqueSortedList</code> object with the clone of the <code>wrappedMap</code> object. */ override public function clone(): * { return new UniqueSortedList(wrappedSortedList.clone()); } /** * Performs an arbitrary, specific evaluation of equality between this object and the <code>other</code> object. * <p>This implementation considers two differente objects equal if:</p> * <p> * <ul><li>object A and object B are instances of the same class (i.e. if they have <b>exactly</b> the same type)</li> * <li>object A contains all elements of object B</li> * <li>object B contains all elements of object A</li> * <li>elements have exactly the same order</li> * <li>object A and object B has the same type of comparator</li> * <li>object A and object B has the same options</li> * </ul></p> * <p>This implementation takes care of the order of the elements in the list. * So, for two lists are equal the order of elements returned by the iterator must be equal.</p> * * @param other the object to be compared for equality. * @return <code>true</code> if the arbitrary evaluation considers the objects equal. */ override public function equals(other:*): Boolean { if (this == other) return true; if (!ReflectionUtil.classPathEquals(this, other)) return false; var l:ISortedList = other as ISortedList; if (options != l.options) return false; if (!comparator && l.comparator) return false; if (comparator && !l.comparator) return false; if (!ReflectionUtil.classPathEquals(comparator, l.comparator)) return false; return super.equals(other); } /** * Forwards the call to <code>wrappedList.sort</code>. * * @param compare * @param options * @return */ public function sort(compare:Function = null, options:uint = 0): Array { return wrappedSortedList.sort(compare, options); } /** * Forwards the call to <code>wrappedList.sortOn</code>. * * @param fieldName * @param options * @return */ public function sortOn(fieldName:*, options:* = null): Array { return wrappedSortedList.sortOn(fieldName, options); } /** * Forwards the call to <code>wrappedList.subList</code>. * * @param fromIndex * @param toIndex * @return */ override public function subList(fromIndex:int, toIndex:int): IList { var subList:IList = wrappedSortedList.subList(fromIndex, toIndex); var sortedSubList:ISortedList = new SortedArrayList(subList.toArray(), comparator, options); return new UniqueSortedList(sortedSubList); } } }
package com.github.mortido.sqcity.models { public class Production { public function Production(isAuto:Boolean, coinsCost:int, energyCost:int, populationCost:int, coinsBonus:int, energyBonus:int, populationBonus:int, time:uint, id:int) { _isAuto = isAuto; _coinsCost = coinsCost; _energyCost = energyCost; _populationCost = populationCost; _coinsBonus = coinsBonus; _energyBonus = energyBonus; _populationBonus = populationBonus; _time = time; _id = id; } private var _isAuto:Boolean; private var _coinsCost:int; private var _energyCost:int; private var _populationCost:int; private var _coinsBonus:int; private var _energyBonus:int; private var _populationBonus:int; private var _time:uint; private var _id:int; public function get isAuto():Boolean { return _isAuto; } public function get coinsCost():int { return _coinsCost; } public function get energyCost():int { return _energyCost; } public function get populationCost():int { return _populationCost; } public function get coinsBonus():int { return _coinsBonus; } public function get energyBonus():int { return _energyBonus; } public function get populationBonus():int { return _populationBonus; } public function get time():uint { return _time; } public function get id():int { return _id; } } }
package serverProto.supershadow { import com.netease.protobuf.Message; import com.netease.protobuf.WritingBuffer; import flash.utils.IDataInput; import com.netease.protobuf.ReadUtils; public final class ProtoSuperShadowQueryToolReq extends Message { public function ProtoSuperShadowQueryToolReq() { super(); } override final function writeToBuffer(param1:WritingBuffer) : void { var _loc2_:* = undefined; for(_loc2_ in this) { super.writeUnknown(param1,_loc2_); } } override final function readFromSlice(param1:IDataInput, param2:uint) : void { var _loc3_:uint = 0; while(param1.bytesAvailable > param2) { _loc3_ = ReadUtils.read$TYPE_UINT32(param1); if(false?0:0) { } super.readUnknown(param1,_loc3_); } } } }
//////////////////////////////////////////////////////////////////////////////// // // 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 { COMPILE::JS /** * @royalesuppresspublicvarwarning */ public class XML { import org.apache.royale.debugging.assert; import org.apache.royale.debugging.assertType; import org.apache.royale.language.toAttributeName; /** * Memory optimization. * Creating a new QName for each XML instance significantly adds memory usage. * The XML QName can be a significant percentage of an XML object size. * By retaining a lookup of QNames and reusing QName objects, we can save quite a bit of memory. */ static private var _nameMap:Object = {}; static private function getQName(localName:String,prefix:*,uri:String,isAttribute:Boolean):QName{ localName = localName || ""; var prefixKey:String = prefix == null ? '{$'+prefix+'$}' : prefix ; // handle nullish values differently to the potent 'null' or 'undefined' string values uri = uri || ''; //internally there is no concept of 'any' namespace which is what a null uri is in a QName. var key:String = localName + ":" + prefixKey + ":" + uri + ":" + isAttribute; var qname:QName = _nameMap[key]; if(!qname){ qname = new QName(uri, localName); if(prefix != null) qname.setPrefix(prefix); if (isAttribute) qname.setIsAttribute(true); _nameMap[key] = qname; } return qname; } /** * Compiler-only method to support multiple 'use namespace' directives * this method is not intended for use other than by the compiler * If it is never generated in application code, which only happens * with 'use namespace "something"' directives in function execution scope * it will be omitted from the js-release build via dead-code elimination * (unless dead-code elimination is switched off - it is on by default). * * @private * @royalesuppressexport * @royalesuppressclosure */ public static function multiQName(namespaces:Array, name:*, isAtt:Boolean):QName{ //create with empty prefix to start: var original:QName = name && typeof name == 'object' && name['className'] == 'QName' ? name : new QName(name); if (isAtt) original.setIsAttribute(true); //generate others var others:Array = []; while(namespaces.length) { var other:QName = new QName(namespaces.shift(), original.localName); if (isAtt) other.setIsAttribute(true); others.push(other); } var superCall:Function = original.matches; var matchesOverride:Function = function (qName:QName):Boolean { var match:Boolean = superCall.call(original, qName); if (!match) { match= multiMatch(others, qName); } return match; }; Object.defineProperties(original, { //override to identify as *not* a regular QName, but identify by string to avoid checks //that create a hard dependency "className": { "get": function():String { return "MultiName"; } }, //override in this instance to perform multiple matching checks: "matches": { 'value': matchesOverride } } ); return original; } /** * @private * see multiQName above */ private static function multiMatch(qNames:Array, name:QName):Boolean{ var l:uint = qNames.length; var match:Boolean; for (var i:uint = 0; i < l; i++) { var check:QName = qNames[i]; match = check.matches(name); if (match) break; } return match; } /** * Compiler-only method to support swf compatibility for queries, * this method is not intended for use other than by the compiler. * It may be off-spec, but matches swf implementation behavior. * The 'correction' is only applied if the argument passed to the * child, descendants, or attributes method of XML or XMLList is strongly typed * as a QName. * If it is never generated in application code by the compiler, * the following code will be omitted from the js-release build via dead-code elimination * (unless dead-code elimination is switched off - it is on by default). * * @private * @royalesuppressexport */ public static function swfCompatibleQuery(original:QName, isAtt:Boolean):QName{ if (!original || !(original.uri)) return original; //the query includes the possibility of 'no namespace' as well as the explicit one in //the defined original. Discussed in dev list. return multiQName([original.uri], original.localName, isAtt); } /** * Compiler-only method to support specific namespaced attribute queries. * If it is never generated in application code by the compiler, * it will be omitted from the js-release build via dead-code elimination * (unless dead-code elimination is switched off - it is on by default). * * @private * @royalesuppressexport */ public static function createAttributeQName(qname:QName):QName{ if (qname) qname.setIsAttribute(true); return qname; } /** * Compiler-only method to support construction with specfied default namespace. * This value is applied for each construction call within the applicable scope, * because setting default namespace as part of XML class internal state could * result in inconsistencies for any departure from the applicable scope * (calls to other function scopes or error handling, for example) * * @private * @royalesuppressexport */ public static function constructWithDefaultXmlNS(source:Object, ns:Object):XML{ if (ns) { var uri:String; //always make sure we have a string value (the uri) if (typeof ns == 'object' && ns['className'] == 'Namespace') { uri = ns.uri; } else { //toString uri = ns + ''; } var ret:XML; var err:Error; if (ns) { try{ _defaultNS = uri; ret = new XML(source); } catch (e:Error) { err = e; } } else ret = new XML(source); _defaultNS = null; if (err) throw err; else return ret; } else return new XML(source); } private static const ELEMENT:String = "e"; private static const ATTRIBUTE:String = "a"; private static const PROCESSING_INSTRUCTION:String = "p"; private static const TEXT:String = "t"; private static const COMMENT:String = "c"; /** * regex to match the xml declaration */ private static const xmlDecl:RegExp = /^\s*<\?xml[^?]*\?>/im; /** * Method to free up references to shared QName objects. * Probably only worth doing if most or all XML instances can be garbage-collected. * @langversion 3.0 * @productversion Royale 0.9 */ static public function clearQNameCache():void { _nameMap = {}; } /** * [static] Determines whether XML comments are ignored when XML objects parse the source XML data. * */ static public var ignoreComments:Boolean = true; /** * [static] Determines whether XML processing instructions are ignored when XML objects parse the source XML data. * */ static public var ignoreProcessingInstructions:Boolean = true; /** * [static] Determines whether white space characters at the beginning and end of text nodes are ignored during parsing. * */ static public var ignoreWhitespace:Boolean = true; static private var _prettyIndent:int = 2; /** * [static] Determines the amount of indentation applied by the toString() and toXMLString() methods when the XML.prettyPrinting property is set to true. * */ static public function set prettyIndent(value:int):void { _prettyIndent = value; _indentStr = ""; for(var i:int = 0; i < value; i++) { _indentStr = _indentStr + INDENT_CHAR; } } static public function get prettyIndent():int { return _prettyIndent; } static private var _indentStr:String = " "; static private var INDENT_CHAR:String = " "; /** * [static] Determines whether the toString() and toXMLString() methods normalize white space characters between some tags. * */ static public var prettyPrinting:Boolean = true; static private function escapeAttributeValue(value:String):String { var arr:Array = String(value).split(""); var len:int = arr.length; for(var i:int=0;i<len;i++) { switch(arr[i]) { case "<": arr[i] = "&lt;"; break; case "&": if(arr[i+1] != "#") arr[i] = "&amp;"; break; case '"': arr[i] = "&quot;"; break; case "\u000A": arr[i] = "&#xA;"; break; case "\u000D": arr[i] = "&#xD;"; break; case "\u0009": arr[i] = "&#x9;"; break; default: break; } } return arr.join(""); } static private function escapeElementValue(value:String):String { var i:int; var arr:Array = value.split(""); const len:uint = arr.length; for(i=0;i<len;i++) { switch(arr[i]) { case "<": arr[i] = "&lt;"; break; case ">": arr[i] = "&gt;"; break; case "&": if(arr[i+1] != "#") arr[i] = "&amp;"; break; default: break; } } return arr.join(""); } static private function insertAttribute(att:Attr,parent:XML):XML { var xml:XML = new XML(); xml._parent = parent; xml._name = getQName(att.localName, '', att.namespaceURI, true); xml._value = att.value; parent.addChildInternal(xml); return xml; } static private function iterateElement(node:Element,xml:XML):void { var i:int; // add attributes var attrs:* = node.attributes; var len:int = node.attributes.length; //set the name var localName:String = node.nodeName; var prefix:String = node.prefix; if(prefix && localName.indexOf(prefix + ":") == 0) { localName = localName.substr(prefix.length+1); } xml._name = getQName(localName, prefix, node.namespaceURI,false); var ns:Namespace; for(i=0;i<len;i++) { var att:Attr = attrs[i]; if ((att.name == 'xmlns' || att.prefix == 'xmlns') && att.namespaceURI == 'http://www.w3.org/2000/xmlns/') { //from e4x spec: NOTE Although namespaces are declared using attribute syntax in XML, they are not represented in the [[Attributes]] property. if (att.prefix) { ns = new Namespace(att.localName, att.nodeValue); } else { ns = new Namespace('', att.nodeValue); } xml.addNamespace(ns); } else insertAttribute(att,xml); } // loop through childNodes which will be one of: // text, cdata, processing instrution or comment and add them as children of the element var childNodes:NodeList = node.childNodes; len = childNodes.length; for(i=0;i<len;i++) { var nativeNode:Node = childNodes[i]; const nodeType:Number = nativeNode.nodeType; if ((nodeType == 7 && XML.ignoreProcessingInstructions) || (nodeType == 8 && XML.ignoreComments)) { continue; } var child:XML = fromNode(nativeNode); if (child) xml.addChildInternal(child); } } /** * returns an XML object from an existing node without the need to parse the XML. * The new XML object is not normalized * * @royaleignorecoercion Element */ static private function fromNode(node:Node):XML { var xml:XML; var data:* = node.nodeValue; switch(node.nodeType) { case 1: //ELEMENT_NODE xml = new XML(); //this is _internal... so don't set it, let it use the protoype value of ELEMENT //xml._nodeKind = "element"; //xml.setName(getQName(localName, prefix, node.namespaceURI,false)); iterateElement(node as Element,xml); break; //case 2:break;// ATTRIBUTE_NODE (handled separately) case 3: //TEXT_NODE if (XML.ignoreWhitespace) { data = data.trim(); if (!data) return null; } xml = new XML(); xml.setValue(data); break; case 4: //CDATA_SECTION_NODE xml = new XML(); data = "<![CDATA[" + data + "]]>"; xml.setValue(data); break; //case 5:break;//ENTITY_REFERENCE_NODE //case 6:break;//ENTITY_NODE case 7: //PROCESSING_INSTRUCTION_NODE xml = new XML(); xml._nodeKind = PROCESSING_INSTRUCTION; //e4x: The [[Name]] for each XML object representing a processing-instruction will have its uri property set to the empty string. var localName:String = node.nodeName; //var prefix:String = node.prefix; if(node.prefix && localName.indexOf(node.prefix + ":") == 0) { localName = localName.substr(node.prefix.length+1); } xml._name = getQName(localName, null, '',false); xml.setValue(data); break; case 8: //COMMENT_NODE xml = new XML(); xml._nodeKind = COMMENT; //e4X: the name must be null (comment node rules) xml.setValue(data); break; //case 9:break;//DOCUMENT_NODE //case 10:break;//DOCUMENT_TYPE_NODE //case 11:break;//DOCUMENT_FRAGMENT_NODE //case 12:break;//NOTATION_NODE default: throw new TypeError("Unknown XML node type!"); break; } return xml; } static private function namespaceInArray(ns:Namespace,arr:Array):Boolean { var i:int; var l:uint = arr.length; for(i=0;i<l;i++) { if(ns.uri == arr[i].uri) { if(ns.prefix == arr[i].prefix) return true; } } return false; } static private function trimXMLWhitespace(value:String):String { return value.replace(/^\s+|\s+$/gm,''); } /** * [static] Returns an object with the following properties set to the default values: ignoreComments, ignoreProcessingInstructions, ignoreWhitespace, prettyIndent, and prettyPrinting. * @return * */ static public function defaultSettings():Object { return { ignoreComments : true, ignoreProcessingInstructions : true, ignoreWhitespace : true, prettyIndent : 2, prettyPrinting : true } } /** * [static] Sets values for the following XML properties: ignoreComments, ignoreProcessingInstructions, ignoreWhitespace, prettyIndent, and prettyPrinting. * @param rest * */ static public function setSettings(value:Object):void { if(!value) return; ignoreComments = value.ignoreComments === undefined ? ignoreComments : value.ignoreComments; ignoreProcessingInstructions = value.ignoreProcessingInstructions === undefined ? ignoreProcessingInstructions : value.ignoreProcessingInstructions; ignoreWhitespace = value.ignoreWhitespace === undefined ? ignoreWhitespace : value.ignoreWhitespace; prettyIndent = value.prettyIndent === undefined ? prettyIndent : value.prettyIndent; prettyPrinting = value.prettyPrinting === undefined ? prettyPrinting : value.prettyPrinting; } /** * [static] Retrieves the following properties: ignoreComments, ignoreProcessingInstructions, ignoreWhitespace, prettyIndent, and prettyPrinting. * * @return * */ static public function settings():Object { return { ignoreComments : ignoreComments, ignoreProcessingInstructions : ignoreProcessingInstructions, ignoreWhitespace : ignoreWhitespace, prettyIndent : prettyIndent, prettyPrinting : prettyPrinting } } /** * mimics the top-level XML function * @royaleignorecoercion XMLList * * @royalesuppressexport */ public static function conversion(xml:*, defaultNS:*):XML { if (xml == null) { //as3 docs say this is a TypeError, but it is actually not (in AVM), return an empty text node return new XML(); } else if (xml.ROYALE_CLASS_INFO != null) { var className:String = xml.ROYALE_CLASS_INFO.names[0].name; switch(className){ case "XML": return xml; case "XMLList": var xmlList:XMLList = xml as XMLList; if (xmlList.length() == 1) return xmlList[0]; // throw TypeError return null; } } if (defaultNS !== undefined) { return constructWithDefaultXmlNS(xml, defaultNS); } else return new XML(xml); } private static var _defaultNS:String; private static var _internal:Boolean; /** * @royaleignorecoercion XML */ public function XML(xml:* = null) { // _origStr = xml; // _children = []; if(xml != null) { var xmlStr:String = ignoreWhitespace ? trimXMLWhitespace("" + xml) : "" + xml; if(xmlStr.indexOf("<") == -1) { // _nodeKind = TEXT; _value = xmlStr; } else { parseXMLStr(xmlStr); } } else { if (!_internal) { // _nodeKind = TEXT; _value = ''; } } initializeClass(); if(!_class_initialized) { Object.defineProperty(XML.prototype,"0", { "get": function():*{return this}, "set": function():void{}, enumerable: true, configurable: true } ); _class_initialized = true; } } private static function initializeClass():void { } private static var _class_initialized:Boolean = false; private static const xmlRegEx:RegExp = /&(?![\w]+;)/g; private static const isWhitespace:RegExp = /^\s+$/; private static var parser:DOMParser; private static var errorNS:String; /** * * @royaleignorecoercion Element */ private function parseXMLStr(xml:String):void { //escape ampersands xml = xml.replace(xmlRegEx,"&amp;"); if(!parser) parser = new DOMParser(); var doc:Document; if(errorNS == null) { // get error namespace. It's different in different browsers. try{ errorNS = parser.parseFromString('<', 'application/xml').getElementsByTagName("parsererror")[0].namespaceURI; } catch(err:Error){ // Some browsers (i.e. IE) just throw an error errorNS = "na"; } } var decl:String = xmlDecl.exec(xml); if (decl) xml = xml.replace(decl,''); if (ignoreWhitespace) xml = trimXMLWhitespace( xml) ; //various node types not supported directly //when parsing, always wrap (e4x ref p34, 'Semantics' of e4x-Ecma-357.pdf) //custom: support alternate default xml namespace when parsing: if (_defaultNS) xml = '<parseRoot xmlns="'+_defaultNS+'">'+xml+'</parseRoot>'; else xml = '<parseRoot>'+xml+'</parseRoot>'; try { doc = parser.parseFromString(xml, "application/xml"); } catch(err:Error) { throw err; } //check for errors var errorNodes:NodeList = doc.getElementsByTagNameNS(errorNS, 'parsererror'); if(errorNodes.length > 0) throw new Error(errorNodes[0].innerHTML); //parseRoot wrapper doc = doc.childNodes[0]; var childCount:uint = doc.childNodes.length; //var rootError:Boolean; var foundRoot:Boolean; var foundCount:uint = 0; for(var i:int=0;i<childCount;i++) { var node:Node = doc.childNodes[i]; if(node.nodeType == 1) { if (foundRoot) { foundCount++; //we have at least 2 root tags... definite error break; } foundRoot = true; foundCount = 1; //top level root tag wins if (foundCount != 0) { //reset any earlier settings\ resetNodeKind(); } _name = getQName(node.localName,node.prefix,node.namespaceURI,false); _internal = true; iterateElement(node as Element,this); _internal = false; } else { if (foundRoot) continue; // if we already found a root, then everything else is ignored outside it, regardless of XML settings, so only continue to check for multiple root tags (an error) if (node.nodeType == 7) { if (XML.ignoreProcessingInstructions) { if (!foundCount) { // this._nodeKind = TEXT; //e4x: The value of the [[Name]] property is null if and only if the XML object represents an XML comment or text node delete this._name; this.setValue(''); } } else { this._nodeKind = PROCESSING_INSTRUCTION; this.setName(node.nodeName); this.setValue(node.nodeValue); foundCount++; } } else if (node.nodeType == 4) { if (!foundCount) { // this._nodeKind = TEXT; //e4x: The value of the [[Name]] property is null if and only if the XML object represents an XML comment or text node delete this._name; this.setValue('<![CDATA[' + node.nodeValue + ']]>'); } foundCount++; } else if (node.nodeType == 8) { //e4x: The value of the [[Name]] property is null if and only if the XML object represents an XML comment or text node delete this._name; if (XML.ignoreComments) { if (!foundCount) { // this._nodeKind = TEXT; this.setValue(''); } } else { if (!foundCount) { this._nodeKind = COMMENT; this.setValue(node.nodeValue); } foundCount++; } } else if (node.nodeType == 3) { var whiteSpace:Boolean = isWhitespace.test(node.nodeValue); if (!whiteSpace || !XML.ignoreWhitespace) { if (!foundCount) { delete this._name; // this._nodeKind = TEXT; this.setValue(node.nodeValue); } foundCount++; } else { //do nothing } } } } if (foundCount > 1) throw new TypeError('Error #1088: The markup in the document following the root element must be well-formed.'); } protected function resetNodeKind():void{ delete this._nodeKind; delete this._value; delete this._name; } protected var _children:Array; protected var _attributes:Array; private var _parent:XML; protected var _value:String; /* The value of the [[InScopeNamespaces]] property is a set of zero or more Namespace objects representing the namespace declarations in scope for this XML object. All of the Namespace objects in the [[InScopeNamespaces]] property have a prefix property with a value that is not undefined. When a new object is added to the [[InScopeNamespaces]] set, it replaces any existing object in the [[InScopeNamespaces]] set that has the same set identity. The set identity of each Namespace object n OF [[InScopeNamespaces]] is defined to be n.prefix. Therefore, there exists no two objects x,y OF [[InScopeNamespaces]], such that the result of the comparison x.prefix == y.prefix is true. */ protected var _namespaces:Array; private function getNamespaces():Array { if(!_namespaces) _namespaces = []; return _namespaces; } /** * @private * * Similar to appendChild, but accepts all XML types (text, comment, processing-instruction, attribute, or element) * * */ public function addChild(child:XML):void { if(!child) return; addChildInternal(child); normalize(); } protected function addChildInternal(child:XML):void { assertType(child,XML,"Type must be XML"); child.setParent(this); if(child.getNodeRef() == ATTRIBUTE) getAttributes().push(child); else getChildren().push(child); } private function getChildren():Array { if(!_children) _children = []; return _children; } private function getAttributes():Array { if(!_attributes) _attributes = []; return _attributes; } /** * Adds a namespace to the set of in-scope namespaces for the XML object. * * @param ns * @return * * * @royaleignorecoercion QName */ public function addNamespace(ns:Namespace):XML { //TODO cached QNames will not work very well here. /* When the [[AddInScopeNamespace]] method of an XML object x is called with a namespace N, the following steps are taken: 1. If x.[[Class]] ∈ {"text", "comment", "processing-instruction", “attribute”}, return 2. If N.prefix != undefined a. If N.prefix == "" and x.[[Name]].uri == "", return b. Let match be null c. For each ns in x.[[InScopeNamespaces]] i. If N.prefix == ns.prefix, let match = ns d. If match is not null and match.uri is not equal to N.uri i. Remove match from x.[[InScopeNamespaces]] e. Let x.[[InScopeNamespaces]] = x.[[InScopeNamespaces]] ∪ { N } f. If x.[[Name]].[[Prefix]] == N.prefix i. Let x.[[Name]].prefix = undefined g. For each attr in x.[[Attributes]] i. If attr.[[Name]].[[Prefix]] == N.prefix, let attr.[[Name]].prefix = undefined 3. Return */ var kind:String = getNodeRef(); if(kind == TEXT || kind == COMMENT || kind == PROCESSING_INSTRUCTION || kind == ATTRIBUTE) return this; if(ns.prefix === undefined) return this; if(ns.prefix == "" && name().uri == "") return this; var match:Namespace = null; var i:int; var nSpaces:Array = getNamespaces(); var len:int = nSpaces.length; //reverse loop to search more recent additions first because of match rule below for(i=len-1;i>0;i--) { if(nSpaces[i].prefix == ns.prefix) { match = nSpaces[i]; break; } } // If match is not null and match.uri is not equal to N.uri if(match && match.uri != ns.uri) { // Remove match from x.[[InScopeNamespaces]] nSpaces.splice(i,1); len--; } nSpaces[len]=ns; if(ns.prefix == name().prefix) { _name = getQName(_name.localName,undefined,_name.uri,false) } len = attributeLength(); for(i=0;i<len;i++) { var att:XML = _attributes[i]; if(att.name().prefix == ns.prefix) { att._name = getQName(QName(att._name).localName,null,QName(att._name).uri,true); } } return this; } /** * Appends the given child to the end of the XML object's properties. * * @param child * @return * * @royaleignorecoercion XML * */ public function appendChild(child:*):XML { /* 1. Let children be the result of calling the [[Get]] method of x with argument "*" 2. Call the [[Put]] method of children with arguments children.[[Length]] and child 3. Return x */ var childType:String = typeof child; if(childType != "object") { const last:uint = childrenLength(); const lastChild:XML = last ? _children[last-1] : null; if (lastChild && lastChild.getNodeRef() == ELEMENT) { const wrapper:XML = new XML(); wrapper.resetNodeKind(); child = new XML(child.toString()); wrapper._name = lastChild._name; child.setParent(wrapper); wrapper.getChildren().push(child); child = wrapper; } else { child = xmlFromStringable(child); } } appendChildInternal(child); //normalize seems not correct here: //normalize(); return this; } /** * * @royaleignorecoercion XML */ private function appendChildInternal(child:*):void { var kind:String; var alreadyPresent:int var children:Array = getChildren(); if(child is XMLList) { var len:int = child.length(); for(var i:int=0; i<len; i++) { //reproduce swf behavior... leaves a phantom child in the source var childItem:XML = child[i] as XML; kind = childItem.getNodeRef(); if (kind == ATTRIBUTE) { var name:String = childItem.localName(); var content:String = '<'+name+'>'+childItem.toString()+'</'+name+'>'; childItem = new XML(content) } else { alreadyPresent = children.indexOf(childItem); if (alreadyPresent != -1) children.splice(alreadyPresent, 1); } childItem.setParent(this, true); children.push(childItem); } } else { assertType(child,XML,"Type must be XML"); kind = child.getNodeRef(); if (kind == ATTRIBUTE) { child = new XML(child.toString()); } else { alreadyPresent = children.indexOf(child); if (alreadyPresent != -1) children.splice(alreadyPresent, 1); } (child as XML).setParent(this); children.push(child); } } /** * Returns the XML value of the attribute that has the name matching the attributeName parameter. * * @param attributeName * @return * */ public function attribute(attributeName:*):XMLList { var i:int; if(attributeName == "*") return attributes(); attributeName = toAttributeName(attributeName); var list:XMLList = new XMLList(); var len:int = attributeLength(); for(i=0;i<len;i++) { if(attributeName.matches(_attributes[i].name())) list.append(_attributes[i]); } list.targetObject = this; list.targetProperty = attributeName; return list; } /** * Returns a list of attribute values for the given XML object. * * @return * */ public function attributes():XMLList { var i:int; var list:XMLList = new XMLList(); var len:int = attributeLength(); for(i=0;i<len;i++) list.append(_attributes[i]); list.targetObject = this; return list; } /** * Lists the children of an XML object. * * @param propertyName * @return * * @royaleignorecoercion XML */ public function child(propertyName:Object):XMLList { /* * When the [[Get]] method of an XML object x is called with property name P, the following steps are taken: 1. If ToString(ToUint32(P)) == P a. Let list = ToXMLList(x) b. Return the result of calling the [[Get]] method of list with argument P 2. Let n = ToXMLName(P) 3. Let list be a new XMLList with list.[[TargetObject]] = x and list.[[TargetProperty]] = n 4. If Type(n) is AttributeName a. For each a in x.[[Attributes]] i. If ((n.[[Name]].localName == "*") or (n.[[Name]].localName == a.[[Name]].localName)) and ((n.[[Name]].uri == null) or (n.[[Name]].uri == a.[[Name]].uri)) 1. Call the [[Append]] method of list with argument a b. Return list 5. For (k = 0 to x.[[Length]]-1) a. If ((n.localName == "*") or ((x[k].[[Class]] == "element") and (x[k].[[Name]].localName == n.localName))) and ((n.uri == null) or ((x[k].[[Class]] == “element”) and (n.uri == x[k].[[Name]].uri))) i. Call the [[Append]] method of list with argument x[k] 6. Return list */ var i:int; var len:int; var list:XMLList = new XMLList(); if(parseInt(propertyName,10).toString() == propertyName) { if(propertyName != "0") return null; list.append(this); list.targetObject = this; return list; } //support MultiQName for multiple use namespace directives: if (propertyName && propertyName['className'] != 'MultiName') propertyName = toXMLName(propertyName); if(propertyName.isAttribute) { len = attributeLength(); for(i=0;i<len;i++) { if(propertyName.matches(_attributes[i].name())) list.append(_attributes[i]); } } else { len = childrenLength(); //special case: '*' var all:Boolean = propertyName.localName == "*" && propertyName.uri === ''; for(i=0;i<len;i++) { var child:XML = _children[i] as XML; if( all || propertyName.matches(child.name())) list.append(child); } } list.targetObject = this; list.targetProperty = propertyName; return list; } /** * Identifies the zero-indexed position of this XML object within the context of its parent. * * @return * */ public function childIndex():int { if(!_parent) return -1; return _parent.getIndexOf(this); } /** * Lists the children of the XML object in the sequence in which they appear. * * @return * */ public function children():XMLList { var i:int; var list:XMLList = new XMLList(); var len:int = childrenLength(); for(i=0;i<len;i++) { list.append(_children[i]); } list.targetObject = this; return list; } /** * Lists the properties of the XML object that contain XML comments. * * @return * * @royaleignorecoercion XML */ public function comments():XMLList { var i:int; var list:XMLList = new XMLList(); var len:int = childrenLength(); for(i=0;i<len;i++) { if((_children[i] as XML).getNodeRef() == COMMENT) list.append(_children[i]); } list.targetObject = this; return list; } public function concat(list:*):XMLList { if(list is XML) { var newList:XMLList = new XMLList(); newList.append(list); list = newList; } if(!(list is XMLList)) throw new TypeError("invalid type"); var retVal:XMLList = new XMLList(); retVal.append(this); var item:XML; for each(item in list) retVal.append(item); return retVal; } /** * Compares the XML object against the given value parameter. * * @param value * @return * */ public function contains(value:*):Boolean { if(value is XML || value is XMLList) return this.equals(value); return value == this; } /** * Returns a copy of the given XML object. * * @return * */ public function copy():XML { /* When the [[DeepCopy]] method of an XML object x is called, the following steps are taken: 1. Let y be a new XML object with y.[[Prototype]] = x.[[Prototype]], y.[[Class]] = x.[[Class]], y.[[Value]] = x.[[Value]], y.[[Name]] = x.[[Name]], y.[[Length]] = x.[[Length]] 2. For each ns in x.[[InScopeNamespaces]] a. Let ns2 be a new Namespace created as if by calling the constructor new Namespace(ns) b. Let y.[[InScopeNamespaces]] = y.[[InScopeNamespaces]] ∪ { ns2 } 3. Let y.[[Parent]] = null 4. For each a in x.[[Attributes]] a. Let b be the result of calling the [[DeepCopy]] method of a b. Let b.[[Parent]] = y c. Let y.[[Attributes]] = y.[[Attributes]] ∪ { b } 5. For i = 0 to x.[[Length]]-1 a. Let c be the result of calling the [[DeepCopy]] method of x[i] b. Let y[i] = c c. Let c.[[Parent]] = y 6. Return y */ var i:int; var xml:XML = new XML(); xml.resetNodeKind(); xml.setNodeKind(getNodeKindInternal()); xml._name = _name; if(_value){ xml.setValue(_value); } var len:int; len = namespaceLength(); for(i=0;i<len;i++) { xml.addNamespace(new Namespace(_namespaces[i])); } //parent should be null by default len = attributeLength(); for(i=0;i<len;i++) xml.addChildInternal(_attributes[i].copy()); len = childrenLength(); for(i=0;i<len;i++) xml.addChildInternal(_children[i].copy()); return xml; } /** * @royaleignorecoercion XML */ private function deleteChildAt(idx:int):void { var child:XML = _children[idx] as XML; child._parent = null; _children.splice(idx,1); } /** * Returns all descendants (children, grandchildren, great-grandchildren, and so on) of the XML object that have the given name parameter. * * @param name * @return * * @royaleignorecoercion XML * */ public function descendants(name:Object = "*"):XMLList { /* When the [[Descendants]] method of an XML object x is called with property name P, the following steps are taken: 1. Let n = ToXMLName(P) 2. Let list be a new XMLList with list.[[TargetObject]] = null 3. If Type(n) is AttributeName a. For each a in x.[[Attributes]] i. If ((n.[[Name]].localName == "*") or (n.[[Name]].localName == a.[[Name]].localName)) and ((n.[[Name]].uri == null) or (n.[[Name]].uri == a.[[Name]].uri )) 1. Call the [[Append]] method of list with argument a 4. For (k = 0 to x.[[Length]]-1) a. If ((n.localName == "*") or ((x[k].[[Class]] == "element") and (x[k].[[Name]].localName == n.localName))) and ((n.uri == null) or ((x[k].[[Class]] == "element") and (n.uri == x[k].[[Name]].uri))) i. Call the [[Append]] method of list with argument x[k] b. Let dq be the resultsof calling the [[Descendants]] method of x[k] with argument P c. If dq.[[Length]] > 0, call the [[Append]] method of list with argument dq 5. Return list */ var i:int; var len:int; if(!name) name = "*"; name = toXMLName(name); var list:XMLList = new XMLList(); if(name.isAttribute) { len = attributeLength(); for(i=0;i<len;i++) { if(name.matches(_attributes[i].name())) list.append(_attributes[i]); } } len = childrenLength(); for(i=0;i<len;i++) { var child:XML = _children[i] as XML; if(name.matches(child.name())) list.append(child); if(child.getNodeRef() == ELEMENT) { list.concat(child.descendants(name)); } } return list; } /** * Lists the elements of an XML object. (handles E4X dot notation) * * @param name * @return * * @royaleignorecoercion XML */ public function elements(name:Object = "*"):XMLList { if(!name) name = "*"; var all:Boolean = (name == "*"); name = toXMLName(name); var i:int; var list:XMLList = new XMLList(); var len:int = childrenLength(); for(i=0;i<len;i++) { if(_children[i].getNodeRef() == ELEMENT && (all || name.matches(_children[i].name()))) list.append(_children[i]); } list.targetObject = this; list.targetProperty = name; return list; } /** * for each should work on XML too * @private */ public function elementNames():Array { return [0]; } public function equals(xml:*):Boolean { /* When the [[Equals]] method of an XML object x is called with value V, the following steps are taken: 1. If Type(V) is not XML, return false 2. If x.[[Class]] is not equal to V.[[Class]], return false 3. If x.[[Name]] is not null a. If V.[[Name]] is null, return false b. If x.[[Name]].localName is not equal to V.[[Name]].localName, return false c. If x.[[Name]].uri is not equal to V.[[Name]].uri, return false 4. Else if V.[[Name]] is not null, return false 5. If x.[[Attributes]] does not contain the same number of items as V.[[Attributes]], return false 6. If x.[[Length]] is not equal to V.[[Length]], return false 7. If x.[[Value]] is not equal to y[[Value]], return false 8. For each a in x.[[Attributes]] a. If V.[[Attributes]] does not contain an attribute b, such that b.[[Name]].localName == a.[[Name]].localName, b.[[Name]].uri == a.[[Name]].uri and b.[[Value]] == a.[[Value]], return false 9. For i = 0 to x.[[Length]]-1 a. Let r be the result of calling the [[Equals]] method of x[i] with argument V[i] b. If r == false, return false 10. Return true */ var i:int; if (xml == this) return true; if(!(xml is XML)) return false; if(xml.getNodeRef() != getNodeRef()) return false; if(!name().equals(xml.name())) return false; var selfAttrs:Array = getAttributeArray(); var xmlAttrs:Array = xml.getAttributeArray(); if(selfAttrs.length != xmlAttrs.length) return false; //length comparison should not be necessary because xml always has a length of 1 if(getValue() != xml.getValue()) return false; for(i=0;i<selfAttrs.length;i++) { if(!xml.hasAttribute(selfAttrs[i])) return false; } var selfChldrn:Array = getChildrenArray(); var xmlChildren:Array = xml.getChildrenArray(); if(selfChldrn.length != xmlChildren.length) return false; for(i=0;i<selfChldrn.length;i++) { if(!selfChldrn[i].equals(xmlChildren[i])) return false; } return true; } public function hasAttribute(nameOrXML:*,value:String=null):Boolean { if(!_attributes) return false; var name:QName; if(nameOrXML is XML) { name = nameOrXML.name(); value = nameOrXML.getValue(); } else { name = new QName(nameOrXML); name.setIsAttribute(true); } var i:int; var len:int = attributeLength(); for(i=0;i<len;i++) { if(name.matches(_attributes[i].name())) { if(!value) return true; return value == _attributes[i].getValue(); } } return false; } private function getAncestorNamespaces(namespaces:Array):Array { //don't modify original namespaces = namespaces.slice(); var nsIdx:int; var pIdx:int; if(_parent) { var parentNS:Array = _parent.inScopeNamespaces(); var len:int = parentNS.length; for(pIdx=0;pIdx<len;pIdx++) { var curNS:Namespace = parentNS[pIdx]; var doInsert:Boolean = true; for(nsIdx=0;nsIdx<namespaces.length;nsIdx++) { if(curNS.uri == namespaces[nsIdx].uri && curNS.prefix == namespaces[nsIdx].prefix) { doInsert = false; break; } } if(doInsert) namespaces.push(curNS); } namespaces = _parent.getAncestorNamespaces(namespaces); } return namespaces; } public function getAttributeArray():Array { return _attributes ? _attributes : []; } public function getChildrenArray():Array { return _children ? _children : []; } public function getIndexOf(elem:XML):int { return _children ? _children.indexOf(elem) : -1; } protected function childrenLength():int { return _children ? _children.length : 0; } protected function attributeLength():int { return _attributes ? _attributes.length : 0; } protected function namespaceLength():int { return _namespaces ? _namespaces.length : 0; } private function getURI(prefix:String):String { var i:int; var namespaces:Array = inScopeNamespaces(); for(i=0;i<namespaces.length;i++) { if(namespaces[i].prefix == prefix) return namespaces[i].uri; } return ""; } public function getValue():String { return _value; } public function hasAncestor(obj:*):Boolean { if(!obj) return false; var parent:XML = this.parent(); while(parent) { if(obj == parent) return true; parent = parent.parent(); } return false; } /** * Checks to see whether the XML object contains complex content. * * @return true if this XML instance contains complex content * * @royaleignorecoercion XML */ public function hasComplexContent():Boolean { /* When the hasComplexContent method is called on an XML object x, the following steps are taken: 1. If x.[[Class]] ∈ {"attribute", "comment", "processing-instruction", "text"}, return false 2. For each property p in x a. If p.[[Class]] == "element", return true 3. Return false */ var kind:String = getNodeRef(); if(kind == ATTRIBUTE || kind == COMMENT || kind == PROCESSING_INSTRUCTION || kind == TEXT) return false; var i:int; var len:int = childrenLength(); for(i=0;i<len;i++) { if((_children[i] as XML).getNodeRef() == ELEMENT) return true; } return false; } /** * * @royaleignorecoercion XML */ override public function hasOwnProperty(p:*):Boolean { /* When the [[HasProperty]] method of an XML object x is called with property name P, the following steps are taken: 1. If ToString(ToUint32(P)) == P a. Return (P == "0") 2. Let n = ToXMLName(P) 3. If Type(n) is AttributeName a. For each a in x.[[Attributes]] i. If ((n.[[Name]].localName == "*") or (n.[[Name]].localName == a.[[Name]].localName)) and ((n.[[Name]].uri == null) or (n.[[Name]].uri == a.[[Name]].uri)) 1. Return true b. Return false 4. For (k = 0 to x.[[Length]]-1) a. If ((n.localName == "*") or ((x[k].[[Class]] == "element") and (x[k].[[Name]].localName == n.localName))) and ((n.uri == null) or (x[k].[[Class]] == "element") and (n.uri == x[k].[[Name]].uri))) i. Return true 5. Return false */ if(parseInt(p,10).toString() == p) return p == "0"; var name:QName = toXMLName(p); var i:int; var len:int; if(name.isAttribute) { len = attributeLength(); for(i=0;i<len;i++) { if(name.matches((_attributes[i] as XML).name())) return true; } } else { len = childrenLength(); for(i=0;i<len;i++) { if((_children[i] as XML).getNodeRef() != ELEMENT) continue; if((_children[i] as XML).name().matches(name)) return true; } } return false; } /** * Checks to see whether the XML object contains simple content. * * @return * * @royaleignorecoercion XML */ public function hasSimpleContent():Boolean { /* When the hasSimpleContent method is called on an XML object x, the following steps are taken: 1. If x.[[Class]] ∈ {"comment", "processing-instruction"}, return false 2. For each property p in x a. If p.[[Class]] == "element", return false 3. Return true */ var kind:String = getNodeRef(); if(kind == COMMENT || kind == PROCESSING_INSTRUCTION) return false; var i:int; var len:int = childrenLength(); for(i=0;i<len;i++) { if((_children[i] as XML).getNodeRef() == ELEMENT) return false; } return true; } /** * Lists the namespaces for the XML object, based on the object's parent. * * @return * */ public function inScopeNamespaces():Array { /* The inScopeNamespaces method returns an Array of Namespace objects representing the namespaces in scope for this XML object in the context of its parent. If the parent of this XML object is modified, the associated namespace declarations may change. The set of namespaces returned by this method may be a super set of the namespaces used by this value. Semantics When the inScopeNamespaces method is called on an XML object x, the following steps are taken: 1. Let y = x 2. Let inScopeNS = { } 3. While (y is not null) a. For each ns in y.[[InScopeNamespaces]] i. If there exists no n ∈ inScopeNS, such that n.prefix == ns.prefix 1. Let inScopeNS = inScopeNS ∪ { ns } b. Let y = y.[[Parent]] 4. Let a be a new Array created as if by calling the constructor, new Array() 5. Let i = 0 6. For each ns in inScopeNS a. Call the [[Put]] method of a with arguments ToString(i) and ns b. Let i = i + 1 7. Return a */ var y:XML = this; var inScopeNS:Array = []; var i:int = 0; var prefixCheck:Object = {}; while (y != null) { var searchNS:Array = y._namespaces; if (searchNS) { for each(var ns:Namespace in searchNS) { if (!prefixCheck[ns.prefix]) { inScopeNS[i++] = ns; prefixCheck[ns.prefix] = true; } } } y = y.parent(); } //return _namespaces ? _namespaces.slice() : []; return inScopeNS; } private function insertChildAt(child:XML,idx:int):void{ /* When the [[Insert]] method of an XML object x is called with property name P and value V, the following steps are taken: 1. If x.[[Class]] ∈ {"text", "comment", "processing-instruction", "attribute"}, return 2. Let i = ToUint32(P) 3. If (ToString(i) is not equal to P), throw a TypeError exception 4. If Type(V) is XML and (V is x or an ancestor of x) throw an Error exception 5. Let n = 1 6. If Type(V) is XMLList, let n = V.[[Length]] 7. If n == 0, Return 8. For j = x.[[Length]]-1 downto i, rename property ToString(j) of x to ToString(j + n) 9. Let x.[[Length]] = x.[[Length]] + n 10. If Type(V) is XMLList a. For j = 0 to V.[[Length-1]] i. V[j].[[Parent]] = x ii. x[i + j] = V[j] 11. Else a. Call the [[Replace]] method of x with arguments i and V 12. Return */ var kind:String = getNodeRef(); if(kind == TEXT || kind == COMMENT || kind == PROCESSING_INSTRUCTION || kind == ATTRIBUTE) return; if(!child) return; var parent:XML = child.parent(); if(parent) parent.removeChild(child); child.setParent(this); getChildren().splice(idx,0,child); } /** * Inserts the given child2 parameter after the child1 parameter in this XML object and returns the resulting object. * * @param child1 * @param child2 * @return * */ public function insertChildAfter(child1:XML, child2:XML):XML { /* When the insertChildAfter method is called on an XML object x with parameters child1 and child2, the following steps are taken: 1. If x.[[Class]] ∈ {"text", "comment", "processing-instruction", "attribute"}, return 2. If (child1 == null) a. Call the [[Insert]] method of x with arguments "0" and child2 b. Return x 3. Else if Type(child1) is XML a. For i = 0 to x.[[Length]]-1 i. If x[i] is the same object as child1 1. Call the [[Insert]] method of x with a */ var kind:String = getNodeRef(); if(kind == TEXT || kind == COMMENT || kind == PROCESSING_INSTRUCTION || kind == ATTRIBUTE) return null; if(!child1) { insertChildAt(child2,0); return child2; } var idx:int = getIndexOf(child1); if(idx >= 0) { insertChildAt(child2,idx+1); } return child2; } /** * Inserts the given child2 parameter before the child1 parameter in this XML object and returns the resulting object. * * @param child1 * @param child2 * @return * */ public function insertChildBefore(child1:XML, child2:XML):XML { /* When the insertChildBefore method is called on an XML object x with parameters child1 and child2, the following steps are taken: 1. If x.[[Class]] ∈ {"text", "comment", "processing-instruction", "attribute"}, return 2. If (child1 == null) a. Call the [[Insert]] method of x with arguments ToString(x.[[Length]]) and child2 b. Return x 3. Else if Type(child1) is XML a. For i = 0 to x.[[Length]]-1 i. If x[i] is the same object as child1 1. Call the [[Insert]] method of x with arguments ToString(i) and child2 2. Return x 4. Return */ var kind:String = getNodeRef(); if(kind == TEXT || kind == COMMENT || kind == PROCESSING_INSTRUCTION || kind == ATTRIBUTE) return null; if(!child1) { var len:int = childrenLength(); insertChildAt(child2,len); return child2; } var idx:int = getIndexOf(child1); if(idx >= 0) { insertChildAt(child2,idx); } return child2; } /** * For XML objects, this method always returns the integer 1. * * @return * */ public function length():int { return 1; } /** * Gives the local name portion of the qualified name of the XML object. * * @return * */ public function localName():String { return _name? _name.localName : null; } protected var _name:QName; /** * Gives the qualified name for the XML object. * * @return * */ public function name():QName { /*if(!_name) _name = getQName("","","",false);*/ return _name; } /** * If no parameter is provided, gives the namespace associated with the qualified name of this XML object. * * @param prefix * @return * */ public function namespace(prefix:String = null):* { /* When the namespace method is called on an XML object x with zero arguments or one argument prefix, the following steps are taken: 1. Let y = x 2. Let inScopeNS = { } 3. While (y is not null) a. For each ns in y.[[InScopeNamespaces]] i. If there exists no n ∈ inScopeNS, such that n.prefix == ns.prefix 1. Let inScopeNS = inScopeNS ∪ { ns } b. Let y = y.[[Parent]] 4. If prefix was not specified a. If x.[[Class]] ∈ {"text", "comment", "processing-instruction"}, return null b. Return the result of calling the [[GetNamespace]] method of x.[[Name]] with argument inScopeNS 5. Else a. Let prefix = ToString(prefix) b. Find a Namespace ns ∈ inScopeNS, such that ns.prefix = prefix. If no such ns exists, let ns = undefined. c. Return ns */ //4.a exit early before performing steps 2,3: var kind:String = getNodeRef(); if(kind == TEXT || kind == COMMENT || kind == PROCESSING_INSTRUCTION) return null; //step 2, 3: var inScopeNS:Array = inScopeNamespaces(); //step 4.b //no prefix. get the namespace of our object if (prefix == null) return name().getNamespace(inScopeNS); //step 5: var len:int = inScopeNS.length; for(var i:int=0;i<len;i++) { if(inScopeNS[i].prefix == prefix) return inScopeNS[i]; } return null; } /** * Lists namespace declarations associated with the XML object in the context of its parent. * * @return * */ public function namespaceDeclarations():Array { /* When the namespaceDeclarations method is called on an XML object x, the following steps are taken: 1. Let a be a new Array created as if by calling the constructor, new Array() 2. If x.[[Class]] ∈ {"text", "comment", "processing-instruction", "attribute"}, return a 3. Let y = x.[[Parent]] 4. Let ancestorNS = { } 5. While (y is not null) a. For each ns in y.[[InScopeNamespaces]] i. If there exists no n ∈ ancestorNS, such that n.prefix == ns.prefix 1. Let ancestorNS = ancestorNS ∪ { ns } b. Let y = y.[[Parent]] 6. Let declaredNS = { } 7. For each ns in x.[[InScopeNamespaces]] a. If there exists no n ∈ ancestorNS, such that n.prefix == ns.prefix and n.uri == ns.uri i. Let declaredNS = declaredNS ∪ { ns } 8. Let i = 0 9. For each ns in declaredNS a. Call the [[Put]] method of a with arguments ToString(i) and ns b. Let i = i + 1 10. Return a */ var kind:String = getNodeRef(); if(kind == TEXT || kind == COMMENT || kind == PROCESSING_INSTRUCTION || kind == ATTRIBUTE) return []; //early check - no need to look in the ancestors if there is nothing local to check: //[[InScopeNamespaces]] is nspaces here: var nspaces:Array = _namespaces; if (!nspaces || !nspaces.length) return []; //step 4 & 5: var ancestors:Array = _parent ? _parent.inScopeNamespaces() : []; //early check -quick exit if (!ancestors.length) { return nspaces.slice(); } var declaredNS:Array = []; var match:Boolean; //steps 7,8,9 for each(var ns:Namespace in nspaces) { match = false; for each(var ns2:Namespace in ancestors) { if (ns.prefix == ns.prefix && ns.uri == ns2.uri) { match = true; break; } } if (!match) { declaredNS.push(ns); } } //10 return declaredNS; } private var _nodeKind:String; protected function getNodeKindInternal():String{ return kindNameLookup[getNodeRef()]; } protected function getNodeRef():String{ if(_nodeKind) return _nodeKind; if(!_name) return TEXT; if(_name.isAttribute){ return ATTRIBUTE; } return ELEMENT; } private static const kindNameLookup:Object = { "e" : "element", "a" : "attribute", "p" : "processing-instruction", "t" : "text", "c" : "comment" }; private static const kindRefLookup:Object = { "element" : "e", "attribute" : "a", "processing-instruction" : "p", "text" : "t", "comment" : "c" }; /** * Specifies the type of node: text, comment, processing-instruction, attribute, or element. * @return * */ public function nodeKind():String { return getNodeKindInternal(); // append '' here to convert the String Object to a primitive } /** * For the XML object and all descendant XML objects, merges adjacent text nodes and eliminates empty text nodes. * * @return * */ public function normalize():XML { var len:int = childrenLength() - 1; var lastChild:XML; for(var i:int=len;i>=0;i--) { var child:XML = _children[i]; // can we have a null child? if(child.getNodeRef() == ELEMENT) { child.normalize(); } else if(child.getNodeRef() == TEXT) { if(lastChild && lastChild.getNodeRef() == TEXT) { child.setValue(child.s() + lastChild.s()); deleteChildAt(i+1); } if(!child.s()) { deleteChildAt(i); continue; //don't set last child if we removed it } } lastChild = child; } return this; } /** * Returns the parent of the XML object. * * @return * */ public function parent():* { return _parent; } public function plus(rightHand:*):* { var list:XMLList = new XMLList(); list.append(this); return list.plus(rightHand); } private function xmlFromStringable(value:*):XML { var str:String = value.toString(); var xml:XML = new XML(); xml.setValue(str); return xml; } /** * Inserts the provided child object into the XML element before any existing XML properties for that element. * @param value * @return * */ public function prependChild(child:XML):XML { var childType:String = typeof child; if(childType != "object") child = xmlFromStringable(child); prependChildInternal(child); normalize(); return this; } private function prependChildInternal(child:*):void { if(child is XMLList) { var len:int = child.length(); for(var i:int=0; i<len; i++) { prependChildInternal(child[0]); } } else { assertType(child,XML,"Type must be XML"); child.setParent(this); getChildren().unshift(child); } } /** * If a name parameter is provided, lists all the children of the XML object that contain processing instructions with that name. * * @param name * @return * * @royaleignorecoercion XML */ public function processingInstructions(name:String = "*"):XMLList { var i:int; var list:XMLList = new XMLList(); var len:int = childrenLength(); for(i=0;i<len;i++) { if((_children[i] as XML).getNodeRef() == PROCESSING_INSTRUCTION) list.append(_children[i]); } list.targetObject = this; return list; } /** * Removes the given child for this object and returns the removed child. * * @param child * @return * */ public function removeChild(child:XML):Boolean { /* When the [[Delete]] method of an XML object x is called with property name P, the following steps are taken: 1. If ToString(ToUint32(P)) == P, throw a TypeError exception NOTE this operation is reserved for future versions of E4X. 2. Let n = ToXMLName(P) 3. If Type(n) is AttributeName a. For each a in x.[[Attributes]] i. If ((n.[[Name]].localName == "*") or (n.[[Name]].localName == a.[[Name]].localName)) and ((n.[[Name]].uri == null) or (n.[[Name]].uri == a.[[Name]].uri)) 1. Let a.[[Parent]] = null 2. Remove the attribute a from x.[[Attributes]] b. Return true 4. Let dp = 0 5. For q = 0 to x.[[Length]]-1 a. If ((n.localName == "*") or (x[q].[[Class]] == "element" and x[q].[[Name]].localName == n.localName)) and ((n.uri == null) or (x[q].[[Class]] == “element” and n.uri == x[q].[[Name]].uri )) i. Let x[q].[[Parent]] = null ii. Remove the property with the name ToString(q) from x iii. Let dp = dp + 1 b. Else i. If dp > 0, rename property ToString(q) of x to ToString(q – dp) 6. Let x.[[Length]] = x.[[Length]] - dp 7. Return true. */ var i:int; var len:int; var removed:XML; if(!child) return false; if(child is XMLList){ var val:Boolean = false; len = child.length(); for(i=len-1;i>=0;i--){ if(removeChild(child[i])){ val = true; } } return val; } if(!(child is XML)) return removeChildByName(child); if(child.getNodeRef() == ATTRIBUTE) { len = attributeLength(); for(i=0;i<len;i++) { if(child.equals(_attributes[i])) { removed = _attributes[i]; removed._parent = null; _attributes.splice(i,1); return true; } } return false; } var idx:int = getIndexOf(child); if(idx < 0) return false; removed = _children.splice(idx,1); child._parent = null; return true; } /** * * @royaleignorecoercion XML */ private function removeChildByName(name:*):Boolean { var i:int; var len:int; name = toXMLName(name); var child:XML; var removedItem:Boolean = false; if(name.isAttribute) { len = attributeLength() -1; for(i=len;i>=0;i--) { child = _attributes[i] as XML; if(name.matches(child.name())) { child = _attributes[i]; child._parent = null; _attributes.splice(i,1); removedItem = true; } } return removedItem; } //QUESTION am I handling non-elements correctly? len = childrenLength() - 1; for(i=len;i>=0;i--) { child = _children[i] as XML; if(child.getNodeRef() != ELEMENT){ continue; } if(name.matches(child.name())) { child = _children[i]; child._parent = null; _children.splice(i,1); removedItem = true; } } normalize(); // <-- check this is correct return removedItem; } public function removeChildAt(index:int):Boolean { /* When the [[DeleteByIndex]] method of an XML object x is called with property name P, the following steps are taken: 1. Let i = ToUint32(P) 2. If ToString(i) == P a. If i is less than x.[[Length]] i. If x has a property with name P 1. Let x[P].[[Parent]] = null 2. Remove the property with the name P from x ii. For q = i+1 to x.[[Length]]-1 1. Rename property ToString(q) of x to ToString(q – 1) iii. Let x.[[Length]] = x.[[Length]] – 1 b. Return true 3. Else throw a TypeError exception */ //Do nothing for XML objects? if (index < childrenLength()) { var removed:XML = _children[index]; if (removed) { removed.setParent(null); index =_children.indexOf(removed); if (index != -1){ _children.splice(index,1); } } return true; } throw new TypeError("Cannot call delete on XML at index "+index); } /** * Removes the given namespace for this object and all descendants. * * @param ns * @return * * @royaleignorecoercion XML */ public function removeNamespace(ns:*):XML { /* Overview The removeNamespace method removes the given namespace from the in scope namespaces of this object and all its descendents, then returns a copy of this XML object. The removeNamespaces method will not remove a namespace from an object where it is referenced by that object’s QName or the QNames of that object’s attributes. Semantics When the removeNamespace method is called on an XML object x with parameter namespace, the following steps are taken: 1. If x.[[Class]] ∈ {"text", "comment", "processing-instruction", "attribute"}, return x 2. Let ns be a Namespace object created as if by calling the function Namespace( namespace ) 3. Let thisNS be the result of calling [[GetNamespace]] on x.[[Name]] with argument x.[[InScopeNamespaces]] 4. If (thisNS == ns), return x 5. For each a in x.[[Attributes]] a. Let aNS be the result of calling [[GetNamespace]] on a.[[Name]] with argument x.[[InScopeNamespaces]] b. If (aNS == ns), return x 6. If ns.prefix == undefined a. If there exists a namespace n ∈ x.[[InScopeNamespaces]], such that n.uri == ns.uri, remove the namespace n from x.[[InScopeNamespaces]] 7. Else a. If there exists a namespace n ∈ x.[[InScopeNamespaces]], such that n.uri == ns.uri and n.prefix == ns.prefix, remove the namespace n from x.[[InScopeNamespaces]] 8. For each property p of x a. If p.[[Class]] = "element", call the removeNamespace method of p with argument ns 9. Return x */ var i:int; var len:int; var ref:String = getNodeRef(); if(ref == TEXT || ref == COMMENT || ref == PROCESSING_INSTRUCTION || ref == ATTRIBUTE) return this; if(!(ns is Namespace)) ns = new Namespace(ns); if(ns == name().getNamespace(_namespaces)) return this; len = attributeLength(); for(i=0;i<len;i++) { if(ns == _attributes[i].name().getNamespace(_namespaces)) return this; } // len = namespaceLength(); for(i=len-1;i>=0;i--) { if(_namespaces[i].uri == ns.uri && _namespaces[i].prefix == ns.prefix) _namespaces.splice(i,1); else if(ns.prefix == null && _namespaces[i].uri == ns.uri) _namespaces.splice(i,1); } len = childrenLength(); for(i=0;i<len;i++) { if((_children[i] as XML).getNodeRef() == ELEMENT) (_children[i] as XML).removeNamespace(ns); } return this; } /** * Replaces the properties specified by the propertyName parameter with the given value parameter. * * @param propertyName * @param value * @return * */ public function replace(propertyName:Object, value:*):* { //@todo this is not finished - needs work, review and testing. Reference to [[Replace]] below should call 'replaceChildAt' /* Semantics (x refers to 'this') When the replace method is called on an XML object x with parameters propertyName and value, the following steps are taken: 1. If x.[[Class]] ∈ {"text", "comment", "processing-instruction", "attribute"}, return x 2. If Type(value) ∉ {XML, XMLList}, let c = ToString(value) 3. Else let c be the result of calling the [[DeepCopy]] method of value 4. If ToString(ToUint32(P)) == P a. Call the [[Replace]] method of x with arguments P and c and return x 5. Let n be a QName object created as if by calling the function QName(P) 6. Let i = undefined 7. For k = x.[[Length]]-1 downto 0 a. If ((n.localName == "*") or ((x[k].[[Class]] == "element") and (x[k].[[Name]].localName==n.localName))) and ((n.uri == null) or ((x[k].[[Class]] == "element") and (n.uri == x[k].[[Name]].uri ))) i. If (i is not undefined), call the [[DeleteByIndex]] method of x with argument ToString(i) ii. Let i = k 8. If i == undefined, return x 9. Call the [[Replace]] method of x with arguments ToString(i) and c 10. Return x */ var ref:String = getNodeRef(); if(ref == TEXT || ref == COMMENT || ref == PROCESSING_INSTRUCTION || ref == ATTRIBUTE) { // Changing this to pretend we're a string return s().replace(propertyName,value); //return this; } if(value === null || value === undefined) return this; if((value is XML) || (value is XMLList)) value = value.copy(); else value = value.toString(); return null; } /** * * @royaleignorecoercion XML * @royaleignorecoercion XMLList */ public function replaceChildAt(idx:int,v:*):void { /* **this is the [[Replace]] method in the spec** When the [[Replace]] method of an XML object x is called with property name P and value V, the following steps are taken: 1. If x.[[Class]] ∈ {"text", "comment", "processing-instruction", "attribute"}, return 2. Let i = ToUint32(P) 3. If (ToString(i) is not equal to P), throw a TypeError exception 4. If i is greater than or equal to x.[[Length]], a. Let P = ToString(x.[[Length]]) b. Let x.[[Length]] = x.[[Length]] + 1 5. If Type(V) is XML and V.[[Class]] ∈ {"element", "comment", "processing-instruction", "text"} a. If V.[[Class]] is “element” and (V is x or an ancestor of x) throw an Error exception b. Let V.[[Parent]] = x c. If x has a property with name P i. Let x[P].[[Parent]] = null d. Let x[P] = V 6. Else if Type(V) is XMLList a. Call the [[DeleteByIndex]] method of x with argument P b. Call the [[Insert]] method of x with arguments P and V 7. Else a. Let s = ToString(V) b. Create a new XML object t with t.[[Class]] = "text", t.[[Parent]] = x and t.[[Value]] = s c. If x has a property with name P i. Let x[P].[[Parent]] = null d. Let the value of property P of x be t 8. Return */ var len:int; var ref:String = getNodeRef(); if(ref == TEXT || ref == COMMENT || ref == PROCESSING_INSTRUCTION || ref == ATTRIBUTE) return; len = childrenLength(); if(idx > len) idx = len; // make sure _children exist getChildren(); if(v is XML && (v as XML).getNodeRef() != ATTRIBUTE) { if((v as XML).getNodeRef() == ELEMENT && (v==this || isAncestor(v)) ) throw new TypeError("cannot assign parent xml as child"); v.setParent(this); if(_children[idx]) removeChild(_children[idx]); insertChildAt(v,idx); } else if(v is XMLList) { len = (v as XMLList).length(); //6. if(_children[idx]) _children[idx]._parent = null; if (len) { v[0].setParent(this); _children[idx] = v[0]; var listIdx:int = 1; var chld:XML = v[0]; while(listIdx < len) { chld = v[listIdx]; insertChildAt(chld,idx+listIdx); listIdx++; } } else { _children.splice(idx,1); } } else { //7. this is a text node chld = new XML(); chld.setValue(v + '');//7.a, 7.b chld.setParent(this); if (_children[idx] != null) (_children[idx] as XML).setParent(null); _children[idx] = chld; } } private function isAncestor(xml:XML):Boolean { var p:XML = _parent; while(p) { if(p == xml) return true; p = p._parent; } return false; } /** * * @royaleignorecoercion XML */ public function setAttribute(attr:*,value:String):String { var i:int; //make sure _attributes is not null getAttributes(); if(attr is XML) { if((attr as XML).getNodeRef() == ATTRIBUTE) { var len:int = attributeLength(); for(i=0;i<len;i++) { if(_attributes[i].name().equals(attr.name())) { _attributes[i].setValue(value); return value; } } if(value) attr.setValue(value); addChild(attr); } return value; } if(typeof attr == 'string' && attr.indexOf("xmlns") == 0) { //it's a namespace declaration var ns:Namespace; var prfIdx:int = attr.indexOf(":"); if (prfIdx != -1){ ns = new Namespace(attr.substring(prfIdx + 1), value.toString()); } else ns = new Namespace(value.toString()); this.addNamespace(ns); } else { //it's a regular attribute string var attrXML:XML = new XML(); var nameRef:QName = toAttributeName(attr); attrXML._name = getQName(nameRef.localName,nameRef.prefix,nameRef.uri,true); attrXML.setValue(value); len = attributeLength(); for(i=0;i<len;i++) { if(_attributes[i].name().equals(attrXML.name())) { _attributes[i].setValue(value); return value; } } addChild(attrXML); } return value; } /** * Replaces the child properties of the XML object with the specified name with the specified XML or XMLList. * This is primarily used to support dot notation assignment of XML. * * @param value * @return * * @royaleignorecoercion QName * @royaleignorecoercion XML */ public function setChild(elementName:*, elements:Object):Object { /* * [[Put]] 1. If ToString(ToUint32(P)) == P, throw a TypeError exception NOTE this operation is reserved for future versions of E4X. 2. If x.[[Class]] ∈ {"text", "comment", "processing-instruction", "attribute"}, return 3. If (Type(V) ∉ {XML, XMLList}) or (V.[[Class]] ∈ {"text", "attribute"}) a. Let c = ToString(V) 4. Else a. Let c be the result of calling the [[DeepCopy]] method of V 5. Let n = ToXMLName(P) 6. If Type(n) is AttributeName a. Call the function isXMLName (section 13.1.2.1) with argument n.[[Name]] and if the result is false, return b. If Type(c) is XMLList i. If c.[[Length]] == 0, let c be the empty string ii. Else 1. Let s = ToString(c[0]) 2. For i = 1 to c.[[Length]]-1 a. Let s be the result of concatenating s, the string " " (space) and ToString(c[i]) 3. Let c = s c. Else i. Let c = ToString(c) d. Let a = null e. For each j in x.[[Attributes]] i. If (n.[[Name]].localName == j.[[Name]].localName) and ((n.[[Name]].uri == null) or (n.[[Name]].uri == j.[[Name]].uri)) 1. If (a == null), a = j 2. Else call the [[Delete]] method of x with argument j.[[Name]] f. If a == null i. If n.[[Name]].uri == null 1. Let nons be a new Namespace created as if by calling the constructor new Namespace() 2. Let name be a new QName created as if by calling the constructor new QName(nons, n.[[Name]]) ii. Else 1. Let name be a new QName created as if by calling the constructor new QName(n.[[Name]]) iii. Create a new XML object a with a.[[Name]] = name, a.[[Class]] == "attribute" and a.[[Parent]] = x iv. Let x.[[Attributes]] = x.[[Attributes]] ∪ { a } v. Let ns be the result of calling the [[GetNamespace]] method of name with no arguments vi. Call the [[AddInScopeNamespace]] method of x with argument ns g. Let a.[[Value]] = c h. Return 7. Let isValidName be the result of calling the function isXMLName (section 13.1.2.1) with argument n 8. If isValidName is false and n.localName is not equal to the string "*", return 9. Let i = undefined 10. Let primitiveAssign = (Type(c) ∉ {XML, XMLList}) and (n.localName is not equal to the string "*") 11. For (k = x.[[Length]]-1 downto 0) a. If ((n.localName == "*") or ((x[k].[[Class]] == "element") and (x[k].[[Name]].localName==n.localName))) and ((n.uri == null) or ((x[k].[[Class]] == “element”) and (n.uri == x[k].[[Name]].uri ))) i. If (i is not undefined), call the [[DeleteByIndex]] property of x with argument ToString(i) ii. Let i = k 12. If i == undefined a. Let i = x.[[Length]] b. If (primitiveAssign == true) i. If (n.uri == null) 1. Let name be a new QName created as if by calling the constructor new QName(GetDefaultNamespace(), n) ii. Else 1. Let name be a new QName created as if by calling the constructor new QName(n) iii. Create a new XML object y with y.[[Name]] = name, y.[[Class]] = "element" and y.[[Parent]] = x iv. Let ns be the result of calling [[GetNamespace]] on name with no arguments v. Call the [[Replace]] method of x with arguments ToString(i) and y vi. Call [[AddInScopeNamespace]] on y with argument ns 13. If (primitiveAssign == true) a. Delete all the properties of the XML object x[i] b. Let s = ToString(c) c. If s is not the empty string, call the [[Replace]] method of x[i] with arguments "0" and s 14. Else a. Call the [[Replace]] method of x with arguments ToString(i) and c 15. Return */ var i:int; /* var len:int; var chld:XML; var retVal:Object = elements; var chldrn:XMLList; var childIdx:int;*/ if (uint(elementName).toString() == elementName) throw new TypeError('not permitted'); var ref:String = getNodeRef(); if(ref == TEXT || ref == COMMENT || ref == PROCESSING_INSTRUCTION || ref == ATTRIBUTE) return this; var n:QName = toXMLName(elementName); //5. if (n.isAttribute) { //@todo return setAttribute(n, elements+''); } //7.0 //8.0 // elements = elements + ''; //13.b i = -1;// undefined; var wild:Boolean = n.localName == '*'; var primitiveAssign:Boolean = !wild && !(elements is XML || elements is XMLList);//primitiveAssign step 10. var k:int = childrenLength() - 1; //11 while (k > -1) { //11 if ( ( wild || ((_children[k] as XML).getNodeRef() == ELEMENT && (_children[k] as XML).localName() == n.localName) ) && (n.uri == null /* maybe: !n.uri ? */ || ((_children[k] as XML).getNodeRef() == ELEMENT && QName((_children[k] as XML)._name).uri == n.uri))) { if (i !== -1) { removeChildAt(i); //11.a.i } i = k; //11.a.ii } k--; } if (i == -1) { //12. i = childrenLength(); //12.a if (primitiveAssign) { //12.b //skipping 12.b.i and 12.b.ii for now...@todo review /*if (n.uri == null) { } else { }*/ _internal = true; var y:XML = new XML(); _internal = false; y._name = getQName(n.localName,n.prefix,n.uri,false); y.setParent(this); //end of 12.n.iii var ns:Namespace = new Namespace('', n); replaceChildAt(i,y); y.setNamespace(ns);//@todo check this for 12.b.iv and 12.b.vi } } if (primitiveAssign) { //13 @todo review guess at conditional //13.a. Delete all the properties of the XML object x[i] y = _children[i]; k = y.childrenLength() - 1; while(k>-1) { y.removeChildAt(k); //13.a k--; } elements = elements + ''; //13.b if (elements) { y.replaceChildAt(0, elements); //13.c } } else { //elements = (elements as XML).copy(); //@todo check... might need attention here replaceChildAt(i, elements); //14.a } return elements; } /** * Replaces the child properties of the XML object with the specified set of XML properties, provided in the value parameter. * * @param value * @return * */ public function setChildren(value:Object):XML { var i:int; var len:int; var chld:XML; if(value is XML) { var list:XMLList = new XMLList(); list[0] = value; value = list; } if(value is XMLList) { // remove all existing elements var chldrn:XMLList = children(); var childIdx:int = chldrn.length() -1; if(chldrn.length()) childIdx = chldrn[0].childIndex(); len = chldrn.length() -1; for (i= len; i >= 0; i--) { removeChild(chldrn[i]); // remove the nodes // remove the children // adjust the childIndexes } var curChild:XML = getChildren()[childIdx]; // Now add them in. len = value.length(); for(i=0;i<len;i++) { chld = value[i]; if(!curChild) { curChild = chld; appendChild(chld); } else { insertChildAfter(curChild, chld); curChild = chld; } } } return this; } /** * Changes the local name of the XML object to the given name parameter. * * @param name * */ public function setLocalName(name:String):void { if(!_name) _name = new QName(); _name = getQName(name,_name.prefix,_name.uri,_name.isAttribute) // _name.localName = name; } /** * Sets the name of the XML object to the given qualified name or attribute name. * * @param name * */ public function setName(name:*):void { //@todo add tests to review against the following: /*1. If x.[[Class]] ∈ {"text", "comment"}, return 2. If (Type(name) is Object) and (name.[[Class]] == "QName") and (name.uri == null) a. Let name = name.localName 3. Let n be a new QName created if by calling the constructor new QName(name) 4. If x.[[Class]] == "processing-instruction", let n.uri be the empty string 5. Let x.[[Name]] = n 6. Let ns be a new Namespace created as if by calling the constructor new Namespace(n.prefix, n.uri) 7. If x.[[Class]] == "attribute" a. If x.[[Parent]] == null, return b. Call x.[[Parent]].[[AddInScopeNamespace]](ns) 8. If x.[[Class]] == "element" a. Call x.[[AddInScopeNamespace]](ns)*/ var ref:String = getNodeRef(); if (ref == TEXT || ref == COMMENT) return; //e4x, see 1 above var nameRef:QName; if(name is QName) nameRef = name; else nameRef = new QName(name); var asAtttribute:Boolean = nameRef.isAttribute; _name = getQName(nameRef.localName,nameRef.prefix,nameRef.uri,asAtttribute); if (asAtttribute) { //optimization, the name alone is sufficient to get the nodeKind() externally (see : getNodeRef()) delete this._nodeKind; } } /** * Sets the namespace associated with the XML object. * * @param ns * */ public function setNamespace(ns:Object):void { var kind:String = getNodeRef(); if(kind == TEXT || kind == COMMENT || kind == PROCESSING_INSTRUCTION) return; var ns2:Namespace = new Namespace(ns); var nameRef:QName = new QName(ns2,name()); if(kind == ATTRIBUTE) { if(_parent == null) return; nameRef.setIsAttribute(true); _parent.addNamespace(ns2); } _name = getQName(nameRef.localName,nameRef.prefix,nameRef.uri,nameRef.isAttribute); if(kind == ELEMENT) addNamespace(ns2); } /** * @private * */ public function setNodeKind(value:String):void { // memory optimization. The default on the prototype is "element" and using the prototype saves memory if(getNodeKindInternal() != value) { var kind:String = kindRefLookup[value]; if(kind){ _nodeKind = kind; } } } /** * @private * @royalesuppressexport */ public function setParent(parent:XML, keep:Boolean=false):void { if(parent == _parent) return; var oldParent:XML = _parent; if(oldParent && !keep) oldParent.removeChild(this); _parent = parent; } public function setValue(value:String):void { _value = value; } /** * @private * * Allows XMLList to get the targetObject of its targetObject and not error when it gets the XML */ public function get targetObject():* { return null; } /** * Returns an XMLList object of all XML properties of the XML object that represent XML text nodes. * * @return * */ public function text():XMLList { var list:XMLList = new XMLList(); var i:int; var len:int = childrenLength(); for(i=0;i<len;i++) { var child:XML = _children[i]; if(child.getNodeRef() == TEXT) list.append(child); } list.targetObject = this; return list; } /** * Provides an overridable method for customizing the JSON encoding of values in an XML object. * * @param k * @return * */ /* override public function toJSON(k:String):String { return this.name(); } */ /** * Returns a string representation of the XML object. * * @return * */ public function toString():String { var i:int; // text, comment, processing-instruction, attribute, or element var kind:String = getNodeRef(); if( kind == ATTRIBUTE) return _value; if(kind == TEXT) return _value && _value.indexOf('<![CDATA[') == 0 ? _value.substring(9, _value.length-3): _value; if(kind == COMMENT) return ""; if(kind == PROCESSING_INSTRUCTION) return ""; if(this.hasSimpleContent()) { var s:String = ""; var len:int = childrenLength(); for(i=0;i<len;i++) { var child:XML = _children[i]; var childKind:String = child.getNodeRef(); if(child.childKind == COMMENT || child.childKind == PROCESSING_INSTRUCTION) continue; s = s + child.toString(); } return s; } return toXMLString(); } /** * * @royaleignorecoercion QName */ /*private function toAttributeName(name:*):QName { const typeName:String = typeof name; if (name == null || typeName == 'number'|| typeName == 'boolean') { throw new TypeError('invalid xml name'); } var qname:QName; //@todo: typeName == 'object' && ... etc here (avoid Language.is) if (name is QName) { if (QName(name).isAttribute) qname = name as QName; else { qname = new QName(name); qname.setIsAttribute(true); } } else { var str:String = name.toString(); //normalize var idx:int = str.indexOf('@'); if (idx != -1) str = str.slice(idx+1); qname = new QName(str); qname.setIsAttribute(true); } return qname; }*/ private function toXMLName(name:*):QName { /* Given a string s, the ToXMLName conversion function returns a QName object or AttributeName. If the first character of s is "@", ToXMLName creates an AttributeName using the ToAttributeName operator. Otherwise, it creates a QName object using the QName constructor. Semantics Given a String value s, ToXMLName operator converts it to a QName object or AttributeName using the following steps: 1. If ToString(ToUint32(s)) == ToString(s), throw a TypeError exception 2. If the first character of s is "@" a. Let name = s.substring(1, s.length) b. Return ToAttributeName(name) 3. Else a. Return a QName object created as if by calling the constructor new QName(s) */ const typeName:String = typeof name; if (name == null || typeName=='number'|| typeName=='boolean') { throw new TypeError('invalid xml name'); } //@todo: typeName == 'object' && ... etc here (avoid Language.is) if (name is QName) { return name; } var str:String = name.toString(); if(parseInt(str,10).toString() == name) throw new TypeError("invalid element name"); if(str.indexOf("@") == 0) return toAttributeName(name); return new QName(str); } /** * Returns a string representation of the XML object. * * @return * */ public function toXMLString():String{ return _toXMLString(); } /** * * @royaleignorecoercion XML */ private function _toXMLString(indentLevel:int=0,ancestors:Array=null):String { /* Given an XML object x and an optional argument AncestorNamespaces and an optional argument IndentLevel, ToXMLString converts it to an XML encoded string s by taking the following steps: 1. Let s be the empty string 2. If IndentLevel was not provided, Let IndentLevel = 0 3. If (XML.prettyPrinting == true) a. For i = 0 to IndentLevel-1, let s be the result of concatenating s and the space <SP> character 4. If x.[[Class]] == "text", a. If (XML.prettyPrinting == true) i. Let v be the result of removing all the leading and trailing XMLWhitespace characters from x.[[Value]] ii. Return the result of concatenating s and EscapeElementValue(v) b. Else i. Return EscapeElementValue(x.[[Value]]) 5. If x.[[Class]] == "attribute", return the result of concatenating s and EscapeAttributeValue(x.[[Value]]) 6. If x.[[Class]] == "comment", return the result of concatenating s, the string "<!--", x.[[Value]] and the string "-->" 7. If x.[[Class]] == "processing-instruction", return the result of concatenating s, the string "<?", x.[[Name]].localName, the space <SP> character, x.[[Value]] and the string "?>" 8. If AncestorNamespaces was not provided, let AncestorNamespaces = { } 9. Let namespaceDeclarations = { } 10. For each ns in x.[[InScopeNamespaces]] a. If there is no ans ∈ AncestorNamespaces, such that ans.uri == ns.uri and ans.prefix == ns.prefix i. Let ns1 be a copy of ns ii. Let namespaceDeclarations = namespaceDeclarations ∪ { ns1 } NOTE implementations may also exclude unused namespace declarations from namespaceDeclarations 11. For each name in the set of names consisting of x.[[Name]] and the name of each attribute in x.[[Attributes]] a. Let namespace be a copy of the result of calling [[GetNamespace]] on name with argument (AncestorNamespaces ∪ namespaceDeclarations) b. If (namespace.prefix == undefined), i. Let namespace.prefix be an arbitrary implementation defined namespace prefix, such that there is no ns2 ∈ (AncestorNamespaces ∪ namespaceDeclarations) with namespace.prefix == ns2.prefix ii. Note: implementations should prefer the empty string as the implementation defined prefix if it is not already used in the set (AncestorNamespaces ∪ namespaceDeclarations) iii. Let namespaceDeclarations = namespaceDeclarations ∪ { namespace } 12. Let s be the result of concatenating s and the string "<" 13. If namespace.prefix is not the empty string, a. Let s be the result of concatenating s, namespace.prefix and the string ":" 14. Let s be the result of concatenating s and x.[[Name]].localName 15. Let attrAndNamespaces = x.[[Attributes]] ∪ namespaceDeclarations 16. For each an in attrAndNamespaces a. Let s be the result of concatenating s and the space <SP> character b. If Type(an) is XML and an.[[Class]] == "attribute" i. Let ans be a copy of the result of calling [[GetNamespace]] on a.[[Name]] with argument AncestorNamespaces ii. If (ans.prefix == undefined), 1. Let ans.prefix be an arbitrary implementation defined namespace prefix, such that there is no ns2 ∈ (AncestorNamespaces ∪ namespaceDeclarations) with ans.prefix == ns2.prefix 2. If there is no ns2 ∈ (AncestorNamespaces ∪ namespaceDeclarations), such that ns2.uri == ans.uri and ns2.prefix == ans.prefix a. Let namespaceDeclarations = namespaceDeclarations ∪ { ans } iii. If ans.prefix is not the empty string 1. Let s be the result of concatenating s, namespace.prefix and the string ":" iv. Let s be the result of concatenating s and a.[[Name]].localName c. Else i. Let s be the result of concatenating s and the string "xmlns" ii. If (an.prefix == undefined), 1. Let an.prefix be an arbitrary implementation defined namespace prefix, such that there is no ns2 ∈ (AncestorNamespaces ∪ namespaceDeclarations) with an.prefix == ns2.prefix iii. If an.prefix is not the empty string 1. Let s be the result of concatenating s, the string ":" and an.prefix d. Let s be the result of concatenating s, the string "=" and a double-quote character (i.e. Unicode codepoint \u0022) e. If an.[[Class]] == "attribute" i. Let s be the result of concatenating s and EscapeAttributeValue(an.[[Value]]) f. Else i. Let s be the result of concatenating s and EscapeAttributeValue(an.uri) g. Let s be the result of concatenating s and a double-quote character (i.e. Unicode codepoint \u0022) 17. If x.[[Length]] == 0 a. Let s be the result of concatenating s and "/>" b. Return s 18. Let s be the result of concatenating s and the string ">" 19. Let indentChildren = ((x.[[Length]] > 1) or (x.[[Length]] == 1 and x[0].[[Class]] is not equal to "text")) 20. If (XML.prettyPrinting == true and indentChildren == true) a. Let nextIndentLevel = IndentLevel + XML.PrettyIndent. 21. Else a. Let nextIndentLevel = 0 22. For i = 0 to x.[[Length]]-1 a. If (XML.prettyPrinting == true and indentChildren == true) i. Let s be the result of concatenating s and a LineTerminator b. Let child = ToXMLString (x[i], (AncestorNamespaces ∪ namespaceDeclarations), nextIndentLevel) c. Let s be the result of concatenating s and child 23. If (XML.prettyPrinting == true and indentChildren == true), a. Let s be the result of concatenating s and a LineTerminator b. For i = 0 to IndentLevel, let s be the result of concatenating s and a space <SP> character 24. Let s be the result of concatenating s and the string "</" 25. If namespace.prefix is not the empty string a. Let s be the result of concatenating s, namespace.prefix and the string ":" 26. Let s be the result of concatenating s, x.[[Name]].localName and the string ">" 27. Return s NOTE Implementations may also preserve insignificant whitespace (e.g., inside and between element tags) and attribute quoting conventions in ToXMLString(). */ var i:int; var len:int; var ns:Namespace; var strArr:Array = []; indentLevel = isNaN(indentLevel) ? 0 : indentLevel; var indentArr:Array = []; for(i=0;i<indentLevel;i++) indentArr.push(_indentStr); var indent:String = indentArr.join(""); const nodeType:String = getNodeRef(); if(nodeType == TEXT) //4. { if(prettyPrinting) { var v:String = trimXMLWhitespace(_value); if (v.indexOf('<![CDATA[') == 0) { return indent + v; } return indent + escapeElementValue(v); } if (_value.indexOf('<![CDATA[') == 0) return _value; return escapeElementValue(_value); } if(nodeType == ATTRIBUTE) return indent + escapeAttributeValue(_value); if(nodeType == COMMENT) return indent + "<!--" + _value + "-->"; if(nodeType == PROCESSING_INSTRUCTION) return indent + "<?" + name().localName + " " + _value + "?>"; // We excluded the other types, so it's a normal element // step 8. var inScopeNS:Array; //ancestors if(!ancestors) { ancestors = []; //this has thee effect of matching AVM behavior which is slightly off spec, see here: // https://github.com/adobe/avmplus/blob/master/core/XMLObject.cpp#L1207 inScopeNS = inScopeNamespaces(); } else inScopeNS = _namespaces? _namespaces : []; var myQName:QName = _name; var declarations:Array; if (ancestors.length == 0) { declarations = inScopeNS; } else { declarations = []; len = inScopeNS.length;//namespaceLength(); for(i=0;i<len;i++) { if(!namespaceInArray(inScopeNS[i],ancestors)) declarations.push(new Namespace(inScopeNS[i])); } } //11 len = attributeLength(); for(i=0;i<len;i++) { ns = new Namespace(_attributes[i].name().getNamespace(declarations.concat(ancestors))); if(ns.prefix === null) { //@todo Note step 11.b.i and 11.b.ii empty string is preferred *only* if it is not already used in the set ns.setPrefix(""); declarations.push(ns); } } //favour the default namespace prefix as '' if it is defined with a prefix elsewhere there twice. ns = new Namespace(myQName.getNamespace(declarations.concat(ancestors))); if(ns.prefix === null) { //@todo Note step 11.b.i and 11.b.ii empty string is preferred *only* if it is not already used in the set ns.setPrefix(""); declarations.push(ns); } if(XML.prettyPrinting && indentLevel > 0) { strArr.push(new Array(indentLevel + 1).join(_indentStr)); } strArr.push("<"); if(ns.prefix) strArr.push(ns.prefix+":"); strArr.push(myQName.localName); //attributes and namespace declarations... (15-16) len = attributeLength(); for(i=0;i<len;i++) { strArr.push(" "); var aName:QName = _attributes[i].name(); var ans:Namespace = aName.getNamespace(declarations.concat(ancestors)); if(ans.prefix) { strArr.push(ans.prefix); strArr.push(":"); } strArr.push(aName.localName); strArr.push('="'); strArr.push(escapeAttributeValue(_attributes[i].getValue())); strArr.push('"'); } // see 15. namespace declarations is after for(i=0;i<declarations.length;i++) { var decVal:String = escapeAttributeValue(declarations[i].uri); if(decVal) { strArr.push(" xmlns"); if(declarations[i].prefix) { strArr.push(":"); strArr.push(declarations[i].prefix); } strArr.push('="'); strArr.push(decVal); strArr.push('"'); } } // now write elements or close the tag if none exist len = childrenLength(); if(len == 0) { strArr.push("/>"); return strArr.join(""); } strArr.push(">"); var indentChildren:Boolean = len > 1 || (len == 1 && (_children[0] as XML).getNodeRef() != TEXT); var nextIndentLevel:int; if(XML.prettyPrinting && indentChildren) nextIndentLevel = indentLevel + 1; else nextIndentLevel = 0; for(i=0;i<len;i++) { // if(XML.prettyPrinting && indentChildren) strArr.push("\n"); strArr.push(XML(_children[i])._toXMLString(nextIndentLevel,declarations.concat(ancestors))); } if(XML.prettyPrinting && indentChildren) { strArr.push("\n"); if (indentLevel > 0) strArr.push(new Array(indentLevel + 1).join(_indentStr)); } strArr.push("</"); if(ns.prefix) { strArr.push(ns.prefix); strArr.push(":"); } strArr.push(myQName.localName); strArr.push(">"); return strArr.join(""); } /** * Returns the XML object. * * @return * */ override public function valueOf():* { var str:String = this.toString(); if(str == "") return str; var num:Number = Number(str); if("" + num == str){ return num; } return str; } //////////////////////////////////////////////////////////////// /// /// /// METHODS to allow XML to behave as if it's a string or number /// /// //////////////////////////////////////////////////////////////// public function charAt(index:Number):String { return s().charAt(index); } public function charCodeAt(index:Number):Number { return s().charCodeAt(index); } public function codePointAt(pos:Number):Number { return s().codePointAt(pos); } /* public function concat(... args):Array { return s().concat(args); } */ public function indexOf(searchValue:String,fromIndex:Number=0):Number { return s().indexOf(searchValue,fromIndex); } public function lastIndexOf(searchValue:String,fromIndex:Number=0):Number { return s().lastIndexOf(searchValue,fromIndex); } public function localeCompare(compareString:String,locales:*=undefined, options:*=undefined):Number { return s().localeCompare(compareString,locales,options); } public function match(regexp:*):Array { return s().match(regexp); } /* Moved this logic (partially) into the other replace method public function replace(regexp:*,withStr:*):String { return s().replace(regexp,withStr); } */ public function search(regexp:*):Number { return s().search(regexp); } public function slice(beginSlice:Number, endSlice:*=undefined):String { return s()["slice"](beginSlice,endSlice); } public function split(separator:*=undefined,limit:*=undefined):Array { return s()["split"](separator,limit); } public function substr(start:Number, length:*=undefined):String { return s()["substr"](start,length); } public function substring(indexStart:Number, indexEnd:*=undefined):String { return s()["substring"](indexStart,indexEnd); } public function toLocaleLowerCase():String { return s().toLocaleLowerCase(); } public function toLocaleUpperCase():String { return s().toLocaleUpperCase(); } public function toLowerCase():String { return s().toLowerCase(); } public function toUpperCase():String { return s().toUpperCase(); } public function trim():String { return s().trim(); } // Number methods /** * @royaleignorecoercion Number */ public function toExponential(fractionDigits:*=undefined):Number { return v()["toExponential"](fractionDigits) as Number; } /** * @royaleignorecoercion Number */ public function toFixed(digits:int=0):Number { return v().toFixed(digits) as Number; } /** * @royaleignorecoercion Number */ public function toPrecision(precision:*=undefined):Number { return v()["toPrecision"](precision) as Number; } private function s():String { return this.toString(); } private function v():Number { return Number(s()); } } }
/* * Copyright (c) 2018 Marcel Piestansky * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marpies.ane.facebook.listeners { import com.marpies.ane.facebook.data.AIRFacebookGameRequest; /** * Interface for objects that want to be notified about a user Game Requests request result. */ public interface IAIRFacebookUserGameRequestsListener { /** * Called if the user Game Requests request is successful. * @param gameRequests List of Game Requests which were sent to current user. */ function onFacebookUserGameRequestsSuccess( gameRequests:Vector.<AIRFacebookGameRequest> ):void; /** * Called if an error occurs during the user Game Requests request. * @param errorMessage Message describing the error. */ function onFacebookUserGameRequestsError( errorMessage:String ):void; } }
package { import flash.display.Graphics; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; public class Orbiter extends MovingObject { private var counter:int = 0; public function Orbiter(origin:Object, sizeWidth :int, sizeHeight :int, radius :int, speed :Number, reverse :Boolean,angle:int) { super(origin,sizeWidth,sizeHeight,radius,speed,reverse,angle); if(stage) { Init(); } else { addEventListener(Event.ADDED_TO_STAGE, onAddedToStage); } } private function onAddedToStage(event: Event): void { removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); Init(); } private function Init() :void { this.addEventListener(Event.ENTER_FRAME, moveStatic); this.setSize(); this.addEventListener(MouseEvent.CLICK, OrbiterClicked); } protected function setSize() :void { this.width = sizeWidth; this.height = sizeHeight; } //handling mouse click private function OrbiterClicked (event:MouseEvent) : void { event.stopImmediatePropagation(); var child :Moon = new Moon(this,60,60,150 + Math.floor(Math.random() * 100), 2, true, 360/this.counter); this.addChild(child); this.counter++; } } }
package devoron.sdk.aslc.core.utils { import devoron.utils.airmediator.AirMediator; import flash.utils.ByteArray; /** * ... * @author Devoron */ public class ConfigurationMaker { public function ConfigurationMaker() { } public static function createConfigFile(outputPath:String, sources:Vector.<String>, classNames:Vector.<String>):String { var str:String = '<?xml version="1.0" encoding="utf-8"?>\n'; str +="<flex-config>\n"; str +=" <compiler>\n"; str +=" <as3>true</as3>\n"; str +=" <optimize>false</optimize>\n"; str +=" <strict>false </strict>\n"; //str +=" <debug>false</debug>\n"; str +=" <external-library-path>\n"; str +=" <path-element>F:\\airglobal.swc</path-element>\n"; str +=" </external-library-path>\n"; str += " <source-path>\n"; for each (var classPath:String in sources) { str +=" <path-element>"+classPath+"</path-element>\n"; } //str +=" <path-element>F:\\Projects\\projects\\flash\\studio\\studiolibs\\</path-element>\n"; str +=" </source-path>\n"; str +=" </compiler>\n"; str += " <include-classes>\n"; for each (var className:String in classNames) { str +=" <class>"+className+"</class>\n"; } str +=" </include-classes>\n"; //str +=" <output>score-ranking-as3.swc</output>\n"; str += "</flex-config>\n"; return str; } } }
// ================================================================================================= // // 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.animation { import starling.core.starling_internal; import starling.events.Event; import starling.events.EventDispatcher; /** A Tween animates numeric properties of objects. It uses different transition functions * to give the animations various styles. * * <p>The primary use of this class is to do standard animations like movement, fading, * rotation, etc. But there are no limits on what to animate; as long as the property you want * to animate is numeric (<code>int, uint, Number</code>), the tween can handle it. For a list * of available Transition types, look at the "Transitions" class.</p> * * <p>Here is an example of a tween that moves an object to the right, rotates it, and * fades it out:</p> * * <listing> * var tween:Tween = new Tween(object, 2.0, Transitions.EASE_IN_OUT); * tween.animate("x", object.x + 50); * tween.animate("rotation", deg2rad(45)); * tween.fadeTo(0); // equivalent to 'animate("alpha", 0)' * Starling.juggler.add(tween);</listing> * * <p>Note that the object is added to a juggler at the end of this sample. That's because a * tween will only be executed if its "advanceTime" method is executed regularly - the * juggler will do that for you, and will remove the tween when it is finished.</p> * * @see Juggler * @see Transitions */ public class Tween extends EventDispatcher implements IAnimatable { private var mTarget:Object; private var mTransitionFunc:Function; private var mTransitionName:String; private var mProperties:Vector.<String>; private var mStartValues:Vector.<Number>; private var mEndValues:Vector.<Number>; private var mOnStart:Function; private var mOnUpdate:Function; private var mOnRepeat:Function; private var mOnComplete:Function; private var mOnStartArgs:Array; private var mOnUpdateArgs:Array; private var mOnRepeatArgs:Array; private var mOnCompleteArgs:Array; private var mTotalTime:Number; private var mCurrentTime:Number; private var mDelay:Number; private var mRoundToInt:Boolean; private var mNextTween:Tween; private var mRepeatCount:int; private var mRepeatDelay:Number; private var mReverse:Boolean; private var mCurrentCycle:int; /** Creates a tween with a target, duration (in seconds) and a transition function. * @param target the object that you want to animate * @param time the duration of the Tween * @param transition can be either a String (e.g. one of the constants defined in the * Transitions class) or a function. Look up the 'Transitions' class for a * documentation about the required function signature. */ public function Tween(target:Object, time:Number, transition:Object="linear") { reset(target, time, transition); } /** Resets the tween to its default values. Useful for pooling tweens. */ public function reset(target:Object, time:Number, transition:Object="linear"):Tween { mTarget = target; mCurrentTime = 0; mTotalTime = Math.max(0.0001, time); mDelay = mRepeatDelay = 0.0; mOnStart = mOnUpdate = mOnComplete = null; mOnStartArgs = mOnUpdateArgs = mOnCompleteArgs = null; mRoundToInt = mReverse = false; mRepeatCount = 1; mCurrentCycle = -1; if (transition is String) this.transition = transition as String; else if (transition is Function) this.transitionFunc = transition as Function; else throw new ArgumentError("Transition must be either a string or a function"); if (mProperties) mProperties.length = 0; else mProperties = new <String>[]; if (mStartValues) mStartValues.length = 0; else mStartValues = new <Number>[]; if (mEndValues) mEndValues.length = 0; else mEndValues = new <Number>[]; return this; } /** Animates the property of an object to a target value. You can call this method multiple * times on one tween. */ public function animate(property:String, targetValue:Number):void { if (mTarget == null) return; // tweening null just does nothing. mProperties.push(property); mStartValues.push(Number.NaN); mEndValues.push(targetValue); } /** Animates the 'scaleX' and 'scaleY' properties of an object simultaneously. */ public function scaleTo(factor:Number):void { animate("scaleX", factor); animate("scaleY", factor); } /** Animates the 'x' and 'y' properties of an object simultaneously. */ public function moveTo(x:Number, y:Number):void { animate("x", x); animate("y", y); } /** Animates the 'alpha' property of an object to a certain target value. */ public function fadeTo(alpha:Number):void { animate("alpha", alpha); } /** @inheritDoc */ public function advanceTime(time:Number):void { if (time == 0 || (mRepeatCount == 1 && mCurrentTime == mTotalTime)) return; var i:int; var previousTime:Number = mCurrentTime; var restTime:Number = mTotalTime - mCurrentTime; var carryOverTime:Number = time > restTime ? time - restTime : 0.0; mCurrentTime = Math.min(mTotalTime, mCurrentTime + time); if (mCurrentTime <= 0) return; // the delay is not over yet if (mCurrentCycle < 0 && previousTime <= 0 && mCurrentTime > 0) { mCurrentCycle++; if (mOnStart != null) mOnStart.apply(null, mOnStartArgs); } var ratio:Number = mCurrentTime / mTotalTime; var reversed:Boolean = mReverse && (mCurrentCycle % 2 == 1); var numProperties:int = mStartValues.length; for (i=0; i<numProperties; ++i) { if (isNaN(mStartValues[i])) mStartValues[i] = mTarget[mProperties[i]] as Number; var startValue:Number = mStartValues[i]; var endValue:Number = mEndValues[i]; var delta:Number = endValue - startValue; var transitionValue:Number = reversed ? mTransitionFunc(1.0 - ratio) : mTransitionFunc(ratio); var currentValue:Number = startValue + transitionValue * delta; if (mRoundToInt) currentValue = Math.round(currentValue); mTarget[mProperties[i]] = currentValue; } if (mOnUpdate != null) mOnUpdate.apply(null, mOnUpdateArgs); if (previousTime < mTotalTime && mCurrentTime >= mTotalTime) { if (mRepeatCount == 0 || mRepeatCount > 1) { mCurrentTime = -mRepeatDelay; mCurrentCycle++; if (mRepeatCount > 1) mRepeatCount--; if (mOnRepeat != null) mOnRepeat.apply(null, mOnRepeatArgs); } else { // save callback & args: they might be changed through an event listener var onComplete:Function = mOnComplete; var onCompleteArgs:Array = mOnCompleteArgs; // in the 'onComplete' callback, people might want to call "tween.reset" and // add it to another juggler; so this event has to be dispatched *before* // executing 'onComplete'. dispatchEventWith(Event.REMOVE_FROM_JUGGLER); if (onComplete != null) onComplete.apply(null, onCompleteArgs); } } if (carryOverTime) advanceTime(carryOverTime); } /** Indicates if the tween is finished. */ public function get isComplete():Boolean { return mCurrentTime >= mTotalTime && mRepeatCount == 1; } /** The target object that is animated. */ public function get target():Object { return mTarget; } /** The transition method used for the animation. @see Transitions */ public function get transition():String { return mTransitionName; } public function set transition(value:String):void { mTransitionName = value; mTransitionFunc = Transitions.getTransition(value); if (mTransitionFunc == null) throw new ArgumentError("Invalid transiton: " + value); } /** The actual transition function used for the animation. */ public function get transitionFunc():Function { return mTransitionFunc; } public function set transitionFunc(value:Function):void { mTransitionName = "custom"; mTransitionFunc = value; } /** The total time the tween will take per repetition (in seconds). */ public function get totalTime():Number { return mTotalTime; } /** The time that has passed since the tween was created. */ public function get currentTime():Number { return mCurrentTime; } /** The delay before the tween is started. @default 0 */ public function get delay():Number { return mDelay; } public function set delay(value:Number):void { mCurrentTime = mCurrentTime + mDelay - value; mDelay = value; } /** The number of times the tween will be executed. * Set to '0' to tween indefinitely. @default 1 */ public function get repeatCount():int { return mRepeatCount; } public function set repeatCount(value:int):void { mRepeatCount = value; } /** The amount of time to wait between repeat cycles, in seconds. @default 0 */ public function get repeatDelay():Number { return mRepeatDelay; } public function set repeatDelay(value:Number):void { mRepeatDelay = value; } /** Indicates if the tween should be reversed when it is repeating. If enabled, * every second repetition will be reversed. @default false */ public function get reverse():Boolean { return mReverse; } public function set reverse(value:Boolean):void { mReverse = value; } /** Indicates if the numeric values should be cast to Integers. @default false */ public function get roundToInt():Boolean { return mRoundToInt; } public function set roundToInt(value:Boolean):void { mRoundToInt = value; } /** A function that will be called when the tween starts (after a possible delay). */ public function get onStart():Function { return mOnStart; } public function set onStart(value:Function):void { mOnStart = value; } /** A function that will be called each time the tween is advanced. */ public function get onUpdate():Function { return mOnUpdate; } public function set onUpdate(value:Function):void { mOnUpdate = value; } /** A function that will be called each time the tween finishes one repetition * (except the last, which will trigger 'onComplete'). */ public function get onRepeat():Function { return mOnRepeat; } public function set onRepeat(value:Function):void { mOnRepeat = value; } /** A function that will be called when the tween is complete. */ public function get onComplete():Function { return mOnComplete; } public function set onComplete(value:Function):void { mOnComplete = value; } /** The arguments that will be passed to the 'onStart' function. */ public function get onStartArgs():Array { return mOnStartArgs; } public function set onStartArgs(value:Array):void { mOnStartArgs = value; } /** The arguments that will be passed to the 'onUpdate' function. */ public function get onUpdateArgs():Array { return mOnUpdateArgs; } public function set onUpdateArgs(value:Array):void { mOnUpdateArgs = value; } /** The arguments that will be passed to the 'onRepeat' function. */ public function get onRepeatArgs():Array { return mOnRepeatArgs; } public function set onRepeatArgs(value:Array):void { mOnRepeatArgs = value; } /** The arguments that will be passed to the 'onComplete' function. */ public function get onCompleteArgs():Array { return mOnCompleteArgs; } public function set onCompleteArgs(value:Array):void { mOnCompleteArgs = value; } /** Another tween that will be started (i.e. added to the same juggler) as soon as * this tween is completed. */ public function get nextTween():Tween { return mNextTween; } public function set nextTween(value:Tween):void { mNextTween = value; } // tween pooling private static var sTweenPool:Vector.<Tween> = new <Tween>[]; /** @private */ starling_internal static function fromPool(target:Object, time:Number, transition:Object="linear"):Tween { if (sTweenPool.length) return sTweenPool.pop().reset(target, time, transition); else return new Tween(target, time, transition); } /** @private */ starling_internal static function toPool(tween:Tween):void { // reset any object-references, to make sure we don't prevent any garbage collection tween.mOnStart = tween.mOnUpdate = tween.mOnRepeat = tween.mOnComplete = null; tween.mOnStartArgs = tween.mOnUpdateArgs = tween.mOnRepeatArgs = tween.mOnCompleteArgs = null; tween.mTarget = null; tween.mTransitionFunc = null; tween.removeEventListeners(); sTweenPool.push(tween); } } }
/* Feathers Copyright 2012-2021 Bowler Hat LLC. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.layout { /** * Constants for horizontal alignment of items in a layout. * * <p>Note: Some constants may not be valid for certain properties. Please * see the description of the property in the API reference for full * details.</p> * * @productversion Feathers 3.0.0 */ public class HorizontalAlign { /** * The items in the layout will be horizontally aligned to the left of * the bounds. * * @productversion Feathers 3.0.0 */ public static const LEFT:String = "left"; /** * The items in the layout will be horizontally aligned to the center of * the bounds. * * @productversion Feathers 3.0.0 */ public static const CENTER:String = "center"; /** * The items in the layout will be horizontally aligned to the right of * the bounds. * * @productversion Feathers 3.0.0 */ public static const RIGHT:String = "right"; /** * The items in the layout will fill the width of the bounds. * * @productversion Feathers 3.0.0 */ public static const JUSTIFY:String = "justify"; } }
; lfinc - floating increment ; lfdec - floating decrement psect text global lfinc, lfdec, asfladd lfinc: exx ld hl,one incdec: exx ;restore original hl ld e,(hl) ;get left operand original value inc hl ld d,(hl) inc hl ld c,(hl) inc hl ld b,(hl) push bc push de ;save on the stack for 'ron dec hl ;restore pointer value dec hl dec hl exx ;now pointer to right op ld e,(hl) inc hl ld d,(hl) inc hl ld c,(hl) inc hl ld b,(hl) push bc ;hi order word first push de ;low order word second exx ;restore pointer to left op call asfladd ;perform the addition pop de ;pop original lo word pop hl ;and high word ret ;and return with it in the right place lfdec: exx ld hl,mone ;get a minus one jp incdec psect data one: deff 1.0 mone: deff -1.0 
//////////////////////////////////////////////////////////////////////////////// // // NOTEFLIGHT LLC // Copyright 2009 Noteflight LLC // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //////////////////////////////////////////////////////////////////////////////// package com.noteflight.standingwave2.elements { import __AS3__.vec.Vector; /** * Sample is the fundamental audio source in StandingWave, and is simply a set of buffers * containing the individual numeric samples of an audio signal. The <code>channelData</code> * property is an Array of channel buffers, whose length is the number of channels * specified by the descriptor. Each channel buffer is a Vector of Numbers, whose elements * are the individual samples for that channel, ranging between -1 and +1. */ public class Sample implements IAudioSource, IRandomAccessSource { /** Array of Vectors of data samples as Numbers, one Vector per channel. */ public var channelData:Array; /** Audio descriptor for this sample. */ private var _descriptor:AudioDescriptor; /** Audio cursor position, expressed as a sample frame index. */ private var _position:Number; /** * Construct a new, empty Sample with some specified audio format. * @param descriptor an AudioDescriptor specifying the audio format of this sample. * @param frames the number of frames in this Sample. If omitted or negative, no channel * data vectors are created. If zero, then zero-length vectors are created and may be * grown in size. If positive, then fixed-size vectors are created, and will contain zeroes. */ public function Sample(descriptor:AudioDescriptor, frames:Number = -1) { _descriptor = descriptor; channelData = []; if (frames >= 0) { for (var c:Number = 0; c < channels; c++) { channelData[c] = new Vector.<Number>(frames, frames > 0); } } _position = 0; } /** * The number of channels in this sample */ public function get channels():Number { return _descriptor.channels; } /** * Return a sample for the given channel and frame index * @param channel the channel index of the sample * @param index the frame index of the sample within that channel */ public function getChannelSample(channel:Number, index:Number):Number { return Vector.<Number>(channelData[channel])[index]; } /** * Return an interpolated sample for a non-integral sample position. * Interpolation is always done within the same channel. */ public function getInterpolatedSample(channel:Number, pos:Number):Number { var intPos:Number = int(pos); var fracPos:Number = pos - intPos; var data:Vector.<Number> = channelData[channel]; var s1:Number = data[intPos]; var s2:Number = data[intPos+1]; return s1 + (fracPos * (s2 - s1)); } /** * Return duration in seconds */ public function get duration():Number { return Number(frameCount) / _descriptor.rate; } /** * Clear this sample. */ public function clear():void { var n:Number = frameCount; for (var c:Number = 0; c < channels; c++) { var data:Vector.<Number> = channelData[c]; for (var i:Number = 0; i < n; i++) { data[i] = 0; } } } //////////////////////////////////////////// // IRandomAccessSource/IAudioSource interface implementation //////////////////////////////////////////// /** * @inheritDoc */ public function get descriptor():AudioDescriptor { return _descriptor; } /** * @inheritDoc */ public function get frameCount():Number { return channelData[0].length; } public function set frameCount(value:Number):void { for (var c:Number = 0; c < channels; c++) { var data:Vector.<Number> = channelData[c]; data.length = value; } } /** * @inheritDoc */ public function get position():Number { return _position; } public function set position(p:Number):void { _position = p; } /** * @inheritDoc */ public function resetPosition():void { _position = 0; } /** * @inheritDoc */ public function getSampleRange(fromOffset:Number, toOffset:Number):Sample { var sample:Sample = new Sample(descriptor); for (var c:Number = 0; c < channels; c++) { sample.channelData[c] = Vector.<Number>(channelData[c]).slice(fromOffset, toOffset); } return sample; } /** * @inheritDoc */ public function getSample(numFrames:Number):Sample { var sample:Sample = getSampleRange(_position, _position + numFrames); _position += numFrames; return sample; } /** * Clone this Sample. Note that the channel data is shared between the * original and the clone, since channel data inside a Sample should never * be mutated except for temporary Samples used inside a filter pipeline. */ public function clone():IAudioSource { var sample:Sample = new Sample(descriptor); for (var c:Number = 0; c < channels; c++) { sample.channelData[c] = channelData[c]; } return sample; } } }
/** * VERSION: 1.0 * DATE: 2012-03-22 * AS3 (AS2 and JS versions are also available) * UPDATES AND DOCS AT: http://www.greensock.com **/ import com.greensock.easing.Ease; /** * See AS3 files for full ASDocs * * <p><strong>Copyright 2008-2014, GreenSock. All rights reserved.</strong> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for <a href="http://www.greensock.com/club/">Club GreenSock</a> members, the software agreement that was issued with the membership.</p> * * @author Jack Doyle, jack@greensock.com */ class com.greensock.easing.Quart { public static var easeOut:Ease = new Ease(null,null,1,3); public static var easeIn:Ease = new Ease(null,null,2,3); public static var easeInOut:Ease = new Ease(null,null,3,3); }
/* * Based on ideas used in Robert Penner's AS3-signals - https://github.com/robertpenner/as3-signals */ package net.richardlord.signals { import flash.utils.Dictionary; /** * The base class for all the signal classes. */ public class SignalBase { internal var head : ListenerNode; internal var tail : ListenerNode; private var nodes : Dictionary; private var listenerNodePool : ListenerNodePool; private var toAddHead : ListenerNode; private var toAddTail : ListenerNode; private var dispatching : Boolean; public function SignalBase() { nodes = new Dictionary( true ); listenerNodePool = new ListenerNodePool(); } protected function startDispatch() : void { dispatching = true; } protected function endDispatch() : void { dispatching = false; if( toAddHead ) { if( !head ) { head = toAddHead; tail = toAddTail; } else { tail.next = toAddHead; toAddHead.previous = tail; tail = toAddTail; } toAddHead = null; toAddTail = null; } listenerNodePool.releaseCache(); } public function add( listener : Function ) : void { if( nodes[ listener ] ) { return; } var node : ListenerNode = listenerNodePool.get(); node.listener = listener; nodes[ listener ] = node; addNode( node ); } public function addOnce( listener : Function ) : void { if( nodes[ listener ] ) { return; } var node : ListenerNode = listenerNodePool.get(); node.listener = listener; node.once = true; nodes[ listener ] = node; addNode( node ); } protected function addNode( node : ListenerNode ) : void { if( dispatching ) { if( !toAddHead ) { toAddHead = toAddTail = node; } else { toAddTail.next = node; node.previous = toAddTail; toAddTail = node; } } else { if ( !head ) { head = tail = node; } else { tail.next = node; node.previous = tail; tail = node; } } } public function remove( listener : Function ) : void { var node : ListenerNode = nodes[ listener ]; if ( node ) { if ( head == node) { head = head.next; } if ( tail == node) { tail = tail.previous; } if ( toAddHead == node) { toAddHead = toAddHead.next; } if ( toAddTail == node) { toAddTail = toAddTail.previous; } if (node.previous) { node.previous.next = node.next; } if (node.next) { node.next.previous = node.previous; } delete nodes[ listener ]; if( dispatching ) { listenerNodePool.cache( node ); } else { listenerNodePool.dispose( node ); } } } public function removeAll() : void { while( head ) { var listener : ListenerNode = head; head = head.next; listener.previous = null; listener.next = null; } tail = null; toAddHead = null; toAddTail = null; } } }
package serverProto.inc { import com.netease.protobuf.Message; import com.netease.protobuf.ReadUtils; import com.netease.protobuf.WireType; import com.netease.protobuf.WriteUtils; import com.netease.protobuf.WritingBuffer; import com.netease.protobuf.used_by_generated_code; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_UINT32; import flash.errors.IOError; import flash.utils.IDataInput; public final class ProtoPlayerKey extends Message { public static const UIN:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.inc.ProtoPlayerKey.uin","uin",1 << 3 | WireType.VARINT); public static const ROLE_ID:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.inc.ProtoPlayerKey.role_id","roleId",2 << 3 | WireType.VARINT); public static const SVR_ID:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.inc.ProtoPlayerKey.svr_id","svrId",3 << 3 | WireType.VARINT); public var uin:uint; public var roleId:uint; public var svrId:uint; public function ProtoPlayerKey() { super(); } override used_by_generated_code function writeToBuffer(param1:WritingBuffer) : void { var _loc2_:* = undefined; WriteUtils.writeTag(param1,WireType.VARINT,1); WriteUtils.write$TYPE_UINT32(param1,this.uin); WriteUtils.writeTag(param1,WireType.VARINT,2); WriteUtils.write$TYPE_UINT32(param1,this.roleId); WriteUtils.writeTag(param1,WireType.VARINT,3); WriteUtils.write$TYPE_UINT32(param1,this.svrId); for(_loc2_ in this) { super.writeUnknown(param1,_loc2_); } } override used_by_generated_code 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: 3, Size: 3) */ throw new flash.errors.IllegalOperationError("Not decompiled due to error"); } } }
package com.codeazur.hxswf.exporters { import com.codeazur.hxswf.SWF; import com.codeazur.hxswf.exporters.core.DefaultSVGShapeExporter; import com.codeazur.hxswf.utils.ColorUtils; import com.codeazur.utils.StringUtils; import flash.display.CapsStyle; import flash.display.GradientType; import flash.display.InterpolationMethod; import flash.display.JointStyle; import flash.display.LineScaleMode; import flash.display.SpreadMethod; import flash.geom.Matrix; class FXGShapeExporter extends DefaultSVGShapeExporter { private static inline var s:Namespace = new Namespace("s", "library://ns.adobe.com/flex/spark"); private var _fxg:XML; private var path:XML; public function FXGShapeExporter(swf:SWF) { super(swf); } public function get fxg():XML { return _fxg; } override public function beginShape():Void { _fxg = <s:Graphic xmlns:s={s.uri}><s:Group /></s:Graphic>; } override public function beginFill(color:Int, alpha:Float = 1.0):Void { finalizePath(); var fill:XML = <s:fill xmlns:s={s.uri} />; var solidColor:XML = <s:SolidColor xmlns:s={s.uri} />; if(color != 0) { solidColor.@color = ColorUtils.rgbToString(color); } if(alpha != 1) { solidColor.@alpha = alpha; } fill.appendChild(solidColor); path.appendChild(fill); } override public function beginGradientFill(type:String, colors:Array, alphas:Array, ratios:Array, matrix:Matrix = null, spreadMethod:String = SpreadMethod.PAD, interpolationMethod:String = InterpolationMethod.RGB, focalPointRatio:Float = 0):Void { finalizePath(); var fill:XML = <s:fill xmlns:s={s.uri} />; var gradient:XML; if(type == GradientType.LINEAR) { gradient = <s:LinearGradient xmlns:s={s.uri} />; } else { gradient = <s:RadialGradient xmlns:s={s.uri} />; } populateGradientElement(gradient, type, colors, alphas, ratios, matrix, spreadMethod, interpolationMethod, focalPointRatio); fill.appendChild(gradient); path.appendChild(fill); } override public function beginBitmapFill(bitmapId:Int, matrix:Matrix = null, repeat:Bool = true, smooth:Bool = false):Void { throw(new Error("Bitmap fills are not yet supported for shape export.")); } override public function lineStyle(thickness:Float = NaN, color:Int = 0, alpha:Float = 1.0, pixelHinting:Bool = false, scaleMode:String = LineScaleMode.NORMAL, startCaps:String = null, endCaps:String = null, joints:String = null, miterLimit:Float = 3):Void { finalizePath(); var stroke:XML = <s:stroke xmlns:s={s.uri} />; var solidColorStroke:XML = <s:SolidColorStroke xmlns:s={s.uri} />; if(!isNaN(thickness) && thickness != 1) { solidColorStroke.@weight = thickness; } if(color != 0) { solidColorStroke.@color = ColorUtils.rgbToString(color); } if(alpha != 1) { solidColorStroke.@alpha = alpha; } if(pixelHinting) { solidColorStroke.@pixelHinting = "true"; } if(scaleMode != LineScaleMode.NORMAL) { solidColorStroke.@scaleMode = scaleMode; } if(startCaps && startCaps != CapsStyle.ROUND) { solidColorStroke.@caps = startCaps; } if(joints && joints != JointStyle.ROUND) { solidColorStroke.@joints = joints; } if(miterLimit != 3) { solidColorStroke.@miterLimit = miterLimit; } stroke.appendChild(solidColorStroke); path.appendChild(stroke); } override public function lineGradientStyle(type:String, colors:Array, alphas:Array, ratios:Array, matrix:Matrix = null, spreadMethod:String = SpreadMethod.PAD, interpolationMethod:String = InterpolationMethod.RGB, focalPointRatio:Float = 0):Void { var strokeElement:XML = path..s::SolidColorStroke[0]; if(strokeElement) { if(type == GradientType.LINEAR) { strokeElement.setLocalName("LinearGradientStroke"); } else { strokeElement.setLocalName("RadialGradientStroke"); } delete strokeElement.@color; delete strokeElement.@alpha; populateGradientElement(strokeElement, type, colors, alphas, ratios, matrix, spreadMethod, interpolationMethod, focalPointRatio); } } override private function finalizePath():Void { if(path && pathData != "") { path.@data = StringUtils.trim(pathData); fxg.s::Group.appendChild(path); } path = <s:Path xmlns:s={s.uri} />; super.finalizePath(); } private function populateGradientElement(gradient:XML, type:String, colors:Array, alphas:Array, ratios:Array, matrix:Matrix, spreadMethod:String, interpolationMethod:String, focalPointRatio:Float):Void { var isLinear:Bool = (type == GradientType.LINEAR); if(!isLinear && focalPointRatio != 0) { gradient.@focalPointRatio = focalPointRatio; } if(spreadMethod != SpreadMethod.PAD) { gradient.@spreadMethod = spreadMethod; } if(interpolationMethod != InterpolationMethod.RGB) { gradient.@interpolationMethod = interpolationMethod; } if(matrix) { // The original matrix transforms the SWF gradient rect: // (-16384, -16384), (16384, 16384) // into the target gradient rect. // We need to transform the FXG gradient rect: // (0, 0), (1, 1) for linear gradients // (-0.5, -0.5), (0.5, 0.5) for radial gradients // Scale and rotation of the original matrix is based on twips, // so additionaly we have to divide by 20. var m:Matrix = matrix.clone(); // Normalize the original scale and rotation m.scale(32768 / 20, 32768 / 20); // Adjust the translation // For linear gradients, we take the point (-16384, 0) // and scale and rotate it using the original matrix. // What we get is the start point of the gradient, // so we add tx/ty to get the real translation for the new rect. // For radial gradients we just stick with the original tx/ty. m.tx = isLinear ? -16384 * matrix.a / 20 + matrix.tx : matrix.tx; m.ty = isLinear ? -16384 * matrix.b / 20 + matrix.ty : matrix.ty; var matrixContainer:XML = <s:matrix xmlns:s={s.uri} /> var matrixChild:XML = <s:Matrix xmlns:s={s.uri} /> if(m.tx != 0) { matrixChild.@tx = m.tx; } if(m.ty != 0) { matrixChild.@ty = m.ty; } if(m.a != 1) { matrixChild.@a = m.a; } if(m.b != 0) { matrixChild.@b = m.b; } if(m.c != 0) { matrixChild.@c = m.c; } if(m.d != 1) { matrixChild.@d = m.d; } matrixContainer.appendChild(matrixChild); gradient.appendChild(matrixContainer); } for(var i:Int = 0; i < colors.length; i++) { var gradientEntry:XML = <s:GradientEntry xmlns:s={s.uri} ratio={ratios[i] / 255} /> if(colors[i] != 0) { gradientEntry.@color = ColorUtils.rgbToString(colors[i]); } if(alphas[i] != 1) { gradientEntry.@alpha = alphas[i]; } gradient.appendChild(gradientEntry); } } } }
package com.controls { import mx.controls.DateField; import mx.core.ClassFactory; public class DateFieldEx extends DateField { private var _isClearButtonRequired:Boolean = false; public function DateFieldEx() { super(); height = 19; } [Bindable("change")] [Bindable("valueCommit")] [Bindable("selectedDateChanged")] public function get selectedMilliseconds():Number { return selectedDate ? selectedDate.getTime() - (selectedDate.timezoneOffset * 60 * 1000) : NaN; } public function set selectedMilliseconds(value:Number):void { if(value == 0 || isNaN(value)) { selectedDate = null; return; } value += new Date(value).timezoneOffset * 60 * 1000; selectedDate = value != 0 && !isNaN(value) ? new Date(value) : null; } public function get isClearButtonRequired():Boolean { return _isClearButtonRequired; } public function set isClearButtonRequired(value:Boolean):void { _isClearButtonRequired = value; if (value) { dropdownFactory = new ClassFactory(ClearedDateChooser); } } } }
package com.ankamagames.dofus.network.messages.game.context.roleplay.havenbag.meeting { import com.ankamagames.jerakine.network.CustomDataWrapper; import com.ankamagames.jerakine.network.ICustomDataInput; import com.ankamagames.jerakine.network.ICustomDataOutput; import com.ankamagames.jerakine.network.INetworkMessage; import com.ankamagames.jerakine.network.NetworkMessage; import com.ankamagames.jerakine.network.utils.FuncTree; import flash.utils.ByteArray; public class HavenBagPermissionsUpdateRequestMessage extends NetworkMessage implements INetworkMessage { public static const protocolId:uint = 9436; private var _isInitialized:Boolean = false; public var permissions:uint = 0; public function HavenBagPermissionsUpdateRequestMessage() { super(); } override public function get isInitialized() : Boolean { return this._isInitialized; } override public function getMessageId() : uint { return 9436; } public function initHavenBagPermissionsUpdateRequestMessage(permissions:uint = 0) : HavenBagPermissionsUpdateRequestMessage { this.permissions = permissions; this._isInitialized = true; return this; } override public function reset() : void { this.permissions = 0; this._isInitialized = false; } override public function pack(output:ICustomDataOutput) : void { var data:ByteArray = new ByteArray(); this.serialize(new CustomDataWrapper(data)); writePacket(output,this.getMessageId(),data); } override public function unpack(input:ICustomDataInput, length:uint) : void { this.deserialize(input); } override public function unpackAsync(input:ICustomDataInput, length:uint) : FuncTree { var tree:FuncTree = new FuncTree(); tree.setRoot(input); this.deserializeAsync(tree); return tree; } public function serialize(output:ICustomDataOutput) : void { this.serializeAs_HavenBagPermissionsUpdateRequestMessage(output); } public function serializeAs_HavenBagPermissionsUpdateRequestMessage(output:ICustomDataOutput) : void { if(this.permissions < 0) { throw new Error("Forbidden value (" + this.permissions + ") on element permissions."); } output.writeInt(this.permissions); } public function deserialize(input:ICustomDataInput) : void { this.deserializeAs_HavenBagPermissionsUpdateRequestMessage(input); } public function deserializeAs_HavenBagPermissionsUpdateRequestMessage(input:ICustomDataInput) : void { this._permissionsFunc(input); } public function deserializeAsync(tree:FuncTree) : void { this.deserializeAsyncAs_HavenBagPermissionsUpdateRequestMessage(tree); } public function deserializeAsyncAs_HavenBagPermissionsUpdateRequestMessage(tree:FuncTree) : void { tree.addChild(this._permissionsFunc); } private function _permissionsFunc(input:ICustomDataInput) : void { this.permissions = input.readInt(); if(this.permissions < 0) { throw new Error("Forbidden value (" + this.permissions + ") on element of HavenBagPermissionsUpdateRequestMessage.permissions."); } } } }
package game.proto { import com.google.protobuf.*; public class heartbeat extends Message { public function heartbeat() { } override public function writeTo(output:CodedOutputStream):void { super.writeTo(output); } override public function readFrom(input:CodedInputStream):void { while(true) { var tag:int = input.readTag(); switch(tag) { case 0: { return; } default: { if (!input.skipField(tag)) { return; } break; } } } } } }
package services.command.checkOut { import com.adobe.cairngorm.control.CairngormEvent; import services.business.checkOut.CheckOutDelegate; import services.cairngorm.BaseCommand; import services.events.checkOut.DetachPackageFromAccountEvent; public class DetachPackageFromAccountCommand extends BaseCommand { /** * @override */ override public function execute(event:CairngormEvent):void { _event = DetachPackageFromAccountEvent(event); var delegate:CheckOutDelegate = new CheckOutDelegate(this); delegate.detachPackageFromAccount(_event as DetachPackageFromAccountEvent); super.execute(event); } /** * @override */ override public function result(data:Object):void { super.result(data); } } }
package com.phono.events { import com.phono.Audio; import flash.events.*; /** * Events related to Media. */ public class MediaEvent extends Event { /** * Dispatched when flash needs to open a permission box for access to the local microphone. */ public static const OPEN:String = "permissionBoxShow"; /** * Dispatched when flash has finished with the permission box. */ public static const CLOSE:String = "permissionBoxHide"; /** * Dispatched when flash is connected to a server */ public static const CONNECTED:String = "flashConnected"; /** * Dispatched when flash is ready with media */ public static const READY:String = "mediaReady"; /** * Dispatched when an error is encountered with media. */ public static const ERROR:String = "mediaError"; /** * The Audio object associated with this media event. */ public var audio:Audio; /** * A descriptive reason sting */ public var reason:String; public function MediaEvent(type:String, audio:Audio=null, reason:String="", bubbles:Boolean=true, cancelable:Boolean=false) { super(type, bubbles, cancelable); this.audio = audio; this.reason = reason; } } }
package io.decagames.rotmg.ui.tabs { import flash.display.Sprite; import flash.events.MouseEvent; import flash.geom.Point; import io.decagames.rotmg.ui.buttons.SliceScalingButton; import io.decagames.rotmg.ui.defaults.DefaultLabelFormat; import io.decagames.rotmg.ui.sliceScaling.SliceScalingBitmap; import io.decagames.rotmg.ui.texture.TextureParser; public class TabButton extends SliceScalingButton { public static const SELECTED_MARGIN: int = 3; public static const LEFT: String = "left"; public static const RIGHT: String = "right"; public static const CENTER: String = "center"; public static const BORDERLESS: String = "borderless"; public function TabButton(_arg_1: String) { this.buttonType = _arg_1; var _local3: * = _arg_1; switch (_local3) { case "left": this.defaultBitmap = "tab_button_left_idle"; this.selectedBitmap = "tab_button_center_open"; break; case "right": this.defaultBitmap = "tab_button_right_idle"; this.selectedBitmap = "tab_button_right_open"; break; case "center": this.defaultBitmap = "tab_button_center_idle"; this.selectedBitmap = "tab_button_center_open"; break; case "borderless": this.defaultBitmap = "tab_button_borderless_idle"; this.selectedBitmap = "tab_button_borderless"; } var _local2: SliceScalingBitmap = TextureParser.instance.getSliceScalingBitmap("UI", this.defaultBitmap); super(_local2); bitmap.name = "TabButton"; _local2.addMargin(0, this.buttonType == "borderless" ? 0 : 3); _interactionEffects = false; } private var selectedBitmap: String; private var defaultBitmap: String; private var buttonType: String; private var indicator: Sprite; private var _selected: Boolean; public function get selected(): Boolean { return this._selected; } public function set selected(_arg_1: Boolean): void { this._selected = _arg_1; if (!this._selected) { setLabelMargin(0, 0); DefaultLabelFormat.defaultInactiveTab(this.label); changeBitmap(this.defaultBitmap, new Point(0, this.buttonType == "borderless" ? 0 : 3)); bitmap.alpha = 0; } else { setLabelMargin(0, this.buttonType == "borderless" ? 0 : 2); DefaultLabelFormat.defaultActiveTab(this.label); changeBitmap(this.selectedBitmap, new Point(0, this.buttonType == "borderless" ? 0 : 3)); bitmap.alpha = 1; } this.updateIndicatorPosition(); } public function get hasIndicator(): Boolean { return this.indicator && this.indicator.parent; } public function set showIndicator(_arg_1: Boolean): void { if (_arg_1) { if (!this.indicator) { this.indicator = new Sprite(); } this.indicator.graphics.clear(); this.indicator.graphics.beginFill(823807); this.indicator.graphics.drawCircle(0, 0, 4); this.indicator.graphics.endFill(); addChild(this.indicator); this.updateIndicatorPosition(); } else if (this.indicator && this.indicator.parent) { removeChild(this.indicator); } } private function updateIndicatorPosition(): void { if (this.indicator) { this.indicator.x = this.label.x + this.label.width + 7; this.indicator.y = this.label.y + 8; } } override protected function onClickHandler(_arg_1: MouseEvent): void { super.onClickHandler(_arg_1); } } }
package kabam.rotmg.assets { import mx.core.BitmapAsset; [Embed(source="EmbeddedAssets_lofiInterface2Embed.png")] public class EmbeddedAssets_lofiInterface2Embed extends BitmapAsset { public function EmbeddedAssets_lofiInterface2Embed() { super(); } } }
/* Feathers Copyright 2012-2013 Joshua Tynjala. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.controls { import feathers.controls.supportClasses.TextFieldViewPort; import feathers.core.FeathersControl; import feathers.core.PropertyProxy; import feathers.events.FeathersEventType; import flash.text.AntiAliasType; import flash.text.GridFitType; import flash.text.StyleSheet; import flash.text.TextFormat; import starling.events.Event; /** * Dispatched when the text is scrolled. * * @eventType starling.events.Event.SCROLL */ [Event(name="scroll",type="starling.events.Event")] /** * Dispatched when the container finishes scrolling in either direction after * being thrown. * * @eventType feathers.events.FeathersEventType.SCROLL_COMPLETE */ [Event(name="scrollComplete",type="starling.events.Event")] /** * Displays long passages of text in a scrollable container using the * runtime's software-based <code>flash.text.TextField</code> as an overlay * above Starling content. * * @see http://wiki.starling-framework.org/feathers/scroll-text */ public class ScrollText extends FeathersControl { /** * The default value added to the <code>nameList</code> of the scroller. */ public static const DEFAULT_CHILD_NAME_SCROLLER:String = "feathers-scroll-text-scroller"; /** * Constructor. */ public function ScrollText() { this.viewPort = new TextFieldViewPort(); } /** * The value added to the <code>nameList</code> of the scroller. */ protected var scrollerName:String = DEFAULT_CHILD_NAME_SCROLLER; /** * The scroller sub-component. */ protected var scroller:Scroller; /** * @private */ protected var viewPort:TextFieldViewPort; /** * @private */ protected var _scrollToHorizontalPageIndex:int = -1; /** * @private */ protected var _scrollToVerticalPageIndex:int = -1; /** * @private */ protected var _scrollToIndexDuration:Number; /** * @private */ protected var _text:String = ""; /** * The text to display. If <code>isHTML</code> is <code>true</code>, the * text will be rendered as HTML with the same capabilities as the * <code>htmlText</code> property of <code>flash.text.TextField</code>. * * @see #isHTML * @see flash.text.TextField#htmlText */ public function get text():String { return this._text; } /** * @private */ public function set text(value:String):void { if(!value) { value = ""; } if(this._text == value) { return; } this._text = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var _isHTML:Boolean = false; /** * Determines if the TextField should display the text as HTML or not. * * @see #text * @see flash.text.TextField#htmlText */ public function get isHTML():Boolean { return this._isHTML; } /** * @private */ public function set isHTML(value:Boolean):void { if(this._isHTML == value) { return; } this._isHTML = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var _textFormat:TextFormat; /** * The font and styles used to draw the text. * * @see flash.text.TextFormat */ public function get textFormat():TextFormat { return this._textFormat; } /** * @private */ public function set textFormat(value:TextFormat):void { if(this._textFormat == value) { return; } this._textFormat = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _styleSheet:StyleSheet; /** * The <code>StyleSheet</code> object to pass to the TextField. * * @see flash.text.StyleSheet */ public function get styleSheet():StyleSheet { return this._styleSheet; } /** * @private */ public function set styleSheet(value:StyleSheet):void { if(this._styleSheet == value) { return; } this._styleSheet = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _embedFonts:Boolean = false; /** * Determines if the TextField should use an embedded font or not. */ public function get embedFonts():Boolean { return this._embedFonts; } /** * @private */ public function set embedFonts(value:Boolean):void { if(this._embedFonts == value) { return; } this._embedFonts = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _antiAliasType:String = AntiAliasType.ADVANCED; /** * Same as the TextField property with the same name. * * @see flash.text.TextField#antiAliasType */ public function get antiAliasType():String { return this._antiAliasType; } /** * @private */ public function set antiAliasType(value:String):void { if(this._antiAliasType == value) { return; } this._antiAliasType = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _background:Boolean = false; /** * Same as the TextField property with the same name. * * @see flash.text.TextField#background */ public function get background():Boolean { return this._background; } /** * @private */ public function set background(value:Boolean):void { if(this._background == value) { return; } this._background = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _backgroundColor:uint = 0xffffff; /** * Same as the TextField property with the same name. * * @see flash.text.TextField#backgroundColor */ public function get backgroundColor():uint { return this._backgroundColor; } /** * @private */ public function set backgroundColor(value:uint):void { if(this._backgroundColor == value) { return; } this._backgroundColor = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _border:Boolean = false; /** * Same as the TextField property with the same name. * * @see flash.text.TextField#border */ public function get border():Boolean { return this._border; } /** * @private */ public function set border(value:Boolean):void { if(this._border == value) { return; } this._border = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _borderColor:uint = 0x000000; /** * Same as the TextField property with the same name. * * @see flash.text.TextField#borderColor */ public function get borderColor():uint { return this._borderColor; } /** * @private */ public function set borderColor(value:uint):void { if(this._borderColor == value) { return; } this._borderColor = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _condenseWhite:Boolean = false; /** * Same as the TextField property with the same name. * * @see flash.text.TextField#condenseWhite */ public function get condenseWhite():Boolean { return this._condenseWhite; } /** * @private */ public function set condenseWhite(value:Boolean):void { if(this._condenseWhite == value) { return; } this._condenseWhite = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _displayAsPassword:Boolean = false; /** * Same as the TextField property with the same name. * * @see flash.text.TextField#displayAsPassword */ public function get displayAsPassword():Boolean { return this._displayAsPassword; } /** * @private */ public function set displayAsPassword(value:Boolean):void { if(this._displayAsPassword == value) { return; } this._displayAsPassword = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _gridFitType:String = GridFitType.PIXEL; /** * Same as the TextField property with the same name. * * @see flash.text.TextField#gridFitType */ public function get gridFitType():String { return this._gridFitType; } /** * @private */ public function set gridFitType(value:String):void { if(this._gridFitType == value) { return; } this._gridFitType = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ private var _sharpness:Number = 0; /** * Same as the TextField property with the same name. * * @see flash.text.TextField#sharpness */ public function get sharpness():Number { return this._sharpness; } /** * @private */ public function set sharpness(value:Number):void { if(this._sharpness == value) { return; } this._sharpness = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ private var _thickness:Number = 0; /** * Same as the TextField property with the same name. * * @see flash.text.TextField#thickness */ public function get thickness():Number { return this._thickness; } /** * @private */ public function set thickness(value:Number):void { if(this._thickness == value) { return; } this._thickness = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * Quickly sets all padding properties to the same value. The * <code>padding</code> getter always returns the value of * <code>paddingTop</code>, but the other padding values may be * different. */ public function get padding():Number { return this._paddingTop; } /** * @private */ public function set padding(value:Number):void { this.paddingTop = value; this.paddingRight = value; this.paddingBottom = value; this.paddingLeft = value; } /** * @private */ protected var _paddingTop:Number = 0; /** * The minimum space, in pixels, between the text's top edge and the * edge of the container. */ public function get paddingTop():Number { return this._paddingTop; } /** * @private */ public function set paddingTop(value:Number):void { if(this._paddingTop == value) { return; } this._paddingTop = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _paddingRight:Number = 0; /** * The minimum space, in pixels, between the text's right edge and the * edge of the container. */ public function get paddingRight():Number { return this._paddingRight; } /** * @private */ public function set paddingRight(value:Number):void { if(this._paddingRight == value) { return; } this._paddingRight = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _paddingBottom:Number = 0; /** * The minimum space, in pixels, between the text's bottom edge and the * edge of the container. */ public function get paddingBottom():Number { return this._paddingBottom; } /** * @private */ public function set paddingBottom(value:Number):void { if(this._paddingBottom == value) { return; } this._paddingBottom = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _paddingLeft:Number = 0; /** * The minimum space, in pixels, between the text's left edge and the * edge of the container. */ public function get paddingLeft():Number { return this._paddingLeft; } /** * @private */ public function set paddingLeft(value:Number):void { if(this._paddingLeft == value) { return; } this._paddingLeft = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _horizontalScrollPosition:Number = 0; /** * The number of pixels the text has been scrolled horizontally (on * the x-axis). */ public function get horizontalScrollPosition():Number { return this._horizontalScrollPosition; } /** * @private */ public function set horizontalScrollPosition(value:Number):void { if(this._horizontalScrollPosition == value) { return; } this._horizontalScrollPosition = value; this.invalidate(INVALIDATION_FLAG_SCROLL); this.dispatchEventWith(Event.SCROLL); } /** * @private */ protected var _maxHorizontalScrollPosition:Number = 0; /** * The maximum number of pixels the text may be scrolled horizontally * (on the x-axis). This value is automatically calculated by the * supplied layout algorithm. The <code>horizontalScrollPosition</code> * property may have a higher value than the maximum due to elastic * edges. However, once the user stops interacting with the text, * it will automatically animate back to the maximum (or minimum, if * the scroll position is below 0). */ public function get maxHorizontalScrollPosition():Number { return this._maxHorizontalScrollPosition; } /** * @private */ protected var _horizontalPageIndex:int = 0; /** * The index of the horizontal page, if snapping is enabled. If snapping * is disabled, the index will always be <code>0</code>. */ public function get horizontalPageIndex():int { return this._horizontalPageIndex; } /** * @private */ protected var _verticalScrollPosition:Number = 0; /** * The number of pixels the text has been scrolled vertically (on * the y-axis). */ public function get verticalScrollPosition():Number { return this._verticalScrollPosition; } /** * @private */ public function set verticalScrollPosition(value:Number):void { if(this._verticalScrollPosition == value) { return; } this._verticalScrollPosition = value; this.invalidate(INVALIDATION_FLAG_SCROLL); this.dispatchEventWith(Event.SCROLL); } /** * @private */ protected var _maxVerticalScrollPosition:Number = 0; /** * The maximum number of pixels the text may be scrolled vertically * (on the y-axis). This value is automatically calculated by the * supplied layout algorithm. The <code>verticalScrollPosition</code> * property may have a higher value than the maximum due to elastic * edges. However, once the user stops interacting with the text, * it will automatically animate back to the maximum (or minimum, if * the scroll position is below 0). */ public function get maxVerticalScrollPosition():Number { return this._maxVerticalScrollPosition; } /** * @private */ protected var _verticalPageIndex:int = 0; /** * The index of the vertical page, if snapping is enabled. If snapping * is disabled, the index will always be <code>0</code>. * * @default 0 */ public function get verticalPageIndex():int { return this._verticalPageIndex; } /** * @private */ protected var _scrollerProperties:PropertyProxy; /** * A set of key/value pairs to be passed down to the container's * scroller sub-component. The scroller is a * <code>feathers.controls.Scroller</code> instance. * * <p>If the subcomponent has its own subcomponents, their properties * can be set too, using attribute <code>&#64;</code> notation. For example, * to set the skin on the thumb of a <code>SimpleScrollBar</code> * which is in a <code>Scroller</code> which is in a <code>List</code>, * you can use the following syntax:</p> * <pre>list.scrollerProperties.&#64;verticalScrollBarProperties.&#64;thumbProperties.defaultSkin = new Image(texture);</pre> * * @see feathers.controls.Scroller */ public function get scrollerProperties():Object { if(!this._scrollerProperties) { this._scrollerProperties = new PropertyProxy(childProperties_onChange); } return this._scrollerProperties; } /** * @private */ public function set scrollerProperties(value:Object):void { if(this._scrollerProperties == value) { return; } if(!value) { value = new PropertyProxy(); } if(!(value is PropertyProxy)) { const newValue:PropertyProxy = new PropertyProxy(); for(var propertyName:String in value) { newValue[propertyName] = value[propertyName]; } value = newValue; } if(this._scrollerProperties) { this._scrollerProperties.removeOnChangeCallback(childProperties_onChange); } this._scrollerProperties = PropertyProxy(value); if(this._scrollerProperties) { this._scrollerProperties.addOnChangeCallback(childProperties_onChange); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * If the user is dragging the scroll, calling stopScrolling() will * cause the container to ignore the drag. The children of the container * will still receive touches, so it's useful to call this if the * children need to support touches or dragging without the container * also scrolling. */ public function stopScrolling():void { if(!this.scroller) { return; } this.scroller.stopScrolling(); } /** * Scrolls the list to a specific page, horizontally and vertically. If * <code>horizontalPageIndex</code> or <code>verticalPageIndex</code> is * -1, it will be ignored */ public function scrollToPageIndex(horizontalPageIndex:int, verticalPageIndex:int, animationDuration:Number = 0):void { if(this._scrollToHorizontalPageIndex == horizontalPageIndex && this._scrollToVerticalPageIndex == verticalPageIndex) { return; } this._scrollToHorizontalPageIndex = horizontalPageIndex; this._scrollToVerticalPageIndex = verticalPageIndex; this._scrollToIndexDuration = animationDuration; this.invalidate(INVALIDATION_FLAG_SCROLL); } /** * @private */ override protected function initialize():void { if(!this.scroller) { this.scroller = new Scroller(); this.scroller.viewPort = this.viewPort; this.scroller.nameList.add(this.scrollerName); this.scroller.addEventListener(Event.SCROLL, scroller_scrollHandler); this.scroller.addEventListener(FeathersEventType.SCROLL_COMPLETE, scroller_scrollCompleteHandler); super.addChildAt(this.scroller, 0); } } /** * @private */ override protected function draw():void { var sizeInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SIZE); const dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); const scrollInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SCROLL); const stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); if(dataInvalid) { this.viewPort.text = this._text; this.viewPort.isHTML = this._isHTML; } if(stylesInvalid) { this.viewPort.antiAliasType = this._antiAliasType; this.viewPort.background = this._background; this.viewPort.backgroundColor = this._backgroundColor; this.viewPort.border = this._border; this.viewPort.borderColor = this._borderColor; this.viewPort.condenseWhite = this._condenseWhite; this.viewPort.displayAsPassword = this._displayAsPassword; this.viewPort.gridFitType = this._gridFitType; this.viewPort.sharpness = this._sharpness; this.viewPort.thickness = this._thickness; this.viewPort.textFormat = this._textFormat; this.viewPort.styleSheet = this._styleSheet; this.viewPort.embedFonts = this._embedFonts; this.viewPort.paddingTop = this._paddingTop; this.viewPort.paddingRight = this._paddingRight; this.viewPort.paddingBottom = this._paddingBottom; this.viewPort.paddingLeft = this._paddingLeft; this.refreshScrollerStyles(); } if(scrollInvalid) { this.scroller.verticalScrollPosition = this._verticalScrollPosition; this.scroller.horizontalScrollPosition = this._horizontalScrollPosition; } if(sizeInvalid) { if(isNaN(this.explicitWidth)) { this.scroller.width = NaN; } else { this.scroller.width = Math.max(0, this.explicitWidth); } if(isNaN(this.explicitHeight)) { this.scroller.height = NaN; } else { this.scroller.height = Math.max(0, this.explicitHeight); } this.scroller.minWidth = Math.max(0, this._minWidth); this.scroller.maxWidth = Math.max(0, this._maxWidth); this.scroller.minHeight = Math.max(0, this._minHeight); this.scroller.maxHeight = Math.max(0, this._maxHeight); } sizeInvalid = this.autoSizeIfNeeded() || sizeInvalid; this.scroller.validate(); this._maxHorizontalScrollPosition = this.scroller.maxHorizontalScrollPosition; this._maxVerticalScrollPosition = this.scroller.maxVerticalScrollPosition; this._horizontalScrollPosition = this.scroller.horizontalScrollPosition; this._verticalScrollPosition = this.scroller.verticalScrollPosition; this._horizontalPageIndex = this.scroller.horizontalPageIndex; this._verticalPageIndex = this.scroller.verticalPageIndex; this.scroll(); } /** * @private */ protected function autoSizeIfNeeded():Boolean { const needsWidth:Boolean = isNaN(this.explicitWidth); const needsHeight:Boolean = isNaN(this.explicitHeight); if(!needsWidth && !needsHeight) { return false; } this.scroller.validate(); var newWidth:Number = this.explicitWidth; var newHeight:Number = this.explicitHeight; if(needsWidth) { newWidth = this.scroller.width; } if(needsHeight) { newHeight = this.scroller.height; } return this.setSizeInternal(newWidth, newHeight, false); } /** * @private */ protected function refreshScrollerStyles():void { for(var propertyName:String in this._scrollerProperties) { if(this.scroller.hasOwnProperty(propertyName)) { var propertyValue:Object = this._scrollerProperties[propertyName]; this.scroller[propertyName] = propertyValue; } } } /** * @private */ protected function scroll():void { if(this._scrollToHorizontalPageIndex >= 0 || this._scrollToVerticalPageIndex >= 0) { this.scroller.throwToPage(this._scrollToHorizontalPageIndex, this._scrollToVerticalPageIndex, this._scrollToIndexDuration); this._scrollToHorizontalPageIndex = -1; this._scrollToVerticalPageIndex = -1; } } /** * @private */ protected function childProperties_onChange(proxy:PropertyProxy, name:String):void { this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected function scroller_scrollHandler(event:Event):void { this._horizontalScrollPosition = this.scroller.horizontalScrollPosition; this._verticalScrollPosition = this.scroller.verticalScrollPosition; this._maxHorizontalScrollPosition = this.scroller.maxHorizontalScrollPosition; this._maxVerticalScrollPosition = this.scroller.maxVerticalScrollPosition; this._horizontalPageIndex = this.scroller.horizontalPageIndex; this._verticalPageIndex = this.scroller.verticalPageIndex; this.invalidate(INVALIDATION_FLAG_SCROLL); this.dispatchEventWith(Event.SCROLL); } /** * @private */ protected function scroller_scrollCompleteHandler(event:Event):void { this.dispatchEventWith(FeathersEventType.SCROLL_COMPLETE); } } }
package fairygui { import flash.events.Event; import flash.events.FocusEvent; import flash.events.KeyboardEvent; import flash.system.Capabilities; import flash.system.IME; import flash.text.TextFieldType; import fairygui.utils.ToolSet; public class GTextInput extends GTextField { private var _changed:Boolean; private var _promptText:String; private var _password:Boolean; public var disableIME:Boolean; public function GTextInput() { super(); this.focusable = true; _textField.wordWrap = true; _textField.addEventListener(KeyboardEvent.KEY_DOWN, __textChanged); _textField.addEventListener(Event.CHANGE, __textChanged); _textField.addEventListener(FocusEvent.FOCUS_IN, __focusIn); _textField.addEventListener(FocusEvent.FOCUS_OUT, __focusOut); } public function set maxLength(val:int):void { _textField.maxChars = val; } public function get maxLength():int { return _textField.maxChars; } public function set editable(val:Boolean):void { if(val) { _textField.type = TextFieldType.INPUT; _textField.selectable = true; } else { _textField.type = TextFieldType.DYNAMIC; _textField.selectable = false; } } public function get editable():Boolean { return _textField.type == TextFieldType.INPUT; } public function get promptText():String { return _promptText; } public function set promptText(value:String):void { _promptText = value; renderNow(); } public function get restrict():String { return _textField.restrict; } public function set restrict(value:String):void { _textField.restrict = value; } public function get password():Boolean { return _password; } public function set password(val:Boolean):void { if(_password != val) { _password = val; render(); } } override protected function createDisplayObject():void { super.createDisplayObject(); _textField.type = TextFieldType.INPUT; _textField.selectable = true; _textField.mouseEnabled = true; } override public function get text():String { if(_changed) { _changed = false; _text = _textField.text.replace(/\r\n/g, "\n"); _text = _text.replace(/\r/g, "\n"); } return _text; } override protected function updateAutoSize():void { //输入文本不支持自动大小 } override protected function render():void { renderNow(); } override protected function renderNow():void { var w:Number, h:Number; w = this.width; if(w!=_textField.width) _textField.width = w; h = this.height+_fontAdjustment+1; if(h!=_textField.height) _textField.height = h; _yOffset = -_fontAdjustment; _textField.y = this.y+_yOffset; if(!_text && _promptText) { _textField.displayAsPassword = false; _textField.htmlText = ToolSet.parseUBB(ToolSet.encodeHTML(_promptText)); } else { _textField.displayAsPassword = _password; _textField.text = _text; } _changed = false; } override protected function handleSizeChanged():void { _textField.width = this.width; _textField.height = this.height+_fontAdjustment; } override public function setup_beforeAdd(xml:XML):void { super.setup_beforeAdd(xml); _promptText = xml.@prompt; var str:String = xml.@maxLength; if(str) _textField.maxChars = parseInt(str); str = xml.@restrict; if(str) _textField.restrict = str; _password = xml.@password=="true"; } override internal function setLang(xml:XML):void { super.setLang(xml); promptText = xml.@prompt; } override public function setup_afterAdd(xml:XML):void { super.setup_afterAdd(xml); if(!_text) { if(_promptText) { _textField.displayAsPassword = false; _textField.htmlText = ToolSet.parseUBB(ToolSet.encodeHTML(_promptText)); } } } private function __textChanged(evt:Event):void { _changed = true; TextInputHistory.inst.markChanged(_textField); } private function __focusIn(evt:Event):void { if(disableIME && Capabilities.hasIME) IME.enabled = false; if(!_text && _promptText) { _textField.displayAsPassword = _password; _textField.text = ""; } TextInputHistory.inst.startRecord(_textField); } private function __focusOut(evt:Event):void { if(disableIME && Capabilities.hasIME) IME.enabled = true; _text = _textField.text; TextInputHistory.inst.stopRecord(_textField); _changed = false; if(!_text && _promptText) { _textField.displayAsPassword = false; _textField.htmlText = ToolSet.parseUBB(ToolSet.encodeHTML(_promptText)); } } } }
package sk.yoz.ycanvas.map.valueObjects { import flash.geom.Rectangle; /** * A helper object for hitTest() optimization. */ public class PartialBounds { public var rectangle:Rectangle; public var vertexIndexMin:uint; public var vertexIndexMax:uint; public var indiceIndexMin:uint; public var indiceIndexMax:uint; } }
package laya.webgl.shapes { import laya.webgl.utils.Buffer2D; public class Ellipse extends BasePoly { public function Ellipse(x:Number,y:Number,width:Number,height:Number,color:uint,borderWidth:int,borderColor:uint) { super(x,y,width,height,40,color,borderWidth,borderColor); } } }
package framework.resource.faxb.tutorial { [XmlType(name="execute", propOrder="showArea,clickGrid,panel")] public class Execute { [XmlElement(name="showArea")] public var showArea: Vector.<ShowArea>; [XmlElement(name="clickGrid")] public var clickGrid: ClickGrid; [XmlElement(name="panel", required="true")] public var panel: Vector.<Panel>; [XmlAttribute(name="type", required="true")] public var type: int; [XmlAttribute(name="isDark", required="true")] public var isDark: String; [XmlAttribute(name="complete", required="true")] public var complete: String; } }
package kabam.lib.console.model { internal final class ActionHistory { public function ActionHistory() { this.stack = new Vector.<String>(); this.index = 0; } private var stack:Vector.<String>; private var index:int; public function get length():int { return (this.stack.length); } public function add(_arg1:String):void { this.index = this.stack.push(_arg1); } public function getPrevious():String { return ((((this.index > 0)) ? this.stack[--this.index] : "")); } public function getNext():String { return ((((this.index < (this.stack.length - 1))) ? this.stack[++this.index] : "")); } } }
package tests{ class TestClass2 { public function test1():void {} public function test2(var1:String, var2:Number):Vector.<uint> {} private function test3():String {} } }
package com.ankamagames.dofus.network.messages.game.context.fight { import com.ankamagames.jerakine.network.CustomDataWrapper; import com.ankamagames.jerakine.network.ICustomDataInput; import com.ankamagames.jerakine.network.ICustomDataOutput; import com.ankamagames.jerakine.network.INetworkMessage; import com.ankamagames.jerakine.network.NetworkMessage; import com.ankamagames.jerakine.network.utils.FuncTree; import flash.utils.ByteArray; public class GameFightPlacementSwapPositionsCancelMessage extends NetworkMessage implements INetworkMessage { public static const protocolId:uint = 8925; private var _isInitialized:Boolean = false; public var requestId:uint = 0; public function GameFightPlacementSwapPositionsCancelMessage() { super(); } override public function get isInitialized() : Boolean { return this._isInitialized; } override public function getMessageId() : uint { return 8925; } public function initGameFightPlacementSwapPositionsCancelMessage(requestId:uint = 0) : GameFightPlacementSwapPositionsCancelMessage { this.requestId = requestId; this._isInitialized = true; return this; } override public function reset() : void { this.requestId = 0; this._isInitialized = false; } override public function pack(output:ICustomDataOutput) : void { var data:ByteArray = new ByteArray(); this.serialize(new CustomDataWrapper(data)); writePacket(output,this.getMessageId(),data); } override public function unpack(input:ICustomDataInput, length:uint) : void { this.deserialize(input); } override public function unpackAsync(input:ICustomDataInput, length:uint) : FuncTree { var tree:FuncTree = new FuncTree(); tree.setRoot(input); this.deserializeAsync(tree); return tree; } public function serialize(output:ICustomDataOutput) : void { this.serializeAs_GameFightPlacementSwapPositionsCancelMessage(output); } public function serializeAs_GameFightPlacementSwapPositionsCancelMessage(output:ICustomDataOutput) : void { if(this.requestId < 0) { throw new Error("Forbidden value (" + this.requestId + ") on element requestId."); } output.writeInt(this.requestId); } public function deserialize(input:ICustomDataInput) : void { this.deserializeAs_GameFightPlacementSwapPositionsCancelMessage(input); } public function deserializeAs_GameFightPlacementSwapPositionsCancelMessage(input:ICustomDataInput) : void { this._requestIdFunc(input); } public function deserializeAsync(tree:FuncTree) : void { this.deserializeAsyncAs_GameFightPlacementSwapPositionsCancelMessage(tree); } public function deserializeAsyncAs_GameFightPlacementSwapPositionsCancelMessage(tree:FuncTree) : void { tree.addChild(this._requestIdFunc); } private function _requestIdFunc(input:ICustomDataInput) : void { this.requestId = input.readInt(); if(this.requestId < 0) { throw new Error("Forbidden value (" + this.requestId + ") on element of GameFightPlacementSwapPositionsCancelMessage.requestId."); } } } }
package { import flash.ui.Mouse; import org.flixel.FlxState; import org.flixel.FlxSprite; import org.flixel.FlxEmitter; import org.flixel.FlxObject; import org.flixel.FlxGroup; import org.flixel.FlxG; import org.flixel.FlxU; public class Playstate extends FlxState { [Embed(source="../assets/images/background.png")] protected var img_Background:Class; [Embed(source="../assets/images/turret.png")] protected var img_Turret:Class; [Embed(source="../assets/images/turret_bullet.png")] protected var img_TurretBullet:Class; [Embed(source="../assets/sounds/turret.mp3")] protected var snd_Turret:Class; [Embed(source="../assets/sounds/hit.mp3")] protected var snd_Hit:Class; [Embed(source="../assets/sounds/enemy.mp3")] protected var snd_Enemy:Class; private var m_background:FlxSprite = new FlxSprite(0, 0, img_Background); private var m_turret:FlxSprite = new FlxSprite(160 -8, 224); private var m_bullets:FlxGroup = new FlxGroup; private var m_invaders:Invaders = new Invaders; private var m_HUD:HUD = new HUD; private var m_fireCooldown:Number = 0.0; private var m_turretParticles:FlxEmitter = new FlxEmitter; private var m_invadersCrap:Array = new Array; private var m_lastCrapEmitter:int = 0; private var m_inDeath:Boolean = false; private var m_deathCooldown:Number = 0.0; public function Playstate():void { super(); m_turret.loadGraphic(img_Turret); m_turret.maxVelocity.x = 300; m_turret.drag.x = 500; m_turretParticles.y = 220; m_turretParticles.setXSpeed(-100, 100); m_turretParticles.setYSpeed(-150, 0); } override public function create():void { add(m_background); add(m_turret); add(m_bullets); add(m_invaders); add(m_turretParticles) add(m_HUD); var i:int, j:int; m_fireCooldown = 0.0; m_deathCooldown = 0.0; m_HUD.show_frame(); m_HUD.show_game_info(); m_HUD.show_version(); m_invaders.create(); for (i = 0; i<m_invadersCrap.length; ++i) add(m_invadersCrap[i]); for (i = 0; i < 16; ++i) { var particle:FlxSprite = new FlxSprite; particle.createGraphic(4, 8, 0xdd6464af); m_turretParticles.add(particle); } m_invadersCrap.length = 0; for (j = 0; j < 12; ++j) { var invaderCrap:FlxEmitter = new FlxEmitter; invaderCrap.y = 220; invaderCrap.setXSpeed(-100, 100); invaderCrap.setYSpeed(-150, 0); invaderCrap.setRotation(0, 0); for (i = 0; i < 4; ++i) { var crap:FlxSprite = new FlxSprite; crap.createGraphic(4, 4, 0xdd4949ab); invaderCrap.add(crap); } m_invadersCrap.push(invaderCrap); add(invaderCrap); } for (i = 0; i < 8; ++i) { var oneBullet:FlxSprite = new FlxSprite(0, 0); oneBullet.loadGraphic(img_TurretBullet); oneBullet.visible = false; m_bullets.add(oneBullet); } } override public function update():void { super.update(); var i:int, j:int; // turret controls if (FlxG.keys.LEFT && m_deathCooldown < 1.5) { m_turret.acceleration.x = -1000; } else if (FlxG.keys.RIGHT && m_deathCooldown < 1.5) { m_turret.acceleration.x = 1000; } else { m_turret.acceleration.x = 0; m_turret.velocity.x *= 0.9; } // turret boundings if (m_turret.x < 4) { m_turret.x = 4; m_turret.velocity.x = 0; } else if (m_turret.x > 320 - 4 - 16) { m_turret.x = 320 - 4 - 16; m_turret.velocity.x = 0; } // bullet check for (i = 0; i < m_bullets.members.length; ++i) { if (m_bullets.members[i].y < 0) { m_bullets.members[i].velocity.y = 0; m_bullets.members[i].visible = false; } } // fire if (FlxG.keys.X && m_fireCooldown <= 0 && m_deathCooldown < 1.5) { for (i = 0; i < m_bullets.members.length; ++i) { if (m_bullets.members[i].visible != false) continue; m_bullets.members[i].x = m_turret.x + 6; m_bullets.members[i].y = 224; m_bullets.members[i].velocity.y = -300; m_bullets.members[i].visible = true; m_fireCooldown = 0.15; FlxG.play(snd_Turret); break; } } if (m_fireCooldown > 0) m_fireCooldown -= FlxG.elapsed; if (m_deathCooldown > 0) m_deathCooldown -= FlxG.elapsed; if (m_invaders.destroyed()) { if(Manager.level == 100) FlxG.state = Manager.state_gameover; else FlxG.state = Manager.state_cleared; } if (m_inDeath && m_deathCooldown < 1.5) { if (Manager.lives == 0) FlxG.state = Manager.state_gameover; if (int(m_deathCooldown*10) % 2) m_turret.visible = false; else m_turret.visible = true; } if (m_inDeath && m_deathCooldown <= 0) { m_turret.visible = true; m_inDeath = false; } FlxU.overlap(m_bullets, m_invaders, on_bullet_hit); if (!m_inDeath) FlxU.overlap(m_turret, m_invaders, on_player_hit); } private function on_bullet_hit(bullet:FlxSprite, invader:FlxSprite):void { bullet.visible = false; bullet.velocity.y = 0; bullet.x = -100; bullet.y = -100; if (invader is Invader) { emit_crap(invader.x, invader.y); FlxG.play(snd_Enemy); invader.kill(); } else { invader.velocity.y = 0; invader.visible = false; invader.x = 420; invader.y = -100; } } private function on_player_hit(AA:FlxObject, BB:FlxObject):void { m_turretParticles.x = m_turret.x + 12; m_turretParticles.y = m_turret.y + 8; m_turretParticles.start(); m_turret.visible = false; m_inDeath = true; m_deathCooldown = 3; Manager.lives -= 1; m_HUD.update_info(); FlxG.play(snd_Hit); } private function emit_crap(x:int, y:int):void { m_invadersCrap[m_lastCrapEmitter].x = x; m_invadersCrap[m_lastCrapEmitter].y = y; m_invadersCrap[m_lastCrapEmitter].start(); m_lastCrapEmitter += 1; m_lastCrapEmitter %= m_invadersCrap.length; } } } // package
/* * 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.reflection.description { /** * @author Thijs Broerse */ public interface IMember { /** * */ function get name():String; /** * */ function get namespace():Namespace; /** * */ function get type():Class; /** * */ function get declaredBy():Class; /** * */ function get metadata():Vector.<IMetadata>; /** * */ function getMetadata(name:String):IMetadata; } }
package com.ankamagames.berilia.types.event { import com.ankamagames.berilia.types.data.ExtendedStyleSheet; import flash.events.Event; public class CssEvent extends Event { public static const CSS_PARSED:String = "event_css_parsed"; private var _stylesheet:ExtendedStyleSheet; public function CssEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false, stylesheet:ExtendedStyleSheet = null) { super(type,bubbles,cancelable); this._stylesheet = stylesheet; } public function get stylesheet() : ExtendedStyleSheet { return this._stylesheet; } } }
package kabam.rotmg.assets { import mx.core.BitmapAsset; [Embed(source="EmbeddedAssets_cursedLibraryChars16x16Embed.png")] public class EmbeddedAssets_cursedLibraryChars16x16Embed extends BitmapAsset { public function EmbeddedAssets_cursedLibraryChars16x16Embed() { super(); } } }
package utils.align { /** * Aligns the items in the array horizontally to each the one preceding it in the array. * Uses the same spacing for all. * * @example <listing version="3.0">Alignment.hAlignSpaceNum( [ clip0, clip1, clip2], 10 );</listing> * * @param items An array of items * @param spacing The spacing between items in pixels */ public function horizontalAlignSpaceNumber(items:Array, spacing:Number):void { var n:int = items.length; for (var i:int = 1; i < n; i++) { items[i].x = items[(i - 1)].x + items[(i - 1)].width + spacing; } } }
import gfx.events.EventDispatcher; import skyui.components.list.BasicEnumeration; import skyui.components.list.ScrollingList; import skyui.components.list.FilteredEnumeration; import skyui.filter.SortFilter; import gfx.ui.InputDetails; class ItemView extends MovieClip { public var itemList: ItemList; public var background: MovieClip; public var paddingBottom = 2; public var paddingTop = 0; private var _sortFilter: SortFilter; private var _sortEnabled: Boolean = false; public var dispatchEvent: Function; public var dispatchQueue: Function; public var hasEventListener: Function; public var addEventListener: Function; public var removeEventListener: Function; public var removeAllEventListeners: Function; public var cleanUpEvents: Function; public function ItemView() { super(); EventDispatcher.initialize(this); _sortFilter = new SortFilter(); } public function onLoad() { itemList.listEnumeration = new BasicEnumeration(itemList.entryList); itemList.addEventListener("invalidateHeight", this, "onInvalidateHeight"); dispatchEvent({type: "onLoad", view: this}); } public function get entryList(): Array { return itemList.entryList; } public function get sortEnabled(): Boolean { return _sortEnabled; } public function set sortEnabled(a_sort: Boolean): Void { _sortEnabled = a_sort; if(a_sort) { var enumeration = itemList.listEnumeration = new FilteredEnumeration(itemList.entryList); enumeration.addFilter(_sortFilter); itemList.listEnumeration = enumeration; } else { itemList.listEnumeration = new BasicEnumeration(itemList.entryList); } } public function set entryList(a_newArray: Array): Void { itemList.entryList = a_newArray; sortEnabled = sortEnabled; } public function handleInput(details: InputDetails, pathToFocus: Array): Boolean { return itemList.handleInput(details, pathToFocus); } public function get listHeight(): Number { return itemList.listHeight; } public function setMinViewport(a_minEntries: Number, a_update: Boolean): Void { itemList.minViewport = a_minEntries; if(a_update) { itemList.requestInvalidate(); } } public function setMaxViewport(a_maxEntries: Number, a_update: Boolean): Void { itemList.maxViewport = a_maxEntries; if(a_update) { itemList.requestInvalidate(); } } public function set listHeight(a_height: Number): Void { itemList.listHeight = a_height; background._y = -paddingTop; background._height = a_height + paddingTop + paddingBottom; } public function onInvalidateHeight(event: Object): Void { listHeight = event.height; } }
package idv.cjcat.stardust.common.particles { public interface InfoRecycler { function recycleInfo(particle:Particle):void; function get needsRecycle():Boolean; } }
/* CASA Framework for ActionScript 3.0 Copyright (c) 2009, Contributors of CASA Framework All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the CASA Framework nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.casalib.events { import org.casalib.core.Destroyable; import org.casalib.events.ListenerManager; import org.casalib.events.IRemovableEventDispatcher; import org.casalib.util.StageReference; import flash.display.Stage; import flash.events.Event; /** Created an event proxy between the Stage that implements {@link IRemovableEventDispatcher} and {@link IDestroyable}. @author Aaron Clinger @version 09/06/09 @usageNote You must first initialize {@link StageReference} before using this class. @example <code> package { import flash.events.KeyboardEvent; import org.casalib.display.CasaMovieClip; import org.casalib.events.StageEventProxy; import org.casalib.util.StageReference; public class MyExample extends CasaMovieClip { protected var _stageEventProxy:StageEventProxy; public function MyExample() { super(); StageReference.setStage(this.stage); this._stageEventProxy = new StageEventProxy(); this._stageEventProxy.addEventListener(KeyboardEvent.KEY_DOWN, this._onKeyDown); this._stageEventProxy.addEventListener(KeyboardEvent.KEY_UP, this._onKeyUp); } protected function _onKeyDown(e:KeyboardEvent):void { trace("Key down " + e.keyCode); if (e.keyCode == 65) { trace("a key pressed!"); this._stageEventProxy.removeEventListeners(); } } protected function _onKeyUp(e:KeyboardEvent):void { trace("Key up " + e.keyCode); } } } </code> */ public class StageEventProxy extends Destroyable implements IRemovableEventDispatcher { protected var _listenerManager:ListenerManager; protected var _stage:Stage; /** Created a new StageEventProxy. @param stageId: An identifier that corresponds to a stored Stage in {@link StageReference}. @usageNote You must first initialize {@link StageReference} before using this class. */ public function StageEventProxy(stageId:String = StageReference.STAGE_DEFAULT) { super(); this._stage = StageReference.getStage(stageId); this._listenerManager = ListenerManager.getManager(this._stage); } /** @see "IEventDispatcher documention for this method." */ public function dispatchEvent(event:Event):Boolean { if (this._stage.willTrigger(event.type)) return this._stage.dispatchEvent(event); return true; } /** @see "IEventDispatcher documention for this method." */ public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { this._stage.addEventListener(type, listener, useCapture, priority, useWeakReference); this._listenerManager.addEventListener(type, listener, useCapture, priority, useWeakReference); } /** @see "IEventDispatcher documention for this method." */ public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { this._stage.removeEventListener(type, listener, useCapture); this._listenerManager.removeEventListener(type, listener, useCapture); } /** @see "IEventDispatcher documention for this method." */ public function hasEventListener(type:String):Boolean { return this._stage.hasEventListener(type); } /** @see "IEventDispatcher documention for this method." */ public function willTrigger(type:String):Boolean { return this._stage.willTrigger(type); } public function removeEventsForType(type:String):void { this._listenerManager.removeEventsForType(type); } public function removeEventsForListener(listener:Function):void { this._listenerManager.removeEventsForListener(listener); } public function removeEventListeners():void { this._listenerManager.removeEventListeners(); } override public function destroy():void { this.removeEventListeners(); this._listenerManager.destroy(); super.destroy(); } } }
package integration.scopedMessaging.testObj.moduleA { import flash.display.Sprite; /** * COMMENT * @author Raimundas Banevicius (http://mvcexpress.org/) */ public class ChannelViewA extends Sprite { public var test1handled:Boolean = false; public var test2handled:Boolean = false; public var test3handled:Boolean = false; public var test4handled:Boolean = false; public var test4params:String; } }
package factories { import mx.core.FlexGlobals; public class HeavyFighterFactory extends ResourceFactory { /* Constructor is not used... */ public function HeavyFighterFactory():* { } [Bindable] public static var name:String = 'HeavyFighter'; private static var level_rates:Array = [ 100, 500, 2500, ]; private static var level_costs:Array = [ 300, 1500, 7500, ]; private static var __current_level__:int = 0; public static function get current_level():int { return __current_level__; } public static function set current_level(level:int):void { if (__current_level__ != level) { __current_level__ = level; } } public static function next_level():void { __current_level__++; var app:GalaxyWars = FlexGlobals.topLevelApplication as GalaxyWars; app.mySO.data.__solar_resource_level__ = __current_level__; app.mySO.flush(); } public static function get current_level_production_rate():Number { try { return level_rates[current_level]; } catch (err:Error) {} return -1; } public static function get current_level_upgrade_cost():Number { try { return level_costs[current_level]; } catch (err:Error) {} return -1; } public static function get current_level_upgrade_time():Number { return ResourceFactory.current_level_upgrade_time(current_level); } } }
package { import flash.display.*; /** * based on source code found at: * http://www.macromedia.com/devnet/mx/flash/articles/adv_draw_methods.html * * @author Ric Ewing - version 1.4 - 4.7.2002 * @author Kevin Williams - version 2.0 - 4.7.2005 * @author Aden Forshaw - Version AS3 - 19.4.2010 * @author Sidney de Koning - Version AS3 - 20.4.2010 - errors/correct datatypes/optimized math operations * * Usage: * var s : Shape = new Shape( ); // Or Sprite of MovieClip or any other Class that makes use of the Graphics class * * // Draw an ARC * s.graphics.lineStyle( 4, 0xE16606 ); * DrawingShapes.drawArc( s.graphics, 50, 50, 10, 150, 60 ); * * // Draw an BURST * s.graphics.lineStyle( 3, 0x000000 ); * DrawingShapes.drawBurst( s.graphics, 80, 60, 3, 15, 6, 27 ); * * // Draw an DASHED-LINE like so - - - - * s.graphics.lineStyle( 1, 0x3C3C39 ); * DrawingShapes.drawDash( s.graphics, 120, 60, 150, 80, 2, 2 ); * * // Draw an GEAR * s.graphics.lineStyle( 3, 0xE16606 ); * DrawingShapes.drawGear( s.graphics, 200, 60, 13, 31, 26, 0, 7, 13 ); * * // Draw a POLYGON * s.graphics.lineStyle( 3, 0x0074B9 ); * DrawingShapes.drawPolygon( s.graphics, 270, 60, 7, 30, 45 ); * * // Draw a STAR * s.graphics.lineStyle( 2, 0x000000 ); * DrawingShapes.drawStar( s.graphics, 340, 60, 18, 24, 19, 27 ); * * // Draw an WEDGE - good for pie charts or pacmans * s.graphics.lineStyle( 2, 0xFFCC00 ); * DrawingShapes.drawWedge( s.graphics, 400, 60, 30, 309, 209 ); * * // Draw a LINE * s.graphics.lineStyle( 2, 0x0074B9 ); * DrawingShapes.drawLine( s.graphics, 440, 85, 30, DrawingShapes.VERTICAL_LINE ); * * addChild( s ); */ public class DrawingShapes { public static const HORIZONTAL_LINE : String = "DrawingShapes.horizontal"; public static const VERTICAL_LINE : String = "DrawingShapes.vertical"; public function DrawingShapes() { throw new ArgumentError( "The DrawingShapes Class cannot be instanicated." ); } /** * drawDash * Draws a dashed line from the point x1,y1 to the point x2,y2 * * @param target Graphics the Graphics Class on which the dashed line will be drawn. * @param x1 Number starting position on x axis - <strong></strong>required</strong> * @param y1 Number starting position on y axis - <strong></strong>required</strong> * @param x2 Number finishing position on x axis - <strong></strong>required</strong> * @param y2 Number finishing position on y axis - <strong></strong>required</strong> * @param dashLength [optional] Number the number of pixels long each dash * will be. Default = 5 * @param spaceLength [optional] Number the number of pixels between each * dash. Default = 5 */ public static function drawDash(target : Graphics, x1 : Number,y1 : Number,x2 : Number, y2 : Number, dashLength : Number = 5, spaceLength : Number = 5 ) : void { var x : Number = x2 - x1; var y : Number = y2 - y1; var hyp : Number = Math.sqrt( (x) * (x) + (y) * (y) ); var units : Number = hyp / (dashLength + spaceLength); var dashSpaceRatio : Number = dashLength / (dashLength + spaceLength); var dashX : Number = (x / units) * dashSpaceRatio; var spaceX : Number = (x / units) - dashX; var dashY : Number = (y / units) * dashSpaceRatio; var spaceY : Number = (y / units) - dashY; target.moveTo( x1, y1 ); while (hyp > 0) { x1 += dashX; y1 += dashY; hyp -= dashLength; if (hyp < 0) { x1 = x2; y1 = y2; } target.lineTo( x1, y1 ); x1 += spaceX; y1 += spaceY; target.moveTo( x1, y1 ); hyp -= spaceLength; } target.moveTo( x2, y2 ); } /** * Draws an arc from the starting position of x,y. * * @param target the Graphics Class that the Arc is drawn on. * @param x x coordinate of the starting pen position * @param y y coordinate of the starting pen position * @param radius radius of Arc. * @param arc = sweep of the arc. Negative values draw clockwise. * @param startAngle = [optional] starting offset angle in degrees. * @param yRadius = [optional] y radius of arc. if different than * radius, then the arc will draw as the arc of an oval. * default = radius. * * Based on mc.drawArc by Ric Ewing. * the version by Ric assumes that the pen is at x:y before this * method is called. I explictily move the pen to x:y to be * consistent with the behaviour of the other methods. */ public static function drawArc(target : Graphics, x : Number, y : Number, radius : Number, arc : Number, startAngle : Number = 0, yRadius : Number = 0) : void { if (arguments.length < 5) { throw new ArgumentError( "DrawingShapes.drawArc() - too few parameters, need atleast 5." ); return; } // if startAngle is undefined, startAngle = 0 if( startAngle == 0 ) { startAngle = 0; } // if yRadius is undefined, yRadius = radius if (yRadius == 0) { yRadius = radius; } // Init vars var segAngle : Number, theta : Number, angle : Number, angleMid : Number, segs : Number, ax : Number, ay : Number, bx : Number, by : Number, cx : Number, cy : Number; // no sense in drawing more than is needed :) if (DrawingShapes.abs( arc ) > 360) { arc = 360; } // Flash uses 8 segments per circle, to match that, we draw in a maximum // of 45 degree segments. First we calculate how many segments are needed // for our arc. segs = DrawingShapes.ceil( DrawingShapes.abs( arc ) / 45 ); // Now calculate the sweep of each segment segAngle = arc / segs; // The math requires radians rather than degrees. To convert from degrees // use the formula (degrees/180)*Math.PI to get radians. theta = -(segAngle / 180) * Math.PI; // convert angle startAngle to radians angle = -(startAngle / 180) * Math.PI; // find our starting points (ax,ay) relative to the secified x,y ax = x - Math.cos( angle ) * radius; ay = y - Math.sin( angle ) * yRadius; // if our arc is larger than 45 degrees, draw as 45 degree segments // so that we match Flash's native circle routines. if (segs > 0) { target.moveTo( x, y ); // Loop for drawing arc segments for (var i : int = 0; i < segs; ++i) { // increment our angle angle += theta; // find the angle halfway between the last angle and the new angleMid = angle - (theta / 2); // calculate our end point bx = ax + Math.cos( angle ) * radius; by = ay + Math.sin( angle ) * yRadius; // calculate our control point cx = ax + Math.cos( angleMid ) * (radius / Math.cos( theta / 2 )); cy = ay + Math.sin( angleMid ) * (yRadius / Math.cos( theta / 2 )); // draw the arc segment target.curveTo( cx, cy, bx, by ); } } } /** * draws pie shaped wedges. Could be employeed to draw pie charts. * * @param target the Graphics on which the wedge is to be drawn. * @param x x coordinate of the center point of the wedge * @param y y coordinate of the center point of the wedge * @param radius the radius of the wedge * @param arc the sweep of the wedge. negative values draw clockwise * @param startAngle the starting angle in degrees * @param yRadius [optional] the y axis radius of the wedge. * If not defined, then yRadius = radius. * * based on mc.drawWedge() - by Ric Ewing (ric@formequalsfunction.com) - version 1.4 - 4.7.2002 */ public static function drawWedge(target : Graphics, x : Number, y : Number, radius : Number, arc : Number, startAngle : Number = 0, yRadius : Number = 0) : void { // if yRadius is undefined, yRadius = radius if (yRadius == 0) { yRadius = radius; } // move to x,y position target.moveTo( x, y ); // if yRadius is undefined, yRadius = radius if (yRadius == 0) { yRadius = radius; } // Init vars var segAngle : Number, theta : Number, angle : Number, angleMid : Number, segs : Number, ax : Number, ay : Number, bx : Number, by : Number, cx : Number, cy : Number; // limit sweep to reasonable numbers if (DrawingShapes.abs( arc ) > 360) { arc = 360; } // Flash uses 8 segments per circle, to match that, we draw in a maximum // of 45 degree segments. First we calculate how many segments are needed // for our arc. segs = DrawingShapes.ceil( DrawingShapes.abs( arc ) / 45 ); // Now calculate the sweep of each segment. segAngle = arc / segs; // The math requires radians rather than degrees. To convert from degrees // use the formula (degrees/180)*Math.PI to get radians. theta = -(segAngle / 180) * Math.PI; // convert angle startAngle to radians angle = -(startAngle / 180) * Math.PI; // draw the curve in segments no larger than 45 degrees. if (segs > 0) { // draw a line from the center to the start of the curve ax = x + Math.cos( startAngle / 180 * Math.PI ) * radius; ay = y + Math.sin( -startAngle / 180 * Math.PI ) * yRadius; target.lineTo( ax, ay ); // Loop for drawing curve segments for (var i : int = 0; i < segs; ++i) { angle += theta; angleMid = angle - (theta / 2); bx = x + Math.cos( angle ) * radius; by = y + Math.sin( angle ) * yRadius; cx = x + Math.cos( angleMid ) * (radius / Math.cos( theta / 2 )); cy = y + Math.sin( angleMid ) * (yRadius / Math.cos( theta / 2 )); target.curveTo( cx, cy, bx, by ); } // close the wedge by drawing a line to the center target.lineTo( x, y ); } } /** * start draws a star shaped polygon. * * <blockquote>Note that the stars by default 'point' to * the right. This is because the method starts drawing * at 0 degrees by default, putting the first point to * the right of center. Negative values for points * draws the star in reverse direction, allowing for * knock-outs when used as part of a mask.</blockquote> * * @param target the Graphics that the star is drawn on * @param x x coordinate of the center of the star * @param y y coordinate of the center of the star * @param points the number of points on the star * @param innerRadius the radius of the inside angles of the star * @param outerRadius the radius of the outside angles of the star * @param angle [optional] the offet angle that the start is rotated * * based on mc.drawStar() - by Ric Ewing (ric@formequalsfunction.com) - version 1.4 - 4.7.2002 */ public static function drawStar(target : Graphics, x : Number, y : Number, points : uint, innerRadius : Number, outerRadius : Number, angle : Number = 0) : void { // check that points is sufficient to build polygon if(points <= 2) { throw ArgumentError( "DrawingShapes.drawStar() - parameter 'points' needs to be atleast 3" ); return; } if (points > 2) { // init vars var step : Number, halfStep : Number, start : Number, n : Number, dx : Number, dy : Number; // calculate distance between points step = (Math.PI * 2) / points; halfStep = step / 2; // calculate starting angle in radians start = (angle / 180) * Math.PI; target.moveTo( x + (Math.cos( start ) * outerRadius), y - (Math.sin( start ) * outerRadius) ); // draw lines for (n = 1; n <= points; ++n) { dx = x + Math.cos( start + (step * n) - halfStep ) * innerRadius; dy = y - Math.sin( start + (step * n) - halfStep ) * innerRadius; target.lineTo( dx, dy ); dx = x + Math.cos( start + (step * n) ) * outerRadius; dy = y - Math.sin( start + (step * n) ) * outerRadius; target.lineTo( dx, dy ); } } } /** * a method for creating polygon shapes. Negative values will draw * the polygon in reverse direction. Negative drawing may be useful * for creating knock-outs in masks. * * @param target the Graphics that the polygon is to be drawn on * @param x x coordinate of the center of the polygon * @param y y coordinate of the center of the polygon * @param sides the number of sides (must be > 2) * @param radius the radius from the center point to the points * on the polygon * @param angle [optional] the starting offset angle (degrees) from * 0. Default = 0 * * based on mc.drawPoly() - by Ric Ewing (ric@formequalsfunction.com) - version 1.4 - 4.7.2002 */ public static function drawPolygon(target : Graphics, x : Number, y : Number, sides : uint, radius : Number, angle : Number = 0) : void { // check that sides is sufficient to build if(sides <= 2) { throw ArgumentError( "DrawingShapes.drawPolygon() - parameter 'sides' needs to be atleast 3" ); return; } if (sides > 2) { // init vars var step : Number, start : Number, n : Number, dx : Number, dy : Number; // calculate span of sides step = (Math.PI * 2) / sides; // calculate starting angle in radians start = (angle / 180) * Math.PI; target.moveTo( x + (Math.cos( start ) * radius), y - (Math.sin( start ) * radius) ); // draw the polygon for (n = 1; n <= sides; ++n) { dx = x + Math.cos( start + (step * n) ) * radius; dy = y - Math.sin( start + (step * n) ) * radius; target.lineTo( dx, dy ); } } } /** * Burst is a method for drawing star bursts. If you've ever worked * with an advertising department, you know what they are ;-) * Clients tend to want them, Developers tend to hate them... * * @param target Graphics where the Burst is to be drawn. * @param x x coordinate of the center of the burst * @param y y coordinate of the center of the burst * @param sides number of sides or points * @param innerRadius radius of the indent of the curves * @param outerRadius radius of the outermost points * @param angle [optional] starting angle in degrees. (defaults to 0) * * based on mc.drawBurst() - by Ric Ewing (ric@formequalsfunction.com) - version 1.4 - 4.7.2002 */ public static function drawBurst(target : Graphics, x : Number, y : Number, sides : uint, innerRadius : Number, outerRadius : Number, angle : Number = 0 ) : void { // check that sides is sufficient to build if(sides <= 2) { throw ArgumentError( "DrawingShapes.drawBurst() - parameter 'sides' needs to be atleast 3" ); return; } if (sides > 2) { // init vars var step : Number, halfStep : Number, qtrStep : Number, start : Number, n : Number, dx : Number, dy : Number, cx : Number, cy : Number; // calculate length of sides step = (Math.PI * 2) / sides; halfStep = step / 2; qtrStep = step / 4; // calculate starting angle in radians start = (angle / 180) * Math.PI; target.moveTo( x + (Math.cos( start ) * outerRadius), y - (Math.sin( start ) * outerRadius) ); // draw curves for (n = 1; n <= sides; ++n) { cx = x + Math.cos( start + (step * n) - (qtrStep * 3) ) * (innerRadius / Math.cos( qtrStep )); cy = y - Math.sin( start + (step * n) - (qtrStep * 3) ) * (innerRadius / Math.cos( qtrStep )); dx = x + Math.cos( start + (step * n) - halfStep ) * innerRadius; dy = y - Math.sin( start + (step * n) - halfStep ) * innerRadius; target.curveTo( cx, cy, dx, dy ); cx = x + Math.cos( start + (step * n) - qtrStep ) * (innerRadius / Math.cos( qtrStep )); cy = y - Math.sin( start + (step * n) - qtrStep ) * (innerRadius / Math.cos( qtrStep )); dx = x + Math.cos( start + (step * n) ) * outerRadius; dy = y - Math.sin( start + (step * n) ) * outerRadius; target.curveTo( cx, cy, dx, dy ); } } } /** * draws a gear shape on the Graphics target. The gear position * is indicated by the x and y arguments. * * @param target Graphics on which the gear is to be drawn. * @param x x coordinate of the center of the gear * @param y y coordinate of the center of the gear * @param sides number of teeth on gear. (must be > 2) * @param innerRadius radius of the indent of the teeth. * @param outerRadius outer radius of the teeth. * @param angle = [optional] starting angle in degrees. Defaults to 0. * @param holeSides [optional] draw a polygonal hole with this many sides (must be > 2) * @param holeRadius [optional] size of hole. Default = innerRadius/3. * * based on mc.drawGear() - by Ric Ewing (ric@formequalsfunction.com) - version 1.4 - 4.7.2002 */ public static function drawGear(target : Graphics, x : Number, y : Number, sides : uint, innerRadius : Number = 80, outerRadius : Number = 4, angle : Number = 0, holeSides : Number = 2, holeRadius : Number = 0 ) : void { // check that sides is sufficient to build polygon if(sides <= 2) { throw ArgumentError( "DrawingShapes.drawGear() - parameter 'sides' needs to be atleast 3" ); return; } if (sides > 2) { // init vars var step : Number, qtrStep : Number, start : Number, n : Number, dx : Number, dy : Number; // calculate length of sides step = (Math.PI * 2) / sides; qtrStep = step / 4; // calculate starting angle in radians start = (angle / 180) * Math.PI; target.moveTo( x + (Math.cos( start ) * outerRadius), y - (Math.sin( start ) * outerRadius) ); // draw lines for (n = 1; n <= sides; ++n) { dx = x + Math.cos( start + (step * n) - (qtrStep * 3) ) * innerRadius; dy = y - Math.sin( start + (step * n) - (qtrStep * 3) ) * innerRadius; target.lineTo( dx, dy ); dx = x + Math.cos( start + (step * n) - (qtrStep * 2) ) * innerRadius; dy = y - Math.sin( start + (step * n) - (qtrStep * 2) ) * innerRadius; target.lineTo( dx, dy ); dx = x + Math.cos( start + (step * n) - qtrStep ) * outerRadius; dy = y - Math.sin( start + (step * n) - qtrStep ) * outerRadius; target.lineTo( dx, dy ); dx = x + Math.cos( start + (step * n) ) * outerRadius; dy = y - Math.sin( start + (step * n) ) * outerRadius; target.lineTo( dx, dy ); } // This is complete overkill... but I had it done already. :) if (holeSides > 2) { step = (Math.PI * 2) / holeSides; target.moveTo( x + (Math.cos( start ) * holeRadius), y - (Math.sin( start ) * holeRadius) ); for (n = 1; n <= holeSides; ++n) { dx = x + Math.cos( start + (step * n) ) * holeRadius; dy = y - Math.sin( start + (step * n) ) * holeRadius; target.lineTo( dx, dy ); } } } } /** * draws a line between two points. Make it horizontal or vertical * * @param target Graphics on which the gear is to be drawn. * @param x x coordinate of the center of the gear * @param y y coordinate of the center of the gear * @param sides number of teeth on gear. (must be > 2) * * */ public static function drawLine(target : Graphics, x : Number, y : Number, length : Number, direction : String = DrawingShapes.HORIZONTAL_LINE ) : void { target.moveTo( x, y ); switch (direction) { case DrawingShapes.HORIZONTAL_LINE : target.lineTo( length, y ); break; case DrawingShapes.VERTICAL_LINE : target.moveTo( x, y ); target.lineTo( x, length ); break; } } /* * new abs function, about 25x faster than Math.abs */ private static function abs( value : Number ) : Number { return value < 0 ? -value : value; } /* * new ceil function about 75% faster than Math.ceil. */ private static function ceil( value : Number) : Number { return (value % 1) ? int( value ) + 1 : value; } } }
package kabam.rotmg.messaging.impl.incoming.arena { import flash.utils.IDataInput; import kabam.rotmg.messaging.impl.incoming.IncomingMessage; public class ArenaDeath extends IncomingMessage { public function ArenaDeath(param1:uint, param2:Function) { super(param1, param2); } public var cost:int; override public function parseFromInput(param1:IDataInput):void { this.cost = param1.readInt(); } override public function toString():String { return formatToString("ARENADEATH", "cost"); } } }
/* Copyright 2019 Tua Rua Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.tuarua.iap.storekit { public class ReceiptInfo { public var original_purchase_date:String; public var original_purchase_date_ms:String; public var original_purchase_date_pst:String; public var product_id:String; public var transaction_id:String; public var original_transaction_id:String; public var is_trial_period:String; public var purchase_date:String; public var purchase_date_ms:String; public var purchase_date_pst:String; public var quantity:String; public var expires_date:String; public var expires_date_ms:String; public var expires_date_pst:String; public var subscription_group_identifier:String; public var is_in_intro_offer_period:String; public var web_order_line_item_id:String; public function ReceiptInfo() { } } }
package kabam.lib.console.signals { import kabam.lib.console.vo.ConsoleAction; import org.osflash.signals.Signal; public final class RegisterConsoleActionSignal extends Signal { public function RegisterConsoleActionSignal() { super(ConsoleAction, Signal); } } }
package { import flash.utils.Dictionary; import starling.text.BitmapFont; import starling.textures.Texture; public class Fonts { public static const NAME:String = "Fira Sans Semi-Bold 13"; [Embed(source="../fonts/fira-sans-semi-bold-13.fnt", mimeType="application/octet-stream")] private static const FiraRegular13XML:Class; private static var fonts:Dictionary = new Dictionary(); public static function getFont(_name:String):BitmapFont { if (fonts["fira-sans-semi-bold-13"] == undefined) { fonts["fira-sans-semi-bold-13"] = XML(new FiraRegular13XML()); } var fntTexture:Texture = Assets.getAtlas().getTexture(_name); return new BitmapFont(fntTexture, fonts[_name]); } } }
package com.unhurdle.spectrum { public class FieldGroup extends Group { /** * <inject_html> * <link rel="stylesheet" href="assets/css/components/fieldgroup/dist.css"> * </inject_html> * */ public function FieldGroup() { super(); } override protected function getSelector():String{ return "spectrum-FieldGroup"; } private var _vertical:Boolean; public function get vertical():Boolean { return _vertical; } public function set vertical(value:Boolean):void { if(value != !!_vertical){ toggle(valueToSelector("vertical"),value); } _vertical = value; } } }
package away3d.tools.helpers { import away3d.core.base.ParticleGeometry; import away3d.core.base.CompactSubGeometry; import away3d.core.base.data.ParticleData; import away3d.core.base.Geometry; import away3d.core.base.ISubGeometry; import away3d.tools.helpers.data.ParticleGeometryTransform; import flash.geom.Matrix; import flash.geom.Matrix3D; import flash.geom.Point; import flash.geom.Vector3D; /** * ... */ public class ParticleGeometryHelper { public static const MAX_VERTEX:int = 65535; public static function generateGeometry(geometries:Vector.<Geometry>, transforms:Vector.<ParticleGeometryTransform> = null):ParticleGeometry { var verticesVector:Vector.<Vector.<Number>> = new Vector.<Vector.<Number>>(); var indicesVector:Vector.<Vector.<uint>> = new Vector.<Vector.<uint>>(); var vertexCounters:Vector.<uint> = new Vector.<uint>(); var particles:Vector.<ParticleData> = new Vector.<ParticleData>(); var subGeometries:Vector.<CompactSubGeometry> = new Vector.<CompactSubGeometry>(); var numParticles:uint = geometries.length; var sourceSubGeometries:Vector.<ISubGeometry>; var sourceSubGeometry:ISubGeometry; var numSubGeometries:uint; var vertices:Vector.<Number>; var indices:Vector.<uint>; var vertexCounter:uint; var subGeometry:CompactSubGeometry; var i:int; var j:int; var sub2SubMap:Vector.<int> = new Vector.<int>; var tempVertex:Vector3D = new Vector3D; var tempNormal:Vector3D = new Vector3D; var tempTangents:Vector3D = new Vector3D; var tempUV:Point = new Point; for (i = 0; i < numParticles; i++) { sourceSubGeometries = geometries[i].subGeometries; numSubGeometries = sourceSubGeometries.length; for (var srcIndex:int = 0; srcIndex < numSubGeometries; srcIndex++) { //create a different particle subgeometry group for each source subgeometry in a particle. if (sub2SubMap.length <= srcIndex) { sub2SubMap.push(subGeometries.length); verticesVector.push(new Vector.<Number>); indicesVector.push(new Vector.<uint>); subGeometries.push(new CompactSubGeometry()); vertexCounters.push(0); } sourceSubGeometry = sourceSubGeometries[srcIndex]; //add a new particle subgeometry if this source subgeometry will take us over the maxvertex limit if (sourceSubGeometry.numVertices + vertexCounters[sub2SubMap[srcIndex]] > MAX_VERTEX) { //update submap and add new subgeom vectors sub2SubMap[srcIndex] = subGeometries.length; verticesVector.push(new Vector.<Number>); indicesVector.push(new Vector.<uint>); subGeometries.push(new CompactSubGeometry()); vertexCounters.push(0); } j = sub2SubMap[srcIndex]; //select the correct vector vertices = verticesVector[j]; indices = indicesVector[j]; vertexCounter = vertexCounters[j]; subGeometry = subGeometries[j]; var particleData:ParticleData = new ParticleData(); particleData.numVertices = sourceSubGeometry.numVertices; particleData.startVertexIndex = vertexCounter; particleData.particleIndex = i; particleData.subGeometry = subGeometry; particles.push(particleData); vertexCounters[j] += sourceSubGeometry.numVertices; var k:int; var tempLen:int; var compact:CompactSubGeometry = sourceSubGeometry as CompactSubGeometry; var product:uint; var sourceVertices:Vector.<Number>; if (compact) { tempLen = compact.numVertices; compact.numTriangles; sourceVertices = compact.vertexData; if (transforms) { var particleGeometryTransform:ParticleGeometryTransform = transforms[i]; var vertexTransform:Matrix3D = particleGeometryTransform.vertexTransform; var invVertexTransform:Matrix3D = particleGeometryTransform.invVertexTransform; var UVTransform:Matrix = particleGeometryTransform.UVTransform; for (k = 0; k < tempLen; k++) { /* * 0 - 2: vertex position X, Y, Z * 3 - 5: normal X, Y, Z * 6 - 8: tangent X, Y, Z * 9 - 10: U V * 11 - 12: Secondary U V*/ product = k*13; tempVertex.x = sourceVertices[product]; tempVertex.y = sourceVertices[product + 1]; tempVertex.z = sourceVertices[product + 2]; tempNormal.x = sourceVertices[product + 3]; tempNormal.y = sourceVertices[product + 4]; tempNormal.z = sourceVertices[product + 5]; tempTangents.x = sourceVertices[product + 6]; tempTangents.y = sourceVertices[product + 7]; tempTangents.z = sourceVertices[product + 8]; tempUV.x = sourceVertices[product + 9]; tempUV.y = sourceVertices[product + 10]; if (vertexTransform) { tempVertex = vertexTransform.transformVector(tempVertex); tempNormal = invVertexTransform.deltaTransformVector(tempNormal); tempTangents = invVertexTransform.deltaTransformVector(tempNormal); } if (UVTransform) tempUV = UVTransform.transformPoint(tempUV); //this is faster than that only push one data vertices.push(tempVertex.x, tempVertex.y, tempVertex.z, tempNormal.x, tempNormal.y, tempNormal.z, tempTangents.x, tempTangents.y, tempTangents.z, tempUV.x, tempUV.y, sourceVertices[product + 11], sourceVertices[product + 12]); } } else { for (k = 0; k < tempLen; k++) { product = k*13; //this is faster than that only push one data vertices.push(sourceVertices[product], sourceVertices[product + 1], sourceVertices[product + 2], sourceVertices[product + 3], sourceVertices[product + 4], sourceVertices[product + 5], sourceVertices[product + 6], sourceVertices[product + 7], sourceVertices[product + 8], sourceVertices[product + 9], sourceVertices[product + 10], sourceVertices[product + 11], sourceVertices[product + 12]); } } } else { //Todo } var sourceIndices:Vector.<uint> = sourceSubGeometry.indexData; tempLen = sourceSubGeometry.numTriangles; for (k = 0; k < tempLen; k++) { product = k*3; indices.push(sourceIndices[product] + vertexCounter, sourceIndices[product + 1] + vertexCounter, sourceIndices[product + 2] + vertexCounter); } } } var particleGeometry:ParticleGeometry = new ParticleGeometry(); particleGeometry.particles = particles; particleGeometry.numParticles = numParticles; numParticles = subGeometries.length; for (i = 0; i < numParticles; i++) { subGeometry = subGeometries[i]; subGeometry.updateData(verticesVector[i]); subGeometry.updateIndexData(indicesVector[i]); particleGeometry.addSubGeometry(subGeometry); } return particleGeometry; } } }
package nt.ui.components { import flash.display.DisplayObject; import flash.events.MouseEvent; import flash.geom.Rectangle; import nt.ui.configs.DefaultStyle; import nt.ui.core.Component; import nt.ui.core.SkinnableComponent; /** * 垂直拖拽条 * @author KK * */ public class VSlider extends SkinnableComponent { /** * 使用同一个 Rectangle 储存拖拽时的参数,避免重复创建对象 */ private static var dragRect:Rectangle = new Rectangle(); [Skin] public var handle:Scale9Image; [Skin] public var track:Scale9Image; protected var direction:int; public function VSlider(skin:* = null, direction:int = SliderDirection.V) { super(skin || DefaultStyle.VSliderSkin); this.direction = direction; } override public function setSkin(value:DisplayObject):void { super.setSkin(value); handle.onMouseDown.add(handle_mouseDownHandler); handle.buttonMode = true; track.longPressEnabled = true; track.longPressDelay = 100; track.onLongPress.add(track_longPressingHandler); track.onLongPressing.add(track_longPressingHandler); } protected function track_longPressingHandler(target:Component):void { isPressing = true; stage.addEventListener(MouseEvent.MOUSE_UP, stage_onMouseUp); if (direction == SliderDirection.V) { if (mouseY < handle.y) { value -= 0.1; } else if (mouseY > handle.y + handle.height) { value += 0.1; } } else { if (mouseX < handle.x) { value -= 0.1; } else if (mouseX > handle.x + handle.width) { value += 0.1; } } } protected function stage_onMouseUp(event:MouseEvent):void { isPressing = false; stage.removeEventListener(MouseEvent.MOUSE_UP, stage_onMouseUp); } protected function handle_mouseDownHandler(target:Component):void { isDragging = true; dragRect.x = track.x; dragRect.y = track.y; if (direction == SliderDirection.V) { dragRect.width = 0; dragRect.height = track.height - handle.height; } else { dragRect.width = track.width - handle.width; dragRect.height = 0; } handle.startDrag(false, dragRect); stage.addEventListener(MouseEvent.MOUSE_MOVE, handle_onMouseMove); stage.addEventListener(MouseEvent.MOUSE_UP, handle_onMouseUp); } protected function handle_onMouseUp(event:MouseEvent):void { isDragging = false; handle.stopDrag(); stage.removeEventListener(MouseEvent.MOUSE_MOVE, handle_onMouseMove); stage.removeEventListener(MouseEvent.MOUSE_UP, handle_onMouseUp); } protected function handle_onMouseMove(event:MouseEvent):void { if (direction == SliderDirection.V) { value = (handle.y - track.y) / (track.height - handle.height); } else { value = (handle.x - track.x) / (track.width - handle.width); } } private var _value:Number = 0; /** * 设置或获取当前 slider 的值 * @return * */ public function get value():Number { return _value; } public function set value(value:Number):void { if (value > 1) { value = 1; } else if (value < 0 || isNaN(value)) { value = 0; } _value = value; if (!isDragging) { invalidate(); } } override protected function render():void { super.render(); if (direction == SliderDirection.V) { handle.y = track.y + (track.height - handle.height) * value; } else { handle.x = track.x + (track.width - handle.width) * value; } } override public function set height(value:Number):void { // 同时更改 track 的高度 if (direction == SliderDirection.V) { track.height = value; super.height = value; } else { throw new Error("当前方向不能设置高度"); } } override public function set width(value:Number):void { if (direction == SliderDirection.H) { track.width = value; super.width = value; } else { throw new Error("当前方向不能设置宽度"); } } override public function get height():Number { // 总是使用 track 作为 VSlider 的高度 return track.height; } override public function get width():Number { // 总是以 track 的宽度作为 Slider 的宽度 return track.width; } /** * 指示当前是否按住了 track * @return * */ protected var isPressing:Boolean; /** * 指示当前是否正在拖动 handle * @return * */ protected var isDragging:Boolean; } }
/** * Created by takumus on 2017/01/23. */ package routes { public class RouteGenerator { public function RouteGenerator() { } } }
package com.tinyspeck.engine.net { public class NetOutgoingLogoutVO extends NetOutgoingMessageVO { public function NetOutgoingLogoutVO() { super(MessageTypes.LOGOUT); } } }
package modules.game.majiangGame.view.majiangPart.huaPart { public class HuaVo { public var cardIdx:int; public var pos:int; public var isMopai:Boolean; public function HuaVo() { } } }
/** * Copyright (c) 2007 - 2009 Adobe * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package com.adobe.cairngorm.navigation.core { import flash.events.Event; import org.flexunit.assertThat; import org.hamcrest.object.equalTo; public class NavigationController_NestedEnterAndExitTest { private var controller : NavigationController; private var content : String = "content"; private var tasks : String = "content.tasks"; private var expenses : String = "content.tasks.expenses"; private var privateexpenses : String = "content.tasks.expenses.private"; private var timetracking : String = "content.tasks.timetracking"; private var news : String = "content.news"; private var sidebar : String = "sidebar.chat"; [Before] public function create() : void { eventHandlerCalled = false; eventHandlerCalls = 0; controller = new NavigationController(); } private var eventHandlerCalled:Boolean; private var eventHandlerCalls:int; private function eventHandler(event:Event):void { eventHandlerCalled = true; eventHandlerCalls++; } [Test] public function whenChildFirstEnterThenTriggerParentFirst() : void { //enter destinations in reading order controller.registerDestination( content ); controller.addEventListener(content + ":" + NavigationActionName.FIRST_ENTER, eventHandler); controller.registerDestination( tasks ); controller.addEventListener(tasks + ":" + NavigationActionName.FIRST_ENTER, eventHandler); controller.registerDestination( expenses ); controller.addEventListener(expenses + ":" + NavigationActionName.FIRST_ENTER, eventHandler); controller.navigateTo( expenses ); assertThat("eventHandlerCalled", eventHandlerCalled); assertThat("calls", eventHandlerCalls, equalTo(3)); } [Test] public function whenChildEnterThenTriggerParentFirst() : void { //enter destinations in reading order controller.registerDestination( content ); controller.addEventListener(content + ":" + NavigationActionName.FIRST_ENTER, eventHandler); controller.registerDestination( tasks ); controller.addEventListener(tasks + ":" + NavigationActionName.FIRST_ENTER, eventHandler); controller.registerDestination( expenses ); controller.addEventListener(expenses + ":" + NavigationActionName.FIRST_ENTER, eventHandler); controller.registerDestination( news ); controller.addEventListener(news + ":" + NavigationActionName.FIRST_ENTER, eventHandler); controller.navigateTo( expenses ); controller.navigateTo( news ); assertThat("eventHandlerCalled", eventHandlerCalled); assertThat("calls", eventHandlerCalls, equalTo(4)); } [Test] public function whenANestedDestinationIsReenteredOnAWaypointTriggerNestedLandmarks() : void { controller.registerDestination( content ); controller.addEventListener( content + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.addEventListener(content + ":" + NavigationActionName.ENTER, eventHandler); controller.registerDestination( tasks ); controller.addEventListener( tasks + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.addEventListener(tasks + ":" + NavigationActionName.ENTER, eventHandler); controller.registerDestination( expenses ); controller.addEventListener( expenses + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.addEventListener(expenses + ":" + NavigationActionName.ENTER, eventHandler); controller.registerDestination( news ); controller.addEventListener( news + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.navigateTo( expenses ); controller.navigateTo( news ); //now navigate back to waypoint and expect nested landmarks to receive enter events controller.navigateTo( tasks ); assertThat("eventHandlerCalled", eventHandlerCalled); assertThat("calls", eventHandlerCalls, equalTo(2)); } [Test] public function shouldPreventDuplicateEvents() : void { controller.registerDestination( content ); controller.addEventListener( content + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.addEventListener(content + ":" + NavigationActionName.EXIT, eventHandler); controller.addEventListener(content + ":" + NavigationActionName.ENTER, eventHandler); controller.registerDestination( tasks ); controller.addEventListener( tasks + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.addEventListener(tasks + ":" + NavigationActionName.EXIT, eventHandler); controller.addEventListener(tasks + ":" + NavigationActionName.ENTER, eventHandler); controller.registerDestination( expenses ); controller.addEventListener( expenses + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.addEventListener(expenses + ":" + NavigationActionName.EXIT, eventHandler); controller.addEventListener(expenses + ":" + NavigationActionName.ENTER, eventHandler); controller.navigateTo( expenses ); controller.navigateTo( expenses ); assertThat("eventHandlerCalled", !eventHandlerCalled); } [Test] public function whenNavigateToSiblingLandmarkThenOnlyEnterSubsetLandmark() : void { controller.registerDestination( content ); controller.addEventListener( content + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.addEventListener(content + ":" + NavigationActionName.EXIT, eventHandler); controller.addEventListener(content + ":" + NavigationActionName.ENTER, eventHandler); controller.registerDestination( tasks ); controller.addEventListener( tasks + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.addEventListener(tasks + ":" + NavigationActionName.EXIT, eventHandler); controller.addEventListener(tasks + ":" + NavigationActionName.ENTER, eventHandler); controller.registerDestination( expenses ); controller.addEventListener( expenses + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.addEventListener(expenses + ":" + NavigationActionName.EXIT, eventHandler); controller.addEventListener(expenses + ":" + NavigationActionName.ENTER, eventHandler); controller.registerDestination( timetracking ); controller.addEventListener( timetracking + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.addEventListener(expenses + ":" + NavigationActionName.ENTER, eventHandler); controller.navigateTo( expenses ); controller.navigateTo( timetracking ); assertThat("eventHandlerCalled", eventHandlerCalled); assertThat("calls", eventHandlerCalls, equalTo(1)); } [Test] public function whenChildExitThenTriggerChildFirst() : void { //exit destinations in reverse order controller.registerDestination( expenses ); controller.addEventListener(expenses + ":" + NavigationActionName.EXIT, eventHandler); controller.registerDestination( tasks ); controller.addEventListener(tasks + ":" + NavigationActionName.EXIT, eventHandler); controller.registerDestination( content ); controller.addEventListener(content + ":" + NavigationActionName.EXIT, eventHandler); controller.registerDestination( news ); controller.addEventListener(news + ":" + NavigationActionName.FIRST_ENTER, eventHandler); controller.navigateTo( expenses ); controller.navigateTo( news ); assertThat("eventHandlerCalled", eventHandlerCalled); assertThat("calls", eventHandlerCalls, equalTo(3)); } [Test] public function whenNavigateToUnkownDestinationThenExit() : void { controller.registerDestination( tasks ); controller.addEventListener( tasks + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.registerDestination( news ); controller.addEventListener(news + ":" + NavigationActionName.EXIT, eventHandler); controller.navigateTo( news ); controller.navigateTo( expenses ); assertThat("eventHandlerCalled", eventHandlerCalled); } [Test] public function whenNavigateToUnkownDestinationWith2NestLevelsThenExit() : void { controller.registerDestination( tasks ); controller.addEventListener( tasks + ":" + NavigationActionName.FIRST_ENTER , dummyHandler ); controller.registerDestination( news ); controller.addEventListener(news + ":" + NavigationActionName.EXIT, eventHandler); controller.navigateTo( news ); controller.navigateTo( privateexpenses ); assertThat("eventHandlerCalled", eventHandlerCalled); } [Test] public function shouldNavigateBackAndFourth() : void { controller.registerDestination( news ); controller.addEventListener(news + ":" + NavigationActionName.ENTER, eventHandler); controller.addEventListener(news + ":" + NavigationActionName.ENTER, eventHandler); controller.registerDestination( expenses ); controller.addEventListener( expenses + ":" + NavigationActionName.ENTER , dummyHandler ); controller.navigateTo( news ); controller.navigateTo( expenses ); controller.navigateTo( news ); controller.navigateTo( expenses ); controller.navigateTo( news ); assertThat("eventHandlerCalled", eventHandlerCalled); assertThat("calls", eventHandlerCalls, equalTo(2)); } private function dummyHandler( event : Event ) : void { } } }
package game.view.card { import com.pickgliss.ui.ComponentFactory; import com.pickgliss.ui.core.Disposeable; import ddt.manager.SoundManager; import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Sprite; import flash.events.Event; import flash.events.TimerEvent; import flash.utils.Timer; public class CardCountDown extends Sprite implements Disposeable { private var _bitmapDatas:Vector.<BitmapData>; private var _timer:Timer; private var _totalSeconds:uint; private var _digit:Bitmap; private var _tenDigit:Bitmap; private var _isPlaySound:Boolean; public function CardCountDown() { super(); this.init(); } public function tick(param1:uint, param2:Boolean = true) : void { this._totalSeconds = param1; this._isPlaySound = param2; this._timer.repeatCount = this._totalSeconds; this.__updateView(); this._timer.start(); } private function init() : void { this._digit = new Bitmap(); this._tenDigit = new Bitmap(); this._bitmapDatas = new Vector.<BitmapData>(); this._timer = new Timer(1000); this._timer.addEventListener(TimerEvent.TIMER,this.__updateView); this._timer.addEventListener(TimerEvent.TIMER_COMPLETE,this.__onTimerComplete); var _loc1_:int = 0; while(_loc1_ < 10) { this._bitmapDatas.push(ComponentFactory.Instance.creatBitmapData("asset.takeoutCard.CountDownNum_" + String(_loc1_))); _loc1_++; } } private function __updateView(param1:TimerEvent = null) : void { var _loc2_:int = this._timer.repeatCount - this._timer.currentCount; if(_loc2_ <= 4) { if(this._isPlaySound) { SoundManager.instance.stop("067"); SoundManager.instance.play("067"); } } else if(this._isPlaySound) { SoundManager.instance.play("014"); } this._tenDigit.bitmapData = this._bitmapDatas[int(_loc2_ / 10)]; this._digit.bitmapData = this._bitmapDatas[_loc2_ % 10]; this._digit.x = this._tenDigit.width - 14; addChild(this._digit); addChild(this._tenDigit); } private function __onTimerComplete(param1:TimerEvent) : void { dispatchEvent(new Event(Event.COMPLETE)); } public function dispose() : void { var _loc1_:BitmapData = null; this._timer.removeEventListener(TimerEvent.TIMER,this.__updateView); this._timer.removeEventListener(TimerEvent.TIMER_COMPLETE,this.__onTimerComplete); this._timer.stop(); this._timer = null; for each(_loc1_ in this._bitmapDatas) { _loc1_.dispose(); _loc1_ = null; } if(this._digit && this._digit.parent) { this._digit.parent.removeChild(this._digit); } if(this._tenDigit && this._tenDigit.parent) { this._tenDigit.parent.removeChild(this._tenDigit); } this._digit = null; this._tenDigit = null; if(this.parent) { parent.removeChild(this); } } } }
/* * Copyright 2010 the original author or authors. * * 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.spicefactory.parsley.core.builder.impl { import org.spicefactory.lib.errors.IllegalArgumentError; import org.spicefactory.lib.reflect.FunctionBase; import org.spicefactory.lib.reflect.Parameter; import org.spicefactory.parsley.core.builder.ImplicitTypeReference; import org.spicefactory.parsley.core.builder.ref.ObjectTypeReference; /** * Utility class for resolving parameters of constructors and methods. * * @author Jens Halm */ public class ParameterBuilder { /** * Returns the parameters to be passed to the specified constructor or method * based on the (potentially) unresolved values passed with the second argument. * If the target method expects one or more parameters but the specified * value array is empty the default behavior * is to assume injection by type for all parameters. Otherwise the value * will get processed and any implicit type reference found in the array * gets notified of the required target type. * * @param target the target (method or constructor) to process the parameters for * @param values the potentially unresolved or empty Array of parameters * @return the parameters as they should be applied to the target */ public static function processParameters (target: FunctionBase, values: Array) : Array { if (values.length == 0) { return getTypeReferences(target); } resolveImplicitTypeReferences(target, values); validateParameterCount(target, values.length); return values; } private static function getTypeReferences (target: FunctionBase) : Array { var params:Array = target.parameters; var refs:Array = new Array(); for each (var param:Parameter in params) { refs.push(new ObjectTypeReference(param.type.getClass(), param.required)); } return refs; } private static function resolveImplicitTypeReferences (target: FunctionBase, values: Array) : void { var params: Array = target.parameters; for (var i:int = 0; i < values.length; i++) { var value: Object = values[i]; if (value is ImplicitTypeReference) { var param: Parameter = (i < params.length) ? params[i] : null; if (!param) { throw new IllegalArgumentError("Cannot resolve implicit type reference for parameter at index" + i + " of " + target); } ImplicitTypeReference(value).expectedType(param.type.getClass()); } } } private static function validateParameterCount (target: FunctionBase, count: uint): void { if (target.parameters.length > count) { var firstMissing: Parameter = target.parameters[count]; if (firstMissing.required) { throw new IllegalArgumentError("Less values than the number of required parameters were provided for " + target); } } // we cannot reflect on rest parameters, so we ignore the case when we get more parameters than expected } } }
package PathFinding.core { /** * ... * @author dongketao */ public class Grid { public var width:int; public var height:int; public var nodes:Array; /** * The Grid class, which serves as the encapsulation of the layout of the nodes. * @constructor * @param {number|Array<Array<(number|boolean)>>} width_or_matrix Number of columns of the grid, or matrix * @param {number} height Number of rows of the grid. * @param {Array<Array<(number|boolean)>>} [matrix] - A 0-1 matrix * representing the walkable status of the nodes(0 or false for walkable). * If the matrix is not supplied, all the nodes will be walkable. */ public function Grid(width_or_matrix:*, height:int, matrix:Array = null) { var width:int; if (width_or_matrix is Number) { width = width_or_matrix; } else { height = width_or_matrix.length; width = width_or_matrix[0].length; matrix = width_or_matrix; } /** * The number of columns of the grid. * @type number */ this.width = width; /** * The number of rows of the grid. * @type number */ this.height = height; /** * A 2D array of nodes. */ this.nodes = this._buildNodes(width, height, matrix); } ///** //* 从图片生成AStar图。 //* @param texture AStar图资源。 //*/ //public static function createGridFromAStarMap(texture:Texture2D):Grid{ //var textureWidth:Number = texture.width; //var textureHeight:Number = texture.height; // //var pixelsInfo:Uint8Array = texture.getPixels(); //var aStarArr:Array = new Array(); //var index:int = 0; // //for (var w:int = 0; w < textureWidth; w++ ){ // //var colaStarArr:Array = aStarArr[w] = []; //for (var h:int = 0; h < textureHeight; h++ ){ // //var r:Number = pixelsInfo[index++]; //var g:Number = pixelsInfo[index++]; //var b:Number = pixelsInfo[index++]; //var a:Number = pixelsInfo[index++]; // //if (r == 255 && g == 255 && b == 255 && a == 255) //colaStarArr[h] = 1; //else { //colaStarArr[h] = 0; //} //} //} // //var gird:Grid = new Grid(textureWidth, textureHeight, aStarArr); //return gird; //} /** * Build and return the nodes. * @private * @param {number} width * @param {number} height * @param {Array<Array<number|boolean>>} [matrix] - A 0-1 matrix representing * the walkable status of the nodes. * @see Grid */ public function _buildNodes(width:int, height:int, matrix:Array = null):Array { var i:int, j:int, nodes:Array = new Array(); for (i = 0; i < height; ++i) { nodes[i] = new Array(); for (j = 0; j < width; ++j) { nodes[i][j] = new Node(j, i); } } if (matrix == null) { return nodes; } if (matrix.length != height || matrix[0].length != width) { throw new Error('Matrix size does not fit'); } for (i = 0; i < height; ++i) { for (j = 0; j < width; ++j) { if (matrix[i][j]) { // 0, false, null will be walkable // while others will be un-walkable nodes[i][j].walkable = false; } } } return nodes; } public function getNodeAt(x:int, y:int):Node { return this.nodes[y][x]; } /** * Determine whether the node at the given position is walkable. * (Also returns false if the position is outside the grid.) * @param {number} x - The x coordinate of the node. * @param {number} y - The y coordinate of the node. * @return {boolean} - The walkability of the node. */ public function isWalkableAt(x:int, y:int):Boolean { return this.isInside(x, y) && this.nodes[y][x].walkable; } /** * Determine whether the position is inside the grid. * XXX: `grid.isInside(x, y)` is wierd to read. * It should be `(x, y) is inside grid`, but I failed to find a better * name for this method. * @param {number} x * @param {number} y * @return {boolean} */ public function isInside(x:int, y:int):Boolean { return (x >= 0 && x < this.width) && (y >= 0 && y < this.height); } /** * Set whether the node on the given position is walkable. * NOTE: throws exception if the coordinate is not inside the grid. * @param {number} x - The x coordinate of the node. * @param {number} y - The y coordinate of the node. * @param {boolean} walkable - Whether the position is walkable. */ public function setWalkableAt(x:int, y:int, walkable:Boolean):void { this.nodes[y][x].walkable = walkable; } /** * Get the neighbors of the given node. * * offsets diagonalOffsets: * +---+---+---+ +---+---+---+ * | | 0 | | | 0 | | 1 | * +---+---+---+ +---+---+---+ * | 3 | | 1 | | | | | * +---+---+---+ +---+---+---+ * | | 2 | | | 3 | | 2 | * +---+---+---+ +---+---+---+ * * When allowDiagonal is true, if offsets[i] is valid, then * diagonalOffsets[i] and * diagonalOffsets[(i + 1) % 4] is valid. * @param {Node} node * @param {diagonalMovement} diagonalMovement */ public function getNeighbors(node:Node, diagonalMovement:int):Array { var x:int = node.x, y:int = node.y, neighbors:Array = [], s0:Boolean = false, d0:Boolean = false, s1:Boolean = false, d1:Boolean = false, s2:Boolean = false, d2:Boolean = false, s3:Boolean = false, d3:Boolean = false, nodes:Array = this.nodes; // ↑ if (this.isWalkableAt(x, y - 1)) { neighbors.push(nodes[y - 1][x]); s0 = true; } // → if (this.isWalkableAt(x + 1, y)) { neighbors.push(nodes[y][x + 1]); s1 = true; } // ↓ if (this.isWalkableAt(x, y + 1)) { neighbors.push(nodes[y + 1][x]); s2 = true; } // ← if (this.isWalkableAt(x - 1, y)) { neighbors.push(nodes[y][x - 1]); s3 = true; } if (diagonalMovement == DiagonalMovement.Never) { return neighbors; } if (diagonalMovement == DiagonalMovement.OnlyWhenNoObstacles) { d0 = s3 && s0; d1 = s0 && s1; d2 = s1 && s2; d3 = s2 && s3; } else if (diagonalMovement == DiagonalMovement.IfAtMostOneObstacle) { d0 = s3 || s0; d1 = s0 || s1; d2 = s1 || s2; d3 = s2 || s3; } else if (diagonalMovement == DiagonalMovement.Always) { d0 = true; d1 = true; d2 = true; d3 = true; } else { throw new Error('Incorrect value of diagonalMovement'); } // ↖ if (d0 && this.isWalkableAt(x - 1, y - 1)) { neighbors.push(nodes[y - 1][x - 1]); } // ↗ if (d1 && this.isWalkableAt(x + 1, y - 1)) { neighbors.push(nodes[y - 1][x + 1]); } // ↘ if (d2 && this.isWalkableAt(x + 1, y + 1)) { neighbors.push(nodes[y + 1][x + 1]); } // ↙ if (d3 && this.isWalkableAt(x - 1, y + 1)) { neighbors.push(nodes[y + 1][x - 1]); } return neighbors; //if (!allowDiagonal) { //return neighbors; //} //if (dontCrossCorners) { //d0 = s3 && s0; //d1 = s0 && s1; //d2 = s1 && s2; //d3 = s2 && s3; //} //else { //d0 = s3 || s0; //d1 = s0 || s1; //d2 = s1 || s2; //d3 = s2 || s3; //} //if (d0 && this.isWalkableAt(x - 1, y - 1)) //{ //neighbors.push(nodes[y - 1][x - 1]); //} //// ↗ //if (d1 && this.isWalkableAt(x + 1, y - 1)) //{ //neighbors.push(nodes[y - 1][x + 1]); //} //// ↘ //if (d2 && this.isWalkableAt(x + 1, y + 1)) //{ //neighbors.push(nodes[y + 1][x + 1]); //} //// ↙ //if (d3 && this.isWalkableAt(x - 1, y + 1)) //{ //neighbors.push(nodes[y + 1][x - 1]); //} //return neighbors; } /** * Get a clone of this grid. * @return {Grid} Cloned grid. */ public function clone():Grid { var i:int, j:int, width:int = this.width, height:int = this.height, thisNodes:Array = this.nodes, newGrid:Grid = new Grid(width, height), newNodes:Array = new Array(); for (i = 0; i < height; ++i) { newNodes[i] = new Array(); for (j = 0; j < width; ++j) { newNodes[i][j] = new Node(j, i, thisNodes[i][j].walkable); } } newGrid.nodes = newNodes; return newGrid; } public function reset():void{ var _node:Node; for (var i:Number = 0; i < height; ++i) { for (var j:Number = 0; j < width; ++j) { _node = this.nodes[i][j]; _node.g = 0; _node.f = 0; _node.h = 0; _node.by = 0; _node.parent = null; _node.opened = null; _node.closed = null; _node.tested = null; } } } } }
/* Copyright (c) 2008 NascomASLib Contributors. See: http://code.google.com/p/nascomaslib 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 gfx { import flash.display.BitmapData; import flash.display.BitmapDataChannel; import flash.display.BlendMode; import flash.display.DisplayObject; import flash.events.Event; import flash.filters.ConvolutionFilter; import flash.filters.DisplacementMapFilter; import flash.geom.ColorTransform; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; /** * * The Rippler class creates an effect of rippling water on a source DisplayObject. * * @example The following code takes a DisplayObject on the stage and adds a ripple to it, assuming source is a DisplayObject already on the stage. * * <listing version="3.0"> * import be.nascom.flash.graphics.Rippler; * * // create a Rippler instance to impact source, with a strength of 60 and a scale of 6. * // The source can be any DisplayObject on the stage, such as a Bitmap or MovieClip object. * var rippler : Rippler = new Rippler(source, 60, 6); * * // create a ripple with size 20 and alpha 1 with origin on position (200, 50) * rippler.drawRipple(100, 50, 20, 1); * </listing> * * @author David Lenaerts * @mail david.lenaerts@nascom.be * */ public class Rippler { // The DisplayObject which the ripples will affect. private var _source : DisplayObject; // Two buffers on which the ripple displacement image will be created, and swapped. // Depending on the scale parameter, this will be smaller than the source private var _buffer1 : BitmapData; private var _buffer2 : BitmapData; // The final bitmapdata containing the upscaled ripple image, to match the source DisplayObject private var _defData : BitmapData; // Rectangle and Point objects created once and reused for performance private var _fullRect : Rectangle; // A buffer-sized Rectangle used to apply filters to the buffer private var _drawRect : Rectangle; // A Rectangle used when drawing a ripple private var _origin : Point = new Point(); // A Point object to (0, 0) used for the DisplacementMapFilter as well as for filters on the buffer // The DisplacementMapFilter applied to the source DisplayObject private var _filter : DisplacementMapFilter; // A filter causing the ripples to grow private var _expandFilter : ConvolutionFilter; // Creates a colour offset to 0x7f7f7f so there is no image offset due to the DisplacementMapFilter private var _colourTransform : ColorTransform; // Used to scale up the buffer to the final source DisplayObject's scale private var _matrix : Matrix; // We only need 1/scale, so we keep it here private var _scaleInv : Number; /** * Creates a Rippler instance. * * @param source The DisplayObject which the ripples will affect. * @param strength The strength of the ripple displacements. * @param scale The size of the ripples. In reality, the scale defines the size of the ripple displacement map (map.width = source.width/scale). Higher values are therefor also potentially faster. * */ public function Rippler(source : DisplayObject, strength : Number, scale : Number = 2) { var correctedScaleX : Number; var correctedScaleY : Number; _source = source; _scaleInv = 1/scale; // create the (downscaled) buffers and final (upscaled) image data, sizes depend on scale _buffer1 = new BitmapData(source.width*_scaleInv, source.height*_scaleInv, false, 0x000000); _buffer2 = new BitmapData(_buffer1.width, _buffer1.height, false, 0x000000); _defData = new BitmapData(source.width, source.height, false, 0x7f7f7f); // Recalculate scale between the buffers and the final upscaled image to prevent roundoff errors. correctedScaleX = _defData.width/_buffer1.width; correctedScaleY = _defData.height/_buffer1.height; // Create reusable objects _fullRect = new Rectangle(0, 0, _buffer1.width, _buffer1.height); _drawRect = new Rectangle(); // Create the DisplacementMapFilter and assign it to the source _filter = new DisplacementMapFilter(_defData, _origin, BitmapDataChannel.BLUE, BitmapDataChannel.BLUE, strength, strength, "wrap"); _source.filters = [_filter]; // Create a frame-based loop to update the ripples _source.addEventListener(Event.ENTER_FRAME, handleEnterFrame); // Create the filter that causes the ripples to grow. // Depending on the colour of its neighbours, the pixel will be turned white _expandFilter = new ConvolutionFilter(3, 3, [0.5, 1, 0.5, 1, 0, 1, 0.5, 1, 0.5], 3); // Create the colour transformation based on _colourTransform = new ColorTransform(1, 1, 1, 1, 128, 128, 128); // Create the Matrix object _matrix = new Matrix(correctedScaleX, 0, 0, correctedScaleY); } /** * Initiates a ripple at a position of the source DisplayObject. * * @param x The horizontal coordinate of the ripple origin. * @param y The vertical coordinate of the ripple origin. * @param size The size of the ripple diameter on first impact. * @param alpha The alpha value of the ripple on first impact. */ public function drawRipple(x : int, y : int, size : int, alpha : Number) : void { var half : int = size >> 1; // We need half the size of the ripple var intensity : int = (alpha*0xff & 0xff)*alpha; // The colour which will be drawn in the currently active buffer // calculate and draw the rectangle, having (x, y) in its centre _drawRect.x = (-half+x)*_scaleInv; _drawRect.y = (-half+y)*_scaleInv; _drawRect.width = _drawRect.height = size*_scaleInv; _buffer1.fillRect(_drawRect, intensity); } /** * Returns the actual ripple image. */ public function getRippleImage() : BitmapData { return _defData; } /** * Removes all memory occupied by this instance. This method must be called before discarding an instance. */ public function destroy() : void { _source.removeEventListener(Event.ENTER_FRAME, handleEnterFrame); _buffer1.dispose(); _buffer2.dispose(); _defData.dispose(); } // the actual loop where the ripples are animated private function handleEnterFrame(event : Event) : void { // a temporary clone of buffer 2 var temp : BitmapData = _buffer2.clone(); // buffer2 will contain an expanded version of buffer1 _buffer2.applyFilter(_buffer1, _fullRect, _origin, _expandFilter); // by substracting buffer2's old image, buffer2 will now be a ring _buffer2.draw(temp, null, null, BlendMode.SUBTRACT, null, false); // scale up and draw to the final displacement map, and apply it to the filter _defData.draw(_buffer2, _matrix, _colourTransform, null, null, true); _filter.mapBitmap = _defData; _source.filters = [_filter]; temp.dispose(); // switch buffers 1 and 2 switchBuffers(); } // switch buffer 1 and 2, so that private function switchBuffers() : void { var temp : BitmapData; temp = _buffer1; _buffer1 = _buffer2; _buffer2 = temp; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.filters { //import flash.filters.ColorMatrixFilter; import mx.filters.BaseFilter; import mx.filters.IBitmapFilter; /** * The ColorMatrixFilter class lets you apply a 4 x 5 matrix transformation on the * RGBA color and alpha values of every pixel in the input image to produce a result * with a new set of RGBA color and alpha values. It allows saturation changes, hue * rotation, luminance to alpha, and various other effects. You can apply the filter * to any display object (that is, objects that inherit from the DisplayObject class), * such as MovieClip, SimpleButton, TextField, and Video objects, as well as to * BitmapData objects. * * @mxml * <p>The <code>&lt;s:ColorMatrixFilter&gt;</code> tag inherits all of the tag * attributes of its superclass and adds the following tag attributes:</p> * * <pre> * &lt;s:ColorMatrixFilter * <strong>Properties</strong> * matrix="[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]" * /&gt; * </pre> * * @see flash.filters.ColorMatrixFilter * * @includeExample examples/ColorMatrixFilterExample.mxml * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public class ColorMatrixFilter extends BaseFilter implements IBitmapFilter { /** * Constructor. * * @tiptext Initializes a new ColorMatrixFilter instance. * * @param matrix An array of 20 items arranged as a 4 x 5 matrix. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function ColorMatrixFilter(matrix:Array = null) { super(); if (matrix != null) { this.matrix = matrix; } } //---------------------------------- // matrix //---------------------------------- private var _matrix:Array = [1,0,0,0,0,0, 1,0,0,0,0,0, 1,0,0,0,0,0, 1,0]; /** * A comma delimited list of 20 doubles that comprise a 4x5 matrix applied to the * rendered element. The matrix is in row major order -- that is, the first five * elements are multipled by the vector [srcR,srcG,srcB,srcA,1] to determine the * output red value, the second five determine the output green value, etc. * * <p>The value must either be an array or comma delimited string of 20 numbers. </p> * * @default [1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0] * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get matrix():Object { return _matrix; } public function set matrix(value:Object):void { if (value != _matrix) { if (value is Array) { _matrix = value as Array; } else if (value is String) { _matrix = String(value).split(','); } notifyFilterChanged(); } } /** * Returns a copy of this filter object. * * @return A new ColorMatrixFilter instance with all of the same * properties as the original one. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function clone():Object { //return new flash.filters.ColorMatrixFilter(_matrix); return null; } } }
package demo.SimpleSite.ui { import org.asaplibrary.ui.buttons.*; import flash.display.MovieClip; public class SimpleButton extends MovieClip { protected var mDelegate : ButtonBehavior; function SimpleButton() { super(); mDelegate = new ButtonBehavior(this); mDelegate.addEventListener(ButtonBehaviorEvent._EVENT, update); drawUpState(); } private function update(e : ButtonBehaviorEvent) : void { switch (e.state) { case ButtonStates.SELECTED: drawSelectedState(); break; case ButtonStates.OVER: drawOverState(); break; case ButtonStates.NORMAL: case ButtonStates.OUT: case ButtonStates.DESELECTED: drawUpState(); default: break; } buttonMode = !e.selected; } private function drawUpState() : void { gotoAndStop("up"); } private function drawOverState() : void { gotoAndStop("over"); } private function drawSelectedState() : void { gotoAndStop("selected"); } } }
/* * * This file is part of the OpenKinect Project. http://www.openkinect.org * * Copyright (c) 2010 individual OpenKinect contributors. See the CONTRIB file * for details. * * This code is licensed to you under the terms of the Apache License, version * 2.0, or, at your option, the terms of the GNU General Public License, * version 2.0. See the APACHE20 and GPL20 files for the text of the licenses, * or the following URLs: * http://www.apache.org/licenses/LICENSE-2.0 * http://www.gnu.org/licenses/gpl-2.0.txt * * If you redistribute this file in source form, modified or unmodified, * you may: * 1) Leave this header intact and distribute it under the same terms, * accompanying it with the APACHE20 and GPL20 files, or * 2) Delete the Apache 2.0 clause and accompany it with the GPL20 file, or * 3) Delete the GPL v2.0 clause and accompany it with the APACHE20 file * In all cases you must keep the copyright notice intact and include a copy * of the CONTRIB file. * Binary distributions must follow the binary distribution requirements of * either License. * */ package org.libfreenect.events { import flash.events.Event; public class libfreenectDataEvent extends Event { public static const DATA_RECEIVED:String = "DATA_RECEIVED"; public var data:*; public function libfreenectDataEvent(type:String, data:*) { this.data = data; super(type); } } }
/* * ______ _____ _______ * .-----..--.--..----..-----.| __ \ \| ___| * | _ || | || _|| -__|| __/ -- | ___| * | __||_____||__| |_____||___| |_____/|___| * |__| * $Id: IElementListener.as 238 2010-01-31 10:49:33Z alessandro.crugnola $ * $Author Alessandro Crugnola $ * $Rev: 238 $ $LastChangedDate: 2010-01-31 05:49:33 -0500 (Sun, 31 Jan 2010) $ * $URL: http://purepdf.googlecode.com/svn/trunk/src/org/purepdf/elements/IElementListener.as $ * * The contents of this file are subject to LGPL license * (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the * provisions of LGPL are applicable instead of those above. If you wish to * allow use of your version of this file only under the terms of the LGPL * License and not to allow others to use your version of this file under * the MPL, indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by the LGPL. * If you do not delete the provisions above, a recipient may use your version * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE * * 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 'iText, a free JAVA-PDF library' ( version 4.2 ) by Bruno Lowagie. * All the Actionscript ported code and all the modifications to the * original java library are written by Alessandro Crugnola (alessandro@sephiroth.it) * * This library is free software; you can redistribute it and/or modify it * under the terms of the MPL as stated above or under the terms of the GNU * Library General Public License as published by the Free Software Foundation; * either version 2 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU LIBRARY GENERAL PUBLIC LICENSE for more * details * * If you didn't download this code from the following link, you should check if * you aren't using an obsolete version: * http://code.google.com/p/purepdf * */ package org.purepdf.elements { public interface IElementListener { function addElement( element: IElement ): Boolean; } }
package common { import game.proto.game_update; import game.net.NetClient; import laya.utils.Utils; import laya.net.LocalStorage; public class GameFunctions{ public static var ownerList_play:Function = null; public static var ownerList_delCell:Function = null; public static var ownerList_prompt:Function = null; public static var ownerList_playPrompt:Function = null; public static var surface_updateCounter:Function = null; public static var control_callLord:Function = null; public static var control_markPlay:Function = null; public static var control_forcePlay:Function = null; public static var control_markStart:Function = null; public static var clock_start:Function = null; public static function send_game_update(cmd:int, msg:*=null):void { var data:Object = new Object(); data.cmd = cmd; data.msg = msg; var sendMsg:game_update = new game_update(); sendMsg.data = JSON.stringify(data); NetClient.send("game_update", sendMsg); } public static function getAccount():String { var gameAccount:String = LocalStorage.getItem("gameAccount"); if(gameAccount == null) { var nameArray:Array = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] var arrayLen:int = nameArray.length; var name:String = ""; for(var i:int = 0; i < 10; i++) { var idx:int = Math.floor(Math.random() * (arrayLen + 1)) % arrayLen; name += nameArray[idx]; } var guid:Number = Utils.getGID(); gameAccount = name + guid LocalStorage.setItem("gameAccount", gameAccount); } return gameAccount; } } }
/* Copyright (c) 2006-2013 Regents of the University of Minnesota. For licensing terms, see the file LICENSE. */ package grax { import utils.misc.Logging; m4_ASSERT(false); // FIXME Remove this class? public class New_Item_Policy_User { // *** Class attributes protected static var log:Logging = Logging.get_logger('GRC/NIP_Usr'); // *** Constructor public function New_Item_Policy_User() { // no-op } } }
package kabam.rotmg.account.web { import com.company.assembleegameclient.parameters.Parameters; import com.company.assembleegameclient.util.GUID; import flash.external.ExternalInterface; import flash.net.SharedObject; import kabam.rotmg.account.core.Account; public class WebAccount implements Account { public static const NETWORK_NAME:String = "rotmg"; private static const WEB_USER_ID:String = ""; private static const WEB_PLAY_PLATFORM_NAME:String = "rotmg"; private var userId:String = ""; private var password:String; private var token:String = ""; private var entryTag:String = ""; private var isVerifiedEmail:Boolean; private var platformToken:String; private var _userDisplayName:String = ""; private var _rememberMe:Boolean = true; private var _paymentProvider:String = ""; private var _paymentData:String = ""; public var signedRequest:String; public var kabamId:String; public function WebAccount() { try { this.entryTag = ExternalInterface.call("rotmg.UrlLib.getParam", "entrypt"); } catch (error:Error) { } } public function getUserName():String { return (this.userId); } public function getUserId():String { return ((this.userId = ((this.userId) || (GUID.create())))); } public function getPassword():String { return (((this.password) || (""))); } public function getToken():String { return (""); } public function getCredentials():Object { return ({ "guid": this.getUserId(), "password": this.getPassword() }); } public function isRegistered():Boolean { return (((!((this.getPassword() == ""))) || (!((this.getToken() == ""))))); } public function updateUser(_arg1:String, _arg2:String, _arg3:String):void { var _local4:SharedObject; this.userId = _arg1; this.password = _arg2; this.token = _arg3; try { if (this._rememberMe) { _local4 = SharedObject.getLocal("LoEV4AGCOptions", "/"); _local4.data["GUID"] = _arg1; _local4.data["Token"] = _arg3; _local4.data["Password"] = _arg2; _local4.flush(); } } catch (error:Error) { } } public function clear():void { this._rememberMe = true; this.updateUser(GUID.create(), null, null); Parameters.sendLogin_ = true; Parameters.data_.charIdUseMap = {}; Parameters.save(); } public function reportIntStat(_arg1:String, _arg2:int):void { } public function getRequestPrefix():String { return ("/credits"); } public function gameNetworkUserId():String { return (WEB_USER_ID); } public function gameNetwork():String { return (NETWORK_NAME); } public function playPlatform():String { return (WEB_PLAY_PLATFORM_NAME); } public function getEntryTag():String { return (((this.entryTag) || (""))); } public function getSecret():String { return (""); } public function verify(_arg1:Boolean):void { this.isVerifiedEmail = _arg1; } public function isVerified():Boolean { return (this.isVerifiedEmail); } public function getPlatformToken():String { return (((this.platformToken) || (""))); } public function setPlatformToken(_arg1:String):void { this.platformToken = _arg1; } public function getMoneyAccessToken():String { return (this.signedRequest); } public function getMoneyUserId():String { return (this.kabamId); } public function get userDisplayName():String { return (this._userDisplayName); } public function set userDisplayName(_arg1:String):void { this._userDisplayName = _arg1; } public function set rememberMe(_arg1:Boolean):void { this._rememberMe = _arg1; } public function get rememberMe():Boolean { return (this._rememberMe); } public function set paymentProvider(_arg1:String) { this._paymentProvider = _arg1; } public function get paymentProvider():String { return (this._paymentProvider); } public function set paymentData(_arg1:String) { this._paymentData = _arg1; } public function get paymentData():String { return (this._paymentData); } } }
package { import Shared.AS3.BSButtonHint; import Shared.AS3.BSButtonHintData; import Shared.GlobalFunc; import Shared.IMenu; import flash.display.MovieClip; public class MultiActivateMenu extends IMenu { public var FadeHolder_mc:MovieClip; public var BGSCodeObj:Object; private var Buttons:Vector.<BSButtonHint>; private var ButtonAnimators:Vector.<MovieClip>; private var ButtonData:Vector.<BSButtonHintData>; private var ABtnData:BSButtonHintData; private var BBtnData:BSButtonHintData; private var XBtnData:BSButtonHintData; private var YBtnData:BSButtonHintData; public function MultiActivateMenu() { this.ABtnData = new BSButtonHintData("","Down","PSN_A","Xenon_A",1,this.onARelease); this.BBtnData = new BSButtonHintData("","Right","PSN_B","Xenon_B",1,this.onBRelease); this.XBtnData = new BSButtonHintData("","Left","PSN_X","Xenon_X",0,this.onXRelease); this.YBtnData = new BSButtonHintData("","Up","PSN_Y","Xenon_Y",0,this.onYRelease); super(); this.visible = false; this.BGSCodeObj = new Object(); this.Buttons = new Vector.<BSButtonHint>(); this.Buttons.push(this.FadeHolder_mc.A.Holder.Button_mc); this.Buttons.push(this.FadeHolder_mc.B.Holder.Button_mc); this.Buttons.push(this.FadeHolder_mc.X.Holder.Button_mc); this.Buttons.push(this.FadeHolder_mc.Y.Holder.Button_mc); this.ButtonAnimators = new Vector.<MovieClip>(); this.ButtonAnimators.push(this.FadeHolder_mc.A); this.ButtonAnimators.push(this.FadeHolder_mc.B); this.ButtonAnimators.push(this.FadeHolder_mc.X); this.ButtonAnimators.push(this.FadeHolder_mc.Y); this.ButtonData = new Vector.<BSButtonHintData>(); this.ButtonData.push(this.ABtnData); this.ButtonData.push(this.BBtnData); this.ButtonData.push(this.XBtnData); this.ButtonData.push(this.YBtnData); } override protected function onSetSafeRect() : void { GlobalFunc.LockToSafeRect(this,"BC",SafeX,SafeY); } public function onCodeObjCreate() : * { this.BGSCodeObj.registerObjects(this.FadeHolder_mc.A,this.FadeHolder_mc.B,this.FadeHolder_mc.X,this.FadeHolder_mc.Y); var _loc1_:uint = 0; while(_loc1_ < this.Buttons.length) { this.Buttons[_loc1_].ButtonHintData = this.ButtonData[_loc1_]; _loc1_++; } } public function SetButtonData(param1:uint, param2:String, param3:Boolean) : * { var _loc4_:Number = NaN; this.ButtonData[param1].ButtonText = param2.toUpperCase(); this.ButtonData[param1].ButtonDisabled = !param3; if(!this.visible && param1 == 3) { _loc4_ = 0; while(_loc4_ < this.Buttons.length) { this.Buttons[_loc4_].bButtonPressed = false; this.ButtonAnimators[_loc4_].gotoAndPlay("showButton"); _loc4_++; } this.visible = true; } } private function onAPress() : * { this.onButtonPress(0); } private function onBPress() : * { this.onButtonPress(1); } private function onXPress() : * { this.onButtonPress(2); } private function onYPress() : * { this.onButtonPress(3); } private function onARelease() : * { this.onButtonRelease(0); } private function onBRelease() : * { this.onButtonRelease(1); } private function onXRelease() : * { this.onButtonRelease(2); } private function onYRelease() : * { this.onButtonRelease(3); } public function ProcessUserEvent(param1:String, param2:Boolean) : Boolean { var _loc3_:Boolean = true; if(param2) { if(param1 == "MultiActivateA") { this.onAPress(); } else if(param1 == "MultiActivateB") { this.onBPress(); } else if(param1 == "MultiActivateX") { this.onXPress(); } else if(param1 == "MultiActivateY") { this.onYPress(); } else { _loc3_ = false; } } else if(param1 == "MultiActivateA") { this.onARelease(); } else if(param1 == "MultiActivateB") { this.onBRelease(); } else if(param1 == "MultiActivateX") { this.onXRelease(); } else if(param1 == "MultiActivateY") { this.onYRelease(); } else { _loc3_ = false; } return _loc3_; } private function onButtonPress(param1:uint) : * { if(param1 < this.Buttons.length) { this.Buttons[param1].bButtonPressed = true; } } private function onButtonRelease(param1:uint) : * { if(param1 < this.Buttons.length) { this.Buttons[param1].bButtonPressed = false; this.BGSCodeObj.onButtonRelease(param1); } } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.controls { import flash.display.DisplayObject; import flash.events.Event; import flash.events.FocusEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.ui.Keyboard; import flash.utils.getTimer; import mx.controls.colorPickerClasses.SwatchPanel; import mx.controls.colorPickerClasses.WebSafePalette; import mx.core.LayoutDirection; import mx.core.UIComponent; import mx.core.UIComponentGlobals; import mx.core.mx_internal; import mx.effects.Tween; import mx.events.ColorPickerEvent; import mx.events.DropdownEvent; import mx.events.FlexEvent; import mx.events.FlexMouseEvent; import mx.events.InterManagerRequest; import mx.events.SandboxMouseEvent; import mx.managers.IFocusManager; import mx.managers.ISystemManager; import mx.managers.PopUpManager; import mx.managers.SystemManager; import mx.skins.halo.SwatchSkin; import mx.styles.StyleProxy; use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched when the selected color * changes as a result of user interaction. * * @eventType mx.events.ColorPickerEvent.CHANGE * @helpid 4918 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name="change", type="mx.events.ColorPickerEvent")] /** * Dispatched when the swatch panel closes. * * @eventType mx.events.DropdownEvent.CLOSE * @helpid 4921 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name="close", type="mx.events.DropdownEvent")] /** * Dispatched if the ColorPicker <code>editable</code> * property is set to <code>true</code> * and the user presses Enter after typing in a hexadecimal color value. * * @eventType mx.events.ColorPickerEvent.ENTER * @helpid 4919 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name="enter", type="mx.events.ColorPickerEvent")] /** * Dispatched when the user rolls the mouse out of a swatch * in the SwatchPanel object. * * @eventType mx.events.ColorPickerEvent.ITEM_ROLL_OUT * @helpid 4924 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name="itemRollOut", type="mx.events.ColorPickerEvent")] /** * Dispatched when the user rolls the mouse over a swatch * in the SwatchPanel object. * * @eventType mx.events.ColorPickerEvent.ITEM_ROLL_OVER * @helpid 4923 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name="itemRollOver", type="mx.events.ColorPickerEvent")] /** * Dispatched when the color swatch panel opens. * * @eventType mx.events.DropdownEvent.OPEN * @helpid 4920 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name="open", type="mx.events.DropdownEvent")] //-------------------------------------- // Styles //-------------------------------------- include "../styles/metadata/FocusStyles.as" include "../styles/metadata/IconColorStyles.as" include "../styles/metadata/LeadingStyle.as" include "../styles/metadata/TextStyles.as" /** * Color of the outer border on the SwatchPanel object. * The default value is <code>0xA5A9AE</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="borderColor", type="uint", format="Color", inherit="no", theme="halo")] /** * Length of a close transition, in milliseconds. * * The default value for the Halo theme is 250. * The default value for the Spark theme is 50. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="closeDuration", type="Number", format="Time", inherit="no")] /** * Easing function to control component tweening. * The default value is <code>undefined</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="closeEasingFunction", type="Function", inherit="no")] /** * Alphas used for the background fill of controls. * The default value is <code>[ 0.6, 0.4 ]</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="fillAlphas", type="Array", arrayType="Number", inherit="no", theme="halo")] /** * Colors used to tint the background of the control. * Pass the same color for both values for a flat-looking control. * The default value is <code>[ 0xFFFFFF, 0xCCCCCC ]</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="fillColors", type="Array", arrayType="uint", format="Color", inherit="no", theme="halo")] /** * Alphas used for the highlight fill of controls. * The default value is <code>[ 0.3, 0.0 ]</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="highlightAlphas", type="Array", arrayType="Number", inherit="no", theme="halo")] /** * Length of an open transition, in milliseconds. * * The default value for the Halo theme is 250. * The default value for the Spark theme is 0. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="openDuration", type="Number", format="Time", inherit="no")] /** * Easing function to control component tweening. * The default value is <code>undefined</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="openEasingFunction", type="Function", inherit="no")] /** * Bottom padding of SwatchPanel object below the swatch grid. * The default value is 5. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="paddingBottom", type="Number", format="Length", inherit="no")] /** * Left padding of SwatchPanel object to the side of the swatch grid. * The default value is 5. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="paddingLeft", type="Number", format="Length", inherit="no")] /** * Right padding of SwatchPanel object to the side of the swatch grid. * The default value is 5. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="paddingRight", type="Number", format="Length", inherit="no")] /** * Top padding of SwatchPanel object above the swatch grid. * The default value is 4. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="paddingTop", type="Number", format="Length", inherit="no")] /** * Color of the swatches' borders. * The default value is <code>0x000000</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="swatchBorderColor", type="uint", format="Color", inherit="no", theme="halo")] /** * Size of the outlines of the swatches' borders. * The default value is 1. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="swatchBorderSize", type="Number", format="Length", inherit="no")] /** * Name of the class selector that defines style properties for the swatch panel. * The default value is <code>undefined</code>. The following example shows the default style properties * that are defined by the <code>swatchPanelStyleName</code>. * <pre> * ColorPicker { * swatchPanelStyleName:mySwatchPanelStyle; * } * * .mySwatchPanelStyle { * backgroundColor:#E5E6E7; * columnCount:20; * horizontalGap:0; * previewHeight:22; * previewWidth:45; * swatchGridBackgroundColor:#000000; * swatchGridBorderSize:0; * swatchHeight:12; * swatchHighlightColor:#FFFFFF; * swatchHighlightSize:1; * swatchWidth:12; * textFieldWidth:72; * verticalGap:0; * } * </pre> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name="swatchPanelStyleName", type="String", inherit="no")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name="text", kind="property")] [Exclude(name="fillAlphas", kind="style")] [Exclude(name="fillColors", kind="style")] [Exclude(name="highlightAlphas", kind="style")] //-------------------------------------- // Other metadata //-------------------------------------- [AccessibilityClass(implementation="mx.accessibility.ColorPickerAccImpl")] [DataBindingInfo("acceptedTypes", "{ dataProvider: { label: &quot;String&quot; } }")] [DefaultBindingProperty(source="selectedItem", destination="dataProvider")] [DefaultTriggerEvent("change")] [IconFile("ColorPicker.png")] /** * The ColorPicker control provides a way for a user to choose a color from a swatch list. * The default mode of the component shows a single swatch in a square button. * When the user clicks the swatch button, the swatch panel appears and * displays the entire swatch list. * * <p>The ColorPicker control has the following default sizing characteristics:</p> * <table class="innertable"> * <tr> * <th>Characteristic</th> * <th>Description</th> * </tr> * <tr> * <td>Default size</td> * <td>ColorPicker: 22 by 22 pixels * <br>Swatch panel: Sized to fit the ColorPicker control width</br></td> * </tr> * <tr> * <td>Minimum size</td> * <td>0 pixels by 0 pixels</td> * </tr> * <tr> * <td>Maximum size</td> * <td>Undefined</td> * </tr> * </table> * * @mxml * * <p>The <code>&lt;mx:ColorPicker&gt;</code> tag inherits all of the properties of its * superclass, and the following properties:</p> * * <pre> * &lt;mx:ColorPicker * <b>Properties</b> * colorField="color" * labelField="label" * selectedColor="0x000000" * selectedIndex="0" * showTextField="true|false" * * <b>Styles</b> * borderColor="0xA5A9AE" * closeDuration="250" * closeEasingFunction="undefined" * color="0x0B333C" * disabledIconColor="0x999999" * fillAlphas="[0.6,0.4]" * fillColors="[0xFFFFFF, 0xCCCCCC]" * focusAlpha="0.5" * focusRoundedCorners="tl tr bl br" * fontAntiAliasType="advanced" * fontfamily="Verdana" * fontGridFitType="pixel" * fontSharpness="0"" * fontSize="10" * fontStyle="normal" * fontThickness="0" * fontWeight="normal" * highlightAlphas="[0.3,0.0]" * iconColor="0x000000" * leading="2" * openDuration="250" * openEasingFunction="undefined" * paddingBottom="5" * paddingLeft="5" * paddingRight="5" * paddingTop="4" * swatchBorderColor="0x000000" * swatchBorderSize="1" * swatchPanelStyleName="undefined" * textAlign="left" * textDecoration="none" * textIndent="0" * * <b>Events</b> * change="<i>No default</i>" * close="<i>No default</i>" * enter="<i>No default</i>" * itemRollOut="<i>No default</i>" * itemRollOver="<i>No default</i>" * open="<i>No default</i>" * /&gt; * </pre> * * @see mx.controls.List * @see mx.effects.Tween * @see mx.managers.PopUpManager * * @includeExample examples/ColorPickerExample.mxml * * @helpid 4917 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class ColorPicker extends ComboBase { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Class mixins // //-------------------------------------------------------------------------- /** * @private * Placeholder for mixin by SliderAccImpl. */ mx_internal static var createAccessibilityImplementation:Function; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function ColorPicker() { super(); if (!isModelInited) loadDefaultPalette(); // Make editable false so that focus doesn't go // to the comboBase's textInput which is not used by CP super.editable = false; // Register for events. addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Used by SwatchPanel */ mx_internal var showingDropdown:Boolean = false; /** * @private * Used by SwatchPanel */ mx_internal var isDown:Boolean = false; /** * @private * Used by SwatchPanel */ mx_internal var isOpening:Boolean = false; /** * @private */ private var dropdownGap:Number = 6; /** * @private */ private var indexFlag:Boolean = false; /** * @private */ private var initializing:Boolean = true; /** * @private */ private var isModelInited:Boolean = false; /** * @private */ private var collectionChanged:Boolean = false; /** * @private */ private var swatchPreview:SwatchSkin; /** * @private */ private var dropdownSwatch:SwatchPanel; /** * @private */ private var triggerEvent:Event; //-------------------------------------------------------------------------- // // Overridden Properties // //-------------------------------------------------------------------------- //---------------------------------- // dataProvider //---------------------------------- [Bindable("collectionChange")] [Inspectable(category="Data")] /** * @private * The dataProvider for the ColorPicker control. * The default dataProvider is an Array that includes all * the web-safe colors. * * @helpid 4929 */ override public function set dataProvider(value:Object):void { super.dataProvider = value; isModelInited = true; if (dropdownSwatch) dropdownSwatch.dataProvider = value; } //---------------------------------- // editable //---------------------------------- [Bindable("editableChanged")] [Inspectable(category="General", defaultValue="true")] /** * @private */ private var _editable:Boolean = true; /** * @private * Specifies whether the user can type a hexadecimal color value * in the text box. * * @default true * @helpid 4930 */ override public function get editable():Boolean { return _editable; } /** * @private */ override public function set editable(value:Boolean):void { _editable = value; if (dropdownSwatch) dropdownSwatch.editable = value; dispatchEvent(new Event("editableChanged")); } //---------------------------------- // selectedIndex //---------------------------------- [Bindable("change")] [Bindable("collectionChange")] [Inspectable(defaultValue="0")] /** * Index in the dataProvider of the selected item in the * SwatchPanel object. * Setting this property sets the selected color to the color that * corresponds to the index, sets the selected index in the drop-down * swatch to the <code>selectedIndex</code> property value, * and displays the associated label in the text box. * The default value is the index corresponding to * black(0x000000) color if found, else it is 0. * * @helpid 4931 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function set selectedIndex(value:int):void { if ((selectedIndex != -1 || !isNaN(selectedColor)) && value != selectedIndex) { if (value >= 0) { indexFlag = true; selectedColor = getColor(value); // Call super in mixed-in DataSelector super.selectedIndex = value; } if (dropdownSwatch) dropdownSwatch.selectedIndex = value; } } //---------------------------------- // selectedItem //---------------------------------- [Bindable("change")] [Bindable("collectionChange")] [Inspectable(defaultValue="0")] /** * @private * If the dataProvider is a complex object, this property is a * reference to the selected item in the SwatchPanel object. * If the dataProvider is an Array of color values, this * property is the selected color value. * If the dataProvider is a complex object, modifying fields of * this property modifies the dataProvider and its views. * * <p>If the dataProvider is a complex object, this property is * read-only. You cannot change its value directly. * If the dataProvider is an Array of hexadecimal color values, * you can change this value directly. * The default value is undefined for complex dataProviders; * 0 if the dataProvider is an Array of color values. * * @helpid 4933 */ override public function set selectedItem(value:Object):void { if (value != selectedItem) { // Call super in mixed-in DataSelector super.selectedItem = value; if (typeof(value) == "object") selectedColor = Number(value[colorField]); else if (typeof(value) == "number") selectedColor = Number(value); indexFlag = true; if (dropdownSwatch) dropdownSwatch.selectedItem = value; } } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // colorField //---------------------------------- /** * @private * Storage for the colorField property. */ private var _colorField:String = "color"; [Bindable("colorFieldChanged")] [Inspectable(category="Data", defaultValue="color")] /** * Name of the field in the objects of the dataProvider Array that * specifies the hexadecimal values of the colors that the swatch * panel displays. * * <p>If the dataProvider objects do not contain a color * field, set the <code>colorField</code> property to use the correct field name. * This property is available, but not meaningful, if the * dataProvider is an Array of hexadecimal color values.</p> * * @default "color" * @helpid 4927 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get colorField():String { return _colorField; } /** * @private */ public function set colorField(value:String):void { _colorField = value; if (dropdownSwatch) dropdownSwatch.colorField = value; dispatchEvent(new Event("colorFieldChanged")); } //---------------------------------- // dropdown //---------------------------------- /** * A reference to the SwatchPanel object that appears when you expand * the ColorPicker control. * * @helpid 4922 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal function get dropdown():SwatchPanel { return dropdownSwatch; // null if not created yet } //---------------------------------- // labelField //---------------------------------- /** * Storage for the labelField property. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ private var _labelField:String = "label"; [Bindable("labelFieldChanged")] [Inspectable(category="Data", defaultValue="label")] /** * Name of the field in the objects of the dataProvider Array that * contain text to display as the label in the SwatchPanel object text box. * * <p>If the dataProvider objects do not contain a label * field, set the <code>labelField</code> property to use the correct field name. * This property is available, but not meaningful, if the * dataProvider is an Array of hexadecimal color values.</p> * * @default "label" * @helpid 4928 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get labelField():String { return _labelField; } /** * @private */ public function set labelField(value:String):void { _labelField = value; if (dropdownSwatch) dropdownSwatch.labelField = value; dispatchEvent(new Event("labelFieldChanged")); } //---------------------------------- // selectedColor //---------------------------------- /** * @private * Storage for the selectedColor property. */ private var _selectedColor:uint = 0x000000; [Bindable("change")] [Bindable("valueCommit")] [Inspectable(category="General", defaultValue="0", format="Color")] /** * The value of the currently selected color in the * SwatchPanel object. * In the &lt;mx:ColorPicker&gt; tag only, you can set this property to * a standard string color name, such as "blue". * If the dataProvider contains an entry for black (0x000000), the * default value is 0; otherwise, the default value is the color of * the item at index 0 of the data provider. * * @helpid 4932 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectedColor():uint { return _selectedColor; } /** * @private */ public function set selectedColor(value:uint):void { if (!indexFlag) { super.selectedIndex = findColorByName(value); } else { indexFlag = false; } if (value != selectedColor) { _selectedColor = value; updateColor(value); if (dropdownSwatch) dropdownSwatch.selectedColor = value; } dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); } //---------------------------------- // showTextField //---------------------------------- /** * @private * Storage for the showTextField property. */ private var _showTextField:Boolean = true; [Inspectable(category="General", defaultValue="true")] /** * Specifies whether to show the text box that displays the color * label or hexadecimal color value. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get showTextField():Boolean { return _showTextField; } /** * @private */ public function set showTextField(value:Boolean):void { _showTextField = value; if (dropdownSwatch) dropdownSwatch.showTextField = value; } //---------------------------------- // swatchStyleFilters //---------------------------------- /** * Set of styles to pass from the ColorPicker through to the preview swatch. * @see mx.styles.StyleProxy * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get swatchStyleFilters():Object { return _swatchStyleFilters; } private static const _swatchStyleFilters:Object = { "swatchBorderColor" : "swatchBorderColor", "swatchBorderSize" : "swatchBorderSize" }; //-------------------------------------------------------------------------- // // Overridden methods: UIComponent // //-------------------------------------------------------------------------- /** * @private */ override protected function initializeAccessibility():void { if (ColorPicker.createAccessibilityImplementation != null) ColorPicker.createAccessibilityImplementation(this); } /** * @private */ override protected function createChildren():void { super.createChildren(); // Create swatch preview if (!swatchPreview) { swatchPreview = new SwatchSkin(); swatchPreview.styleName = new StyleProxy(this, swatchStyleFilters); swatchPreview.color = selectedColor; swatchPreview.name = "colorPickerSwatch"; addChild(swatchPreview); } setChildIndex(swatchPreview, getChildIndex(downArrowButton)); textInput.visible = false; // Update the preview swatch if (!enabled) super.enabled = enabled; initializing = false; } /** * @private */ override protected function commitProperties():void { super.commitProperties(); // Code executed when model (dataProvider changes) // If dataProvider is changed, selectedColor if found in // the new dataProvider is selected // else selectedColor is color at selectedIndex = 0; if (collectionChanged) { if (findColorByName(selectedColor) == -1) { if (dataProvider.length > 0 && selectedIndex > dataProvider.length) selectedIndex = 0; if (getColor(selectedIndex) >= 0) { selectedColor = getColor(selectedIndex); swatchPreview.color = selectedColor; } else { if (dropdownSwatch) swatchPreview.color = dropdownSwatch.selectedColor; } } else selectedIndex = findColorByName(selectedColor); collectionChanged = false; } } /** * @private */ override protected function measure():void { // Though deriving from ComboBase this doesnot implement // calcPreferredSizeFromData required by the super measure. // Hence do not call it. // super.measure(); // Make sure we're a small square, so we use HEIGHT for both measuredMinWidth = measuredWidth = DEFAULT_MEASURED_MIN_HEIGHT; measuredMinHeight = measuredHeight = DEFAULT_MEASURED_MIN_HEIGHT; } /** * @private */ override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); swatchPreview.color = selectedColor; swatchPreview.setActualSize(unscaledWidth, unscaledHeight); // super may push it around downArrowButton.move(0, 0); downArrowButton.setActualSize(unscaledWidth, unscaledHeight); if (dropdownSwatch) { dropdownSwatch.setActualSize( dropdownSwatch.getExplicitOrMeasuredWidth(), dropdownSwatch.getExplicitOrMeasuredHeight()); } } /** * @private * Invalidate Style */ override public function styleChanged(styleProp:String):void { if (dropdownSwatch) { if (styleProp == "swatchPanelStyleName") { var swatchPanelStyleName:Object = getStyle("swatchPanelStyleName"); if (swatchPanelStyleName) dropdownSwatch.styleName = swatchPanelStyleName; } dropdownSwatch.styleChanged(styleProp); } super.styleChanged(styleProp); // Adjust tweenMask size if needed invalidateDisplayList(); } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Displays the drop-down SwatchPanel object * that shows colors that users can select. * * @helpid 4925 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function open():void { displayDropdown(true); } /** * Hides the drop-down SwatchPanel object. * * @param trigger The event to dispatch when the * drop-down list closes. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function close(trigger:Event = null):void { displayDropdown(false, trigger); } /** * @private * Dropdown Creation */ mx_internal function getDropdown():SwatchPanel { if (initializing) return null; if (!dropdownSwatch) { dropdownSwatch = new SwatchPanel(); dropdownSwatch.owner = this; dropdownSwatch.editable = editable; dropdownSwatch.colorField = colorField; dropdownSwatch.labelField = labelField; dropdownSwatch.dataProvider = dataProvider; dropdownSwatch.showTextField = showTextField; dropdownSwatch.selectedColor = selectedColor; dropdownSwatch.selectedIndex = selectedIndex; dropdownSwatch.textInputClass = getStyle("textInputClass"); var swatchPanelStyleName:Object = getStyle("swatchPanelStyleName"); if (swatchPanelStyleName) dropdownSwatch.styleName = swatchPanelStyleName; // Assign event handlers dropdownSwatch.addEventListener(ColorPickerEvent.ITEM_ROLL_OVER, dropdownSwatch_itemRollOverHandler); dropdownSwatch.addEventListener(ColorPickerEvent.ITEM_ROLL_OUT, dropdownSwatch_itemRollOutHandler); dropdownSwatch.cacheAsBitmap = true; dropdownSwatch.scrollRect = new Rectangle(0, 0, 0, 0); PopUpManager.addPopUp(dropdownSwatch, this); UIComponentGlobals.layoutManager.validateClient(dropdownSwatch, true); dropdownSwatch.setActualSize( dropdownSwatch.getExplicitOrMeasuredWidth(), dropdownSwatch.getExplicitOrMeasuredHeight()); dropdownSwatch.validateDisplayList(); } dropdownSwatch.layoutDirection = layoutDirection; dropdownSwatch.scaleX = scaleX; dropdownSwatch.scaleY = scaleY; return dropdownSwatch; } /** * @private * Display Dropdown */ mx_internal function displayDropdown(show:Boolean, trigger:Event = null):void { if (show == showingDropdown) return; // Show or hide the dropdown var initY:Number; var endY:Number; var tween:Tween = null; var easingFunction:Function; var duration:Number; // Save the current triggerEvent triggerEvent = trigger; if (show) // Open { getDropdown(); // Find global position for the dropdown var point:Point = new Point(layoutDirection == LayoutDirection.RTL ? dropdownSwatch.getExplicitOrMeasuredWidth() : 0, 0); point = localToGlobal(point); if (dropdownSwatch.parent == null) PopUpManager.addPopUp(dropdownSwatch, this, false); else PopUpManager.bringToFront(dropdownSwatch); dropdownSwatch.addEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE, dropdownSwatch_mouseDownOutsideHandler); dropdownSwatch.addEventListener(FlexMouseEvent.MOUSE_WHEEL_OUTSIDE, dropdownSwatch_mouseDownOutsideHandler); dropdownSwatch.addEventListener(SandboxMouseEvent.MOUSE_DOWN_SOMEWHERE, dropdownSwatch_mouseDownOutsideHandler); dropdownSwatch.addEventListener(SandboxMouseEvent.MOUSE_WHEEL_SOMEWHERE, dropdownSwatch_mouseDownOutsideHandler); dropdownSwatch.isOpening = true; dropdownSwatch.showTextField = showTextField; dropdownSwatch.selectedColor = selectedColor; dropdownSwatch.owner = this; // Position: top or bottom var sm:ISystemManager = systemManager.topLevelSystemManager; var screen:Rectangle = sm.getVisibleApplicationRect(null, true); if (point.y + height + dropdownGap + dropdownSwatch.height > screen.bottom && point.y > (screen.top + dropdownGap + dropdownSwatch.height)) // Up { // Dropdown opens up instead of down point.y -= dropdownGap + dropdownSwatch.height; initY = -dropdownSwatch.height/scaleY; dropdownSwatch.tweenUp = true; } else // Down { point.y += dropdownGap + height; initY = dropdownSwatch.height/scaleY; dropdownSwatch.tweenUp = false; } // Position: left or right if (point.x + dropdownSwatch.width > screen.right && point.x > (screen.left + dropdownSwatch.width)) { // Dropdown appears to the left instead of right point.x -= (dropdownSwatch.width - width); } point.x = Math.max(point.x, 0); // Position the dropdown point = dropdownSwatch.parent.globalToLocal(point); dropdownSwatch.move(point.x, point.y); //dropdownSwatch.setFocus(); isDown = true; isOpening = true; endY = 0; duration = getStyle("openDuration"); easingFunction = getStyle("openEasingFunction") as Function; showingDropdown = show; } else // Close { initY = 0; endY = dropdownSwatch.tweenUp ? -dropdownSwatch.height/scaleY : dropdownSwatch.height/scaleY; isDown = false; duration = getStyle("closeDuration"); easingFunction = getStyle("closeEasingFunction") as Function; showingDropdown = show; dropdownSwatch.removeEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE, dropdownSwatch_mouseDownOutsideHandler); dropdownSwatch.removeEventListener(FlexMouseEvent.MOUSE_WHEEL_OUTSIDE, dropdownSwatch_mouseDownOutsideHandler); dropdownSwatch.removeEventListener(SandboxMouseEvent.MOUSE_DOWN_SOMEWHERE, dropdownSwatch_mouseDownOutsideHandler); dropdownSwatch.removeEventListener(SandboxMouseEvent.MOUSE_WHEEL_SOMEWHERE, dropdownSwatch_mouseDownOutsideHandler); PopUpManager.removePopUp(dropdownSwatch); } if (dropdownSwatch) { dropdownSwatch.visible = true; dropdownSwatch.enabled = false; } UIComponentGlobals.layoutManager.validateNow(); // Block all layout, responses from web service, and other background // processing until the tween finishes executing. UIComponent.suspendBackgroundProcessing(); tween = new Tween(this, initY, endY, duration); if (easingFunction != null) tween.easingFunction = easingFunction; } /** * @private * Load Default Palette */ private function loadDefaultPalette():void { // Initialize default swatch list if (!dataProvider || dataProvider.length < 1) { var wsp:WebSafePalette = new WebSafePalette(); dataProvider = wsp.getList(); } selectedIndex = findColorByName(selectedColor); } /** * @private * Update Color Preview */ private function updateColor(color:Number):void { if (initializing || isNaN(color)) return; // Update the preview swatch swatchPreview.updateSkin(color); } /** * @private * Find Color by Name */ private function findColorByName(name:Number):int { if (name == getColor(selectedIndex)) return selectedIndex; var n:int = dataProvider.length; for (var i:int = 0; i < dataProvider.length; i++) { if (name == getColor(i)) return i; } return -1; } /** * @private * Get Color Value */ private function getColor(location:int):Number { if (!dataProvider || dataProvider.length < 1 || location < 0 || location >= dataProvider.length) { return -1; } return Number(typeof(dataProvider.getItemAt(location)) == "object" ? dataProvider.getItemAt(location)[colorField] : dataProvider.getItemAt(location)); } //-------------------------------------------------------------------------- // // Overridden event handlers: UIComponent // //-------------------------------------------------------------------------- /** * @private */ override protected function focusInHandler(event:FocusEvent):void { var fm:IFocusManager = focusManager; if (fm) fm.showFocusIndicator = true; if (isDown && !isOpening) close(); else if (isOpening) isOpening = false; super.focusInHandler(event); } /** * @private */ override protected function keyDownHandler(event:KeyboardEvent):void { var cpEvent:ColorPickerEvent = null; // If rtl layout, need to swap LEFT and RIGHT so correct action // is done. var keyCode:uint = mapKeycodeForLayoutDirection(event); if (event.ctrlKey && keyCode == Keyboard.DOWN) { displayDropdown(true, event); } else if ((event.ctrlKey && keyCode == Keyboard.UP) || keyCode == Keyboard.ESCAPE) { if (dropdownSwatch && dropdownSwatch.enabled) close(event); } else if (showingDropdown && keyCode == Keyboard.ENTER && dropdownSwatch.enabled) { if (!dropdownSwatch.isOverGrid && editable) { if (selectedColor != dropdownSwatch.selectedColor) { selectedColor = dropdownSwatch.selectedColor; cpEvent = new ColorPickerEvent(ColorPickerEvent.CHANGE); cpEvent.index = selectedIndex; cpEvent.color = selectedColor; dispatchEvent(cpEvent); cpEvent = new ColorPickerEvent(ColorPickerEvent.ENTER); // The index isn't set for an ENTER event, // because the user can enter an RGB hex string that // doesn't correspond to any color in the dataProvider. cpEvent.color = selectedColor; dispatchEvent(cpEvent); } } else if (selectedIndex != dropdownSwatch.focusedIndex) { dropdownSwatch.selectedIndex = dropdownSwatch.focusedIndex; selectedIndex = dropdownSwatch.selectedIndex; cpEvent = new ColorPickerEvent(ColorPickerEvent.CHANGE); cpEvent.index = selectedIndex; cpEvent.color = selectedColor; dispatchEvent(cpEvent); } close(); event.stopPropagation(); } else if (showingDropdown && (keyCode == Keyboard.HOME || keyCode == Keyboard.END || keyCode == Keyboard.PAGE_UP || keyCode == Keyboard.PAGE_DOWN || keyCode == Keyboard.LEFT || keyCode == Keyboard.RIGHT || keyCode == Keyboard.UP || keyCode == Keyboard.DOWN)) { // Redispatch the event from the SwatchPanel // so that its keyDownHandler() can handle it. dropdownSwatch.dispatchEvent(event); } else if (keyCode == Keyboard.LEFT) { if (selectedIndex == -1) { selectedIndex = findColorByName(selectedColor); } if (selectedIndex - 1 >= 0) { selectedIndex--; cpEvent = new ColorPickerEvent(ColorPickerEvent.CHANGE); cpEvent.index = selectedIndex; cpEvent.color = selectedColor; dispatchEvent(cpEvent); } } else if (keyCode == Keyboard.RIGHT) { if (selectedIndex == -1) { selectedIndex = findColorByName(selectedColor); } if (selectedIndex + 1 < dataProvider.length) { selectedIndex++; cpEvent = new ColorPickerEvent(ColorPickerEvent.CHANGE); cpEvent.index = selectedIndex; cpEvent.color = selectedColor; dispatchEvent(cpEvent); } } } //-------------------------------------------------------------------------- // // Overridden event handlers: ComboBase // //-------------------------------------------------------------------------- /** * @private */ override protected function collectionChangeHandler(event:Event):void { // Change index to match selectedcolor if the model changes. if (!initializing) { if (dataProvider.length > 0) invalidateProperties(); else { selectedColor = 0x000000; selectedIndex = -1; } collectionChanged = true; } if (dropdownSwatch) dropdownSwatch.dataProvider = dataProvider; } /** * @private * On Down Arrow */ override protected function downArrowButton_buttonDownHandler( event:FlexEvent):void { // The down arrow should always toggle the visibility of the dropdown displayDropdown(!showingDropdown, event); } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function dropdownSwatch_itemRollOverHandler(event:ColorPickerEvent):void { dispatchEvent(event); } /** * @private */ private function dropdownSwatch_itemRollOutHandler(event:ColorPickerEvent):void { dispatchEvent(event); } /** * @private */ private function dropdownSwatch_mouseDownOutsideHandler(event:Event):void { if (event is MouseEvent) { var mouseEvent:MouseEvent = MouseEvent(event); if (!hitTestPoint(mouseEvent.stageX, mouseEvent.stageY, true)) close(event); } else if (event is SandboxMouseEvent) close(event); } /** * @private */ mx_internal function onTweenUpdate(value:Number):void { dropdownSwatch.scrollRect = new Rectangle(0, value, dropdownSwatch.width, dropdownSwatch.height); } /** * @private */ mx_internal function onTweenEnd(value:Number):void { if (showingDropdown) { dropdownSwatch.scrollRect = null; } else { onTweenUpdate(value); dropdownSwatch.visible = false; isOpening = false; } UIComponent.resumeBackgroundProcessing(); if (showingDropdown && showTextField) dropdownSwatch.callLater(dropdownSwatch.setFocus); else setFocus(); dropdownSwatch.enabled = true; dispatchEvent(new DropdownEvent(showingDropdown ? DropdownEvent.OPEN : DropdownEvent.CLOSE, false, false, triggerEvent)); } } }
package com.ankamagames.dofus.logic.common.managers { import com.ankamagames.berilia.enums.StrataEnum; import com.ankamagames.berilia.managers.KernelEventsManager; import com.ankamagames.berilia.managers.TooltipManager; import com.ankamagames.berilia.managers.UiModuleManager; import com.ankamagames.berilia.types.data.TextTooltipInfo; import com.ankamagames.dofus.datacenter.quest.Quest; import com.ankamagames.dofus.misc.lists.HookList; import com.ankamagames.jerakine.data.I18n; import flash.geom.Rectangle; public class HyperlinkShowQuestManager { private static var _questList:Array = new Array(); private static var _questId:uint = 0; public function HyperlinkShowQuestManager() { super(); } public static function showQuest(questId:uint) : void { var data:Object = null; var quest:Quest = Quest.getQuestById(_questList[questId].id); if(quest) { data = new Object(); data.quest = quest; data.forceOpen = true; KernelEventsManager.getInstance().processCallback(HookList.OpenBook,"questTab",data); } } public static function addQuest(questId:uint) : String { var code:* = null; var quest:Quest = Quest.getQuestById(questId); if(quest) { _questList[_questId] = quest; code = "{chatquest," + _questId + "::[" + quest.name + "]}"; ++_questId; return code; } return "[null]"; } public static function rollOver(pX:int, pY:int, objectGID:uint, questId:uint = 0) : void { var target:Rectangle = new Rectangle(pX,pY,10,10); var info:TextTooltipInfo = new TextTooltipInfo(I18n.getUiText("ui.tooltip.chat.quest")); TooltipManager.show(info,target,UiModuleManager.getInstance().getModule("Ankama_GameUiCore"),false,"HyperLink",6,2,3,true,null,null,null,null,false,StrataEnum.STRATA_TOOLTIP,1); } } }
package flare.vis.controls { import flare.util.Filter; import flash.display.InteractiveObject; import flash.events.EventDispatcher; /** * Base class for interactive controls. */ public class Control extends EventDispatcher implements IControl { /** @private */ protected var _object:InteractiveObject; /** @private */ protected var _filter:Function; /** Boolean function indicating the items considered by the control. * @see flare.util.Filter */ public function get filter():Function { return _filter; } public function set filter(f:*):void { _filter = Filter.$(f); } /** * Creates a new Control */ public function Control() { // do nothing } /** @inheritDoc */ public function get object():InteractiveObject { return _object; } /** @inheritDoc */ public function attach(obj:InteractiveObject):void { if (_object) detach(); _object = obj; } /** @inheritDoc */ public function detach():InteractiveObject { var obj:InteractiveObject = _object; _object = null; return obj; } } // end of class Control }
package Ankama_Storage.ui.behavior { import Ankama_Storage.Api; import Ankama_Storage.ui.AbstractStorageUi; import Ankama_Storage.ui.EquipmentUi; import Ankama_Storage.ui.enum.StorageState; import com.ankamagames.berilia.enums.SelectMethodEnum; import com.ankamagames.berilia.enums.UIEnum; import com.ankamagames.berilia.types.graphic.GraphicContainer; import com.ankamagames.dofus.internalDatacenter.DataEnum; import com.ankamagames.dofus.internalDatacenter.items.ItemWrapper; import com.ankamagames.dofus.logic.game.common.actions.OpenIdolsAction; import com.ankamagames.dofus.logic.game.common.actions.mount.MountInfoRequestAction; import com.ankamagames.dofus.logic.game.roleplay.actions.ObjectSetPositionAction; import com.ankamagames.dofus.types.enums.ItemCategoryEnum; public class StorageClassicBehavior implements IStorageBehavior { private var _storage:EquipmentUi; private var _waitingObject:Object; public function StorageClassicBehavior() { super(); } public function filterStatus(enabled:Boolean) : void { } public function dropValidator(target:Object, data:Object, source:Object) : Boolean { if(data is ItemWrapper && this._storage.categoryFilter != ItemCategoryEnum.QUEST_CATEGORY) { if(data.position != 63) { return true; } } return false; } public function processDrop(target:Object, data:Object, source:Object) : void { if(data.quantity == 1) { Api.system.sendAction(new ObjectSetPositionAction([data.objectUID,63,1])); } else { this._waitingObject = data; Api.common.openQuantityPopup(1,data.quantity,data.quantity,this.onValidQty); } } public function onRelease(target:GraphicContainer) : void { } public function onSelectItem(target:GraphicContainer, selectMethod:uint, isNewSelection:Boolean) : void { var item:Object = null; if(target == this._storage.grid) { item = this._storage.grid.selectedItem; switch(selectMethod) { case SelectMethodEnum.CLICK: break; case SelectMethodEnum.DOUBLE_CLICK: Api.ui.hideTooltip(); this.doubleClickGridItem(item); break; case SelectMethodEnum.CTRL_DOUBLE_CLICK: this.doubleClickGridItem(item); } } } public function attach(storageUi:AbstractStorageUi) : void { if(!(storageUi is EquipmentUi)) { throw new Error("Can\'t attach a StorageClassicBehavior to a non EquipmentUi storage"); } this._storage = storageUi as EquipmentUi; } public function detach() : void { } public function onUnload() : void { } public function getStorageUiName() : String { return UIEnum.EQUIPMENT_UI; } public function getName() : String { return StorageState.BAG_MOD; } public function get replacable() : Boolean { return true; } private function onValidQty(qty:Number) : void { Api.system.sendAction(new ObjectSetPositionAction([this._waitingObject.objectUID,63,qty])); } public function doubleClickGridItem(pItem:Object) : void { var freeSlot:int = 0; var item:ItemWrapper = pItem as ItemWrapper; if(item && (item.category == ItemCategoryEnum.EQUIPMENT_CATEGORY || item.category == ItemCategoryEnum.COSMETICS_CATEGORY)) { freeSlot = Api.storage.getBestEquipablePosition(item); if(freeSlot > -1) { Api.system.sendAction(new ObjectSetPositionAction([item.objectUID,freeSlot,1])); } } else if(item) { if(item.usable || item.targetable) { this._storage.useItem(item); } else if(item.typeId == DataEnum.ITEM_TYPE_IDOLS) { Api.system.sendAction(new OpenIdolsAction([])); } else if(item.hasOwnProperty("isCertificate") && item.isCertificate) { Api.system.sendAction(new MountInfoRequestAction([item])); } } } public function transfertAll() : void { } public function transfertList() : void { } public function transfertExisting() : void { } } }
package com.codeazur.as3swf.data.abc.bytecode.attributes { import com.codeazur.as3swf.SWFData; import com.codeazur.as3swf.data.abc.ABCData; import com.codeazur.utils.StringUtils; /** * @author Simon Richardson - simon@ustwo.co.uk */ public class ABCOpcodeUnsignedByteAttribute extends ABCOpcodeAttribute implements IABCOpcodeUnsignedIntegerAttribute { private var _unsignedInteger:uint; public function ABCOpcodeUnsignedByteAttribute(abcData:ABCData) { super(abcData); } public static function create(abcData:ABCData):ABCOpcodeUnsignedByteAttribute { return new ABCOpcodeUnsignedByteAttribute(abcData); } override public function read(data:SWFData):void { _unsignedInteger = data.readUnsignedByte(); } override public function write(bytes : SWFData) : void { bytes.writeByte(unsignedInteger); } public function get unsignedInteger():uint { return _unsignedInteger; } override public function get value():* { return _unsignedInteger; } override public function get name():String { return "ABCOpcodeUnsignedByteAttribute"; } override public function toString(indent : uint = 0) : String { var str:String = super.toString(indent); str += "\n" + StringUtils.repeat(indent + 2) + "UnsignedInteger: "; str += "\n" + StringUtils.repeat(indent + 4) + unsignedInteger; return str; } } }
int myvar = 42; void Function(int a, int b = myvar) { assert( b == 42 ); } void main() { int myvar = 1; Function(1); }