CombinedText
stringlengths
4
3.42M
/* 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 flexunit.framework.tests { import flexunit.framework.*; public class TestTestCase extends TestCase { public static function suite() : TestSuite { var suite : TestSuite = new TestSuite(); suite.addTest(new TestTestCase("testCaseToString")); suite.addTest(new TestTestCase("testError")); suite.addTest(new TestTestCase("testRunAndTearDownFails")); suite.addTest(new TestTestCase("testSetupFails")); suite.addTest(new TestTestCase("testSuccess")); suite.addTest(new TestTestCase("testFailure")); suite.addTest(new TestTestCase("testTearDownAfterError")); suite.addTest(new TestTestCase("testTearDownFails")); suite.addTest(new TestTestCase("testTearDownSetupFails")); suite.addTest(new TestTestCase("testWasRun")); suite.addTest(new TestTestCase("testExceptionRunningAndTearDown")); //suite.addTest(new TestTestCase("testNoArgTestCasePasses")); suite.addTest(new TestTestCase("testNamelessTestCase")); return suite; } public function TestTestCase(name : String = null) { super(name); } public function testCaseToString() : void { Assert.assertEquals( "testCaseToString (flexunit.framework.tests::TestTestCase)", toString() ); } //------------------------------------------------------------------------------ public function testError() : void { var error : ErrorTestCase = new ErrorTestCase("throwError"); verifyError( error ); } //------------------------------------------------------------------------------ public function testRunAndTearDownFails() : void { var fails : TearDownErrorTestCase = new TearDownErrorTestCase("throwError"); //MATT: because of the asynchronous support an error in tearDown will now be an additional //error instead of overwriting the error that was thrown in the test run verifyError( fails, 2 ); Assert.assertTrue( fails.expectedResult ); } //------------------------------------------------------------------------------ public function testSetupFails() : void { var fails : SetupErrorTestCase = new SetupErrorTestCase( "throwError" ) verifyError( fails, 1 ); } //------------------------------------------------------------------------------ public function testSuccess() : void { var success : TestCase = new SuccessTestCase( "testSuccess" ) verifySuccess( success ); } //------------------------------------------------------------------------------ public function testFailure() : void { var failure : TestCase = new FailureTestCase( "testFailure" ) verifyFailure( failure ); } //------------------------------------------------------------------------------ public function testTearDownAfterError() : void { var fails : TearDownTestCase = new TearDownTestCase("throwError"); verifyError( fails ); Assert.assertTrue( fails.expectedResult ); } //------------------------------------------------------------------------------ public function testTearDownFails() : void { var fails : TearDownErrorTestCase = new TearDownErrorTestCase( "testSuccess" ) verifyError( fails ); } //------------------------------------------------------------------------------ public function testTearDownSetupFails() : void { var fails : SetupErrorTearDownTestCase = new SetupErrorTearDownTestCase("testSuccess"); verifyError( fails ); Assert.assertFalse( fails.expectedResult ); } //------------------------------------------------------------------------------ public function testWasRun() : void { var test : SuccessTestCase = new SuccessTestCase("testSuccess"); test.run(); Assert.assertTrue( test.expectedResult ); } //------------------------------------------------------------------------------ public function testExceptionRunningAndTearDown() : void { var t : TestCase = new TearDownErrorTestCase("testSuccess"); var result : TestResult = new TestResult(); t.runWithResult( result ); var failure : TestFailure = TestFailure ( result.errorsIterator().next() ); Assert.assertEquals( "tearDown", failure.thrownException().message ); } //------------------------------------------------------------------------------ //MATT: since the automatic test creation doesn't work anymore and we've verified other no-arg tests (in SuccessTestCase) //we should be cool without this one /* public function testNoArgTestCasePasses() : void { var t : Test = new TestSuite( NoArgTestCase ); var result : TestResult = new TestResult(); t.runWithResult( result ); Assert.assertEquals( 1, result.runCount() ); Assert.assertEquals( 0, result.failureCount() ); Assert.assertEquals( 0, result.errorCount() ); } */ //------------------------------------------------------------------------------ public function testNamelessTestCase() : void { var test : TestCase = new TestCase(); var result : TestResult = test.run(); Assert.assertEquals( "runCount", 1, result.runCount() ); Assert.assertEquals( "failures", 1, result.failureCount() ); Assert.assertEquals( "errors", 0, result.errorCount() ); Assert.assertEquals( "No test method to run", TestFailure(result.failuresIterator().next()).thrownException().message ); /* try { t.run(); fail(); } catch ( e: AssertionFailedError ) { } */ } //------------------------------------------------------------------------------ private function verifyError( test : TestCase , errorCount : int = 1) : void { var result : TestResult = test.run(); Assert.assertEquals( 1, result.runCount() ); Assert.assertEquals( 0, result.failureCount() ); Assert.assertEquals( errorCount, result.errorCount() ); } //------------------------------------------------------------------------------ private function verifyFailure( test : TestCase ) : void { var result : TestResult = test.run(); Assert.assertEquals( 1, result.runCount() ); Assert.assertEquals( 1, result.failureCount() ); Assert.assertEquals( 0, result.errorCount() ); } //------------------------------------------------------------------------------ private function verifySuccess( test : TestCase ) : void { var result : TestResult = test.run(); Assert.assertEquals( 1, result.runCount() ); Assert.assertEquals( 0, result.failureCount() ); Assert.assertEquals( 0, result.errorCount() ); } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is [Open Source Virtual Machine.]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2005-2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package P { public namespace Baseball; public class Game{ Baseball var teamName = "Giants"; use namespace Baseball; } } var SECTION = "Directives"; // provide a document reference (ie, Actionscript section) var VERSION = "AS 3.0"; // Version of ECMAScript or ActionScript var TITLE = "namespace inside package"; // Provide ECMA section title or a description var BUGNUMBER = ""; startTest(); // leave this alone import P.*; var game = new Game(); AddTestCase( "Baseball var teamName = 'Giants'", "Giants", game.Baseball::teamName ); var teamName = "Test" AddTestCase( "Baseball var teamName = 'Test'", "Test", teamName ); test(); // leave this alone. this executes the test cases and // displays results.
/* * 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.speech.googlespeech.data { import temple.data.result.DataResult; /** * @author Arjan van Wijk */ public class GoogleSpeechResult extends DataResult { public function GoogleSpeechResult(data:*, success:Boolean = true, message:String = null, code:String = null) { super(data, success, message, code); } public function set data(value:GoogleSpeechResultData):void { data = value; } override public function get code():String { return data ? GoogleSpeechResultData(data).status.toString() : "10"; } } }
package cmodule.decry { function AS3_TypeOf(param1:*) : String { return typeof param1; } }
package { import flash.display.Loader; /** * ... * @author santiago */ public class GameLoader extends Loader { public function GameLoader() { super(); } public var box:Object = null; public var tag:Object = new Object(); public function isVisible():Boolean{ return (this.y>0 && this.visible); } } }
/******************************************************************************* * PushButton Engine * Copyright (C) 2009 PushButton Labs, LLC * For more information see http://www.pushbuttonengine.com * * This file is licensed under the terms of the MIT license, which is included * in the License.html file at the root directory of this SDK. ******************************************************************************/ package com.pblabs.engine.resource { import com.pblabs.engine.PBE; import com.pblabs.engine.PBUtil; import com.pblabs.engine.debug.Logger; import com.pblabs.engine.pb_internal; import com.pblabs.engine.resource.provider.EmbeddedResourceProvider; import com.pblabs.engine.resource.provider.FallbackResourceProvider; import com.pblabs.engine.resource.provider.IResourceProvider; import com.pblabs.engine.serialization.TypeUtility; import flash.events.Event; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; /** * The resource manager handles all tasks related to using asset files (images, xml, etc) * in a project. This includes loading files, managing embedded resources, and cleaninp up * resources no longer in use. */ public class ResourceManager { public static const RESOURCE_KEY_SPLITTER:String = "|*|"; /** * If true, we will never get resources from outside the SWF - only resources * that have been properly embedded and registered with the ResourceManager * will be used. */ public var onlyLoadEmbeddedResources:Boolean = false; /** * Function that will be called if OnlyLoadEmbeddedResources is set and we * fail to find something. Useful for displaying feedback for artists (such * as via a dialog box ;). Passed the filename of the requested resource. */ public var onEmbeddedFail:Function; /** * Loads a resource from a file. If the resource has already been loaded or is embedded, a * reference to the existing resource will be given. The resource is not returned directly * since loading is asynchronous. Instead, it will be passed to the function specified in * the onLoaded parameter. Even if the resource has already been loaded, it cannot be * assumed that the callback will happen synchronously. * * <p>This will not attempt to load resources that have previously failed to load. Instead, * the load will fail instantly.</p> * * @param filename The url of the file to load. * @param resourceType The Resource subclass specifying the type of resource that is being * requested. * @param onLoaded A function that will be called on successful load of the resource. The * function should take a single parameter of the type specified in the resourceType * parameter. * @param onFailed A function that will be called if loading of the resource fails. The * function should take a single parameter of the type specified in the resourceType * parameter. The resource passed to the function will be invalid, but the filename * property will be correct. * @param forceReload Always reload the resource, even if it has already been loaded. * * @see Resource */ public function load(filename:String, resourceType:Class, onLoaded:Function = null, onFailed:Function = null, forceReload:Boolean = false):Resource { // Sanity! if(filename == null || filename == "") { Logger.error(this, "load", "Cannot load a " + resourceType + " with empty filename."); return null; } // Look up the resource. var resourceIdentifier:String = getResourceIdentifier(filename, resourceType); var resource:Resource = _resources[resourceIdentifier]; // If it was loaded and we want to force a reload, do that. if (resource && forceReload) { _resources[resourceIdentifier] = null; delete _resources[resourceIdentifier]; resource = null; } // If it wasn't loaded... if (!resource) { // Then it wasn't embedded, so error if we're configured for that. if(onlyLoadEmbeddedResources && !EmbeddedResourceProvider.instance.isResourceKnown(filename, resourceType)) { var tmpR:Resource = new Resource(); tmpR.filename = filename; tmpR.fail("not embedded in the SWF with type " + resourceType + "."); fail(tmpR, onFailed, "'" + filename + "' was not loaded because it was not embedded in the SWF with type " + resourceType + "."); if(onEmbeddedFail != null) onEmbeddedFail(filename); return null; } // Hack for MP3 and WAV files. TODO: Generalize this for arbitrary formats. var fileExtension:String = PBUtil.getFileExtension(filename).toLowerCase(); if(resourceType == SoundResource && (fileExtension == "mp3" || fileExtension == "wav")) resourceType = MP3Resource; // check available resource providers and request the resource if it is known for (var rp:int = 0; rp < resourceProviders.length; rp++) { if ((resourceProviders[rp] as IResourceProvider).isResourceKnown(filename, resourceType)) resource = (resourceProviders[rp] as IResourceProvider).getResource(filename, resourceType, forceReload); } // If we couldn't find a match, fall back to the default provider. if (!resource) resource = FallbackResourceProvider.instance.getResource(filename, resourceType, forceReload); // Make sure the filename is set. if(!resource.filename) resource.filename = filename; // Store it in the resource dictionary. _resources[resourceIdentifier] = resource; } else if (!(resource is resourceType)) { fail(resource, onFailed, "The resource " + filename + " is already loaded, but is of type " + TypeUtility.getObjectClassName(resource) + " rather than the specified " + resourceType + "."); return null; } // Deal with it if it already failed, already loaded, or if it is still pending. if (resource.didFail) { fail(resource, onFailed, "The resource " + filename + " has previously failed to load"); } else if (resource.isLoaded) { if (onLoaded != null) PBE.callLater(onLoaded, [ resource ]); } else { // Still in process, so just hook up to its events. if (onLoaded != null) resource.addEventListener(ResourceEvent.LOADED_EVENT, function (event:Event):void { onLoaded(resource); } ); if (onFailed != null) resource.addEventListener(ResourceEvent.FAILED_EVENT, function (event:Event):void { onFailed(resource); } ); } // Don't forget to bump its ref count. resource.incrementReferenceCount(); return resource; } /** * Unloads a previously loaded resource. This does not necessarily mean the resource * will be available for garbage collection. Resources are reference counted so if * the specified resource has been loaded multiple times, its reference count will * only decrease as a result of this. * * @param filename The url of the resource to unload. * @param resourceType The type of the resource to unload. */ public function unload(filename:String, resourceType:Class):void { var resourceIdentifier:String = getResourceIdentifier(filename, resourceType); if (!_resources[resourceIdentifier]) { Logger.warn(this, "Unload", "The resource from file " + filename + " of type " + resourceType + " is not loaded."); return; } _resources[resourceIdentifier].decrementReferenceCount(); if (_resources[resourceIdentifier].referenceCount < 1) { _resources[resourceIdentifier] = null; delete _resources[resourceIdentifier]; // unload with resourceProvider for (var rp:int = 0; rp < resourceProviders.length; rp++) { if ((resourceProviders[rp] as IResourceProvider).isResourceKnown(filename, resourceType)) { (resourceProviders[rp] as IResourceProvider).unloadResource(filename, resourceType); return; } } FallbackResourceProvider.instance.unloadResource(filename, resourceType); } } /** * Provide a source for resources to the ResourceManager. Once added, * the ResourceManager will use this IResourceProvider to try to fulfill * resource load requests. * * @param resourceProvider Provider to add. * @see IResourceProvider */ public function registerResourceProvider(resourceProvider:IResourceProvider):void { // check if resourceProvider is already registered if (resourceProviders.indexOf(resourceProvider) != -1) { Logger.warn(ResourceManager, "registerResourceProvider", "Tried to register ResourceProvider '" + resourceProvider + "' twice. Ignoring..."); return; } // add resourceProvider to list of known resourceProviders resourceProviders.push(resourceProvider); } /** * Check if a resource is loaded and ready to go. * @param filename Same as request to load() * @param resourceType Same as request to load(). * @return True if resource is loaded. */ public function isLoaded(filename:String, resourceType:Class):Boolean { var resourceIdentifier:String = getResourceIdentifier(filename, resourceType); if(!_resources[resourceIdentifier]) return false; var r:Resource = _resources[resourceIdentifier]; return r.isLoaded; } /** * Provides a resource if it is known. could be that it is not loaded yet. * @param filename Same as request to load() * @param resourceType Same as request to load(). * @return resource */ public function getResource(filename:String, resourceType:Class):Resource { return _resources[getResourceIdentifier(filename, resourceType)]; } /** * Properly mark a resource as failed-to-load. */ private function fail(resource:Resource, onFailed:Function, message:String):void { if(!resource) throw new Error("Tried to fail null resource."); Logger.error(this, "load", message); if (onFailed != null) PBE.callLater(onFailed, [resource]); } private function getResourceIdentifier(filename:String, resourceType:Class):String { return filename.toLowerCase() + RESOURCE_KEY_SPLITTER + getQualifiedClassName(resourceType); } /** * Dictionary of loaded resources indexed by resource name and type. */ private var _resources:Dictionary = new Dictionary(); /** * List of resource providers used to get resources. */ private var resourceProviders:Array = new Array(); /*** Helper methods for PBE not externally exposed ***/ pb_internal function getResources():Dictionary { return _resources; } pb_internal function getResourceByIdentifier(identifier:String):Resource { return _resources[identifier]; } } }
package com.codeazur.as3swf.data.actions.swf5 { import com.codeazur.as3swf.data.actions.*; public class ActionBitURShift extends Action implements IAction { public function ActionBitURShift(code:uint, length:uint) { super(code, length); } public function toString(indent:uint = 0):String { return "[ActionBitURShift]"; } } }
// Copyright (c) 2012, Unwrong Ltd. http://www.unwrong.com // All rights reserved. package cadetEditor2D.ui.overlays { import cadetEditor2D.ui.views.ICadetEditorView2D; import core.ui.components.IUIComponent; public interface ICadetEditorOverlay2D extends IUIComponent { function set view( value:ICadetEditorView2D ):void; function get view():ICadetEditorView2D; } }
package com.ankamagames.dofus.network.messages.game.alliance { import com.ankamagames.dofus.network.messages.game.social.SocialNoticeSetErrorMessage; import com.ankamagames.jerakine.network.CustomDataWrapper; import com.ankamagames.jerakine.network.ICustomDataInput; import com.ankamagames.jerakine.network.ICustomDataOutput; import com.ankamagames.jerakine.network.INetworkMessage; import com.ankamagames.jerakine.network.utils.FuncTree; import flash.utils.ByteArray; public class AllianceBulletinSetErrorMessage extends SocialNoticeSetErrorMessage implements INetworkMessage { public static const protocolId:uint = 5502; private var _isInitialized:Boolean = false; public function AllianceBulletinSetErrorMessage() { super(); } override public function get isInitialized() : Boolean { return super.isInitialized && this._isInitialized; } override public function getMessageId() : uint { return 5502; } public function initAllianceBulletinSetErrorMessage(reason:uint = 0) : AllianceBulletinSetErrorMessage { super.initSocialNoticeSetErrorMessage(reason); this._isInitialized = true; return this; } override public function reset() : void { super.reset(); this._isInitialized = false; } override public function pack(output:ICustomDataOutput) : void { var data:ByteArray = new ByteArray(); this.serialize(new CustomDataWrapper(data)); writePacket(output,this.getMessageId(),data); } override public function unpack(input:ICustomDataInput, length:uint) : void { this.deserialize(input); } override public function unpackAsync(input:ICustomDataInput, length:uint) : FuncTree { var tree:FuncTree = new FuncTree(); tree.setRoot(input); this.deserializeAsync(tree); return tree; } override public function serialize(output:ICustomDataOutput) : void { this.serializeAs_AllianceBulletinSetErrorMessage(output); } public function serializeAs_AllianceBulletinSetErrorMessage(output:ICustomDataOutput) : void { super.serializeAs_SocialNoticeSetErrorMessage(output); } override public function deserialize(input:ICustomDataInput) : void { this.deserializeAs_AllianceBulletinSetErrorMessage(input); } public function deserializeAs_AllianceBulletinSetErrorMessage(input:ICustomDataInput) : void { super.deserialize(input); } override public function deserializeAsync(tree:FuncTree) : void { this.deserializeAsyncAs_AllianceBulletinSetErrorMessage(tree); } public function deserializeAsyncAs_AllianceBulletinSetErrorMessage(tree:FuncTree) : void { super.deserializeAsync(tree); } } }
package { import flash.display.Sprite; import flash.events.Event; import flash.globalization.DateTimeFormatter; import flash.globalization.LocaleID; import flash.globalization.DateTimeStyle; import flash.utils.Dictionary; /** * ... * @author Huw Pritchard */ public class Main extends Sprite { public function Main() { var locale = "en-US"; var date:Date = new Date(2020, 10, 20, 1, 2, 3); var date2:Date = new Date(1999, 1, 1, 23, 59, 59); trace(date); trace(date2); var longDf:DateTimeFormatter = new DateTimeFormatter(locale, DateTimeStyle.LONG, DateTimeStyle.LONG); var mediumDf:DateTimeFormatter = new DateTimeFormatter(locale, DateTimeStyle.MEDIUM, DateTimeStyle.MEDIUM); var shortDf:DateTimeFormatter = new DateTimeFormatter(locale, DateTimeStyle.SHORT, DateTimeStyle.SHORT); var longDate:String = longDf.format(date); var mediumDate:String = mediumDf.format(date); var shortDate:String = shortDf.format(date); var expectedDate = "Friday, November 20, 2020 1:02:03 AM"; if (longDate == expectedDate) { trace("Passed"); } else { trace("Failed"); trace("Got: " + longDate + ", expected: " + expectedDate); } expectedDate = "Friday, November 20, 2020 1:02:03 AM"; if (mediumDate == expectedDate) { trace("Passed"); } else { trace("Failed"); trace("Got: " + mediumDate + ", expected: " + expectedDate); } expectedDate = "11/20/2020 1:02 AM"; if (shortDate == expectedDate) { trace("Passed"); } else { trace("Failed"); trace("Got: " + shortDate + ", expected: " + expectedDate); } var dtf:DateTimeFormatter = new DateTimeFormatter(locale); dtf.setDateTimePattern("yyyy-MM-dd 'at' hh:mm:ssa"); var customDate = dtf.format(date); expectedDate = "2020-11-20 at 01:02:03AM"; if (customDate == "2020-11-20 at 01:02:03AM") { trace("Passed"); } else { trace("Failed"); trace("Got: " + customDate + ", expected: " + expectedDate); } if (longDf.getDateStyle() == "long") { trace("Passed"); } else { trace("Failed"); } if (mediumDf.getDateStyle() == "medium") { trace("Passed"); } else { trace("Failed"); } if (shortDf.getDateStyle() == "short") { trace("Passed"); } else { trace("Failed"); } if (longDf.getTimeStyle() == "long") { trace("Passed"); } else { trace("Failed"); } if (mediumDf.getTimeStyle() == "medium") { trace("Passed"); } else { trace("Failed"); } if (shortDf.getTimeStyle() == "short") { trace("Passed"); } else { trace("Failed"); } var tests2:Dictionary = new Dictionary(); tests2["G"] = "A.D."; tests2["GG"] = "A.D."; tests2["GGG"] = "A.D."; tests2["GGGG"] = "A.D."; tests2["GGGGG"] = "A.D."; tests2["y"] = "2020"; tests2["yy"] = "20"; tests2["yyyy"] = "2020"; tests2["yyyyy"] = "2020"; tests2["M"] = "11"; tests2["MM"] = "11"; tests2["MMM"] = "Nov"; tests2["MMMM"] = "November"; tests2["MMMMM"] = "November"; tests2["d"] = "20"; tests2["dd"] = "20"; tests2["E"] = "Fri"; tests2["EE"] = "Fri"; tests2["EEEE"] = "Friday"; tests2["EEEEE"] = "Friday"; tests2["Q"] = ""; tests2["QQ"] = ""; tests2["QQQ"] = ""; tests2["QQQQ"] = ""; tests2["w"] = ""; tests2["ww"] = ""; tests2["W"] = ""; tests2["D"] = ""; tests2["DD"] = ""; tests2["DDD"] = ""; tests2["F"] = ""; tests2["a"] = "AM"; //tests2["p"] = "PM"; tests2["h"] = "1"; tests2["hh"] = "01"; tests2["hhh"] = "01"; tests2["H"] = "1"; tests2["HH"] = "01"; tests2["HHH"] = "01"; tests2["K"] = "1"; tests2["KK"] = "01"; tests2["k"] = "1"; tests2["kk"] = "01"; tests2["m"] = "2"; tests2["mm"] = "02"; tests2["s"] = "3"; tests2["ss"] = "03"; tests2["S"] = ""; tests2["SS"] = ""; tests2["SSS"] = ""; tests2["SSSS"] = ""; tests2["SSSSS"] = ""; tests2["z"] = ""; tests2["zz"] = ""; tests2["zzz"] = ""; tests2["zzzz"] = ""; tests2["Z"] = ""; tests2["ZZ"] = ""; tests2["ZZZ"] = ""; tests2["ZZZZ"] = ""; tests2["v"] = ""; tests2["vvvv"] = ""; for (var k:String in tests2) { var value:String = tests2[k]; var key:String = k; var dtf:DateTimeFormatter = new DateTimeFormatter(locale); dtf.setDateTimePattern(key); if (dtf.format(date) == value && dtf.lastOperationStatus == "noError") { trace("Passed"); } else { trace("Failed"); trace(key + ": Got" + ": " + dtf.format(date) + " expected: " + value); trace(""); } } var tests:Dictionary = new Dictionary(); tests["G"] = "A.D."; tests["GG"] = "A.D."; tests["GGG"] = "A.D."; tests["GGGG"] = "A.D."; tests["GGGGG"] = "A.D."; tests["y"] = "1999"; tests["yy"] = "99"; tests["yyyy"] = "1999"; tests["yyyyy"] = "1999"; tests["M"] = "2"; tests["MM"] = "02"; tests["MMM"] = "Feb"; tests["MMMM"] = "February"; tests["MMMMM"] = "February"; tests["d"] = "1"; tests["dd"] = "01"; tests["E"] = "Mon"; tests["EE"] = "Mon"; tests["EEEE"] = "Monday"; tests["EEEEE"] = "Monday"; tests["Q"] = ""; tests["QQ"] = ""; tests["QQQ"] = ""; tests["QQQQ"] = ""; tests["w"] = ""; tests["ww"] = ""; tests["W"] = ""; tests["D"] = ""; tests["DD"] = ""; tests["DDD"] = ""; tests["F"] = ""; tests["a"] = "PM"; //tests["p"] = "PM"; tests["h"] = "11"; tests["hh"] = "11"; tests["hhh"] = "11"; tests["H"] = "23"; tests["HH"] = "23"; tests["HHH"] = "23"; tests["K"] = "11"; tests["KK"] = "11"; tests["k"] = "23"; tests["kk"] = "23"; tests["m"] = "59"; tests["mm"] = "59"; tests["s"] = "59"; tests["ss"] = "59"; tests["S"] = ""; tests["SS"] = ""; tests["SSS"] = ""; tests["SSSS"] = ""; tests["SSSSS"] = ""; tests["z"] = ""; tests["zz"] = ""; tests["zzz"] = ""; tests["zzzz"] = ""; tests["Z"] = ""; tests["ZZ"] = ""; tests["ZZZ"] = ""; tests["ZZZZ"] = ""; tests["v"] = ""; tests["vvvv"] = ""; tests[""] = ""; //tests[" "] = ""; tests["-"] = "-"; tests["/"] = "/"; //tests[":"] = ":"; for (var k:String in tests) { var value:String = tests[k]; var key:String = k; var dtf:DateTimeFormatter = new DateTimeFormatter(locale); dtf.setDateTimePattern(key); if (dtf.format(date2) == value && dtf.lastOperationStatus == "noError") { trace("Passed"); } else { trace("Failed"); trace(key + ": Got" + ": " + dtf.format(date2) + " expected: " + value); trace(""); } } } } }
package com.ankamagames.dofus.network.enums { public class PvpArenaStepEnum { public static const ARENA_STEP_REGISTRED:uint = 0; public static const ARENA_STEP_WAITING_FIGHT:uint = 1; public static const ARENA_STEP_STARTING_FIGHT:uint = 2; public static const ARENA_STEP_UNREGISTER:uint = 3; public function PvpArenaStepEnum() { super(); } } }
/* * Copyright(c) 2007 yoshiweb.NET * * 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. * * The MIT License * http://www.opensource.org/licenses/mit-license.php */ import mx.transitions.OnEnterFrameBeacon; /** * 任意の間隔で関数を実行するクラス * * @description setInterval/setTimeout のフレーム版 * @usage <code> import net.yoshiweb.utils.FrameInterval; FrameInterval.setInterval(trace, 10, "10フレームごとに実行"); </code> <code> import net.yoshiweb.utils.FrameInterval; FrameInterval.setInterval(this, "test", 10); function test(){ trace("10フレームごとに実行"); } </code> * * @author Takano Yoshihiro * @since Flash Player 6 (ActionScript 2.0) * @version 0.20060831 * @history * 20060831 - 内包されたfunction対応 * 20060816 - setTimeout・clearTimeoutを追加 * 20060724 - 作成 */ class net.yoshiweb.utils.FrameInterval { private var CLASS_NAME:String = "[FrameInterval]"; private static var __initBeacon = OnEnterFrameBeacon.init(); // private static var _id:Number = 0; private static var _enterFrameObj:Array = new Array(); /** * コンストラクタ */ private function FrameInterval() { } /** * 繰り返し実行 * @param functionReference 呼び出される関数への参照。 * @param interval functionReference または methodName 関数に対する呼び出しの間隔 (フレーム数)。 * @param param functionReference または methodName に送られた関数に渡すパラメータ。複数のパラメータはカンマで区切ります。 param1 , param2 , ..., paramN * @param objectReference methodName で指定したメソッドを含むオブジェクト。 * @param methodName objectReference で指定したオブジェクトのスコープ内に存在するメソッド。 * @return 間隔を識別するための整数 (インターバル ID)。 * @usage <code> setInterval(functionReference:Function, interval:Number, [param1:Object, param2, ..., paramN]) : Number setInterval(objectReference:Object, methodName:String, interval:Number, [param1:Object, param2, ..., paramN]) : Number </code> */ public static function setInterval():Number { if (arguments[0] == undefined) { return; } var obj:Object = _interval.apply(FrameInterval, arguments); _id++; _enterFrameObj[_id] = new Object(); _countDown(false, _enterFrameObj[_id], obj); return _id; } /** * 1回だけ実行 * @param functionReference 呼び出される関数への参照。 * @param interval functionReference または methodName 関数に対する呼び出しの間隔 (フレーム数)。 * @param param functionReference または methodName に送られた関数に渡すパラメータ。複数のパラメータはカンマで区切ります。 param1 , param2 , ..., paramN * @param objectReference methodName で指定したメソッドを含むオブジェクト。 * @param methodName objectReference で指定したオブジェクトのスコープ内に存在するメソッド。 * @return 間隔を識別するための整数 (インターバル ID)。 * @usage <code> setTimeout(functionReference:Function, interval:Number, [param1:Object, param2, ..., paramN]) : Number setTimeout(objectReference:Object, methodName:String, interval:Number, [param1:Object, param2, ..., paramN]) : Number </code> */ public static function setTimeout():Number { if (arguments[0] == undefined) { return; } var obj:Object = _interval.apply(FrameInterval, arguments); _id++; _enterFrameObj[_id] = new Object(); _countDown(true, _enterFrameObj[_id], obj); return _id; } /** * setIntervalを停止する * @param id 停止する関数のインターバルID * @return なし */ public static function clearInterval(id:Number):Void { _clear(id); } /** * setTimeoutを停止する * @param id 停止する関数のインターバルID * @return なし */ public static function clearTimeout(id:Number):Void { _clear(id); } // /** * パラメータを解析 * @return 解析した関数情報オブジェクト */ private static function _interval():Object { var target:Object; var method; var interval:Number; var args:Array; // var a0 = arguments[0]; var a1 = arguments[1]; var a2 = arguments[2]; // if (a0 instanceof Function && typeof (a1) == "number") { target = null; method = a0; interval = Math.max(0, Math.floor(a1)); args = [].concat(arguments.slice(2)); //} else if (a0[a1] instanceof Function && typeof (a2) == "number") { } else { target = a0; method = a0[a1]; if (method == undefined) { method = a1; } interval = Math.max(0, Math.floor(a2)); args = [].concat(arguments.slice(3)); } return {target:target, method:method, interval:interval, args:args}; } /** * 停止 * @param id 停止する関数のインターバルID * @return なし */ private static function _clear(id:Number):Void { MovieClip.removeListener(_enterFrameObj[id]); } /** * カウントダウン * @param timeout setTimeoutの場合 true。 * @param enterObj カウントダウンオブジェクト * @param obj 実行する関数の情報 * @return なし */ private static function _countDown(timeout:Boolean, enterObj:Object, obj:Object):Void { var target:Object = obj.target; var method = obj.method; var interval:Number = obj.interval; var args:Array = obj.args; // if (!(method instanceof Function)) { var methodName:String = obj.method; } // var count:Number = interval; enterObj.onEnterFrame = function() { count--; if (count<=0) { count = interval; if (!(method instanceof Function)) { method = target[methodName]; } // 実行 method.apply(target, args); if (timeout) { // setTimeoutの場合、終了 MovieClip.removeListener(this); } } }; MovieClip.addListener(enterObj); } // private function toString():String { return CLASS_NAME; } }
//////////////////////////////////////////////////////////////////////////////// // // 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. // //////////////////////////////////////////////////////////////////////////////// import mx.core.mx_internal; /** * @private * Version string for this class. */ mx_internal static const VERSION:String = "4.15.0.0";
package away3d.core.traverse { import away3d.arcane; import away3d.containers.*; import away3d.core.base.*; import away3d.core.clip.*; import away3d.core.draw.*; import away3d.core.geom.Frustum; import away3d.core.light.*; import away3d.core.math.*; import away3d.core.project.*; import away3d.core.render.*; import away3d.core.utils.*; import away3d.materials.*; import flash.utils.*; use namespace arcane; /** * Traverser that gathers drawing primitives to render the scene. */ public class PrimitiveTraverser extends Traverser { private var _view:View3D; private var _clipping:Clipping; private var _viewTransform:MatrixAway3D; private var _cameraVarsStore:CameraVarsStore; private var _nodeClassification:int; private var _consumer:IPrimitiveConsumer; private var _mouseEnabled:Boolean; private var _mouseEnableds:Array = new Array(); private var _projectorDictionary:Dictionary = new Dictionary(true); private var _light:ILightProvider; /** * Defines the view being used. */ public function get view():View3D { return _view; } public function set view(val:View3D):void { _view = val; _mouseEnabled = true; _mouseEnableds.length = 0; _cameraVarsStore = _view.cameraVarsStore; //setup the projector dictionary _projectorDictionary[ProjectorType.CONVEX_BLOCK] = _view._convexBlockProjector; _projectorDictionary[ProjectorType.DIR_SPRITE] = _view._dirSpriteProjector; _projectorDictionary[ProjectorType.DOF_SPRITE] = _view._dofSpriteProjector; _projectorDictionary[ProjectorType.MESH] = _view._meshProjector; _projectorDictionary[ProjectorType.MOVIE_CLIP_SPRITE] = _view._movieClipSpriteProjector; _projectorDictionary[ProjectorType.OBJECT_CONTAINER] = _view._objectContainerProjector; _projectorDictionary[ProjectorType.SPRITE] = _view._spriteProjector; } /** * Creates a new <code>PrimitiveTraverser</code> object. */ public function PrimitiveTraverser() { } /** * @inheritDoc */ public override function match(node:Object3D):Boolean { _clipping = _view.clipping; if (!node.visible || (_clipping.objectCulling && !_cameraVarsStore.nodeClassificationDictionary[node])) return false; if (node is ILODObject) return (node as ILODObject).matchLOD(_view.camera); return true; } /** * @inheritDoc */ public override function enter(node:Object3D):void { node;//TODO : FDT Warning _mouseEnableds.push(_mouseEnabled); } /** * @inheritDoc */ public override function apply(node:Object3D):void { if (node.session.updated) { _viewTransform = _cameraVarsStore.viewTransformDictionary[node]; _consumer = node.session.getConsumer(_view); if (node.projectorType) (_projectorDictionary[node.projectorType] as IPrimitiveProvider).primitives(node, _viewTransform, _consumer); if (node.debugbb && node.debugBoundingBox.visible) { node.debugBoundingBox._session = node.session; if (_clipping.objectCulling) { _cameraVarsStore.frustumDictionary[node.debugBoundingBox] = _cameraVarsStore.frustumDictionary[node]; _nodeClassification = _cameraVarsStore.nodeClassificationDictionary[node]; if (_nodeClassification == Frustum.INTERSECT) (node.debugBoundingBox.material as WireframeMaterial).color = 0xFF0000; else (node.debugBoundingBox.material as WireframeMaterial).color = 0x333333; } _view._meshProjector.primitives(node.debugBoundingBox, _viewTransform, _consumer); } if (node.debugbs && node.debugBoundingSphere.visible) { node.debugBoundingSphere._session = node.session; if (_clipping.objectCulling) { _cameraVarsStore.frustumDictionary[node.debugBoundingSphere] = _cameraVarsStore.frustumDictionary[node]; _nodeClassification = _cameraVarsStore.nodeClassificationDictionary[node]; if (_nodeClassification == Frustum.INTERSECT) (node.debugBoundingSphere.material as WireframeMaterial).color = 0xFF0000; else (node.debugBoundingSphere.material as WireframeMaterial).color = 0x00FFFF; } _view._meshProjector.primitives(node.debugBoundingSphere, _viewTransform, _consumer); } if (node is ILightProvider) { _light = node as ILightProvider; if (_light.debug) { _light.debugPrimitive._session = node.session; if (_clipping.objectCulling) _cameraVarsStore.frustumDictionary[_light.debugPrimitive] = _cameraVarsStore.frustumDictionary[_light]; _view._meshProjector.primitives(_light.debugPrimitive, _viewTransform, _consumer); } } } _mouseEnabled = node._mouseEnabled = (_mouseEnabled && node.mouseEnabled); } /** * @inheritDoc */ public override function leave(node:Object3D):void { node;//TODO : FDT Warning _mouseEnabled = _mouseEnableds.pop(); } } }
package kabam.rotmg.account.web.view { import kabam.lib.tasks.Task; import kabam.rotmg.account.core.signals.RegisterSignal; import kabam.rotmg.account.web.model.AccountData; import kabam.rotmg.core.signals.TaskErrorSignal; import kabam.rotmg.dialogs.control.CloseDialogsSignal; import kabam.rotmg.dialogs.control.OpenDialogSignal; import kabam.rotmg.game.signals.SetWorldInteractionSignal; import robotlegs.bender.bundles.mvcs.Mediator; public class WebRegisterMediator extends Mediator { [Inject] public var view:WebRegisterDialog; [Inject] public var closeDialog:CloseDialogsSignal; [Inject] public var openDialog:OpenDialogSignal; [Inject] public var register:RegisterSignal; [Inject] public var registrationError:TaskErrorSignal; [Inject] public var setWorldInteraction:SetWorldInteractionSignal; override public function initialize():void { this.view.register.add(this.onRegister); this.view.signIn.add(this.onSignIn); this.view.cancel.add(this.onCancel); this.registrationError.add(this.onRegistrationError); this.setWorldInteraction.dispatch(false); } override public function destroy():void { this.view.register.remove(this.onRegister); this.view.signIn.remove(this.onSignIn); this.view.cancel.remove(this.onCancel); this.registrationError.remove(this.onRegistrationError); this.setWorldInteraction.dispatch(true); } private function onRegister(_arg1:AccountData):void { this.view.disable(); this.register.dispatch(_arg1); } private function onCancel():void { this.closeDialog.dispatch(); } private function onSignIn():void { this.openDialog.dispatch(new WebLoginDialog()); } private function onRegistrationError(_arg1:Task):void { this.view.displayServerError(_arg1.error); this.view.enable(); } } }
package kabam.rotmg.assets { import mx.core.*; [Embed(source="EmbeddedAssets_lofiParticlesShockerEmbed_.png")] public class EmbeddedAssets_lofiParticlesShockerEmbed_ extends BitmapAsset { public function EmbeddedAssets_lofiParticlesShockerEmbed_() { super(); } } }
/** * Copyright (c) 2012 - 2100 Sindney * * 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 bloom { import flash.display.DisplayObjectContainer; import flash.display.Shape; import flash.events.Event; import flash.events.MouseEvent; import bloom.brushes.BMPBrush; import bloom.brushes.ColorBrush; import bloom.core.Component; import bloom.core.ScaleBitmap; import bloom.themes.ThemeBase; /** * FormItem * * @author sindney */ public class FormItem extends Component { protected var _data:Array = null; protected var _selected:Boolean = false; protected var _bg:Shape; public function FormItem(p:DisplayObjectContainer = null) { super(p); _bg = new Shape(); addChild(_bg); brush = ThemeBase.FormItem; size(100, 20); buttonMode = true; tabEnabled = tabChildren = false; addEventListener(MouseEvent.CLICK, onMouseClick); } /** * Call this when data:Array is modified. */ public function dataChanged():void { _changed = true; invalidate(); } override protected function draw(e:Event):void { if (_changed) { _changed = false; } else { return; } var bmpBrush:BMPBrush; var colorBrush:ColorBrush; var scale:ScaleBitmap; _bg.graphics.clear(); if (brush is ColorBrush) { colorBrush = brush as ColorBrush; _bg.graphics.beginFill(colorBrush.colors[_selected ? 0 : 1]); } else if (brush is BMPBrush) { bmpBrush = brush as BMPBrush; scale = bmpBrush.bitmap[_selected ? 0 : 1]; scale.setSize(_width, _height); _bg.graphics.beginBitmapFill(scale.bitmapData); } _bg.graphics.drawRect(0, 0, _width, _height); _bg.graphics.endFill(); } private function onMouseClick(e:MouseEvent):void { selected = !_selected; } /////////////////////////////////// // getter/setters /////////////////////////////////// public function set data(a:Array):void { if (_data != a) { _data = a; _changed = true; invalidate(); } } public function get data():Array { return _data; } public function set selected(value:Boolean):void { if (_selected != value) { _selected = value; _changed = true; invalidate(); } } public function get selected():Boolean { return _selected; } /////////////////////////////////// // toString /////////////////////////////////// override public function toString():String { return "[bloom.FormItem]"; } } }
/* Copyright (c) 2008, Adobe Systems Incorporated All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Adobe Systems Incorporated nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package actionScripts.extResources.com.adobe.images { import flash.display.BitmapData; import flash.utils.ByteArray; /** * Class that converts BitmapData into a valid PNG */ public class PNGEncoder { /** * Created a PNG image from the specified BitmapData * * @param image The BitmapData that will be converted into the PNG format. * @return a ByteArray representing the PNG encoded image data. * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public static function encode(img:BitmapData):ByteArray { // Create output byte array var png:ByteArray = new ByteArray(); // Write PNG signature png.writeUnsignedInt(0x89504e47); png.writeUnsignedInt(0x0D0A1A0A); // Build IHDR chunk var IHDR:ByteArray = new ByteArray(); IHDR.writeInt(img.width); IHDR.writeInt(img.height); IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA IHDR.writeByte(0); writeChunk(png,0x49484452,IHDR); // Build IDAT chunk var IDAT:ByteArray= new ByteArray(); for(var i:int=0;i < img.height;i++) { // no filter IDAT.writeByte(0); var p:uint; var j:int; if ( !img.transparent ) { for(j=0;j < img.width;j++) { p = img.getPixel(j,i); IDAT.writeUnsignedInt( uint(((p&0xFFFFFF) << 8)|0xFF)); } } else { for(j=0;j < img.width;j++) { p = img.getPixel32(j,i); IDAT.writeUnsignedInt( uint(((p&0xFFFFFF) << 8)| (p>>>24))); } } } IDAT.compress(); writeChunk(png,0x49444154,IDAT); // Build IEND chunk writeChunk(png,0x49454E44,null); // return PNG return png; } private static var crcTable:Array; private static var crcTableComputed:Boolean = false; private static function writeChunk(png:ByteArray, type:uint, data:ByteArray):void { if (!crcTableComputed) { crcTableComputed = true; crcTable = []; var c:uint; for (var n:uint = 0; n < 256; n++) { c = n; for (var k:uint = 0; k < 8; k++) { if (c & 1) { c = uint(uint(0xedb88320) ^ uint(c >>> 1)); } else { c = uint(c >>> 1); } } crcTable[n] = c; } } var len:uint = 0; if (data != null) { len = data.length; } png.writeUnsignedInt(len); var p:uint = png.position; png.writeUnsignedInt(type); if ( data != null ) { png.writeBytes(data); } var e:uint = png.position; png.position = p; c = 0xffffffff; for (var i:int = 0; i < (e-p); i++) { c = uint(crcTable[ (c ^ png.readUnsignedByte()) & uint(0xff)] ^ uint(c >>> 8)); } c = uint(c^uint(0xffffffff)); png.position = e; png.writeUnsignedInt(c); } } }
package com.ankamagames.dofus.logic.game.common.actions.party { import com.ankamagames.dofus.misc.utils.AbstractAction; import com.ankamagames.jerakine.handlers.messages.Action; public class PartyShowMenuAction extends AbstractAction implements Action { public var playerId:Number; public var partyId:int; public function PartyShowMenuAction(params:Array = null) { super(params); } public static function create(pPlayerId:Number, pPartyId:int) : PartyShowMenuAction { var a:PartyShowMenuAction = new PartyShowMenuAction(arguments); a.playerId = pPlayerId; a.partyId = pPartyId; return a; } } }
/* Copyright (c) 2009 by contributors: * James Hight (http://labs.zavoo.com/) * Richard R. Masters 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.svgweb.nodes { import org.svgweb.core.SVGNode; import flash.events.Event; public class SVGScriptNode extends SVGNode { public function SVGScriptNode(svgRoot:SVGSVGNode, xml:XML=null, original:SVGNode=null) { super(svgRoot, xml, original); } override protected function drawNode(event:Event = null):void { this.topSprite.removeEventListener(Event.ENTER_FRAME, drawNode); //Don't reset _invalidDisplay //This way drawNode is only called once //this._invalidDisplay = false; var content:String; if (this._xml.children().length() > 0) { content = this._xml.children()[0].text().toString(); this.svgRoot.handleScript(content); } this.topSprite.visible = false; this.svgRoot.renderFinished(); } } }
package { import flash.display.MovieClip; public dynamic class FarmMarker extends MovieClip { public function FarmMarker() { super(); addFrameScript(0,this.frame1,1,this.frame2); } function frame1() : * { stop(); } function frame2() : * { stop(); } } }
/* * Copyright 2011 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.command { import org.spicefactory.lib.command.builder.CommandProxyBuilder; import org.spicefactory.parsley.command.impl.DefaultManagedCommandProxy; import org.spicefactory.parsley.core.command.ManagedCommandProxy; import org.spicefactory.parsley.core.context.Context; /** * A builder DSL for creating command instances that are managed by the container. * This API adds on top of the standalone Spicelib Commands builder APIs the ability * to let commands get managed by a Parsley Context during execution. * * @author Jens Halm */ public class ManagedCommandBuilder { private var builder:CommandProxyBuilder; private var proxy:DefaultManagedCommandProxy; private var _id:String; /** * @private */ function ManagedCommandBuilder (target:Object) { this.proxy = new DefaultManagedCommandProxy(); builder = new CommandProxyBuilder(target, proxy); } /** * The identifier of the managed command. * The id is optional and can be used for identifying matching command observers. * * @param the identifier of the managed command * @return this builder instance for method chaining */ public function id (value:String) : ManagedCommandBuilder { _id = value; return this; } /** * Sets the timeout for the command execution. When the specified * amount of time is elapsed the command will abort with an error. * * @param milliseconds the timeout for the command execution in milliseconds * @return this builder instance for method chaining */ public function timeout (milliseconds:uint) : ManagedCommandBuilder { builder.timeout(milliseconds); return this; } /** * Adds a value that can get passed to the command * executed by the proxy this builder creates. * * @param value the value to pass to the command * @return this builder instance for method chaining */ public function data (value:Object) : ManagedCommandBuilder { builder.data(value); return this; } /** * Adds a callback to invoke when the command completes successfully. * The result produced by the command will get passed to the callback. * * @param callback the callback to invoke when the command completes successfully * @return this builder instance for method chaining */ public function result (callback:Function) : ManagedCommandBuilder { builder.result(callback); return this; } /** * Adds a callback to invoke when the command produced an error. * The cause of the error will get passed to the callback. * * @param callback the callback to invoke when the command produced an error * @return this builder instance for method chaining */ public function error (callback:Function) : ManagedCommandBuilder { builder.error(callback); return this; } /** * Adds a callback to invoke when the command gets cancelled. * The callback should not expect any parameters. * * @param callback the callback to invoke when the command gets cancelled * @return this builder instance for method chaining */ public function cancel (callback:Function) : ManagedCommandBuilder { builder.cancel(callback); return this; } /** * Builds the target command without executing it, applying all configurations specified * through this builder instance and associating it with the specified * Context. * * @param the Context that is responsible for managing the command created by this builder * @return the command proxy will all configuration of this builder applied */ public function build (context:Context) : ManagedCommandProxy { builder.domain(context.domain); proxy.id = _id; proxy.context = context; builder.build(); return proxy; } /** * Builds and executes the target command. * A shortcut for calling <code>build().execute()</code>. * In case of asynchronous commands the returned proxy * will still be active. In case of synchronous commands * it will already be completed, so that adding event * listeners won't have any effect. * * @param the Context that is responsible for managing the command created by this builder * @return the command that was built and executed by this builder */ public function execute (context:Context) : ManagedCommandProxy { var com:ManagedCommandProxy = build(context); com.execute(); return com; } } }
// Decompiled by AS3 Sorcerer 6.08 // www.as3sorcerer.com //kabam.rotmg.startup.model.impl.TaskDelegate package kabam.rotmg.startup.model.impl { import kabam.rotmg.startup.model.api.StartupDelegate; import org.swiftsuspenders.Injector; import kabam.lib.tasks.Task; public class TaskDelegate implements StartupDelegate { public var injector:Injector; public var taskClass:Class; public var priority:int; public function getPriority():int { return (this.priority); } public function make():Task { return (this.injector.getInstance(this.taskClass)); } } }//package kabam.rotmg.startup.model.impl
package com.ankamagames.dofus.network.messages.game.context.roleplay.havenbag { 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 EditHavenBagFinishedMessage extends NetworkMessage implements INetworkMessage { public static const protocolId:uint = 2273; public function EditHavenBagFinishedMessage() { super(); } override public function get isInitialized() : Boolean { return true; } override public function getMessageId() : uint { return 2273; } public function initEditHavenBagFinishedMessage() : EditHavenBagFinishedMessage { return this; } override public function reset() : void { } 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 { } public function serializeAs_EditHavenBagFinishedMessage(output:ICustomDataOutput) : void { } public function deserialize(input:ICustomDataInput) : void { } public function deserializeAs_EditHavenBagFinishedMessage(input:ICustomDataInput) : void { } public function deserializeAsync(tree:FuncTree) : void { } public function deserializeAsyncAs_EditHavenBagFinishedMessage(tree:FuncTree) : void { } } }
/* * Copyright 2019 Tallence AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tallence.core.redirects.studio.editor.grid.columns { import com.coremedia.cms.editor.sdk.editorContext; import com.tallence.core.redirects.studio.data.RedirectTargetParameter; import ext.grid.column.Column; use namespace editorContext; public class RedirectParametersColumnBase extends Column { public function RedirectParametersColumnBase(config:RedirectParametersColumn = null) { super(config); } protected function typeColRenderer(parameters:Array):String { var value:String = parameters && parameters.length > 0 ? "?" : ""; value = value + parameters.map(function (parameter:RedirectTargetParameter):String { return parameter.getName() + "=" + parameter.getValue(); }).join("&"); return value; } } }
package com.hurlant.eval.ast { public class LeftShift implements IAstBinOp {} }
package hansune.net { import flash.errors.IOError; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.ServerSocketConnectEvent; import flash.net.ServerSocket; import flash.net.Socket; import flash.utils.ByteArray; import hansune.events.NSocketEvent; /** * 바이트 어레이 데이터가 들어올 경우 * */ [Event(name="data", type="hansune.events.NSocketEvent")] /** * NServer 클라이언트 연결되었을 때 */ [Event(name="clientConnected", type="hansune.events.NSocketEvent")] /** * NServer 클라이언트 연결이 해제 되었을 때 */ [Event(name="clientDisconnected", type="hansune.events.NSocketEvent")] /** * NServer 서버가 bind 되었을 경우 */ [Event(name="open", type="flash.events.Event")] /** * 서버가 정지되었을 경우, end 명령에 의해 발생하지는 않으며, 운영체제에서 소켓을 닫을 때 발생 */ [Event(name="close", type="flash.events.Event")] /** *에러 이벤트 */ [Event(name="error", type="flash.events.ErrorEvent")] /** * 메시지 전달을 위한 기본 소켓서버, * writeUTFBytes, writeBytes 을 사용한다. * @author hansoo * */ public class NServer extends EventDispatcher { /** * 끊어지면 자동연결 할 껀가요? */ public var autoConnecting:Boolean = true; /** * whether tracing message or not */ public static var debug:Boolean = false; private var _host:String; private var _port:uint; private var serverSocket:ServerSocket; private var clientSockets:Vector.<Socket>; public function NServer(target:IEventDispatcher=null) { super(target); clientSockets = new Vector.<Socket>(); } public function get bound():Boolean { return serverSocket.bound; } /** * 소켓서버 정지 * */ public function end():void { if(serverSocket.bound){ serverSocket.close(); } var len:int = clientSockets.length; for(var i:int = 0; i<len; i++) { clientSockets[0].close(); clientSockets[0].removeEventListener(ProgressEvent.SOCKET_DATA, onClientSocketData); clientSockets[0].removeEventListener(Event.CLOSE, onClientClose); clientSockets[0].removeEventListener(IOErrorEvent.IO_ERROR, onClientIOError); clientSockets.splice(0,1); } } /** * 소켓서버를 시작한다. * @param port * @param localIp * */ public function bind(port:int, localIp:String):void { if(serverSocket != null){ if(serverSocket.bound){ serverSocket.close(); } serverSocket = null; } serverSocket = new ServerSocket(); _host = localIp; _port = port; try { serverSocket.bind(port, localIp); serverSocket.addEventListener(ServerSocketConnectEvent.CONNECT, onConnect); serverSocket.addEventListener(Event.CLOSE, onClose); serverSocket.listen(); trace( "Bound to: " + serverSocket.localAddress + ":" + serverSocket.localPort ); } catch (e:RangeError){ trace("RangeError : " + e.toString()); dispatchEvent(new ErrorEvent(ErrorEvent.ERROR,false, false, e.name + e.message, e.errorID)); return; } catch (e:IOError){ trace("IOError : " + e.toString()); dispatchEvent(new ErrorEvent(ErrorEvent.ERROR,false, false, e.name + e.message, e.errorID)); trace(clientSockets.length); return; } catch (e:ArgumentError) { trace("ArgumentError : " + e.toString()); dispatchEvent(new ErrorEvent(ErrorEvent.ERROR,false, false, e.name + e.message, e.errorID)); return; } dispatchEvent(new Event(Event.OPEN)); } //close 명령에 의해 발생하지는 않으며, 운영체제에서 소켓을 닫을 때 발생 private function onClose(e:Event):void { dispatchEvent(new Event(Event.CLOSE)); } /** * 연결되어 있는 모든 클라이언트에게 바이트어레이를 전송 * clientSockets[i].writeBytes(bytes); * @param bytes * @param excepts 제외시킬 소켓 */ public function sendBytes(bytes:ByteArray, excepts:Array = null):void { if(!serverSocket.bound || !serverSocket.listening) return; var i:int = 0; for (i = 0; i < clientSockets.length; i++) { if( clientSockets[i] == null || !clientSockets[i].connected ) { if(clientSockets[i] != null) { clientSockets[i].close(); clientSockets[i].removeEventListener(ProgressEvent.SOCKET_DATA, onClientSocketData); clientSockets[i].removeEventListener(Event.CLOSE, onClientClose); clientSockets[i].removeEventListener(IOErrorEvent.IO_ERROR, onClientIOError); } clientSockets.splice(i, 1); dispatchEvent(new NSocketEvent(NSocketEvent.CLIENT_DISCONNECTED, null, clientSockets[i])); } } if(excepts == null) excepts = []; for (i = 0; i < clientSockets.length; i++) { if( excepts.indexOf(clientSockets[i]) < 0) { clientSockets[i].writeBytes(bytes); clientSockets[i].flush(); } } } /** * 클라이언트에 스트링 데이터 전송<br/> * clientSockets[i].writeUTFBytes(str); * @param str * @param excepts 제외시킬 소켓 * */ public function send( str:String, excepts:Array = null ):void { if(!serverSocket.bound || !serverSocket.listening) return; var i:int; for (i = 0; i < clientSockets.length; i++) { if( clientSockets[i] == null || !clientSockets[i].connected ) { if(clientSockets[i] != null) { clientSockets[i].close(); clientSockets[i].removeEventListener(ProgressEvent.SOCKET_DATA, onClientSocketData); clientSockets[i].removeEventListener(Event.CLOSE, onClientClose); clientSockets[i].removeEventListener(IOErrorEvent.IO_ERROR, onClientIOError); } clientSockets.splice(i, 1); dispatchEvent(new NSocketEvent(NSocketEvent.CLIENT_DISCONNECTED, null, clientSockets[i])); } } if(excepts == null) excepts = []; for (i = 0; i < clientSockets.length; i++) { if( excepts.indexOf(clientSockets[i]) < 0) { clientSockets[i].writeUTFBytes(str); clientSockets[i].flush(); } } } private function onConnect( event:ServerSocketConnectEvent ):void { clientSockets.push(event.socket); event.socket.addEventListener(ProgressEvent.SOCKET_DATA, onClientSocketData); event.socket.addEventListener(Event.CLOSE, onClientClose); event.socket.addEventListener(IOErrorEvent.IO_ERROR, onClientIOError); dispatchEvent(new NSocketEvent(NSocketEvent.CLIENT_CONNECTED, null, event.socket)); } private function onClientClose(e:Event):void { var sock:Socket = e.currentTarget as Socket; sock.removeEventListener(ProgressEvent.SOCKET_DATA, onClientSocketData); sock.removeEventListener(Event.CLOSE, onClientClose); sock.removeEventListener(IOErrorEvent.IO_ERROR, onClientIOError); var index:int = clientSockets.indexOf(sock); if(index > -1) { clientSockets.splice(index, 1); } dispatchEvent(new NSocketEvent(NSocketEvent.CLIENT_DISCONNECTED, null, sock)); } private function onClientIOError(e:Event):void { var sock:Socket = e.currentTarget as Socket; sock.removeEventListener(ProgressEvent.SOCKET_DATA, onClientSocketData); sock.removeEventListener(Event.CLOSE, onClientClose); sock.removeEventListener(IOErrorEvent.IO_ERROR, onClientIOError); var index:int = clientSockets.indexOf(sock); if(index > -1) { clientSockets.splice(index, 1); } dispatchEvent(new NSocketEvent(NSocketEvent.CLIENT_DISCONNECTED, null, sock)); } private var buffer:ByteArray = new ByteArray(); private function onClientSocketData( e:ProgressEvent ):void { var sock:Socket = e.currentTarget as Socket; var data:ByteArray = new ByteArray(); sock.readBytes(data, 0, sock.bytesAvailable); dispatchEvent(new NSocketEvent(NSocketEvent.DATA, data, sock)); } } }
package robotlegs.bender.extensions.navigator.api { import flash.events.IEventDispatcher; import robotlegs.bender.extensions.navigator.behaviors.INavigationResponder; public interface INavigator extends IEventDispatcher { /** * Adds responders to the navigator. Every responder is matched to one or more states, * based on the supplied behavior. Omit the behavior paramater for auto-addition based on interface implementation. * * @param responder should implement a sub-interface of INavigationResponder. Check the behaviors package for details. * @param pathsOrStates - provide a string path, a typed NavigationState *or an array of both* to add the responder to. * @param behavior - provide a constant from the #NavigationBehaviors enumeration or omit for #NavigationBehaviors.AUTO */ function add(responder : INavigationResponder, pathsOrStates : *, behavior : String = null) : void; /** * Removes responders from the navigator per behavior or automatically. * If the responder is in the middle of a transition, it will be removed after the transition finishes. * * @param responder should implement a sub-interface of INavigationResponder. Check the behaviors package for details. * @param pathsOrStates - provide a string path, a typed NavigationState *or an array of both* to remove the responder from. * @param behavior - provide a constant from the #NavigationBehaviors enumeration or omit for #NavigationBehaviors.AUTO */ function remove(responder : INavigationResponder, pathsOrStates : *, behavior : String = null) : void; /** * If you want to provide shortcuts to deeper paths, like `/gallery/` pointing to `/gallery/main/1/`, * the registerRedirect is the way to go. Mind that there's also a more versatile behavior interface * called #IHasStateRedirection by which you can dynamically redirect the navigator in mid-validation. */ function registerRedirect(fromStateOrPath : *, toStateOrPath : *) : void; /** * Make sure you call this method before any other request calls. Part of the request logic * relies on a default state being set, this is the place to set it. */ function start(defaultStateOrPath : * = "", startStateOrPath : * = null) : void; /** * Request a new state by providing a #NavigationState instance. * If the new state is different from the current, it will be validated and granted. */ function request(stateOrPath : *) : void; /** * You can use this to retrieve the current state of the navigator. You shouldn't need it too * often if the behavior interfaces are implemented correctly, but every project has that * one exceptional scenario where it's quite handy. */ function get currentState() : NavigationState; } }
package alternativa.engine3d.spriteset.util { import alternativa.engine3d.core.VertexAttributes; import alternativa.engine3d.resources.Geometry; import flash.utils.ByteArray; import flash.utils.Dictionary; import flash.utils.Endian; import alternativa.engine3d.alternativa3d; import flash.utils.getQualifiedClassName; use namespace alternativa3d; /** * Utility to help work with Sprite3DSet and your own custom sprite materials! * @author Glenn Ko */ public class SpriteGeometryUtil { public static const REQUIRE_UVs:uint = 1; public static const REQUIRE_NORMAL:uint = 2; public static const REQUIRE_TANGENT:uint = 4; public static const ATTRIBUTE:uint = 20; // same attribute as used in MeshSet public static var MATERIAL_REQUIREMENTS:Dictionary = new Dictionary(); public static function guessRequirementsAccordingToMaterial(material:*):int { if (MATERIAL_REQUIREMENTS && MATERIAL_REQUIREMENTS[material.constructor]) return MATERIAL_REQUIREMENTS[material.constructor]; var classeName:String = getQualifiedClassName(material).split("::").pop(); if (MATERIAL_REQUIREMENTS && MATERIAL_REQUIREMENTS[classeName]) return MATERIAL_REQUIREMENTS[classeName]; switch (classeName) { case "Material": case "FillMaterial": return 0; case "TextureMaterial": return ( REQUIRE_UVs ); case "StandardMaterial": return ( REQUIRE_UVs ); return ( REQUIRE_UVs | REQUIRE_NORMAL | REQUIRE_TANGENT ); default: return ( REQUIRE_UVs | REQUIRE_NORMAL | REQUIRE_TANGENT ); } } public static function createNormalizedSpriteGeometry(numSprites:int, indexOffset:int, requirements:uint = 1, scale:Number=1, originX:Number=0, originY:Number=0, indexMultiplier:int=1):Geometry { var geometry:Geometry = new Geometry(); var attributes:Array = []; var i:int = 0; originX *= scale; originY *= scale; var indices:Vector.<uint> = new Vector.<uint>(); var vertices:ByteArray = new ByteArray(); vertices.endian = Endian.LITTLE_ENDIAN; var requireUV:Boolean = (requirements & REQUIRE_UVs)!=0; var requireNormal:Boolean = (requirements & REQUIRE_NORMAL)!=0; var requireTangent:Boolean = (requirements & REQUIRE_TANGENT)!=0; attributes[i++] = VertexAttributes.POSITION; attributes[i++] = VertexAttributes.POSITION; attributes[i++] = VertexAttributes.POSITION; if ( requireUV) { attributes[i++] = VertexAttributes.TEXCOORDS[0]; attributes[i++] = VertexAttributes.TEXCOORDS[0]; } if (requireNormal) { attributes[i++] = VertexAttributes.NORMAL; attributes[i++] = VertexAttributes.NORMAL; attributes[i++] = VertexAttributes.NORMAL; } if ( requireTangent) { attributes[i++] = VertexAttributes.TANGENT4; attributes[i++] = VertexAttributes.TANGENT4; attributes[i++] = VertexAttributes.TANGENT4; attributes[i++] = VertexAttributes.TANGENT4; } attributes[i++] = ATTRIBUTE; for (i = 0; i<numSprites;i++) { vertices.writeFloat(-1*scale - originX); vertices.writeFloat(-1*scale - originY); vertices.writeFloat(0); if ( requireUV) { vertices.writeFloat(0); vertices.writeFloat(1); } if ( requireNormal) { vertices.writeFloat(0); vertices.writeFloat(0); vertices.writeFloat(1); } if ( requireTangent) { vertices.writeFloat(1); vertices.writeFloat(0); vertices.writeFloat(0); vertices.writeFloat(-1); } vertices.writeFloat(i*indexMultiplier+indexOffset); vertices.writeFloat(1*scale - originX); vertices.writeFloat(-1*scale - originY); vertices.writeFloat(0); if ( requireUV) { vertices.writeFloat(1); vertices.writeFloat(1); } if ( requireNormal) { vertices.writeFloat(0); vertices.writeFloat(0); vertices.writeFloat(1); } if ( requireTangent) { vertices.writeFloat(1); vertices.writeFloat(0); vertices.writeFloat(0); vertices.writeFloat(-1); } vertices.writeFloat(i*indexMultiplier+indexOffset); vertices.writeFloat(1*scale - originX); vertices.writeFloat(1*scale - originY); vertices.writeFloat(0); if ( requireUV) { vertices.writeFloat(1); vertices.writeFloat(0); } if ( requireNormal) { vertices.writeFloat(0); vertices.writeFloat(0); vertices.writeFloat(1); } if ( requireTangent) { vertices.writeFloat(1); vertices.writeFloat(0); vertices.writeFloat(0); vertices.writeFloat(-1); } vertices.writeFloat(i*indexMultiplier+indexOffset); vertices.writeFloat(-1*scale - originX); vertices.writeFloat(1*scale - originY); vertices.writeFloat(0); if ( requireUV) { vertices.writeFloat(0); vertices.writeFloat(0); } if (requireNormal) { vertices.writeFloat(0); vertices.writeFloat(0); vertices.writeFloat(1); } if ( requireTangent) { vertices.writeFloat(1); vertices.writeFloat(0); vertices.writeFloat(0); vertices.writeFloat(-1); } vertices.writeFloat(i*indexMultiplier+indexOffset); var baseI:int = i * 4; indices.push(baseI, baseI+1, baseI+3, baseI+1, baseI+2, baseI+3); } geometry._indices = indices; geometry.addVertexStream(attributes); geometry._vertexStreams[0].data = vertices; geometry._numVertices = numSprites * 4; return geometry; } } }
/* 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.dragDrop { /** * Stores data associated with a drag and drop operation. * * @see feathers.dragDrop.DragDropManager * * @productversion Feathers 1.0.0 */ public class DragData { /** * Constructor. */ public function DragData() { } /** * @private */ protected var _data:Object = {}; /** * Determines if the specified data format is available. */ public function hasDataForFormat(format:String):Boolean { return this._data.hasOwnProperty(format); } /** * Returns data for the specified format. */ public function getDataForFormat(format:String):* { if(this._data.hasOwnProperty(format)) { return this._data[format]; } return undefined; } /** * Saves data for the specified format. */ public function setDataForFormat(format:String, data:*):void { this._data[format] = data; } /** * Removes all data for the specified format. */ public function clearDataForFormat(format:String):* { var data:* = undefined; if(this._data.hasOwnProperty(format)) { data = this._data[format]; } delete this._data[format]; return data; } } }
package com.swfwire.decompiler.data.swf3.tags { import com.swfwire.decompiler.data.swf.records.ClipActionsRecord; import com.swfwire.decompiler.data.swf.records.MatrixRecord; import com.swfwire.decompiler.data.swf.tags.SWFTag; import com.swfwire.decompiler.data.swf3.records.CXFormWithAlphaRecord; public class PlaceObject2Tag extends SWFTag { public var move:Boolean; public var depth:uint; public var characterId:Object; public var matrix:MatrixRecord; public var colorTransform:CXFormWithAlphaRecord; public var ratio:Object; public var name:String; public var clipDepth:Object; public var clipActions:ClipActionsRecord; public function PlaceObject2Tag(move:Boolean = false, depth:uint = 0, characterId:Object = null, matrix:MatrixRecord = null, colorTransform:CXFormWithAlphaRecord = null, ratio:Object = null, name:String = null, clipDepth:Object = null, clipActions:ClipActionsRecord = null) { this.move = move; this.depth = depth; this.characterId = characterId; this.matrix = matrix; this.colorTransform = colorTransform; this.ratio = ratio; this.name = name; this.clipDepth = clipDepth; this.clipActions = clipActions; } } }
/** * Created by hyh on 1/14/16. */ package starlingbuilder.editor { import feathers.data.ListCollection; import flash.geom.Point; import starling.core.Starling; import starling.display.DisplayObject; import starling.display.DisplayObject; import starling.display.DisplayObjectContainer; import starling.events.Touch; import starling.events.TouchEvent; import starling.events.TouchPhase; public class CITestUtil { public static function simulateTouch(target:DisplayObject, offsetX:Number = 0, offsetY:Number = 0, dx:Number = 0, dy:Number = 0):void { var position:Point = target.localToGlobal(new Point(offsetX, offsetY)); target = target.stage.hitTest(position, true); var touch:Touch = new Touch(0); touch.target = target; touch.phase = TouchPhase.BEGAN; touch.globalX = position.x; touch.globalY = position.y; var touches:Vector.<Touch> = new <Touch>[touch]; target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches)); touch.phase = TouchPhase.MOVED; target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches)); touch.globalX += dx; touch.globalY += dy; touch.phase = TouchPhase.MOVED; target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches)); touch.phase = TouchPhase.ENDED; target.dispatchEvent(new TouchEvent(TouchEvent.TOUCH, touches)); } public static function findDisplayObjectWithCondition(condition:Function, container:DisplayObjectContainer = null):DisplayObject { if (container == null) container = Starling.current.stage; for (var i:int = 0; i < container.numChildren; ++i) { var child:DisplayObject = container.getChildAt(i); if (condition(child)) return child; if (child is DisplayObjectContainer) { var obj:DisplayObject = findDisplayObjectWithCondition(condition, child as DisplayObjectContainer); if (obj) return obj; } } return null; } public static function findDisplayObject(options:Object, container:DisplayObjectContainer = null):DisplayObject { return findDisplayObjectWithCondition(function(obj:DisplayObject):Boolean{ for (var name:String in options) { var value:String = options[name]; if (obj.hasOwnProperty(name) && obj[name] == value) return true; if ("cls" in options && obj is options.cls) return true; } return false; }, container); } public static function findListCollectionIndex(listCollection:ListCollection, text:String):int { for (var i:int = 0; i < listCollection.length; ++i) { var item:Object = listCollection.getItemAt(i); if (item.label == text) return i; } return -1; } } }
/* Feathers Copyright 2012-2015 Joshua Tynjala. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.skins { import flash.utils.Dictionary; /** * Maps a component's states to values, perhaps for one of the component's * properties such as a skin or text format. */ public class StateValueSelector { /** * Constructor. */ public function StateValueSelector() { } /** * @private * Stores the values for each state. */ protected var stateToValue:Dictionary = new Dictionary(true); /** * If there is no value for the specified state, a default value can * be used as a fallback. */ public var defaultValue:Object; /** * Stores a value for a specified state to be returned from * getValueForState(). */ public function setValueForState(value:Object, state:Object):void { this.stateToValue[state] = value; } /** * Clears the value stored for a specific state. */ public function clearValueForState(state:Object):Object { var value:Object = this.stateToValue[state]; delete this.stateToValue[state]; return value; } /** * Returns the value stored for a specific state. */ public function getValueForState(state:Object):Object { return this.stateToValue[state]; } /** * Returns the value stored for a specific state. May generate a value, * if none is present. * * @param target The object receiving the stored value. The manager may query properties on the target to customize the returned value. * @param state The current state. * @param oldValue The previous value. May be reused for the new value. */ public function updateValue(target:Object, state:Object, oldValue:Object = null):Object { var value:Object = this.stateToValue[state]; if(!value) { value = this.defaultValue; } return value; } } }
/* * Copyright 2009 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.logging.flex { import org.spicefactory.parsley.core.bootstrap.BootstrapConfigProcessor; import org.spicefactory.lib.reflect.ClassInfo; import org.spicefactory.parsley.core.bootstrap.BootstrapConfig; import org.spicefactory.parsley.xml.mapper.XmlConfigurationNamespaceRegistry; /** * Provides a static method to initalize the Flex Logging XML tag extension. * Can be used as a child tag of a <code>&lt;ContextBuilder&gt;</code> tag in MXML alternatively. * * @author Jens Halm */ public class FlexLoggingXmlSupport implements BootstrapConfigProcessor { /** * The XML Namespace of the Flex Logging tag extension. */ public static const NAMESPACE_URI:String = "http://www.spicefactory.org/parsley/flex/logging"; private static var initialized:Boolean = false; /** * Initializes the Flex Logging XML tag extension. * Must be invoked before the <code>XmlContextBuilder</code> is used for the first time. */ public static function initialize () : void { if (initialized) return; XmlConfigurationNamespaceRegistry .getNamespace(NAMESPACE_URI) .newMapperBuilder(LogTargetTag, new QName(NAMESPACE_URI, "target")) .addPropertyHandler(new LogEventLevelAttributeHandler( ClassInfo.forClass(LogTargetTag).getProperty("level"), new QName("", "level"))); initialized = true; } /** * @private */ public function processConfig (config:BootstrapConfig) : void { initialize(); } } } import org.spicefactory.lib.reflect.Property; import org.spicefactory.lib.xml.XmlProcessorContext; import org.spicefactory.lib.xml.mapper.handler.AttributeHandler; import org.spicefactory.parsley.core.errors.ContextError; import mx.logging.LogEventLevel; class LogEventLevelAttributeHandler extends AttributeHandler { function LogEventLevelAttributeHandler (property:Property, xmlName:QName) { super(property, xmlName); } protected override function getValueFromNode (node:XML, context:XmlProcessorContext) : * { var value:String = super.getValueFromNode(node, context).toString().toUpperCase(); if (!(LogEventLevel[value] is int)) { throw new ContextError("Illegal value for log event level: " + value); } return LogEventLevel[value]; } }
//////////////////////////////////////////////////////////////////////////////// // // 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.events.Event; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.ui.Keyboard; import mx.core.IFlexDisplayObject; import mx.core.IFlexModuleFactory; import mx.core.mx_internal; import mx.events.FlexEvent; import mx.core.FlexVersion; import mx.core.IToggleButton; import mx.events.ItemClickEvent; import mx.managers.IFocusManager; import mx.managers.IFocusManagerGroup; import mx.core.UITextField; import mx.styles.CSSStyleDeclaration; import mx.styles.StyleManager; import flash.text.TextLineMetrics; import flash.utils.getQualifiedClassName; use namespace mx_internal; //-------------------------------------- // Styles //-------------------------------------- include "../styles/metadata/IconColorStyles.as" /** * Color of any symbol of a component. Examples include the check mark of a CheckBox or * the arrow of a ScrollBar button. * * @default 0x000000 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ [Style(name="symbolColor", type="uint", format="Color", inherit="yes", theme="spark")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name="emphasized", kind="property")] [Exclude(name="toggle", kind="property")] //-------------------------------------- // Other metadata //-------------------------------------- [AccessibilityClass(implementation="mx.accessibility.RadioButtonAccImpl")] [IconFile("RadioButton.png")] [ResourceBundle("controls")] [Alternative(replacement="spark.components.RadioButton", since="4.0")] /** * The RadioButton control lets the user make a single choice * within a set of mutually exclusive choices. * A RadioButton group is composed of two or more RadioButton controls * with the same <code>groupName</code> property. While grouping RadioButton instances * in a RadioButtonGroup is optional, a group lets you do things * like set a single event handler on a group of buttons, rather than * on each individual button. The RadioButton group can refer to a group created by the * <code>&lt;mx:RadioButtonGroup&gt;</code> tag. * The user selects only one member of the group at a time. * Selecting an unselected group member deselects the currently selected * RadioButton control within that group. * * <p>The RadioButton control has the following default characteristics:</p> * <table class="innertable"> * <tr> * <th>Characteristic</th> * <th>Description</th> * </tr> * <tr> * <td>Default size</td> * <td>Wide enough to display the text label of the control</td> * </tr> * <tr> * <td>Minimum size</td> * <td>0 pixels</td> * </tr> * <tr> * <td>Maximum size</td> * <td>Undefined</td> * </tr> * </table> * * @mxml * * <p>The <code>&lt;mx:RadioButton&gt;</code> tag inherits all of the tag * attributes of its superclass, and adds the following tag attributes:</p> * * <pre> * &lt;mx:RadioButton * <strong>Properties</strong> * groupName="" * labelPlacement="right|left|top|bottom" * * <strong>Styles</strong> * disabledIconColor="0x999999" * iconColor="0x2B333C" * /&gt; * </pre> * * @includeExample examples/RadioButtonExample.mxml * * @see mx.controls.RadioButtonGroup * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class RadioButton extends Button implements IFocusManagerGroup, IToggleButton { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Class mixins // //-------------------------------------------------------------------------- /** * @private * Placeholder for mixin by RadioButtonAccImpl. */ mx_internal static var createAccessibilityImplementation:Function; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function RadioButton() { super(); // Button variables. _labelPlacement = ""; _toggle = true; groupName = "radioGroup"; addEventListener(FlexEvent.ADD, addHandler); // Old padding logic variables centerContent = false; extraSpacing = 8; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Default inital index value */ mx_internal var indexNumber:int = 0; //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- //---------------------------------- // emphasized //---------------------------------- [Inspectable(environment="none")] /** * @private * A RadioButton doesn't have an emphasized state, so _emphasized * is set false in the constructor and can't be changed via this setter. */ override public function get emphasized():Boolean { return false; } //---------------------------------- // labelPlacement //---------------------------------- [Bindable("labelPlacementChanged")] [Inspectable(category="General", enumeration="left,right,top,bottom", defaultValue="right")] /** * Position of the label relative to the RadioButton icon. * Valid values in MXML are <code>"right"</code>, <code>"left"</code>, * <code>"bottom"</code>, and <code>"top"</code>. * * <p>In ActionScript, you use the following constants * to set this property: * <code>ButtonLabelPlacement.RIGHT</code>, * <code>ButtonLabelPlacement.LEFT</code>, * <code>ButtonLabelPlacement.BOTTOM</code>, and * <code>ButtonLabelPlacement.TOP</code>.</p> * * @default ButtonLabelPlacement.RIGHT * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function get labelPlacement():String { var value:String = ButtonLabelPlacement.RIGHT; if (_labelPlacement != "") value = _labelPlacement; else if (_group && _group.labelPlacement != "") value = _group.labelPlacement; return value; } /** * @private */ override public function set moduleFactory(factory:IFlexModuleFactory):void { super.moduleFactory = factory; if (FlexVersion.compatibilityVersion >= FlexVersion.VERSION_4_0) { var typeSelector:CSSStyleDeclaration = styleManager.getStyleDeclaration("mx.controls.RadioButton"); if (typeSelector) { if (typeSelector.getStyle("cornerRadius") === undefined) typeSelector.setStyle("cornerRadius", 7); } } } //---------------------------------- // toggle //---------------------------------- [Inspectable(environment="none")] /** * @private * A RadioButton is always toggleable by definition, so toggle is set * true in the constructor and can't be changed for a RadioButton. */ override public function get toggle():Boolean { return super.toggle; } /** * @private */ override public function set toggle(value:Boolean):void { } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // group //---------------------------------- /** * @private * Storage for the group property. */ private var _group:RadioButtonGroup; /** * The RadioButtonGroup object to which this RadioButton belongs. * * @default "undefined" * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get group():RadioButtonGroup { // Debugger asks too soon. if (!document) return _group; if (!_group) { if (groupName && groupName != "") { var g:RadioButtonGroup; try { g = RadioButtonGroup(document[groupName]); } catch(e:Error) { // UIComponent has a special automaticRadioButtonGroups slot. if (document.automaticRadioButtonGroups && document.automaticRadioButtonGroups[groupName]) { g = RadioButtonGroup( document.automaticRadioButtonGroups[groupName]); } } if (!g) { g = new RadioButtonGroup(IFlexDisplayObject(document)); if (!document.automaticRadioButtonGroups) document.automaticRadioButtonGroups = {}; document.automaticRadioButtonGroups[groupName] = g; } else if (!(g is RadioButtonGroup)) { return null; } _group = g; } } return _group; } /** * @private */ public function set group(value:RadioButtonGroup):void { _group = value; } //---------------------------------- // groupName //---------------------------------- /** * @private * Storage for groupName property. */ mx_internal var _groupName:String; /** * @private */ private var groupChanged:Boolean = false; [Bindable("groupNameChanged")] [Inspectable(category="General", defaultValue="radioGroup")] /** * Specifies the name of the group to which this RadioButton control belongs, or * specifies the value of the <code>id</code> property of a RadioButtonGroup control * if this RadioButton is part of a group defined by a RadioButtonGroup control. * * @default "undefined" * @throws ArgumentError Throws an ArgumentError if you are using Flex 4 or later and the groupName starts with the string "_fx_". * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get groupName():String { return _groupName; } /** * @private */ public function set groupName(value:String):void { // A groupName must be non-empty string. if (!value || value == "") return; // Since Halo and Spark share the same automaticRadioButtonGroups slot in // UIComponent, the Spark group names are decorated with a prefix to // differentiate. Spark group names can not start with the prefix. if (FlexVersion.compatibilityVersion >= FlexVersion.VERSION_4_0) { const FX_GROUP_NAME_PREFIX:String = "_fx_"; if (value.indexOf(FX_GROUP_NAME_PREFIX) == 0) { var message:String = resourceManager.getString( "controls", "invalidGroupName", [ value, FX_GROUP_NAME_PREFIX ]); throw ArgumentError(message); } } deleteGroup(); // Delete the old group _groupName = value; groupChanged = true; invalidateProperties(); invalidateDisplayList(); dispatchEvent(new Event("groupNameChanged")); } //---------------------------------- // value //---------------------------------- /** * @private * Storage for value property. */ private var _value:Object; [Bindable("valueChanged")] [Inspectable(category="General", defaultValue="")] /** * Optional user-defined value * that is associated with a RadioButton control. * * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get value():Object { return _value; } /** * @private */ public function set value(value:Object):void { _value = value; dispatchEvent(new Event("valueChanged")); if (selected && group) group.dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); } //-------------------------------------------------------------------------- // // Overridden methods: UIComponent // //-------------------------------------------------------------------------- /** * @private */ override protected function initializeAccessibility():void { if (RadioButton.createAccessibilityImplementation != null) RadioButton.createAccessibilityImplementation(this); } /** * @private * Update properties before measurement/layout. */ override protected function commitProperties():void { super.commitProperties(); if (groupChanged) { addToGroup(); groupChanged = false; } } /** * @private */ override protected function measure():void { super.measure(); if (!label && FlexVersion.compatibilityVersion >= FlexVersion.VERSION_4_0 && getQualifiedClassName(currentIcon).indexOf(".spark") >= 0) { // Adjust the height to account for text height, even when there // is no label. super.measure() handles non-null label case, so we just // handle null label case here var lineMetrics:TextLineMetrics = measureText(label); var textH:Number = lineMetrics.height + UITextField.TEXT_HEIGHT_PADDING; textH += getStyle("paddingTop") + getStyle("paddingBottom"); measuredMinHeight = measuredHeight = Math.max(textH, measuredMinHeight); } } /** * @private */ override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); if (groupChanged) { addToGroup(); groupChanged = false; } if (_group && _selected && _group.selection != this) group.setSelection(this, false); } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * Create radio button group if it does not exist * and add the instance to the group. */ private function addToGroup():Object { var g:RadioButtonGroup = group; // Trigger getting the group if (g) g.addInstance(this); return g; } /** * @private */ mx_internal function deleteGroup():void { try { if (document[groupName]) delete document[groupName]; } catch(e:Error) { try { if (document.automaticRadioButtonGroups[groupName]) delete document.automaticRadioButtonGroups[groupName]; } catch(e1:Error) { } } } /** * @private * Set next radio button in the group. */ private function setPrev(moveSelection:Boolean = true):void { var g:RadioButtonGroup = group; var fm:IFocusManager = focusManager; if (fm) fm.showFocusIndicator = true; for (var i:int = 1; i <= indexNumber; i++) { var radioButton:RadioButton = g.getRadioButtonAt(indexNumber - i); if (radioButton && radioButton.enabled) { if (moveSelection) g.setSelection(radioButton); radioButton.setFocus(); return; } } if (moveSelection && g.getRadioButtonAt(indexNumber) != g.selection) g.setSelection(this); this.drawFocus(true); } /** * @private * Set the previous radio button in the group. */ private function setNext(moveSelection:Boolean = true):void { var g:RadioButtonGroup = group; var fm:IFocusManager = focusManager; if (fm) fm.showFocusIndicator = true; for (var i:int = indexNumber + 1; i < g.numRadioButtons; i++) { var radioButton:RadioButton = g.getRadioButtonAt(i); if (radioButton && radioButton.enabled) { if (moveSelection) g.setSelection(radioButton); radioButton.setFocus(); return; } } if (moveSelection && g.getRadioButtonAt(indexNumber) != g.selection) g.setSelection(this); this.drawFocus(true); } /** * @private */ private function setThis():void { if (!_group) addToGroup(); var g:RadioButtonGroup = group; if (g.selection != this) g.setSelection(this); } //-------------------------------------------------------------------------- // // Overridden event handlers: UIComponent // //-------------------------------------------------------------------------- /** * @private * Support the use of keyboard within the group. */ override protected function keyDownHandler(event:KeyboardEvent):void { if (!enabled) return; // If rtl layout, need to swap LEFT and RIGHT so correct action // is done. var keyCode:uint = mapKeycodeForLayoutDirection(event); switch (keyCode) { case Keyboard.DOWN: { setNext(!event.ctrlKey); event.stopPropagation(); break; } case Keyboard.UP: { setPrev(!event.ctrlKey); event.stopPropagation(); break; } case Keyboard.LEFT: { setPrev(!event.ctrlKey); event.stopPropagation(); break; } case Keyboard.RIGHT: { setNext(!event.ctrlKey); event.stopPropagation(); break; } case Keyboard.SPACE: { setThis(); //disable toggling behavior for the RadioButton when //dealing with the spacebar since selection is maintained //by the group instead _toggle = false; //fall through, no break } default: { super.keyDownHandler(event); break; } } } /** * @private * Support the use of keyboard within the group. */ override protected function keyUpHandler(event:KeyboardEvent):void { super.keyUpHandler(event); if (event.keyCode == Keyboard.SPACE && !_toggle) { //we disabled _toggle for SPACE because we don't want to allow //de-selection, but now it needs to be re-enabled _toggle = true; } } /** * @private * When we are added, make sure we are part of our group. */ private function addHandler(event:FlexEvent):void { if (!_group && initialized) addToGroup(); } //-------------------------------------------------------------------------- // // Overridden event handlers: Button // //-------------------------------------------------------------------------- /** * @private * Set radio button to selected and dispatch that there has been a change. */ override protected function clickHandler(event:MouseEvent):void { if (!enabled || selected) return; // prevent a selected button from dispatching "click" if (!_group) addToGroup(); // Must call super.clickHandler() before setting // the group's selection. super.clickHandler(event); group.setSelection(this); // Dispatch an itemClick event from the RadioButtonGroup. var itemClickEvent:ItemClickEvent = new ItemClickEvent(ItemClickEvent.ITEM_CLICK); itemClickEvent.label = label; itemClickEvent.index = indexNumber; itemClickEvent.relatedObject = this; itemClickEvent.item = value; group.dispatchEvent(itemClickEvent); } } }
/** * VERSION: 1.769 * DATE: 2010-12-19 * AS3 * UPDATES AND DOCS AT: http://www.greensock.com/loadermax/ **/ package com.greensock.loading.display { import com.greensock.loading.core.LoaderItem; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Sprite; import flash.geom.Matrix; import flash.geom.Rectangle; import mx.core.UIComponent; /** * A container for visual content that is loaded by any of the following: ImageLoaders, SWFLoaders, * or VideoLoaders which is to be used in Flex. It is essentially a UIComponent that has a <code>loader</code> * property for easily referencing the original loader, as well as several other useful properties for * controling the placement of <code>rawContent</code> and the way it is scaled to fit (if at all). That way, * you can add a FlexContentDisplay to the display list or populate an array with as many as you want and then if * you ever need to unload() the content or reload it or figure out its url, etc., you can reference your * FlexContentDisplay's <code>loader</code> property like <code>myContent.loader.url</code> or * <code>(myContent.loader as SWFLoader).getClass("com.greensock.TweenLite");</code>. For * <br /><br /> * * <strong>IMPORTANT</strong>: In order for the LoaderMax loaders to use FlexContentDisplay instead of * the regular ContentDisplay class, you must set the <code>LoaderMax.contentDisplayClass</code> property * to FlexContentDisplay once like: * @example Example AS3 code:<listing version="3.0"> import com.greensock.loading.~~; import com.greensock.loading.display.~~; LoaderMax.contentDisplayClass = FlexContentDisplay; </listing> * * After that, all ImageLoaders, SWFLoaders, and VideoLoaders will return FlexContentDisplay objects * as their <code>content</code> instead of regular ContentDisplay objects. <br /><br /> * * <b>Copyright 2011, GreenSock. All rights reserved.</b> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership. * * @author Jack Doyle, jack@greensock.com */ public class FlexContentDisplay extends UIComponent { /** @private **/ protected static var _transformProps:Object = {x:1, y:1, scaleX:1, scaleY:1, rotation:1, alpha:1, visible:true, blendMode:"normal", centerRegistration:false, crop:false, scaleMode:"stretch", hAlign:"center", vAlign:"center"}; /** @private **/ protected var _loader:LoaderItem; /** @private **/ protected var _rawContent:DisplayObject; /** @private **/ protected var _centerRegistration:Boolean; /** @private **/ protected var _crop:Boolean; /** @private **/ protected var _scaleMode:String = "stretch"; /** @private **/ protected var _hAlign:String = "center"; /** @private **/ protected var _vAlign:String = "center"; /** @private **/ protected var _bgColor:uint; /** @private **/ protected var _bgAlpha:Number = 0; /** @private **/ protected var _fitWidth:Number; /** @private **/ protected var _fitHeight:Number; /** @private only used when crop is true - works around bugs in Flash with the way it reports getBounds() on objects with a scrollRect. **/ protected var _cropContainer:Sprite; /** @private A place to reference an object that should be protected from gc - this is used in VideoLoader in order to protect the NetStream object when the loader is disposed. **/ public var gcProtect:*; /** Arbitrary data that you can associate with the FlexContentDisplay instance. For example, you could set <code>data</code> to be an object containing various other properties or set it to an index number related to an array in your application. It is completely optional and arbitrary. **/ public var data:*; /** * Constructor * * @param loader The Loader object that will populate the FlexContentDisplay's <code>rawContent</code>. */ public function FlexContentDisplay(loader:LoaderItem) { super(); this.loader = loader; } /** * Removes the FlexContentDisplay from the display list (if necessary), dumps the <code>rawContent</code>, * and calls <code>unload()</code> and <code>dispose()</code> on the loader (unless you define otherwise with * the optional parameters). This essentially destroys the FlexContentDisplay and makes it eligible for garbage * collection internally, although if you added any listeners manually, you should remove them as well. * * @param unloadLoader If <code>true</code>, <code>unload()</code> will be called on the loader. It is <code>true</code> by default. * @param disposeLoader If <code>true</code>, <code>dispose()</code> will be called on the loader. It is <code>true</code> by default. */ public function dispose(unloadLoader:Boolean=true, disposeLoader:Boolean=true):void { if (this.parent != null) { if (this.parent.hasOwnProperty("removeElement")) { (this.parent as Object).removeElement(this); } else { this.parent.removeChild(this); } } this.rawContent = null; this.gcProtect = null; if (_loader != null) { if (unloadLoader) { _loader.unload(); } if (disposeLoader) { _loader.dispose(false); _loader = null; } } } /** @private **/ protected function _update():void { var left:Number = (_centerRegistration && _fitWidth > 0) ? _fitWidth / -2 : 0; var top:Number = (_centerRegistration && _fitHeight > 0) ? _fitHeight / -2 : 0; graphics.clear(); if (_fitWidth > 0 && _fitHeight > 0) { graphics.beginFill(_bgColor, _bgAlpha); graphics.drawRect(left, top, _fitWidth, _fitHeight); graphics.endFill(); } if (_rawContent == null) { return; } var mc:DisplayObject = _rawContent; var contentWidth:Number = mc.width; var contentHeight:Number = mc.height; if (_loader.hasOwnProperty("getClass")) { //for SWFLoaders, use loaderInfo.width/height so that everything is based on the stage size, not the bounding box of the DisplayObjects that happen to be on the stage (which could be much larger or smaller than the swf's stage) var m:Matrix = mc.transform.matrix; var loaderInfo:LoaderInfo = (mc is Loader) ? Object(mc).contentLoaderInfo : mc.loaderInfo; contentWidth = loaderInfo.width * Math.abs(m.a) + loaderInfo.height * Math.abs(m.b); contentHeight = loaderInfo.width * Math.abs(m.c) + loaderInfo.height * Math.abs(m.d); } if (_fitWidth > 0 && _fitHeight > 0) { var w:Number = _fitWidth; var h:Number = _fitHeight; var wGap:Number = w - contentWidth; var hGap:Number = h - contentHeight; if (_scaleMode != "none") { var displayRatio:Number = w / h; var contentRatio:Number = contentWidth / contentHeight; if ((contentRatio < displayRatio && _scaleMode == "proportionalInside") || (contentRatio > displayRatio && _scaleMode == "proportionalOutside")) { w = h * contentRatio; } if ((contentRatio > displayRatio && _scaleMode == "proportionalInside") || (contentRatio < displayRatio && _scaleMode == "proportionalOutside")) { h = w / contentRatio; } if (_scaleMode != "heightOnly") { mc.width *= w / contentWidth; wGap = _fitWidth - w; } if (_scaleMode != "widthOnly") { mc.height *= h / contentHeight; hGap = _fitHeight - h; } } if (_hAlign == "left") { wGap = 0; } else if (_hAlign != "right") { wGap /= 2; } if (_vAlign == "top") { hGap = 0; } else if (_vAlign != "bottom") { hGap /= 2; } if (_crop) { //due to bugs in the way Flash reports getBounds() on objects with a scrollRect, we need to just wrap the rawContent in a container and apply the scrollRect to the container. if (_cropContainer == null || mc.parent != _cropContainer) { _cropContainer = new Sprite(); this.addChildAt(_cropContainer, this.getChildIndex(mc)); _cropContainer.addChild(mc); } _cropContainer.x = left; _cropContainer.y = top; _cropContainer.scrollRect = new Rectangle(0, 0, _fitWidth, _fitHeight); mc.x = wGap; mc.y = hGap; } else { if (_cropContainer != null) { this.addChildAt(mc, this.getChildIndex(_cropContainer)); _cropContainer = null; } mc.x = left + wGap; mc.y = top + hGap; } } else { mc.x = (_centerRegistration) ? contentWidth / -2 : 0; mc.y = (_centerRegistration) ? contentHeight / -2 : 0; } measure(); } override protected function measure():void { var bounds:Rectangle = this.getBounds(this); this.explicitWidth = bounds.width; this.explicitHeight = bounds.height; if (this.parent) { bounds = this.getBounds(this.parent); this.width = bounds.width; this.height = bounds.height; } super.measure(); } //---- GETTERS / SETTERS ------------------------------------------------------------------------- /** * The width to which the <code>rawContent</code> should be fit according to the FlexContentDisplay's <code>scaleMode</code> * (this width is figured before rotation, scaleX, and scaleY). When a "width" property is defined in the loader's <code>vars</code> * property/parameter, it is automatically applied to this <code>fitWidth</code> property. For example, the following code will * set the loader's FlexContentDisplay <code>fitWidth</code> to 100:<code><br /><br /> * * var loader:ImageLoader = new ImageLoader("photo.jpg", {width:100, height:80, container:this});</code> * * @see #fitHeight * @see #scaleMode **/ public function get fitWidth():Number { return _fitWidth; } public function set fitWidth(value:Number):void { _fitWidth = value; _update(); } /** * The height to which the <code>rawContent</code> should be fit according to the FlexContentDisplay's <code>scaleMode</code> * (this height is figured before rotation, scaleX, and scaleY). When a "height" property is defined in the loader's <code>vars</code> * property/parameter, it is automatically applied to this <code>fitHeight</code> property. For example, the following code will * set the loader's FlexContentDisplay <code>fitHeight</code> to 80:<code><br /><br /> * * var loader:ImageLoader = new ImageLoader("photo.jpg", {width:100, height:80, container:this});</code> * * @see #fitWidth * @see #scaleMode **/ public function get fitHeight():Number { return _fitHeight; } public function set fitHeight(value:Number):void { _fitHeight = value; _update(); } /** * When the FlexContentDisplay's <code>fitWidth</code> and <code>fitHeight</code> properties are defined (or <code>width</code> * and <code>height</code> in the loader's <code>vars</code> property/parameter), the <code>scaleMode</code> controls how * the <code>rawContent</code> will be scaled to fit the area. The following values are recognized (you may use the * <code>com.greensock.layout.ScaleMode</code> constants if you prefer): * <ul> * <li><code>"stretch"</code> (the default) - The <code>rawContent</code> will fill the width/height exactly.</li> * <li><code>"proportionalInside"</code> - The <code>rawContent</code> will be scaled proportionally to fit inside the area defined by the width/height</li> * <li><code>"proportionalOutside"</code> - The <code>rawContent</code> will be scaled proportionally to completely fill the area, allowing portions of it to exceed the bounds defined by the width/height.</li> * <li><code>"widthOnly"</code> - Only the width of the <code>rawContent</code> will be adjusted to fit.</li> * <li><code>"heightOnly"</code> - Only the height of the <code>rawContent</code> will be adjusted to fit.</li> * <li><code>"none"</code> - No scaling of the <code>rawContent</code> will occur.</li> * </ul> **/ public function get scaleMode():String { return _scaleMode; } public function set scaleMode(value:String):void { if (value == "none" && _rawContent != null) { _rawContent.scaleX = _rawContent.scaleY = 1; } _scaleMode = value; _update(); } /** * If <code>true</code>, the FlexContentDisplay's registration point will be placed in the center of the <code>rawContent</code> * which can be useful if, for example, you want to animate its scale and have it grow/shrink from its center. * @see #scaleMode **/ public function get centerRegistration():Boolean { return _centerRegistration; } public function set centerRegistration(value:Boolean):void { _centerRegistration = value; _update(); } /** * When the FlexContentDisplay's <code>fitWidth</code> and <code>fitHeight</code> properties are defined (or <code>width</code> * and <code>height</code> in the loader's <code>vars</code> property/parameter), setting <code>crop</code> to * <code>true</code> will cause the <code>rawContent</code> to be cropped within that area (by applying a <code>scrollRect</code> * for maximum performance). This is typically useful when the <code>scaleMode</code> is <code>"proportionalOutside"</code> * or <code>"none"</code> so that any parts of the <code>rawContent</code> that exceed the dimensions defined by * <code>fitWidth</code> and <code>fitHeight</code> are visually chopped off. Use the <code>hAlign</code> and * <code>vAlign</code> properties to control the vertical and horizontal alignment within the cropped area. * * @see #scaleMode **/ public function get crop():Boolean { return _crop; } public function set crop(value:Boolean):void { _crop = value; _update(); } /** * When the FlexContentDisplay's <code>fitWidth</code> and <code>fitHeight</code> properties are defined (or <code>width</code> * and <code>height</code> in the loader's <code>vars</code> property/parameter), the <code>hAlign</code> determines how * the <code>rawContent</code> is horizontally aligned within that area. The following values are recognized (you may use the * <code>com.greensock.layout.AlignMode</code> constants if you prefer): * <ul> * <li><code>"center"</code> (the default) - The <code>rawContent</code> will be centered horizontally in the FlexContentDisplay</li> * <li><code>"left"</code> - The <code>rawContent</code> will be aligned with the left side of the FlexContentDisplay</li> * <li><code>"right"</code> - The <code>rawContent</code> will be aligned with the right side of the FlexContentDisplay</li> * </ul> * @see #scaleMode * @see #vAlign **/ public function get hAlign():String { return _hAlign; } public function set hAlign(value:String):void { _hAlign = value; _update(); } /** * When the FlexContentDisplay's <code>fitWidth</code> and <code>fitHeight</code> properties are defined (or <code>width</code> * and <code>height</code> in the loader's <code>vars</code> property/parameter), the <code>vAlign</code> determines how * the <code>rawContent</code> is vertically aligned within that area. The following values are recognized (you may use the * <code>com.greensock.layout.AlignMode</code> constants if you prefer): * <ul> * <li><code>"center"</code> (the default) - The <code>rawContent</code> will be centered vertically in the FlexContentDisplay</li> * <li><code>"top"</code> - The <code>rawContent</code> will be aligned with the top of the FlexContentDisplay</li> * <li><code>"bottom"</code> - The <code>rawContent</code> will be aligned with the bottom of the FlexContentDisplay</li> * </ul> * @see #scaleMode * @see #hAlign **/ public function get vAlign():String { return _vAlign; } public function set vAlign(value:String):void { _vAlign = value; _update(); } /** * When the FlexContentDisplay's <code>fitWidth</code> and <code>fitHeight</code> properties are defined (or <code>width</code> * and <code>height</code> in the loader's <code>vars</code> property/parameter), a rectangle will be drawn inside the * FlexContentDisplay object immediately in order to ease the development process (for example, you can add <code>ROLL_OVER/ROLL_OUT</code> * event listeners immediately). It is transparent by default, but you may define a <code>bgAlpha</code> if you prefer. * @see #bgAlpha * @see #fitWidth * @see #fitHeight **/ public function get bgColor():uint { return _bgColor; } public function set bgColor(value:uint):void { _bgColor = value; _update(); } /** * Controls the alpha of the rectangle that is drawn when the FlexContentDisplay's <code>fitWidth</code> and <code>fitHeight</code> * properties are defined (or <code>width</code> and <code>height</code> in the loader's <code>vars</code> property/parameter). * @see #bgColor * @see #fitWidth * @see #fitHeight **/ public function get bgAlpha():Number { return _bgAlpha; } public function set bgAlpha(value:Number):void { _bgAlpha = value; _update(); } /** The raw content which can be a Bitmap, a MovieClip, a Loader, or a Video depending on the type of loader associated with the FlexContentDisplay. **/ public function get rawContent():* { return _rawContent; } public function set rawContent(value:*):void { if (_rawContent != null && _rawContent != value) { if (_rawContent.parent == this) { removeChild(_rawContent); } else if (_cropContainer != null && _rawContent.parent == _cropContainer) { _cropContainer.removeChild(_rawContent); removeChild(_cropContainer); _cropContainer = null; } } _rawContent = value as DisplayObject; if (_rawContent == null) { return; } addChildAt(_rawContent as DisplayObject, 0); _update(); } /** The loader whose rawContent populates this FlexContentDisplay. If you get the loader's <code>content</code>, it will return this FlexContentDisplay object. **/ public function get loader():LoaderItem { return _loader; } public function set loader(value:LoaderItem):void { _loader = value; if (value == null) { return; } else if (!_loader.hasOwnProperty("setContentDisplay")) { throw new Error("Incompatible loader used for a FlexContentDisplay"); } this.name = _loader.name; var type:String; for (var p:String in _transformProps) { if (p in _loader.vars) { type = typeof(_transformProps[p]); this[p] = (type == "number") ? Number(_loader.vars[p]) : (type == "string") ? String(_loader.vars[p]) : Boolean(_loader.vars[p]); } } _bgColor = uint(_loader.vars.bgColor); _bgAlpha = ("bgAlpha" in _loader.vars) ? Number(_loader.vars.bgAlpha) : ("bgColor" in _loader.vars) ? 1 : 0; _fitWidth = ("fitWidth" in _loader.vars) ? Number(_loader.vars.fitWidth) : Number(_loader.vars.width); _fitHeight = ("fitHeight" in _loader.vars) ? Number(_loader.vars.fitHeight) : Number(_loader.vars.height); _update(); if (_loader.vars.container is DisplayObjectContainer) { if (_loader.vars.container.hasOwnProperty("addElement")) { (_loader.vars.container as Object).addElement(this); } else { (_loader.vars.container as DisplayObjectContainer).addChild(this); } } if (_loader.content != this) { (_loader as Object).setContentDisplay(this); } this.rawContent = (_loader as Object).rawContent; } } }
package com.longtailvideo.jwplayer.parsers { import com.longtailvideo.jwplayer.utils.Strings; /** * Parse a MRSS group into a playlistitem (used in RSS and ATOM). **/ public class MediaParser { /** Prefix for the JW Player namespace. **/ private static const PREFIX:String = 'media'; /** * Parse a feeditem for Yahoo MediaRSS extensions. * The 'content' and 'group' elements can nest other MediaRSS elements. * * @param obj The entire MRSS XML object. * @param itm The playlistentry to amend the object to. * @return The playlistentry, amended with the MRSS info. * @see ATOMParser * @see RSSParser **/ public static function parseGroup(obj:XML, itm:Object):Object { var ytp:Boolean = false; for each (var i:XML in obj.children()) { if (i.namespace().prefix == MediaParser.PREFIX) { switch (i.localName().toLowerCase()) { case 'content': if (!ytp) { itm['file'] = Strings.xmlAttribute(i, 'url'); } if (i.@duration.length() > 0) { itm['duration'] = Strings.seconds(Strings.xmlAttribute(i, 'duration')); } if (i.@start.length() > 0) { itm['start'] = Strings.seconds(Strings.xmlAttribute(i, 'start')); } if (i.children().length() > 0) { itm = MediaParser.parseGroup(i, itm); } if (i.@width.length() > 0 || i.@bitrate.length() > 0) { if (!itm.levels) { itm.levels = new Array(); } itm.levels.push({ width:Strings.xmlAttribute(i, 'width'), bitrate:Strings.xmlAttribute(i, 'bitrate'), file:Strings.xmlAttribute(i, 'url') }); } break; case 'title': itm['title'] = i.text().toString(); break; case 'description': itm['description'] = i.text().toString(); break; case 'keywords': itm['tags'] = i.text().toString(); break; case 'thumbnail': itm['image'] = Strings.xmlAttribute(i, 'url'); break; case 'credit': itm['author'] = i.text().toString(); break; case 'player': if (i.@url.indexOf('youtube.com') > 0) { ytp = true; itm['file'] = Strings.xmlAttribute(i, 'url'); } break; case 'group': itm = MediaParser.parseGroup(i, itm); break; } } } return itm; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.royale.html.elements { import org.apache.royale.core.UIBase; COMPILE::JS { import org.apache.royale.core.WrappedHTMLElement; import org.apache.royale.html.util.addElementToWrapper; } import org.apache.royale.html.TextNodeContainerBase; /** * The Small class represents an HTML <small> element * * * @toplevel * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9 */ public class Small extends TextNodeContainerBase { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9 */ public function Small() { super(); } COMPILE::JS override protected function createElement():WrappedHTMLElement { return addElementToWrapper(this,'small'); } } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * * See http://bugzilla.mozilla.org/show_bug.cgi?id=561249 * */ //----------------------------------------------------------------------------- import avmplus.System; import com.adobe.test.Assert; // var SECTION = "561249"; // var VERSION = ""; // var TITLE = "Specialized Addition Helper Functions"; // var bug = "561249"; var array:Array = new Array(); var item:int = 0; function VerifyEquals(actual, expect, a, b, ctx) { var status = ctx + " " + a + " + " + b; array[item++] = Assert.expectEq( status, expect, actual); } function canon(a) { return System.canonicalizeNumber(a); } function AddIntToAtom(a:int, b, c) { VerifyEquals(a + canon(b), c, a, b, "AddIntToAtom"); } function AddAtomToInt(a, b:int, c) { VerifyEquals(canon(a) + b, c, a, b, "AddAtomToInt"); } function AddDoubleToAtom(a:Number, b, c) { VerifyEquals(a + canon(b), c, a, b, "AddDoubleToAtom"); } function AddAtomToDouble(a, b:Number, c) { VerifyEquals(canon(a) + b, c, a, b, "AddAtomToDouble"); } function AddAtomToAtom(a, b, c) { VerifyEquals(canon(a) + canon(b), c, a, b, "AddAtomToAtom"); } var z = null; var z_n:Number = z; var n = new Namespace("http://www.example.com/"); var n_n:Number = n; var s = "foo"; var s_s:String = s; var o = new Object(); var o_s:String = o; var d = new Date(0); var d_s:String = d; var x = new XML("<a><b/></a>"); var x_s:String = x; var l = new XMLList("<a>one</a><b>two</b>"); var l_s:String = l; var int32_max = 2147483647; // We test cases in which a numeric value is added/concatenated to a non-numeric atom. // We characterize the value of the non-numeric atom as to whether it results in a numeric // addition or a string concatentation, i.e., behaves like a number or a string, when // combined with a number. function LikeNumber(i, a, a_n:Number) { var i_n:Number = i; //NOTE: We assume that typed Number + Number addition functions correctly. if (i <= int32_max) { AddIntToAtom (i, a, i_n + a_n); AddAtomToInt (a, i, a_n + i_n); } AddDoubleToAtom (i, a, i_n + a_n); AddAtomToDouble (a, i, a_n + i_n); AddAtomToAtom (i, a, i_n + a_n); AddAtomToAtom (a, i, a_n + i_n); } function LikeString(i, a, a_s:String) { var i_s:String = i; //NOTE: We assume that typed String + String concatenation functions correctly. if (i <= int32_max) { AddIntToAtom (i, a, i_s + a_s); AddAtomToInt (a, i, a_s + i_s); } AddDoubleToAtom (i, a, i_s + a_s); AddAtomToDouble (a, i, a_s + i_s); AddAtomToAtom (i, a, i_s + a_s); AddAtomToAtom (a, i, a_s + i_s); } function TryIntValue(i) { LikeNumber(i, z, z_n); // null LikeNumber(i, n, n_n); // Namespace LikeString(i, s, s_s); // String LikeString(i, o, o_s); // Object LikeString(i, d, d_s); // Date LikeString(i, x, x_s); // XML LikeString(i, l, l_s); // XMLList } var i = 555; // Fits in 29-bit intptr var j = 555555555; // Won't fit in 29-bit intptr var k = 5555555555555555; // Won't fit in 53-bit intptr function getTestCases() { TryIntValue(i); TryIntValue(j); TryIntValue(k); return array; } var testcases = getTestCases();
package age.extensions { import flash.errors.IllegalOperationError; import flash.geom.Point; import age.AGE; import age.data.TextureAsset; import age.renderers.SceneRenender; import starling.animation.IAnimatable; import starling.display.MovieClip; import starling.display.Sprite; import starling.events.Event; public class DamageFx { public function DamageFx() { // 没用的构造函数 } private static const DEFAULT_TEXTURE_PATH:String = "assets/textures/damage_effect"; private static var container:Sprite; /** * 贴图的用户,用于维持引用 */ private static var user:DummyUser = new DummyUser(); private static var ta:TextureAsset; /** * 删除所有的伤害数字,解除 container 引用<br> * 此后可以通过调用 init 重新进行初始化 * */ public static function dispose():void { if (!container) { throw new IllegalOperationError("[DamageNumber] 调用 dispose失败,因为尚未初始化"); } removeAll(); user.asset = null; ta = null; container = null; } /** * 删除所有的伤害数字 * */ public static function removeAll():void { if (!container) { throw new IllegalOperationError("[DamageNumber] 调用 removeAll 失败,因为尚未初始化"); } for (var i:int = container.numChildren - 1; i >= 0; i--) { if (container.getChildAt(i) is Helper) { container.getChildAt(i).removeFromParent(true); } } } /** * 初始化伤害数字<br> * <del>在正式使用前,请确保<br> * ImagePool 和 TextFieldPool 已正确初始化</del><br> * @param container 设置伤害数字出现在哪个容器中 * @param texturePath 贴图文件路径 */ public static function init(container:Sprite, texturePath:String = DEFAULT_TEXTURE_PATH):void { if (!container) { throw new IllegalOperationError("[DamageNumber] 调用 init 失败,因为已初始化"); } DamageFx.container = container; ta = TextureAsset.get(texturePath); ta.useThumb = false; user.asset = ta; ta.load(); } /** * 显示伤害数字 * @param number * @param x * @param y * */ public static function showNumber(number:int, isCrictial:Boolean, x:Number, y:Number):void { if (!container) { throw new IllegalOperationError("[DamageNumber] 调用 showNumber 失败,因为尚未初始化"); } var s:String = String(number); var prefix:String = isCrictial ? "crictial_number/" : "normal_number/"; const charWidth:int = 24; const anchor:int = s.length * charWidth * 0.5; for (var i:int = 0, n:int = s.length; i < n; i++) { var mc:MovieClip = createMC(prefix + s.charAt(i), 48, x - anchor + i * charWidth, y); } } /** * 显示暴击 * @param x * @param y * */ public static function showCrictial(x:Number, y:Number):void { if (!container) { throw new IllegalOperationError("[DamageNumber] 调用 showNumber 失败,因为尚未初始化"); } var mc:MovieClip = createMC("crictial/", 48, x, y); } /** * 显示打击特效 * @param x * @param y * @param id 要显示的造型 * @param isFlipX 是否要水平反转 */ public static function showHitEffect(x:Number, y:Number, id:int = -1, isFlipX:Boolean = false):void { if (!container) { throw new IllegalOperationError("[DamageNumber] 调用 showNumber 失败,因为尚未初始化"); } if (id == -1) { const n:int = 3 + 1; id = Math.random() * n; } var mc:MovieClip = createMC("hit_effect/" + id, 30, x, y); mc.pivotX = mc.pivotY = mc.texture.frame.width * 0.5; // 水平映射 if (isFlipX) { mc.scaleX = -1; } } private static function removeMC(event:Event):void { MovieClip(event.currentTarget).removeFromParent(true); AGE.s.juggler.remove(IAnimatable(event.currentTarget)); } private static function createMC(prefix:String, fps:int, x:Number, y:Number):MovieClip { var mc:MovieClip = new Helper(ta.getTextures(prefix), fps); mc.loop = false; mc.addEventListener(Event.COMPLETE, removeMC); container.addChild(mc); AGE.s.juggler.add(mc); var globalPoint:Point = SceneRenender(AGE.s.root).charLayer.localToGlobal(new Point(x, y)); mc.x = globalPoint.x; mc.y = globalPoint.y; return mc; } } } import starling.display.MovieClip; import starling.textures.Texture; class Helper extends MovieClip { public function Helper(textures:Vector.<Texture>, fps:Number = 12) { super(textures, fps); } }
package age.renderers { import com.greensock.TweenLite; import com.greensock.easing.Expo; import com.greensock.easing.Quad; import flash.geom.Point; import flash.geom.Rectangle; import flash.system.Capabilities; import age.AGE; import org.osflash.signals.Signal; import starling.animation.IAnimatable; import starling.filters.Spotlight2Filter; /** * 2D 相机 * @author zhanghaocong * */ public class Camera2D implements IAnimatable { private var _onShakeStart:Signal; /** * 开始震屏时广播 * @return * */ public function get onShakeStart():Signal { return _onShakeStart ||= new Signal(Camera2D); } /** * 标记当前是否正在 tween */ private var isTweening:Boolean; /** * 当前跟踪的点<br> * 该点可以是任意具有 x, y 属性的对象 */ private var trackPoint:Object; /** * 抖动的辅助类 */ private var _shake:CameraShake; /** * 是否限制边界 */ public var isLimitBounds:Boolean = true; /** * 创建一个新的 Camera2D * */ public function Camera2D() { } /** * @inheritDoc * @param time * */ public function advanceTime(time:Number):void { if (!_scene) { return; } if (!_scene.info) { return; } if (!trackPoint) { return; } // 动态更新中心点 if (threshold > 0) { var globalTrackPoint:Point = _scene.charLayer.localToGlobal(new Point(trackPoint.x, trackPoint.y)); centerPoint.x = globalTrackPoint.x; if (globalTrackPoint.x < AGE.stageWidth * threshold) { centerPoint.x = AGE.stageWidth * threshold; } if (globalTrackPoint.x > AGE.stageWidth * (1 - threshold)) { centerPoint.x = AGE.stageWidth * (1 - threshold); } } _scene.globalToLocal(centerPoint, centerPointLocal); var baseX:int = centerPointLocal.x - trackPoint.x; var baseY:int = centerPointLocal.y - trackPoint.y; if (isLimitBounds) { // 左边界 if (baseX > 0) { baseX = 0; } // 上边界 if (baseY > 0) { baseY = 0; } // 右边界 if (baseX < AGE.stageWidth / _zoomScale - scene.info.width) { baseX = AGE.stageWidth / _zoomScale - scene.info.width; } // 下边界 if (baseY < AGE.stageHeight / _zoomScale - scene.info.height) { baseY = AGE.stageHeight / _zoomScale - scene.info.height; } } for (var i:int = 0, n:int = _scene.numChildren; i < n; i++) { var l:LayerRenderer = _scene.getChildAt(i) as LayerRenderer; var newX:int = baseX * l.info.scrollRatio * _zoomScale; var newY:int = baseY * l.info.scrollRatio * _zoomScale; if (isTweening) // 平滑 Tween { // TODO TweenLite 复用 TweenLite.to(l, 0.3, { x: newX, y: newY, ease: Expo.easeOut }); } else { // 最朴素的移动方法 l.x = newX; l.y = newY; } } if (spotlight) { var sp:Point = scene.charLayer.localToGlobal(new Point(trackPoint.x, trackPoint.y)); spotlight.x = sp.x; spotlight.y = sp.y; } // 抖动效果 if (_shake) { if (!_shake.nextFrame(this)) { _shake = null; } } } /** * 跟踪一个 Point2D<br> * @param p 要跟踪的点,必须含有 x 和 y 属性 * @param zoomScale 缩放比例 * @param useTween 是否使用平滑卷动 * @param threshold 当 useTween 为 false 时,距屏幕多少百分比才进行卷动 */ public function track(p:Object, zoomScale:Number = 1, useTween:Boolean = false, threshold:Number = 0.3):void { if (p == null) { this.trackPoint = p; return; } if (!(p.hasOwnProperty("x") && p.hasOwnProperty("y"))) { if (Capabilities.isDebugger) { throw new ArgumentError("p 必须含有 x 和 y 属性"); } else { return; } } this.trackPoint = p; isTweening = useTween; this.threshold = threshold; zoom(zoomScale); } private var _zoomScale:Number = 1; /** * 获取缩放比例 * @return * */ final public function get zoomScale():Number { return _zoomScale; } /** * 缩放到指定比例 * @param scale * */ public function zoom(scale:Number):void { if (_zoomScale != scale) { _zoomScale = scale; TweenLite.to(_scene, 0.3, { ease: Quad.easeOut, scaleX: _zoomScale, scaleY: _zoomScale, onComplete: function():void { }}); } } /** * @private */ private var _center:Point; /** * 临时变量 */ private var centerPoint:Point = new Point; /** * 临时变量 */ private var centerPointLocal:Point = new Point; /** * 设置或获取中心点 * @return * */ final public function get center():Point { return _center; } public function set center(value:Point):void { _center = value; centerPoint.x = _center.x; centerPoint.y = _center.y; } private var _scene:SceneRenender; /** * 设置或获取 SceneRenender * @return * */ public function get scene():SceneRenender { return _scene; } public function set scene(value:SceneRenender):void { _scene = value; if (_scene) { _zoomScale = _scene.scaleX; // 当前缩放值 } /*if (_scene) { spotlight = new Spotlight2Filter(0, 0, .33, 2); _scene.filter = spotlight; }*/ } // TODO 将帧数改成持续时间 /** * 抖动<br> * @param intensity 剧烈程度 * @param numFrames 持续帧数 * */ public function shake(intensity:Number, numFrames:int):void { _shake = new CameraShake(intensity, numFrames); if (_onShakeStart) { _onShakeStart.dispatch(this); } } private var _bounds:Rectangle; /** * 点光滤镜,可以用来做失明 debuff */ private var spotlight:Spotlight2Filter; /** * 设置跟踪的目标移动了多少像素后,相机才跟着走 */ private var threshold:Number; /** * 设置或获取摄像机的边界<br> * 默认值为设置的 scene 的宽度 * @return * */ public function get bounds():Rectangle { return _bounds; } public function set bounds(value:Rectangle):void { _bounds = value; } } }
package fairygui { import fairygui.utils.ByteBuffer; import laya.display.Sprite; import laya.events.Event; import laya.maths.Point; import laya.maths.Rectangle; import laya.utils.Handler; public class GList extends GComponent { /** * itemRenderer(int index, GObject item); */ public var itemRenderer:Handler; /** * itemProvider(index:int):String; */ public var itemProvider:Handler; public var scrollItemToViewOnClick: Boolean; public var foldInvisibleItems:Boolean; private var _layout: int; private var _lineCount:int = 0; private var _columnCount:int = 0; private var _lineGap: int = 0; private var _columnGap: int = 0; private var _defaultItem: String; private var _autoResizeItem: Boolean; private var _selectionMode: int; private var _align:String; private var _verticalAlign:String; private var _selectionController:Controller; private var _lastSelectedIndex: Number = 0; private var _pool: GObjectPool; //Virtual List support private var _virtual:Boolean; private var _loop: Boolean; private var _numItems: int = 0; private var _realNumItems:int; private var _firstIndex: int = 0; //the top left index private var _curLineItemCount: int = 0; //item count in one line private var _curLineItemCount2:int; //只用在页面模式,表示垂直方向的项目数 private var _itemSize:Point; private var _virtualListChanged: int = 0; //1-content changed, 2-size changed private var _virtualItems:Vector.<ItemInfo>; private var _eventLocked: Boolean; private var itemInfoVer:uint = 0; //用来标志item是否在本次处理中已经被重用了 public function GList() { super(); this._trackBounds = true; this._pool = new GObjectPool(); this._layout = ListLayoutType.SingleColumn; this._autoResizeItem = true; this._lastSelectedIndex = -1; this._selectionMode = ListSelectionMode.Single; this.opaque = true; this.scrollItemToViewOnClick = true; this._align = "left"; this._verticalAlign = "top"; _container = new Sprite(); _displayObject.addChild(_container); } override public function dispose(): void { this._pool.clear(); super.dispose(); } /** * @see ListLayoutType */ public function get layout(): int { return this._layout; } /** * @see ListLayoutType */ public function set layout(value: int):void { if (this._layout != value) { this._layout = value; this.setBoundsChangedFlag(); if(this._virtual) this.setVirtualListChangedFlag(true); } } final public function get lineCount():int { return _lineCount; } final public function set lineCount(value:int):void { if (_lineCount != value) { _lineCount = value; if (_layout == ListLayoutType.FlowVertical || _layout == ListLayoutType.Pagination) { setBoundsChangedFlag(); if (_virtual) setVirtualListChangedFlag(true); } } } final public function get columnCount():int { return _columnCount; } final public function set columnCount(value:int):void { if (_columnCount != value) { _columnCount = value; if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) { setBoundsChangedFlag(); if (_virtual) setVirtualListChangedFlag(true); } } } public function get lineGap(): int { return this._lineGap; } public function set lineGap(value: int):void { if (this._lineGap != value) { this._lineGap = value; this.setBoundsChangedFlag(); if(this._virtual) this.setVirtualListChangedFlag(true); } } public function get columnGap(): int { return this._columnGap; } final public function set columnGap(value:int):void { if(_columnGap != value) { _columnGap = value; setBoundsChangedFlag(); if (_virtual) setVirtualListChangedFlag(true); } } public function get align():String { return _align; } public function set align(value:String):void { if(_align!=value) { _align = value; setBoundsChangedFlag(); if (_virtual) setVirtualListChangedFlag(true); } } final public function get verticalAlign():String { return _verticalAlign; } public function set verticalAlign(value:String):void { if(_verticalAlign!=value) { _verticalAlign = value; setBoundsChangedFlag(); if (_virtual) setVirtualListChangedFlag(true); } } public function get virtualItemSize(): Point { return this._itemSize; } public function set virtualItemSize(value: Point):void { if(this._virtual) { if(this._itemSize == null) this._itemSize = new Point(); this._itemSize.setTo(value.x, value.y); this.setVirtualListChangedFlag(true); } } public function get defaultItem(): String { return this._defaultItem; } public function set defaultItem(val: String):void { this._defaultItem = val; } public function get autoResizeItem(): Boolean { return this._autoResizeItem; } public function set autoResizeItem(value: Boolean):void { if(_autoResizeItem != value) { _autoResizeItem = value; setBoundsChangedFlag(); if (_virtual) setVirtualListChangedFlag(true); } } /** * @see ListSelectionMode */ public function get selectionMode(): int { return this._selectionMode; } /** * @see ListSelectionMode */ public function set selectionMode(value: int):void { this._selectionMode = value; } public function get selectionController():Controller { return _selectionController; } public function set selectionController(value:Controller):void { _selectionController = value; } public function get itemPool():GObjectPool { return this._pool; } public function getFromPool(url: String= null): GObject { if (!url) url = this._defaultItem; var obj:GObject = this._pool.getObject(url); if(obj!=null) obj.visible = true; return obj; } public function returnToPool(obj: GObject): void { obj.displayObject.cacheAs = "none"; this._pool.returnObject(obj); } override public function addChildAt(child: GObject, index: Number = 0): GObject { super.addChildAt(child, index); if (child is GButton) { var button: GButton = GButton(child); button.selected = false; button.changeStateOnClick = false; } child.on(Event.CLICK, this, this.__clickItem); return child; } public function addItem(url: String= null): GObject { if (!url) url = this._defaultItem; return this.addChild(UIPackage.createObjectFromURL(url)); } public function addItemFromPool(url: String= null): GObject { return this.addChild(this.getFromPool(url)); } override public function removeChildAt(index: Number, dispose: Boolean= false): GObject { var child: GObject = super.removeChildAt(index, dispose); child.off(Event.CLICK, this, this.__clickItem); return child; } public function removeChildToPoolAt(index: Number = 0): void { var child: GObject = super.removeChildAt(index); this.returnToPool(child); } public function removeChildToPool(child: GObject): void { super.removeChild(child); this.returnToPool(child); } public function removeChildrenToPool(beginIndex: Number= 0, endIndex: Number= -1): void { if (endIndex < 0 || endIndex >= this._children.length) endIndex = this._children.length - 1; for (var i: Number = beginIndex; i <= endIndex; ++i) this.removeChildToPoolAt(beginIndex); } public function get selectedIndex():int { var i:int; if (_virtual) { for (i = 0; i < _realNumItems; i++) { var ii:ItemInfo = _virtualItems[i]; if ((ii.obj is GButton) && GButton(ii.obj).selected || ii.obj == null && ii.selected) { if (_loop) return i % _numItems; else return i; } } } else { var cnt:int = _children.length; for (i = 0; i < cnt; i++) { var obj:GButton = _children[i].asButton; if (obj != null && obj.selected) return i; } } return -1; } public function set selectedIndex(value: int):void { if (value >= 0 && value < this.numItems) { if(_selectionMode!=ListSelectionMode.Single) clearSelection(); addSelection(value); } else clearSelection(); } public function getSelection():Vector.<int> { var ret:Vector.<int> = new Vector.<int>(); var i:int; if (_virtual) { for (i = 0; i < _realNumItems; i++) { var ii:ItemInfo = _virtualItems[i]; if ((ii.obj is GButton) && GButton(ii.obj).selected || ii.obj == null && ii.selected) { var j:int = i; if (_loop) { j = i % _numItems; if (ret.indexOf(j)!=-1) continue; } ret.push(j); } } } else { var cnt:int = _children.length; for (i = 0; i < cnt; i++) { var obj:GButton = _children[i].asButton; if (obj != null && obj.selected) ret.push(i); } } return ret; } public function addSelection(index:int, scrollItToView:Boolean=false):void { if(_selectionMode==ListSelectionMode.None) return; checkVirtualList(); if(_selectionMode==ListSelectionMode.Single) clearSelection(); if (scrollItToView) scrollToView(index); _lastSelectedIndex = index; var obj:GButton = null; if (_virtual) { var ii:ItemInfo = _virtualItems[index]; if (ii.obj != null) obj = ii.obj.asButton; ii.selected = true; } else obj = getChildAt(index).asButton; if (obj != null && !obj.selected) { obj.selected = true; updateSelectionController(index); } } public function removeSelection(index:int):void { if(_selectionMode==ListSelectionMode.None) return; var obj:GButton = null; if (_virtual) { var ii:ItemInfo = _virtualItems[index]; if (ii.obj != null) obj = ii.obj.asButton; ii.selected = false; } else obj = getChildAt(index).asButton; if (obj != null) obj.selected = false; } public function clearSelection():void { var i:int; if (_virtual) { for (i = 0; i < _realNumItems; i++) { var ii:ItemInfo = _virtualItems[i]; if (ii.obj is GButton) GButton(ii.obj).selected = false; ii.selected = false; } } else { var cnt:int = _children.length; for (i = 0; i < cnt; i++) { var obj:GButton = _children[i].asButton; if (obj != null) obj.selected = false; } } } private function clearSelectionExcept(g:GObject):void { var i:int; if (_virtual) { for (i = 0; i < _realNumItems; i++) { var ii:ItemInfo = _virtualItems[i]; if (ii.obj != g) { if ((ii.obj is GButton)) GButton(ii.obj).selected = false; ii.selected = false; } } } else { var cnt:int = _children.length; for (i = 0; i < cnt; i++) { var obj:GButton = _children[i].asButton; if (obj != null && obj != g) obj.selected = false; } } } public function selectAll():void { checkVirtualList(); var last:int = -1; var i:int; if (_virtual) { for (i = 0; i < _realNumItems; i++) { var ii:ItemInfo = _virtualItems[i]; if ((ii.obj is GButton) && !GButton(ii.obj).selected) { GButton(ii.obj).selected = true; last = i; } ii.selected = true; } } else { var cnt:int = _children.length; for (i = 0; i < cnt; i++) { var obj:GButton = _children[i].asButton; if (obj != null && !obj.selected) { obj.selected = true; last = i; } } } if(last!=-1) updateSelectionController(last); } public function selectNone():void { clearSelection(); } public function selectReverse():void { checkVirtualList(); var last:int = -1; var i:int; if (_virtual) { for (i = 0; i < _realNumItems; i++) { var ii:ItemInfo = _virtualItems[i]; if (ii.obj is GButton) { GButton(ii.obj).selected = !GButton(ii.obj).selected; if (GButton(ii.obj).selected) last = i; } ii.selected = !ii.selected; } } else { var cnt:int = _children.length; for (i = 0; i < cnt; i++) { var obj:GButton = _children[i].asButton; if (obj != null) { obj.selected = !obj.selected; if (obj.selected) last = i; } } } if(last!=-1) updateSelectionController(last); } public function handleArrowKey(dir: Number = 0): void { var index: Number = this.selectedIndex; if (index == -1) return; switch (dir) { case 1://up if (this._layout == ListLayoutType.SingleColumn || this._layout == ListLayoutType.FlowVertical) { index--; if (index >= 0) { this.clearSelection(); this.addSelection(index, true); } } else if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) { var current: GObject = this._children[index]; var k: Number = 0; for (var i: Number = index - 1; i >= 0; i--) { var obj: GObject = this._children[i]; if (obj.y != current.y) { current = obj; break; } k++; } for (; i >= 0; i--) { obj = this._children[i]; if (obj.y != current.y) { this.clearSelection(); this.addSelection(i + k + 1, true); break; } } } break; case 3://right if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) { index++; if (index < this._children.length) { this.clearSelection(); this.addSelection(index, true); } } else if (this._layout == ListLayoutType.FlowVertical) { current = this._children[index]; k = 0; var cnt: Number = this._children.length; for (i = index + 1; i < cnt; i++) { obj = this._children[i]; if (obj.x != current.x) { current = obj; break; } k++; } for (; i < cnt; i++) { obj = this._children[i]; if (obj.x != current.x) { this.clearSelection(); this.addSelection(i - k - 1, true); break; } } } break; case 5://down if (this._layout == ListLayoutType.SingleColumn || this._layout == ListLayoutType.FlowVertical) { index++; if (index < this._children.length) { this.clearSelection(); this.addSelection(index, true); } } else if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) { current = this._children[index]; k = 0; cnt = this._children.length; for (i = index + 1; i < cnt; i++) { obj = this._children[i]; if (obj.y != current.y) { current = obj; break; } k++; } for (; i < cnt; i++) { obj = this._children[i]; if (obj.y != current.y) { this.clearSelection(); this.addSelection(i - k - 1, true); break; } } } break; case 7://left if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) { index--; if (index >= 0) { this.clearSelection(); this.addSelection(index, true); } } else if (this._layout == ListLayoutType.FlowVertical) { current = this._children[index]; k = 0; for (i = index - 1; i >= 0; i--) { obj = this._children[i]; if (obj.x != current.x) { current = obj; break; } k++; } for (; i >= 0; i--) { obj = this._children[i]; if (obj.x != current.x) { this.clearSelection(); this.addSelection(i + k + 1, true); break; } } } break; } } private function __clickItem(evt:Event): void { if (this._scrollPane != null && this._scrollPane.isDragged) return; var item: GObject = GObject.cast(evt.currentTarget); this.setSelectionOnEvent(item, evt); if(this._scrollPane && scrollItemToViewOnClick) this._scrollPane.scrollToView(item,true); this.displayObject.event(Events.CLICK_ITEM, [item, Events.createEvent(Events.CLICK_ITEM, this.displayObject,evt)]); } private function setSelectionOnEvent(item: GObject, evt:Event): void { if (!(item is GButton) || this._selectionMode == ListSelectionMode.None) return; var dontChangeLastIndex: Boolean = false; var button: GButton = GButton(item); var index: int = childIndexToItemIndex(this.getChildIndex(item)); if (this._selectionMode == ListSelectionMode.Single) { if (!button.selected) { this.clearSelectionExcept(button); button.selected = true; } } else { if (evt.shiftKey) { if (!button.selected) { if (this._lastSelectedIndex != -1) { var min:int = Math.min(_lastSelectedIndex, index); var max:int = Math.max(_lastSelectedIndex, index); max = Math.min(max, this.numItems-1); var i:int; if (_virtual) { for (i = min; i <= max; i++) { var ii:ItemInfo = _virtualItems[i]; if (ii.obj is GButton) GButton(ii.obj).selected = true; ii.selected = true; } } else { for(i=min;i<=max;i++) { var obj:GButton = getChildAt(i).asButton; if(obj!=null) obj.selected = true; } } dontChangeLastIndex = true; } else { button.selected = true; } } } else if (evt.ctrlKey || this._selectionMode == ListSelectionMode.Multiple_SingleClick) { button.selected = !button.selected; } else { if (!button.selected) { this.clearSelectionExcept(button); button.selected = true; } else this.clearSelectionExcept(button); } } if (!dontChangeLastIndex) this._lastSelectedIndex = index; if(button.selected) updateSelectionController(index); } public function resizeToFit(itemCount: Number = 1000000, minSize: Number = 0): void { this.ensureBoundsCorrect(); var curCount: Number = this.numItems; if (itemCount > curCount) itemCount = curCount; if(this._virtual) { var lineCount: Number = Math.ceil(itemCount / this._curLineItemCount); if(this._layout == ListLayoutType.SingleColumn || this._layout == ListLayoutType.FlowHorizontal) this.viewHeight = lineCount * this._itemSize.y + Math.max(0,lineCount - 1) * this._lineGap; else this.viewWidth = lineCount * this._itemSize.x + Math.max(0,lineCount - 1) * this._columnGap; } else if(itemCount == 0) { if (this._layout == ListLayoutType.SingleColumn || this._layout == ListLayoutType.FlowHorizontal) this.viewHeight = minSize; else this.viewWidth = minSize; } else { var i: Number = itemCount - 1; var obj: GObject = null; while (i >= 0) { obj = this.getChildAt(i); if (!foldInvisibleItems || obj.visible) break; i--; } if (i < 0) { if (this._layout == ListLayoutType.SingleColumn || this._layout == ListLayoutType.FlowHorizontal) this.viewHeight = minSize; else this.viewWidth = minSize; } else { var size: Number = 0; if (this._layout == ListLayoutType.SingleColumn || this._layout == ListLayoutType.FlowHorizontal) { size = obj.y + obj.height; if (size < minSize) size = minSize; this.viewHeight = size; } else { size = obj.x + obj.width; if (size < minSize) size = minSize; this.viewWidth = size; } } } } public function getMaxItemWidth(): Number { var cnt: Number = this._children.length; var max: Number = 0; for (var i: Number = 0; i < cnt; i++) { var child: GObject = this.getChildAt(i); if (child.width > max) max = child.width; } return max; } override protected function handleSizeChanged(): void { super.handleSizeChanged(); this.setBoundsChangedFlag(); if (this._virtual) this.setVirtualListChangedFlag(true); } override public function handleControllerChanged(c:Controller):void { super.handleControllerChanged(c); if (_selectionController == c) this.selectedIndex = c.selectedIndex; } private function updateSelectionController(index:int):void { if (_selectionController != null && !_selectionController.changing && index < _selectionController.pageCount) { var c:Controller = _selectionController; _selectionController = null; c.selectedIndex = index; _selectionController = c; } } override public function getSnappingPosition(xValue:Number, yValue:Number, resultPoint:Point=null):Point { if (_virtual) { if(!resultPoint) resultPoint = new Point(); var saved:Number; var index:int; if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) { saved = yValue; GList.pos_param = yValue; index = getIndexOnPos1(false); yValue = GList.pos_param; if (index < _virtualItems.length && saved - yValue > _virtualItems[index].height / 2 && index < _realNumItems) yValue += _virtualItems[index].height + _lineGap; } else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) { saved = xValue; GList.pos_param = xValue; index = getIndexOnPos2(false); xValue = GList.pos_param; if (index < _virtualItems.length && saved - xValue > _virtualItems[index].width / 2 && index < _realNumItems) xValue += _virtualItems[index].width + _columnGap; } else { saved = xValue; GList.pos_param = xValue; index = getIndexOnPos3(false); xValue = GList.pos_param; if (index < _virtualItems.length && saved - xValue > _virtualItems[index].width / 2 && index < _realNumItems) xValue += _virtualItems[index].width + _columnGap; } resultPoint.x = xValue; resultPoint.y = yValue; return resultPoint; } else return super.getSnappingPosition(xValue, yValue, resultPoint); } public function scrollToView(index:int, ani:Boolean=false, setFirst:Boolean=false):void { if (_virtual) { if(_numItems==0) return; checkVirtualList(); if (index >= _virtualItems.length) throw new Error("Invalid child index: " + index + ">" + _virtualItems.length); if(_loop) index = Math.floor(_firstIndex/_numItems)*_numItems+index; var rect:Rectangle; var ii:ItemInfo = _virtualItems[index]; var pos:Number = 0; var i:int; if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) { for (i = _curLineItemCount-1; i < index; i += _curLineItemCount) pos += _virtualItems[i].height + _lineGap; rect = new Rectangle(0, pos, _itemSize.x, ii.height); } else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) { for (i = _curLineItemCount-1; i < index; i += _curLineItemCount) pos += _virtualItems[i].width + _columnGap; rect = new Rectangle(pos, 0, ii.width, _itemSize.y); } else { var page:int = index / (_curLineItemCount * _curLineItemCount2); rect = new Rectangle(page * viewWidth + (index % _curLineItemCount) * (ii.width + _columnGap), (index / _curLineItemCount) % _curLineItemCount2 * (ii.height + _lineGap), ii.width, ii.height); } setFirst = true;//因为在可变item大小的情况下,只有设置在最顶端,位置才不会因为高度变化而改变,所以只能支持setFirst=true if (_scrollPane != null) _scrollPane.scrollToView(rect, ani, setFirst); } else { var obj:GObject = getChildAt(index); if (_scrollPane != null) _scrollPane.scrollToView(obj, ani, setFirst); else if (parent != null && parent.scrollPane != null) parent.scrollPane.scrollToView(obj, ani, setFirst); } } override public function getFirstChildInView():int { return childIndexToItemIndex(super.getFirstChildInView()); } public function childIndexToItemIndex(index:int):int { if (!_virtual) return index; if (_layout == ListLayoutType.Pagination) { for (var i:int = _firstIndex; i < _realNumItems; i++) { if (_virtualItems[i].obj != null) { index--; if (index < 0) return i; } } return index; } else { index += _firstIndex; if (_loop && _numItems > 0) index = index % _numItems; return index; } } public function itemIndexToChildIndex(index:int):int { if (!_virtual) return index; if (_layout == ListLayoutType.Pagination) { return getChildIndex(_virtualItems[index].obj); } else { if (_loop && _numItems > 0) { var j:int = _firstIndex % _numItems; if (index >= j) index = index - j; else index = _numItems - j + index; } else index -= _firstIndex; return index; } } public function setVirtual(): void { this._setVirtual(false); } /** * Set the list to be virtual list, and has loop behavior. */ public function setVirtualAndLoop(): void { this._setVirtual(true); } private function _setVirtual(loop: Boolean): void { if(!this._virtual) { if(this._scrollPane == null) throw new Error("Virtual list must be scrollable!"); if(loop) { if(this._layout == ListLayoutType.FlowHorizontal || this._layout == ListLayoutType.FlowVertical) throw new Error("Loop list is not supported for FlowHorizontal or FlowVertical layout!"); this._scrollPane.bouncebackEffect = false; } this._virtual = true; this._loop = loop; this._virtualItems = new Vector.<ItemInfo>(); this.removeChildrenToPool(); if(this._itemSize==null) { this._itemSize = new Point(); var obj: GObject = this.getFromPool(null); if (obj == null) { throw new Error("Virtual List must have a default list item resource."); } else { this._itemSize.x = obj.width; this._itemSize.y = obj.height; } this.returnToPool(obj); } if(this._layout == ListLayoutType.SingleColumn || this._layout == ListLayoutType.FlowHorizontal) { this._scrollPane.scrollStep = this._itemSize.y; if(_loop) this._scrollPane._loop = 2; } else { this._scrollPane.scrollStep = this._itemSize.x; if(_loop) this._scrollPane._loop = 1; } this.on(Events.SCROLL, this, this.__scrolled); this.setVirtualListChangedFlag(true); } } /** * Set the list item count. * If the list is not virtual, specified Number of items will be created. * If the list is virtual, only items in view will be created. */ public function get numItems():int { if(this._virtual) return this._numItems; else return this._children.length; } public function set numItems(value:int):void { var i:int; if (_virtual) { if (itemRenderer == null) throw new Error("Set itemRenderer first!"); _numItems = value; if (_loop) _realNumItems = _numItems * 6;//设置6倍数量,用于循环滚动 else _realNumItems = _numItems; //_virtualItems的设计是只增不减的 var oldCount:int = _virtualItems.length; if (_realNumItems > oldCount) { for (i = oldCount; i < _realNumItems; i++) { var ii:ItemInfo = new ItemInfo(); ii.width = _itemSize.x; ii.height = _itemSize.y; _virtualItems.push(ii); } } else { for (i = _realNumItems; i < oldCount; i++) _virtualItems[i].selected = false; } if (this._virtualListChanged != 0) Laya.timer.clear(this, this._refreshVirtualList); //立即刷新 _refreshVirtualList(); } else { var cnt:int = _children.length; if (value > cnt) { for (i = cnt; i < value; i++) { if (itemProvider == null) addItemFromPool(); else addItemFromPool(itemProvider.runWith(i)); } } else { removeChildrenToPool(value, cnt); } if (itemRenderer != null) { for (i = 0; i < value; i++) itemRenderer.runWith([i, getChildAt(i)]); } } } public function refreshVirtualList():void { this.setVirtualListChangedFlag(false); } private function checkVirtualList():void { if(this._virtualListChanged!=0) { this._refreshVirtualList(); Laya.timer.clear(this, this._refreshVirtualList); } } private function setVirtualListChangedFlag(layoutChanged:Boolean = false):void { if(layoutChanged) this._virtualListChanged = 2; else if(this._virtualListChanged == 0) this._virtualListChanged = 1; Laya.timer.callLater(this, this._refreshVirtualList); } private function _refreshVirtualList():void { var layoutChanged:Boolean = _virtualListChanged == 2; _virtualListChanged = 0; _eventLocked = true; if (layoutChanged) { if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.SingleRow) _curLineItemCount = 1; else if (_layout == ListLayoutType.FlowHorizontal) { if (_columnCount > 0) _curLineItemCount = _columnCount; else { _curLineItemCount = Math.floor((_scrollPane.viewWidth + _columnGap) / (_itemSize.x + _columnGap)); if (_curLineItemCount <= 0) _curLineItemCount = 1; } } else if (_layout == ListLayoutType.FlowVertical) { if (_lineCount > 0) _curLineItemCount = _lineCount; else { _curLineItemCount = Math.floor((_scrollPane.viewHeight + _lineGap) / (_itemSize.y + _lineGap)); if (_curLineItemCount <= 0) _curLineItemCount = 1; } } else //pagination { if (_columnCount > 0) _curLineItemCount = _columnCount; else { _curLineItemCount = Math.floor((_scrollPane.viewWidth + _columnGap) / (_itemSize.x + _columnGap)); if (_curLineItemCount <= 0) _curLineItemCount = 1; } if (_lineCount > 0) _curLineItemCount2 = _lineCount; else { _curLineItemCount2 = Math.floor((_scrollPane.viewHeight + _lineGap) / (_itemSize.y + _lineGap)); if (_curLineItemCount2 <= 0) _curLineItemCount2 = 1; } } } var ch:Number = 0, cw:Number = 0; if (_realNumItems > 0) { var i:int; var len:int = Math.ceil(_realNumItems / _curLineItemCount) * _curLineItemCount; var len2:int = Math.min(_curLineItemCount, _realNumItems); if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) { for (i = 0; i < len; i += _curLineItemCount) ch += _virtualItems[i].height + _lineGap; if (ch > 0) ch -= _lineGap; if (_autoResizeItem) cw = _scrollPane.viewWidth; else { for (i = 0; i < len2; i++) cw += _virtualItems[i].width + _columnGap; if (cw > 0) cw -= _columnGap; } } else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) { for (i = 0; i < len; i += _curLineItemCount) cw += _virtualItems[i].width + _columnGap; if (cw > 0) cw -= _columnGap; if (_autoResizeItem) ch = _scrollPane.viewHeight; else { for (i = 0; i < len2; i++) ch += _virtualItems[i].height + _lineGap; if (ch > 0) ch -= _lineGap; } } else { var pageCount:int = Math.ceil(len / (_curLineItemCount * _curLineItemCount2)); cw = pageCount * viewWidth; ch = viewHeight; } } handleAlign(cw, ch); _scrollPane.setContentSize(cw, ch); _eventLocked = false; handleScroll(true); } private function __scrolled(evt:Event):void { handleScroll(false); } private function getIndexOnPos1(forceUpdate:Boolean):int { if (_realNumItems < _curLineItemCount) { pos_param = 0; return 0; } var i:int; var pos2:Number; var pos3:Number; if (numChildren > 0 && !forceUpdate) { pos2 = this.getChildAt(0).y; if (pos2 > pos_param) { for (i = _firstIndex - _curLineItemCount; i >= 0; i -= _curLineItemCount) { pos2 -= (_virtualItems[i].height + _lineGap); if (pos2 <= pos_param) { pos_param = pos2; return i; } } pos_param = 0; return 0; } else { for (i = _firstIndex; i < _realNumItems; i += _curLineItemCount) { pos3 = pos2 + _virtualItems[i].height + _lineGap; if (pos3 > pos_param) { pos_param = pos2; return i; } pos2 = pos3; } pos_param = pos2; return _realNumItems - _curLineItemCount; } } else { pos2 = 0; for (i = 0; i < _realNumItems; i += _curLineItemCount) { pos3 = pos2 + _virtualItems[i].height + _lineGap; if (pos3 > pos_param) { pos_param = pos2; return i; } pos2 = pos3; } pos_param = pos2; return _realNumItems - _curLineItemCount; } } private function getIndexOnPos2(forceUpdate:Boolean):int { if (_realNumItems < _curLineItemCount) { pos_param = 0; return 0; } var i:int; var pos2:Number; var pos3:Number; if (numChildren > 0 && !forceUpdate) { pos2 = this.getChildAt(0).x; if (pos2 > pos_param) { for (i = _firstIndex - _curLineItemCount; i >= 0; i -= _curLineItemCount) { pos2 -= (_virtualItems[i].width + _columnGap); if (pos2 <= pos_param) { pos_param = pos2; return i; } } pos_param = 0; return 0; } else { for (i = _firstIndex; i < _realNumItems; i += _curLineItemCount) { pos3 = pos2 + _virtualItems[i].width + _columnGap; if (pos3 > pos_param) { pos_param = pos2; return i; } pos2 = pos3; } pos_param = pos2; return _realNumItems - _curLineItemCount; } } else { pos2 = 0; for (i = 0; i < _realNumItems; i += _curLineItemCount) { pos3 = pos2 + _virtualItems[i].width + _columnGap; if (pos3 > pos_param) { pos_param = pos2; return i; } pos2 = pos3; } pos_param = pos2; return _realNumItems - _curLineItemCount; } } private function getIndexOnPos3(forceUpdate:Boolean):int { if (_realNumItems < _curLineItemCount) { pos_param = 0; return 0; } var viewWidth:Number = this.viewWidth; var page:int = Math.floor(pos_param / viewWidth); var startIndex:int = page * (_curLineItemCount * _curLineItemCount2); var pos2:Number = page * viewWidth; var i:int; var pos3:Number; for (i = 0; i < _curLineItemCount; i++) { pos3 = pos2 + _virtualItems[startIndex + i].width + _columnGap; if (pos3 > pos_param) { pos_param = pos2; return startIndex + i; } pos2 = pos3; } pos_param = pos2; return startIndex + _curLineItemCount - 1; } private function handleScroll(forceUpdate:Boolean):void { if (_eventLocked) return; if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) { var enterCounter:int = 0; while(handleScroll1(forceUpdate)) { enterCounter++; forceUpdate = false; if(enterCounter>20) { trace("FairyGUI: list will never be filled as the item renderer function always returns a different size."); break; } } handleArchOrder1(); } else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) { enterCounter = 0; while(handleScroll2(forceUpdate)) { enterCounter++; forceUpdate = false; if(enterCounter>20) { trace("FairyGUI: list will never be filled as the item renderer function always returns a different size."); break; } } handleArchOrder2(); } else { handleScroll3(forceUpdate); } _boundsChanged = false; } private static var pos_param:Number; private function handleScroll1(forceUpdate:Boolean):Boolean { var pos:Number = _scrollPane.scrollingPosY; var max:Number = pos + _scrollPane.viewHeight; var end:Boolean = max == _scrollPane.contentHeight;//这个标志表示当前需要滚动到最末,无论内容变化大小 //寻找当前位置的第一条项目 GList.pos_param = pos; var newFirstIndex:int = getIndexOnPos1(forceUpdate); pos = GList.pos_param; if (newFirstIndex == _firstIndex && !forceUpdate) return false; var oldFirstIndex:int = _firstIndex; _firstIndex = newFirstIndex; var curIndex:int = newFirstIndex; var forward:Boolean = oldFirstIndex > newFirstIndex; var childCount:int = this.numChildren; var lastIndex:int = oldFirstIndex + childCount - 1; var reuseIndex:int = forward ? lastIndex : oldFirstIndex; var curX:Number = 0, curY:Number = pos; var needRender:Boolean; var deltaSize:Number = 0; var firstItemDeltaSize:Number = 0; var url:String = defaultItem; var ii:ItemInfo, ii2:ItemInfo; var i:int,j:int; var partSize:int = (_scrollPane.viewWidth - _columnGap * (_curLineItemCount - 1)) / _curLineItemCount; itemInfoVer++; while (curIndex < _realNumItems && (end || curY < max)) { ii = _virtualItems[curIndex]; if (ii.obj == null || forceUpdate) { if (itemProvider != null) { url = itemProvider.runWith(curIndex % _numItems); if (url == null) url = _defaultItem; url = UIPackage.normalizeURL(url); } if (ii.obj != null && ii.obj.resourceURL != url) { if (ii.obj is GButton) ii.selected = GButton(ii.obj).selected; removeChildToPool(ii.obj); ii.obj = null; } } if (ii.obj == null) { //搜索最适合的重用item,保证每次刷新需要新建或者重新render的item最少 if (forward) { for (j = reuseIndex; j >= oldFirstIndex; j--) { ii2 = _virtualItems[j]; if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) { if (ii2.obj is GButton) ii2.selected = GButton(ii2.obj).selected; ii.obj = ii2.obj; ii2.obj = null; if (j == reuseIndex) reuseIndex--; break; } } } else { for (j = reuseIndex; j <= lastIndex; j++) { ii2 = _virtualItems[j]; if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) { if (ii2.obj is GButton) ii2.selected = GButton(ii2.obj).selected; ii.obj = ii2.obj; ii2.obj = null; if (j == reuseIndex) reuseIndex++; break; } } } if (ii.obj != null) { setChildIndex(ii.obj, forward ? curIndex - newFirstIndex : numChildren); } else { ii.obj = _pool.getObject(url); if (forward) this.addChildAt(ii.obj, curIndex - newFirstIndex); else this.addChild(ii.obj); } if (ii.obj is GButton) GButton(ii.obj).selected = ii.selected; needRender = true; } else needRender = forceUpdate; if (needRender) { if (_autoResizeItem && (_layout == ListLayoutType.SingleColumn || _columnCount > 0)) ii.obj.setSize(partSize, ii.obj.height, true); itemRenderer.runWith([curIndex % _numItems, ii.obj]); if (curIndex % _curLineItemCount == 0) { deltaSize += Math.ceil(ii.obj.height) - ii.height; if (curIndex == newFirstIndex && oldFirstIndex > newFirstIndex) { //当内容向下滚动时,如果新出现的项目大小发生变化,需要做一个位置补偿,才不会导致滚动跳动 firstItemDeltaSize = Math.ceil(ii.obj.height) - ii.height; } } ii.width = Math.ceil(ii.obj.width); ii.height = Math.ceil(ii.obj.height); } ii.updateFlag = itemInfoVer; ii.obj.setXY(curX, curY); if (curIndex == newFirstIndex) //要显示多一条才不会穿帮 max += ii.height; curX += ii.width + _columnGap; if (curIndex % _curLineItemCount == _curLineItemCount - 1) { curX = 0; curY += ii.height + _lineGap; } curIndex++; } for (i = 0; i < childCount; i++) { ii = _virtualItems[oldFirstIndex + i]; if (ii.updateFlag != itemInfoVer && ii.obj != null) { if (ii.obj is GButton) ii.selected = GButton(ii.obj).selected; removeChildToPool(ii.obj); ii.obj = null; } } childCount = _children.length; for (i = 0; i < childCount; i++) { var obj:GObject = _virtualItems[newFirstIndex + i].obj; if (_children[i] != obj) setChildIndex(obj, i); } if (deltaSize != 0 || firstItemDeltaSize != 0) _scrollPane.changeContentSizeOnScrolling(0, deltaSize, 0, firstItemDeltaSize); if (curIndex > 0 && this.numChildren > 0 && _container.y < 0 && getChildAt(0).y > -_container.y)//最后一页没填满! return true; else return false; } private function handleScroll2(forceUpdate:Boolean):Boolean { var pos:Number = _scrollPane.scrollingPosX; var max:Number = pos + _scrollPane.viewWidth; var end:Boolean = pos == _scrollPane.contentWidth;//这个标志表示当前需要滚动到最末,无论内容变化大小 //寻找当前位置的第一条项目 GList.pos_param = pos; var newFirstIndex:int = getIndexOnPos2(forceUpdate); pos = GList.pos_param; if (newFirstIndex == _firstIndex && !forceUpdate) return false; var oldFirstIndex:int = _firstIndex; _firstIndex = newFirstIndex; var curIndex:int = newFirstIndex; var forward:Boolean = oldFirstIndex > newFirstIndex; var childCount:int = this.numChildren; var lastIndex:int = oldFirstIndex + childCount - 1; var reuseIndex:int = forward ? lastIndex : oldFirstIndex; var curX:Number = pos, curY:Number = 0; var needRender:Boolean; var deltaSize:Number = 0; var firstItemDeltaSize:Number = 0; var url:String = defaultItem; var ii:ItemInfo, ii2:ItemInfo; var i:int,j:int; var partSize:int = (_scrollPane.viewHeight - _lineGap * (_curLineItemCount - 1)) / _curLineItemCount; itemInfoVer++; while (curIndex < _realNumItems && (end || curX < max)) { ii = _virtualItems[curIndex]; if (ii.obj == null || forceUpdate) { if (itemProvider != null) { url = itemProvider.runWith(curIndex % _numItems); if (url == null) url = _defaultItem; url = UIPackage.normalizeURL(url); } if (ii.obj != null && ii.obj.resourceURL != url) { if (ii.obj is GButton) ii.selected = GButton(ii.obj).selected; removeChildToPool(ii.obj); ii.obj = null; } } if (ii.obj == null) { if (forward) { for (j = reuseIndex; j >= oldFirstIndex; j--) { ii2 = _virtualItems[j]; if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) { if (ii2.obj is GButton) ii2.selected = GButton(ii2.obj).selected; ii.obj = ii2.obj; ii2.obj = null; if (j == reuseIndex) reuseIndex--; break; } } } else { for (j = reuseIndex; j <= lastIndex; j++) { ii2 = _virtualItems[j]; if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) { if (ii2.obj is GButton) ii2.selected = GButton(ii2.obj).selected; ii.obj = ii2.obj; ii2.obj = null; if (j == reuseIndex) reuseIndex++; break; } } } if (ii.obj != null) { setChildIndex(ii.obj, forward ? curIndex - newFirstIndex : numChildren); } else { ii.obj = _pool.getObject(url); if (forward) this.addChildAt(ii.obj, curIndex - newFirstIndex); else this.addChild(ii.obj); } if (ii.obj is GButton) GButton(ii.obj).selected = ii.selected; needRender = true; } else needRender = forceUpdate; if (needRender) { if (_autoResizeItem && (_layout == ListLayoutType.SingleRow || _lineCount > 0)) ii.obj.setSize(ii.obj.width, partSize, true); itemRenderer.runWith([curIndex % _numItems, ii.obj]); if (curIndex % _curLineItemCount == 0) { deltaSize += Math.ceil(ii.obj.width) - ii.width; if (curIndex == newFirstIndex && oldFirstIndex > newFirstIndex) { //当内容向下滚动时,如果新出现的一个项目大小发生变化,需要做一个位置补偿,才不会导致滚动跳动 firstItemDeltaSize = Math.ceil(ii.obj.width) - ii.width; } } ii.width = Math.ceil(ii.obj.width); ii.height = Math.ceil(ii.obj.height); } ii.updateFlag = itemInfoVer; ii.obj.setXY(curX, curY); if (curIndex == newFirstIndex) //要显示多一条才不会穿帮 max += ii.width; curY += ii.height + _lineGap; if (curIndex % _curLineItemCount == _curLineItemCount - 1) { curY = 0; curX += ii.width + _columnGap; } curIndex++; } for (i = 0; i < childCount; i++) { ii = _virtualItems[oldFirstIndex + i]; if (ii.updateFlag != itemInfoVer && ii.obj != null) { if (ii.obj is GButton) ii.selected = GButton(ii.obj).selected; removeChildToPool(ii.obj); ii.obj = null; } } childCount = _children.length; for (i = 0; i < childCount; i++) { var obj:GObject = _virtualItems[newFirstIndex + i].obj; if (_children[i] != obj) setChildIndex(obj, i); } if (deltaSize != 0 || firstItemDeltaSize != 0) _scrollPane.changeContentSizeOnScrolling(deltaSize, 0, firstItemDeltaSize, 0); if (curIndex > 0 && this.numChildren > 0 && _container.x < 0 && getChildAt(0).x > - _container.x)//最后一页没填满! return true; else return false; } private function handleScroll3(forceUpdate:Boolean):void { var pos:Number = _scrollPane.scrollingPosX; //寻找当前位置的第一条项目 GList.pos_param = pos; var newFirstIndex:int = getIndexOnPos3(forceUpdate); pos = GList.pos_param; if (newFirstIndex == _firstIndex && !forceUpdate) return; var oldFirstIndex:int = _firstIndex; _firstIndex = newFirstIndex; //分页模式不支持不等高,所以渲染满一页就好了 var reuseIndex:int = oldFirstIndex; var virtualItemCount:int = _virtualItems.length; var pageSize:int = _curLineItemCount * _curLineItemCount2; var startCol:int = newFirstIndex % _curLineItemCount; var viewWidth:Number = this.viewWidth; var page:int = Math.floor(newFirstIndex / pageSize); var startIndex:int = page * pageSize; var lastIndex:int = startIndex + pageSize * 2; //测试两页 var needRender:Boolean; var i:int; var ii:ItemInfo, ii2:ItemInfo; var col:int; var url:String = _defaultItem; var partWidth:int = (_scrollPane.viewWidth - _columnGap * (_curLineItemCount - 1)) / _curLineItemCount; var partHeight:int = (_scrollPane.viewHeight - _lineGap * (_curLineItemCount2 - 1)) / _curLineItemCount2; itemInfoVer++; //先标记这次要用到的项目 for (i = startIndex; i < lastIndex; i++) { if (i >= _realNumItems) continue; col = i % _curLineItemCount; if (i - startIndex < pageSize) { if (col < startCol) continue; } else { if (col > startCol) continue; } ii = _virtualItems[i]; ii.updateFlag = itemInfoVer; } var lastObj:GObject = null; var insertIndex:int = 0; for (i = startIndex; i < lastIndex; i++) { if (i >= _realNumItems) continue; ii = _virtualItems[i]; if (ii.updateFlag != itemInfoVer) continue; if (ii.obj == null) { //寻找看有没有可重用的 while (reuseIndex < virtualItemCount) { ii2 = _virtualItems[reuseIndex]; if (ii2.obj != null && ii2.updateFlag != itemInfoVer) { if (ii2.obj is GButton) ii2.selected = GButton(ii2.obj).selected; ii.obj = ii2.obj; ii2.obj = null; break; } reuseIndex++; } if (insertIndex == -1) insertIndex = getChildIndex(lastObj) + 1; if (ii.obj == null) { if (itemProvider != null) { url = itemProvider.runWith(i % _numItems); if (url == null) url = _defaultItem; url = UIPackage.normalizeURL(url); } ii.obj = _pool.getObject(url); this.addChildAt(ii.obj, insertIndex); } else { insertIndex = setChildIndexBefore(ii.obj, insertIndex); } insertIndex++; if (ii.obj is GButton) GButton(ii.obj).selected = ii.selected; needRender = true; } else { needRender = forceUpdate; insertIndex = -1; lastObj = ii.obj; } if (needRender) { if (_autoResizeItem) { if (_curLineItemCount == _columnCount && _curLineItemCount2 == _lineCount) ii.obj.setSize(partWidth, partHeight, true); else if (_curLineItemCount == _columnCount) ii.obj.setSize(partWidth, ii.obj.height, true); else if (_curLineItemCount2 == _lineCount) ii.obj.setSize(ii.obj.width, partHeight, true); } itemRenderer.runWith([i % _numItems, ii.obj]); ii.width = Math.ceil(ii.obj.width); ii.height = Math.ceil(ii.obj.height); } } //排列item var borderX:int = (startIndex / pageSize) * viewWidth; var xx:int = borderX; var yy:int = 0; var lineHeight:int = 0; for (i = startIndex; i < lastIndex; i++) { if (i >= _realNumItems) continue; ii = _virtualItems[i]; if (ii.updateFlag == itemInfoVer) ii.obj.setXY(xx, yy); if (ii.height > lineHeight) lineHeight = ii.height; if (i % _curLineItemCount == _curLineItemCount - 1) { xx = borderX; yy += lineHeight + _lineGap; lineHeight = 0; if (i == startIndex + pageSize - 1) { borderX += viewWidth; xx = borderX; yy = 0; } } else xx += ii.width + _columnGap; } //释放未使用的 for (i = reuseIndex; i < virtualItemCount; i++) { ii = _virtualItems[i]; if (ii.updateFlag != itemInfoVer && ii.obj != null) { if (ii.obj is GButton) ii.selected = GButton(ii.obj).selected; removeChildToPool(ii.obj); ii.obj = null; } } } private function handleArchOrder1():void { if (this.childrenRenderOrder == ChildrenRenderOrder.Arch) { var mid:Number = _scrollPane.posY + this.viewHeight / 2; var minDist:Number = Number.POSITIVE_INFINITY; var dist:Number = 0; var apexIndex:int = 0; var cnt:int = this.numChildren; for (var i:int = 0; i < cnt; i++) { var obj:GObject = getChildAt(i); if (!foldInvisibleItems || obj.visible) { dist = Math.abs(mid - obj.y - obj.height / 2); if (dist < minDist) { minDist = dist; apexIndex = i; } } } this.apexIndex = apexIndex; } } private function handleArchOrder2():void { if (this.childrenRenderOrder == ChildrenRenderOrder.Arch) { var mid:Number = _scrollPane.posX + this.viewWidth / 2; var minDist:Number = Number.POSITIVE_INFINITY; var dist:Number = 0; var apexIndex:int = 0; var cnt:int = this.numChildren; for (var i:int = 0; i < cnt; i++) { var obj:GObject = getChildAt(i); if (!foldInvisibleItems || obj.visible) { dist = Math.abs(mid - obj.x - obj.width / 2); if (dist < minDist) { minDist = dist; apexIndex = i; } } } this.apexIndex = apexIndex; } } private function handleAlign(contentWidth:Number, contentHeight:Number):void { var newOffsetX:Number = 0; var newOffsetY:Number = 0; if (contentHeight < viewHeight) { if (_verticalAlign == "middle") newOffsetY = Math.floor((viewHeight - contentHeight) / 2); else if (_verticalAlign == "bottom") newOffsetY = viewHeight - contentHeight; } if (contentWidth < this.viewWidth) { if (_align == "center") newOffsetX = Math.floor((viewWidth - contentWidth) / 2); else if (_align == "right") newOffsetX = viewWidth - contentWidth; } if (newOffsetX!=_alignOffset.x || newOffsetY!=_alignOffset.y) { _alignOffset.setTo(newOffsetX, newOffsetY); if (_scrollPane != null) _scrollPane.adjustMaskContainer(); else _container.pos(_margin.left + _alignOffset.x, _margin.top + _alignOffset.y); } } override protected function updateBounds():void { if(_virtual) return; var i:int; var child:GObject; var curX:int; var curY:int; var maxWidth:int; var maxHeight:int; var cw:int, ch:int; var j:int = 0; var page:int = 0; var k:int = 0; var cnt:int = _children.length; var viewWidth:Number = this.viewWidth; var viewHeight:Number = this.viewHeight; var lineSize:Number = 0; var lineStart:int = 0; var ratio:Number; if(_layout==ListLayoutType.SingleColumn) { for(i=0;i<cnt;i++) { child = getChildAt(i); if (foldInvisibleItems && !child.visible) continue; if (curY != 0) curY += _lineGap; child.y = curY; if (_autoResizeItem) child.setSize(viewWidth, child.height, true); curY += Math.ceil(child.height); if(child.width>maxWidth) maxWidth = child.width; } cw = Math.ceil(maxWidth); ch = curY; } else if(_layout==ListLayoutType.SingleRow) { for(i=0;i<cnt;i++) { child = getChildAt(i); if (foldInvisibleItems && !child.visible) continue; if(curX!=0) curX += _columnGap; child.x = curX; if (_autoResizeItem) child.setSize(child.width, viewHeight, true); curX += Math.ceil(child.width); if(child.height>maxHeight) maxHeight = child.height; } cw = curX; ch = Math.ceil(maxHeight); } else if(_layout==ListLayoutType.FlowHorizontal) { if (_autoResizeItem && _columnCount > 0) { for (i = 0; i < cnt; i++) { child = getChildAt(i); if (foldInvisibleItems && !child.visible) continue; lineSize += child.sourceWidth; j++; if (j == _columnCount || i == cnt - 1) { ratio = (viewWidth - lineSize - (j - 1) * _columnGap) / lineSize; curX = 0; for (j = lineStart; j <= i; j++) { child = getChildAt(j); if (foldInvisibleItems && !child.visible) continue; child.setXY(curX, curY); if (j < i) { child.setSize(child.sourceWidth + Math.round(child.sourceWidth * ratio), child.height, true); curX += Math.ceil(child.width) + _columnGap; } else { child.setSize(viewWidth - curX, child.height, true); } if (child.height > maxHeight) maxHeight = child.height; } //new line curY += Math.ceil(maxHeight) + _lineGap; maxHeight = 0; j = 0; lineStart = i + 1; lineSize = 0; } } ch = curY + Math.ceil(maxHeight); cw = viewWidth; } else { for(i=0;i<cnt;i++) { child = getChildAt(i); if (foldInvisibleItems && !child.visible) continue; if(curX!=0) curX += _columnGap; if (_columnCount != 0 && j >= _columnCount || _columnCount == 0 && curX + child.width > viewWidth && maxHeight != 0) { //new line curX = 0; curY += Math.ceil(maxHeight) + _lineGap; maxHeight = 0; j = 0; } child.setXY(curX, curY); curX += Math.ceil(child.width); if (curX > maxWidth) maxWidth = curX; if (child.height > maxHeight) maxHeight = child.height; j++; } ch = curY + Math.ceil(maxHeight); cw = Math.ceil(maxWidth); } } else if (_layout == ListLayoutType.FlowVertical) { if (_autoResizeItem && _lineCount > 0) { for (i = 0; i < cnt; i++) { child = getChildAt(i); if (foldInvisibleItems && !child.visible) continue; lineSize += child.sourceHeight; j++; if (j == _lineCount || i == cnt - 1) { ratio = (viewHeight - lineSize - (j - 1) * _lineGap) / lineSize; curY = 0; for (j = lineStart; j <= i; j++) { child = getChildAt(j); if (foldInvisibleItems && !child.visible) continue; child.setXY(curX, curY); if (j < i) { child.setSize(child.width, child.sourceHeight + Math.round(child.sourceHeight * ratio), true); curY += Math.ceil(child.height) + _lineGap; } else { child.setSize(child.width, viewHeight - curY, true); } if (child.width > maxWidth) maxWidth = child.width; } //new line curX += Math.ceil(maxWidth) + _columnGap; maxWidth = 0; j = 0; lineStart = i + 1; lineSize = 0; } } cw = curX + Math.ceil(maxWidth); ch = viewHeight; } else { for(i=0;i<cnt;i++) { child = getChildAt(i); if (foldInvisibleItems && !child.visible) continue; if(curY!=0) curY += _lineGap; if (_lineCount != 0 && j >= _lineCount || _lineCount == 0 && curY + child.height > viewHeight && maxWidth != 0) { curY = 0; curX += Math.ceil(maxWidth) + _columnGap; maxWidth = 0; j = 0; } child.setXY(curX, curY); curY += Math.ceil(child.height); if (curY > maxHeight) maxHeight = curY; if (child.width > maxWidth) maxWidth = child.width; j++; } cw = curX + Math.ceil(maxWidth); ch = Math.ceil(maxHeight); } } else //pagination { var eachHeight:int; if(_autoResizeItem && _lineCount>0) eachHeight = Math.floor((viewHeight-(_lineCount-1)*_lineGap)/_lineCount); if (_autoResizeItem && _columnCount > 0) { for (i = 0; i < cnt; i++) { child = getChildAt(i); if (foldInvisibleItems && !child.visible) continue; if (j==0 && (_lineCount != 0 && k >= _lineCount || _lineCount == 0 && curY + child.height > viewHeight)) { //new page page++; curY = 0; k = 0; } lineSize += child.sourceWidth; j++; if (j == _columnCount || i == cnt - 1) { ratio = (viewWidth - lineSize - (j - 1) * _columnGap) / lineSize; curX = 0; for (j = lineStart; j <= i; j++) { child = getChildAt(j); if (foldInvisibleItems && !child.visible) continue; child.setXY(page * viewWidth + curX, curY); if (j < i) { child.setSize(child.sourceWidth + Math.round(child.sourceWidth * ratio), _lineCount>0?eachHeight:child.height, true); curX += Math.ceil(child.width) + _columnGap; } else { child.setSize(viewWidth - curX, _lineCount>0?eachHeight:child.height, true); } if (child.height > maxHeight) maxHeight = child.height; } //new line curY += Math.ceil(maxHeight) + _lineGap; maxHeight = 0; j = 0; lineStart = i + 1; lineSize = 0; k++; } } } else { for (i = 0; i < cnt; i++) { child = getChildAt(i); if (foldInvisibleItems && !child.visible) continue; if (curX != 0) curX += _columnGap; if (_autoResizeItem && _lineCount > 0) child.setSize(child.width, eachHeight, true); if (_columnCount != 0 && j >= _columnCount || _columnCount == 0 && curX + child.width > viewWidth && maxHeight != 0) { //new line curX = 0; curY += Math.ceil(maxHeight) + _lineGap; maxHeight = 0; j = 0; k++; if (_lineCount != 0 && k >= _lineCount || _lineCount == 0 && curY + child.height > viewHeight && maxWidth != 0)//new page { page++; curY = 0; k = 0; } } child.setXY(page * viewWidth + curX, curY); curX += Math.ceil(child.width); if (curX > maxWidth) maxWidth = curX; if (child.height > maxHeight) maxHeight = child.height; j++; } } ch = page > 0 ? viewHeight : curY + Math.ceil(maxHeight); cw = (page + 1) * viewWidth; } handleAlign(cw, ch); setBounds(0,0,cw,ch); } override public function setup_beforeAdd(buffer:ByteBuffer, beginPos:int): void { super.setup_beforeAdd(buffer, beginPos); buffer.seek(beginPos, 5); var i:int; var j:int; var cnt:int; var i1:int; var i2:int; var nextPos:int; var str:String; _layout = buffer.readByte(); _selectionMode = buffer.readByte(); i1 = buffer.readByte(); _align = i1==0?"left":(i1==1?"center":"right"); i1 = buffer.readByte(); _verticalAlign = i1==0?"top":(i1==1?"middle":"bottom"); _lineGap = buffer.getInt16(); _columnGap = buffer.getInt16(); _lineCount = buffer.getInt16(); _columnCount = buffer.getInt16(); _autoResizeItem = buffer.readBool(); _childrenRenderOrder = buffer.readByte(); _apexIndex = buffer.getInt16(); if (buffer.readBool()) { _margin.top = buffer.getInt32(); _margin.bottom = buffer.getInt32(); _margin.left = buffer.getInt32(); _margin.right = buffer.getInt32(); } var overflow:int = buffer.readByte(); if (overflow == OverflowType.Scroll) { var savedPos:int = buffer.pos; buffer.seek(beginPos, 7); setupScroll(buffer); buffer.pos = savedPos; } else setupOverflow(overflow); if (buffer.readBool()) buffer.skip(8); buffer.seek(beginPos, 8); _defaultItem = buffer.readS(); var itemCount:int = buffer.getInt16(); for (i = 0; i < itemCount; i++) { nextPos = buffer.getInt16(); nextPos += buffer.pos; str = buffer.readS(); if (str == null) { str = defaultItem; if (!str) { buffer.pos = nextPos; continue; } } var obj:GObject = getFromPool(str); if (obj != null) { addChild(obj); str = buffer.readS(); if (str != null) obj.text = str; str = buffer.readS(); if (str != null && (obj is GButton)) (obj as GButton).selectedTitle = str; str = buffer.readS(); if (str != null) obj.icon = str; str = buffer.readS(); if (str != null && (obj is GButton)) (obj as GButton).selectedIcon = str; str = buffer.readS(); if (str != null) obj.name = str; if (obj is GComponent) { cnt = buffer.getInt16(); for (j = 0; j < cnt; j++) { var cc:Controller = (obj as GComponent).getController(buffer.readS()); str = buffer.readS(); if (cc != null) cc.selectedPageId = str; } } } buffer.pos = nextPos; } } override public function setup_afterAdd(buffer:ByteBuffer, beginPos:int):void { super.setup_afterAdd(buffer, beginPos); buffer.seek(beginPos, 6); var i:int = buffer.getInt16(); if (i != -1) _selectionController = parent.getControllerAt(i); } } } import fairygui.GObject; class ItemInfo { public var width:Number = 0; public var height:Number = 0; public var obj:GObject; public var updateFlag:uint = 0; public var selected:Boolean = false; public function ItemInfo():void { } }
package nz.co.codec.flexorm { import flash.data.SQLConnection; import flash.events.SQLErrorEvent; import flash.events.SQLEvent; import flash.filesystem.File; import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; import mx.collections.ArrayCollection; import mx.collections.IList; import mx.rpc.IResponder; import mx.rpc.Responder; import mx.utils.UIDUtil; import nz.co.codec.flexorm.command.BeginCommand; import nz.co.codec.flexorm.command.CommitCommand; import nz.co.codec.flexorm.command.DeleteCommand; import nz.co.codec.flexorm.command.InsertCommand; import nz.co.codec.flexorm.command.RollbackCommand; import nz.co.codec.flexorm.command.SelectCommand; import nz.co.codec.flexorm.command.UpdateCommand; import nz.co.codec.flexorm.criteria.Criteria; import nz.co.codec.flexorm.criteria.Sort; import nz.co.codec.flexorm.metamodel.AssociatedType; import nz.co.codec.flexorm.metamodel.Association; import nz.co.codec.flexorm.metamodel.CompositeKey; import nz.co.codec.flexorm.metamodel.Entity; import nz.co.codec.flexorm.metamodel.Field; import nz.co.codec.flexorm.metamodel.IDStrategy; import nz.co.codec.flexorm.metamodel.Identity; import nz.co.codec.flexorm.metamodel.ManyToManyAssociation; import nz.co.codec.flexorm.metamodel.OneToManyAssociation; import nz.co.codec.flexorm.metamodel.PersistentEntity; public class EntityManagerAsync extends EntityManagerBase implements IEntityManagerAsync { private static var _instance:EntityManagerAsync; private static var localInstantiation:Boolean; public static function get instance():EntityManagerAsync { if (_instance == null) { localInstantiation = true; _instance = new EntityManagerAsync(); localInstantiation = false; } return _instance; } public static function getInstance():EntityManagerAsync { if (_instance == null) { localInstantiation = true; _instance = new EntityManagerAsync(); localInstantiation = false; } return _instance; } /** * EntityManagerAsync is a Singleton. */ public function EntityManagerAsync() { super(); if (!localInstantiation) { throw new Error("EntityManagerAsync is a singleton. Use EntityManagerAsync.instance "); } } private var inTransaction:Boolean; private var dbFile:File; /** * Opens an asynchronous connection to the database. */ public function openAsyncConnection(dbFilename:String, responder:IResponder):void { dbFile = File.applicationStorageDirectory.resolvePath(dbFilename); sqlConnection = new SQLConnection(); var openHandler:Function = function(ev:SQLEvent):void { sqlConnection.removeEventListener(SQLEvent.OPEN, openHandler); sqlConnection.removeEventListener(SQLErrorEvent.ERROR, errorHandler); responder.result(ev); }; sqlConnection.addEventListener(SQLEvent.OPEN, openHandler); var errorHandler:Function = function(e:SQLErrorEvent):void { sqlConnection.removeEventListener(SQLEvent.OPEN, openHandler); sqlConnection.removeEventListener(SQLErrorEvent.ERROR, errorHandler); responder.fault(e); }; sqlConnection.addEventListener(SQLErrorEvent.ERROR, errorHandler); sqlConnection.openAsync(dbFile); } public function closeAsyncConnection(responder:IResponder):void { if (sqlConnection.connected) { var closeHandler:Function = function(ev:SQLEvent):void { sqlConnection.removeEventListener(SQLEvent.CLOSE, closeHandler); sqlConnection.removeEventListener(SQLErrorEvent.ERROR, errorHandler); responder.result(ev); }; sqlConnection.addEventListener(SQLEvent.CLOSE, closeHandler); var errorHandler:Function = function(e:SQLErrorEvent):void { sqlConnection.removeEventListener(SQLEvent.CLOSE, closeHandler); sqlConnection.removeEventListener(SQLErrorEvent.ERROR, errorHandler); responder.fault(e); }; sqlConnection.addEventListener(SQLErrorEvent.ERROR, errorHandler); sqlConnection.close(); } } public function deleteDBFile():void { dbFile.deleteFile(); } public function startTransaction(responder:IResponder):void { var beginCommand:BeginCommand = new BeginCommand(sqlConnection); beginCommand.responder = responder; beginCommand.execute(); inTransaction = true; } public function endTransaction(responder:IResponder):void { var commitCommand:CommitCommand = new CommitCommand(sqlConnection); commitCommand.responder = new Responder( function(event:EntityEvent):void { responder.result(event); inTransaction = false; }, function(error:EntityErrorEvent):void { if (sqlConnection.inTransaction) { var rollbackCommand:RollbackCommand = new RollbackCommand(sqlConnection); rollbackCommand.responder = new Responder( function(ev:EntityEvent):void { error.message = "Rollback successful: " + error.message; responder.fault(error); }, function(e:EntityErrorEvent):void { trace("Rollback failed!!!"); error.message = e.message + ": " + error.message; responder.fault(error); } ); } else { responder.fault(error); } inTransaction = false; } ); } private function getEntityForObject(obj:Object, q:BlockingExecutor):Entity { var c:Class = (obj is PersistentEntity) ? obj.__class : Class(getDefinitionByName(getQualifiedClassName(obj))); return getEntity(c, q); } private function getEntity(cls:Class, q:BlockingExecutor):Entity { var c:Class = (cls is PersistentEntity) ? cls.__class : cls; var cn:String = getClassName(c); var entity:Entity = entityMap[cn]; if (entity == null || !entity.initialisationComplete) { entity = introspector.loadMetadata(c, q); } return entity; } private function createBlockingExecutor(responder:IResponder, finalHandler:Function=null):BlockingExecutor { var q:BlockingExecutor = new BlockingExecutor(); q.debugLevel = debugLevel; q.responder = responder; q.finalHandler = finalHandler; return q; } public function findAll(cls:Class, responder:IResponder):void { var q:BlockingExecutor = createBlockingExecutor(responder, function(data:Object):void { clearCache(); }); var entity:Entity = getEntity(cls, q); q.add(entity.selectAllCommand.clone(), function(data:Object):void { q.data = typeArray(data as Array, entity, q.branchBlocking()); }); q.execute(); } public function loadOneToManyAssociation(a:OneToManyAssociation, idMap:Object, responder:IResponder):void { var branch:BlockingExecutor; var q:BlockingExecutor = createBlockingExecutor(responder, function(data:Object):void { q.data = branch.data; clearCache(); }); branch = q.branchBlocking(); loadOneToManyAssociationInternal(a, idMap, branch); q.execute(); } private function loadOneToManyAssociationInternal(a:OneToManyAssociation, idMap:Object, q:BlockingExecutor):void { var items:Array = []; q.finalHandler = function(data:Object):void { if (a.indexed) items.sortOn("index"); var result:ArrayCollection = new ArrayCollection(); for each(var it:Object in items) { result.addItem(typeObject(it.row, it.associatedEntity, q)); } q.data = result; }; for each(var type:AssociatedType in a.associatedTypes) { loadAssociatedType(a, items, type, idMap, q); } } private function loadAssociatedType( a:OneToManyAssociation, items:Array, type:AssociatedType, idMap:Object, q:BlockingExecutor):void { var associatedEntity:Entity = type.associatedEntity; var selectCommand:SelectCommand = type.selectCommand.clone(); setIdentMapParams(selectCommand, idMap); q.add(selectCommand, function(data:Object):void { if (data) { var row:Object; if (associatedEntity.isSuperEntity()) { var subtypes:Object = {}; for each(row in data) { subtypes[row.entity_type] = null; } for (var subtype:String in subtypes) { loadSubtype(a, items, associatedEntity, subtype, idMap, q); } } else { for each(row in data) { items.push( { associatedEntity: associatedEntity, index : getDbColumn(row, a.indexColumn), row : row }); } } } }); } private function loadSubtype( a:OneToManyAssociation, items:Array, associatedEntity:Entity, subtype:String, idMap:Object, q:BlockingExecutor):void { var subClass:Class = getDefinitionByName(subtype) as Class; var subEntity:Entity = getEntity(subClass, q); var selectSubtypeCommand:SelectCommand = subEntity.selectSubtypeCommand.clone(); var ownerEntity:Entity = a.ownerEntity; if (ownerEntity.hasCompositeKey()) { for each(var identity:Identity in ownerEntity.identities) { selectSubtypeCommand.addFilter(identity.fkColumn, identity.fkProperty, associatedEntity.table); selectSubtypeCommand.setParam(identity.fkProperty, idMap[identity.fkProperty]); } } else { selectSubtypeCommand.addFilter(a.fkColumn, a.fkProperty, associatedEntity.table); selectSubtypeCommand.setParam(a.fkProperty, idMap[a.fkProperty]); } if (a.indexed) selectSubtypeCommand.addSort(a.indexColumn, Sort.ASC, associatedEntity.table); q.add(selectSubtypeCommand, function(data:Object):void { for each(var row:Object in data) { items.push( { associatedEntity: subEntity, index : getDbColumn(row, a.indexColumn), row : row }); } }); } /** * Return a list of the associated objects in a many-to-many association * using a map of the key values (fkProperty : value). */ public function loadManyToManyAssociation(a:ManyToManyAssociation, idMap:Object, responder:IResponder):void { var q:BlockingExecutor = createBlockingExecutor(responder); var selectCommand:SelectCommand = a.selectCommand.clone(); setIdentMapParams(selectCommand, idMap); q.add(selectCommand, function(data:Object):void { q.data = typeArray(data as Array, a.associatedEntity, q); }); q.execute(); } public function load(cls:Class, id:*, responder:IResponder):void { loadItem(cls, id, responder); } public function loadItem(cls:Class, id:*, responder:IResponder):void { var q:BlockingExecutor = createBlockingExecutor(responder, function(data:Object):void { clearCache(); }); var entity:Entity = getEntity(cls, q); if (entity.hasCompositeKey()) { throw new Error("Entity '" + entity.name + "' has a composite key. " + "Use EntityManagerAsync.loadItemByCompositeKey instead. "); } loadComplexEntity(entity, getIdentityMap(entity.fkProperty, id), q); q.execute(); } private function loadComplexEntity(entity:Entity, idMap:Object, q:BlockingExecutor):void { var selectCommand:SelectCommand = entity.selectCommand.clone(); setIdentMapParams(selectCommand, idMap); q.add(selectCommand, function(data:Object):void { if (data) { var row:Object = data[0]; // Add to cache to avoid reselecting from database q.data = typeObject(row, entity, q); if (entity.isSuperEntity()) { var subtype:String = row.entity_type; if (subtype) { var subClass:Class = getDefinitionByName(subtype) as Class; var subEntity:Entity = getEntity(subClass, q); if (subEntity == null) throw new Error("Cannot find entity of type " + subtype); var map:Object = entity.hasCompositeKey() ? getIdentityMapFromRow(row, subEntity) : getIdentityMap(subEntity.fkProperty, idMap[entity.fkProperty]); var value:Object = getCachedValue(subEntity, map); if (value) { q.data = value; } else { loadComplexEntity(subEntity, map, q); } } } } else { q.fault(new EntityErrorEvent(debug("Load of " + entity.name + " failed. "))); } }); } private function loadEntity(entity:Entity, idMap:Object, q:BlockingExecutor):void { var selectCommand:SelectCommand = entity.selectCommand.clone(); setIdentMapParams(selectCommand, idMap); q.add(selectCommand, function(data:Object):void { if (data) { q.data = typeObject(data[0], entity, q); } else { q.fault(new EntityErrorEvent(debug("Load of " + entity.name + " failed. "))); } }); } public function loadItemByCompositeKey(cls:Class, keys:Array, responder:IResponder):void { var q:BlockingExecutor = createBlockingExecutor(responder, function(data:Object):void { clearCache(); }); var entity:Entity = getEntity(cls, q); if (!entity.hasCompositeKey()) { throw new Error("Entity '" + entity.name + "' does not have a composite key. Use EntityManagerAsync.loadItem instead. "); } var idMap:Object = {}; for each(var obj:Object in keys) { var keyEntity:Entity = getEntityForObject(obj, q); // Validate if key is a specified identifier for entity var match:Boolean = false; for each(var key:CompositeKey in entity.keys) { if (keyEntity.equals(key.associatedEntity)) { match = true; break; } } // if not, then check if key type is used in a many-to-one // association instead if (!match) { trace("Key of type '" + keyEntity.name + "' not specified as an identifier for '" + entity.name + "'. "); for each (var aOto:Association in entity.oneToOneAssociations) { if (keyEntity.equals(aOto.associatedEntity)) { trace("Key type '" + keyEntity.name + "' is used in a one-to-one association, so will allow. "); match = true; break; } } for each (var aMto:Association in entity.manyToOneAssociations) { if (keyEntity.equals(aMto.associatedEntity)) { trace("Key type '" + keyEntity.name + "' is used in a many-to-one association, so will allow. "); match = true; break; } } } if (match) { idMap = combineMaps([idMap, getIdentityMapFromInstance(obj, keyEntity)]); } else { throw new Error("Invalid key of type '" + keyEntity.name + "' specified. "); } } loadComplexEntity(entity, idMap, q); q.execute(); } /** * Insert or update an object into the database, depending on whether * the object is new (determined by an id > 0). Metadata for the object, * and all associated objects, will be loaded on a just-in-time basis. * The save operation and all cascading saves are enclosed in a * transaction to ensure the database is left in a consistent state. * * opt(ions), from client code: * - name:String * - ownerClass:Class * Must be set if the client code specifies an indexValue so to * determine the class that owns the indexed list. * - indexValue:int * Set by client code when saving an indexed object directly, * instead of saving the object that owns the list and using the * cascade 'save-update' behaviour to set the index property on * each item in the list. * - lft:int * Sets the left boundary index when saving a nested set object (a * node in a hierarchy) directly, instead of saving the parent * object and using the cascade 'save-update' behaviour to set the * nested set properties on each child in the list. * * The lft and ownerClass/indexValue properties are mutually exclusive; * ie., the ownerClass and indexValue are unnecessary for a nested set * object. The indexed position will be determined from the lft value. * * The rgt property is unnecessary as it will be set to lft + 1 if the * object is new, or to lft + the distance of the object's current rgt * value from the current lft value. * * SaveRecursiveArgs, system-defined: * - name:String * - a:Association (OneToMany || ManyToMany) * - associatedEntity:Entity * - hasCompositeKey:Boolean * - idMap:Object * - mtmInsertCommand:InsertCommand * - indexValue:int * - subInsertCommand:InsertCommand * - entityType:String * - fkProperty:String * - lft:int * - rootEval:Boolean * - rootLft:int * - rootSpread:int */ public function save(obj:Object, responder:IResponder, opt:Object=null):void { if (obj == null) return; var args:SaveRecursiveArgs = new SaveRecursiveArgs(); for (var key:String in opt) { args[key] = opt[key]; } var q:BlockingExecutor = createBlockingExecutor(responder, function(data:Object):void { clearCache(); }); // if not already part of a programmer-defined transaction, then // start one to group all cascade 'save-update' operations if (!inTransaction) { q.add(new BeginCommand(sqlConnection)); saveItem(obj, q, args); q.add(new CommitCommand(sqlConnection)); } else { saveItem(obj, q, args); } q.execute(); } private function saveItem(obj:Object, q:BlockingExecutor, args:SaveRecursiveArgs):void { if (obj == null) return; var entity:Entity = getEntityForObject(obj, q); if (entity.hasCompositeKey()) { var selectCommand:SelectCommand = entity.selectCommand; // Validate that each composite key is not null. for each(var key:CompositeKey in entity.keys) { var value:Object = obj[key.property]; if (value == null) throw new Error("Object of type '" + entity.name + "' has a null key. "); } setIdentityParams(selectCommand, obj, entity); q.add(selectCommand, function(data:Object):void { if (data) { updateItem(entity.updateCommand.clone(), obj, entity, q, args); } else { createItem(entity.insertCommand.clone(), obj, entity, q, args); } }); } else { var id:* = obj[entity.pk.property]; if (idAssigned(id)) { updateItem(entity.updateCommand.clone(), obj, entity, q, args); } else { createItem(entity.insertCommand.clone(), obj, entity, q, args); } } } private function createItem( insertCommand:InsertCommand, obj:Object, entity:Entity, q:BlockingExecutor, args:SaveRecursiveArgs):void { saveOneToOneAssociations(obj, entity, q.branchNonBlocking()); saveManyToOneAssociations(obj, entity, q.branchNonBlocking()); if (entity.superEntity) { args.subInsertCommand = insertCommand; args.entityType = getQualifiedClassName(entity.cls); args.fkProperty = entity.fkProperty; createItem(entity.superEntity.insertCommand.clone(), obj, entity.superEntity, q, args); } setFieldParams(insertCommand, obj, entity); setOneToOneAssociationParams(insertCommand, obj, entity); setManyToOneAssociationParams(insertCommand, obj, entity); setInsertTimestampParams(insertCommand, obj); if (entity.isSuperEntity()) { insertCommand.setParam("entityType", args.entityType); } if (prefs.syncSupport && !entity.hasCompositeKey()) { insertCommand.setParam("version", 0); insertCommand.setParam("serverId", 0); } insertCommand.setParam("markedForDeletion", false); // if this obj is an item of a one-to-many association and matches // the specific entity, that is the object of the association, in // the entity's inheritance hierarchy... if ((args.a is OneToManyAssociation) && entity.equals(args.associatedEntity)) { if (args.hasCompositeKey) { setIdentMapParams(insertCommand, args.idMap); } else { q.addFunction(function(data:Object):void { insertCommand.setParam(args.a.fkProperty, q.parent.parent.id); }); } if (args.a.indexed) insertCommand.setParam(args.a.indexProperty, args.indexValue); } if (args.a == null) { for each(var aOtm:OneToManyAssociation in entity.oneToManyInverseAssociations) { if (aOtm.indexed) { // specified by client code if ((aOtm.ownerEntity.cls == args.ownerClass) && args.indexValue) { insertCommand.setParam(aOtm.indexProperty, args.indexValue); } else { insertCommand.setParam(aOtm.indexProperty, 0); } } } } var id:*; if (!entity.hasCompositeKey() && (IDStrategy.UID == entity.pk.strategy)) { id = UIDUtil.createUID(); insertCommand.setParam(entity.fkProperty, id); obj[entity.pk.property] = id; } q.add(insertCommand, function(data:Object):void { if (!entity.hasCompositeKey() && (entity.superEntity == null)) { if (IDStrategy.AUTO_INCREMENT == entity.pk.strategy) { id = data; obj[entity.pk.property] = id; } var subInsertCommand:InsertCommand = args.subInsertCommand; if (subInsertCommand) subInsertCommand.setParam(args.fkProperty, id); q.id = id; q.label = entity.name; } q.data = obj; }); // The mtmInsertCommand must be executed after the associated entity // has been inserted to maintain referential integrity. if ((args.a is ManyToManyAssociation) && entity.equals(args.associatedEntity)) { var mtmInsertCommand:InsertCommand = args.mtmInsertCommand; if (args.hasCompositeKey || (IDStrategy.UID == entity.pk.strategy)) { setIdentityParams(mtmInsertCommand, obj, entity); setIdentMapParams(mtmInsertCommand, args.idMap); } else { q.addFunction(function(data:Object):void { mtmInsertCommand.setParam(entity.fkProperty, data); mtmInsertCommand.setParam(args.a.ownerEntity.fkProperty, q.parent.parent.id); }); } if (args.a.indexed) mtmInsertCommand.setParam(args.a.indexProperty, args.indexValue); q.add(mtmInsertCommand); } var idMap:Object = getIdentityMapFromInstance(obj, entity); var executor:NonBlockingExecutor = q.branchNonBlocking(); saveOneToManyAssociations(obj, entity, idMap, executor); for each(var mtm:ManyToManyAssociation in entity.manyToManyAssociations) { saveManyToManyAssociation(obj, false, mtm, idMap, executor.branchBlocking()); } } private function updateItem( updateCommand:UpdateCommand, obj:Object, entity:Entity, q:BlockingExecutor, args:SaveRecursiveArgs):void { saveOneToOneAssociations(obj, entity, q.branchNonBlocking()); saveManyToOneAssociations(obj, entity, q.branchNonBlocking()); if (entity.superEntity) updateItem(entity.superEntity.updateCommand.clone(), obj, entity.superEntity, q, args); setIdentityParams(updateCommand, obj, entity); setFieldParams(updateCommand, obj, entity); setOneToOneAssociationParams(updateCommand, obj, entity); setManyToOneAssociationParams(updateCommand, obj, entity); setUpdateTimestampParams(updateCommand, obj); if ((args.a is OneToManyAssociation) && entity.equals(args.associatedEntity)) { setIdentMapParams(updateCommand, args.idMap); if (args.a.indexed) updateCommand.setParam(args.a.indexProperty, args.indexValue); } if (args.a == null) { for each(var aOtm:OneToManyAssociation in entity.oneToManyInverseAssociations) { if (aOtm.indexed) { // specified by client code if ((aOtm.ownerEntity.cls == args.ownerClass) && args.indexValue) { updateCommand.setParam(aOtm.indexProperty, args.indexValue); } else { updateCommand.setParam(aOtm.indexProperty, 0); } } } } q.add(updateCommand); q.data = obj; if ((args.a is ManyToManyAssociation) && entity.equals(args.associatedEntity)) { var mtmInsertCommand:InsertCommand = args.mtmInsertCommand; setIdentityParams(mtmInsertCommand, obj, entity); setIdentMapParams(mtmInsertCommand, args.idMap); if (args.a.indexed) mtmInsertCommand.setParam(args.a.indexProperty, args.indexValue); q.add(mtmInsertCommand); } var idMap:Object = getIdentityMapFromInstance(obj, entity); var executor:NonBlockingExecutor = q.branchNonBlocking(); saveOneToManyAssociations(obj, entity, idMap, executor); for each(var mtm:ManyToManyAssociation in entity.manyToManyAssociations) { saveManyToManyAssociation(obj, true, mtm, idMap, executor.branchBlocking()); } } private function saveOneToOneAssociations(obj:Object, entity:Entity, executor:NonBlockingExecutor):void { for each (var aOto:Association in entity.oneToOneAssociations) { var value:Object = obj[aOto.property]; if (value && !aOto.inverse && isCascadeSave(aOto)) saveItem(value, executor.branchBlocking(), new SaveRecursiveArgs()); } } private function saveManyToOneAssociations(obj:Object, entity:Entity, executor:NonBlockingExecutor):void { for each(var aMto:Association in entity.manyToOneAssociations) { var value:Object = obj[aMto.property]; if (value && !aMto.inverse && isCascadeSave(aMto)) saveItem(value, executor.branchBlocking(), new SaveRecursiveArgs()); } } private function saveOneToManyAssociations(obj:Object, entity:Entity, idMap:Object, executor:NonBlockingExecutor):void { for each (var aOtm:OneToManyAssociation in entity.oneToManyAssociations) { if (!entity.hasCompositeKey()) { idMap = getIdentityMap(aOtm.fkProperty, obj[entity.pk.property]); } var value:IList = obj[aOtm.property]; if (value && !aOtm.inverse && (!aOtm.lazy || !(value is LazyList) || LazyList(value).loaded) && isCascadeSave(aOtm)) { for (var i:int = 0; i < value.length; i++) { var item:Object = value.getItemAt(i); var q:BlockingExecutor = executor.branchBlocking(); var itemEntity:Entity = getEntityForObject(item, q); var associatedEntity:Entity = aOtm.getAssociatedEntity(itemEntity); if (associatedEntity) { var args:SaveRecursiveArgs = new SaveRecursiveArgs(); args.a = aOtm; args.associatedEntity = associatedEntity; args.hasCompositeKey = entity.hasCompositeKey(); args.idMap = idMap; if (aOtm.indexed) args.indexValue = i; saveItem(item, q, args); } else { throw new Error("Attempting to save a collection " + "item of a type not specified in " + "the one-to-many association. "); } } } } } private function saveManyToManyAssociation(obj:Object, update:Boolean, a:ManyToManyAssociation, idMap:Object, q:BlockingExecutor):void { var value:IList = obj[a.property]; if (value && (!a.lazy || !(value is LazyList) || LazyList(value).loaded)) { var selectExistingCommand:SelectCommand = a.selectManyToManyKeysCommand; var hasCompositeKey:Boolean = a.ownerEntity.hasCompositeKey(); if (hasCompositeKey || update) { setIdentMapParams(selectExistingCommand, idMap); } else { q.addFunction(function(data:Object):void { idMap[a.ownerEntity.fkProperty] = q.parent.parent.id; setIdentMapParams(selectExistingCommand, idMap); }); } q.add(selectExistingCommand, function(data:Object):void { var existing:Array = []; for each(var row:Object in data) { existing.push(getIdentityMapFromMtmAssociation(row, a)); } var map:Object; for (var i:int = 0; i < value.length; i++) { var item:Object = value.getItemAt(i); var itemIdMap:Object = getIdentityMapFromInstance(item, a.associatedEntity); var isLinked:Boolean = false; var k:int = 0; for each(map in existing) { isLinked = true; for each(var identity:Identity in a.associatedEntity.identities) { if (itemIdMap[identity.fkProperty] != map[identity.fkProperty]) { isLinked = true; break; } } if (isLinked) break; k++; } if (isLinked) // then no need to create the associationTable { if (isCascadeSave(a)) { if (a.indexed) { var updateCommand:UpdateCommand = a.updateCommand.clone(); setIdentMapParams(updateCommand, idMap); setIdentMapParams(updateCommand, itemIdMap); updateCommand.setParam(a.indexProperty, i); q.add(updateCommand); } saveItem(item, q, new SaveRecursiveArgs()); } existing.splice(k, 1); } else { var insertCommand:InsertCommand = a.insertCommand.clone(); if (isCascadeSave(a)) { // insert link in associationTable after // inserting the associated entity instance var args:SaveRecursiveArgs = new SaveRecursiveArgs(); args.a = a; args.associatedEntity = a.associatedEntity; args.hasCompositeKey = hasCompositeKey; args.idMap = idMap; args.mtmInsertCommand = insertCommand; if (a.indexed) args.indexValue = i; saveItem(item, q, args); } else // just create the link instead { setIdentMapParams(insertCommand, idMap); setIdentMapParams(insertCommand, itemIdMap); if (a.indexed) insertCommand.setParam(a.indexProperty, i); q.add(insertCommand); } } } // for each pre index left for each(map in existing) { // delete link from associationTable var deleteCommand:DeleteCommand = a.deleteCommand; setIdentMapParams(deleteCommand, idMap); setIdentMapParams(deleteCommand, map); q.add(deleteCommand); } }); } } public function markForDeletion(obj:Object, responder:IResponder):void { var q:BlockingExecutor = createBlockingExecutor(responder); var entity:Entity = getEntityForObject(obj, q); var markForDeletionCommand:UpdateCommand = entity.markForDeletionCommand; setIdentityParams(markForDeletionCommand, obj, entity); q.add(markForDeletionCommand); q.execute(); } public function removeItem(cls:Class, id:*, responder:IResponder):void { loadItem(cls, id, new Responder( function(ev:EntityEvent):void { remove(ev.data, responder); }, function(e:EntityErrorEvent):void { trace(e); responder.fault(e); } )); } public function remove(obj:Object, responder:IResponder):void { var q:BlockingExecutor = createBlockingExecutor(responder); // if not already part of a programmer-defined transaction, // then start one to group all cascade 'delete' operations if (!inTransaction) { q.add(new BeginCommand(sqlConnection)); removeObject(obj, q); q.add(new CommitCommand(sqlConnection)); } else { removeObject(obj, q); } q.execute(); } private function removeObject(obj:Object, q:BlockingExecutor):void { removeEntity(getEntityForObject(obj, q), obj, q); } private function removeEntity(entity:Entity, obj:Object, q:BlockingExecutor):void { if (entity == null) return; removeOneToManyAssociations(entity, obj, q.branchNonBlocking()); // Doesn't make sense to support 'cascade delete' // on many-to-many associations var deleteCommand:DeleteCommand = entity.deleteCommand; setIdentityParams(deleteCommand, obj, entity); q.add(deleteCommand); removeEntity(entity.superEntity, obj, q); removeOneToOneAssociations(entity, obj, q.branchNonBlocking()); removeManyToOneAssociations(entity, obj, q.branchNonBlocking()); } // TODO I had changed this for performance, but I should revert back // to iterating through and removeObject to remove the object graph // to effect any cascade delete of associations of the removed object. private function removeOneToManyAssociations(entity:Entity, obj:Object, executor:NonBlockingExecutor):void { for each(var aOtm:OneToManyAssociation in entity.oneToManyAssociations) { if (isCascadeDelete(aOtm)) { if (aOtm.multiTyped) { for each(var type:AssociatedType in aOtm.associatedTypes) { removeEntity(type.associatedEntity, obj, executor.branchBlocking()); } } else { var deleteCommand:DeleteCommand = aOtm.deleteCommand; if (entity.hasCompositeKey()) { setIdentityParams(deleteCommand, obj, entity); } else { deleteCommand.setParam(aOtm.fkProperty, obj[entity.pk.property]); } executor.add(deleteCommand); } } else // set the FK to 0 { var updateCommand:UpdateCommand = aOtm.updateFKAfterDeleteCommand; if (entity.hasCompositeKey()) { setIdentityParams(updateCommand, obj, entity); } else { updateCommand.setParam(aOtm.fkProperty, obj[entity.pk.property]); } executor.add(updateCommand); } } } private function removeOneToOneAssociations(entity:Entity, obj:Object, executor:NonBlockingExecutor):void { for each (var aOto:Association in entity.oneToOneAssociations) { var value:Object = obj[aOto.property]; if (value && isCascadeDelete(aOto)) { removeObject(value, executor.branchBlocking()); } } } private function removeManyToOneAssociations(entity:Entity, obj:Object, executor:NonBlockingExecutor):void { for each(var aMto:Association in entity.manyToOneAssociations) { var value:Object = obj[aMto.property]; if (value && isCascadeDelete(aMto)) { removeObject(value, executor.branchBlocking()); } } } private function typeArray(array:Array, entity:Entity, q:BlockingExecutor):ArrayCollection { var coll:ArrayCollection = new ArrayCollection(); for each(var row:Object in array) { coll.addItem(typeObject(row, entity, q)); } return coll; } private function typeObject(row:Object, entity:Entity, q:BlockingExecutor):Object { if (row == null) return null; var value:Object = getCachedValue(entity, getIdentityMapFromRow(row, entity)); if (value) return value; var instance:Object = new entity.cls(); for each(var f:Field in entity.fields) { if (f.type == SQLType.DATE) { // Views return a Number or String instead of a Date (which cannot be cast to Date type) instance[f.property] = ConvertToDate(getDbColumn(row, f.column)); } else { instance[f.property] = getDbColumn(row, f.column); } } loadSuperProperties(instance, row, entity, q); var executor:NonBlockingExecutor = q.branchNonBlocking(); for each (var aOto:Association in entity.oneToOneAssociations) { setOneToOneAssociation(instance, row, aOto, executor.branchBlocking()); } for each (var aMto:Association in entity.manyToOneAssociations) { setManyToOneAssociation(instance, row, aMto, executor.branchBlocking()); } // Must be after keys on instance has been loaded, which includes: // # loadManyToOneAssociation to load composite keys, and // # loadSuperProperties to load inherited keys. if (entity.hasCompositeKey()) { // then must be after many-to-one associations have been loaded // to set composite keys q.addFunction(function(data:Object):void { setListAssociations(instance, row, entity, q.branchNonBlocking()); }); } else { setListAssociations(instance, row, entity, executor); } return instance; } private function setListAssociations(instance:Object, row:Object, entity:Entity, executor:NonBlockingExecutor):void { setCachedValue(instance, entity); for each(var otm:OneToManyAssociation in entity.oneToManyAssociations) { setOneToManyAssociation(instance, row, otm, entity, executor.branchBlocking()); } for each(var mtm:ManyToManyAssociation in entity.manyToManyAssociations) { setManyToManyAssociation(instance, row, mtm, entity, executor.branchBlocking()); } } private function loadSuperProperties( instance:Object, row:Object, entity:Entity, q:BlockingExecutor):void { var superEntity:Entity = entity.superEntity; if (superEntity == null) return; var idMap:Object = entity.hasCompositeKey() ? getIdentityMapFromRow(row, superEntity) : getIdentityMap(superEntity.fkProperty, getDbColumn(row, entity.pk.column)); var superInstance:Object = getCachedValue(superEntity, idMap); if (superInstance == null) { // No need to select since I have the super entity's columns // from the join in the original select. I just need to call // typeObject to load any associations of the super entity. setSuperProperties(instance, typeObject(row, superEntity, q), superEntity); } else { setSuperProperties(instance, superInstance, superEntity); } } private function setSuperProperties(instance:Object, superInstance:Object, superEntity:Entity):void { for each(var f:Field in superEntity.fields) { // commented out to populate a sub instance's inherited ID field // if (superEntity.hasCompositeKey() || (f.property != superEntity.pk.property)) // { instance[f.property] = superInstance[f.property]; // } } for each (var oto:Association in superEntity.oneToOneAssociations) { instance[oto.property] = superInstance[oto.property]; } for each(var mto:Association in superEntity.manyToOneAssociations) { instance[mto.property] = superInstance[mto.property]; } for each(var otm:Association in superEntity.oneToManyAssociations) { instance[otm.property] = superInstance[otm.property]; } for each(var mtm:Association in superEntity.manyToManyAssociations) { instance[mtm.property] = superInstance[mtm.property]; } } private function setOneToOneAssociation(instance:Object, row:Object, a:Association, q:BlockingExecutor):void { var associatedEntity:Entity = a.associatedEntity; var value:Object = null; if (!associatedEntity.isSuperEntity()) { value = getCachedAssociationValue(a, row); } if (value) { instance[a.property] = value; } else { var idMap:Object = null; if (associatedEntity.hasCompositeKey()) { idMap = getIdentityMapFromAssociation(row, associatedEntity); } else { var id:* = getDbColumn(row, a.fkColumn); if (idAssigned(id)) { idMap = getIdentityMap(associatedEntity.fkProperty, id); } } if (idMap) { loadComplexEntity(associatedEntity, idMap, q.branchBlocking()); q.addFunction(function(data:Object):void { instance[a.property] = data.data; }); } } } private function setManyToOneAssociation( instance:Object, row:Object, a:Association, q:BlockingExecutor):void { var associatedEntity:Entity = a.associatedEntity; var value:Object = null; if (!associatedEntity.isSuperEntity()) { value = getCachedAssociationValue(a, row); } if (value) { instance[a.property] = value; } else { var idMap:Object = null; if (associatedEntity.hasCompositeKey()) { idMap = getIdentityMapFromAssociation(row, associatedEntity); } else { var id:* = getDbColumn(row, a.fkColumn); if (idAssigned(id)) { idMap = getIdentityMap(associatedEntity.fkProperty, id); } } if (idMap) { loadComplexEntity(associatedEntity, idMap, q.branchBlocking()); q.addFunction(function(data:Object):void { instance[a.property] = data.data; }); } } } private function setOneToManyAssociation( instance:Object, row:Object, a:OneToManyAssociation, entity:Entity, q:BlockingExecutor):void { var idMap:Object = entity.hasCompositeKey() ? getIdentityMapFromRow(row, entity) : getIdentityMap(a.fkProperty, getDbColumn(row, entity.pk.column)); // Lazy Loading not supported using the Asynchronous API yet // if (a.lazy) // { // var lazyList:LazyList = new LazyList(this, a, idMap); // var value:ArrayCollection = new ArrayCollection(); // value.list = lazyList; // instance[a.property] = value; // lazyList.initialise(); // } // else // { // TODO optimise if not multiple types loadOneToManyAssociationInternal(a, idMap, q.branchBlocking()); q.addFunction(function(data:Object):void { instance[a.property] = data.data; }); // } } private function setManyToManyAssociation( instance:Object, row:Object, a:ManyToManyAssociation, entity:Entity, q:BlockingExecutor):void { // Lazy Loading not supported using the Asynchronous API yet // if (a.lazy) // { // var lazyList:LazyList = new LazyList(this, a, getIdentityMapFromRow(row, entity)); // var value:ArrayCollection = new ArrayCollection(); // value.list = lazyList; // instance[a.property] = value; // lazyList.initialise(); // } // else // { var selectCommand:SelectCommand = a.selectCommand; setIdentMapParams(selectCommand, getIdentityMapFromRow(row, entity)); q.add(selectCommand, function(data:Object):void { instance[a.property] = typeArray(data as Array, a.associatedEntity, q); }); // } } public function createCriteria(cls:Class, responder:IResponder):void { var q:BlockingExecutor = createBlockingExecutor(responder); var entity:Entity = getEntity(cls, q); q.addFunction(function(data:Object):void { q.data = new Criteria(entity); }); q.execute(); } public function fetchCriteria(crit:Criteria, responder:IResponder):void { var q:BlockingExecutor = createBlockingExecutor(responder, function(data:Object):void { clearCache(); }); var selectCommand:SelectCommand = crit.entity.selectCommand.clone(); selectCommand.setCriteria(crit); q.add(selectCommand, function(data:Object):void { q.data = typeArray(data as Array, crit.entity, q.branchBlocking()); }); q.execute(); } public function fetchCriteriaFirstResult(crit:Criteria, responder:IResponder):void { var q:BlockingExecutor = createBlockingExecutor(responder, function(data:Object):void { clearCache(); }); var selectCommand:SelectCommand = crit.entity.selectCommand.clone(); selectCommand.setCriteria(crit); q.add(selectCommand, function(data:Object):void { if (data) { var result:Array = data as Array; if (result.length > 0) q.data = typeObject(result[0], crit.entity, q.branchBlocking()); else q.data = null; } }); q.execute(); } private function debug(message:String):String { if (debugLevel > 0) { trace(message); } return message; } } }
package Scenery { import net.flashpunk.Entity; import net.flashpunk.graphics.Image; /** * ... * @author Time */ public class Dresser extends Entity { [Embed(source = "../../assets/graphics/Dresser.png")] private var imgDresser:Class; private var sprDresser:Image = new Image(imgDresser); public function Dresser(_x:int, _y:int) { super(_x, _y, sprDresser); sprDresser.y = -8; sprDresser.originY = -sprDresser.y; setHitbox(32, 16); type = "Solid"; layer = -(y - originY + height * 4/5); } } }
// ================================================================================================= // // Starling Framework - Particle System Extension // Copyright 2012 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.extensions { import com.adobe.utils.AGALMiniAssembler; import flash.display3D.Context3D; import flash.display3D.Context3DBlendFactor; import flash.display3D.Context3DProgramType; import flash.display3D.Context3DVertexBufferFormat; import flash.display3D.IndexBuffer3D; import flash.display3D.Program3D; import flash.display3D.VertexBuffer3D; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import starling.animation.IAnimatable; import starling.core.RenderSupport; import starling.core.Starling; import starling.display.DisplayObject; import starling.errors.MissingContextError; import starling.events.Event; import starling.textures.Texture; import starling.textures.TextureSmoothing; import starling.utils.MatrixUtil; import starling.utils.VertexData; /** Dispatched when emission of particles is finished. */ [Event(name="complete", type="starling.events.Event")] public class ParticleSystem extends DisplayObject implements IAnimatable { public static const MAX_NUM_PARTICLES:int = 16383; private var mTexture:Texture; private var mParticles:Vector.<Particle>; private var mFrameTime:Number; private var mProgram:Program3D; private var mVertexData:VertexData; private var mVertexBuffer:VertexBuffer3D; private var mIndices:Vector.<uint>; private var mIndexBuffer:IndexBuffer3D; private var mNumParticles:int; private var mMaxCapacity:int; private var mEmissionRate:Number; // emitted particles per second private var mEmissionTime:Number; /** Helper objects. */ private static var sHelperMatrix:Matrix = new Matrix(); private static var sHelperPoint:Point = new Point(); private static var sRenderAlpha:Vector.<Number> = new <Number>[1.0, 1.0, 1.0, 1.0]; protected var mEmitterX:Number; protected var mEmitterY:Number; protected var mBlendFactorSource:String; protected var mBlendFactorDestination:String; protected var mSmoothing:String; public function ParticleSystem(texture:Texture, emissionRate:Number, initialCapacity:int=128, maxCapacity:int=16383, blendFactorSource:String=null, blendFactorDest:String=null) { if (texture == null) throw new ArgumentError("texture must not be null"); mTexture = texture; mParticles = new Vector.<Particle>(0, false); mVertexData = new VertexData(0); mIndices = new <uint>[]; mEmissionRate = emissionRate; mEmissionTime = 0.0; mFrameTime = 0.0; mEmitterX = mEmitterY = 0; mMaxCapacity = Math.min(MAX_NUM_PARTICLES, maxCapacity); mSmoothing = TextureSmoothing.BILINEAR; mBlendFactorSource = blendFactorSource || Context3DBlendFactor.ONE; mBlendFactorDestination = blendFactorDest || Context3DBlendFactor.ONE_MINUS_SOURCE_ALPHA; createProgram(); updatePremultipliedAlpha(); raiseCapacity(initialCapacity); // handle a lost device context Starling.current.stage3D.addEventListener(Event.CONTEXT3D_CREATE, onContextCreated, false, 0, true); } public override function dispose():void { Starling.current.stage3D.removeEventListener(Event.CONTEXT3D_CREATE, onContextCreated); if (mVertexBuffer) mVertexBuffer.dispose(); if (mIndexBuffer) mIndexBuffer.dispose(); super.dispose(); } private function onContextCreated(event:Object):void { createProgram(); raiseCapacity(0); } private function updatePremultipliedAlpha():void { var pma:Boolean = mTexture.premultipliedAlpha; // Particle Designer uses special logic for a certain blend factor combination if (mBlendFactorSource == Context3DBlendFactor.ONE && mBlendFactorDestination == Context3DBlendFactor.ONE_MINUS_SOURCE_ALPHA) { mVertexData.premultipliedAlpha = mTexture.premultipliedAlpha; if (!pma) mBlendFactorSource = Context3DBlendFactor.SOURCE_ALPHA; } else { mVertexData.premultipliedAlpha = false; } } protected function createParticle():Particle { return new Particle(); } protected function initParticle(particle:Particle):void { particle.x = mEmitterX; particle.y = mEmitterY; particle.currentTime = 0; particle.totalTime = 1; particle.color = Math.random() * 0xffffff; } protected function advanceParticle(particle:Particle, passedTime:Number):void { particle.y += passedTime * 250; particle.alpha = 1.0 - particle.currentTime / particle.totalTime; particle.scale = 1.0 - particle.alpha; particle.currentTime += passedTime; } private function raiseCapacity(byAmount:int):void { var oldCapacity:int = capacity; var newCapacity:int = Math.min(mMaxCapacity, oldCapacity + byAmount); var context:Context3D = Starling.context; if (context == null) throw new MissingContextError(); var baseVertexData:VertexData = new VertexData(4); baseVertexData.setTexCoords(0, 0.0, 0.0); baseVertexData.setTexCoords(1, 1.0, 0.0); baseVertexData.setTexCoords(2, 0.0, 1.0); baseVertexData.setTexCoords(3, 1.0, 1.0); mTexture.adjustVertexData(baseVertexData, 0, 4); mParticles.fixed = false; mIndices.fixed = false; for (var i:int=oldCapacity; i<newCapacity; ++i) { var numVertices:int = i * 4; var numIndices:int = i * 6; mParticles[i] = createParticle(); mVertexData.append(baseVertexData); mIndices[ numIndices ] = numVertices; mIndices[int(numIndices+1)] = numVertices + 1; mIndices[int(numIndices+2)] = numVertices + 2; mIndices[int(numIndices+3)] = numVertices + 1; mIndices[int(numIndices+4)] = numVertices + 3; mIndices[int(numIndices+5)] = numVertices + 2; } if (newCapacity < oldCapacity) { mParticles.length = newCapacity; mIndices.length = newCapacity * 6; } mParticles.fixed = true; mIndices.fixed = true; // upload data to vertex and index buffers if (mVertexBuffer) mVertexBuffer.dispose(); if (mIndexBuffer) mIndexBuffer.dispose(); if (newCapacity > 0) { mVertexBuffer = context.createVertexBuffer(newCapacity * 4, VertexData.ELEMENTS_PER_VERTEX); mVertexBuffer.uploadFromVector(mVertexData.rawData, 0, newCapacity * 4); mIndexBuffer = context.createIndexBuffer(newCapacity * 6); mIndexBuffer.uploadFromVector(mIndices, 0, newCapacity * 6); } } /** Starts the emitter for a certain time. @default infinite time */ public function start(duration:Number=Number.MAX_VALUE):void { if (mEmissionRate != 0) mEmissionTime = duration; } /** Stops emitting new particles. Depending on 'clearParticles', the existing particles * will either keep animating until they die or will be removed right away. */ public function stop(clearParticles:Boolean=false):void { mEmissionTime = 0.0; if (clearParticles) clear(); } /** Removes all currently active particles. */ public function clear():void { mNumParticles = 0; } /** Returns an empty rectangle at the particle system's position. Calculating the * actual bounds would be too expensive. */ public override function getBounds(targetSpace:DisplayObject, resultRect:Rectangle=null):Rectangle { if (resultRect == null) resultRect = new Rectangle(); getTransformationMatrix(targetSpace, sHelperMatrix); MatrixUtil.transformCoords(sHelperMatrix, 0, 0, sHelperPoint); resultRect.x = sHelperPoint.x; resultRect.y = sHelperPoint.y; resultRect.width = resultRect.height = 0; return resultRect; } public function advanceTime(passedTime:Number):void { var particleIndex:int = 0; var particle:Particle; // advance existing particles while (particleIndex < mNumParticles) { particle = mParticles[particleIndex] as Particle; if (particle.currentTime < particle.totalTime) { advanceParticle(particle, passedTime); ++particleIndex; } else { if (particleIndex != mNumParticles - 1) { var nextParticle:Particle = mParticles[int(mNumParticles-1)] as Particle; mParticles[int(mNumParticles-1)] = particle; mParticles[particleIndex] = nextParticle; } --mNumParticles; if (mNumParticles == 0 && mEmissionTime == 0) dispatchEventWith(Event.COMPLETE); } } // create and advance new particles if (mEmissionTime > 0) { var timeBetweenParticles:Number = 1.0 / mEmissionRate; mFrameTime += passedTime; while (mFrameTime > 0) { if (mNumParticles < mMaxCapacity) { if (mNumParticles == capacity) raiseCapacity(capacity); particle = mParticles[mNumParticles] as Particle; initParticle(particle); // particle might be dead at birth if (particle.totalTime > 0.0) { advanceParticle(particle, mFrameTime); ++mNumParticles } } mFrameTime -= timeBetweenParticles; } if (mEmissionTime != Number.MAX_VALUE) mEmissionTime = Math.max(0.0, mEmissionTime - passedTime); if (mNumParticles == 0 && mEmissionTime == 0) dispatchEventWith(Event.COMPLETE); } // update vertex data var vertexID:int = 0; var color:uint; var alpha:Number; var rotation:Number; var x:Number, y:Number; var xOffset:Number, yOffset:Number; var textureWidth:Number = mTexture.width; var textureHeight:Number = mTexture.height; for (var i:int=0; i<mNumParticles; ++i) { vertexID = i << 2; particle = mParticles[i] as Particle; color = particle.color; alpha = particle.alpha; rotation = particle.rotation; x = particle.x; y = particle.y; xOffset = textureWidth * particle.scale >> 1; yOffset = textureHeight * particle.scale >> 1; for (var j:int=0; j<4; ++j) mVertexData.setColorAndAlpha(vertexID+j, color, alpha); if (rotation) { var cos:Number = Math.cos(rotation); var sin:Number = Math.sin(rotation); var cosX:Number = cos * xOffset; var cosY:Number = cos * yOffset; var sinX:Number = sin * xOffset; var sinY:Number = sin * yOffset; mVertexData.setPosition(vertexID, x - cosX + sinY, y - sinX - cosY); mVertexData.setPosition(vertexID+1, x + cosX + sinY, y + sinX - cosY); mVertexData.setPosition(vertexID+2, x - cosX - sinY, y - sinX + cosY); mVertexData.setPosition(vertexID+3, x + cosX - sinY, y + sinX + cosY); } else { // optimization for rotation == 0 mVertexData.setPosition(vertexID, x - xOffset, y - yOffset); mVertexData.setPosition(vertexID+1, x + xOffset, y - yOffset); mVertexData.setPosition(vertexID+2, x - xOffset, y + yOffset); mVertexData.setPosition(vertexID+3, x + xOffset, y + yOffset); } } } public override function render(support:RenderSupport, alpha:Number):void { if (mNumParticles == 0) return; // always call this method when you write custom rendering code! // it causes all previously batched quads/images to render. support.finishQuadBatch(); // make this call to keep the statistics display in sync. // to play it safe, it's done in a backwards-compatible way here. if (support.hasOwnProperty("raiseDrawCount")) support.raiseDrawCount(); alpha *= this.alpha; var context:Context3D = Starling.context; var pma:Boolean = texture.premultipliedAlpha; sRenderAlpha[0] = sRenderAlpha[1] = sRenderAlpha[2] = pma ? alpha : 1.0; sRenderAlpha[3] = alpha; if (context == null) throw new MissingContextError(); mVertexBuffer.uploadFromVector(mVertexData.rawData, 0, mNumParticles * 4); mIndexBuffer.uploadFromVector(mIndices, 0, mNumParticles * 6); context.setBlendFactors(mBlendFactorSource, mBlendFactorDestination); context.setTextureAt(0, mTexture.base); context.setProgram(mProgram); context.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 0, support.mvpMatrix3D, true); context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 4, sRenderAlpha, 1); context.setVertexBufferAt(0, mVertexBuffer, VertexData.POSITION_OFFSET, Context3DVertexBufferFormat.FLOAT_2); context.setVertexBufferAt(1, mVertexBuffer, VertexData.COLOR_OFFSET, Context3DVertexBufferFormat.FLOAT_4); context.setVertexBufferAt(2, mVertexBuffer, VertexData.TEXCOORD_OFFSET, Context3DVertexBufferFormat.FLOAT_2); context.drawTriangles(mIndexBuffer, 0, mNumParticles * 2); context.setTextureAt(0, null); context.setVertexBufferAt(0, null); context.setVertexBufferAt(1, null); context.setVertexBufferAt(2, null); } /** Initialize the <tt>ParticleSystem</tt> with particles distributed randomly throughout * their lifespans. */ public function populate(count:int):void { count = Math.min(count, mMaxCapacity - mNumParticles); if (mNumParticles + count > capacity) raiseCapacity(mNumParticles + count - capacity); var p:Particle; for (var i:int=0; i<count; i++) { p = mParticles[mNumParticles+i]; initParticle(p); advanceParticle(p, Math.random() * p.totalTime); } mNumParticles += count; } // program management private function createProgram():void { var mipmap:Boolean = mTexture.mipMapping; var textureFormat:String = mTexture.format; var programName:String = "ext.ParticleSystem." + textureFormat + "/" + mSmoothing.charAt(0) + (mipmap ? "+mm" : ""); mProgram = Starling.current.getProgram(programName); if (mProgram == null) { var textureOptions:String = RenderSupport.getTextureLookupFlags(textureFormat, mipmap, false, mSmoothing); var vertexProgramCode:String = "m44 op, va0, vc0 \n" + // 4x4 matrix transform to output clipspace "mul v0, va1, vc4 \n" + // multiply color with alpha and pass to fragment program "mov v1, va2 \n"; // pass texture coordinates to fragment program var fragmentProgramCode:String = "tex ft1, v1, fs0 " + textureOptions + "\n" + // sample texture 0 "mul oc, ft1, v0"; // multiply color with texel color var assembler:AGALMiniAssembler = new AGALMiniAssembler(); Starling.current.registerProgram(programName, assembler.assemble(Context3DProgramType.VERTEX, vertexProgramCode), assembler.assemble(Context3DProgramType.FRAGMENT, fragmentProgramCode)); mProgram = Starling.current.getProgram(programName); } } public function get isEmitting():Boolean { return mEmissionTime > 0 && mEmissionRate > 0; } public function get capacity():int { return mVertexData.numVertices / 4; } public function get numParticles():int { return mNumParticles; } public function get maxCapacity():int { return mMaxCapacity; } public function set maxCapacity(value:int):void { mMaxCapacity = Math.min(MAX_NUM_PARTICLES, value); } public function get emissionRate():Number { return mEmissionRate; } public function set emissionRate(value:Number):void { mEmissionRate = value; } public function get emitterX():Number { return mEmitterX; } public function set emitterX(value:Number):void { mEmitterX = value; } public function get emitterY():Number { return mEmitterY; } public function set emitterY(value:Number):void { mEmitterY = value; } public function get blendFactorSource():String { return mBlendFactorSource; } public function set blendFactorSource(value:String):void { mBlendFactorSource = value; updatePremultipliedAlpha(); } public function get blendFactorDestination():String { return mBlendFactorDestination; } public function set blendFactorDestination(value:String):void { mBlendFactorDestination = value; updatePremultipliedAlpha(); } public function get texture():Texture { return mTexture; } public function set texture(value:Texture):void { if (value == null) throw new ArgumentError("Texture cannot be null"); mTexture = value; createProgram(); updatePremultipliedAlpha(); for (var i:int = mVertexData.numVertices - 4; i >= 0; i -= 4) { mVertexData.setTexCoords(i + 0, 0.0, 0.0); mVertexData.setTexCoords(i + 1, 1.0, 0.0); mVertexData.setTexCoords(i + 2, 0.0, 1.0); mVertexData.setTexCoords(i + 3, 1.0, 1.0); mTexture.adjustVertexData(mVertexData, i, 4); } } public function get smoothing():String { return mSmoothing; } public function set smoothing(value:String):void { mSmoothing = value; } } }
/***************************************************** * * Copyright 2009 Adobe Systems Incorporated. All Rights Reserved. * ***************************************************** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * * The Initial Developer of the Original Code is Adobe Systems Incorporated. * Portions created by Adobe Systems Incorporated are Copyright (C) 2009 Adobe Systems * Incorporated. All Rights Reserved. * *****************************************************/ package org.osmf.events { import flash.events.Event; /** * A LoadEvent is dispatched when the properties of a LoadTrait change. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 * @productversion FLEXOSMF 4.0 */ public class LoadEvent extends Event { /** * The LoadEvent.LOAD_STATE_CHANGE constant defines the value * of the type property of the event object for a loadStateChange * event. * * @eventType loadStateChange * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 * @productversion FLEXOSMF 4.0 */ public static const LOAD_STATE_CHANGE:String = "loadStateChange"; /** * The LoadEvent.BYTES_LOADED_CHANGE constant defines the value * of the type property of the event object for a bytesLoadedChange * event. * * @eventType bytesLoadedChange * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 * @productversion FLEXOSMF 4.0 */ public static const BYTES_LOADED_CHANGE:String = "bytesLoadedChange"; /** * The LoadEvent.BYTES_TOTAL_CHANGE constant defines the value * of the type property of the event object for a bytesTotalChange * event. * * @eventType bytesTotalChange * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 * @productversion FLEXOSMF 4.0 */ public static const BYTES_TOTAL_CHANGE:String = "bytesTotalChange"; /** * Constructor. * * @param type Event type. * @param bubbles Specifies whether the event can bubble up the display list hierarchy. * @param cancelable Specifies whether the behavior associated with the event can be prevented. * @param loadState New LoadState of the LoadTrait. * @param bytes New value of bytesLoaded or bytesTotal. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 * @productversion FLEXOSMF 4.0 */ public function LoadEvent ( type:String, bubbles:Boolean=false, cancelable:Boolean=false, loadState:String=null, bytes:Number=NaN ) { super(type, bubbles, cancelable); _loadState = loadState; _bytes = bytes; } /** * @private */ override public function clone():Event { return new LoadEvent(type, bubbles, cancelable, loadState, bytes); } /** * New LoadState of the LoadTrait. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 * @productversion FLEXOSMF 4.0 */ public function get loadState():String { return _loadState; } /** * New value of bytesLoaded or bytesTotal. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 * @productversion FLEXOSMF 4.0 */ public function get bytes():Number { return _bytes; } // Internals // private var _loadState:String; private var _bytes:Number; } }
// Action script... // [Initial MovieClip Action of sprite 20923] #initclip 188 if (!dofus.graphics.gapi.ui.bigstore.BigStorePriceItem) { if (!dofus) { _global.dofus = new Object(); } // end if if (!dofus.graphics) { _global.dofus.graphics = new Object(); } // end if if (!dofus.graphics.gapi) { _global.dofus.graphics.gapi = new Object(); } // end if if (!dofus.graphics.gapi.ui) { _global.dofus.graphics.gapi.ui = new Object(); } // end if if (!dofus.graphics.gapi.ui.bigstore) { _global.dofus.graphics.gapi.ui.bigstore = new Object(); } // end if var _loc1 = (_global.dofus.graphics.gapi.ui.bigstore.BigStorePriceItem = function () { super(); }).prototype; _loc1.__set__list = function (mcList) { this._mcList = mcList; //return (this.list()); }; _loc1.__set__row = function (mcRow) { this._mcRow = mcRow; //return (this.row()); }; _loc1.setValue = function (bUsed, sSuggested, oItem) { delete this._nSelectedSet; if (bUsed) { this._oItem = oItem; var _loc5 = this._mcList._parent._parent.isThisPriceSelected(oItem.id, 1); var _loc6 = this._mcList._parent._parent.isThisPriceSelected(oItem.id, 2); var _loc7 = this._mcList._parent._parent.isThisPriceSelected(oItem.id, 3); if (_loc5) { var _loc8 = this._btnPriceSet1; } // end if if (_loc6) { _loc8 = this._btnPriceSet2; } // end if if (_loc7) { _loc8 = this._btnPriceSet3; } // end if if (_loc5 || (_loc6 || _loc7)) { var _loc9 = this._btnBuy; } // end if if (_loc9 != undefined) { this._mcList._parent._parent.setButtons(_loc8, _loc9); } // end if this._btnPriceSet1.selected = _loc5 && !_global.isNaN(oItem.priceSet1); this._btnPriceSet2.selected = _loc6 && !_global.isNaN(oItem.priceSet2); this._btnPriceSet3.selected = _loc7 && !_global.isNaN(oItem.priceSet3); if (_loc5) { this._nSelectedSet = 1; } else if (_loc6) { this._nSelectedSet = 2; } else if (_loc7) { this._nSelectedSet = 3; } // end else if this._btnBuy.enabled = this._nSelectedSet != undefined; this._btnBuy._visible = true; this._btnPriceSet1._visible = true; this._btnPriceSet2._visible = true; this._btnPriceSet3._visible = true; this._btnPriceSet1.enabled = !_global.isNaN(oItem.priceSet1); this._btnPriceSet2.enabled = !_global.isNaN(oItem.priceSet2); this._btnPriceSet3.enabled = !_global.isNaN(oItem.priceSet3); this._btnPriceSet1.label = _global.isNaN(oItem.priceSet1) ? ("- ") : (new ank.utils.ExtendedString(oItem.priceSet1).addMiddleChar(this._mcList.gapi.api.lang.getConfigText("THOUSAND_SEPARATOR"), 3) + " "); this._btnPriceSet2.label = _global.isNaN(oItem.priceSet2) ? ("- ") : (new ank.utils.ExtendedString(oItem.priceSet2).addMiddleChar(this._mcList.gapi.api.lang.getConfigText("THOUSAND_SEPARATOR"), 3) + " "); this._btnPriceSet3.label = _global.isNaN(oItem.priceSet3) ? ("- ") : (new ank.utils.ExtendedString(oItem.priceSet3).addMiddleChar(this._mcList.gapi.api.lang.getConfigText("THOUSAND_SEPARATOR"), 3) + " "); this._ldrIcon.contentParams = oItem.item.params; this._ldrIcon.contentPath = oItem.item.iconFile; } else if (this._ldrIcon.contentPath != undefined) { this._btnPriceSet1._visible = false; this._btnPriceSet2._visible = false; this._btnPriceSet3._visible = false; this._btnBuy._visible = false; this._ldrIcon.contentPath = ""; } // end else if }; _loc1.init = function () { super.init(false); this._btnPriceSet1._visible = false; this._btnPriceSet2._visible = false; this._btnPriceSet3._visible = false; this._btnBuy._visible = false; }; _loc1.createChildren = function () { this.addToQueue({object: this, method: this.addListeners}); this.addToQueue({object: this, method: this.initTexts}); }; _loc1.addListeners = function () { this._btnPriceSet1.addEventListener("click", this); this._btnPriceSet2.addEventListener("click", this); this._btnPriceSet3.addEventListener("click", this); this._btnBuy.addEventListener("click", this); }; _loc1.initTexts = function () { this._btnBuy.label = this._mcList.gapi.api.lang.getText("BUY"); }; _loc1.click = function (oEvent) { switch (oEvent.target._name) { case "_btnPriceSet1": case "_btnPriceSet2": case "_btnPriceSet3": { var _loc3 = Number(oEvent.target._name.substr(12)); this._mcList._parent._parent.selectPrice(this._oItem, _loc3, oEvent.target, this._btnBuy); if (oEvent.target.selected) { this._nSelectedSet = _loc3; this._mcRow.select(); this._btnBuy.enabled = true; } else { delete this._nSelectedSet; this._btnBuy.enabled = false; } // end else if break; } case "_btnBuy": { if (!this._nSelectedSet || _global.isNaN(this._nSelectedSet)) { this._btnBuy.enabled = false; return; } // end if this._mcList._parent._parent.askBuy(this._oItem.item, this._nSelectedSet, this._oItem["priceSet" + this._nSelectedSet]); this._mcList._parent._parent.askMiddlePrice(this._oItem.item); break; } } // End of switch }; _loc1.addProperty("row", function () { }, _loc1.__set__row); _loc1.addProperty("list", function () { }, _loc1.__set__list); ASSetPropFlags(_loc1, null, 1); } // end if #endinitclip
/////////////////////////////////////////////////////////////////////////// // Copyright (c) 2010-2011 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// package cn.seisys.TGISViewer { /** * Contains widget state constants. */ public final class WidgetStates { /** * Indicates the widget is open. */ public static const WIDGET_OPENED:String = "open"; /** * Indicates the widget is minimized. */ public static const WIDGET_MINIMIZED:String = "minimized"; /** * Indicates the widget is closed. */ public static const WIDGET_CLOSED:String = "closed"; } }
package com.ankamagames.dofus.logic.game.roleplay.messages { import com.ankamagames.dofus.network.types.game.context.GameContextActorInformations; import com.ankamagames.jerakine.messages.Message; public class GameRolePlaySetAnimationMessage implements Message { private var _informations:GameContextActorInformations; private var _animation:String; private var _duration:uint; private var _spellLevelId:uint; private var _instant:Boolean; private var _directions8:Boolean; private var _playStaticOnly:Boolean; public function GameRolePlaySetAnimationMessage(informations:GameContextActorInformations, animation:String, spellLevelId:uint = 0, duration:uint = 0, instant:Boolean = true, directions8:Boolean = true, playStaticOnly:Boolean = false) { super(); this._informations = informations; this._animation = animation; this._spellLevelId = spellLevelId; this._duration = duration; this._instant = instant; this._directions8 = directions8; this._playStaticOnly = playStaticOnly; } public function get informations() : GameContextActorInformations { return this._informations; } public function get animation() : String { return this._animation; } public function get duration() : uint { return this._duration; } public function get spellLevelId() : uint { return this._spellLevelId; } public function get instant() : Boolean { return this._instant; } public function get directions8() : Boolean { return this._directions8; } public function get playStaticOnly() : Boolean { return this._playStaticOnly; } } }
/* Disclaimer for Robert Penner's Easing Equations license: TERMS OF USE - EASING EQUATIONS Open source under the BSD License. Copyright � 2001 Robert Penner 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 author nor the names of 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 jp.raohmaru.toolkit.motion.easing { /** * Ecuaciones de movimiento de Robert Penner utilizadas por la clase Paprika. */ public class Quint { public static function easeIn(t :Number, b :Number, c :Number, d :Number) :Number { return c * (t /= d) * t * t * t * t + b; } public static function easeOut(t :Number, b :Number, c :Number, d :Number) :Number { return c * ((t = t / d - 1) * t * t * t * t + 1) + b; } public static function easeInOut(t :Number, b :Number, c :Number, d :Number) :Number { if ((t /= d * 0.5) < 1) return c * 0.5 * t * t * t * t * t + b; return c * 0.5 * ((t -= 2) * t * t * t * t + 2) + b; } } }
package idv.cjcat.stardust.twoD.initializers { import idv.cjcat.stardust.common.initializers.Alpha; import idv.cjcat.stardust.common.initializers.CollisionRadius; import idv.cjcat.stardust.common.initializers.CompositeInitializer; import idv.cjcat.stardust.common.initializers.Initializer; import idv.cjcat.stardust.common.initializers.InitializerCollection; import idv.cjcat.stardust.common.initializers.Life; import idv.cjcat.stardust.common.initializers.Mask; import idv.cjcat.stardust.common.initializers.Mass; import idv.cjcat.stardust.common.initializers.Scale; import idv.cjcat.stardust.common.math.UniformRandom; import idv.cjcat.stardust.common.xml.XMLBuilder; import idv.cjcat.stardust.sd; import idv.cjcat.stardust.twoD.geom.Vec2D; import idv.cjcat.stardust.twoD.zones.LazySectorZone; import idv.cjcat.stardust.twoD.zones.SinglePoint; import idv.cjcat.stardust.twoD.zones.Zone; /** * This is a wrapper class of several common and useful initializers. * As it's name suggests, you can use this class whenever you're too lazy to create initializers one by one. * You don't directly control these component initializers; * instead, you use the abstract properties provided by this class. * * <p> * This composite initializer is consisted of the folling actions: * <ul> * <li>DisplayObjectClass</li> * <li>Position</li> * <li>Rotation</li> * <li>Velocity</li> * <li>Omega</li> * <li>Scale</li> * <li>Mass</li> * <li>Mask</li> * <li>CollisionRadius</li> * <li>Alpha</li> * </ul> * </p> */ public class LazyInitializer extends CompositeInitializer { private var _posInit:Position; private var _rotationInit:Rotation; private var _rotationInitRand:UniformRandom; private var _displayObjectClassInit:DisplayObjectClass; private var _displayObjectClassParams:Array; private var _lifeInit:Life; private var _lifeInitRand:UniformRandom; private var _velocityInit:Velocity; private var _velocityInitSector:LazySectorZone; private var _omegaInit:Omega; private var _omegaInitRand:UniformRandom; private var _inScaleit:Scale; private var _inScaleitRand:UniformRandom; private var _massInit:Mass; private var _massInitRand:UniformRandom; private var _maskInit:Mask; private var _collisionRadiusInit:CollisionRadius; private var _alphaInit:Alpha; private var _alphaInitRand:UniformRandom; public function LazyInitializer(displayObjectClass:Class = null, positionArea:Zone = null) { if (!positionArea) positionArea = new SinglePoint(); _displayObjectClassInit = new DisplayObjectClass(displayObjectClass); _posInit = new Position(positionArea); _rotationInitRand = new UniformRandom(0, 180); _rotationInit = new Rotation(_rotationInitRand); _lifeInitRand = new UniformRandom(50, 0); _lifeInit = new Life(_lifeInitRand); _velocityInitSector = new LazySectorZone(3, 0); _velocityInitSector.direction.set(0, -1); _velocityInit = new Velocity(_velocityInitSector); _omegaInitRand = new UniformRandom(0, 0); _omegaInit = new Omega(_omegaInitRand); _inScaleitRand = new UniformRandom(1, 0); _inScaleit = new Scale(_inScaleitRand); _massInitRand = new UniformRandom(1, 0); _massInit = new Mass(_massInitRand); _maskInit = new Mask(1); _collisionRadiusInit = new CollisionRadius(0); _alphaInitRand = new UniformRandom(1, 0); _alphaInit = new Alpha(_alphaInitRand); superAddInitializer(_displayObjectClassInit); superAddInitializer(_posInit); superAddInitializer(_rotationInit); superAddInitializer(_lifeInit); superAddInitializer(_velocityInit); superAddInitializer(_omegaInit); superAddInitializer(_inScaleit); superAddInitializer(_massInit); superAddInitializer(_maskInit); superAddInitializer(_collisionRadiusInit); superAddInitializer(_alphaInit); } public function get displayObjectClass():Class { return _displayObjectClassInit.displayObjectClass; } public function set displayObjectClass(value:Class):void { _displayObjectClassInit.displayObjectClass = value; } public function get displayObjectClassParams():Array { return _displayObjectClassInit.constructorParams; } public function set displayObjectClassParams(value:Array):void { _displayObjectClassInit.constructorParams = value; } /** * Position zone. */ public function get position():Zone { return _posInit.zone; } public function set position(value:Zone):void { _posInit.zone = value; } /** * Average rotation. */ public function get rotation():Number { return _rotationInitRand.center; } public function set rotation(value:Number):void { _rotationInitRand.center = value; } /** * Rotation variation. */ public function get rotationVar():Number { return _rotationInitRand.radius; } public function set rotationVar(value:Number):void { _rotationInitRand.radius = value; } /** * Average life. */ public function get life():Number { return _lifeInitRand.center; } public function set life(value:Number):void { _lifeInitRand.center = value; } /** * Life variation. */ public function get lifeVar():Number { return _lifeInitRand.radius; } public function set lifeVar(value:Number):void { _lifeInitRand.radius = value; } /** * Average speed. */ public function get speed():Number { return _velocityInitSector.radius; } public function set speed(value:Number):void { _velocityInitSector.radius = value; } /** * Speed variation. */ public function get speedVar():Number { return _velocityInitSector.radiusVar; } public function set speedVar(value:Number):void { _velocityInitSector.radiusVar = value; } /** * Average direction. */ public function get direction():Vec2D { return _velocityInitSector.direction; } /** * Direction variation, in degrees. */ public function get directionVar():Number { return _velocityInitSector.directionVar; } public function set directionVar(value:Number):void { _velocityInitSector.directionVar = value; } /** * Average omega (angular velocity). */ public function get omega():Number { return _omegaInitRand.center; } public function set omega(value:Number):void { _omegaInitRand.center = value; } /** * Omega variation. */ public function get omegaVar():Number { return _omegaInitRand.radius; } public function set omegaVar(value:Number):void { _omegaInitRand.radius = value; } /** * Average scale. */ public function get scale():Number { return _inScaleitRand.center; } public function set scale(value:Number):void { _inScaleitRand.center = value; } /** * Scale variation. */ public function get scaleVar():Number { return _inScaleitRand.radius; } public function set scaleVar(value:Number):void { _inScaleitRand.radius = value; } /** * Average mass. */ public function get mass():Number { return _massInitRand.center; } public function set mass(value:Number):void { _massInitRand.center = value; } /** * Mass variation. */ public function get massVar():Number { return _massInitRand.radius; } public function set massVar(value:Number):void { _massInitRand.radius = value; } /** * Particle mask value. */ public function get mask():int { return _maskInit.mask; } public function set mask(value:int):void { _maskInit.mask = value; } /** * Particle collision radius. */ public function get collisionRadius():Number { return _collisionRadiusInit.radius; } public function set collisionRadius(value:Number):void { _collisionRadiusInit.radius = value; } /** * Average alpha. */ public function get alpha():Number { return _alphaInitRand.center; } public function set alpha(value:Number):void { _alphaInitRand.center = value; } /** * Alpha variation. */ public function get alphaVar():Number { return _alphaInitRand.radius; } public function set alphaVar(value:Number):void { _alphaInitRand.radius = value; } //additional initializers //------------------------------------------------------------------------------------------------ protected function superAddInitializer(initializer:Initializer):void { super.addInitializer(initializer); } private var additionalInitializers:InitializerCollection = new InitializerCollection(); override public function addInitializer(initializer:Initializer):void { super.addInitializer(initializer); additionalInitializers.addInitializer(initializer); } override public function removeInitializer(initializer:Initializer):void { super.removeInitializer(initializer); additionalInitializers.removeInitializer(initializer); } override public function clearInitializers():void { super.clearInitializers(); additionalInitializers.clearInitializers(); } //------------------------------------------------------------------------------------------------ //end of additional initializers //XML //------------------------------------------------------------------------------------------------ override public function getRelatedObjects():Array { return [position].concat(additionalInitializers.sd::initializers); } override public function getXMLTagName():String { return "LazyInitializer"; } override public function toXML():XML { var xml:XML = super.toXML(); delete xml.initializers; xml.@position = position.name; xml.@rotation = rotation; xml.@rotationVar = rotationVar; xml.@life = life; xml.@lifeVar = lifeVar; xml.@speed = speedVar; xml.@speedVar = speedVar; xml.@directionX = direction.x; xml.@directionY = direction.y; xml.@omega = omega; xml.@omegaVar = omegaVar; xml.@scale = scale; xml.@scaleVar = scaleVar; xml.@mass = mass; xml.@mask = mask; xml.@collisionRadius = collisionRadius; xml.@alpha = alpha; xml.@alphaVar = alphaVar; if (additionalInitializers.sd::initializers.length > 0) { xml.appendChild(<initializers/>); var initializer:Initializer; for each (initializer in additionalInitializers.sd::initializers) { xml.initializers.appendChild(initializer.getXMLTag()); } } return xml; } override public function parseXML(xml:XML, builder:XMLBuilder = null):void { name = xml.@name; active = (xml.@active == "true"); //mask = parseInt(xml.@mask); if (xml.@position.length()) position = builder.getElementByName(xml.@position) as Zone; if (xml.@rotation.length()) rotation = parseFloat(xml.@rotation); if (xml.@rotationVar.length()) rotationVar = parseFloat(xml.@rotationVar); if (xml.@life.length()) life = parseFloat(xml.@life); if (xml.@lifeVar.length()) lifeVar = parseFloat(xml.@lifeVar); if (xml.@directionX.length()) direction.x = parseFloat(xml.@directionX); if (xml.@directionY.length()) direction.y = parseFloat(xml.@directionY); if (xml.@omega.length()) omega = parseFloat(xml.@omega); if (xml.@omegaVar.length()) omegaVar = parseFloat(xml.@omegaVar); if (xml.@scale.length()) scale = parseFloat(xml.@scale); if (xml.@scaleVar.length()) scaleVar = parseFloat(xml.@scaleVar); if (xml.@mask.length()) mask = parseInt(xml.@mask); if (xml.@mass.length()) mass = parseFloat(xml.@mass); if (xml.@collisionRadius.length()) collisionRadius = parseFloat(xml.@collisionRadius); if (xml.@alpha.length()) alpha = parseFloat(xml.@alpha); if (xml.@alphaVar.length()) alphaVar = parseFloat(xml.@alphaVar); additionalInitializers.clearInitializers(); for each (var node:XML in xml.initializers.*) { addInitializer(builder.getElementByName(node.@name) as Initializer); } } //------------------------------------------------------------------------------------------------ //end of XML } }
package com.registerguard.peel { import flash.display.MovieClip; import flash.display.SimpleButton; import flash.display.DisplayObject; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.MouseEvent; public class Peel extends MovieClip { // Private: private var _stager:Stager; private var _cookie:Cookie; private var _timing:Timing; private var _peelMc:MovieClip; private var _maskMc:MovieClip; private var _closeBtn:SimpleButton; private var _rewind:Boolean; private var _flag:Boolean; /** * Peel() * About: Class constructor. * Returns: Nothing. */ public function Peel():void { // Initialize program: init(); }; /** * init() * About: Initialize. * Returns: Nothing. */ private function init():void { // Button mode: this.buttonMode = true; // Initialize: _flag = false; // Instantiate custom classes: _stager = new Stager(this); _cookie = new Cookie("cookie"); // Object lookups: _peelMc = this.peel_mc; _maskMc = this.mask_mc; _closeBtn = _peelMc.close_btn; // Begin program: peeler(); }; /** * peeler() * About: Launching pad for the differnt events. * Returns: Nothing. */ private function peeler():void { // Event.ENTER_FRAME event listener: this.addEventListener(Event.ENTER_FRAME, onEnter, false, 0, true); if (_closeBtn.hasEventListener(MouseEvent.MOUSE_UP)) { // Garbage collection: _closeBtn.removeEventListener(MouseEvent.MOUSE_UP, onPeelClosed); } if (_cookie.cookieExists() == false) { _flag = true; // Set cookie: _cookie.cookieSet(); // First time visit, open the peel: _peelMc.play(); _maskMc.play(); } else { // Setup event listeners: this.addEventListener(MouseEvent.ROLL_OVER, onOver, false, 0, true); this.addEventListener(MouseEvent.ROLL_OUT, onOut, false, 0, true); } }; /** * onEnter() * About: Handles Event.ENTER_FRAME event. * Returns: Nothing. */ private function onEnter(e:Event):void { if (_peelMc.currentFrame == 1) { // Bools: _flag = false; _rewind = false; // Play: _peelMc.play(); _maskMc.play(); } else if (!_flag && (_peelMc.currentLabel != 'loop')) { // Loop: _peelMc.gotoAndPlay('loop'); _maskMc.gotoAndPlay('loop'); } else if (_rewind == true) { // Rewind: _peelMc.prevFrame(); _maskMc.prevFrame(); } else { // If peel is opened, call onPeelOpened(), otherwise trace current frame number: (_peelMc.currentLabel == "finish") ? onPeelOpened() : trace(_peelMc.currentFrame); } }; /** * onOver() * About: Handles MouseEvent.ROLL_OVER event. * Returns: Nothing. */ private function onOver(e:Event):void { // Bools: _flag = true; _rewind = false; // Play: _peelMc.play(); _maskMc.play(); }; /** * onOut() * About: Handles MouseEvent.ROLL_OVER event. * Returns: Nothing. */ private function onOut(e:Event):void { _flag = true; _rewind = true; }; /** * onUp() * About: Handles MouseEvent.MOUSE_UP event for peel close button. * Returns: Nothing. */ private function onPeelClosed(e:Event):void { // GC: _timing.removeEventListener(Timing.TIMING_COMPLETE, onPeelClosed); // Bools: _rewind = true; // Launching pad: peeler(); }; /** * onPeelOpened() * About: Fired when peel is fully opened. * Returns: Nothing. */ private function onPeelOpened():void { // GC: this.removeEventListener(Event.ENTER_FRAME, onEnter); this.removeEventListener(MouseEvent.ROLL_OVER, onOver); this.removeEventListener(MouseEvent.ROLL_OUT, onOut); // Setup the close button: _closeBtn.addEventListener(MouseEvent.MOUSE_UP, onPeelClosed, false, 0, true); // Timer: _timing = new Timing(10000); _timing.addEventListener(Timing.TIMING_COMPLETE, onPeelClosed, false, 0, true); }; }; };
package Pipboy.COMPANIONAPP { import Shared.AS3.BSScrollingListEntry; import flash.display.MovieClip; public class QuestsObjectivesListItemRenderer extends QuestsListItemRenderer { public var Background_mc:MovieClip; public function QuestsObjectivesListItemRenderer() { super(); } override protected function createScrollingListEntry() : BSScrollingListEntry { return new ObjectivesListEntry(); } override protected function setupScrollinglistEntry() : * { super.setupScrollinglistEntry(); var _loc1_:ObjectivesListEntry = _scrollingListEntry as ObjectivesListEntry; _loc1_.Background_mc = this.Background_mc; } } }
package com.google.zxing.qrcode.decoder { import com.google.zxing.qrcode.decoder.DataMaskBase; /// <summary> 000: mask bits for which (i + j) mod 2 == 0</summary> public class DataMask000 extends DataMaskBase { public override function isMasked(i:int, j:int):Boolean { return ((i + j) & 0x01) == 0; } } }
/******************************************************************************* * ZaaUtils * Copyright (c) 2010 ZaaLabs, Ltd. * For more information see http://www.zaalabs.com * * This file is licensed under the terms of the MIT license, which is included * in the license.txt file at the root directory of this library. ******************************************************************************/ package { import com.zaalabs.utils.SwfData; import flash.display.Sprite; [SWF(backgroundColor="0x969696")] public class SwfDataExample extends Sprite { public function SwfDataExample() { var data:SwfData = new SwfData(loaderInfo.bytes); trace("version \t"+data.version); trace("frameRate \t"+data.frameRate); trace("frameCount \t"+data.frameCount); trace("fileLength \t"+data.fileLength); trace("bgColor \t0x"+data.backgroundColor.toString(16)); } } }
package kabam.rotmg.dailyLogin.view { import flash.display.Sprite; import kabam.rotmg.dailyLogin.model.CalendarDayModel; import kabam.rotmg.dailyLogin.config.CalendarSettings; public class CalendarView extends Sprite { public function CalendarView() { super(); } public function init(param1:Vector.<CalendarDayModel>, param2:int, param3:int) : void { var _loc7_:CalendarDayModel = null; var _loc8_:int = 0; var _loc9_:CalendarDayBox = null; var _loc4_:int = 0; var _loc5_:int = 0; var _loc6_:int = 0; for each(_loc7_ in param1) { _loc9_ = new CalendarDayBox(_loc7_,param2,_loc4_ + 1 == param3); addChild(_loc9_); _loc9_.x = _loc5_ * CalendarSettings.BOX_WIDTH; if(_loc5_ > 0) { _loc9_.x = _loc9_.x + _loc5_ * CalendarSettings.BOX_MARGIN; } _loc9_.y = _loc6_ * CalendarSettings.BOX_HEIGHT; if(_loc6_ > 0) { _loc9_.y = _loc9_.y + _loc6_ * CalendarSettings.BOX_MARGIN; } _loc5_++; _loc4_++; if(_loc4_ % CalendarSettings.NUMBER_OF_COLUMNS == 0) { _loc5_ = 0; _loc6_++; } } _loc8_ = CalendarSettings.BOX_WIDTH * CalendarSettings.NUMBER_OF_COLUMNS + (CalendarSettings.NUMBER_OF_COLUMNS - 1) * CalendarSettings.BOX_MARGIN; this.x = (this.parent.width - _loc8_) / 2; this.y = CalendarSettings.DAILY_LOGIN_TABS_PADDING + CalendarSettings.TABS_HEIGHT; } } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import com.adobe.test.Assert; // var SECTION = "15.4.4"; // var VERSION = "ECMA_1"; // var TITLE = "Properties of the Array Prototype Object"; var testcases = getTestCases(); function getTestCases() { var array = new Array(); var item = 0; array[item++] = Assert.expectEq( "Array.prototype.length", 0, Array.prototype.length ); array[item++] = Assert.expectEq( "Array.length", 1, Array.length ); // verify that prototype object is an Array object. array[item++] = Assert.expectEq( "typeof Array.prototype", "object", typeof Array.prototype ); var tempToString = Array.prototype.toString; array[item++] = Assert.expectEq( "Array.prototype.toString = Object.prototype.toString; Array.prototype.toString()", "[object Array]", (Array.prototype.toString = Object.prototype.toString, Array.prototype.toString()) ); // revert Array.prototype.toString back to original for ATS tests Array.prototype.toString = tempToString; return ( array ); }
/* * Scratch Project Editor and Player * Copyright (C) 2014 Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // SpriteInfoPart.as // John Maloney, November 2011 // // This part shows information about the currently selected object (the stage or a sprite). package ui.parts { import flash.display.*; import flash.events.*; import flash.geom.*; import flash.text.*; import scratch.*; import translation.Translator; import uiwidgets.*; import util.DragClient; import watchers.ListWatcher; public class SpriteInfoPart extends UIPart implements DragClient { private const readoutLabelFormat:TextFormat = new TextFormat(CSS.font, 12, 0xA6A8AB, true); private const readoutFormat:TextFormat = new TextFormat(CSS.font, 12, 0xA6A8AB); private var shape:Shape; // sprite info parts private var closeButton:IconButton; private var thumbnail:Bitmap; private var spriteName:EditableLabel; private var xReadoutLabel:TextField; private var yReadoutLabel:TextField; private var xReadout:TextField; private var yReadout:TextField; private var dirLabel:TextField; private var dirReadout:TextField; private var dirWheel:Sprite; private var rotationStyleLabel:TextField; private var rotationStyleButtons:Array; private var draggableLabel:TextField; private var draggableButton:IconButton; private var showSpriteLabel:TextField; private var showSpriteButton:IconButton; private var lastX:Number, lastY:Number, lastDirection:Number, lastRotationStyle:String; private var lastSrcImg:DisplayObject; public function SpriteInfoPart(app:Scratch) { this.app = app; shape = new Shape(); addChild(shape); addParts(); updateTranslation(); } public static function strings():Array { return ['direction:', 'rotation style:', 'can drag in player:', 'show:']; } public function updateTranslation():void { dirLabel.text = Translator.map('direction:'); rotationStyleLabel.text = Translator.map('rotation style:'); draggableLabel.text = Translator.map('can drag in player:'); showSpriteLabel.text = Translator.map('show:'); if (app.viewedObj()) refresh(); } public function setWidthHeight(w:int, h:int):void { this.w = w; this.h = h; var g:Graphics = shape.graphics; g.clear(); g.beginFill(CSS.white); g.drawRect(0, 0, w, h); g.endFill(); } public function step():void { updateSpriteInfo() } public function refresh():void { spriteName.setContents(app.viewedObj().objName); updateSpriteInfo(); if (app.stageIsContracted) layoutCompact(); else layoutFullsize(); } private function addParts():void { addChild(closeButton = new IconButton(closeSpriteInfo, 'backarrow')); closeButton.isMomentary = true; addChild(spriteName = new EditableLabel(nameChanged)); spriteName.setWidth(200); addChild(thumbnail = new Bitmap()); addChild(xReadoutLabel = makeLabel('x:', readoutLabelFormat)); addChild(xReadout = makeLabel('-888', readoutFormat)); addChild(yReadoutLabel = makeLabel('y:', readoutLabelFormat)); addChild(yReadout = makeLabel('-888', readoutFormat)); addChild(dirLabel = makeLabel('', readoutLabelFormat)); addChild(dirWheel = new Sprite()); dirWheel.addEventListener(MouseEvent.MOUSE_DOWN, dirMouseDown); addChild(dirReadout = makeLabel('-179', readoutFormat)); addChild(rotationStyleLabel = makeLabel('', readoutLabelFormat)); rotationStyleButtons = [ new IconButton(rotate360, 'rotate360', null, true), new IconButton(rotateFlip, 'flip', null, true), new IconButton(rotateNone, 'norotation', null, true)]; for each (var b:IconButton in rotationStyleButtons) addChild(b); addChild(draggableLabel = makeLabel('', readoutLabelFormat)); addChild(draggableButton = new IconButton(toggleLock, 'checkbox')); draggableButton.disableMouseover(); addChild(showSpriteLabel = makeLabel('', readoutLabelFormat)); addChild(showSpriteButton = new IconButton(toggleShowSprite, 'checkbox')); showSpriteButton.disableMouseover(); } private function layoutFullsize():void { dirLabel.visible = true; rotationStyleLabel.visible = true; closeButton.x = 5; closeButton.y = 5; thumbnail.x = 40; thumbnail.y = 8; var left:int = 150; spriteName.setWidth(228); spriteName.x = left; spriteName.y = 5; var nextY:int = spriteName.y + spriteName.height + 9; xReadoutLabel.x = left; xReadoutLabel.y = nextY; xReadout.x = xReadoutLabel.x + 15; xReadout.y = nextY; yReadoutLabel.x = left + 47; yReadoutLabel.y = nextY; yReadout.x = yReadoutLabel.x + 15; yReadout.y = nextY; // right aligned dirWheel.x = w - 38; dirWheel.y = nextY + 8; dirReadout.x = dirWheel.x - 47; dirReadout.y = nextY; dirLabel.x = dirReadout.x - dirLabel.textWidth - 5; dirLabel.y = nextY; nextY += 22; rotationStyleLabel.x = left; rotationStyleLabel.y = nextY; var buttonsX:int = rotationStyleLabel.x + rotationStyleLabel.width + 5; rotationStyleButtons[0].x = buttonsX; rotationStyleButtons[1].x = buttonsX + 28; rotationStyleButtons[2].x = buttonsX + 55; rotationStyleButtons[0].y = rotationStyleButtons[1].y = rotationStyleButtons[2].y = nextY; nextY += 22; draggableLabel.x = left; draggableLabel.y = nextY; draggableButton.x = draggableLabel.x + draggableLabel.textWidth + 10; draggableButton.y = nextY + 4; nextY += 22; showSpriteLabel.x = left; showSpriteLabel.y = nextY; showSpriteButton.x = showSpriteLabel.x + showSpriteLabel.textWidth + 10; showSpriteButton.y = nextY + 4; } private function layoutCompact():void { dirLabel.visible = false; rotationStyleLabel.visible = false; closeButton.x = 5; closeButton.y = 5; spriteName.setWidth(130); spriteName.x = 28; spriteName.y = 5; var left:int = 6; thumbnail.x = ((w - thumbnail.width) / 2) + 3; thumbnail.y = spriteName.y + spriteName.height + 10; var nextY:int = 125; xReadoutLabel.x = left; xReadoutLabel.y = nextY; xReadout.x = left + 15; xReadout.y = nextY; yReadoutLabel.x = left + 47; yReadoutLabel.y = nextY; yReadout.x = yReadoutLabel.x + 15; yReadout.y = nextY; // right aligned dirWheel.x = w - 18; dirWheel.y = nextY + 8; dirReadout.x = dirWheel.x - 47; dirReadout.y = nextY; nextY += 22; rotationStyleButtons[0].x = left; rotationStyleButtons[1].x = left + 33; rotationStyleButtons[2].x = left + 64; rotationStyleButtons[0].y = rotationStyleButtons[1].y = rotationStyleButtons[2].y = nextY; nextY += 22; draggableLabel.x = left; draggableLabel.y = nextY; draggableButton.x = draggableLabel.x + draggableLabel.textWidth + 10; draggableButton.y = nextY + 4; nextY += 22; showSpriteLabel.x = left; showSpriteLabel.y = nextY; showSpriteButton.x = showSpriteLabel.x + showSpriteLabel.textWidth + 10; showSpriteButton.y = nextY + 4; } private function closeSpriteInfo(ignore:*):void { var lib:LibraryPart = parent as LibraryPart; if (lib) lib.showSpriteDetails(false); } private function rotate360(ignore:*):void { var spr:ScratchSprite = app.viewedObj() as ScratchSprite; spr.rotationStyle = 'normal'; spr.setDirection(spr.direction); app.setSaveNeeded(); } private function rotateFlip(ignore:*):void { var spr:ScratchSprite = app.viewedObj() as ScratchSprite; var dir:Number = spr.direction; spr.setDirection(90); spr.rotationStyle = 'leftRight'; spr.setDirection(dir); app.setSaveNeeded(); } private function rotateNone(ignore:*):void { var spr:ScratchSprite = app.viewedObj() as ScratchSprite; var dir:Number = spr.direction; spr.setDirection(90); spr.rotationStyle = 'none'; spr.setDirection(dir); app.setSaveNeeded(); } private function toggleLock(b:IconButton):void { var spr:ScratchSprite = ScratchSprite(app.viewedObj()); if (spr) { spr.isDraggable = b.isOn(); app.setSaveNeeded(); } } private function toggleShowSprite(b:IconButton):void { var spr:ScratchSprite = ScratchSprite(app.viewedObj()); if (spr) { spr.visible = !spr.visible; spr.updateBubble(); b.setOn(spr.visible); app.setSaveNeeded(); } } private function updateSpriteInfo():void { // Update the sprite info. Do nothing if a field is already up to date (to minimize CPU load). var spr:ScratchSprite = app.viewedObj() as ScratchSprite; if (spr == null) return; updateThumbnail(); if (spr.scratchX != lastX) { xReadout.text = String(Math.round(spr.scratchX)); lastX = spr.scratchX; } if (spr.scratchY != lastY) { yReadout.text = String(Math.round(spr.scratchY)); lastY = spr.scratchY; } if (spr.direction != lastDirection) { dirReadout.text = String(Math.round(spr.direction)) + '\u00B0'; drawDirWheel(spr.direction); lastDirection = spr.direction; } if (spr.rotationStyle != lastRotationStyle) { updateRotationStyle(); lastRotationStyle = spr.rotationStyle; } draggableButton.setOn(spr.isDraggable); showSpriteButton.setOn(spr.visible); } private function drawDirWheel(dir:Number):void { const DegreesToRadians:Number = (2 * Math.PI) / 360; var r:Number = 11; var g:Graphics = dirWheel.graphics; g.clear(); // circle g.beginFill(0xFF, 0); g.drawCircle (0, 0, r + 5); g.endFill(); g.lineStyle(2, 0xD0D0D0, 1, true); g.drawCircle (0, 0, r - 3); // direction pointer g.lineStyle(3, 0x006080, 1, true); g.moveTo(0, 0); var dx:Number = r * Math.sin(DegreesToRadians * (180 - dir)); var dy:Number = r * Math.cos(DegreesToRadians * (180 - dir)); g.lineTo(dx, dy); } private function nameChanged():void { app.runtime.renameSprite(spriteName.contents()); spriteName.setContents(app.viewedObj().objName); } public function updateThumbnail():void { var targetObj:ScratchObj = app.viewedObj(); if (targetObj == null) return; if (targetObj.img.numChildren == 0) return; // shouldn't happen var src:DisplayObject = targetObj.img.getChildAt(0); if (src == lastSrcImg) return; // thumbnail is up to date var c:ScratchCostume = targetObj.currentCostume(); thumbnail.bitmapData = c.thumbnail(80, 80, targetObj.isStage); lastSrcImg = src; } private function updateRotationStyle():void { var targetObj:ScratchSprite = app.viewedObj() as ScratchSprite; if (targetObj == null) return; for (var i:int = 0; i < numChildren; i++) { var b:IconButton = getChildAt(i) as IconButton; if (b) { if (b.clickFunction == rotate360) b.setOn(targetObj.rotationStyle == 'normal'); if (b.clickFunction == rotateFlip) b.setOn(targetObj.rotationStyle == 'leftRight'); if (b.clickFunction == rotateNone) b.setOn(targetObj.rotationStyle == 'none'); } } } // ----------------------------- // Direction Wheel Interaction //------------------------------ private function dirMouseDown(evt:MouseEvent):void { app.gh.setDragClient(this, evt) } public function dragBegin(evt:MouseEvent):void { dragMove(evt) } public function dragEnd(evt:MouseEvent):void { dragMove(evt) } public function dragMove(evt:MouseEvent):void { var spr:ScratchSprite = app.viewedObj() as ScratchSprite; if (!spr) return; var p:Point = dirWheel.localToGlobal(new Point(0, 0)); var dx:int = evt.stageX - p.x; var dy:int = evt.stageY - p.y; if ((dx == 0) && (dy == 0)) return; var degrees:Number = 90 + ((180 / Math.PI) * Math.atan2(dy, dx)); spr.setDirection(degrees); } }}
package mocks { public class MockComponentA { [Ember] public var n:int; } }
package net.guttershark.managers { import flash.display.Sprite; import flash.events.Event; import flash.events.EventDispatcher; import flash.media.Sound; import flash.media.SoundChannel; import flash.media.SoundTransform; import flash.utils.Dictionary; import net.guttershark.util.Assertions; import net.guttershark.util.Singleton; /** * Dispatched when the internal volume has changed. * * @eventType flash.events.Event */ [Event("change", type="flash.events.Event")] /** * The SoundManager class manages sounds globaly, and manages * sound control for sprites. */ final public class SoundManager extends EventDispatcher { /** * Singleton instance. */ private static var inst:SoundManager; /** * A Assertions singleton instance. */ private var ast:Assertions; /** * Sounds stored in the manager. */ private var sounddic:Dictionary; /** * Internal volume indicator. Used for volume toggling. */ private var vol:Number; /** * Sounds objects with transforms store. */ private var sndObjectsWithTransforms:Dictionary; /** * Single transform used internally when playing any sound * This is passed to the sound object to set it's volume. */ private var mainTransform:SoundTransform; /** * Array of sounds transforms currently being used by playing sounds. */ private var soundTransforms:Dictionary; /** * Any sound currently playing. */ private var playingSounds:Dictionary; /** * @private * * Singleton SoundManager */ public function SoundManager() { Singleton.assertSingle(SoundManager); sounddic = new Dictionary(); sndObjectsWithTransforms = new Dictionary(); playingSounds = new Dictionary(); soundTransforms = new Dictionary(); mainTransform = new SoundTransform(1,0); vol = 1; ast = Assertions.gi(); } /** * Singleton access. */ public static function gi():SoundManager { if(!inst) inst = Singleton.gi(SoundManager); return inst; } /** * Add a sound into the sound manager. * * @param name Any unique identifier to give to the sound. * @param snd The sound to associate with that unique identifier. */ public function addSound(name:String, snd:Sound):void { ast.notNil(name,"The {name} parameter cannot be null"); ast.notNil(snd,"The {snd} parameter cannot be null"); sounddic[name] = snd; } /** * Add a sprite to control it's sound. * * @param obj Any sprite who's volume you want to control. */ public function addSprite(obj:Sprite):void { ast.notNil(obj,"The {obj} parameter cannot be null."); sndObjectsWithTransforms[obj] = obj; } /** * Remove a sprite from sound control * * @param obj The sprite to remove. */ public function removeSprite(obj:Sprite):void { if(!obj) return; sndObjectsWithTransforms[obj] = null; } /** * Remove a sound from the manager. * * @param name The unique sound identifier used when registering it into the manager. */ public function removeSound(name:String):void { if(!name) return; sounddic[name] = null; } /** * Play a sound that was previously registered. * * @param name The unique name used when registering it into the manager. * @param startOffset The start offset for the sound. * @param int The number of times to loop the sound. * @param customVolume A custom volume to play at, other than the current internal volume. */ public function playSound(name:String,startOffset:Number=0,loopCount:int=0,customVolume:int=-1):void { ast.notNil(name,"The {name} parameter cannot be null"); var snd:Sound = Sound(sounddic[name]); if(customVolume > -1) { var st:SoundTransform = new SoundTransform(customVolume,customVolume); soundTransforms[name] = st; playingSounds[name] = snd.play(startOffset,loopCount,st); } else playingSounds[name] = snd.play(startOffset,loopCount,mainTransform); } /** * Stop a playing sound. * * @param name The unique name used when registering it into the manager. */ public function stopSound(name:String):void { if(!name) return; if(!playingSounds[name]) return; var ch:SoundChannel = playingSounds[name] as SoundChannel; ch.stop(); playingSounds[name] = null; } /** * Stop all sounds playing through the SoundManager. */ public function stopAllSounds():void { for each(var ch:SoundChannel in playingSounds) ch.stop(); playingSounds = new Dictionary(); } /** * Set the global volume on all objects registered. * * @param level The volume level. */ public function set volume(level:int):void { ast.smaller(level,1,"The {level} parameter must be less than 1."); ast.greater(level,-0.9,"The {level} parameter must be 0 or greater."); mainTransform.volume = level; var obj:*; for each(obj in sndObjectsWithTransforms) obj.soundTransform.volume = mainTransform.volume; dispatchEvent(new Event(Event.CHANGE)); } /** * Read the internal volume. */ public function get volume():int { return vol; } /** * Toggle the current volume with 0. */ public function toggleVolume():void { var tmp1:Number = vol; var tmp2:Number = mainTransform.volume; mainTransform.volume = tmp1; vol = tmp2; dispatchEvent(new Event(Event.CHANGE)); } } }
/** * IMode * * An interface for confidentiality modes to implement * This could become deprecated at some point. * Copyright (c) 2007 Henri Torgemane * * See LICENSE.txt for full license information. */ package hurlant.crypto.symmetric { public interface IMode extends ICipher { } }
package cj.video { public final class TotalLine extends VideoBtn { public function TotalLine() { super(this.name); } } }
// ================================================================================================= // // Starling Framework // Copyright 2011-2014 Gamua. All Rights Reserved. // // This program is free software. You can redistribute and/or modify it // in accordance with the terms of the accompanying license agreement. // // ================================================================================================= package starling.display { import flash.geom.Rectangle; import flash.ui.Mouse; import flash.ui.MouseCursor; import starling.events.Event; import starling.events.Touch; import starling.events.TouchEvent; import starling.events.TouchPhase; import starling.text.TextField; import starling.textures.Texture; import starling.utils.HAlign; import starling.utils.VAlign; /** Dispatched when the user triggers the button. Bubbles. */ [Event(name="triggered", type="starling.events.Event")] /** A simple button composed of an image and, optionally, text. * * <p>You can use different textures for various states of the button. If you're providing * only an up state, the button is simply scaled a little when it is touched.</p> * * <p>In addition, you can overlay text on the button. To customize the text, you can use * properties equivalent to those of the TextField class. Move the text to a certain position * by updating the <code>textBounds</code> property.</p> * * <p>To react on touches on a button, there is special <code>Event.TRIGGERED</code> event. * Use this event instead of normal touch events. That way, users can cancel button * activation by moving the mouse/finger away from the button before releasing.</p> */ public class Button extends DisplayObjectContainer { private static const MAX_DRAG_DIST:Number = 50; private var mUpState:Texture; private var mDownState:Texture; private var mOverState:Texture; private var mDisabledState:Texture; private var mContents:Sprite; private var mBody:Image; private var mTextField:TextField; private var mTextBounds:Rectangle; private var mOverlay:Sprite; private var mScaleWhenDown:Number; private var mAlphaWhenDisabled:Number; private var mUseHandCursor:Boolean; private var mEnabled:Boolean; private var mState:String; private var mTriggerBounds:Rectangle; /** Creates a button with a set of state-textures and (optionally) some text. * Any state that is left 'null' will display the up-state texture. Beware that all * state textures should have the same dimensions. */ public function Button(upState:Texture, text:String="", downState:Texture=null, overState:Texture=null, disabledState:Texture=null) { if (upState == null) throw new ArgumentError("Texture 'upState' cannot be null"); mUpState = upState; mDownState = downState; mOverState = overState; mDisabledState = disabledState; mState = ButtonState.UP; mBody = new Image(upState); mScaleWhenDown = downState ? 1.0 : 0.9; mAlphaWhenDisabled = disabledState ? 1.0: 0.5; mEnabled = true; mUseHandCursor = true; mTextBounds = new Rectangle(0, 0, mBody.width, mBody.height); mContents = new Sprite(); mContents.addChild(mBody); addChild(mContents); addEventListener(TouchEvent.TOUCH, onTouch); this.touchGroup = true; this.text = text; } /** @inheritDoc */ public override function dispose():void { // text field might be disconnected from parent, so we have to dispose it manually if (mTextField) mTextField.dispose(); super.dispose(); } /** Readjusts the dimensions of the button according to its current state texture. * Call this method to synchronize button and texture size after assigning a texture * with a different size. Per default, this method also resets the bounds of the * button's text. */ public function readjustSize(resetTextBounds:Boolean=true):void { mBody.readjustSize(); if (resetTextBounds && mTextField != null) textBounds = new Rectangle(0, 0, mBody.width, mBody.height); } private function createTextField():void { if (mTextField == null) { mTextField = new TextField(mTextBounds.width, mTextBounds.height, ""); mTextField.vAlign = VAlign.CENTER; mTextField.hAlign = HAlign.CENTER; mTextField.touchable = false; mTextField.autoScale = true; mTextField.batchable = true; } mTextField.width = mTextBounds.width; mTextField.height = mTextBounds.height; mTextField.x = mTextBounds.x; mTextField.y = mTextBounds.y; } private function onTouch(event:TouchEvent):void { Mouse.cursor = (mUseHandCursor && mEnabled && event.interactsWith(this)) ? MouseCursor.BUTTON : MouseCursor.AUTO; var touch:Touch = event.getTouch(this); var isWithinBounds:Boolean; if (!mEnabled) { return; } else if (touch == null) { state = ButtonState.UP; } else if (touch.phase == TouchPhase.HOVER) { state = ButtonState.OVER; } else if (touch.phase == TouchPhase.BEGAN && mState != ButtonState.DOWN) { mTriggerBounds = getBounds(stage, mTriggerBounds); mTriggerBounds.inflate(MAX_DRAG_DIST, MAX_DRAG_DIST); state = ButtonState.DOWN; } else if (touch.phase == TouchPhase.MOVED) { isWithinBounds = mTriggerBounds.contains(touch.globalX, touch.globalY); if (mState == ButtonState.DOWN && !isWithinBounds) { // reset button when finger is moved too far away ... state = ButtonState.UP; } else if (mState == ButtonState.UP && isWithinBounds) { // ... and reactivate when the finger moves back into the bounds. state = ButtonState.DOWN; } } else if (touch.phase == TouchPhase.ENDED && mState == ButtonState.DOWN) { state = ButtonState.UP; dispatchEventWith(Event.TRIGGERED, true); } } /** The current state of the button. The corresponding strings are found * in the ButtonState class. */ public function get state():String { return mState; } public function set state(value:String):void { mState = value; mContents.scaleX = mContents.scaleY = 1.0; switch (mState) { case ButtonState.DOWN: setStateTexture(mDownState); mContents.scaleX = mContents.scaleY = scaleWhenDown; mContents.x = (1.0 - scaleWhenDown) / 2.0 * mBody.width; mContents.y = (1.0 - scaleWhenDown) / 2.0 * mBody.height; break; case ButtonState.UP: setStateTexture(mUpState); mContents.x = mContents.y = 0; break; case ButtonState.OVER: setStateTexture(mOverState); mContents.x = mContents.y = 0; break; case ButtonState.DISABLED: setStateTexture(mDisabledState); mContents.x = mContents.y = 0; break; default: throw new ArgumentError("Invalid button state: " + mState); } } private function setStateTexture(texture:Texture):void { mBody.texture = texture ? texture : mUpState; } /** The scale factor of the button on touch. Per default, a button without a down state * texture will be made slightly smaller, while a button with a down state texture * remains unscaled. */ public function get scaleWhenDown():Number { return mScaleWhenDown; } public function set scaleWhenDown(value:Number):void { mScaleWhenDown = value; } /** The alpha value of the button when it is disabled. @default 0.5 */ public function get alphaWhenDisabled():Number { return mAlphaWhenDisabled; } public function set alphaWhenDisabled(value:Number):void { mAlphaWhenDisabled = value; } /** Indicates if the button can be triggered. */ public function get enabled():Boolean { return mEnabled; } public function set enabled(value:Boolean):void { if (mEnabled != value) { mEnabled = value; mContents.alpha = value ? 1.0 : mAlphaWhenDisabled; state = value ? ButtonState.UP : ButtonState.DISABLED; } } /** The text that is displayed on the button. */ public function get text():String { return mTextField ? mTextField.text : ""; } public function set text(value:String):void { if (value.length == 0) { if (mTextField) { mTextField.text = value; mTextField.removeFromParent(); } } else { createTextField(); mTextField.text = value; if (mTextField.parent == null) mContents.addChild(mTextField); } } /** The name of the font displayed on the button. May be a system font or a registered * bitmap font. */ public function get fontName():String { return mTextField ? mTextField.fontName : "Verdana"; } public function set fontName(value:String):void { createTextField(); mTextField.fontName = value; } /** The size of the font. */ public function get fontSize():Number { return mTextField ? mTextField.fontSize : 12; } public function set fontSize(value:Number):void { createTextField(); mTextField.fontSize = value; } /** The color of the font. */ public function get fontColor():uint { return mTextField ? mTextField.color : 0x0; } public function set fontColor(value:uint):void { createTextField(); mTextField.color = value; } /** Indicates if the font should be bold. */ public function get fontBold():Boolean { return mTextField ? mTextField.bold : false; } public function set fontBold(value:Boolean):void { createTextField(); mTextField.bold = value; } /** The texture that is displayed when the button is not being touched. */ public function get upState():Texture { return mUpState; } public function set upState(value:Texture):void { if (value == null) throw new ArgumentError("Texture 'upState' cannot be null"); if (mUpState != value) { mUpState = value; if ( mState == ButtonState.UP || (mState == ButtonState.DISABLED && mDisabledState == null) || (mState == ButtonState.DOWN && mDownState == null) || (mState == ButtonState.OVER && mOverState == null)) { setStateTexture(value); } } } /** The texture that is displayed while the button is touched. */ public function get downState():Texture { return mDownState; } public function set downState(value:Texture):void { if (mDownState != value) { mDownState = value; if (mState == ButtonState.DOWN) setStateTexture(value); } } /** The texture that is displayed while mouse hovers over the button. */ public function get overState():Texture { return mOverState; } public function set overState(value:Texture):void { if (mOverState != value) { mOverState = value; if (mState == ButtonState.OVER) setStateTexture(value); } } /** The texture that is displayed when the button is disabled. */ public function get disabledState():Texture { return mDisabledState; } public function set disabledState(value:Texture):void { if (mDisabledState != value) { mDisabledState = value; if (mState == ButtonState.DISABLED) setStateTexture(value); } } /** The vertical alignment of the text on the button. */ public function get textVAlign():String { return mTextField ? mTextField.vAlign : VAlign.CENTER; } public function set textVAlign(value:String):void { createTextField(); mTextField.vAlign = value; } /** The horizontal alignment of the text on the button. */ public function get textHAlign():String { return mTextField ? mTextField.hAlign : HAlign.CENTER; } public function set textHAlign(value:String):void { createTextField(); mTextField.hAlign = value; } /** The bounds of the textfield on the button. Allows moving the text to a custom position. */ public function get textBounds():Rectangle { return mTextBounds.clone(); } public function set textBounds(value:Rectangle):void { mTextBounds = value.clone(); createTextField(); } /** The color of the button's state image. Just like every image object, each pixel's * color is multiplied with this value. @default white */ public function get color():uint { return mBody.color; } public function set color(value:uint):void { mBody.color = value; } /** The overlay sprite is displayed on top of the button contents. It scales with the * button when pressed. Use it to add additional objects to the button (e.g. an icon). */ public function get overlay():Sprite { if (mOverlay == null) mOverlay = new Sprite(); mContents.addChild(mOverlay); // make sure it's always on top return mOverlay; } /** Indicates if the mouse cursor should transform into a hand while it's over the button. * @default true */ public override function get useHandCursor():Boolean { return mUseHandCursor; } public override function set useHandCursor(value:Boolean):void { mUseHandCursor = value; } } }
/* Copyright (c) 2006-2013 Regents of the University of Minnesota. For licensing terms, see the file LICENSE. */ package utils.rev_spec { public class Pinned extends Base { // *** Constructor public function Pinned() :void { super(); } // override public function equals(rev:Base) :Boolean { var other:Pinned = (rev as Pinned); return (other !== null); } } }
package serverProto.equipment { import com.netease.protobuf.Message; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_UINT64; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_UINT32; import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_ENUM; import com.netease.protobuf.WireType; import com.netease.protobuf.UInt64; import com.netease.protobuf.WritingBuffer; import com.netease.protobuf.WriteUtils; import flash.utils.IDataInput; import com.netease.protobuf.ReadUtils; import flash.errors.IOError; public final class ProtoDecomposeStoneRequest extends Message { public static const EQUIPMENT_SEQUENCE:FieldDescriptor$TYPE_UINT64 = new FieldDescriptor$TYPE_UINT64("serverProto.equipment.ProtoDecomposeStoneRequest.equipment_sequence","equipmentSequence",1 << 3 | WireType.VARINT); public static const MAIN_STONE_INDEX:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.equipment.ProtoDecomposeStoneRequest.main_stone_index","mainStoneIndex",2 << 3 | WireType.VARINT); public static const OBJ_TYPE:FieldDescriptor$TYPE_ENUM = new FieldDescriptor$TYPE_ENUM("serverProto.equipment.ProtoDecomposeStoneRequest.obj_type","objType",3 << 3 | WireType.VARINT,OperateObjType); public var equipmentSequence:UInt64; public var mainStoneIndex:uint; private var obj_type$field:int; private var hasField$0:uint = 0; public function ProtoDecomposeStoneRequest() { super(); } public function clearObjType() : void { this.hasField$0 = this.hasField$0 & 4.294967294E9; this.obj_type$field = new int(); } public function get hasObjType() : Boolean { return (this.hasField$0 & 1) != 0; } public function set objType(param1:int) : void { this.hasField$0 = this.hasField$0 | 1; this.obj_type$field = param1; } public function get objType() : int { return this.obj_type$field; } override final function writeToBuffer(param1:WritingBuffer) : void { var _loc2_:* = undefined; WriteUtils.writeTag(param1,WireType.VARINT,1); WriteUtils.write$TYPE_UINT64(param1,this.equipmentSequence); WriteUtils.writeTag(param1,WireType.VARINT,2); WriteUtils.write$TYPE_UINT32(param1,this.mainStoneIndex); if(this.hasObjType) { WriteUtils.writeTag(param1,WireType.VARINT,3); WriteUtils.write$TYPE_ENUM(param1,this.obj_type$field); } for(_loc2_ in this) { super.writeUnknown(param1,_loc2_); } } override final function readFromSlice(param1:IDataInput, param2:uint) : void { /* * Decompilation error * Code may be obfuscated * Tip: You can try enabling "Automatic deobfuscation" in Settings * Error type: IndexOutOfBoundsException (Index: 3, Size: 3) */ throw new flash.errors.IllegalOperationError("Not decompiled due to error"); } } }
package cc.gullinbursti.audio.modulate { public class BasicModulate { public function BasicModulate() { } } }
package Levels.BasicTutorials { import Levels.Level; import Modules.*; import Testing.Goals.InstructionSelectGoal; import Values.OpcodeValue; /** * ... * @author Nicholas "PleasingFungus" Feinberg */ public class Op2Tutorial extends Level { public function Op2Tutorial() { super("Two Instructions", new InstructionSelectGoal, false, [ConstIn, Adder, Latch, DataWriter, DataReader, InstructionDecoder, InstructionDemux], [OpcodeValue.OP_SAVI, OpcodeValue.OP_ADDM]); info = "There are two different instruction types that appear in this level, and a new part, the Instruction Multiplexer module."; useModuleRecord = false; commentsEnabled = true; } } }
package com.company.assembleegameclient.objects.particles { public class HitEffect extends ParticleEffect { public function HitEffect(param1:Vector.<uint>, param2:int, param3:int, param4:Number, param5:Number) { super(); this.colors_ = param1; size_ = param2; this.numParts_ = param3; this.angle_ = param4; this.speed_ = param5; } public var colors_:Vector.<uint>; public var numParts_:int; public var angle_:Number; public var speed_:Number; override public function runNormalRendering(param1:int, param2:int):Boolean { var _loc6_:uint = 0; var _loc7_:Particle = null; if (this.colors_.length == 0) { return false; } var _loc3_:Number = this.speed_ / 10 * 60 * Math.cos(this.angle_ + 3.14159265358979); var _loc4_:Number = this.speed_ / 10 * 60 * Math.sin(this.angle_ + 3.14159265358979); var _loc5_:int = 0; while (_loc5_ < this.numParts_) { _loc6_ = this.colors_[int(this.colors_.length * Math.random())]; _loc7_ = new HitParticle(_loc6_, 0.5, size_, 200 + Math.random() * 100, _loc3_ + (Math.random() - 0.5) * 0.4, _loc4_ + (Math.random() - 0.5) * 0.4, 0); map_.addObj(_loc7_, x_, y_); _loc5_++; } return false; } override public function runEasyRendering(param1:int, param2:int):Boolean { var _loc6_:uint = 0; var _loc7_:Particle = null; if (this.colors_.length == 0) { return false; } var _loc3_:Number = this.speed_ / 10 * 60 * Math.cos(this.angle_ + 3.14159265358979); var _loc4_:Number = this.speed_ / 10 * 60 * Math.sin(this.angle_ + 3.14159265358979); this.numParts_ = this.numParts_ * 0.2; var _loc5_:int = 0; while (_loc5_ < this.numParts_) { _loc6_ = this.colors_[int(this.colors_.length * Math.random())]; _loc7_ = new HitParticle(_loc6_, 0.5, 10, 5 + Math.random() * 100, _loc3_ + (Math.random() - 0.5) * 0.4, _loc4_ + (Math.random() - 0.5) * 0.4, 0); map_.addObj(_loc7_, x_, y_); _loc5_++; } return false; } } } import com.company.assembleegameclient.objects.particles.Particle; import flash.geom.Vector3D; class HitParticle extends Particle { function HitParticle(param1:uint, param2:Number, param3:int, param4:int, param5:Number, param6:Number, param7:Number) { this.moveVec_ = new Vector3D(); super(param1, param2, param3); var _loc8_:* = param4; this.lifetime_ = _loc8_; this.timeLeft_ = _loc8_; this.moveVec_.x = param5; this.moveVec_.y = param6; this.moveVec_.z = param7; } public var lifetime_:int; public var timeLeft_:int; protected var moveVec_:Vector3D; override public function update(param1:int, param2:int):Boolean { this.timeLeft_ = this.timeLeft_ - param2; if (this.timeLeft_ <= 0) { return false; } x_ = x_ + this.moveVec_.x * param2 * 0.008; y_ = y_ + this.moveVec_.y * param2 * 0.008; z_ = z_ + this.moveVec_.z * param2 * 0.008; return true; } }
package org.flexlite.domUI.effects.easing { /** * Bounce 类实现缓动功能,该功能模拟目标对象上的重力牵引和回弹目标对象。效果目标的移动会向着最终值加速,然后对着最终值回弹几次。 * @author DOM */ public class Bounce implements IEaser { /** * 构造函数 */ public function Bounce() { } public function ease(fraction:Number):Number { return easeOut(fraction, 0, 1, 1); } public function easeOut(t:Number, b:Number, c:Number, d:Number):Number { if ((t /= d) < (1 / 2.75)) return c * (7.5625 * t * t) + b; else if (t < (2 / 2.75)) return c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b; else if (t < (2.5 / 2.75)) return c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b; else return c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b; } } }
/* * _________ __ __ * _/ / / /____ / /________ ____ ____ ___ * _/ / / __/ -_) __/ __/ _ `/ _ `/ _ \/ _ \ * _/________/ \__/\__/\__/_/ \_,_/\_, /\___/_//_/ * /___/ * * Tetragon : Game Engine for multi-platform ActionScript projects. * http://www.tetragonengine.com/ - Copyright (C) 2012 Sascha Balkau * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package tetragon.view.display.shape { import tetragon.util.reflection.getClassName; import flash.display.BitmapData; import flash.display.Shape; import flash.geom.Matrix; import flash.geom.Rectangle; /** * A scale-9 Shape that uses a bitmap fill. */ public class Scale9BitmapShape extends Shape implements IShape { //----------------------------------------------------------------------------------------- // Properties //----------------------------------------------------------------------------------------- /** @private */ protected var _bitmapData:BitmapData; /** @private */ protected var _width:Number = 0; /** @private */ protected var _height:Number = 0; /** @private */ protected var _inner:Rectangle; /** @private */ protected var _outer:Rectangle; /** @private */ protected var _smoothing:Boolean; //----------------------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------------------- /** * Creates a new instance of the class. * * @param bitmapData BitmapData source. * @param width Draw width. * @param height Draw height. * @param inner Inner rectangle (relative to 0,0). * @param outer Outer rectangle (relative to 0,0). * @param smoothing If <code>false</code>, upscaled bitmap images are rendered by * using a nearest-neighbor algorithm and look pixelated. If * <code>true</code>, upscaled bitmap images are rendered by using a * bilinear algorithm. Rendering by using the nearest neighbor algorithm is * usually faster. */ public function Scale9BitmapShape(bitmapData:BitmapData = null, width:Number = 0, height:Number = 0, inner:Rectangle = null, outer:Rectangle = null, smoothing:Boolean = false) { setProperties(bitmapData, width, height, inner, outer, smoothing); draw(); } //----------------------------------------------------------------------------------------- // Public Methods //----------------------------------------------------------------------------------------- /** * Allows to set all properties at once without updating. * * @param bitmapData * @param width * @param height * @param inner * @param outer * @param smoothing */ public function setProperties(bitmapData:BitmapData = null, width:Number = NaN, height:Number = NaN, inner:Rectangle = null, outer:Rectangle = null, smoothing:Boolean = false):void { if (bitmapData) _bitmapData = bitmapData; if (!isNaN(width)) _width = width < 0 ? 0 : width; if (!isNaN(height)) _height = height < 0 ? 0 : height; if (inner) _inner = inner; if (outer) _outer = outer; _smoothing = smoothing; } /** * @inheritDoc */ public function draw():void { if (_bitmapData && _width > 0 && _height > 0) drawShape(); } /** * @inheritDoc */ public function clone():* { return cloneShape(this); } /** * @inheritDoc */ override public function toString():String { return getClassName(this); } //----------------------------------------------------------------------------------------- // Accessors //----------------------------------------------------------------------------------------- override public function get width():Number { return _width; } override public function set width(v:Number):void { if (v == _width) return; _width = v < 0 ? 0 : v; draw(); } override public function get height():Number { return _height; } override public function set height(v:Number):void { if (v == _height) return; _height = v < 0 ? 0 : v; draw(); } public function get bitmapData():BitmapData { return _bitmapData; } public function set bitmapData(v:BitmapData):void { if (v == _bitmapData) return; _bitmapData = v; draw(); } public function get inner():Rectangle { return _inner; } public function set inner(v:Rectangle):void { if (v == _inner) return; _inner = v; draw(); } public function get outer():Rectangle { return _outer; } public function set outer(v:Rectangle):void { if (v == _outer) return; _outer = v; draw(); } public function get smoothing():Boolean { return _smoothing; } public function set smoothing(v:Boolean):void { if (v == _smoothing) return; _smoothing = v; draw(); } //----------------------------------------------------------------------------------------- // Private Methods //----------------------------------------------------------------------------------------- /** * @private */ protected function drawShape():void { if (!_inner) { _inner = new Rectangle(10, 10, _bitmapData.width - 10, _bitmapData.height - 10); } var x:int, y:int; var ox:Number = 0, oy:Number; var dx:Number = 0, dy:Number; var w:Number, h:Number, dw:Number, dh:Number; var sw:int = _bitmapData.width; var sh:int = _bitmapData.height; var widths:Array = [_inner.left + 1, _inner.width - 2, sw - _inner.right + 1]; var heights:Array = [_inner.top + 1, _inner.height - 2, sh - _inner.bottom + 1]; var rx:Number = _width - widths[0] - widths[2]; var ry:Number = _height - heights[0] - heights[2]; var ol:Number = _outer ? -_outer.left : 0; var ot:Number = _outer ? -_outer.top : 0; var m:Matrix = new Matrix(); for (x; x < 3 ; x++) { w = widths[x]; dw = x == 1 ? rx : w; dy = oy = 0; m.a = dw / w; for (y = 0; y < 3; y++) { h = heights[y]; dh = y == 1 ? ry : h; if (dw > 0 && dh > 0) { m.d = dh / h; m.tx = -ox * m.a + dx; m.ty = -oy * m.d + dy; m.translate(ol, ot); graphics.beginBitmapFill(_bitmapData, m, false, _smoothing); graphics.drawRect(dx + ol, dy + ot, dw, dh); } oy += h; dy += dh; } ox += w; dx += dw; } graphics.endFill(); } /** * @private */ private static function cloneShape(s:Scale9BitmapShape):Scale9BitmapShape { var clazz:Class = (s as Object)['constructor']; return new clazz(s.bitmapData, s.width, s.height, s.inner, s.outer, s.smoothing); } } }
// ================================================================================================= // // Starling Framework // Copyright 2011-2014 Gamua. All Rights Reserved. // // This program is free software. You can redistribute and/or modify it // in accordance with the terms of the accompanying license agreement. // // ================================================================================================= package starling.filters { import flash.display.BitmapDataChannel; import flash.display3D.Context3D; import flash.display3D.Context3DProgramType; import flash.display3D.Context3DTextureFormat; import flash.display3D.Context3DVertexBufferFormat; import flash.display3D.Program3D; import flash.display3D.VertexBuffer3D; import flash.geom.Matrix3D; import flash.geom.Point; import starling.core.RenderSupport; import starling.core.Starling; import starling.textures.Texture; import starling.utils.formatString; /** The DisplacementMapFilter class uses the pixel values from the specified texture (called * the displacement map) to perform a displacement of an object. You can use this filter * to apply a warped or mottled effect to any object that inherits from the DisplayObject * class. * * <p>The filter uses the following formula:</p> * <listing>dstPixel[x, y] = srcPixel[x + ((componentX(x, y) - 128) &#42; scaleX) / 256, * y + ((componentY(x, y) - 128) &#42; scaleY) / 256] * </listing> * * <p>Where <code>componentX(x, y)</code> gets the componentX property color value from the * map texture at <code>(x - mapPoint.x, y - mapPoint.y)</code>.</p> */ public class DisplacementMapFilter extends FragmentFilter { private var mMapTexture:Texture; private var mMapPoint:Point; private var mComponentX:uint; private var mComponentY:uint; private var mScaleX:Number; private var mScaleY:Number; private var mRepeat:Boolean; private var mShaderProgram:Program3D; private var mMapTexCoordBuffer:VertexBuffer3D; /** Helper objects */ private static var sOneHalf:Vector.<Number> = new <Number>[0.5, 0.5, 0.5, 0.5]; private static var sMapTexCoords:Vector.<Number> = new <Number>[0, 0, 1, 0, 0, 1, 1, 1]; private static var sMatrix:Matrix3D = new Matrix3D(); private static var sMatrixData:Vector.<Number> = new <Number>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; /** Creates a new displacement map filter that uses the provided map texture. */ public function DisplacementMapFilter(mapTexture:Texture, mapPoint:Point=null, componentX:uint=0, componentY:uint=0, scaleX:Number=0.0, scaleY:Number=0.0, repeat:Boolean=false) { mMapTexture = mapTexture; mMapPoint = new Point(); mComponentX = componentX; mComponentY = componentY; mScaleX = scaleX; mScaleY = scaleY; this.mapPoint = mapPoint; super(); } /** @inheritDoc */ public override function dispose():void { if (mMapTexCoordBuffer) mMapTexCoordBuffer.dispose(); super.dispose(); } /** @private */ protected override function createPrograms():void { // the texture coordinates for the map texture are uploaded via a separate buffer if (mMapTexCoordBuffer) mMapTexCoordBuffer.dispose(); mMapTexCoordBuffer = Starling.context.createVertexBuffer(4, 2); var target:Starling = Starling.current; var mapFlags:String = RenderSupport.getTextureLookupFlags( mapTexture.format, mapTexture.mipMapping, mapTexture.repeat); var inputFlags:String = RenderSupport.getTextureLookupFlags( Context3DTextureFormat.BGRA, false, mRepeat); var programName:String = formatString("DMF_m{0}_i{1}", mapFlags, inputFlags); if (target.hasProgram(programName)) { mShaderProgram = target.getProgram(programName); } else { // vc0-3: mvpMatrix // va0: vertex position // va1: input texture coords // va2: map texture coords var vertexShader:String = [ "m44 op, va0, vc0", // 4x4 matrix transform to output space "mov v0, va1", // pass input texture coordinates to fragment program "mov v1, va2" // pass map texture coordinates to fragment program ].join("\n"); // v0: input texCoords // v1: map texCoords // fc0: OneHalf // fc1-4: matrix var fragmentShader:String = [ "tex ft0, v1, fs1 " + mapFlags, // read map texture "sub ft1, ft0, fc0", // subtract 0.5 -> range [-0.5, 0.5] "m44 ft2, ft1, fc1", // multiply matrix with displacement values "add ft3, v0, ft2", // add displacement values to texture coords "tex oc, ft3, fs0 " + inputFlags // read input texture at displaced coords ].join("\n"); mShaderProgram = target.registerProgramFromSource(programName, vertexShader, fragmentShader); } } /** @private */ protected override function activate(pass:int, context:Context3D, texture:Texture):void { // already set by super class: // // vertex constants 0-3: mvpMatrix (3D) // vertex attribute 0: vertex position (FLOAT_2) // vertex attribute 1: texture coordinates (FLOAT_2) // texture 0: input texture updateParameters(texture.nativeWidth, texture.nativeHeight); context.setVertexBufferAt(2, mMapTexCoordBuffer, 0, Context3DVertexBufferFormat.FLOAT_2); context.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 0, sOneHalf); context.setProgramConstantsFromMatrix(Context3DProgramType.FRAGMENT, 1, sMatrix, true); context.setTextureAt(1, mMapTexture.base); context.setProgram(mShaderProgram); } /** @private */ override protected function deactivate(pass:int, context:Context3D, texture:Texture):void { context.setVertexBufferAt(2, null); context.setTextureAt(1, null); } private function updateParameters(textureWidth:int, textureHeight:int):void { // matrix: // Maps RGBA values of map texture to UV-offsets in input texture. var scale:Number = Starling.contentScaleFactor; var columnX:int, columnY:int; for (var i:int=0; i<16; ++i) sMatrixData[i] = 0; if (mComponentX == BitmapDataChannel.RED) columnX = 0; else if (mComponentX == BitmapDataChannel.GREEN) columnX = 1; else if (mComponentX == BitmapDataChannel.BLUE) columnX = 2; else columnX = 3; if (mComponentY == BitmapDataChannel.RED) columnY = 0; else if (mComponentY == BitmapDataChannel.GREEN) columnY = 1; else if (mComponentY == BitmapDataChannel.BLUE) columnY = 2; else columnY = 3; sMatrixData[int(columnX * 4 )] = mScaleX * scale / textureWidth; sMatrixData[int(columnY * 4 + 1)] = mScaleY * scale / textureHeight; sMatrix.copyRawDataFrom(sMatrixData); // vertex buffer: (containing map texture coordinates) // The size of input texture and map texture may be different. We need to calculate // the right values for the texture coordinates at the filter vertices. var mapX:Number = mMapPoint.x / mapTexture.width; var mapY:Number = mMapPoint.y / mapTexture.height; var maxU:Number = textureWidth / mapTexture.nativeWidth; var maxV:Number = textureHeight / mapTexture.nativeHeight; sMapTexCoords[0] = -mapX; sMapTexCoords[1] = -mapY; sMapTexCoords[2] = -mapX + maxU; sMapTexCoords[3] = -mapY; sMapTexCoords[4] = -mapX; sMapTexCoords[5] = -mapY + maxV; sMapTexCoords[6] = -mapX + maxU; sMapTexCoords[7] = -mapY + maxV; mMapTexture.adjustTexCoords(sMapTexCoords); mMapTexCoordBuffer.uploadFromVector(sMapTexCoords, 0, 4); } // properties /** Describes which color channel to use in the map image to displace the x result. * Possible values are constants from the BitmapDataChannel class. */ public function get componentX():uint { return mComponentX; } public function set componentX(value:uint):void { mComponentX = value; } /** Describes which color channel to use in the map image to displace the y result. * Possible values are constants from the BitmapDataChannel class. */ public function get componentY():uint { return mComponentY; } public function set componentY(value:uint):void { mComponentY = value; } /** The multiplier used to scale the x displacement result from the map calculation. */ public function get scaleX():Number { return mScaleX; } public function set scaleX(value:Number):void { mScaleX = value; } /** The multiplier used to scale the y displacement result from the map calculation. */ public function get scaleY():Number { return mScaleY; } public function set scaleY(value:Number):void { mScaleY = value; } /** The texture that will be used to calculate displacement. */ public function get mapTexture():Texture { return mMapTexture; } public function set mapTexture(value:Texture):void { if (mMapTexture != value) { mMapTexture = value; createPrograms(); } } /** A value that contains the offset of the upper-left corner of the target display * object from the upper-left corner of the map image. */ public function get mapPoint():Point { return mMapPoint; } public function set mapPoint(value:Point):void { if (value) mMapPoint.setTo(value.x, value.y); else mMapPoint.setTo(0, 0); } /** Indicates how the pixels at the edge of the input image (the filtered object) will * be wrapped at the edge. */ public function get repeat():Boolean { return mRepeat; } public function set repeat(value:Boolean):void { if (mRepeat != value) { mRepeat = value; createPrograms(); } } } }
package com.playata.framework.util.mousewheel { public class BrowserInfo { public static const WIN_PLATFORM:String = "win"; public static const MAC_PLATFORM:String = "mac"; public static const SAFARI_AGENT:String = "safari"; public static const OPERA_AGENT:String = "opera"; public static const IE_AGENT:String = "msie"; public static const MOZILLA_AGENT:String = "mozilla"; public static const CHROME_AGENT:String = "chrome"; private var _platform:String = "undefined"; private var _browser:String = "undefined"; private var _version:String = "undefined"; public function BrowserInfo(param1:Object, param2:Object, param3:String) { super(); if(!param1 || !param2 || !param3) { return; } _version = param1.version; var _loc7_:int = 0; var _loc6_:* = param1; for(var _loc5_ in param1) { if(_loc5_ != "version") { if(param1[_loc5_] == true) { _browser = _loc5_; break; } } } var _loc9_:int = 0; var _loc8_:* = param2; for(var _loc4_ in param2) { if(param2[_loc4_] == true) { _platform = _loc4_; } } } public function get platform() : String { return _platform; } public function get browser() : String { return _browser; } public function get version() : String { return _version; } } }
package world.command { import com.tencent.morefun.framework.base.Command; import flash.geom.Point; import def.PluginDef; public class StartChangeSceneCommand extends Command { public var toScene:int; public var toPosition:Point; public var toDirection:int; public var reason:int; public function StartChangeSceneCommand(param1:int = 0, param2:Point = null, param3:int = -1, param4:int = 0) { super(Command.FULL_SCREEN | Command.TOTAL_FILE,false); this.toScene = param1; this.toPosition = param2; this.toDirection = param3; this.reason = param4; } override public function getPluginName() : String { return PluginDef.WORLD; } } }
package com.dougmccune.foam.view { import flash.display.DisplayObject; import flash.utils.Dictionary; import org.generalrelativity.foam.dynamics.element.IBody; import org.generalrelativity.foam.dynamics.element.ISimulatable; import org.generalrelativity.foam.view.IFoamRenderer; import org.generalrelativity.foam.view.Renderable; import org.generalrelativity.foam.view.SimpleFoamRenderer; public class DisplayObjectFoamRenderer extends SimpleFoamRenderer implements IFoamRenderer { /** * We need to override setupRenderDataDefaults because the SimpleFoamRenderer assumes we're passing in * a Renderable object that has a data property that has a few specific properties, like color, alpha, and hash. * Since we're actually going to pass in a DisplayObject, we can't let super.setupRenderDataDefaults run. */ override protected function setupRenderDataDefaults( renderable:Renderable ) : void { } override public function redraw():void { for each( var renderable:Renderable in _dynamicRenderables ) { if(renderable.data is DisplayObject) { var displayObject:DisplayObject = (renderable.data as DisplayObject); if( renderable.element is ISimulatable ) { displayObject.x = ISimulatable( renderable.element ).x; displayObject.y = ISimulatable( renderable.element ).y; if( renderable.element is IBody ) { displayObject.rotation = IBody( renderable.element ).q * 180 / Math.PI; } } } } } } }
package de.notfound.resourcely { import de.notfound.resourcely.config.ResourcelyConfigBuilderTest; import de.notfound.resourcely.demo.DemoTest; import de.notfound.resourcely.dimension.ImageFileDimensionExtractorTest; import de.notfound.resourcely.type.FileTypeSignatureTest; import de.notfound.resourcely.type.ImageFileTypeIdentifierTest; import de.notfound.resourcely.util.FileUtilTest; [Suite] [RunWith("org.flexunit.runners.Suite")] public class TestSuite { public var demoTest : DemoTest; public var fileTypeSignatureTest : FileTypeSignatureTest; public var imageFileTypeIdentifierTest : ImageFileTypeIdentifierTest; public var imageFileDimensionExtractorTest : ImageFileDimensionExtractorTest; public var fileUtilTest : FileUtilTest; public var resourcelyConfigBuilderTest : ResourcelyConfigBuilderTest; } }
package com.google.zxing.client.result.optional { /* * Copyright 2008 ZXing 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. */ import com.google.zxing.client.result.ResultParser; /** * <p>Superclass for classes encapsulating results in the NDEF format. * See <a href="http://www.nfc-forum.org/specs/">http://www.nfc-forum.org/specs/</a>.</p> * * <p>This code supports a limited subset of NDEF messages, ones that are plausibly * useful in 2D barcode formats. This generally includes 1-record messages, no chunking, * "short record" syntax, no ID field.</p> * * @author Sean Owen */ public class AbstractNDEFResultParser extends ResultParser { public static function bytesToString(bytes:Array, offset:int, length:int, encoding:String):String { try { // can't do this in Actionscript //return new String(bytes, offset, length, encoding); throw new Error("Platform does not support encoding"); } catch (uee:Error) { // This should only be used when 'encoding' is an encoding that must necessarily // be supported by the JVM, like UTF-8 throw new Error("Platform does not support required encoding: " + uee); } throw new Error("Platform does not support encoding"); } }}
import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import mx.core.IPropertyChangeNotifier; import mx.events.PropertyChangeEvent; import mx.utils.ObjectProxy; import mx.utils.UIDUtil; import spark.components.Label; import spark.components.VGroup; import valueObjects.Product; import spark.components.Button; class BindableProperty { /* * generated bindable wrapper for property add (public) * - generated setter * - generated getter * - original public var 'add' moved to '_96417add' */ [Bindable(event="propertyChange")] public function get add():spark.components.Button { return this._96417add; } public function set add(value:spark.components.Button):void { var oldValue:Object = this._96417add; if (oldValue !== value) { this._96417add = value; if (this.hasEventListener("propertyChange")) this.dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this, "add", oldValue, value)); } } /* * generated bindable wrapper for property price (public) * - generated setter * - generated getter * - original public var 'price' moved to '_106934601price' */ [Bindable(event="propertyChange")] public function get price():spark.components.Label { return this._106934601price; } public function set price(value:spark.components.Label):void { var oldValue:Object = this._106934601price; if (oldValue !== value) { this._106934601price = value; if (this.hasEventListener("propertyChange")) this.dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this, "price", oldValue, value)); } } /* * generated bindable wrapper for property prodName (public) * - generated setter * - generated getter * - original public var 'prodName' moved to '_1004925310prodName' */ [Bindable(event="propertyChange")] public function get prodName():spark.components.Label { return this._1004925310prodName; } public function set prodName(value:spark.components.Label):void { var oldValue:Object = this._1004925310prodName; if (oldValue !== value) { this._1004925310prodName = value; if (this.hasEventListener("propertyChange")) this.dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this, "prodName", oldValue, value)); } } /* * generated bindable wrapper for property products (public) * - generated setter * - generated getter * - original public var 'products' moved to '_1003761308products' */ [Bindable(event="propertyChange")] public function get products():spark.components.VGroup { return this._1003761308products; } public function set products(value:spark.components.VGroup):void { var oldValue:Object = this._1003761308products; if (oldValue !== value) { this._1003761308products = value; if (this.hasEventListener("propertyChange")) this.dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this, "products", oldValue, value)); } } /* * generated bindable wrapper for property remove (public) * - generated setter * - generated getter * - original public var 'remove' moved to '_934610812remove' */ [Bindable(event="propertyChange")] public function get remove():spark.components.Button { return this._934610812remove; } public function set remove(value:spark.components.Button):void { var oldValue:Object = this._934610812remove; if (oldValue !== value) { this._934610812remove = value; if (this.hasEventListener("propertyChange")) this.dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this, "remove", oldValue, value)); } } /* * generated bindable wrapper for property product (public) * - generated setter * - generated getter * - original public var 'product' moved to '_309474065product' */ [Bindable(event="propertyChange")] public function get product():Product { return this._309474065product; } public function set product(value:Product):void { var oldValue:Object = this._309474065product; if (oldValue !== value) { this._309474065product = value; if (this.hasEventListener("propertyChange")) this.dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this, "product", oldValue, value)); } } }
/* Copyright (c) 2014 James M. Greene */ import flash.*; package { public class PmdPassingTest { } }
/* Copyright (c) 2006-2013 Regents of the University of Minnesota. For licensing terms, see the file LICENSE. */ package items.feats { import flash.display.Graphics; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.geom.Point; import flash.utils.Dictionary; import flash.utils.Timer; import mx.collections.ArrayCollection; import mx.controls.Alert; import mx.core.IToolTip; import mx.managers.ToolTipManager; import mx.utils.ObjectUtil; import mx.utils.StringUtil; import mx.utils.UIDUtil; import grax.Access_Infer; import grax.Access_Level; import grax.Aggregator_Base; import items.Geofeature; import items.Item_Versioned; import items.Record_Base; import items.utils.Geofeature_Layer; import items.utils.Item_Type; import items.utils.Landmark; import items.utils.Travel_Mode; import utils.geom.Dual_Rect; import utils.geom.Geometry; import utils.geom.MOBRable_DR; import utils.misc.Collection; import utils.misc.Data_Change_Event; import utils.misc.Introspect; import utils.misc.Logging; import utils.misc.Map_Label; import utils.misc.Set_UUID; import utils.misc.Strutil; import utils.misc.Timeutil; import utils.rev_spec.*; import views.base.App_Action; import views.base.Map_Layer; import views.base.Paint; import views.base.UI; import views.map_widgets.Item_Sprite; import views.map_widgets.tools.Tool_Pan_Select; import views.map_widgets.tools.Tool_Route_Destination; import views.panel_base.Detail_Panel_Base; import views.panel_items.Panel_Item_Geofeature; import views.panel_routes.Panel_Item_Route; import views.panel_routes.Panel_Routes_Box; import views.panel_routes.Route_Details_Panel_Historic; import views.panel_routes.Route_Editor_UI; import views.panel_routes.Route_Stop; import views.panel_routes.Route_Stop_Editor; import views.panel_routes.Route_Viz; import views.panel_routes.Route_Viz_Diff_Map; public class Route extends Geofeature { // *** Class attributes protected static var log:Logging = Logging.get_logger('##Route'); // MAGIC_NUMBER: 160 is route z-level. // The client does not send z-level for routes since it's always the // same: 160. We might change this in the future, but for now this is // strictly the case. // SYNC_ME: pyserver/item/feat/route.py::route.Geofeature_Layer.Z_DEFAULT // flashclient/items/feats/Route.as::Route.z_level_always protected static const z_level_always:int = 160; // *** Mandatory attributes public static const class_item_type:String = 'route'; public static const class_gwis_abbrev:String = 'rt'; public static const class_item_type_id:int = Item_Type.ROUTE; // The Class of the details panel used to show info about this item. public static const dpanel_class_static:Class = Panel_Item_Route; // SYNC_ME: Search geofeature_layer table. public static const geofeature_layer_types:Array = [ Geofeature_Layer.ROUTE_DEFAULT, ]; // *** Other static attributes // A lookup of Route by stack_id public static var all:Dictionary = new Dictionary(); // FIXME: Diff Mode: Fix historic mode. protected static var history_detail_panel:Route_Details_Panel_Historic; protected static var tooltip:IToolTip; // tooltip display on mouse over // MAYBE: 2012.10.16: [lb]: Do these belong in a view class and not the // item (model) class? Or maybe the item manager class (so we can // avoid static vars in this class)? I can fix in CcpV2... // Feedback mode. public static const FB_OFF:int = 0; public static const FB_DRAGGING:int = 1; public static const FB_SELECTING:int = 2; // Feedback instance. public static const FB_NEW:int = 1; public static const FB_OLD:int = 2; // FIXME: These statics belong in Item_Manager or Find_Route_Manager. // // Originally-requested route (fresh from the route-finder). // Already evaluated routes. public static var evaluated:Array = new Array(); // Feedback highlighting and selecting. public static var highlighted_step:Route_Step = null; public static var selected_steps:Array = new Array(); // *** Instance variables // These are sent to and from the server. public var details:String; public var beg_addr:String; public var fin_addr:String; public var rsn_len:Number; //public var rsn_min:Number; //public var rsn_max:Number; //public var n_steps:Number; //public var beg_nid:Number; //public var fin_nid:Number; public var avg_cost:Number; public var stale_steps:int; public var stale_nodes:int; // This references Travel_Mode and represents the routed used to generate // the route (like, p1, p2, or p3, unlike Route_Step, where travel_mode // represents the mode of travel, like bike or bus). public var travel_mode:int; public var p1_priority:Number = NaN; public var p2_depart_at:String; public var p2_transit_pref:int; public var p3_weight_attr:String; public var p3_weight_type:String; public var p3_rating_pump:int; public var p3_burden_pump:int; public var p3_spalgorithm:String; public var tags_use_defaults:Boolean; // Not sent by server: source, z, host // Computed values. public var computed_length:Number; // meters (bicycle portion only) public var alternate_length:Number; public var total_time:Number; // seconds // If we just fetched a new route, it's considered unlibraried // until the user explicitly saves it. // MAYBE: The unlibraried bool probably belongs in a common base // class for gia-restricted type items. public var unlibraried:Boolean = false; // Route steps and directions will be null if the route is half-loaded/ // not hydrated. protected var rsteps_:Array; // We store lightweight Route_Stop_Editor objects in rstops. // Each route has at least two route stops: the origin and the // destination of the route. Users can also add extra route // stops. The heavierweight Route_Stop objects, in edit_stops, // manage the view and are what the user interacts with on the // map and in the route details panel. The rstops items, on the // other hand, store just data objects. We especially use them // with the Route_Path_Edit_Command to track edits to the route. public var rstops:Array; // An array of objects of the same type as the rstops array. // This array contains the position/name state of edit_stops from // when the last Route_Path_Edit_Command was performed public var last_cmd_stops:Array; // An array of Route_Stops used to populate the view of named or // important route stops. // 2014.06.27: The use of rstops and edit_stops and last_cmd_stops // is somewhat confusing. They're all collections of route_stops. // The rstops member is immutable. last_cmd_stops is used by // Route_Path_Edit_Command. And this.edit_stops is what the user // plays with. public var edit_stops:Array = new Array(); // If the user longpresses on the route and they haven't asked for // immediate route_stop editing, we'll start route_stop editing. // Not needed: we use tool_pan_select's longpress timer: // public var rstop_editing_enabler:Timer; public var rstop_editing_enabled:Boolean; protected var num_dests_:* = null; [Bindable] public var num_rstops_selected:int = 0; // A list of Route_Segment objects, each representing the route steps // between two adjacent route stops, used by Route_Path_Edit_Command // while updating path segments (i.e., after the user moves, removes, // or adds a route stop). public var updating_segments:Array; // When the byways of the road network are edited, they might invalidate // existing routes. If the server sees this, it can send the orignal // route as well as a newly computed route using the current road // network. public var alternate_steps:Array; public var alternate_xs:Array; public var alternate_ys:Array; public var directions:Array; // For route manip. public var alternate_directions:Array; // *** View-related attributes. // The Panel_Item_Route panel. public var route_panel_:Panel_Item_Route; // MAYBE: Replace master_route with item_stack.master_item... public var master_route:Route; // We want to draw routes that have active panels or whose // Route_List_Entry checkbox is selected. Since there could // be more than one Route_List, we track the selected state // of the checkbox here, in the Route, and each Route_List_Entry // adjusts its checkbox to match this bool. protected var filter_show_route_:Boolean = false; // We also track the Route_Lists to which this route belongs. When there // are no more Route_List associations and no more panel associations, we // can discard the route (if we so choose, otherwise we can just leave it // in memory; the latter is nice if you want to let users paginate route // lists and not discard routes when they leave a page). public var route_list_membership:Set_UUID = new Set_UUID(); // To avoid excessive coupling -- and possibly an import loop -- make // Panel_Routes_Library to us who to call. Otherwise, we'd have to // spaghetti it, e.g., G.app.routes_panel.routes_library.blah(). static public var looked_at_list_callback:Function = null; // The route could be, e.g., attached to a route panel, or a discussion // panel, or both. public var keep_showing_while_paneled:Set_UUID = new Set_UUID(); // This is used by route reactions to remember the route returned by the // server, since the user is allowed to edit the route. With other items, // the undo/redo command history can essentially revert an item to the // server state, and the user can also discard all edits and reload the // entire map. So route has it's own special way of reverting to its // server state. public var fresh_route:Route = null; // This is a collection of route stop labels. It used to be called // rstop_labels. It's just letters of the alphabet atop the route stop // circles (the "A", "B", "C", etc., labels). protected var rstop_labels:Array; // The path_arrows (the straight, dashed line that we draw when the user // is dragging a route stop around) are not editable or interactive, so // we use a regular Sprite and not an Item_Sprite. protected var path_arrows:Sprite; // For drawing a circle at the current route step. protected var current_dir_step_sprite:Sprite; protected var current_dir_step:Array; // The route stops are interactive, so make these Item_Sprites. // These are the colorful circles beneath the A, B, C, etc., labels. public var rstop_sprite:Item_Sprite; // This is the draggable route stop. protected var temporary_rstop:Item_Sprite; // Helpers for route manip. protected var tooltip_timer:Timer; protected var last_mouse_over:MouseEvent; protected var delight_on_mouse_out:Boolean; // Route Feedback Drag mode and instance. public var feedback_mode:int = Route.FB_OFF; public var feedback_instance:int = Route.FB_OFF; public var routes_viz:Route_Viz = null; public var landmarks_loaded:Boolean = false; public var show_landmarks:Boolean = false; // *** Constructor // public function Route(xml:XML=null, rev:utils.rev_spec.Base=null) { this.geofeature_layer_id = Geofeature_Layer.ROUTE_DEFAULT; this.z_level = Route.z_level_always; this.directions = new Array(); this.alternate_directions = new Array(); this.rstop_labels = new Array(); this.path_arrows = new Sprite(); this.current_dir_step_sprite = new Sprite(); // This is needed after gml_consume, before super(). this.rstop_sprite = new Item_Sprite(this); this.temporary_rstop = new Item_Sprite(this); this.routes_viz = Conf.route_vizs[0]; super(xml, rev); this.sprite.addChild(this.temporary_rstop); // Show a toolTip on the route if the user hovers over the geometry. if (Conf.route_path_tooltip_delay > 0) { this.tooltip_timer = new Timer(Conf.route_path_tooltip_delay, 1); this.tooltip_timer.addEventListener( TimerEvent.TIMER, this.on_tooltip_timer, false, 0, true); } } // *** // public static function redraw_all() :void { m4_TALKY('redraw_all: Route.all.len:', Route.all.length); for each (var route:Route in Route.all) { if (route.visible) { route.draw(); } } } // *** // public static function cleanup_all() :void { if (Conf_Instance.recursive_item_cleanup) { // NOTE: Geofeature also goes through it's all, so... this is // probably redundant. var sprite_idx:int = -1; // We'll reset Route.all so don't bother deleting from it. var skip_delete:Boolean = true; for each (var route:Route in Route.all) { route.item_cleanup(sprite_idx, skip_delete); } } // Route.all = new Dictionary(); } // override protected function clone_once(to_other:Record_Base) :void { var other:Route = (to_other as Route); super.clone_once(other); other.details = this.details; other.beg_addr = this.beg_addr; other.fin_addr = this.fin_addr; other.rsn_len = this.rsn_len; // Skipping/Not received from server: // rsn_min, rsn_max, n_steps, beg_nid, fin_nid other.avg_cost = this.avg_cost; m4_TALKY('clone_once: avg_cost:', other.avg_cost); other.stale_steps = this.stale_steps; other.stale_nodes = this.stale_nodes; other.travel_mode = this.travel_mode; other.p1_priority = this.p1_priority; other.p2_depart_at = this.p2_depart_at; other.p2_transit_pref = this.p2_transit_pref; other.p3_weight_attr = this.p3_weight_attr; other.p3_weight_type = this.p3_weight_type; other.p3_rating_pump = this.p3_rating_pump; other.p3_burden_pump = this.p3_burden_pump; other.p3_spalgorithm = this.p3_spalgorithm; other.tags_use_defaults = this.tags_use_defaults; // Not sent by server: tagprefs for when route was 1st requested. // Not sent by server: source, z, host other.computed_length = NaN; other.alternate_length = NaN; other.total_time = NaN; other.unlibraried = this.unlibraried; if (this.rsteps !== null) { other.rsteps = Collection.array_copy(this.rsteps); } //other.rstops = null; if (this.rstops !== null) { other.rstops = Collection.array_copy(this.rstops); } //other.rstops_sync(); other.edit_stops_set(Collection.array_copy(this.edit_stops)); if (this.last_cmd_stops !== null) { other.last_cmd_stops = Collection.array_copy(this.last_cmd_stops); } other.alternate_steps = null; other.alternate_xs = null; other.alternate_ys = null; // Skipping: rstop_editing_enabled // Skipping: updating_segments (used when user edits rte, adds stops) // Skipping: route_panel_ // Skipping: master_route // Skipping: filter_show_route_ // route_list_membership // looked_at_list_callback // keep_showing_while_paneled // Skipping: fresh_route // rstop_labels // path_arrows // current_dir_step_sprite // current_dir_step // rstop_sprite // temporary_rstop // tooltip_timer // delight_on_mouse_out // Skipping: other.feedback_mode = this.feedback_mode; // Skipping: other.feedback_instance = this.feedback_instance; // Skipping: routes_viz // show_landmarks } // override protected function clone_update( // on-op to_other:Record_Base, newbie:Boolean) :void { var other:Route = (to_other as Route); super.clone_update(other, newbie); if ((!other.computed_length) || (isNaN(other.computed_length))) { other.computed_length = this.computed_length; m4_TALKY('clone_update: computed_length:', other.computed_length); } if ((!other.alternate_length) || (isNaN(other.alternate_length))) { other.alternate_length = this.alternate_length; m4_TALKY2('clone_update: alternate_length:', other.alternate_length); } if ((!other.total_time) || (isNaN(other.total_time))) { other.total_time = this.total_time; m4_TALKY('clone_update: total_time:', other.total_time); } if ((other.rsteps === null) && (this.rsteps !== null)) { other.stale_steps = this.stale_steps; other.stale_nodes = this.stale_nodes; // STYLE GUIDE: ObjectUtil doesn't really work // var arr:Array = ObjectUtil.copy(other_arr) as Array; // for each (var cls:My_Class in arr) { ... } // TypeError: Error #1034: Type Coercion failed: // cannot convert Object@f39acd79 to my.project.My_Class. // for each (var o:Object in arr) { ... } // TypeError: Error #1009: Cannot access a property or method // of a null object reference. m4_TALKY2('clone_update: copying rsteps: len:', (this.rsteps !== null) ? this.rsteps.length : 'null'); other.rsteps = Collection.array_copy(this.rsteps); } if ((other.rstops === null) && (this.rstops !== null)) { m4_TALKY2('clone_update: copying rstops: len:', (this.rstops !== null) ? this.rstops.length : 'null'); other.rstops = new Array(); var rstop:Route_Stop_Editor; for each (rstop in this.rstops) { var other_stop:Route_Stop_Editor = new Route_Stop_Editor(); other_stop.name_ = rstop.name_; other_stop.node_id = rstop.node_id; m4_ASSERT_SOFT(other_stop.node_id > 0); // MAGIC_NUMBER: Use stop_version=1 for route stops that the // server sends so we can distinguish them from new // route stops that the user creates that are not yet // geocoded. other_stop.stop_version = 1; other_stop.x_map = rstop.x_map; other_stop.y_map = rstop.y_map; other_stop.is_endpoint = rstop.is_endpoint; other_stop.is_pass_through = rstop.is_pass_through; other_stop.is_transit_stop = rstop.is_transit_stop; other_stop.internal_system_id = rstop.internal_system_id; other_stop.external_result = rstop.external_result; other_stop.street_name_ = null; other_stop.editor = null; other.rstops.push(other_stop); } // Call rstops_sync and set: // other.last_cmd_stops // other.edit_stops other.rstops_sync(); } if ((other.alternate_steps === null) && (this.alternate_steps !== null)) { m4_TALKY2('clone_update: alternate_steps.len:', this.alternate_steps.length); other.alternate_steps = Collection.array_copy(this.alternate_steps); other.alternate_xs = Collection.array_copy(this.alternate_xs); other.alternate_ys = Collection.array_copy(this.alternate_ys); other.mark_route_panel_dirty(); } // We're called after lazy-loading the route, so make sure we update // the directions and whatnot. // NOTE: This sets: computed_length // alternate_length // total_time // directions // alternate_directions // EXPLAIN: But above, we just copied: // computed_length, alternate_length, total_time // and now we're recalculating? Should be fine... // I guess the recalculate only applies if rsteps // are loaded, so maybe the copy above is good for // routes that aren't fully hydrated. other.update_route_stats(); } // override public function gml_consume(gml:XML) :void { m4_TALKY('gml_consume: gml?:', (gml !== null)); super.gml_consume(gml); if (gml !== null) { if ((this.name_) && (gml.@name) && (this.name_ != gml.@name)) { m4_WARNING('!! name_:', this.name_, '/ gml.@name:', gml.@name); m4_ASSERT_SOFT(this.name_ == gml.@name); } // Base class consumes: name, ids, stealth_secret, etc. this.details = gml.@details; // The beg_addr and fin_addr are stored with the route so it's // easy to know the names of the endpoints, but if the route has // its route stops loaded, the names of the route stop endpoints // will be used instead, at least in the view. this.beg_addr = gml.@beg_addr; this.fin_addr = gml.@fin_addr; // Skipping: rsn_min, rsn_max, n_steps, beg_nid, fin_nid this.rsn_len = Number(gml.@rsn_len); this.avg_cost = Number(gml.@avg_cost); this.stale_steps = int(gml.@stale_steps); this.stale_nodes = int(gml.@stale_nodes); m4_TALKY2('gml_consume: stale_steps:', this.stale_steps, '/ stale_nodes:', stale_nodes); // Calculated below: computed_length, alternate_length, total_time this.travel_mode = int(gml.@travel_mode); m4_TALKY('gml_consume: travel_mode:', this.travel_mode); this.p1_priority = Number(gml.@p1_priority); this.p2_depart_at = gml.@p2_depart_at; this.p2_transit_pref = int(this.p2_transit_pref); this.p3_weight_attr = gml.@p3_weight_attr; this.p3_weight_type = gml.@p3_weight_type; this.p3_rating_pump = int(gml.@p3_rating_pump); this.p3_burden_pump = int(gml.@p3_burden_pump); this.p3_spalgorithm = gml.@p3_spalgorithm; this.tags_use_defaults = Boolean(int(gml.@tags_use_defaults)); // Not sent by server: tagprefs for when route was 1st requested. m4_TALKY7('gml_consume: p1_priority:', this.p1_priority, '/ p3_atr:', this.p3_weight_attr, '/ p3_wgt:', this.p3_weight_type, '/ p3_rat:', this.p3_rating_pump, '/ p3_bdn:', this.p3_burden_pump, '/ p3_alg:', this.p3_spalgorithm, '/ tags_use_defs:', this.tags_use_defaults); // Not sent by server: source, z, host m4_TALKY('gml_consume: access_infer_id:', this.access_infer_id); m4_TALKY('gml_consume: access_level_id:', this.access_level_id); // Not sent from server: unlibraried (we must deduce): if ((this.access_infer_id == Access_Infer.sessid_arbiter) && (this.access_level_id == Access_Level.arbiter)) { this.unlibraried = true; } // Consumed below: rsteps_ // Consumed below: rstops // Consumed below: alternate_steps, alternate_xs, alternate_ys // Consumed below: directions, alternate_directions m4_ASSERT_SOFT((this.z_level == 0) || (this.z_level == Route.z_level_always)); this.z_level = Route.z_level_always; // m4_VERBOSE('gml_consume: gml:', gml); // m4_VERBOSE('gml_consume: gml.step:', gml.step); // m4_VERBOSE('gml_consume: gml..step:', gml..step); // MAYBE: This should be renamed 'rstep' but android still uses // this name. if ('step' in gml) { this.rsteps = new Array(); this.compute_xys(gml.step, this.rsteps, this.xs, this.ys); m4_TALKY('gml_consume: num rsteps:', this.rsteps.length); if (this.rsteps.length == 0) { m4_WARNING('gml_consume: no rsteps:', gml.step); } } else { // Leave rsteps null to indicate this object is not a hydrated // route. m4_ASSURT(this.rsteps === null); } // BUG_JUL_2014: BUG nnnn: See route: // "molly quinn to Humphry terminal" // The duplicate road network problem (in the data) causes // a really, weird, super long, out of the way route to be // recalculated (repair route feature). This might be a data // problem (probably), or it might be a route planner problem // (less likely). // [lb] had a note that the route repair just repaired the 2nd // leg of the route (i.e., three route endpoints), but the 1st // leg was appropriately repaired... so maybe a server error? if ('alternate' in gml) { // Parse alternate geometry, too. This is sent when the road // network has changed and the byways that the old route // followed have changed. this.alternate_steps = new Array(); this.alternate_xs = new Array(); this.alternate_ys = new Array(); this.compute_xys(gml.alternate[0].step, this.alternate_steps, this.alternate_xs, this.alternate_ys); m4_TALKY2('gml_consume: num alternate_steps:', this.alternate_steps.length); } // MAYBE: Here and earlier, using 'step' and 'stop' and not 'rst?p' // MAYBE: This should be renamed 'rstop' but android still uses // this name. if ('waypoint' in gml) { this.rstops = this.compute_rstops(gml.waypoint); this.rstops_sync(); m4_TALKY('gml_consume: rstops.length:', this.rstops.length); if (this.rstops.length == 0) { m4_WARNING('gml_consume: no rstops:', gml.waypoint); } } this.update_route_stats(); m4_TALKY('gml_consume: this:', this); } } // override public function gml_produce() :XML { var gml:XML = super.gml_produce(); gml.setName(Route.class_item_type); // 'route' // Remove the xy string text that Geofeature adds since we don't // want that for the route (we give route steps instead). gml.setChildren(''); // Don't send: // beg_addr // fin_addr // rsn_len // //rsn_min // //rsn_max // //n_steps // //beg_nid // //fin_nid // avg_cost // stale_steps // stale_nodes // // These are sent by the gwis command, and apply to when the // // route was first created, so we don't send them when saving // // changes to a route: // travel_mode // p1_priority // p2_depart_at // p2_transit_pref // p3_weight_attr // p3_weight_type // p3_rating_pump // p3_burden_pump // p3_spalgorithm // tags_use_defaults // computed_length // alternate_length // total_time // FIXME/EXPLAIN: How does this make sense? Travel_Mode is fixed. gml.@travel_mode = this.travel_mode; gml.@details = this.details; // Skipping: unlibraried gml.@source = 'put_feature'; if (this.rsteps !== null) { var rstep_xml:XML; var rstep:Route_Step; for each (rstep in this.rsteps) { // MAYBE: This should be renamed 'rstep' but android still uses // this name. rstep_xml = <step step_name={rstep.step_name} travel_mode={rstep.travel_mode} beg_time={rstep.beg_time} fin_time={rstep.fin_time} />; rstep_xml.@forward = int(rstep.forward); if (rstep.travel_mode == Travel_Mode.bicycle) { rstep_xml.@byway_id = rstep.byway_system_id; rstep_xml.@byway_stack_id = rstep.byway_stack_id; rstep_xml.@byway_version = rstep.byway_version; } else { rstep_xml.appendChild( Geometry.coords_xys_to_string( this.xs.slice(rstep.beg_index, rstep.fin_index), this.ys.slice(rstep.beg_index, rstep.fin_index))); } gml.appendChild(rstep_xml); } } if (this.edit_stops !== null) { var rstop_xml:XML; var rstop_obj:Route_Stop; for each (rstop_obj in this.edit_stops) { // MAYBE: This should be renamed 'rstop' but android still uses // this name. rstop_xml = <waypoint node_id={rstop_obj.node_id} x={rstop_obj.x_map} y={rstop_obj.y_map} />; // Not sent: rstop_obj.stop_version // Not sent: rstop_obj.is_endpoint rstop_xml.@is_pass_through = int(rstop_obj.is_pass_through); rstop_xml.@is_transit_stop = int(rstop_obj.is_transit_stop); rstop_xml.@int_sid = rstop_obj.internal_system_id; rstop_xml.@ext_res = int(rstop_obj.external_result); // Skipping: street_name_ if (rstop_obj.name_ !== null) { rstop_xml.@name = rstop_obj.name_; } gml.appendChild(rstop_xml); } } // Skipping: the rest.... return gml; } // *** Base class overrides // override protected function get class_item_lookup() :Dictionary { return Route.all; } // public static function get_class_item_lookup() :Dictionary { return Route.all; } // override public function item_cleanup( i:int=-1, skip_delete:Boolean=false) :void { m4_TALKY('item_cleanup:', this); // We used to call: // G.map.routes_viewed.removeItemAt(this); // but we don't no more. // MAYBE: Should we check that we're not in a route_list or attached // to a panel still? if (i == -1) { try { i = (G.map.layers[this.zplus] as Map_Layer).getChildIndex( this.sprite); } catch (e:ArgumentError) { // Error #2025: The supplied DisplayObject must be a child of // the caller. // No-op } catch (e:TypeError) { // No-op } } var rs_label:Map_Label; for each (rs_label in this.rstop_labels) { if (rs_label.parent === G.map.route_labels) { m4_TALKY('item_cleanup: removing rs label:', rs_label); G.map.route_labels.removeChild(rs_label); } else { m4_TALKY2('item_cleanup: EXPLAIN: Why label missing?:', rs_label); m4_TALKY(' .. parent:', rs_label.parent); } } //?: this.rstop_labels = new Array(); try { m4_TALKY('item_cleanup: remove path_arrows from direction_arrows'); G.map.direction_arrows.removeChild(this.path_arrows); } catch (e:ArgumentError) { // No-op } try { G.map.vertices.removeChild(this.rstop_sprite); G.map.vertices.removeChild(this.current_dir_step_sprite); } catch (e:ArgumentError) { // No-op } m4_TALKY2('item_cleanup: rem on_mouse_over- on_mouse_out lstnrs:', this); this.sprite.removeEventListener(MouseEvent.MOUSE_OVER, this.on_mouse_over); this.sprite.removeEventListener(MouseEvent.MOUSE_OUT, this.on_mouse_out); if (this.tooltip_timer !== null) { this.tooltip_timer.removeEventListener( TimerEvent.TIMER, this.on_tooltip_timer); this.tooltip_timer = null; } // Remove self from base class lookup. if (!skip_delete) { delete Route.all[this.stack_id]; } super.item_cleanup(i, skip_delete); } // override public function get editable_at_current_zoom() :Boolean { return true; } // *** // public function disable_rstop_editing() :void { m4_DEBUG('disable_rstop_editing: rstop_editing_enabled=f:', this); this.rstop_editing_enabled = false; for each (var rt_stop:Route_Stop in this.edit_stops) { m4_DEBUG('disable_rstop_editing: rstop_selected=f:', rt_stop); if (rt_stop.rstop_selected) { rt_stop.rstop_selected = false; this.num_rstops_selected -= 1; } rt_stop.rstop_deselecting = false; rt_stop.draw(); if (G.map.tool_cur.dragged_object === rt_stop) { m4_DEBUG('disable_rstop_editing: dragged_object=null'); G.map.tool_cur.dragged_object = null; } } if (G.map.tool_is_active(Tool_Route_Destination)) { m4_DEBUG('disable_rstop_editing: cancel route destination tool'); G.map.tool_choose('tools_pan'); } this.num_rstops_selected = 0; this.mark_route_panel_dirty(); } // *** // // FIXME: Delete this someday. This fcn. rewritten for route manip, // but [lb] already found a few things missing so keeping this // fcn. for the time being. For one, this fcn. calls merge_stop... // so we should test whatever merge_stop resolves and then // delete the fcns., draw_DELETE_ME and merge_stop. /*/ public function draw_DELETE_ME(is_drawable:Object=null) :void { var i:int = 0; var x:Number; var y:Number; var step:Route_Step; var gr:Graphics = this.sprite.graphics; var startx:Number = G.map.xform_x_map2cv(this.xs[0]); var starty:Number = G.map.xform_y_map2cv(this.ys[0]); var endx:Number = G.map.xform_x_map2cv(this.xs[this.xs.length - 1]); var endy:Number = G.map.xform_y_map2cv(this.ys[this.ys.length - 1]); super.draw(); gr.clear(); // remove old map rstop_labels if (this.rstop_labels !== null) { for (i = 0; i < this.rstop_labels.length; i++) { if (this.rstop_labels[i] !== null) { this.sprite.removeChild(this.rstop_labels[i]); } } this.rstop_labels = null; } // remove old transit stops, start/end markers if (this.rstops !== null) { for (i = 0; i < this.rstops.length; i++) { this.sprite.removeChild(this.rstops[i]); } this.rstops = null; } if (this.selected) { // blue selection outline Paint.line_draw(gr, this.xs, this.ys, this.draw_width + 4, Conf.selection_color); // use route viz to render the route G.user.route_viz.route_line_render(this, this.rsteps); } else { // render the route normally Paint.line_draw(gr, this.xs, this.ys, this.draw_width, Conf.route_color); } // workaround for weird flash bug // flash would fill the last line segment with green gr.moveTo(startx, starty); // FIXME: Probably put following in new fcn. // Find and place labels and route stop markers. var rstops:Array = new Array(); // {rsteps: [...], x:, y:} var transit_label_txt:String; var transit_label_type:String; var tx:Number; var ty:Number; var j:int; this.rstops = new Array(); this.rstop_labels = new Array(); this.merge_stop(this.rsteps[0], startx, starty, rstops); for (i = 0; i < this.rsteps.length; i++) { step = this.rsteps[i]; if ((step.transit_type == 'board_bus') || (step.transit_type == 'board_train') || (step.transit_type == 'alight_bus') || (step.transit_type == 'alight_train')) { if ((step.forward && (step.transit_type == 'alight_bus' || step.transit_type == 'alight_train')) || (!step.forward && (step.transit_type == 'board_bus' || step.transit_type == 'board_train'))) { tx = G.map.xform_x_map2cv(this.xs[step.fin_index - 1]); ty = G.map.xform_y_map2cv(this.ys[step.fin_index - 1]); } else { tx = G.map.xform_x_map2cv(this.xs[step.beg_index]); ty = G.map.xform_y_map2cv(this.ys[step.beg_index]); } this.merge_stop(step, tx, ty, rstops); } } this.merge_stop(this.rsteps[this.rsteps.length - 1], endx, endy, rstops); // Create labels and route stops for these points. for (i = 0; i < rstops.length; i++) { transit_label_txt = ''; transit_label_type = null; for (j = 0; j < rstops[i].rsteps.length; j++) { step = rstops[i].rsteps[j]; if (j > 0) { transit_label_txt += ', '; } if (i == 0 && j == 0) { // special case for first stop transit_label_txt += 'Start'; transit_label_type = null; } else if ((i == rstops.length - 1 ) && (j == rstops[i].rsteps.length - 1)) { // special case for last stop transit_label_txt += 'End'; transit_label_type = null; } else if (step.transit_type == 'board_bus' || step.transit_type == 'alight_bus') { if (transit_label_type != 'bus') { transit_label_txt += 'Bus '; } transit_label_txt += step.transit_name; transit_label_type = 'bus'; } else { if (transit_label_type != 'train') { transit_label_txt += 'Train '; } transit_label_txt += step.transit_name; transit_label_type = 'train'; } } this.rstops.push(new Transit_Stop(rstops[i].rsteps, i == 0, i == rstops.length - 1, rstops[i].x, rstops[i].y)); this.rstop_labels.push(new Map_Label(transit_label_txt, 15, 0, rstops[i].x - 2, rstops[i].y - 24)); } // place all labels and rstops in the map for (i = 0; i < this.rstops.length; i++) { this.sprite.addChild(this.rstops[i]); this.sprite.addChild(this.rstop_labels[i]); } } /*/ // override public function draw(is_drawable:Object=null) :void { var drawable:Boolean; if (is_drawable !== null) { drawable = (is_drawable as Boolean); } else { drawable = this.is_drawable; } m4_TALKY2('draw: sel?:', this.selected, '/ drawable:', drawable, this); // MAYBE: Care about this.master_route.route_panel_? var conflict_old_sel:Boolean = ( (this.route_panel_ !== null) && (this.route_panel_.tab_route_details !== null) && (this.route_panel_.tab_route_details.conflict_old !== null) && (this.route_panel_.tab_route_details.conflict_old.selected)); var conflict_new_sel:Boolean = ( (this.route_panel_ !== null) && (this.route_panel_.tab_route_details !== null) && (this.route_panel_.tab_route_details.conflict_new !== null) && (this.route_panel_.tab_route_details.conflict_new.selected)); var conflict_diff_sel:Boolean = ( (this.route_panel_ === null) || (this.route_panel_.tab_route_details === null) || (this.route_panel_.tab_route_details.conflict_diff === null) || (this.route_panel_.tab_route_details.conflict_diff.selected)); var show_primary:Boolean = ( (this.alternate_steps === null) || conflict_old_sel || conflict_diff_sel || !this.rev_is_working); var show_alternate:Boolean = ( (this.alternate_steps !== null) && (this.rev_is_working) && (conflict_new_sel || conflict_diff_sel)); // Must show at least one version (maybe two) m4_ASSERT(show_primary || show_alternate); //m4_TALKY('draw: this.route_panel_:', this.route_panel_); //m4_TALKY('draw: this.master_route:', this.master_route); //m4_TALKY('draw: is_drawable:', is_drawable); //m4_TALKY('draw: this.visible:', this.visible); //m4_TALKY('draw: this.sprite.visible:', this.sprite.visible); super.draw(); this.sprite.graphics.clear(); // Remove old source and destination map labels. for each (var rs_label:Map_Label in this.rstop_labels) { if (rs_label.parent === G.map.route_labels) { m4_TALKY('draw: remove map rs label:', rs_label); G.map.route_labels.removeChild(rs_label); } // We're called from geofeatures_redraw_and_relabel for // new objects, so we may have never been labeled before. // else { // m4_TALKY('draw: EXPLAIN: Why is label missing?:', label); // m4_TALKY(' .. parent:', label.parent); // } } m4_TALKY('draw: reset map rs labels:', this.rstop_labels.length); this.rstop_labels = new Array(); // Cleanup this.rstop_sprite. for (var i:int = this.rstop_sprite.numChildren - 1; i >= 0; i--) { this.rstop_sprite.removeChildAt(i); } this.current_dir_step_sprite.graphics.clear(); if ((this.is_drawable) && (this.visible)) { this.draw_finally(show_primary, show_alternate); } else { ////this.label_reset(); //this.label.visible = false; } } // public function draw_finally(show_primary:Boolean, show_alternate:Boolean) :void { var gr:Graphics = this.sprite.graphics; var nongeo:Boolean = ( (this.is_vgroup_new || this.is_vgroup_old) && (this.counterpart !== null) && (this.digest_nongeo != this.counterpart.digest_nongeo)); var selected_highlighted:Boolean = this.selected || this.highlighted; m4_TALKY2('draw_finally: selected_highlighted:', selected_highlighted); // At higher zooms, make sure users can see the map beneath. var settings_alpha:Number = G.tabs.settings.settings_panel .settings_options.route_transparency_slider.value; if (!G.map.zoom_is_vector()) { // Note that using line_draw's alpha doesn't work; rather, // set the sprite alpha. if (settings_alpha == 1.0) { this.sprite.alpha = 0.45; } else { this.sprite.alpha = settings_alpha; } } else { //this.sprite.alpha = 1.0; this.sprite.alpha = settings_alpha; } // Route Line Outline if (selected_highlighted && (this.feedback_mode == Route.FB_OFF)) { // Regular mode route selection outline. if (show_primary) { m4_TALKY('draw_finally: rt oline: line_draw: primary'); Paint.line_draw(gr, this.xs, this.ys, this.draw_width + 4, Conf.selection_color); } if (show_alternate) { m4_TALKY('draw_finally: rt oline: line_draw: alternate'); Paint.line_draw(gr, this.alternate_xs, this.alternate_ys, this.draw_width + 4, Conf.selection_color); } } else if (this.feedback_mode != Route.FB_OFF) { // Feedback mode route line outline. m4_TALKY('draw_finally: rt feedback oline: line_draw'); Paint.line_draw(gr, this.xs, this.ys, this.draw_width + 4, ((this.feedback_instance == Route.FB_OLD) ? Conf.route_feedback_old_outline : Conf.route_feedback_new_outline)); } else if (nongeo) { // Historic mode: green highlight for nongeometric changes. m4_TALKY('draw_finally: rt historic green highlight: line_draw'); m4_ASSERT(show_primary && !show_alternate); Paint.line_draw(gr, this.xs, this.ys, this.draw_width + 4, Conf.change_color); } // Route Line. if ((G.map.rmode == Conf.map_mode_feedback) && (this.feedback_instance == Route.FB_OLD)) { // Route Feedback: Old route. m4_TALKY('draw_finally: rt feedback: old route: line_draw'); Paint.line_draw(gr, this.xs, this.ys, this.draw_width, Conf.route_feedback_old_color); } else if (show_alternate && show_primary) { // m4_TALKY('draw: show_alternate && show_primary'); // do a route-step comparison between current and alternate m4_TALKY('draw_finally: rt alternate diffs'); m4_ASSERT(!this.rev_is_diffing); this.draw_alternate_diff(gr, this.rsteps, this.alternate_steps, this.xs, this.ys, Conf.vgroup_move_old_color, true); this.draw_alternate_diff(gr, this.alternate_steps, this.rsteps, this.alternate_xs, this.alternate_ys, Conf.vgroup_move_new_color, false); } else if (this.rev_is_working && selected_highlighted) { // m4_TALKY('draw: rev_is_working/current && selected'); // Use route visualization to render the route. // FIXME: Correct re-use of is_path_editable? m4_TALKY('draw_finally: rt selected: highlighted: working rev.'); this.draw_pri_or_alt( show_primary, show_alternate, this.is_path_editable()); } else if (this.rev_is_diffing) { m4_ASSERT(show_primary && !show_alternate); if (this.counterpart === null) { // either a deleted or new route m4_TALKY('draw_finally: rt: rev_is_diffing: no counterpart'); Paint.line_draw(gr, this.xs, this.ys, this.draw_width, (this.is_vgroup_old ? Conf.vgroup_old_color : Conf.vgroup_new_color)); } else { // do a route-step level geometry comparison and render it m4_TALKY('draw_finally: rt: rev_is_diffing: counterpart diff'); this.draw_geometry_diff(); } } else { // Unselected or historic route view. m4_TALKY('draw_finally: rt: unselected or historic'); this.draw_pri_or_alt( show_primary, show_alternate, /*editable=*/false); } // Restore selections, if needed (feedback mode only). if (this.feedback_mode == Route.FB_SELECTING) { for each (var step:Route_Step in Route.selected_steps) { if (this.rsteps.indexOf(step) >= 0) this.rs_select(step, true); } } // workaround for weird flash bug // flash would fill the last line segment with green var sx:Number; var sy:Number; gr.moveTo(sx, sy); // draw the rstops and add labels var letter:int = 0; var places:int = 1; var lettering:String; for (var i:int = 0; i < this.edit_stops.length; i++) { if (!this.edit_stops[i].is_stop_valid) { // Remove route stop with no x,y from the map. m4_TALKY2('draw_finally: i:', i, '/ !edit_stop.is_stop_valid:', this.edit_stops[i]); if (this.edit_stops[i].parent !== null) { this.rstop_sprite.removeChild(this.edit_stops[i]); } continue; } else if (this.edit_stops[i].parent === null) { // The route stop was not valid but now it's valid, so add it. m4_TALKY2('draw_finally: i:', i, '/ edit_stop.is_stop_valid:', this.edit_stops[i]); this.rstop_sprite.addChild(this.edit_stops[i]); } // else, the route stop is already setup, and we're its parent. sx = this.edit_stops[i].x_cv; sy = this.edit_stops[i].y_cv; if (selected_highlighted) { m4_TALKY2('draw_finally: i:', i, '/ rstop_selected:', this.edit_stops[i]); // No: this.edit_stops[i].rstop_selected = true; // otherwise you draw _all_ route stops highlighted. this.edit_stops[i].draw(); } else { m4_TALKY2('draw_finally: i:', i, '/ rstop_selected=f:', this.edit_stops[i]); if (this.edit_stops[i].rstop_selected) { this.edit_stops[i].rstop_selected = false; this.num_rstops_selected -= 1; } if (this.edit_stops[i].graphics !== null) { // Remove the old route stop circle. m4_TALKY2('draw_finally: i:', i, '/ clearing edit_stop:', this.edit_stops[i]); this.edit_stops[i].graphics.clear(); } if ((this.edit_stops[i].is_endpoint) || (!this.edit_stops[i].is_pass_through)) { m4_TALKY3('draw_finally: i:', i, '/ !is_pass_thru or is_endpt:', this.edit_stops[i]); this.draw_circle(this.edit_stops[i].color, sx, sy, 6); } } if (((this.edit_stops[i].is_endpoint) || (!this.edit_stops[i].is_pass_through)) && (selected_highlighted)) { // Label the route stop with a letter, or letters, if there // are more than 26 stops. We just start repeating the same // letter in the latter case, but I doubt this case has ever // been tested. // E.g., 'A', 'B', ..., 'Z', 'AA', 'BB', ... lettering = ''; for (var col_num:int = 1; col_num <= places; col_num++) { lettering += Strutil.letters_uc[letter]; } m4_TALKY2('draw_finally: i', i, 'nlttr', letter, 'nplcs', places, 'alttr', lettering, '/', this.edit_stops[i]); var rs_label:Map_Label; rs_label = new Map_Label(lettering, /*size=*/12, /*rotation=*/0, sx - 2, sy - 0, this); m4_TALKY('draw_finally: adding rs label:', rs_label); this.rstop_labels.push(rs_label); G.map.route_labels.addChild(rs_label); // The next time we label a route_stop, use the next letter // in the alphabet. letter++; if (letter >= Strutil.letters_uc.length) { letter = 0; places += 1; } } } // end: for (var i:int = 0; i < this.edit_stops.length; i++) this.rstop_sprite.visible = selected_highlighted; // [lb] is not quite sure about including this one: m4_TALKY('draw_finally: path_arrows.visible:', selected_highlighted); this.path_arrows.visible = selected_highlighted; if (this.current_dir_step !== null) { this.current_dir_step_sprite.graphics.clear(); this.current_dir_step_sprite.graphics.lineStyle(2, 0x000000); this.current_dir_step_sprite.graphics.beginFill(0xffff00); this.current_dir_step_sprite.graphics.drawCircle( G.map.xform_x_map2cv(this.current_dir_step[0]), G.map.xform_y_map2cv(this.current_dir_step[1]), 6); this.current_dir_step_sprite.graphics.endFill(); } } // protected function draw_pri_or_alt( show_primary:Boolean, show_alternate:Boolean, editable:Boolean) :void { m4_TALKY3('draw_pri_or_alt: show_pri?:', show_primary, '/ show_alt?:', show_alternate, '/ editable?:', editable); if (editable) { if (show_primary) { this.draw_edit_mode(this.rsteps); } else if (show_alternate) { this.draw_edit_mode(this.alternate_steps); } } else { m4_TALKY('draw_finally: path_arrows.graphics.clear'); this.path_arrows.graphics.clear(); //m4_TALKY6('draw_pri_or_alt: xs.len:', this.xs.length, // '/ ys.len:', this.ys.length, // '/ rsteps.len:', (this.rsteps !== null) // ? this.rsteps.length : 'null', // '/ show_primary:', show_primary, // '/ show_alternate:', show_alternate); //m4_TALKY('draw_pri_or_alt: this:', this); if (show_primary) { // Instead of the boring old solid light blue line, which is // also the default route line ornamentation, use whatever the // user chose from the Visualization dropdown. // // Boring: // var gr:Graphics = this.sprite.graphics; // Paint.line_draw(gr, this.xs, this.ys, // this.draw_width, Conf.route_color); // // More Interestinger: if (this.rsteps !== null) { this.routes_viz.route_line_render( this, this.rsteps, /*alternate=*/false); } } else if (show_alternate) { // Boring: // Paint.line_draw(gr, this.alternate_xs, this.alternate_ys, // this.draw_width, Conf.route_color); // The new haute: if (this.alternate_steps !== null) { this.route_panel.route_viz.route_line_render( this, this.alternate_steps, /*alternate=*/true); } } else { m4_TALKY('draw_pri_or_alt: skipping route_line_render:', this); } } } // override public function init_item(item_agg:Aggregator_Base, soft_add:Boolean=false) :Item_Versioned { var updated_item:Item_Versioned = super.init_item(item_agg, soft_add); if (updated_item === null) { m4_TALKY('item_cleanup: add path_arrows to direction_arrows'); G.map.direction_arrows.addChild(this.path_arrows); G.map.vertices.addChild(this.rstop_sprite); G.map.vertices.addChild(this.current_dir_step_sprite); // NOTE: Map_Controller has its own handlers. We make sure to // coordinate our behavior, so we don't accidentally do // two things when the user is only expecting one. m4_TALKY('init: add on_mouse_over- on_mouse_out listnrs:', this); if (this.master_item === null) { this.sprite.addEventListener(MouseEvent.MOUSE_OVER, this.on_mouse_over, false, 0, true); this.sprite.addEventListener(MouseEvent.MOUSE_OUT, this.on_mouse_out, false, 0, true); } } // else, we cloned to an existing item, so don't bother with sprites. return updated_item; } // override public function set deleted(d:Boolean) :void { super.deleted = d; } // override protected function init_add(item_agg:Aggregator_Base, soft_add:Boolean=false) :void { m4_TALKY('init_add: this:', this); super.init_add(item_agg, soft_add); if (!soft_add) { if (this !== Route.all[this.stack_id]) { if (this.stack_id in Route.all) { m4_WARNING('init_add: overwrite:', Route.all[this.stack_id]); m4_WARNING(' with:', this); m4_WARNING(Introspect.stack_trace()); } Route.all[this.stack_id] = this; } } else { var master_route:Route = Route.all[this.stack_id]; if (master_route !== null) { this.master_route = master_route; m4_DEBUG('init_add: master_route: set:', this); } else{ m4_WARNING('init_add: master_route: none?', this); } } } // override protected function init_update( existing:Item_Versioned, item_agg:Aggregator_Base) :Item_Versioned { m4_TALKY('init_update: this:', this); var route:Route = Route.all[this.stack_id]; if (route !== null) { m4_VERBOSE(' >> existing:', existing); m4_VERBOSE(' >> route:', route); m4_ASSERT((existing === null) || (existing === route)); // If the local item is hydrated, only update if the server item // is also hydrated, so that we don't overwrite the item when just // updating a Route_List. // FIXME_2013_06_11: Check that clone() calls clone_update() and all's good. // if ((!route.hydrated) || (this.hydrated)) { // this.clone_item(route); // /* // super.init_update(route, item_agg); // // // This is cheating... kind of. Why duplicate code? // this.clone_item(route); // */ // } // else { // m4_TALKY('init_update: not updating: rt:', existing); // } // this.clone_update(route, /*newbie=*/false); this.clone_item(route); } else { m4_WARNING('Route not found: stack_id:', this.stack_id); m4_ASSERT_SOFT(false); } return route; } // override protected function is_item_loaded(item_agg:Aggregator_Base) :Boolean { var is_loaded:Boolean = (super.is_item_loaded(item_agg) || (this.stack_id in Route.all)); m4_TALKY('is_item_loaded: is_loaded:', is_loaded, '/ this:', this); return is_loaded; } // override public function get is_revisionless() :Boolean { return true; } // override public function label_draw(halo_color:*=null) :void { m4_TALKY('label_draw'); m4_ASSERT(halo_color === null); halo_color = Conf.label_halo_route; // The base class adds a new Map_Label, for the the route name_, // and not for the route stops. super.label_draw(halo_color); } // override public function label_reset() :void { // If you're having problems with route labels, either the name_ label // or the route stop letter labels, it's easier to debug them in this // Class, rather than mucking around in Geofeature. [lb] was having a // problem with route labels being removed, but that problem was label // conflicts with byways. The problem was solved in that collides fcn. m4_TALKY('label_reset'); super.label_reset(); } // override public function get use_ornament_selection() :Boolean { return false; } // override public function vertices_redraw() :void { // EXPLAIN: This a no-op for routes, right? m4_TALKY2('vertices_redraw: vertices.len:', (this.vertices !== null) ? this.vertices.length : 'null'); super.vertices_redraw(); } // *** Developer methods // 2013.09.05: [lb] used getUID to figure out why deep links were // using the wrong route object (the new one from GWIS // and not the one that's already loaded). // override public function toString() :String { return (super.toString() + ' / ' + ((this.rsteps_ !== null) ? String(this.rsteps_.length) : 'empty') + ' steps' + ', ' + ((this.rstops !== null) ? String(this.rstops.length) : 'empty') + ' stops' //+ ' / details: ' + (this.details) //+ ' / beg_addr: ' + (this.beg_addr) //+ ' / fin_addr: ' + (this.fin_addr) //+ ' / rsn_len: ' + (this.rsn_len) //+ ' / computed_length: ' + (this.computed_length) //+ ' / alternate_length: ' + (this.alternate_length) //+ ' / total_time: ' + (this.total_time) + ' / fShw?: ' + (this.filter_show_route_) + ', lib?: ' + (!this.unlibraried) + ', avgc: ' + String(this.avg_cost) + ', stalee: ' + String(this.stale_steps) + ', stalen: ' + String(this.stale_nodes) + ' / ' + ((this.route_panel_ !== null) ? this.route_panel_.toString_Terse() : 'no panel') + ' / ' + ((this.master_route !== null) ? this.master_route.toString_Terse() : 'no master rte') ); } // override public function toString_Terse() :String { return (super.toString_Terse() + ((this.filter_show_route_) ? ' fShowRte' : '') + ' ' + ((this.route_panel_ !== null) ? this.route_panel_.toString_Terse() : 'panelless') + ' ' + ((this.master_route !== null) ? this.master_route.toString_Terse() : 'nomastrrte') ); } // override public function toString_Verbose() :String { return (super.toString_Verbose() + ' / nsteps: ' + ((this.rsteps_ !== null) ? String(this.rsteps_.length) : 'null') + ' / nstops: ' + ((this.rstops !== null) ? String(this.rstops.length) : 'null') //+ ' / details: ' + (this.details) //+ ' / beg_addr: ' + (this.beg_addr) //+ ' / fin_addr: ' + (this.fin_addr) //+ ' / rsn_len: ' + (this.rsn_len) //+ ' / computed_length: ' + (this.computed_length) //+ ' / alternate_length: ' + (this.alternate_length) //+ ' / total_time: ' + (this.total_time) + ' / fltr_show: ' + (this.filter_show_route_) + ' / lib: ' + (!this.unlibraried) + ' / avgc: ' + String(this.avg_cost) + ' / stlstps: ' + String(this.stale_steps) + ' / stlnds: ' + String(this.stale_nodes) + ' / pnl: ' + ((this.route_panel_ !== null) ? this.route_panel_.class_name_tail : 'null') + ' / mrt: ' + ((this.master_route !== null) ? this.master_route.toString_Terse() : 'null') //+ ' / uuid: ' + UIDUtil.getUID(this) + ' / ' + UIDUtil.getUID(this) ); } // public function toString_Plops() :String { var verbose:String = ( //this.toString_Terse() + //super.toString_Terse() + ' / tvl_mod: ' + (this.travel_mode) + ' / p1_pri: ' + (this.p1_priority) + ' / p2_dep: ' + (this.p2_depart_at) + ' / p2_txp: ' + (this.p2_transit_pref) + ' / p3_attr: ' + (this.p3_weight_attr) + ' / p3_type: ' + (this.p3_weight_type) + ' / p3_rating: ' + (this.p3_rating_pump) + ' / p3_burden: ' + (this.p3_burden_pump) + ' / p3_spalg: ' + (this.p3_spalgorithm) + ' / tags_defs: ' + (this.tags_use_defaults) ); return verbose; } // *** Instance methods // protected function compute_len_and_ids() :void { var step:Route_Step; // FIXME: delete this? and just use rsn_len? this.computed_length = Number(0); // Note that length is only accumulated for biking, alternate // modes of transportation are not summed. for each (step in this.rsteps) { if (step.travel_mode == Travel_Mode.bicycle) { this.computed_length += step.step_length; } } this.alternate_length = Number(0); if (this.alternate_steps !== null) { for each (step in this.alternate_steps) { if (step.travel_mode == Travel_Mode.bicycle) { this.alternate_length += step.step_length; } } } m4_TALKY4('compute_len_and_ids:', 'computed_length:', this.computed_length, '/ alternate:', this.alternate_length, '/ rsn_len', this.rsn_len); } // protected function compute_rstops(xml:XMLList) :Array { var result:Array = new Array(); var name:String; var stop_xml:XML; for each (stop_xml in xml) { if ('@name' in stop_xml) { name = stop_xml.@name; } else { name = null; } var rstope:Route_Stop_Editor = new Route_Stop_Editor(); rstope.name_ = name; rstope.node_id = int(stop_xml.@node_id); m4_ASSERT_SOFT(rstope.node_id > 0); // MAGIC_NUMBER: User version=1 for real route stops. rstope.stop_version = 1; rstope.x_map = Number(stop_xml.@x); rstope.y_map = Number(stop_xml.@y); // Skipping: is_endpoint rstope.is_pass_through = Boolean(int(stop_xml.@is_pass_through)); rstope.is_transit_stop = Boolean(int(stop_xml.@is_transit_stop)); rstope.internal_system_id = int(stop_xml.@int_sid); rstope.external_result = Boolean(int(stop_xml.@ext_res)); // Skipping: street_name_ rstope.editor = null; result.push(rstope); m4_VERBOSE('compute_rstops: stop_xml.node_id:', stop_xml.@node_id); } return result; } // public function compute_smart_name() :void { var step:Route_Step; var max_len:int = 0; var step_names:Dictionary = new Dictionary(); var smart_name:String = null; var step_name:String; // Do only for routes not in library. if (!this.can_view) { // Build step name dictionary. for each (step in this.rsteps) { if (!(step.step_name in step_names)) { step_names[step.step_name] = 0; } step_names[step.step_name] += step.step_length; } // Find longest step. for (step_name in step_names) { if (step_names[step_name] > max_len) { max_len = step_names[step_name]; smart_name = step_name; } } this.name_ = 'Route via ' + smart_name; } // else... we'll use the name saved in the database, or the local // item's name. } // protected function compute_step_dir(step:Route_Step, leaving_step:Boolean, xs:Array, ys:Array) :Array { var start_at_zero:Boolean = !leaving_step; var i:int = (start_at_zero ? step.beg_index : step.fin_index - 1); var dir:int = (start_at_zero ? 1 : -1); var mul:Number = (leaving_step ? 1 : -1); var vec_len:Number = 0; var result:Array = [xs[i], ys[i],]; // 2014?: BUGMAYBE: I [lb] opened a bunch of routes, was later on the // Routes panel, then click side panels' 'x'es to close panels // not active, and null object reference // update_route_stats: Route:1569236.6$ "Roseville-TheDepot" // fShowRte Panel_Item_Route6877 1 selected //m4_VERBOSE('compute_step_dir: result:', result); while (vec_len < Conf.route_step_dir_length) { vec_len += Geometry.distance((xs[i] - xs[i + dir]) * mul, (ys[i] - ys[i + dir]) * mul, 0, 0); i += dir; if (step.is_endpoint(i)) { break; } } result[0] = (result[0] - xs[i]) * mul; result[1] = (result[1] - ys[i]) * mul; return result; } // protected function compute_xys(xml:XMLList, rsteps:Array, xs:Array, ys:Array) :void { var i:int; var step_xml:XML; var prev_step:Route_Step = null; var step:Route_Step; var step_xs:Array; var step_ys:Array; for each (step_xml in xml) { step = new Route_Step(step_xml); rsteps.push(step); step_xs = new Array(); step_ys = new Array(); step.beg_index = xs.length; Geometry.coords_string_to_xys(step_xml.text(), step_xs, step_ys); if (!step.forward) { step_xs.reverse(); step_ys.reverse(); } for (i = 0; i < step_xs.length; i++) { // Don't push 1st coord of intermediate steps. if (i == 0 && (prev_step !== null)) { step.beg_index--; continue; } xs.push(step_xs[i]); ys.push(step_ys[i]); } step.fin_index = xs.length; // FIXME: This was missing from route manip. Make sure this works. prev_step = step; } } // Rebuilds the direction rsteps array protected function directions_build(rsteps:Array, xs:Array, ys:Array) :Array { ////m4_VERBOSE('directions_build: xs:', xs, '/ ys:', ys); var step:Route_Step; var dir_step:Direction_Step; var landmarks:Array = null; var n_v:Array = [NaN, NaN,]; // [nx, ny,] var p_v:Array = [NaN, NaN,]; // [px, py,] var classify:int; var dirs:Array = new Array(); // Tracking the number of route_stops, but skip the first one (so // start the index at 1). var stop_num:int = 1; var stop_name:String; var stop_type:int; var num_transit_stops:int = 0; // Keep track of board/alight stops. var step_num:int = 1; var rstep_i:int; //?: this.landmarks_loaded = false; for (rstep_i = 0; rstep_i < rsteps.length; rstep_i++) { step = rsteps[rstep_i]; m4_ASSERT(step !== null); m4_VERBOSE(' .. dir_build: step:', step); // Compute the direction vector for the start of the current step. // MAYBE: We do this for every step. Is this really necessary? n_v = this.compute_step_dir(step, false, xs, ys); classify = G.angle_class_idx(n_v[0], n_v[1]); m4_VERBOSE(' .. dir_build: n_v:', n_v[0], n_v[1]); // We consider a step to be the same if it has the same name, // AND (its going in the same direction OR its relative angle // is too large). if (dirs.length == 0) { // The very first step, so it has a special relative class. // FIXME: Does step.travel_mode matter? // What if this is a transit stop? (Or is that not // possible?) dir_step = new Direction_Step( Conf.bearing.length - 2, classify, step.step_length, step.step_name, 0, // stop_type=0 is non multimodal step.beg_time, step.fin_time, null, [this.xs[step.beg_index], this.ys[step.beg_index],], null, this, rstep_i, /*route_caller=*/'directions_build-no_dirs') dirs.push(dir_step); dirs[dirs.length - 1].geofeature_layer_id = step.byway_geofeature_layer_id; //m4_VERBOSE(' .. dir_build: first step:', dir_step.text); } else if (step.travel_mode == Travel_Mode.bicycle) { // Don't include transit mode steps in the directions ////m4_VERBOSE(' .. dir_build: bike step: p_v:', p_v); ////m4_VERBOSE(' .. dir_build: bike step: n_v:', n_v); //m4_ASSERT((p_v[0] != 0) || (p_v[1] != 0)); var rel_angle:Number; rel_angle = Geometry.ang_rel(p_v[0], p_v[1], n_v[0], n_v[1]); if (!Strutil.equals_ignore_case(step.step_name, dirs[dirs.length - 1].name) || ((step.step_name == '') && (step.byway_geofeature_layer_id != dirs[dirs.length - 1].geofeature_layer_id)) || ((Math.abs(rel_angle - 90) > Conf.dir_merge_angle) && (step.step_length > Conf.dir_merge_length)) || dirs[dirs.length - 1].is_route_stop) { // get the relative angle between the direction we were // traveling and the landmark if (landmarks !== null) { for each (l in landmarks) { if (l.xs !== null) { for (var i:int=0; i<l.xs.length; i++) { // calculate angle var landmark_angle:Number = 0; l.angles.push(Geometry.ang_rel( p_v[0], p_v[1], l.xs[i] - this.xs[step.beg_index], l.ys[i] - this.ys[step.beg_index])); } } } } dir_step = new Direction_Step( G.angle_class_id(rel_angle), classify, step.step_length, step.step_name, 0, // stop_type=0 is non multimodal step.beg_time, step.fin_time, dirs[dirs.length - 1], [this.xs[step.beg_index], this.ys[step.beg_index],], landmarks, this, rstep_i, /*route_caller=*/'directions_build-by_bike'); dirs.push(dir_step); //m4_VERBOSE2(' .. dir_build: stop_num:', stop_num, // '/', dir_step.text); } else { // If part of the same step, add to the dist/time of previous ////m4_VERBOSE(' .. dir_build: other step'); dirs[dirs.length - 1].rel_distance += step.step_length; dirs[dirs.length - 1].fin_time = step.fin_time; } dirs[dirs.length - 1].geofeature_layer_id = step.byway_geofeature_layer_id; //m4_VERBOSE3(' .. dir_build: bike step:', dir_step.text, // '/ rt.stack_id:', this.stack_id, // '/ step_num:', step_num); step_num += 1; } // Check if we've reached a route stop. var found_rstop:Boolean = false; try { found_rstop = ( ((step.fin_node_id == this.rstops[stop_num].node_id) && (step.forward)) || ((step.beg_node_id == this.rstops[stop_num].node_id) && (!step.forward))); } catch (e:TypeError) { // this.rstops is empty. m4_WARNING(' .. step_num:', step_num); m4_WARNING(' .. rsteps.length:', rsteps.length); m4_WARNING(' .. edit_stops.length:', this.edit_stops.length); m4_WARNING(' .. step.forward:', step.forward); m4_WARNING(' .. step.beg_node_id:', step.beg_node_id); m4_WARNING(' .. step.fin_node_id:', step.fin_node_id); m4_WARNING(' .. stop_num:', stop_num); if (this.rstops !== null) { m4_WARNING(' .. rstops.length:', this.rstops.length); m4_WARNING(' .. rstops[stop_num]:', this.rstops[stop_num]); if (this.rstops[stop_num] !== null) { m4_WARNING2(' .. rstops[stop_num].node_id:', this.rstops[stop_num].node_id); } } else { // This happened on loading a saved, edited, non-libraried // route. // BUG nnnn/FIXMEFIXME: route_stop version 2 not being saved! m4_WARNING(' .. rstops: null'); } m4_ASSERT(false); } if (found_rstop) { if ((this.rstops[stop_num].is_endpoint) || (!this.rstops[stop_num].is_pass_through)) { stop_name = this.rstops[stop_num].name_; if (stop_name === null) { stop_name = this.street_name(stop_num); } ////m4_VERBOSE(' .. dir_build: found stop_name:', stop_name); } else { stop_name = null; ////m4_VERBOSE(' .. dir_build: found pass_through stop'); } // Select a different direction code if it's the last route // stop. if (this.rstops[stop_num].is_transit_stop) { num_transit_stops++; // If even # of stops, we're alighting transit else boarding. // FIXME: MAGIC_NUMBER: Replace these with new class type. // I.e., // stop_type = ((num_transit_stops % 2) == 0 // ? Stop_Type.alight // : Stop_Type.board); stop_type = ((num_transit_stops % 2) == 0 ? -1 : 1); ////m4_VERBOSE2(' .. dir_build: transit stop:', //// ((stop_type == -1) ? 'alight' : 'board')); } else { // FIXME: MAGIC_NUMBER: Replace this with new class type. // I.e., // stop_type = Stop_Type.not_transit stop_type = 0; // MAGIC_NUMBER: 0 means not a transit stop. ////m4_VERBOSE(' .. dir_build: not a transit stop'); } stop_num++; if (stop_num == this.rstops.length) { if (stop_name === null) { stop_name = 'Destination'; } dir_step = new Direction_Step( Conf.bearing.length - 1, // rel_direction Conf.bearing.length - 1, // abs_direction 0, // rel_distance stop_name, stop_type, step.beg_time, step.fin_time, dirs[dirs.length - 1], // prev(Direction_Step) [this.xs[step.fin_index-1], this.ys[step.fin_index-1],], null, this, rstep_i, /*route_caller=*/'directions_build-unnamed_dest'); dirs.push(dir_step); } else if ((stop_name !== null) || (stop_type != 0)) { //else if ((stop_name !== null) // || (stop_type != Stop_Type.no_transit)) { } // We skip intermediate rstops that don't have names // and are not transit stops. // MAGIC_NUMBERS: The 3rd-from-last Conf.bearing entry is // 'Bicycle stop' and the 4th-from-last Conf.bearing entry is // 'Transit stop'. classify = ((stop_type == 0) ? Conf.bearing.length - 3 : Conf.bearing.length - 4); //classify = ((stop_type == Stop_Type.no_transit) // ? Conf.bearing.length - 3 // : Conf.bearing.length - 4); dir_step = new Direction_Step( classify, // rel_direction classify, // abs_direction 0, // rel_distance stop_name, stop_type, step.beg_time, step.fin_time, dirs[dirs.length - 1], // prev(Direction_Step) [this.xs[step.fin_index-1], this.ys[step.fin_index-1],], null, this, rstep_i, /*route_caller=*/'directions_build-named_dest'); dirs.push(dir_step); } } // Compute the direction vector for the end of the current // step (used potentially for the next step to get the // relative turn angle) p_v = this.compute_step_dir(step, true, xs, ys); ////m4_VERBOSE(' .. dir_build: end of step: p_v:', p_v); ////m4_VERBOSE(' .. dir_build: end of step: n_v:', n_v); // Landmarks experiment. // set next landmarks if ((step.landmarks !== null) && (step.landmarks.length > 0) && (this.show_landmarks)) { landmarks = step.landmarks; // calculate distances (use for points for now) var l:Landmark; for each (l in landmarks) { if (l.xs !== null) { l.dist = Geometry.distance(l.xs[0], l.ys[0], this.xs[step.beg_index], this.ys[step.beg_index]); } } // This isn't the only place that we'll set landmarks true, // since, if we look for landmarks but find none for all of // the route steps, then we won't set loaded to true. this.landmarks_loaded = true; } else { landmarks = null; } } // end: for (rstep_i = 0; rstep_i < rsteps.length; rstep_i++) return dirs; } // protected function draw_alternate_diff(gr:Graphics, main_steps:Array, other_steps:Array, xs:Array, ys:Array, main_color:int, draw_neutral:Boolean) :void { var step_in_other:Boolean = false; var i:int; var m:Route_Step; var o:Route_Step; var x:Number; var y:Number; for each (m in main_steps) { step_in_other = false; for each (o in other_steps) { if (o.byway_stack_id == m.byway_stack_id) { step_in_other = (o.byway_version == m.byway_version); break; } } if (!step_in_other || draw_neutral) { x = G.map.xform_x_map2cv(xs[m.beg_index]); y = G.map.xform_y_map2cv(ys[m.beg_index]); gr.lineStyle(this.draw_width, (step_in_other ? Conf.vgroup_dark_static_color : main_color), Conf.route_alpha); gr.moveTo(x, y); for (i = m.beg_index + 1; i < m.fin_index; i++) { x = G.map.xform_x_map2cv(xs[i]); y = G.map.xform_y_map2cv(ys[i]); gr.lineTo(x, y); } } } } // protected function draw_circle(color:int, x:int, y:int, radius:int) :void { var gr:Graphics = this.sprite.graphics; gr.beginFill(color); gr.lineStyle(2, 0x000000); gr.drawCircle(x, y, radius); gr.endFill(); } // protected function draw_edit_mode(rsteps:Array) :void { var normal_steps:Array = new Array(); var dirty_steps:Array = new Array(); var s:Route_Step; var prev:Route_Stop_Editor = this.rstops[0]; var next:Route_Stop_Editor = this.rstops[1]; var i:int = 2; var j:int; var k:int; var in_dirty_seg:Boolean; var gr:Graphics = this.sprite.graphics; var sx:Number; var sy:Number; var ex:Number; var ey:Number; m4_TALKY2('draw_edit_mode: rsteps.length:', (rsteps !== null) ? rsteps.length : 'null'); m4_TALKY2('draw_edit_mode: rstops.length:', (rstops !== null) ? rstops.length : 'null'); m4_TALKY3('draw_edit_mode: this.edit_stops.length:', (this.edit_stops !== null) ? this.edit_stops.length : 'null'); // Render route steps first. for each (s in rsteps) { //m4_TALKY3('draw_edit_mode: i:', i, // '/ prev:', (prev !== null) ? prev : 'null', // '/ prev.editor', (prev !== null) ? prev.editor : 'null'); //m4_TALKY2('.. / next:', (next !== null) ? next : 'null', // '/ next.editor', (next !== null) ? next.editor : 'null'); in_dirty_seg = ( ( (prev === null) || (prev.editor === null) || (prev.editor.dirty_stop)) || ( (next === null) || (next.editor === null) || (next.editor.dirty_stop)) ); if (!in_dirty_seg) { // The rstops haven't been modified but a route stop could // have been inserted; check for that. j = this.edit_stops.indexOf(prev.editor); k = this.edit_stops.indexOf(next.editor); in_dirty_seg = ((j < 0) || (k < 0) || (k != j + 1)); } if (in_dirty_seg) { dirty_steps.push(s); } else { normal_steps.push(s); } // Check to see if this route step reaches a route stop. if ( ((s.forward) && (s.fin_node_id == next.node_id)) || ((!s.forward) && (s.beg_node_id == next.node_id))) { if (i < this.rstops.length) { prev = next; next = this.rstops[i++]; } // else: we're already done. } } // for each (s in rsteps) // Draw dirty parts in the old diff color. if (dirty_steps.length > 0) { var rviz_dirty:Route_Viz = new Route_Viz( -1, 'dirty', null, function(step:Route_Step) :int { return Conf.vgroup_move_old_color; }); m4_TALKY('draw_edit_mode: dirty_steps.len:', dirty_steps.length); rviz_dirty.route_line_render( this, dirty_steps, (rsteps === this.alternate_steps)); } // Draw unchanged parts with a solid color. if (G.map.rmode == Conf.map_mode_feedback) { // Color with plain color. // FIXME: RtFbDrag: [lb]: Make this more readable. // And make lambda fcn. static class fcn. or something. var rviz_unchanged:Route_Viz = new Route_Viz( -1, 'new', null, function(step:Route_Step) :int { return Conf.route_feedback_new_color; }); rviz_unchanged.route_line_render( this, normal_steps, (rsteps === this.alternate_steps)); } else { if (normal_steps.length > 0) { m4_TALKY('draw_edit_mode: normal_steps:', normal_steps.length); this.route_panel.route_viz.route_line_render( this, normal_steps, (rsteps === this.alternate_steps)); } } // Now draw dotted lines to fill in dirty parts of the route. m4_TALKY('draw_edit_mode: clear path_arrows graphics before redraw'); this.path_arrows.graphics.clear(); this.current_dir_step_sprite.graphics.clear(); m4_TALKY('draw_edit_mode: edit_stops.len:', this.edit_stops.length); for (i = 1; i < this.edit_stops.length; i++) { if ((!this.edit_stops[i - 1].is_stop_valid) || (!this.edit_stops[i].is_stop_valid)) { continue; } j = this.rstops.indexOf(this.edit_stops[i - 1].orig_stop); k = this.rstops.indexOf(this.edit_stops[i].orig_stop); // Note that k == i except when the route is edited, because // edit_stops will have deviated from rstops. // don't draw a line if points aren't dirty and order hasnt changed // [lb]'s non-negative rewording of previous comment: // Only draw a (dashed) line (indicating route request is // outstanding for a route segment) if points are dirty or if // order has changed. m4_TALKY6('draw_edit_mode: j:', Strutil.string_pad(j, 3, ' ', false), '/ k:', Strutil.string_pad(k, 3, ' ', false), '/ edit_stops[i-1].dirty_stop:', this.edit_stops[i-1].dirty_stop, '/ [i].dirty_stop:', this.edit_stops[i].dirty_stop); if ( (!this.edit_stops[i-1].dirty_stop) && (!this.edit_stops[i].dirty_stop) && ((j + 1) == k)) { continue; } sx = this.edit_stops[i - 1].x_cv; sy = this.edit_stops[i - 1].y_cv; ex = this.edit_stops[i].x_cv; ey = this.edit_stops[i].y_cv; // This is a fat dashed line we draw straight-as-the-crow-flies // from the existing neighbor node to where the user has the mouse. m4_TALKY('draw_edit_mode: line_draw_dashed: line_draw_dashed'); Paint.line_draw_dashed(gr, 20, sx, sy, ex, ey, 0.75 * this.draw_width, Conf.route_edit_color); // This is an arrow we draw pointing from the neighbor to the new // node/mouse position. m4_TALKY('draw_edit_mode: redraw path_arrows: arrow_tip_draw'); Paint.arrow_tip_draw(this.path_arrows.graphics, (sx + ex) / 2.0, (sy + ey) / 2.0, ex - sx, ey - sy, int(this.draw_width * 1.5), this.draw_width * 2, Conf.route_edit_color, 1); } // m4_TALKY('draw_edit_mode: this.visible:', this.visible); // m4_TALKY2('draw_edit_mode: this.sprite.visible:', // this.sprite.visible); } // protected function draw_geometry_diff() :void { var diff_color_map:Function = Route_Viz_Diff_Map.color_diff(this); var route_viz:Route_Viz; route_viz = new Route_Viz(-1, 'diff', null, diff_color_map); route_viz.route_line_render(this, this.rsteps, /*alternate=*/false); } // override public function label_maybe() :void { m4_TALKY('label_maybe:', this); super.label_maybe(); } // override protected function label_parms_compute() :void { m4_TALKY('label_parms_compute:', this); this.label_parms_compute_line_segment(); } // override public function panel_get_for_geofeatures( feats_being_selected:*, loose_selection_set:Boolean=false, skip_new:Boolean=false) :Panel_Item_Geofeature { m4_ASSERT(feats_being_selected.length == 1); var route:Route = feats_being_selected.item_get_random(); m4_ASSERT(route !== null); m4_TALKY('gpfgfs: route.route_panel:', route.route_panel); m4_ASSERT(!route.route_panel.panel_close_pending); // Am I right? return route.route_panel; } // // FIXME: Test two routes whose stops align. Is this pre-route manip code // useful? If it's handled okay, delete this function. // [lb] is not sure this behavior was preserved post-route manip. // See also: rs_under_mouse. /*/ // protected function merge_stop(step:Route_Step, tx:Number, ty:Number, rstops:Array) :void { // merge this stop into stops array based on location // we want to group them by proximity so that stops right on // top of each other are displayed differently. // - won't fix very close stops that might overlap, but this // is a situation easier for the user to tell what's going on var stop_found:Boolean = false; for (var j:int = 0; j < rstops.length; j++) { if (Math.abs(rstops[j].x - tx) < 10 && Math.abs(rstops[j].y - ty) < 10) { rstops[j].rsteps.push(step); stop_found = true; break; } } if (!stop_found) { // must create a new stop rstops.push({rsteps: [step], x: tx, y: ty}); } } /*/ // protected function rs_highlight(rs:Route_Step, highlight:Boolean) :void { var color:int; if (Route.selected_steps.indexOf(rs) == -1) { color = ((this.feedback_instance == Route.FB_NEW) ? Conf.route_feedback_new_color : Conf.route_feedback_old_color); } else { color = ((this.feedback_instance == Route.FB_NEW) ? Conf.route_feedback_new_color_selected : Conf.route_feedback_old_color_selected); } Paint.line_draw(this.sprite.graphics, this.xs.slice(rs.beg_index, rs.fin_index + 1), this.ys.slice(rs.beg_index, rs.fin_index + 1), this.draw_width, (highlight ? Conf.mouse_highlight_color : color)); } // protected function rs_highlight_maybe(evt:MouseEvent) :void { var rs:Route_Step = this.rs_under_mouse(evt); // De-highlight old step. if ((Route.highlighted_step !== null) && (Route.highlighted_step !== rs)) { this.rs_highlight(Route.highlighted_step, false); } // Highlight new step. if ((rs !== null) && (Route.highlighted_step !== rs)) { this.rs_highlight(rs, true); } // Update highlighted step. Route.highlighted_step = rs; } // protected function rs_select(rs:Route_Step, select:Boolean) :void { Paint.line_draw(this.sprite.graphics, this.xs.slice(rs.beg_index, rs.fin_index + 1), this.ys.slice(rs.beg_index, rs.fin_index + 1), this.draw_width, (select ? ((this.feedback_instance == Route.FB_NEW) ? Conf.route_feedback_new_color_selected : Conf.route_feedback_old_color_selected) : ((this.feedback_instance == Route.FB_NEW) ? Conf.route_feedback_new_color : Conf.route_feedback_old_color))); // Remove the pointing widget, if any. if (this.route_panel.widget_feedback.feedback.pw !== null) { this.route_panel.widget_feedback.feedback.pw.on_close(); } } // protected function rs_toggle_select(evt:MouseEvent) :void { var rs:Route_Step = this.rs_under_mouse(evt); if (rs !== null) { if (Route.selected_steps.indexOf(rs) == -1) { this.rs_select(rs, true); Route.selected_steps.push(rs); } else { this.rs_select(rs, false); Route.selected_steps.splice( Route.selected_steps.indexOf(rs), 1); } } this.route_panel.widget_feedback.feedback.update_segment_list(); } // Find route step under mouse pointer. protected function rs_under_mouse(evt:MouseEvent) :Route_Step { var p:Array = new Array(2); var dist:Number; var min_dist:Number = Infinity; var min_i:int = -1; var mx:Number = G.map.xform_x_stage2map(evt.stageX); var my:Number = G.map.xform_y_stage2map(evt.stageY); var rs:Route_Step = null; // Find closest route geometry segment. for (var i:int = 0; i < this.xs.length - 1; i++) { dist = Geometry.distance_point_line( mx, my, this.xs[i], this.ys[i], this.xs[i + 1], this.ys[i + 1]); if (dist < min_dist) { min_dist = dist; min_i = i; } } // Find the route step (min_i, min_i + 1) belongs to. if ((min_i > -1) && (min_dist < G.map.xform_scalar_cv2map(this.draw_width / 2))) { for each (rs in this.rsteps) { if ( (min_i >= rs.beg_index) && (min_i + 1 >= rs.beg_index) && (min_i <= rs.fin_index) && (min_i + 1 <= rs.fin_index)) { return rs; } } } return null; } // Update edit_stops and last_cmd_stops to match rstops. public function rstops_sync() :void { m4_TALKY('rstops_sync: no. rstops:', this.rstops.length); // Remove old rstops from the route stop sprite layer. for (var i:int = this.rstop_sprite.numChildren - 1; i >= 0; i--) { this.rstop_sprite.removeChildAt(i); } // Setup edit_stops and last_cmd_stops. this.edit_stops_set(new Array()); this.last_cmd_stops = new Array(); for each (var curr_rstope:Route_Stop_Editor in this.rstops) { var new_rstop:Route_Stop; if (curr_rstope.editor === null) { if (this.master_route === null) { new_rstop = new Route_Stop(this, curr_rstope); } else { new_rstop = new Route_Stop(this.master_route, curr_rstope); } m4_ASSERT_SOFT(this.master_route === this.master_item); } else { m4_DEBUG2('rstops_sync: curr_rstope.editor:', curr_rstope.editor); new_rstop = curr_rstope.editor; } var last_rstop:Route_Stop_Editor = new Route_Stop_Editor(); last_rstop.name_ = curr_rstope.name_; last_rstop.node_id = curr_rstope.node_id; m4_ASSERT_SOFT(last_rstop.node_id > 0); last_rstop.stop_version = curr_rstope.stop_version; last_rstop.x_map = curr_rstope.x_map; last_rstop.y_map = curr_rstope.y_map; last_rstop.is_endpoint = curr_rstope.is_endpoint; last_rstop.is_pass_through = curr_rstope.is_pass_through; last_rstop.is_transit_stop = curr_rstope.is_transit_stop; last_rstop.internal_system_id = curr_rstope.internal_system_id; last_rstop.external_result = curr_rstope.external_result; last_rstop.street_name_ = curr_rstope.street_name_; last_rstop.editor = new_rstop; last_rstop.orig_stop = curr_rstope; last_rstop.dirty_stop = false; m4_DEBUG('rstops_sync: last_rstop:', last_rstop); // EXPLAIN: How exactly does editor work? It's so the last_rstop // and curr_rstope objects can both reference the same Route_Stop? curr_rstope.editor = new_rstop; m4_DEBUG('rstops_sync: curr_rstope:', curr_rstope); new_rstop.name_ = curr_rstope.name_; // if (new_rstop.node_id == 0) { new_rstop.node_id = curr_rstope.node_id; } else { m4_ASSERT_SOFT(new_rstop.node_id == curr_rstope.node_id); } // if (new_rstop.stop_version == 0) { m4_ASSERT_SOFT(false); new_rstop.stop_version = curr_rstope.stop_version; } else { m4_ASSERT_SOFT(new_rstop.stop_version == curr_rstope.stop_version); } // new_rstop.x_map = curr_rstope.x_map; new_rstop.y_map = curr_rstope.y_map; new_rstop.is_endpoint = curr_rstope.is_endpoint; new_rstop.is_pass_through = curr_rstope.is_pass_through; new_rstop.is_transit_stop = curr_rstope.is_transit_stop; new_rstop.internal_system_id = curr_rstope.internal_system_id; new_rstop.external_result = curr_rstope.external_result; m4_TALKY2('rstops_sync: new_rstop.street_name_ = :', curr_rstope.street_name_); new_rstop.street_name_ = curr_rstope.street_name_; new_rstop.orig_stop = curr_rstope; new_rstop.dirty_stop = false; m4_DEBUG('rstops_sync: new_rstop:', new_rstop); this.edit_stops_push(new_rstop); this.last_cmd_stops.push(last_rstop); } } // Return an array of Route_Steps such that the first step in the list // starts at the given start node, and the last step ends at the given // end node. This assumes that start node and the end node exist in route public function steps_between(start_node:int, end_node:int) :Array { var s:Route_Step; var looking_for_start:Boolean = true; var results:Array = new Array(); m4_TALKY3('steps_between: beg nd:', start_node, '/ end nd:', end_node, '/ no. rsteps', this.rsteps.length); for each (s in this.rsteps) { m4_VERBOSE('rstep', s.beg_node_id, s.fin_node_id, s.forward); if (looking_for_start) { // only add step if it matches the start node if ((s.forward && s.beg_node_id == start_node) || (!s.forward && s.fin_node_id == start_node)) { looking_for_start = false; m4_VERBOSE3('found beg rstep: beg_node_id:', s.beg_node_id, '/ fin_node_id:', s.fin_node_id, '/ fwd?:', s.forward); } } if (!looking_for_start) { // Add all steps, but return if we've found the end. //m4_VERBOSE2('adding rstep', // s.beg_node_id, s.fin_node_id, s.forward); results.push(s); if ((s.forward && s.fin_node_id == end_node) || (!s.forward && s.beg_node_id == end_node)) { // The results are ready. m4_VERBOSE3('found fin rstep: beg_node_id:', s.beg_node_id, '/ fin_node_id:', s.fin_node_id, '/ fwd?:', s.forward); break; } } } if (results.length == 0) { // EXPLAIN: Added 2012.10.26 for route reactions, but [lb] is // curious why this would happen. m4_WARNING('EXPLAIN: steps_between: no results?'); G.sl.event( 'route/steps_between/failure', {route_id: this.stack_id, version: this.version, start_node_id: start_node, end_node_id: end_node, result_length: results.length}); } return results; } // public function street_name(rt_stop_or_num:Object) :String { var rs_editor:Route_Stop_Editor; rs_editor = (rt_stop_or_num as Route_Stop_Editor); if (rs_editor === null) { rs_editor = (this.rstops[rt_stop_or_num as int] as Route_Stop_Editor); } // MEH: This fcn. is/was inefficient (who cares?), because it walks // the list of route steps. So we cache the street name. It's up to // the rest of the code to invalidate the cache value when // appropriate. var street_name:String = rs_editor.street_name_; // NOTE: Callers generally check rs_editor.name_ first and then // call us if that's empty. Which is why this fcn. ignores it. if (!street_name) { var rt_step:Route_Step; for each (rt_step in this.rsteps) { if ( (rt_step.beg_node_id == rs_editor.node_id) || (rt_step.fin_node_id == rs_editor.node_id)) { m4_TALKY2('street_name: rs_editor.node_id:', rs_editor.node_id); m4_TALKY3('street_name: beg_node_id fin_node_id step_name:', rt_step.beg_node_id, rt_step.fin_node_id, rt_step.step_name, rt_step); street_name = rt_step.step_name; break; } } if (!street_name) { if (rs_editor === this.rstops[0]) { street_name = this.rsteps[0].step_name; m4_TALKY('street_name: first step:', street_name); } else if (rs_editor === this.rstops[this.rstops.length-1]) { street_name = this.rsteps[this.rsteps.length-1].step_name; m4_TALKY('street_name: last step:', street_name); } if (!street_name) { street_name = Conf.route_stop_map_name; m4_TALKY('street_name: default stop name:', street_name); } } m4_TALKY('street_name: street_name_ = :', street_name); if (street_name != 'Point on map') { rs_editor.street_name_ = 'Point near ' + street_name; } else { rs_editor.street_name_ = street_name; } } return street_name; } // public function temporary_rstop_clear() :void { m4_DEBUG('temporary_rstop_clear: temporary_rstop'); this.removeEventListener(MouseEvent.MOUSE_MOVE, this.on_mouse_move); this.temporary_rstop.graphics.clear(); UI.cursor_set_native_arrow(); } // protected function temporary_rstop_draw(event:MouseEvent) :void { m4_DEBUG('temporary_rstop_draw: temporary_rstop'); var p:Array = new Array(2); var in_segment:Boolean = false; var closest_p:Array = null; var closest_l:Number; var mx:Number = G.map.xform_x_stage2map(event.stageX); var my:Number = G.map.xform_y_stage2map(event.stageY); for (var i:int = 1; i < this.xs.length; i++) { in_segment = Geometry.project( mx, my, this.xs[i - 1], this.ys[i - 1], this.xs[i], this.ys[i], p, .5); if (in_segment) { // found the point so compare it to the closest point if ((closest_p === null) || (Geometry.distance(p[0], p[1], mx, my) < closest_l)) { closest_p = [p[0], p[1]]; closest_l = Geometry.distance(p[0], p[1], mx, my); } } } if (closest_p === null) { // pick the end point or start point if (Geometry.distance(mx, my, this.xs[0], this.ys[0]) < Geometry.distance(mx, my, this.xs[this.xs.length - 1], this.ys[this.ys.length - 1])) { closest_p = [this.xs[0], this.ys[0]]; } else { closest_p = [this.xs[this.xs.length - 1], this.ys[this.ys.length - 1]]; } } Route_Stop.draw_point(G.map.xform_x_map2cv(closest_p[0]), G.map.xform_y_map2cv(closest_p[1]), this.temporary_rstop.graphics); } // protected function tooltip_display(on:Boolean) :void { var tt:String; m4_TALKY2('tooltip_display: on:', on, '/ sel?:', this.selected, '/ is_clckbl?', this.is_clickable); if (on) { m4_ASSERT(this.last_mouse_over !== null); if (tooltip !== null) { ToolTipManager.destroyToolTip(tooltip); } tooltip = null; if (this.selected) { return; // Do not show tooltips for selected items. } if (!this.is_clickable) { return; // The user disabled routes at this zoom; no tooltip. } if (this.is_multimodal) { // BUG nnnn: We could show info about this transit leg, dummy! return; // The route cannot be edited, so don't tease the user. } if (!this.can_edit) { tt = 'Click the route to select it.'; } if (this.feedback_mode == Route.FB_SELECTING) { // If the user is in route feedback mode... tt = 'Click the route to select roads for your feedback.'; } else { // If the user is in route editing mode... tt = 'Click the route to select it. You can also edit its path.'; } tooltip = ToolTipManager.createToolTip( tt, this.last_mouse_over.stageX, this.last_mouse_over.stageY); } else { if (tooltip !== null) { ToolTipManager.destroyToolTip(tooltip); } tooltip = null; } this.last_mouse_over = null; } // public function update_route_stats() :void { m4_TALKY5('update_route_stats: hydrated:', this.hydrated, '/ rsteps:', (this.rsteps !== null) ? this.rsteps.length : 'null', '/ rstops:', (this.rstops !== null) ? this.rstops.length : 'null', '/ invalid:', this.invalid, '/ links_lazy_loaded:', this.links_lazy_loaded); // MAYBE: Are we doing this for sub-segments that we just delete // anyway? If stack_id is 0, we should bail now? m4_TALKY('update_route_stats:', this.softstr); if (this.rsteps !== null) { this.compute_len_and_ids(); this.directions = this.directions_build(this.rsteps, this.xs, this.ys); if (this.alternate_steps !== null) { this.alternate_directions = this.directions_build( this.alternate_steps, this.alternate_xs, this.alternate_ys); var idx:int = this.alternate_steps.length - 1; this.total_time = this.alternate_steps[idx].fin_time - this.alternate_steps[0].beg_time; } else { this.alternate_directions = new Array(); this.total_time = this.rsteps[this.rsteps.length - 1].fin_time - this.rsteps[0].beg_time; // m4_TALKY('abs start time=', this.rsteps[0].beg_time); // m4_TALKY2('abs end time=', // this.rsteps[this.rsteps.length-1].fin_time); // m4_TALKY('total time=', this.total_time); } } } // *** Event handlers // override public function on_mouse_doubleclick( event:MouseEvent, processed:Boolean) :Boolean { m4_DEBUG('on_mouse_doubleclick:', this, '/ target:', event.target); processed = true; // Skipping: super.on_mouse_doubleclick(ev, processed); // Geofeature selects all vertices (for Byways and Regions). // This is a little hacky: if we don't process the click, // Map_Canvas_Controller will recenter the map; but it won't // zoom the viewport because it checks to see if we're a Route // or not, which we are, so it doesn't zoom... which explains // why it's a hack of a little sorts. //return true; return false; } // This is called via Tool_Pan_Select via on_mouse_up, after it // knows we're not processing a double-click. override public function on_mouse_down(event:MouseEvent) :void { m4_DEBUG('on_mouse_down:', this.softstr); if ((this.is_path_editable( /*assume_editing_enabled=*/this.rstop_editing_enabled)) && (G.panel_mgr.effectively_active_panel === this.route_panel)) { if (!this.route_stop_still_under_mouse(event)) { m4_DEBUG2('on_mouse_down: dragged_object:', G.map.tool_cur.dragged_object); var mx:Number = G.map.xform_x_stage2map(event.stageX); var my:Number = G.map.xform_y_stage2map(event.stageY); var new_rstop:Route_Stop; new_rstop = Route_Editor_UI.route_stop_insert(this, mx, my); m4_DEBUG('on_mouse_down: new_rstop:', new_rstop); new_rstop.on_roll_over(event, /*called_by_route=*/true); new_rstop.on_mouse_down(event, /*called_by_route=*/true); } else { // There's an existing route stop upon which being clicked. // This is unexpected, since Route_Stop should get the click // first, and its on_mouse_down calls stopPropagation... m4_ASSERT_SOFT(false); } } else { m4_DEBUG2('on_mouse_down: !active_panel: !is_path_editable:', this); } this.on_mouse_down_route_stop_safe(event); // Geofeature on_mouse_down is a no-op. super.on_mouse_down(event); } public function on_mouse_down_route_stop_safe(event:MouseEvent) :void { this.tooltip_display(false); if (this.tooltip_timer !== null) { this.tooltip_timer.stop(); } if ((G.map.rmode == Conf.map_mode_feedback) && (this.feedback_mode == Route.FB_SELECTING) && (Route.highlighted_step !== null)) { this.rs_toggle_select(event); } } // // NOTE: Map_Controller is also monitoring mouse move. public function on_mouse_move(event:MouseEvent) :void { m4_DEBUG2('on_mouse_move: temporary_rstop: is_path_editable:', this.is_path_editable()); if ((G.map.rmode == Conf.map_mode_feedback) && (this.feedback_mode == Route.FB_SELECTING)) { this.rs_highlight_maybe(event); } else if (this.is_path_editable()) { m4_DEBUG('on_mouse_move: temporary_rstop_draw'); this.temporary_rstop_draw(event); } } // override public function on_mouse_out(event:MouseEvent) :void { m4_DEBUG('on_mouse_out:', this); // Note the event.target and event.currentTarget === this.sprite. // Bugfix: If you hover the mouse over the route stop of an unselected // route, you'll get a rapid back-and-forth flip-flopping of two UI // components. The mouse over causes the route_stop sprite and label // to be drawn, which causes a mouse_out on the route, which then // removes the route_stop sprite and label, which causes on_roll_out // on the route_stop, and then the route gets an on_mouse_over and // we start the whole silly cycle over again. if (!this.route_stop_still_under_mouse(event)) { // This just unsets the route highlight... super.on_mouse_out(event); if ((G.map.rmode == Conf.map_mode_feedback) && (this.feedback_mode == Route.FB_SELECTING)) { this.rs_highlight_maybe(event); } m4_TALKY2('on_mouse_out: delight_on_mouse_out:', this.delight_on_mouse_out); if (this.delight_on_mouse_out) { this.highlighted = false; if (this.is_drawable) { this.draw(); } this.delight_on_mouse_out = false; } } if (this.selected) { if (this.is_path_editable()) { m4_DEBUG('on_mouse_out: temporary_rstop_clear'); this.temporary_rstop_clear(); } } // If a real mouse out, naturally hide the tooltip, and also if the // mouse is now over a Route_Stop, which has its own tooltip (which // is the route stop name). this.tooltip_display(false); if (this.tooltip_timer !== null) { this.tooltip_timer.stop(); } } // override public function on_mouse_over(event:MouseEvent) :void { m4_TALKY('on_mouse_over:', this, '/ sel?:', this.selected); // This just sets the route highlight... super.on_mouse_over(event); if (!this.selected) { // Start the tooltip timer. this.last_mouse_over = event; if (this.tooltip_timer !== null) { m4_DEBUG('on_mouse_over: starting tooltip_timer'); this.tooltip_timer.reset(); // See: Conf.route_path_tooltip_delay (366 ms.). this.tooltip_timer.start(); } else { this.tooltip_display(true); } // Always select the route on the map, which tells the user that // it's hot (i.e., clickable)... not that the tooltip doesn't // already indicate the same think. this.delight_on_mouse_out = true; this.highlighted = true; if (this.is_drawable) { this.draw(); } } else { // Show temporary route stop. m4_TALKY2('on_mouse_over: is_path_editable:', this.is_path_editable()); if ((this.is_path_editable()) && (!this.route_stop_still_under_mouse(event))) { m4_DEBUG('on_mouse_over: temporary_rstop_draw'); this.sprite.addEventListener(MouseEvent.MOUSE_MOVE, this.on_mouse_move); this.temporary_rstop_draw(event); UI.cursor_set_native_finger(); } } // If we are in the feedback mode and this route is locked, it // means that we are ready to select route segments. In this case, // hovering should highlight route steps, and clicking should // toggle them. if ((G.map.rmode == Conf.map_mode_feedback) && (this.feedback_mode == Route.FB_SELECTING)) { // NOTE: Map_Controller will also see the same mouse move events. this.sprite.addEventListener(MouseEvent.MOUSE_MOVE, this.on_mouse_move); this.rs_highlight_maybe(event); } // Prevent other routes from handling event and hijacking highlights. event.stopPropagation(); } // public function on_tooltip_timer(event:TimerEvent) :void { this.tooltip_display(true); } // protected function route_stop_still_under_mouse(event:MouseEvent) :Boolean { var stay_golden_ponyboy:Boolean = false; if (this.sprite !== null) { if (this.sprite.stage !== null) { if (event !== null) { var results:Array = null; results = this.sprite.stage.getObjectsUnderPoint( new Point(event.stageX, event.stageY)); m4_DEBUG2('route_stop_still_under_mouse: results.length:', (results !== null) ? results.length : 'null'); if (results !== null) { for each (var o:Object in results) { // Note the that Route_Stop for checked out routes is // in edit_stops (Route_Stops), not rstops (Objects). if (o is Route_Stop) { if ((o as Route_Stop).route === this) { m4_DEBUG('rstop_still_undr_mouse sty_gldn_pnyb'); stay_golden_ponyboy = true; break; } else { m4_DEBUG2('rstop_still_undr_mouse: rt_stop.rte:', (o as Route_Stop).route); m4_DEBUG('rstop_still_undr_mouse: this:', this); } } } } } m4_ASSERT_ELSE_SOFT; } m4_ASSERT_ELSE_SOFT; } m4_ASSERT_ELSE_SOFT; return stay_golden_ponyboy; } // *** Base class getters and setters // override public function get actionable_at_raster() :Boolean { return true; } // MAYBE: This class doesn't do anything if the current selected state // is the same as the one being requested. However, if the item was // selected before its panel was ready, currently, the client has to // clear item selected and then set it again to force us to show the // route panel. Can't we just detect if we're selected but not associated // with any panel, and then do something proactive about it? // overridden to bring selected route to the front override public function set_selected( s:Boolean, nix:Boolean=false, solo:Boolean=false) :void { var cur_selected:Boolean = this.selected; super.set_selected(s, nix, solo); // De-select any selected map items. Note that this doesn't clear the // user's selection -- whatever was selected is still part of its // panel's selection set, so the user can restore the old map // selection by re-activating that selection's panel. // Remember that this is the active_route. if (s) { if ((G.item_mgr.active_route !== null) && (G.item_mgr.active_route !== this)) { m4_WARNING2('selected: deselect active_route:', G.item_mgr.active_route); G.item_mgr.active_route.set_selected(false, /*nix=*/true); } m4_DEBUG('set_selected: setting active_route: this:', this); G.item_mgr.active_route = this; } else { if ((G.item_mgr.active_route !== null) && (G.item_mgr.active_route !== this)) { m4_WARNING2('selected: unexpected active_route:', G.item_mgr.active_route); m4_WARNING('selected: was expecting this:', this); // MAYBE: Don't clear active_route? // 2014.04.29: This might be causing panel to force-show // the route details panel when you're trying to see the // find route panel. // trying this: G.item_mgr.active_route = null; } else { m4_DEBUG2('set_selected: clearing active_route: this:', this.toString_Terse()); G.item_mgr.active_route = null; } } // Fiddle with other things. var r_index:int; if (s != cur_selected) { if (s) { // Swap last child with this route -- move the route sprite to // the top of the display list (by putting the sprite as the // last child). // EXPLAIN: Why swap sprites instead of just placing this one at // the back of the list? Though the only side-effect of // this is that the route or items that were selected // don't sink below the newly selected item but sink // below other items, too, which might appear awkward. //m4_DEBUG('set_selected: this.sprite:', this.sprite); //m4_DEBUG2('set_selected: this.sprite.parent:', // this.sprite.parent); if (this.sprite.parent !== null) { r_index = this.sprite.parent.getChildIndex(this.sprite); //m4_DEBUG('set_selected: r_index:', r_index); this.sprite.parent.swapChildrenAt( r_index, this.sprite.parent.numChildren - 1); } else { // 2013.09.09: Logged in w/ routes, then logged out, null ref // I can see the 'A' and 'B' labels... ug. // 2013.09.12: [lb] logged in and tried to save two deleted // routes. -- Happens on roll over, trying to set the route // selected, so the route must be deleted but still in the // route_list, I'm guessing. // 2014.07.16: [lb] is pretty sure this just means the route // has already been removed from the map. // No: m4_ASSERT_SOFT(false); } // 2013.12.11: This is wrong: When the user mouses over a route // in the route list that's on the map -- even if it's panel has // not been opened -- this code path is followed and we're // recording a view event on the route. But the user is just // looking at its geometry; it's not like this is a real route // view event. // this.signal_route_view(); if (!this.is_multimodal) { // activate route editing mode Route_Editor_UI.route_edit_start(); } } else { if (!this.is_multimodal) { // deactivate route editing mode Route_Editor_UI.route_edit_stop(); } this.disable_rstop_editing(); } m4_TALKY('set_selected: set_selected: path_arrows.visible:', s); this.rstop_sprite.visible = s; this.path_arrows.visible = s; } } // override protected function set_selected_ensure_finalize( s:Boolean, nix:Boolean=false) :void { m4_TALKY2('set_selected_ensure_finalize: s:', s, '/ nix:', nix, '/ is_drawable:', this.is_drawable, '/', this); super.set_selected_ensure_finalize(s, nix); } // override public function set visible(v:Boolean) :void { var old_label_visible:Boolean = false; if (this.label !== null) { old_label_visible = this.label.visible; } m4_DEBUG('set visible:', v, '/', this); super.visible = v; if (!v) { var rs_label:Map_Label; for each (rs_label in this.rstop_labels) { if (rs_label.parent === G.map.route_labels) { m4_TALKY('set visible: removing map rs label:', rs_label); G.map.route_labels.removeChild(rs_label); } else { m4_DEBUG2('visible: EXPLAIN: Why is rs label missing?:', rs_label); m4_DEBUG(' .. parent:', rs_label.parent); } } m4_TALKY('set visible: resetting rs label:', rs_label); this.rstop_labels = new Array(); } if (v != old_label_visible) { // 2013.12.17: With calling this, the changing of route visibility // is quick. But recaculating labels takes a while... but it looks // nice... G.map.geofeatures_relabel(); } } // *** Getters and setters // public function get counterpart() :Route { return (this.counterpart_untyped as Route); } // override public function get counterpart_gf() :Geofeature { return this.counterpart; } // override public function get discardable() :Boolean { // EXPLAIN: We do delete Routes, but... discardable is really just // used when panning, right? So Routes can be discarded, // it's just that that doesn't automatically happen on pan? // 2013.09.09: Well, when you change users, branches, or // revisions, this value is checked to see if we should // reload the item (see G.map.items_preserve). return false; } // [Bindable] public function get filter_show_route() :Boolean { // This fcn. pertains to the checkbox in the routes list, basically // (if the route is loaded into a page on the routes lists). We'll // still draw the route on the map if there's a details panel for // it, but if there's no route panel, we only draw the route if the // user selected its list_entry. // Nope: ((this.route_panel_ !== null) && ...); // EXPLAIN/FIXME: For route history, [lb] is not sure that checking // rev_is_working makes sense. var cbox_selected:Boolean; // EXPLAIN: Why do we show if not working? Implies Diff or Historic? // How do you view historic routes? cbox_selected = ((!this.rev_is_working) || (this.filter_show_route_)); m4_TALKY3('get filter_show_route:', this.filter_show_route_, '/ rev:', this.rev.friendly_name, '/ working?:', this.rev_is_working, '/ ', this.softstr); return cbox_selected; } // public function set filter_show_route(cbox_selected:Boolean) :void { // Any code may set cbox_selected to false, but only a // Route_List_Entry should set cbox_selected to true. this.set_filter_show_route(cbox_selected, /*force=*/false); } // public function set_filter_show_route(cbox_selected:Boolean, force:Boolean=false) :void { m4_TALKY5('set_filter_show_route:', 'cbox_selected/filter_show_route:', cbox_selected, '/ force:', force, '/ filter_show_route_:', this.filter_show_route_, '/ this:', this); if ((this.filter_show_route_ != cbox_selected) || (force)) { this.filter_show_route_ = cbox_selected; // m4_TALKY3('set filter_show_route: visible:', this.visible, // '/ is_drawable:', this.is_drawable, // '/ selected:', this.selected); if ((this.visible != this.is_drawable) || (force)) { this.visible = this.is_drawable; // Call draw_all so we draw the route name_ label. //this.draw(); this.draw_all(); } if (!this.visible) { // m4_TALKY('set filter_show_route: not visible:', this); this.set_selected(false); } // Tell the Route_List_Entry listeners to adjust their checkboxes. m4_TALKY('set_filter_show_route: dispatchEvt: routeFilterChanged'); this.dispatchEvent(new Event('routeFilterChanged')); } } // public function route_list_membership_add(rte_lst_entry:Object) :void { m4_DEBUG('route_list_membership_add: rte_lst_entry:', rte_lst_entry); this.route_list_membership.add(rte_lst_entry); this.route_remove_from_map_maybe(); } // public function route_list_membership_nix(rte_lst_entry:Object) :void { m4_DEBUG('route_list_membership_nix: rte_lst_entry:', rte_lst_entry); this.route_list_membership.remove(rte_lst_entry); this.route_remove_from_map_maybe(); } // protected function route_remove_from_map_maybe() :void { var is_drawable:Boolean = this.is_drawable; m4_TALKY3('route_remove_from_map_maybe: is_drawable:', is_drawable, '/ route_list_membership.len:', this.route_list_membership.length); var remove_from_map:Boolean = ((!is_drawable) && (this.route_list_membership.length <= 0)); m4_TALKY2('route_remove_from_map_maybe: remove_from_map:', remove_from_map); // Reset the checkbox flag if we're no longer part of a route list. if (this.route_list_membership.length == 0) { m4_TALKY('rte_rem_fr_map_maybe: clear filter_show_rte:', this); this.filter_show_route_ = false; } // FIXME/MAYBE: [lb] is not sure that we should do this... // maybe test it first... // TEST_THIS_CODE: test_this_code = true is untested. var test_this_code:Boolean = false; if (test_this_code) { if (remove_from_map) { G.map.item_discard(this); } } } // public function set_visible_with_panel( any_panel:Detail_Panel_Base, panel_attach:Boolean, panel_release:Boolean) :void { m4_DEBUG3('set_visible_with_panel: any_panel:', any_panel, '/ panel_attach:', panel_attach, '/ panel_release:', panel_release) if (any_panel !== null) { if (panel_attach) { this.keep_showing_while_paneled.add(any_panel); } else { this.keep_showing_while_paneled.remove(any_panel); } if (this.visible != this.is_drawable) { this.visible = this.is_drawable; if (!this.visible) { // m4_DEBUG('set_visible_with_panel: not visible:', this); this.set_selected(false); } this.draw_all(); } } } // public function signal_route_view() :void { m4_DEBUG2('signal_route_view: route_list_membership:', route_list_membership); // Tell the route library to update its list. If all routes existed in // the list, we could signal an event, but because new routes won't be // in the list, we have to contact the list directly. //Insufficient: //m4_DEBUG('signal_route_view: dispatchEvent: routeViewCountIt'); //this.dispatchEvent(new Data_Change_Event('routeViewCountIt', this)); if (Route.looked_at_list_callback !== null) { Route.looked_at_list_callback(this); } m4_ASSERT_ELSE_SOFT; } // public function update_cur_dir(coords:Array) :void { this.current_dir_step = coords; this.draw(); } // *** // public function get from_canaddr() :String { var is_beg:Boolean = true; var is_fin:Boolean = false; return this.get_addr_name(is_beg, is_fin); } // public function get to_canaddr() :String { var is_beg:Boolean = false; var is_fin:Boolean = true; return this.get_addr_name(is_beg, is_fin); } // *** // public function get_addr_name(is_beg:Boolean, is_fin:Boolean) :String { var name:String = null; if ((this.rstops !== null) && (this.rstops.length > 0)) { var rstop_i:int; if (is_beg) { rstop_i = 0; } else { m4_ASSURT(is_fin); rstop_i = this.rstops.length - 1; } name = this.rstops[rstop_i].name_; if (name === null) { name = this.street_name(rstop_i); } } if ((name === null) || (name == '')) { if (is_beg) { name = this.beg_addr; } else { name = this.fin_addr; } } if ((name === null) || (name == '')) { // What about using the final edge's street name? if ((this.rstops !== null) && (this.rstops.length >= 2)) { if (is_beg) { name = this.street_name(/*stop_num=*/0); } else { name = this.street_name(this.rstops.length-1); } if (name != 'Point on map') { name = 'Point near ' + name; } } else { name = Conf.route_stop_map_name; } } return name; } // public function get alternate_html_text() :String { if (this.alternate_steps === null) { return ""; } else { return this.html_text_build(this.alternate_directions, this.alternate_length); } } // public function get html_text() :String { return this.html_text_build(this.directions, this.rsn_len); } // public function html_text_build(dirs:Array, dir_len:Number) :String { m4_TALKY2('html_text_build: dirs.len:', dirs.length, '/ dir_len:', dir_len); // NOTE: dir_len isn't used. What was the original intent? var i:int = 0; var dr:Direction_Step; var first_col_width:int; var first_col_label:String; var the_fourth_row:String = ''; var direction_steps:String = ''; var html_text:String = ''; if (!this.is_multimodal) { // only have length text first_col_width = 46; first_col_label = 'Odo.'; } else { // change length text and add a time row first_col_width = 66; first_col_label = 'Time'; the_fourth_row = StringUtil.substitute( (<![CDATA[ <tr> <td class="header">Total Time:</td> <td class="normal"> {0} </td> </tr> ]]>).toString(), [ Timeutil.total_time_to_pretty_string(this.total_time), ] ); } // build direction steps in html rows for each (dr in dirs) { if ((i++) % 2 == 0) { direction_steps += '<tr bgcolor="#E7E7E7">' + dr.html_text(is_multimodal) + '</tr>\n'; } else { direction_steps += '<tr>' + dr.html_text(is_multimodal) + '</tr>\n'; } } html_text = StringUtil.substitute( (<![CDATA[ {0} <tr> <td class="header">From:</td> <td class="normal">{1}</td> </tr> <tr> <td class="header">To:</td> <td class="normal">{2}</td> </tr> <tr> <td class="header">Length:</td> <td class="normal"> {3} </td> </tr> {4} {5} {6} {7} ]]>).toString(), [ Conf.directions_html_header(), this.from_canaddr, this.to_canaddr, Strutil.meters_to_miles_pretty(this.rsn_len), the_fourth_row, Conf.directions_html_table(first_col_width, first_col_label), direction_steps, Conf.directions_html_tail, ] ); return html_text; } // override public function get hydrated() :Boolean { var hydrated:Boolean = (this.rsteps !== null); m4_ASSERT((hydrated && (this.rsteps !== null)) || ((!hydrated) && (this.rsteps === null))); //m4_DEBUG('get hydrated (route):', hydrated); hydrated &&= super.hydrated; ////m4_DEBUG('get hydrated (&& super):', hydrated); //if (!hydrated) { // m4_DEBUG(' .. this.links_lazy_loaded:', this.links_lazy_loaded); // m4_DEBUG(' .. this.invalid:', this.invalid); //} return hydrated; } // override public function get is_clickable() :Boolean { var is_clickable:Boolean = false; if (this.master_route === null) { if (G.map.rmode == Conf.map_mode_feedback) { is_clickable = (this.feedback_instance == Route.FB_NEW); } else { is_clickable = ( super.is_clickable && (G.tabs.settings.routes_clickable || (!this.route_panel.widget_route_footer.save_footer .route_clicks_ignore.selected) || (!G.map.zoom_is_vector()) || (!this.rev_is_working))); } } // else, an older route version; the route line is viewable but not // clickable/interactiveable. return is_clickable; } // override public function get is_drawable() :Boolean { var is_drawable:Boolean = super.is_drawable; // All routes have their own panels, which are registered with the // panel manager, but that doesn't mean the panel is visible. //var is_registered:Boolean = // G.panel_mgr.is_panel_registered(this.route_panel_); var is_panel_showing:Boolean = false; var is_panel_closed_or_closing:Boolean = true; var rt_panel:Panel_Item_Route; if (this.master_route === null) { rt_panel = this.route_panel_; } else { rt_panel = this.master_route.route_panel_; } if (rt_panel !== null) { if (G.panel_mgr.tab_index_get(rt_panel) >= 0) { is_panel_showing = true; } if (!rt_panel.panel_close_pending) { is_panel_closed_or_closing = false; } } m4_TALKY7('get is_drawable: super.is_drawable:', is_drawable, '/ filter_show_route:', this.filter_show_route, '/ keep_showing_while_paneled.len:', this.keep_showing_while_paneled.length, '/ is_panel_showing:', is_panel_showing, '/ is_panel_closed_or_closing:', is_panel_closed_or_closing); is_drawable &&= ( (this.filter_show_route) || (this.keep_showing_while_paneled.length > 0) || ((is_panel_showing) && (!(is_panel_closed_or_closing)))); m4_TALKY('get is_drawable: is_drawable:', is_drawable); return is_drawable; } // override public function get is_labelable() :Boolean { var is_labelable:Boolean = ((super.is_labelable) && (this.hydrated)); m4_TALKY4('is_labelable:', is_labelable, '/ this.is_drawable:', this.is_drawable, '/ !this.hidden_by_filter():', !this.hidden_by_filter(), '/ this.hydrated:', this.hydrated); return is_labelable; } // public function get is_multimodal() :Boolean { return (this.travel_mode == Travel_Mode.transit); } // public function get is_path_clickable() :Boolean { // We could have the panel change us, or we could just be a little // coupled and wire the route to the panel. At least having a getter // is better than writing route.route_panel.tab_route_details... // everywhere. return ((!this.route_panel.widget_route_footer.save_footer .route_clicks_ignore.selected) && (this.master_route === null)); } // public function get is_path_edit_immediately() :Boolean { var editable:Boolean = ( this.route_panel.widget_route_footer.save_footer .route_clicks_drag_rstop.selected); m4_DEBUG('is_path_edit_immediately: editable/1:', editable); // To enable the long-press feature to get around when the checkbox is // not checkbox (e.g., Drag Route Line to Add Stops is not selected), // the Tool_Pan_Select tool hacks our enabling flag. editable ||= this.rstop_editing_enabled; m4_DEBUG('is_path_edit_immediately: editable/2:', editable); return editable; } // public function is_path_editable(assume_editing_enabled:Boolean=false) :Boolean { // FIXME: App Mode Stuff: // // Allow editing when: // // - route is new and route_modify_new is allowed // - route is saved, private and route_modify_private is allowed // - route is saved, shared/public and item_edit is allowed // // 2013.05.03: [mm] notes: This logic does not check for ownership, // e.g. it checks is_private, but does not check if the route is owned // by the current user. Is that a problem? Or should this.can_edit // (also in the return clause) take care of that? // // 2013.05.07: [lb] notes that is_private and the rest of the // access_infer values are only indicative of an item's scope, // and should generally just be used to draw different colored // backgrounds in application widgets. We shouldn't use access_infer // for any permissions decisions. But for this Boolean it looks like // we want to let user's edit their private routes when they might // not otherwise be able to edit a shared or public route. So the // real question is, is that the desireable behaviour? // var allowed_by_mode:Boolean = ( ((this.unlibraried) && (G.app.mode.is_allowed(App_Action.route_modify_new))) || ((!this.unlibraried) && (this.is_private) && (G.app.mode.is_allowed(App_Action.route_modify_own))) || ((!this.unlibraried) && ((this.is_shared) || (this.is_public)) && (G.app.mode.is_allowed(App_Action.route_modify_all))) ); // If the user checked the "Click on Routes to Add Stops" checkbox // or has longpressed on the route and is still holding the mouse // down, the path is considered editable. var route_stops_okay:Boolean = (assume_editing_enabled //|| this.rstop_editing_enabled || (this.is_path_edit_immediately && this.is_path_clickable)); var is_editable:Boolean = ((this.selected) && (!this.is_multimodal) && (this.rev_is_working) && (this.is_clickable) && (this.master_route === null) && (this.can_edit) && (allowed_by_mode) && (this.feedback_mode != Route.FB_SELECTING) && (this.feedback_instance != Route.FB_OLD) && (G.map.tool_is_active(Tool_Pan_Select)) && (route_stops_okay)); m4_TALKY6('is_path_editable:', 'is_editable: ', is_editable, '/ is_private: ', this.is_private, '/ is_shared: ', this.is_shared, '/ is_public: ', this.is_public, '/ fresh: ', this.fresh); m4_TALKY6(' ', '/ can_edit: ', this.can_edit, '/ alwd_by_mode:', allowed_by_mode, '/ rev_is_workg:', this.rev_is_working, '/ is_clickable:', this.is_clickable, '/ is_private: ', this.is_private); m4_TALKY4(' ', '/ pth_edt_immd:', this.is_path_edit_immediately, '/ rs_edtg_nbld:', this.rstop_editing_enabled, '/ rt_stops_ok: ', route_stops_okay); return is_editable; } // [Bindable] public function get is_route_stop_selection_deleteable() :Boolean { // If the user selects all the route stops or all but one route stop, // we cannot bulk-delete the selected route stops. return (this.num_rstops_selected < (this.num_dests - 1)); } // public function set is_route_stop_selection_deleteable(ignored:Boolean) :void { m4_ASSERT(false); } // public function get num_dests() :int { var rstop:Route_Stop; if (this.num_dests_ === null) { this.num_dests_ = 0; this.num_rstops_selected = 0; if (this.edit_stops !== null) { var stop_0:Route_Stop = this.edit_stops[0]; var stop_n:Route_Stop = this.edit_stops[ this.edit_stops.length-1]; if (stop_0 !== null) { stop_0.is_endpoint = true; } if (stop_n !== null) { stop_n.is_endpoint = true; } for each (rstop in this.edit_stops) { // We used to only consider named, properly geocoded stops in // the num_dests count, so you could not delete the last two // named stops, but the code is now smart enough to treat // unnamed route stops with as much courtesy as named stops. // Ignoring: ((rstop.is_endpoint || (!rstop.is_pass_through)) // && (rstop.name)) if (rstop !== Route_Editor_UI.new_stop) { m4_DEBUG('num_dests: rstop:', rstop); this.num_dests_++; } if (rstop.rstop_selected) { this.num_rstops_selected += 1; } } } m4_DEBUG2('get num_dests: num_rstops_selected:', this.num_rstops_selected); } return (this.num_dests_ as int); } // public function edit_stop_name_fcn( rt_stop_:*, to:*=null, do_or_undo:*=null) :* { var rt_stop:Route_Stop = (rt_stop_ as Route_Stop); m4_DEBUG('edit_stop_name_fcn: rt_stop:', rt_stop); if (do_or_undo !== null) { m4_DEBUG('edit_stop_name_fcn: to:', to); rt_stop.name_ = String(to); // Consider this stop no longer pass-through if named. rt_stop.is_pass_through = (rt_stop.name_ == ''); } return rt_stop.name_; } // public function edit_stops_push(rstop:Route_Stop) :void { if (this.edit_stops.length > 1) { var old_lastie:Route_Stop; old_lastie = this.edit_stops[this.edit_stops.length-1]; old_lastie.is_endpoint = false; if (rstop !== Route_Editor_UI.new_stop) { this.num_dests_ += 1; m4_TALKY2('edit_stops_push: two or more: rstop:', rstop, '/ num_dests_:', this.num_dests_); } } else if (rstop !== Route_Editor_UI.new_stop) { this.num_dests_ += 1; m4_TALKY2('edit_stops_push: just one: rstop:', rstop, '/ num_dests_:', this.num_dests_); } if (rstop.rstop_selected) { this.num_rstops_selected += 1; } rstop.is_endpoint = true; this.edit_stops.push(rstop); } // public function edit_stops_set(new_stops:Array) :void { if (this.edit_stops !== null) { for each (var old_rstop:Route_Stop in this.edit_stops) { old_rstop.is_endpoint = false; } } this.edit_stops = new_stops; for each (var new_rstop:Route_Stop in this.edit_stops) { new_rstop.route = this; } this.num_dests_ = null; this.num_rstops_selected = 0; if (new_stops !== null) { // Set the is_endpoint route stops. var ignored:int = this.num_dests; } } // public function mark_route_panel_dirty() :void { if (this.route_panel_ !== null) { G.panel_mgr.panels_mark_dirty([this.route_panel_,]); } else if (this.master_route !== null) { m4_ASSERT_SOFT(false); // Shouldn't happen... } } // public function get route_panel() :Panel_Item_Route { var rt_panel:Panel_Item_Route; if (this.master_route !== null) { rt_panel = this.master_route.route_panel; } else { if (this.route_panel_ === null) { this.route_panel_ = (G.item_mgr.item_panel_create(this) as Panel_Item_Route); this.route_panel_.route = this; m4_DEBUG2('get route_panel: created route_panel_:', this.route_panel_); // this.visible is false until the panel is set (because if the // panel is removed, we don't want to show the sprite) so tickle // the route now that this.is_drawable may return true. this.geofeature_added_to_map_layer(); } rt_panel = this.route_panel_; } return rt_panel; } // public function set route_panel(route_panel:Panel_Item_Route) :void { m4_ASSERT_SOFT(false); // Never called. Search: \.route_panel_? = } // public function get rsteps() :Array { return this.rsteps_; } // public function set rsteps(rsteps:Array) :void { this.rsteps_ = rsteps; // Tell interested parties of our success. // 2013.04.30: This isn't the most robust solution, but it's better // than what was coded, which was a tight loop in // Route_Editor_UI waiting for this to happen (using a // bunch of callLaters). // (It's not the best solution because we don't discern by // the route: we signal routeStepsLoaded via item_mgr, so // listeners have to check if they care.) if (this.rsteps_ !== null) { m4_DEBUG('rsteps: dispatchEvent: routeStepsLoaded'); this.dispatchEvent(new Event('routeStepsLoaded')); } } } }
// ================================================================================================= // // Starling Framework // Copyright Gamua GmbH. All Rights Reserved. // // This program is free software. You can redistribute and/or modify it // in accordance with the terms of the accompanying license agreement. // // ================================================================================================= package starling.core { import flash.display.Shape; import flash.display.Sprite; import flash.display.Stage3D; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.display3D.Context3D; import flash.display3D.Context3DProfile; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TouchEvent; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.system.Capabilities; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import flash.text.TextFormatAlign; import flash.ui.Mouse; import flash.ui.Multitouch; import flash.ui.MultitouchInputMode; import flash.utils.getTimer; import flash.utils.setTimeout; import starling.rendering.VertexData; import starling.animation.Juggler; import starling.display.DisplayObject; import starling.display.Stage; import starling.events.EventDispatcher; import starling.events.ResizeEvent; import starling.events.TouchPhase; import starling.events.TouchProcessor; import starling.rendering.Painter; import starling.textures.TextureSmoothing; import starling.utils.Align; import starling.utils.Color; import starling.utils.MatrixUtil; import starling.utils.Pool; import starling.utils.RectangleUtil; import starling.utils.SystemUtil; /** Dispatched when a new render context is created. The 'data' property references the context. */ [Event(name="context3DCreate", type="starling.events.Event")] /** Dispatched when the root class has been created. The 'data' property references that object. */ [Event(name="rootCreated", type="starling.events.Event")] /** Dispatched when a fatal error is encountered. The 'data' property contains an error string. */ [Event(name="fatalError", type="starling.events.Event")] /** Dispatched when the display list is about to be rendered. This event provides the last * opportunity to make changes before the display list is rendered. */ [Event(name="render", type="starling.events.Event")] /** The Starling class represents the core of the Starling framework. * * <p>The Starling framework makes it possible to create 2D applications and games that make * use of the Stage3D architecture introduced in Flash Player 11. It implements a display tree * system that is very similar to that of conventional Flash, while leveraging modern GPUs * to speed up rendering.</p> * * <p>The Starling class represents the link between the conventional Flash display tree and * the Starling display tree. To create a Starling-powered application, you have to create * an instance of the Starling class:</p> * * <pre>var starling:Starling = new Starling(Game, stage);</pre> * * <p>The first parameter has to be a Starling display object class, e.g. a subclass of * <code>starling.display.Sprite</code>. In the sample above, the class "Game" is the * application root. An instance of "Game" will be created as soon as Starling is initialized. * The second parameter is the conventional (Flash) stage object. Per default, Starling will * display its contents directly below the stage.</p> * * <p>It is recommended to store the Starling instance as a member variable, to make sure * that the Garbage Collector does not destroy it. After creating the Starling object, you * have to start it up like this:</p> * * <pre>starling.start();</pre> * * <p>It will now render the contents of the "Game" class in the frame rate that is set up for * the application (as defined in the Flash stage).</p> * * <strong>Context3D Profiles</strong> * * <p>Stage3D supports different rendering profiles, and Starling works with all of them. The * last parameter of the Starling constructor allows you to choose which profile you want. * The following profiles are available:</p> * * <ul> * <li>BASELINE_CONSTRAINED: provides the broadest hardware reach. If you develop for the * browser, this is the profile you should test with.</li> * <li>BASELINE: recommend for any mobile application, as it allows Starling to use a more * memory efficient texture type (RectangleTextures). It also supports more complex * AGAL code.</li> * <li>BASELINE_EXTENDED: adds support for textures up to 4096x4096 pixels. This is * especially useful on mobile devices with very high resolutions.</li> * <li>STANDARD_CONSTRAINED, STANDARD, STANDARD_EXTENDED: each provide more AGAL features, * among other things. Most Starling games will not gain much from them.</li> * </ul> * * <p>The recommendation is to deploy your app with the profile "auto" (which makes Starling * pick the best available of those), but to test it in all available profiles.</p> * * <strong>Accessing the Starling object</strong> * * <p>From within your application, you can access the current Starling object anytime * through the static method <code>Starling.current</code>. It will return the active Starling * instance (most applications will only have one Starling object, anyway).</p> * * <strong>Viewport</strong> * * <p>The area the Starling content is rendered into is, per default, the complete size of the * stage. You can, however, use the "viewPort" property to change it. This can be useful * when you want to render only into a part of the screen, or if the player size changes. For * the latter, you can listen to the RESIZE-event dispatched by the Starling * stage.</p> * * <strong>Native overlay</strong> * * <p>Sometimes you will want to display native Flash content on top of Starling. That's what the * <code>nativeOverlay</code> property is for. It returns a Flash Sprite lying directly * on top of the Starling content. You can add conventional Flash objects to that overlay.</p> * * <p>Beware, though, that conventional Flash content on top of 3D content can lead to * performance penalties on some (mobile) platforms. For that reason, always remove all child * objects from the overlay when you don't need them any longer.</p> * * <strong>Multitouch</strong> * * <p>Starling supports multitouch input on devices that provide it. During development, * where most of us are working with a conventional mouse and keyboard, Starling can simulate * multitouch events with the help of the "Shift" and "Ctrl" (Mac: "Cmd") keys. Activate * this feature by enabling the <code>simulateMultitouch</code> property.</p> * * <strong>Skipping Unchanged Frames</strong> * * <p>It happens surprisingly often in an app or game that a scene stays completely static for * several frames. So why redraw the stage at all in those situations? That's exactly the * point of the <code>skipUnchangedFrames</code>-property. If enabled, static scenes are * recognized as such and the back buffer is simply left as it is. On a mobile device, the * impact of this feature can't be overestimated! There's simply no better way to enhance * battery life. Make it a habit to always activate it; look at the documentation of the * corresponding property for details.</p> * * <strong>Handling a lost render context</strong> * * <p>On some operating systems and under certain conditions (e.g. returning from system * sleep), Starling's stage3D render context may be lost. Starling will try to recover * from a lost context automatically; to be able to do this, it will cache textures in * RAM. This will take up quite a bit of extra memory, though, which might be problematic * especially on mobile platforms. To avoid the higher memory footprint, it's recommended * to load your textures with Starling's "AssetManager"; it is smart enough to recreate a * texture directly from its origin.</p> * * <p>In case you want to react to a context loss manually, Starling dispatches an event with * the type "Event.CONTEXT3D_CREATE" when the context is restored, and textures will execute * their <code>root.onRestore</code> callback, to which you can attach your own logic. * Refer to the "Texture" class for more information.</p> * * <strong>Sharing a 3D Context</strong> * * <p>Per default, Starling handles the Stage3D context itself. If you want to combine * Starling with another Stage3D engine, however, this may not be what you want. In this case, * you can make use of the <code>shareContext</code> property:</p> * * <ol> * <li>Manually create and configure a context3D object that both frameworks can work with * (ideally through <code>RenderUtil.requestContext3D</code> and * <code>context.configureBackBuffer</code>).</li> * <li>Initialize Starling with the stage3D instance that contains that configured context. * This will automatically enable <code>shareContext</code>.</li> * <li>Call <code>start()</code> on your Starling instance (as usual). This will make * Starling queue input events (keyboard/mouse/touch).</li> * <li>Create a game loop (e.g. using the native <code>ENTER_FRAME</code> event) and let it * call Starling's <code>nextFrame</code> as well as the equivalent method of the other * Stage3D engine. Surround those calls with <code>context.clear()</code> and * <code>context.present()</code>.</li> * </ol> * * <p>The Starling wiki contains a <a href="http://goo.gl/BsXzw">tutorial</a> with more * information about this topic.</p> * * @see starling.utils.AssetManager * @see starling.textures.Texture * */ public class Starling extends EventDispatcher { /** The version of the Starling framework. */ public static const VERSION:String = "2.7"; // members private var _stage:Stage; // starling.display.stage! private var _rootClass:Class; private var _root:DisplayObject; private var _juggler:Juggler; private var _painter:Painter; private var _touchProcessor:TouchProcessor; private var _defaultTextureSmoothing:String; private var _antiAliasing:int; private var _frameTimestamp:Number; private var _frameID:uint; private var _leftMouseDown:Boolean; private var _statsDisplay:StatsDisplay; private var _statsDisplayAlign:Object; private var _started:Boolean; private var _rendering:Boolean; private var _supportHighResolutions:Boolean; private var _supportBrowserZoom:Boolean; private var _skipUnchangedFrames:Boolean; private var _showStats:Boolean; private var _supportsCursor:Boolean; private var _multitouchEnabled:Boolean; private var _viewPort:Rectangle; private var _previousViewPort:Rectangle; private var _clippedViewPort:Rectangle; private var _nativeStage:flash.display.Stage; private var _nativeStageEmpty:Boolean; private var _nativeOverlay:Sprite; private static var sCurrent:Starling; private static var sAll:Vector.<Starling> = new <Starling>[]; // construction /** Creates a new Starling instance. * @param rootClass A subclass of 'starling.display.DisplayObject'. It will be created * as soon as initialization is finished and will become the first child * of the Starling stage. Pass <code>null</code> if you don't want to * create a root object right away. (You can use the * <code>rootClass</code> property later to make that happen.) * @param stage The Flash (2D) stage. * @param viewPort A rectangle describing the area into which the content will be * rendered. Default: stage size * @param stage3D The Stage3D object into which the content will be rendered. If it * already contains a context, <code>sharedContext</code> will be set * to <code>true</code>. Default: the first available Stage3D. * @param renderMode The Context3D render mode that should be requested. * Use this parameter if you want to force "software" rendering. * @param profile The Context3D profile that should be requested. * * <ul> * <li>If you pass a profile String, this profile is enforced.</li> * <li>Pass an Array of profiles to make Starling pick the first * one that works (starting with the first array element).</li> * <li>Pass the String "auto" to make Starling pick the best available * profile automatically.</li> * </ul> */ public function Starling(rootClass:Class, stage:flash.display.Stage, viewPort:Rectangle=null, stage3D:Stage3D=null, renderMode:String="auto", profile:Object="auto") { if (stage == null) throw new ArgumentError("Stage must not be null"); if (viewPort == null) viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); if (stage3D == null) stage3D = stage.stage3Ds[0]; // TODO it might make sense to exchange the 'renderMode' and 'profile' parameters. SystemUtil.initialize(); sAll.push(this); makeCurrent(); _rootClass = rootClass; _viewPort = viewPort; _previousViewPort = new Rectangle(); _stage = new Stage(viewPort.width, viewPort.height, stage.color); _nativeOverlay = new Sprite(); _nativeStage = stage; _nativeStage.addChild(_nativeOverlay); _touchProcessor = new TouchProcessor(_stage); _touchProcessor.discardSystemGestures = !SystemUtil.isDesktop; _juggler = new Juggler(); _antiAliasing = 0; _defaultTextureSmoothing = TextureSmoothing.BILINEAR; _supportHighResolutions = false; _painter = new Painter(stage3D); _frameTimestamp = getTimer() / 1000.0; _frameID = 1; _supportsCursor = Mouse.supportsCursor || Capabilities.os.indexOf("Windows") == 0; _statsDisplayAlign = {}; // register appropriate touch/mouse event handlers setMultitouchEnabled(Multitouch.inputMode == MultitouchInputMode.TOUCH_POINT, true); // make the native overlay behave just like one would expect intuitively nativeOverlayBlocksTouches = true; // all other modes are problematic in Starling, so we force those here stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; // register other event handlers stage.addEventListener(Event.ENTER_FRAME, onEnterFrame, false, 0, true); stage.addEventListener(KeyboardEvent.KEY_DOWN, onKey, false, 0, true); stage.addEventListener(KeyboardEvent.KEY_UP, onKey, false, 0, true); stage.addEventListener(Event.RESIZE, onResize, false, 0, true); stage.addEventListener(Event.MOUSE_LEAVE, onMouseLeave, false, 0, true); stage.addEventListener(Event.ACTIVATE, onActivate, false, 0, true); stage3D.addEventListener(Event.CONTEXT3D_CREATE, onContextCreated, false, 10, true); stage3D.addEventListener(ErrorEvent.ERROR, onStage3DError, false, 10, true); var runtimeVersion:int = parseInt(SystemUtil.version.split(",").shift()); if (runtimeVersion < 19) { var runtime:String = SystemUtil.isAIR ? "Adobe AIR" : "Flash Player"; stopWithFatalError( "Your " + runtime + " installation is outdated. " + "This software requires at least version 19."); } else if (_painter.shareContext) { setTimeout(initialize, 1); // we don't call it right away, because Starling should // behave the same way with or without a shared context } else { _painter.requestContext3D(renderMode, profile); } } /** Disposes all children of the stage and the render context; removes all registered * event listeners. */ public function dispose():void { stop(true); _nativeStage.removeEventListener(Event.ENTER_FRAME, onEnterFrame, false); _nativeStage.removeEventListener(KeyboardEvent.KEY_DOWN, onKey, false); _nativeStage.removeEventListener(KeyboardEvent.KEY_UP, onKey, false); _nativeStage.removeEventListener(Event.RESIZE, onResize, false); _nativeStage.removeEventListener(Event.MOUSE_LEAVE, onMouseLeave, false); _nativeStage.removeEventListener(Event.BROWSER_ZOOM_CHANGE, onBrowserZoomChange, false); _nativeStage.removeChild(_nativeOverlay); stage3D.removeEventListener(Event.CONTEXT3D_CREATE, onContextCreated, false); stage3D.removeEventListener(Event.CONTEXT3D_CREATE, onContextRestored, false); stage3D.removeEventListener(ErrorEvent.ERROR, onStage3DError, false); for each (var touchEventType:String in getTouchEventTypes(_multitouchEnabled)) _nativeStage.removeEventListener(touchEventType, onTouch, false); _touchProcessor.dispose(); _stage.dispose(); _painter.dispose(); var index:int = sAll.indexOf(this); if (index != -1) sAll.removeAt(index); if (sCurrent == this) sCurrent = null; } // functions private function initialize():void { makeCurrent(); updateViewPort(true); // ideal time: after viewPort setup, before root creation dispatchEventWith(Event.CONTEXT3D_CREATE, false, context); initializeRoot(); _frameTimestamp = getTimer() / 1000.0; } private function initializeRoot():void { if (_root == null && _rootClass != null) { _root = new _rootClass() as DisplayObject; if (_root == null) throw new Error("Invalid root class: " + _rootClass); _stage.addChildAt(_root, 0); dispatchEventWith(starling.events.Event.ROOT_CREATED, false, _root); } } /** Calls <code>advanceTime()</code> (with the time that has passed since the last frame) * and <code>render()</code>. */ public function nextFrame():void { var now:Number = getTimer() / 1000.0; var passedTime:Number = now - _frameTimestamp; _frameTimestamp = now; // to avoid overloading time-based animations, the maximum delta is truncated. if (passedTime > 1.0) passedTime = 1.0; // after about 25 days, 'getTimer()' will roll over. A rare event, but still ... if (passedTime < 0.0) passedTime = 1.0 / _nativeStage.frameRate; advanceTime(passedTime); render(); } /** Dispatches ENTER_FRAME events on the display list, advances the Juggler * and processes touches. */ public function advanceTime(passedTime:Number):void { if (!contextValid) return; makeCurrent(); _touchProcessor.advanceTime(passedTime); _stage.advanceTime(passedTime); _juggler.advanceTime(passedTime); } /** Renders the complete display list. Before rendering, the context is cleared; afterwards, * it is presented (to avoid this, enable <code>shareContext</code>). * * <p>This method also dispatches an <code>Event.RENDER</code>-event on the Starling * instance. That's the last opportunity to make changes before the display list is * rendered.</p> */ public function render():void { if (!contextValid) return; makeCurrent(); updateViewPort(); var doRedraw:Boolean = _stage.requiresRedraw || mustAlwaysRender; if (doRedraw) { dispatchEventWith(starling.events.Event.RENDER); var shareContext:Boolean = _painter.shareContext; var scaleX:Number = _viewPort.width / _stage.stageWidth; var scaleY:Number = _viewPort.height / _stage.stageHeight; var stageColor:uint = _stage.color; _painter.nextFrame(); _painter.pixelSize = 1.0 / contentScaleFactor; _painter.state.setProjectionMatrix( _viewPort.x < 0 ? -_viewPort.x / scaleX : 0.0, _viewPort.y < 0 ? -_viewPort.y / scaleY : 0.0, _clippedViewPort.width / scaleX, _clippedViewPort.height / scaleY, _stage.stageWidth, _stage.stageHeight, _stage.cameraPosition); if (!shareContext) _painter.clear(stageColor, Color.getAlpha(stageColor)); _stage.render(_painter); VertexData.starling_internal::unassignDomainMemory(); _painter.finishFrame(); _painter.frameID = ++_frameID; if (!shareContext) _painter.present(); } else dispatchEventWith(starling.events.Event.SKIP_FRAME); if (_statsDisplay) _statsDisplay.drawCount = _painter.drawCount; } private function updateViewPort(forceUpdate:Boolean=false):void { // the last set viewport is stored in a variable; that way, people can modify the // viewPort directly (without a copy) and we still know if it has changed. if (forceUpdate || !RectangleUtil.compare(_viewPort, _previousViewPort)) { _previousViewPort.setTo(_viewPort.x, _viewPort.y, _viewPort.width, _viewPort.height); // Constrained mode requires that the viewport is within the native stage bounds; // thus, we use a clipped viewport when configuring the back buffer. (In baseline // mode, that's not necessary, but it does not hurt either.) updateClippedViewPort(); updateStatsDisplayPosition(); var contentScaleFactor:Number = _supportHighResolutions ? _nativeStage.contentsScaleFactor : 1.0; if (_supportBrowserZoom) contentScaleFactor *= _nativeStage.browserZoomFactor; _painter.configureBackBuffer(_clippedViewPort, contentScaleFactor, _antiAliasing, true, _supportBrowserZoom); setRequiresRedraw(); } } private function updateClippedViewPort():void { var stageBounds:Rectangle = Pool.getRectangle(0, 0, _nativeStage.stageWidth, _nativeStage.stageHeight); _clippedViewPort = RectangleUtil.intersect(_viewPort, stageBounds, _clippedViewPort); if (_clippedViewPort.width < 32) _clippedViewPort.width = 32; if (_clippedViewPort.height < 32) _clippedViewPort.height = 32; Pool.putRectangle(stageBounds); } private function updateNativeOverlay():void { _nativeOverlay.x = _viewPort.x; _nativeOverlay.y = _viewPort.y; _nativeOverlay.scaleX = _viewPort.width / _stage.stageWidth; _nativeOverlay.scaleY = _viewPort.height / _stage.stageHeight; } /** Stops Starling right away and displays an error message on the native overlay. * This method will also cause Starling to dispatch a FATAL_ERROR event. */ public function stopWithFatalError(message:String):void { var background:Shape = new Shape(); background.graphics.beginFill(0x0, 0.8); background.graphics.drawRect(0, 0, _stage.stageWidth, _stage.stageHeight); background.graphics.endFill(); var textField:TextField = new TextField(); var textFormat:TextFormat = new TextFormat("Verdana", 14, 0xFFFFFF); textFormat.align = TextFormatAlign.CENTER; textField.defaultTextFormat = textFormat; textField.wordWrap = true; textField.width = _stage.stageWidth * 0.75; textField.autoSize = TextFieldAutoSize.CENTER; textField.text = message; textField.x = (_stage.stageWidth - textField.width) / 2; textField.y = (_stage.stageHeight - textField.height) / 2; textField.background = true; textField.backgroundColor = 0x550000; updateNativeOverlay(); nativeOverlay.addChild(background); nativeOverlay.addChild(textField); stop(true); trace("[Starling]", message); dispatchEventWith(starling.events.Event.FATAL_ERROR, false, message); } /** Make this Starling instance the <code>current</code> one. */ public function makeCurrent():void { sCurrent = this; } /** As soon as Starling is started, it will queue input events (keyboard/mouse/touch); * furthermore, the method <code>nextFrame</code> will be called once per Flash Player * frame. (Except when <code>shareContext</code> is enabled: in that case, you have to * call that method manually.) */ public function start():void { _started = _rendering = true; _frameTimestamp = getTimer() / 1000.0; } /** Stops all logic and input processing, effectively freezing the app in its current state. * Per default, rendering will continue: that's because the classic display list * is only updated when stage3D is. (If Starling stopped rendering, conventional Flash * contents would freeze, as well.) * * <p>However, if you don't need classic Flash contents, you can stop rendering, too. * On some mobile systems (e.g. iOS), you are even required to do so if you have * activated background code execution.</p> */ public function stop(suspendRendering:Boolean=false):void { _started = false; _rendering = !suspendRendering; } /** Makes sure that the next frame is actually rendered. * * <p>When <code>skipUnchangedFrames</code> is enabled, some situations require that you * manually force a redraw, e.g. when a RenderTexture is changed. This method is the * easiest way to do so; it's just a shortcut to <code>stage.setRequiresRedraw()</code>. * </p> */ public function setRequiresRedraw():void { _stage.setRequiresRedraw(); } // event handlers private function onStage3DError(event:ErrorEvent):void { if (event.errorID == 3702) { var mode:String = Capabilities.playerType == "Desktop" ? "renderMode" : "wmode"; stopWithFatalError("Context3D not available! Possible reasons: wrong " + mode + " or missing device support."); } else stopWithFatalError("Stage3D error: " + event.text); } private function onContextCreated(event:Event):void { stage3D.removeEventListener(Event.CONTEXT3D_CREATE, onContextCreated); stage3D.addEventListener(Event.CONTEXT3D_CREATE, onContextRestored, false, 10, true); trace("[Starling] Context ready. Display Driver:", context.driverInfo); initialize(); } private function onContextRestored(event:Event):void { trace("[Starling] Context restored."); updateViewPort(true); _painter.setupContextDefaults(); dispatchEventWith(Event.CONTEXT3D_CREATE, false, context); } private function onEnterFrame(event:Event):void { // On mobile, the native display list is only updated on stage3D draw calls. // Thus, we render even when Starling is paused. if (!shareContext) { if (_started) nextFrame(); else if (_rendering) render(); } updateNativeOverlay(); } private function onActivate(event:Event):void { // with 'skipUnchangedFrames' enabled, a forced redraw is required when the app // is restored on some platforms (namely Windows with BASELINE_CONSTRAINED profile // and some Android versions). setTimeout(setRequiresRedraw, 100); } private function onKey(event:KeyboardEvent):void { if (!_started) return; var keyEvent:starling.events.KeyboardEvent = new starling.events.KeyboardEvent( event.type, event.charCode, event.keyCode, event.keyLocation, event.ctrlKey, event.altKey, event.shiftKey); makeCurrent(); _stage.dispatchEvent(keyEvent); if (keyEvent.isDefaultPrevented()) event.preventDefault(); } private function onResize(event:Event):void { var stageWidth:int = event.target.stageWidth; var stageHeight:int = event.target.stageHeight; if (contextValid) dispatchResizeEvent(); else addEventListener(Event.CONTEXT3D_CREATE, dispatchResizeEvent); function dispatchResizeEvent():void { // on Android, the context is not valid while we're resizing. To avoid problems // with user code, we delay the event dispatching until it becomes valid again. makeCurrent(); removeEventListener(Event.CONTEXT3D_CREATE, dispatchResizeEvent); _stage.dispatchEvent(new ResizeEvent(Event.RESIZE, stageWidth, stageHeight)); } } private function onBrowserZoomChange(event:Event):void { _painter.refreshBackBufferSize( _nativeStage.contentsScaleFactor * _nativeStage.browserZoomFactor); } private function onMouseLeave(event:Event):void { _touchProcessor.enqueueMouseLeftStage(); } private function onTouch(event:Event):void { if (!_started) return; var globalX:Number; var globalY:Number; var touchID:int; var phase:String; var pressure:Number = 1.0; var width:Number = 1.0; var height:Number = 1.0; // figure out general touch properties if (event is MouseEvent) { var mouseEvent:MouseEvent = event as MouseEvent; globalX = mouseEvent.stageX; globalY = mouseEvent.stageY; touchID = 0; // MouseEvent.buttonDown returns true for both left and right button (AIR supports // the right mouse button). We only want to react on the left button for now, // so we have to save the state for the left button manually. if (event.type == MouseEvent.MOUSE_DOWN) _leftMouseDown = true; else if (event.type == MouseEvent.MOUSE_UP) _leftMouseDown = false; } else { var touchEvent:TouchEvent = event as TouchEvent; // On a system that supports both mouse and touch input, the primary touch point // is dispatched as mouse event as well. Since we don't want to listen to that // event twice, we ignore the primary touch in that case. if (_supportsCursor && touchEvent.isPrimaryTouchPoint) return; else { globalX = touchEvent.stageX; globalY = touchEvent.stageY; touchID = touchEvent.touchPointID; pressure = touchEvent.pressure; width = touchEvent.sizeX; height = touchEvent.sizeY; } } // figure out touch phase switch (event.type) { case TouchEvent.TOUCH_BEGIN: phase = TouchPhase.BEGAN; break; case TouchEvent.TOUCH_MOVE: phase = TouchPhase.MOVED; break; case TouchEvent.TOUCH_END: phase = TouchPhase.ENDED; break; case MouseEvent.MOUSE_DOWN: phase = TouchPhase.BEGAN; break; case MouseEvent.MOUSE_UP: phase = TouchPhase.ENDED; break; case MouseEvent.MOUSE_MOVE: phase = (_leftMouseDown ? TouchPhase.MOVED : TouchPhase.HOVER); break; } // move position into viewport bounds globalX = _stage.stageWidth * (globalX - _viewPort.x) / _viewPort.width; globalY = _stage.stageHeight * (globalY - _viewPort.y) / _viewPort.height; // enqueue touch in touch processor _touchProcessor.enqueue(touchID, phase, globalX, globalY, pressure, width, height); // allow objects that depend on mouse-over state to be updated immediately if (event.type == MouseEvent.MOUSE_UP && _supportsCursor) _touchProcessor.enqueue(touchID, TouchPhase.HOVER, globalX, globalY); } private function hitTestNativeOverlay(localX:Number, localY:Number):Boolean { if (_nativeOverlay.numChildren) { var globalPos:Point = Pool.getPoint(); var matrix:Matrix = Pool.getMatrix( _nativeOverlay.scaleX, 0, 0, _nativeOverlay.scaleY, _nativeOverlay.x, _nativeOverlay.y); MatrixUtil.transformCoords(matrix, localX, localY, globalPos); var result:Boolean = _nativeOverlay.hitTestPoint(globalPos.x, globalPos.y, true); Pool.putPoint(globalPos); Pool.putMatrix(matrix); return result; } else return false; } private function setMultitouchEnabled(value:Boolean, forceUpdate:Boolean=false):void { if (forceUpdate || value != _multitouchEnabled) { var oldEventTypes:Array = getTouchEventTypes(_multitouchEnabled); var newEventTypes:Array = getTouchEventTypes(value); for each (var oldEventType:String in oldEventTypes) _nativeStage.removeEventListener(oldEventType, onTouch); for each (var newEventType:String in newEventTypes) _nativeStage.addEventListener(newEventType, onTouch, false, 0, true); _touchProcessor.cancelTouches(); _multitouchEnabled = value; } } private function getTouchEventTypes(multitouchEnabled:Boolean):Array { var types:Array = []; if (multitouchEnabled) types.push(TouchEvent.TOUCH_BEGIN, TouchEvent.TOUCH_MOVE, TouchEvent.TOUCH_END); if (!multitouchEnabled || _supportsCursor) types.push(MouseEvent.MOUSE_DOWN, MouseEvent.MOUSE_MOVE, MouseEvent.MOUSE_UP); return types; } private function get mustAlwaysRender():Boolean { // On mobile, and in some browsers with the "baselineConstrained" profile, the // standard display list is only rendered after calling "context.present()". // In such a case, we cannot omit frames if there is any content on the stage. if (!_skipUnchangedFrames || _painter.shareContext) return true; else if (SystemUtil.isDesktop && profile != Context3DProfile.BASELINE_CONSTRAINED) return false; else { // Rendering can be skipped when both this and previous frame are empty. var nativeStageEmpty:Boolean = isNativeDisplayObjectEmpty(_nativeStage); var mustAlwaysRender:Boolean = !nativeStageEmpty || !_nativeStageEmpty; _nativeStageEmpty = nativeStageEmpty; return mustAlwaysRender; } } // properties /** Indicates if this Starling instance is started. */ public function get isStarted():Boolean { return _started; } /** The default juggler of this instance. Will be advanced once per frame. */ public function get juggler():Juggler { return _juggler; } /** The painter, which is used for all rendering. The same instance is passed to all * <code>render</code>methods each frame. */ public function get painter():Painter { return _painter; } /** The render context of this instance. */ public function get context():Context3D { return _painter.context; } /** Indicates if multitouch simulation with "Shift" and "Ctrl"/"Cmd"-keys is enabled. * @default false */ public function get simulateMultitouch():Boolean { return _touchProcessor.simulateMultitouch; } public function set simulateMultitouch(value:Boolean):void { _touchProcessor.simulateMultitouch = value; } /** Indicates if Stage3D render methods will report errors. It's recommended to activate * this when writing custom rendering code (shaders, etc.), since you'll get more detailed * error messages. However, it has a very negative impact on performance, and it prevents * ATF textures from being restored on a context loss. Never activate for release builds! * * @default false */ public function get enableErrorChecking():Boolean { return _painter.enableErrorChecking; } public function set enableErrorChecking(value:Boolean):void { _painter.enableErrorChecking = value; } /** The anti-aliasing level. 0 - none, 16 - maximum. @default 0 */ public function get antiAliasing():int { return _antiAliasing; } public function set antiAliasing(value:int):void { if (_antiAliasing != value) { _antiAliasing = value; if (contextValid) updateViewPort(true); } } /** The default texture smoothing. This value will be used as the default value when * creating 'MeshStyle', 'FragmentFilter' or 'FilterEffect'. * Changing it won't have any impact on the existing meshes & filters. * @default "bilinear" */ public function get defaultTextureSmoothing():String { return _defaultTextureSmoothing; } public function set defaultTextureSmoothing(value:String):void { if (!TextureSmoothing.isValid(value)) throw new ArgumentError("Invalid texture smoothing: " + value); _defaultTextureSmoothing = value; } /** The viewport into which Starling contents will be rendered. */ public function get viewPort():Rectangle { return _viewPort; } public function set viewPort(value:Rectangle):void { _viewPort.copyFrom(value); } /** The ratio between viewPort width and stage width. Useful for choosing a different * set of textures depending on the display resolution. */ public function get contentScaleFactor():Number { return (_viewPort.width * _painter.backBufferScaleFactor) / _stage.stageWidth; } /** A Flash Sprite placed directly on top of the Starling content. Use it to display native * Flash components. */ public function get nativeOverlay():Sprite { return _nativeOverlay; } /** If enabled, touches or mouse events on the native overlay won't be propagated to * Starling. @default true */ public function get nativeOverlayBlocksTouches():Boolean { return _touchProcessor.occlusionTest != null; } public function set nativeOverlayBlocksTouches(value:Boolean):void { if (value != this.nativeOverlayBlocksTouches) _touchProcessor.occlusionTest = value ? hitTestNativeOverlay : null; } /** Indicates if a small statistics box (with FPS, memory usage and draw count) is * displayed. * * <p>When the box turns dark green, more than 50% of the frames since the box' last * update could skip rendering altogether. This will only happen if the property * <code>skipUnchangedFrames</code> is enabled.</p> * * <p>Beware that the memory usage should be taken with a grain of salt. The value is * determined via <code>System.totalMemory</code> and does not take texture memory * into account. It is recommended to use Adobe Scout for reliable and comprehensive * memory analysis.</p> */ public function get showStats():Boolean { return _showStats; } public function set showStats(value:Boolean):void { _showStats = value; if (value) { showStatsAt(_statsDisplayAlign.horizontal || "left", _statsDisplayAlign.vertical || "top"); } else if (_statsDisplay) { _statsDisplay.removeFromParent(); } } /** Displays the statistics box at a certain position. */ public function showStatsAt(horizontalAlign:String="left", verticalAlign:String="top", scale:Number=1):void { _showStats = true; _statsDisplayAlign.horizontal = horizontalAlign; _statsDisplayAlign.vertical = verticalAlign; if (context == null) { // Starling is not yet ready - we postpone this until it's initialized. addEventListener(starling.events.Event.ROOT_CREATED, onRootCreated); } else { if (_statsDisplay == null) { _statsDisplay = new StatsDisplay(); _statsDisplay.touchable = false; } _stage.addChild(_statsDisplay); _statsDisplay.scaleX = _statsDisplay.scaleY = scale; _statsDisplay.showSkipped = _skipUnchangedFrames; updateClippedViewPort(); updateStatsDisplayPosition(); } function onRootCreated():void { if (_showStats) showStatsAt(horizontalAlign, verticalAlign, scale); removeEventListener(starling.events.Event.ROOT_CREATED, onRootCreated); } } private function updateStatsDisplayPosition():void { if (!_showStats || _statsDisplay == null) return; // The stats display must always be visible, i.e. inside the clipped viewPort. // So we take viewPort clipping into account when calculating its position. var horizontalAlign:String = _statsDisplayAlign.horizontal; var verticalAlign:String = _statsDisplayAlign.vertical; var scaleX:Number = _viewPort.width / _stage.stageWidth; var scaleY:Number = _viewPort.height / _stage.stageHeight; var clipping:Rectangle = Pool.getRectangle( _viewPort.x < 0 ? -_viewPort.x / scaleX : 0.0, _viewPort.y < 0 ? -_viewPort.y / scaleY : 0.0, _clippedViewPort.width / scaleX, _clippedViewPort.height / scaleY); if (horizontalAlign == Align.LEFT) _statsDisplay.x = clipping.x; else if (horizontalAlign == Align.RIGHT) _statsDisplay.x = clipping.right - _statsDisplay.width; else if (horizontalAlign == Align.CENTER) _statsDisplay.x = (clipping.right - _statsDisplay.width) / 2; else throw new ArgumentError("Invalid horizontal alignment: " + horizontalAlign); if (verticalAlign == Align.TOP) _statsDisplay.y = clipping.y; else if (verticalAlign == Align.BOTTOM) _statsDisplay.y = clipping.bottom - _statsDisplay.height; else if (verticalAlign == Align.CENTER) _statsDisplay.y = (clipping.bottom - _statsDisplay.height) / 2; else throw new ArgumentError("Invalid vertical alignment: " + verticalAlign); Pool.putRectangle(clipping); } /** The Starling stage object, which is the root of the display tree that is rendered. */ public function get stage():Stage { return _stage; } /** The Flash Stage3D object Starling renders into. */ public function get stage3D():Stage3D { return _painter.stage3D; } /** The Flash (2D) stage object Starling renders beneath. */ public function get nativeStage():flash.display.Stage { return _nativeStage; } /** The instance of the root class provided in the constructor. Available as soon as * the event 'ROOT_CREATED' has been dispatched. */ public function get root():DisplayObject { return _root; } /** The class that will be instantiated by Starling as the 'root' display object. * Must be a subclass of 'starling.display.DisplayObject'. * * <p>If you passed <code>null</code> as first parameter to the Starling constructor, * you can use this property to set the root class at a later time. As soon as the class * is instantiated, Starling will dispatch a <code>ROOT_CREATED</code> event.</p> * * <p>Beware: you cannot change the root class once the root object has been * instantiated.</p> */ public function get rootClass():Class { return _rootClass; } public function set rootClass(value:Class):void { if (_rootClass != null && _root != null) throw new Error("Root class may not change after root has been instantiated"); else if (_rootClass == null) { _rootClass = value; if (context) initializeRoot(); } } /** Indicates if another Starling instance (or another Stage3D framework altogether) * uses the same render context. If enabled, Starling will not execute any destructive * context operations (e.g. not call 'configureBackBuffer', 'clear', 'present', etc. * This has to be done manually, then. @default false */ public function get shareContext():Boolean { return _painter.shareContext; } public function set shareContext(value:Boolean):void { if (!value) _previousViewPort.setEmpty(); // forces back buffer update _painter.shareContext = value; } /** The Context3D profile of the current render context, or <code>null</code> * if the context has not been created yet. */ public function get profile():String { return _painter.profile; } /** Indicates that if the device supports HiDPI screens Starling will attempt to allocate * a larger back buffer than indicated via the viewPort size. Note that this is used * on Desktop only; mobile AIR apps still use the "requestedDisplayResolution" parameter * the application descriptor XML. @default false */ public function get supportHighResolutions():Boolean { return _supportHighResolutions; } public function set supportHighResolutions(value:Boolean):void { if (_supportHighResolutions != value) { _supportHighResolutions = value; if (contextValid) updateViewPort(true); } } /** If enabled, the Stage3D back buffer will change its size according to the browser zoom * value - similar to what's done when "supportHighResolutions" is enabled. The resolution * is updated on the fly when the zoom factor changes. Only relevant for the browser plugin. * @default false */ public function get supportBrowserZoom():Boolean { return _supportBrowserZoom; } public function set supportBrowserZoom(value:Boolean):void { if (_supportBrowserZoom != value) { _supportBrowserZoom = value; if (contextValid) updateViewPort(true); if (value) _nativeStage.addEventListener( Event.BROWSER_ZOOM_CHANGE, onBrowserZoomChange, false, 0, true); else _nativeStage.removeEventListener( Event.BROWSER_ZOOM_CHANGE, onBrowserZoomChange, false); } } /** When enabled, Starling will skip rendering the stage if it hasn't changed since the * last frame. This is great for apps that remain static from time to time, since it will * greatly reduce power consumption. You should activate this whenever possible! * * <p>The reason why it's disabled by default is just that it causes problems with Render- * and VideoTextures. When you use those, you either have to disable this property * temporarily, or call <code>setRequiresRedraw()</code> (ideally on the stage) whenever * those textures are changing. Otherwise, the changes won't show up.</p> * * @default false */ public function get skipUnchangedFrames():Boolean { return _skipUnchangedFrames; } public function set skipUnchangedFrames(value:Boolean):void { _skipUnchangedFrames = value; _nativeStageEmpty = false; // required by 'mustAlwaysRender' if (_statsDisplay) _statsDisplay.showSkipped = value; } /** The TouchProcessor is passed all mouse and touch input and is responsible for * dispatching TouchEvents to the Starling display tree. If you want to handle these * types of input manually, pass your own custom subclass to this property. */ public function get touchProcessor():TouchProcessor { return _touchProcessor; } public function set touchProcessor(value:TouchProcessor):void { if (value == null) throw new ArgumentError("TouchProcessor must not be null"); else if (value != _touchProcessor) { _touchProcessor.dispose(); _touchProcessor = value; } } /** When enabled, all touches that start very close to the screen edges are discarded. * On mobile, such touches often indicate swipes that are meant to use OS features. * Per default, margins of 15 points at the top, bottom, and left side of the screen are * checked. Call <code>starling.touchProcessor.setSystemGestureMargins()</code> to adapt * the margins in each direction. @default true on mobile, false on desktop */ public function get discardSystemGestures():Boolean { return _touchProcessor.discardSystemGestures; } public function set discardSystemGestures(value:Boolean):void { _touchProcessor.discardSystemGestures = value; } /** The number of frames that have been rendered since this instance was created. */ public function get frameID():uint { return _frameID; } /** Indicates if the Context3D object is currently valid (i.e. it hasn't been lost or * disposed). */ public function get contextValid():Boolean { return _painter.contextValid; } // static properties /** The currently active Starling instance. */ public static function get current():Starling { return sCurrent; } /** All Starling instances. <p>CAUTION: not a copy, but the actual object! Do not modify!</p> */ public static function get all():Vector.<Starling> { return sAll; } /** The render context of the currently active Starling instance. */ public static function get context():Context3D { return sCurrent ? sCurrent.context : null; } /** The default juggler of the currently active Starling instance. */ public static function get juggler():Juggler { return sCurrent ? sCurrent._juggler : null; } /** The painter used for all rendering of the currently active Starling instance. */ public static function get painter():Painter { return sCurrent ? sCurrent._painter : null; } /** The contentScaleFactor of the currently active Starling instance. */ public static function get contentScaleFactor():Number { return sCurrent ? sCurrent.contentScaleFactor : 1.0; } /** Indicates if multitouch input should be supported. You can enable or disable * multitouch at any time; just beware that any current touches will be cancelled. */ public static function get multitouchEnabled():Boolean { var enabled:Boolean = Multitouch.inputMode == MultitouchInputMode.TOUCH_POINT; var outOfSync:Boolean = false; for each (var star:Starling in sAll) if (star._multitouchEnabled != enabled) outOfSync = true; if (outOfSync) trace("[Starling] Warning: multitouch settings are out of sync. Always set " + "'Starling.multitouchEnabled' instead of 'Multitouch.inputMode'."); return enabled; } public static function set multitouchEnabled(value:Boolean):void { var wasEnabled:Boolean = Multitouch.inputMode == MultitouchInputMode.TOUCH_POINT; Multitouch.inputMode = value ? MultitouchInputMode.TOUCH_POINT : MultitouchInputMode.NONE; var isEnabled:Boolean = Multitouch.inputMode == MultitouchInputMode.TOUCH_POINT; if (wasEnabled != isEnabled) { for each (var star:Starling in sAll) star.setMultitouchEnabled(isEnabled); } } /** The number of frames that have been rendered since the current instance was created. */ public static function get frameID():uint { return sCurrent ? sCurrent._frameID : 0; } } } import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; // put here to avoid naming conflicts function isNativeDisplayObjectEmpty(object:DisplayObject):Boolean { if (object == null) return true; else if (object is DisplayObjectContainer) { var container:DisplayObjectContainer = object as DisplayObjectContainer; var numChildren:int = container.numChildren; for (var i:int=0; i<numChildren; ++i) { if (!isNativeDisplayObjectEmpty(container.getChildAt(i))) return false; } return true; } else return !object.visible; }
package org.as3wavsound.sazameki.core { /** * Contains a sound's playback configuration, such as mono / stereo, * sample rate and bit rate. * * @author Takaaki Yamazaki(zk design), * @author Benny Bottema (modified, optimized and cleaned up code) */ public class AudioSetting { // 1 or 2 private var _channels:uint; // 11025, 22050 or 44100 private var _sampleRate:uint; // 8 or 16 private var _bitRate:uint; /** * Constructor: performs some validations on the values being passed in. */ public function AudioSetting(channels:uint = 2, sampleRate:uint = 44100, bitRate:uint = 16) { if (sampleRate != 44100 && sampleRate != 22050 && sampleRate != 11025) { throw new Error("bad sample rate. sample rate must be 44100, 22050 or 11025"); } if (channels != 1 && channels != 2) { throw new Error("channels must be 1 or 2"); } if (bitRate != 16 && bitRate != 8) { throw new Error("bitRate must be 8 or 16"); } _channels=channels; _sampleRate=sampleRate; _bitRate=bitRate; } public function get channels():uint{ return _channels; } public function get sampleRate():uint{ return _sampleRate; } public function get bitRate():uint{ return _bitRate; } } }
intrinsic class flash.text.TextRenderer { static var maxLevel : Number; static function setAdvancedAntialiasingTable( fontName : String, fontStyle: String, colorType : String, advancedAntialiasingTable : Array ) : Void; }
package com.ankamagames.jerakine.interfaces { public interface ICustomUnicNameGetter { function get customUnicName() : String; } }
package age.renderers { /** * 方向渲染器 * @author zhanghaocong * */ public interface IDirectionRenderer { /** * 设置或获取方向,默认是 Direction.RIGHT * @see Direction * @return * */ function get direction():int; function set direction(value:int):void; } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.automation.delegates.controls { import flash.display.DisplayObject; import flash.events.Event; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.ui.Keyboard; import flash.utils.getTimer; import mx.automation.Automation; import mx.automation.AutomationIDPart; import mx.automation.IAutomationObject; import mx.automation.IAutomationObjectHelper; import mx.core.mx_internal; import mx.core.UIComponent; import mx.controls.PopUpButton; import mx.events.DropdownEvent; use namespace mx_internal; [Mixin] /** * * Defines methods and properties required to perform instrumentation for the * PopUpButton control. * * @see mx.controls.PopUpButton * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class PopUpButtonAutomationImpl extends ButtonAutomationImpl { 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(PopUpButton, PopUpButtonAutomationImpl); } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * @param obj PopUpButton object to be automated. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function PopUpButtonAutomationImpl(obj:PopUpButton) { super(obj); obj.addEventListener(DropdownEvent.OPEN, popUpOpenHandler, false, 0, true); obj.addEventListener(DropdownEvent.CLOSE, popUpCloseHandler, false, 0, true); } /** * @private * storage for the owner component */ protected function get popUpButton():PopUpButton { return uiComponent as PopUpButton; } //---------------------------------- // automationName //---------------------------------- /** * @private * We need to override Button's behavior since we don't want * to use a changing label as our automation name * though we're fine with using it for automationValue. */ override public function get automationName():String { return (uiComponent as UIComponent).id; } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ override public function replayAutomatableEvent(event:Event):Boolean { var help:IAutomationObjectHelper = Automation.automationObjectHelper; if (event is DropdownEvent) { if (DropdownEvent(event).triggerEvent is KeyboardEvent) { var kbEvent:KeyboardEvent = new KeyboardEvent(KeyboardEvent.KEY_DOWN); kbEvent.keyCode = event.type == DropdownEvent.OPEN ? Keyboard.DOWN : Keyboard.UP; kbEvent.ctrlKey = true; help.replayKeyboardEvent(uiComponent, kbEvent); } else if (DropdownEvent(event).triggerEvent is MouseEvent) { if ((event.type == DropdownEvent.OPEN && !popUpButton.isShowingPopUp) || (event.type == DropdownEvent.CLOSE && popUpButton.isShowingPopUp)) { var mEvent:MouseEvent = new MouseEvent(MouseEvent.CLICK); mEvent.localX = popUpButton.getUnscaledWidth() - popUpButton.getArrowButtonsWidth(); mEvent.localY = popUpButton.getUnscaledHeight() / 2; super.replayAutomatableEvent(mEvent); } else { return false; } } else { throw new Error(); } var completeTime:Number = getTimer() + popUpButton.getStyle(DropdownEvent(event).type == DropdownEvent.OPEN ? "openDuration": "closeDuration") as Number; help.addSynchronization(function():Boolean { return getTimer() >= completeTime; }); return true; } else { return super.replayAutomatableEvent(event); } } /** * @private */ override public function createAutomationIDPart( child:IAutomationObject):Object { var help:IAutomationObjectHelper = Automation.automationObjectHelper; return help.helpCreateIDPart(uiAutomationObject, child); } /** * @private */ override public function createAutomationIDPartWithRequiredProperties(child:IAutomationObject, properties:Array):Object { var help:IAutomationObjectHelper = Automation.automationObjectHelper; return help ? help.helpCreateIDPartWithRequiredProperties(uiAutomationObject, child,properties) :null; } /** * @private */ override public function resolveAutomationIDPart(part:Object):Array { var help:IAutomationObjectHelper = Automation.automationObjectHelper; return help.helpResolveIDPart(uiAutomationObject, part); } //---------------------------------- // numAutomationChildren //---------------------------------- /** * @private */ override public function get numAutomationChildren():int { var delegate:IAutomationObject = popUpButton.popUp as IAutomationObject; return delegate ? 1 : 0; } /** * @private */ override public function getAutomationChildAt(index:int):IAutomationObject { return popUpButton.popUp as IAutomationObject; } /** * @private */ override public function getAutomationChildren():Array { return [popUpButton.popUp as IAutomationObject]; } //---------------------------------- // automationTabularData //---------------------------------- /** * @private */ override public function get automationTabularData():Object { var delegate:IAutomationObject = (popUpButton.popUp as IAutomationObject); return delegate.automationTabularData; } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function popUpOpenHandler(event:DropdownEvent):void { if (event.triggerEvent) recordAutomatableEvent(event); } /** * @private */ private function popUpCloseHandler(event:DropdownEvent):void { if (event.triggerEvent) { recordAutomatableEvent(event); } } /** * @private */ override protected function clickHandler(event:MouseEvent):void { if (!popUpButton.overArrowButton(event)) super.clickHandler(event); } } }
package com.ankamagames.dofus.network.types.game.character.alignment { import com.ankamagames.jerakine.network.ICustomDataInput; import com.ankamagames.jerakine.network.ICustomDataOutput; import com.ankamagames.jerakine.network.INetworkType; import com.ankamagames.jerakine.network.utils.FuncTree; public class ActorExtendedAlignmentInformations extends ActorAlignmentInformations implements INetworkType { public static const protocolId:uint = 2352; public var honor:uint = 0; public var honorGradeFloor:uint = 0; public var honorNextGradeFloor:uint = 0; public var aggressable:uint = 0; public function ActorExtendedAlignmentInformations() { super(); } override public function getTypeId() : uint { return 2352; } public function initActorExtendedAlignmentInformations(alignmentSide:int = 0, alignmentValue:uint = 0, alignmentGrade:uint = 0, characterPower:Number = 0, honor:uint = 0, honorGradeFloor:uint = 0, honorNextGradeFloor:uint = 0, aggressable:uint = 0) : ActorExtendedAlignmentInformations { super.initActorAlignmentInformations(alignmentSide,alignmentValue,alignmentGrade,characterPower); this.honor = honor; this.honorGradeFloor = honorGradeFloor; this.honorNextGradeFloor = honorNextGradeFloor; this.aggressable = aggressable; return this; } override public function reset() : void { super.reset(); this.honor = 0; this.honorGradeFloor = 0; this.honorNextGradeFloor = 0; this.aggressable = 0; } override public function serialize(output:ICustomDataOutput) : void { this.serializeAs_ActorExtendedAlignmentInformations(output); } public function serializeAs_ActorExtendedAlignmentInformations(output:ICustomDataOutput) : void { super.serializeAs_ActorAlignmentInformations(output); if(this.honor < 0 || this.honor > 20000) { throw new Error("Forbidden value (" + this.honor + ") on element honor."); } output.writeVarShort(this.honor); if(this.honorGradeFloor < 0 || this.honorGradeFloor > 20000) { throw new Error("Forbidden value (" + this.honorGradeFloor + ") on element honorGradeFloor."); } output.writeVarShort(this.honorGradeFloor); if(this.honorNextGradeFloor < 0 || this.honorNextGradeFloor > 20000) { throw new Error("Forbidden value (" + this.honorNextGradeFloor + ") on element honorNextGradeFloor."); } output.writeVarShort(this.honorNextGradeFloor); output.writeByte(this.aggressable); } override public function deserialize(input:ICustomDataInput) : void { this.deserializeAs_ActorExtendedAlignmentInformations(input); } public function deserializeAs_ActorExtendedAlignmentInformations(input:ICustomDataInput) : void { super.deserialize(input); this._honorFunc(input); this._honorGradeFloorFunc(input); this._honorNextGradeFloorFunc(input); this._aggressableFunc(input); } override public function deserializeAsync(tree:FuncTree) : void { this.deserializeAsyncAs_ActorExtendedAlignmentInformations(tree); } public function deserializeAsyncAs_ActorExtendedAlignmentInformations(tree:FuncTree) : void { super.deserializeAsync(tree); tree.addChild(this._honorFunc); tree.addChild(this._honorGradeFloorFunc); tree.addChild(this._honorNextGradeFloorFunc); tree.addChild(this._aggressableFunc); } private function _honorFunc(input:ICustomDataInput) : void { this.honor = input.readVarUhShort(); if(this.honor < 0 || this.honor > 20000) { throw new Error("Forbidden value (" + this.honor + ") on element of ActorExtendedAlignmentInformations.honor."); } } private function _honorGradeFloorFunc(input:ICustomDataInput) : void { this.honorGradeFloor = input.readVarUhShort(); if(this.honorGradeFloor < 0 || this.honorGradeFloor > 20000) { throw new Error("Forbidden value (" + this.honorGradeFloor + ") on element of ActorExtendedAlignmentInformations.honorGradeFloor."); } } private function _honorNextGradeFloorFunc(input:ICustomDataInput) : void { this.honorNextGradeFloor = input.readVarUhShort(); if(this.honorNextGradeFloor < 0 || this.honorNextGradeFloor > 20000) { throw new Error("Forbidden value (" + this.honorNextGradeFloor + ") on element of ActorExtendedAlignmentInformations.honorNextGradeFloor."); } } private function _aggressableFunc(input:ICustomDataInput) : void { this.aggressable = input.readByte(); if(this.aggressable < 0) { throw new Error("Forbidden value (" + this.aggressable + ") on element of ActorExtendedAlignmentInformations.aggressable."); } } } }
package raix.reactive.tests.operators.filter { import org.flexunit.Assert; import raix.reactive.IObservable; import raix.reactive.Subject; import raix.reactive.tests.mocks.StatsObserver; import raix.reactive.tests.operators.AbsDecoratorOperatorFixture; public class FirstOrDefaultFixture extends AbsDecoratorOperatorFixture { protected override function createEmptyObservable(source:IObservable):IObservable { return source.firstOrDefault(); } [Test] public function returns_first_value_and_completes() : void { var manObs : Subject = new Subject(); var obs : IObservable = manObs.firstOrDefault(); var stats : StatsObserver = new StatsObserver(); obs.subscribeWith(stats); manObs.onNext(1); Assert.assertEquals(1, stats.nextCount); Assert.assertTrue(stats.completedCalled); } [Test] public function returns_default_if_no_values() : void { var manObs : Subject = new Subject(); var obs : IObservable = manObs.firstOrDefault(); var stats : StatsObserver = new StatsObserver(); obs.subscribeWith(stats); manObs.onCompleted(); Assert.assertFalse(stats.errorCalled); Assert.assertTrue(stats.completedCalled); Assert.assertEquals(1, stats.nextCount); Assert.assertNull(stats.nextValues[0]); } [Test(expects="Error")] public function errors_thrown_by_subscriber_are_bubbled() : void { var manObs : Subject = new Subject(); var obs : IObservable = manObs.asObservable(); obs.subscribe( function(pl:int):void { throw new Error(); }, function():void { }, function(e:Error):void { Assert.fail("Unexpected call to onError"); } ); manObs.onNext(0); } [Test] public override function is_normalized_for_oncompleted() : void { var manObs : Subject = new Subject(); var obs : IObservable = createEmptyObservable(manObs); var stats : StatsObserver = new StatsObserver(); obs.subscribeWith(stats); manObs.onCompleted(); manObs.onNext(new Object()); manObs.onError(new Error()); Assert.assertEquals(1, stats.nextCount); Assert.assertEquals(1, stats.completedCalled); Assert.assertFalse(stats.errorCalled); } } }
/** * MACs * * An enumeration of MACs implemented for TLS * Copyright (c) 2007 Henri Torgemane * * See LICENSE.txt for full license information. */ package com.hurlant.crypto.tls { import com.hurlant.crypto.hash.HMAC; import com.hurlant.crypto.Crypto; public class MACs { public static const NULL:uint = 0; public static const MD5:uint = 1; public static const SHA1:uint = 2; public static function getHashSize(hash:uint):uint { return [0,16,20][hash]; } public static function getHMAC(hash:uint):HMAC { if (hash==NULL) return null; return Crypto.getHMAC(['',"md5","sha1"][hash]); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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 bxf.ui.inspectors { public interface IHUDLayoutElement { /** return the width of the primary label for this property editor */ function getLabelWidth():int; function set maxSiblingLabelWid(inMaxLblWid:int):void; function set sectionSpacer(inSectionSpacer:Boolean):void; } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.core { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Sprite; import flash.geom.Rectangle; import mx.managers.ISystemManager; /** * The IUIComponent interface defines the basic set of APIs * that you must implement to create a child of a Flex container or list. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public interface IUIComponent extends IFlexDisplayObject { //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // baselinePosition //---------------------------------- /** * The y-coordinate of the baseline * of the first line of text of the component. * * <p>This property is used to implement * the <code>baseline</code> constraint style. * It is also used to align the label of a FormItem * with the controls in the FormItem.</p> * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get baselinePosition():Number; //---------------------------------- // document //---------------------------------- /** * A reference to the document object associated with this component. * A document object is an Object at the top of the hierarchy * of a Flex application, MXML component, or ActionScript component. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get document():Object /** * @private */ function set document(value:Object):void //---------------------------------- // enabled //---------------------------------- /** * Whether the component can accept user interaction. After setting the <code>enabled</code> * property to <code>false</code>, some components still respond to mouse interactions such * as mouseOver. As a result, to fully disable UIComponents, * you should also set the value of the <code>mouseEnabled</code> property to <code>false</code>. * If you set the <code>enabled</code> property to <code>false</code> * for a container, Flex dims the color of the container and of all * of its children, and blocks user input to the container * and to all of its children. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get enabled():Boolean; /** * @private */ function set enabled(value:Boolean):void; //---------------------------------- // explicitHeight //---------------------------------- /** * The explicitly specified height for the component, * in pixels, as the component's coordinates. * If no height is explicitly specified, the value is <code>NaN</code>. * * @see mx.core.UIComponent#explicitHeight * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get explicitHeight():Number; /** * @private */ function set explicitHeight(value:Number):void; //---------------------------------- // explicitMaxHeight //---------------------------------- /** * Number that specifies the maximum height of the component, * in pixels, as the component's coordinates. * * @see mx.core.UIComponent#explicitMaxHeight * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get explicitMaxHeight():Number; //---------------------------------- // explicitMaxWidth //---------------------------------- /** * Number that specifies the maximum width of the component, * in pixels, as the component's coordinates. * * @see mx.core.UIComponent#explicitMaxWidth * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get explicitMaxWidth():Number; //---------------------------------- // explicitMinHeight //---------------------------------- /** * Number that specifies the minimum height of the component, * in pixels, as the component's coordinates. * * @see mx.core.UIComponent#explicitMinHeight * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get explicitMinHeight():Number; //---------------------------------- // explicitMinWidth //---------------------------------- /** * Number that specifies the minimum width of the component, * in pixels, as the component's coordinates. * * @see mx.core.UIComponent#explicitMinWidth * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get explicitMinWidth():Number; //---------------------------------- // explicitWidth //---------------------------------- /** * The explicitly specified width for the component, * in pixels, as the component's coordinates. * If no width is explicitly specified, the value is <code>NaN</code>. * * @see mx.core.UIComponent#explicitWidth * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get explicitWidth():Number; /** * @private */ function set explicitWidth(value:Number):void; //---------------------------------- // focusPane //---------------------------------- /** * A single Sprite object that is shared among components * and used as an overlay for drawing the focus indicator. * Components share this object if their parent is a focused component, * not if the component implements the IFocusManagerComponent interface. * * @see mx.core.UIComponent#focusPane * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get focusPane():Sprite; /** * @private */ function set focusPane(value:Sprite):void; //---------------------------------- // includeInLayout //---------------------------------- /** * @copy mx.core.UIComponent#includeInLayout * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get includeInLayout():Boolean; /** * @private */ function set includeInLayout(value:Boolean):void; //---------------------------------- // isPopUp //---------------------------------- /** * @copy mx.core.UIComponent#isPopUp * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get isPopUp():Boolean; /** * @private */ function set isPopUp(value:Boolean):void; //---------------------------------- // maxHeight //---------------------------------- /** * Number that specifies the maximum height of the component, * in pixels, as the component's coordinates. * * @see mx.core.UIComponent#maxHeight * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get maxHeight():Number; //---------------------------------- // maxWidth //---------------------------------- /** * Number that specifies the maximum width of the component, * in pixels, as the component's coordinates. * * @see mx.core.UIComponent#maxWidth * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get maxWidth():Number; //---------------------------------- // measuredMinHeight //---------------------------------- /** * @copy mx.core.UIComponent#measuredMinHeight * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get measuredMinHeight():Number; /** * @private */ function set measuredMinHeight(value:Number):void; //---------------------------------- // measuredMinWidth //---------------------------------- /** * @copy mx.core.UIComponent#measuredMinWidth * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get measuredMinWidth():Number; /** * @private */ function set measuredMinWidth(value:Number):void; //---------------------------------- // minHeight //---------------------------------- /** * Number that specifies the minimum height of the component, * in pixels, as the component's coordinates. * * @see mx.core.UIComponent#minHeight * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get minHeight():Number; //---------------------------------- // minWidth //---------------------------------- /** * Number that specifies the minimum width of the component, * in pixels, as the component's coordinates. * * @see mx.core.UIComponent#minWidth * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get minWidth():Number; //---------------------------------- // owner //---------------------------------- /** * @copy mx.core.IVisualElement#owner * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get owner():DisplayObjectContainer; /** * @private */ function set owner(value:DisplayObjectContainer):void; //---------------------------------- // percentHeight //---------------------------------- /** * Number that specifies the height of a component as a * percentage of its parent's size. * Allowed values are 0 to 100. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get percentHeight():Number; /** * @private */ function set percentHeight(value:Number):void; //---------------------------------- // percentWidth //---------------------------------- /** * Number that specifies the width of a component as a * percentage of its parent's size. * Allowed values are 0 to 100. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get percentWidth():Number; /** * @private */ function set percentWidth(value:Number):void; //---------------------------------- // systemManager //---------------------------------- /** * A reference to the SystemManager object for this component. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get systemManager():ISystemManager; /** * @private */ function set systemManager(value:ISystemManager):void; //---------------------------------- // tweeningProperties //---------------------------------- /** * Used by EffectManager. * Returns non-null if a component * is not using the EffectManager to execute a Tween. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function get tweeningProperties():Array; /** * @private */ function set tweeningProperties(value:Array):void; //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Initialize the object. * * @see mx.core.UIComponent#initialize() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function initialize():void; /** * @copy mx.core.UIComponent#parentChanged() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function parentChanged(p:DisplayObjectContainer):void; /** * @copy mx.core.UIComponent#getExplicitOrMeasuredWidth() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function getExplicitOrMeasuredWidth():Number; /** * @copy mx.core.UIComponent#getExplicitOrMeasuredHeight() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function getExplicitOrMeasuredHeight():Number; /** * @copy mx.core.UIComponent#setVisible() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function setVisible(value:Boolean, noEvent:Boolean = false):void; /** * @copy mx.core.UIComponent#owns() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ function owns(displayObject:DisplayObject):Boolean; } }
package com.xgame.godwar.core.room.views { import com.greensock.TweenLite; import com.greensock.easing.Strong; import com.xgame.godwar.common.parameters.card.HeroCardParameter; import com.xgame.godwar.common.pool.ResourcePool; import com.xgame.godwar.liteui.component.ImageContainer; import com.xgame.godwar.liteui.core.Component; import com.xgame.godwar.utils.UIUtils; import flash.display.DisplayObjectContainer; import flash.display.MovieClip; import flash.events.MouseEvent; public class BattleRoomHeroComponent extends Component { private var avatarMask: MovieClip; private var imgAvatar: ImageContainer; private var selectedMc: MovieClip; private var _selected: Boolean = false; private var parameter: HeroCardParameter; public function BattleRoomHeroComponent(_skin:DisplayObjectContainer=null) { super(_skin ? _skin : ResourcePool.instance.getDisplayObject("assets.ui.room.BattleRoomHeroComponent", null, false) as DisplayObjectContainer); imgAvatar = getUI(ImageContainer, "imgAvatar") as ImageContainer; avatarMask = getSkin("avatarMask") as MovieClip; selectedMc = getSkin("selected") as MovieClip; sortChildIndex(); addEventListener(MouseEvent.MOUSE_OVER, onMouseOver); addEventListener(MouseEvent.MOUSE_OUT, onMouseOut); imgAvatar.mask = avatarMask; selectedMc.visible = false; } public function set heroCardParameter(value: HeroCardParameter): void { if(value != null) { parameter = value; imgAvatar.source = parameter.avatarPath; } } public function get heroCardParameter(): HeroCardParameter { return parameter; } override protected function onMouseOver(evt: MouseEvent): void { if(_enabled) { UIUtils.setBrightness(this, 0.2); } } override protected function onMouseOut(evt: MouseEvent): void { if(_enabled) { UIUtils.setBrightness(this, 0); } } public function get selected():Boolean { return _selected; } public function set selected(value:Boolean):void { _selected = value; if(_selected) { selectedMc.visible = true; } else { selectedMc.visible = false; } } } }
package { import flash.display.MovieClip; import flash.display.Sprite; import flash.display.Stage; import flash.events.Event; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.geom.Rectangle; import flash.net.LocalConnection; import flash.system.Capabilities; import flash.system.System; import flash.text.StyleSheet; import flash.text.TextField; import flash.text.TextFormat; import flash.utils.Timer; import flash.utils.getTimer; import templates.*; import util.elm.ELM; [SWF (width="550", height = "706", backgroundColor="0x323232", frameRate="30")] public class ELMBenchmark extends Sprite{ /* // Stage size: 550x800px // testCycles: How many cycles running through the testValues. // testValues: no of generated Sprites/IEventDispatchers // testDdelay: between cycles. default = 20ms (prevents flashplayer from freezing */ private const testDelay:uint = 100, // ms 100 testCycles:int = 5, //5 testValues:Array = [25, 50, 75, 100, 150, 200, 250, 350, 500, 1000], testColors:Array = [0xebebeb, 0x000000, 0xFF0000, 0x0000FF, 0x00FF00], BENCHVERSION:String = "ELM-Benchmark 1.36"; private static var currentTest:int = -2; var currentCycle:int = 0, testNo:int = -1, resultArr:Array = [], resultStringTitle:String = BENCHVERSION+", Settings: delay = "+testDelay+" ms, cycles = "+testCycles+", Player: " + Capabilities.version, resultStringAVG:String = "AVERAGE RESULTS\n\n", resultString1k:String = testValues[int(testValues.length-1)]+" Sprites | "+(3*testValues[int(testValues.length-1)])+" Events\n\n", testTemplate:TemplateBase = null, baseMemory:Number = 0, memStatsStr:String = "start | peak MB: ", startMemory:Number = 0, endMemory:Number = 0, peakMemory:Number = -1, startTime:Number = 0, endTime:Number = 0, sleeps:uint = 0, timer:Timer = null, tfMemoryStatus:TextField; public function ELMBenchmark() { trace(Capabilities.version+" / "+Capabilities.playerType); stage.frameRate = 30; stage.scaleMode = "noScale"; tfMemoryStatus = new TextField(); tfMemoryStatus.defaultTextFormat = new TextFormat("_sans", "10", 0xFFFFFF, true, null, null, null, "center"); tfMemoryStatus.setTextFormat(tfMemoryStatus.defaultTextFormat); tfMemoryStatus.x = 15; tfMemoryStatus.y = 680; tfMemoryStatus.width = 500; addChild(tfMemoryStatus); nextTest(); } public function nextTest():void { testTemplate = null; runGC(); switch (++currentTest) { case -1: // init run testTemplate = new InitTemplate(); break; case 0: // Flash testTemplate = new FlashTemplate(); break; case 1: // AS3 Signals testTemplate = new SignalsTemplate(); break; case 2: // ELM testTemplate = new ELMTemplate(); break; case 3: // EventListenerManager testTemplate = new EVLTemplate(); break; case 4: // EventController testTemplate = new EventControllerTemplate(); break; case 5: // Rabbit // needs to run last due to massive memory consumption testTemplate = new RabbitTemplate(); break; default: showFinalResult(); return; } resultArr = []; currentCycle = 0; testNo = -1; timer = null; sleeps = 0; startMemory = getMem(); memStatsStr = "start | peak MB:\t ["+(startMemory/1024).toFixed(2)+" | "; var tfInfo:TextField = new TextField(); tfInfo.defaultTextFormat = new TextFormat("Arial", "18", 0xFFFFFF, true, null, null); //, "center" tfInfo.defaultTextFormat.align = "center"; tfInfo.width = stage.stageWidth; tfInfo.y = int(stage.stageHeight / 5); tfInfo.autoSize = "center"; addChild(tfInfo); tfInfo.text = (currentTest == -1) ? BENCHVERSION+"\ninitialization" : BENCHVERSION+"\ntesting:\n\n"+testTemplate.getTitle(); runGC(); startTime = getTimer(); sleep(2000); } private function startTest() { clearTestPattern(); if (++testNo >= testValues.length) { if (++currentCycle >= testCycles) { endTime = getTimer(); endTime -= 2000 - int(((sleeps-1)*testDelay)); prepTestResult(); nextTest(); return; } testNo = 0; } /* Basic Test */ createTestPattern(); runGC(); addHandler(); runGC(); disableHandler(); runGC(); enableHandler(); runGC(); removeHandler(); /* Extended Random Test createRandomTestPattern(); runGC(); addRandomHandler(); runGC(); disableRandomHandler(); runGC(); enableRandomHandler(); runGC(); removeRandomHandler(); */ sleep(testDelay); } private function showFinalResult() { tfMemoryStatus.text = ""; var headline:TextField = new TextField(); var result:TextField = new TextField(); var result2:TextField = new TextField(); headline.defaultTextFormat = result.defaultTextFormat = result2.defaultTextFormat = new TextFormat("Verdana", "10", 0xFFFFFF, false, null, null, null, "left"); headline.wordWrap = result.wordWrap = result2.wordWrap = true; headline.x = result.x = 10; result2.x = 275; result.y = result2.y = 32; headline.y = 10; headline.width = 530; result.width = result2.width = 250; result.height = result2.height = 666; addChild(headline);addChild(result);addChild(result2); headline.text = resultStringTitle; result.text = resultStringAVG; result2.text = resultString1k; //trace(ELM.length()); ELM.showAll(); } // private function prepTestResult():void { runGC(); if (currentTest == -1) return; endMemory = getMem(); resultStringAVG += "< "+testTemplate.getTitle()+" >\nbenchtime | mem use | peak mem\n"+ Number((endTime-startTime)/1000).toFixed(2)+" sec | "+ Number((endMemory-startMemory)/1024).toFixed(2)+" MB | "; var avgAddTime:Number = 0, avgAddMem:Number = 0, avgDisableTime:Number = 0, avgDisableMem:Number = 0, avgEnableTime:Number = 0, avgEnableMem:Number = 0, avgRemoveTime:Number = 0, avgRemoveMem:Number = 0, len:uint = uint(testValues.length-1); peakMemory = 0; for (var i:uint = 0; i < resultArr.length; i++) { avgAddTime += Number(resultArr[i].endTime - resultArr[i].startTime); avgAddMem += Number(resultArr[i].endMem - resultArr[i].startMem); peakMemCheck(Number(resultArr[i].endMem)); i++; avgDisableTime += Number(resultArr[i].endTime - resultArr[i].startTime); avgDisableMem += Number(resultArr[i].endMem - resultArr[i].startMem); peakMemCheck(Number(resultArr[i].endMem)); i++; avgEnableTime += Number(resultArr[i].endTime - resultArr[i].startTime); avgEnableMem += Number(resultArr[i].endMem - resultArr[i].startMem); peakMemCheck(Number(resultArr[i].endMem)); i++; avgRemoveTime += Number(resultArr[i].endTime - resultArr[i].startTime); avgRemoveMem += Number(resultArr[i].endMem - resultArr[i].startMem); peakMemCheck(Number(resultArr[i].endMem)); } resultStringAVG += Number((peakMemory-startMemory)/1024).toFixed(2)+" MB\n\n"+ "add: "+Number(avgAddTime/len).toFixed(2)+" ms | "+Number(avgAddMem/len).toFixed(2)+" kb\n"+ "remove: "+Number(avgRemoveTime/len).toFixed(2)+" ms | "+Number(avgRemoveMem/len).toFixed(2)+" kb\n"; resultStringAVG += (testTemplate.isManager && testTemplate.getTitle().indexOf("Signals") == -1 && testTemplate.getTitle().indexOf("Controller") == -1) ? "enable: "+Number(avgEnableTime/len).toFixed(2)+" ms | "+Number(avgEnableMem/len).toFixed(2)+" kb\n"+ "disable: "+Number(avgDisableTime/len).toFixed(2)+" ms | "+Number(avgDisableMem/len).toFixed(2)+" kb\n\n" : "enable: N/A ms | N/A kb\n"+"disable: N/A ms | N/A kb\n\n"; if (currentCycle >= testCycles && testNo >= testValues.length) { i -=4; resultString1k += "< "+testTemplate.getTitle()+" >\n\n\n\n"+ "add: "+Number(resultArr[i].endTime - resultArr[i].startTime).toFixed(2)+" ms | "+Number(resultArr[i].endMem - resultArr[i].startMem).toFixed(2)+" kb\n"+ "remove: "+Number(resultArr[int(i+3)].endTime - resultArr[int(i+3)].startTime).toFixed(2)+" ms | "+Number(resultArr[int(i+3)].endMem - resultArr[int(i+3)].startMem).toFixed(2)+" kb\n"; resultString1k += (testTemplate.isManager && testTemplate.getTitle().indexOf("Signals") == -1 && testTemplate.getTitle().indexOf("Controller") == -1) ? "enable: "+Number(resultArr[int(i+2)].endTime - resultArr[int(i+2)].startTime).toFixed(2)+" ms | "+Number(resultArr[int(i+2)].endMem - resultArr[int(i+2)].startMem).toFixed(2)+" kb\n"+ "disable: "+Number(resultArr[int(i+1)].endTime - resultArr[int(i+1)].startTime).toFixed(2)+" ms | "+Number(resultArr[int(i+1)].endMem - resultArr[int(i+1)].startMem).toFixed(2)+" kb\n\n" : "enable: N/A ms | N/A kb\n"+"disable: N/A ms | N/A kb\n\n"; } } private function peakMemCheck(n:Number):void { if (n > peakMemory) peakMemory = n; } // private function addHandler():void { var len:int = numChildren; startTimer(); while (--len > 0) { testTemplate.addL(getChildAt(len), MouseEvent.CLICK, dummyHandler); testTemplate.addL(getChildAt(len), MouseEvent.MOUSE_OVER, dummyHandler); testTemplate.addL(getChildAt(len), MouseEvent.MOUSE_OUT, dummyHandler); } endTimer(); } private function disableHandler():void { startTimer() testTemplate.disableL(); endTimer(); } private function enableHandler():void { startTimer(); testTemplate.enableL(); endTimer(); } // private function removeHandler():void { var len:int = numChildren; startTimer(); while (--len > -1) { testTemplate.removeL(getChildAt(len), MouseEvent.CLICK, dummyHandler); if (testTemplate.isManager || testTemplate is EventControllerTemplate) break; testTemplate.removeL(getChildAt(len), MouseEvent.MOUSE_OVER, dummyHandler); testTemplate.removeL(getChildAt(len), MouseEvent.MOUSE_OUT, dummyHandler); } endTimer(); } private function createTestPattern() { var xp:uint = 0; var yp:uint = 0, total:int = testValues[testNo], rw:uint = 21, rh:uint = 9, stepX:uint = rw+1, stepY:uint = rh+1; while (--total > -1) { var spr:Sprite = new Sprite(); spr.graphics.beginFill(Number(testColors[currentTest])); spr.graphics.drawRect(0,0, rw,rh); spr.graphics.endFill(); spr.x = xp; spr.y = yp; spr.mouseEnabled = false; addChild(spr); xp += stepX; if (xp >= 550) { xp = 0; yp += stepY; } } } private function clearTestPattern() { while (numChildren > 1) { removeChildAt(int(numChildren-1)); } } private function startTimer():void { if (testCycles == int(currentCycle+1)) resultArr.push(new ResultObj(numChildren, getTimer(), 0, getMem(), 0)); } private function endTimer():void { if (testCycles == int(currentCycle+1)) { resultArr[int(resultArr.length-1)].endTime = getTimer(); resultArr[int(resultArr.length-1)].endMem = getMem(); } } /** * Forces the garbage collector to run. This is used internally to reduce the impact of GC operations on tests, * and to measure memory usage. (by Grant Skinner - www.gskinner.com/blog PerformanceTest2) **/ public static function runGC():void { try { new LocalConnection().connect("_FORCE_GC_"); new LocalConnection().connect("_FORCE_GC_"); } catch(e:*) {} } private function getMem():Number { var mem:Number = Math.round(System.totalMemory/ 1024); return mem; } private function sleep(sv:int):void { sleeps++; timer = new Timer(sv, 1); timer.addEventListener(TimerEvent.TIMER, timerHandler); timer.start(); tfMemoryStatus.text = memStatsStr+(getMem()/1024).toFixed(2)+" MB ]"; } private function timerHandler(e:TimerEvent=null):void { timer.removeEventListener(TimerEvent.TIMER, timerHandler); timer = null; startTest(); } private function dummyHandler(e:*):void { throw new ArgumentError("ERROR EVENT MUST NOT BE FIRED!"); } } } internal class ResultObj { public var sprites:uint, startTime:uint, endTime:uint, startMem:int, endMem:int; public function ResultObj(spr:uint, st:uint, et:uint, sm:int, em:int):void { sprites = spr-1; startTime = st; endTime = et; startMem = sm; endMem = em; } }
package com.guepard.decompiler.abc.info { /** * ... * @author Antonov Sergey */ public class MethodInfo { public var returnType:MultinameInfo; public var paramTypes:Array; public var name:String; public var flags:uint; public var optionInfos:Array; public var paramInfos:Array; public var body:MethodBody; public function MethodInfo() { } public function dispose():void { returnType = null; paramTypes = null; optionInfos = null; paramInfos = null; body = null; } public function clone():MethodInfo { var methodInfo:MethodInfo = new MethodInfo(); methodInfo.returnType = returnType; methodInfo.paramTypes = paramTypes; methodInfo.name = name; methodInfo.flags = flags; methodInfo.optionInfos = optionInfos; methodInfo.paramInfos = paramInfos; methodInfo.body = body.clone(); methodInfo.body.method = methodInfo; methodInfo.body.changed = true; return methodInfo; } public function getInfo(tab:String = ""):String { var s:String = tab + toString() + "\n"; s += tab + "{\n"; for each(var line:String in body.code) { s += tab + "\t" + line + "\n"; } s += tab + "}"; return s; } public function toString():String { var ret:String = "("; var mnm:MultinameInfo; var opt:OptionInfo; var di:uint; for (var i:uint = 0; i < paramTypes.length; i++) { if (paramInfos) { ret += paramInfos[i] + ":"; } else { ret += "_loc" + i + ":"; } mnm = MultinameInfo(paramTypes[i]); if (mnm) { ret += mnm.name; } else { ret += "null"; } if (optionInfos && optionInfos.length > 0) { di = paramTypes.length - optionInfos.length; if (i >= di) { opt = OptionInfo(optionInfos[i - di]); if (opt.value is String) { ret += ' = "' + opt.value + '"'; } else { ret += " = " + opt.value; } } } if (i < paramTypes.length - 1) ret += ", "; } if (returnType) { ret += "):" + returnType.name; } else { ret += "):void"; } return ret; } } }
package idv.cjcat.stardustextended.handlers { import idv.cjcat.stardustextended.emitters.Emitter; import idv.cjcat.stardustextended.particles.Particle; import idv.cjcat.stardustextended.StardustElement; /** * A particle handler is assigned to a particle by using the <code>Handler</code> initializer. * A handler monitors the beginning of an emitter step, the end of an emitter step, * the adding of a new particle, and the removal of a dead particle. * Also, the <code>readParticle()<code> method is used to read data out of <code>Particle</code> * objects when each particle is completely updated by actions. */ public class ParticleHandler extends StardustElement { public function reset() : void { } /** * [Abstract Method] Invoked when each emitter step begins. * @param emitter * @param particles * @param time */ public function stepBegin(emitter : Emitter, particles : Vector.<Particle>, time : Number) : void { } /** * [Abstract Method] Invoked when each emitter step ends. Particles are at their final position and ready to be * rendered. * @param emitter * @param particles * @param time */ public function stepEnd(emitter : Emitter, particles : Vector.<Particle>, time : Number) : void { } /** * [Abstract Method] Invoked for each particle added. * Handle particle creation in this method. * @param particle */ public function particleAdded(particle : Particle) : void { } /** * [Abstract Method] Invoked for each particle removed. * Handle particle removal in this method. * @param particle */ public function particleRemoved(particle : Particle) : void { } //XML //------------------------------------------------------------------------------------------------ override public function getXMLTagName() : String { return "ParticleHandler"; } override public function getElementTypeXMLTag() : XML { return <handlers/>; } //------------------------------------------------------------------------------------------------ //end of XML } }
package com.codeazur.as3swf.data.actions.swf4 { import com.codeazur.as3swf.data.actions.*; public class ActionOr extends Action implements IAction { public static const CODE:uint = 0x11; public function ActionOr(code:uint, length:uint) { super(code, length); } override public function toString(indent:uint = 0):String { return "[ActionOr]"; } } }
package com.rokannon.command.directoryListing { import com.rokannon.core.command.CommandBase; import com.rokannon.logging.Log; import com.rokannon.logging.Logger; import flash.events.FileListEvent; import flash.events.IOErrorEvent; public class DirectoryListingCommand extends CommandBase { private static const logger:Logger = Log.instance.getLogger(DirectoryListingCommand); private var _context:DirectoryListingContext; public function DirectoryListingCommand(context:DirectoryListingContext) { super(); _context = context; } override protected function onStart():void { _context.directoryToLoad.addEventListener(FileListEvent.DIRECTORY_LISTING, onListingComplete); _context.directoryToLoad.addEventListener(IOErrorEvent.IO_ERROR, onListingError); _context.directoryToLoad.getDirectoryListingAsync(); } private function onListingError(event:IOErrorEvent):void { _context.directoryToLoad.removeEventListener(FileListEvent.DIRECTORY_LISTING, onListingComplete); _context.directoryToLoad.removeEventListener(IOErrorEvent.IO_ERROR, onListingError); CONFIG::log_error { logger.error("Error listing directory: {0}", _context.directoryToLoad.nativePath); } onFailed(); } private function onListingComplete(event:FileListEvent):void { _context.directoryToLoad.removeEventListener(FileListEvent.DIRECTORY_LISTING, onListingComplete); _context.directoryToLoad.removeEventListener(IOErrorEvent.IO_ERROR, onListingError); var length:int = event.files.length; for (var i:int = 0; i < length; ++i) _context.directoryListing[i] = event.files[i]; onComplete(); } } }
package com.gigateam.extensions.usb { public class Baud { public static const BAUD_110:int=110; public static const BAUD_300:int=300; public static const BAUD_600:int=600; public static const BAUD_1200:int=1200; public static const BAUD_2400:int=2400; public static const BAUD_4800:int=4800; public static const BAUD_9600:int=9600; public static const BAUD_14400:int=14400; public static const BAUD_19200:int=19200; public static const BAUD_28800:int=28800; public static const BAUD_38400:int=38400; public static const BAUD_56000:int=56000; public static const BAUD_57600:int=57600; public static const BAUD_115200:int=115200; public static const BAUD_128000:int=128000; public static const BAUD_153600:int=153600; public static const BAUD_230400:int=230400; public static const BAUD_256000:int=256000; public static const BAUD_460800:int=460800; public static const BAUD_921600:int=921600; public function Baud() { // constructor code } } }
package com.rockdot.library.view.util { import flash.display.CapsStyle; import flash.display.Graphics; import flash.display.Shape; /** * @author Nils Doehring (nilsdoehring(at)gmail.com) */ public class RoundMasker extends Shape { private var _progress : Number; private var _g : Graphics; private var _h : uint; private var _radiusX : Number; private var _radiusY : Number; private var _centerX : Number; private var _centerY : Number; private var _density : uint; private var _startAngle : Number; public function RoundMasker(w : uint, h : uint, density : uint = 1, startAngle : Number = Math.PI * 0.5) { _h = h; _density = density; _startAngle = startAngle; _radiusX = w * 0.5; _radiusY = h * 0.5; _centerX = _radiusX; _centerY = _radiusY; _progress = 0; _g = graphics; } public function get progress() : Number { return _progress; } public function set progress(progress : Number) : void { if (progress < 0) _progress = 0; else if (progress > 1) _progress = 1; else _progress = progress; _g.clear(); _g.lineStyle(1, 0, 1, false, "normal", CapsStyle.NONE); var angle : Number; for (var i : Number = 0;i < _progress;i += 0.1 / (10*_density)) { _g.moveTo(_centerX, _centerY); angle = i * Math.PI * 2 - _startAngle; _g.lineTo(Math.cos(angle) * _radiusX + _centerX, Math.sin(angle) * _radiusY + _centerY); } } } }
/* * Copyright 2006 Jeremias Maerki in part, and ZXing Authors in part * * 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. */ /* * This file has been modified from its original form in Barcode4J. */ package com.google.zxing.pdf417.encoder{ import com.google.zxing.WriterException; import com.google.zxing.common.flexdatatypes.StringBuilder; /** * Top-level class for the logic part of the PDF417 implementation. */ public class PDF417 { /** * The start pattern (17 bits) */ private static var START_PATTERN:int = 0x1fea8; /** * The stop pattern (18 bits) */ private static var STOP_PATTERN:int = 0x3fa29; /** * The codeword table from the Annex A of ISO/IEC 15438:2001(E). */ private static var CODEWORD_TABLE:Array = [ [0x1d5c0, 0x1eaf0, 0x1f57c, 0x1d4e0, 0x1ea78, 0x1f53e, 0x1a8c0, 0x1d470, 0x1a860, 0x15040, 0x1a830, 0x15020, 0x1adc0, 0x1d6f0, 0x1eb7c, 0x1ace0, 0x1d678, 0x1eb3e, 0x158c0, 0x1ac70, 0x15860, 0x15dc0, 0x1aef0, 0x1d77c, 0x15ce0, 0x1ae78, 0x1d73e, 0x15c70, 0x1ae3c, 0x15ef0, 0x1af7c, 0x15e78, 0x1af3e, 0x15f7c, 0x1f5fa, 0x1d2e0, 0x1e978, 0x1f4be, 0x1a4c0, 0x1d270, 0x1e93c, 0x1a460, 0x1d238, 0x14840, 0x1a430, 0x1d21c, 0x14820, 0x1a418, 0x14810, 0x1a6e0, 0x1d378, 0x1e9be, 0x14cc0, 0x1a670, 0x1d33c, 0x14c60, 0x1a638, 0x1d31e, 0x14c30, 0x1a61c, 0x14ee0, 0x1a778, 0x1d3be, 0x14e70, 0x1a73c, 0x14e38, 0x1a71e, 0x14f78, 0x1a7be, 0x14f3c, 0x14f1e, 0x1a2c0, 0x1d170, 0x1e8bc, 0x1a260, 0x1d138, 0x1e89e, 0x14440, 0x1a230, 0x1d11c, 0x14420, 0x1a218, 0x14410, 0x14408, 0x146c0, 0x1a370, 0x1d1bc, 0x14660, 0x1a338, 0x1d19e, 0x14630, 0x1a31c, 0x14618, 0x1460c, 0x14770, 0x1a3bc, 0x14738, 0x1a39e, 0x1471c, 0x147bc, 0x1a160, 0x1d0b8, 0x1e85e, 0x14240, 0x1a130, 0x1d09c, 0x14220, 0x1a118, 0x1d08e, 0x14210, 0x1a10c, 0x14208, 0x1a106, 0x14360, 0x1a1b8, 0x1d0de, 0x14330, 0x1a19c, 0x14318, 0x1a18e, 0x1430c, 0x14306, 0x1a1de, 0x1438e, 0x14140, 0x1a0b0, 0x1d05c, 0x14120, 0x1a098, 0x1d04e, 0x14110, 0x1a08c, 0x14108, 0x1a086, 0x14104, 0x141b0, 0x14198, 0x1418c, 0x140a0, 0x1d02e, 0x1a04c, 0x1a046, 0x14082, 0x1cae0, 0x1e578, 0x1f2be, 0x194c0, 0x1ca70, 0x1e53c, 0x19460, 0x1ca38, 0x1e51e, 0x12840, 0x19430, 0x12820, 0x196e0, 0x1cb78, 0x1e5be, 0x12cc0, 0x19670, 0x1cb3c, 0x12c60, 0x19638, 0x12c30, 0x12c18, 0x12ee0, 0x19778, 0x1cbbe, 0x12e70, 0x1973c, 0x12e38, 0x12e1c, 0x12f78, 0x197be, 0x12f3c, 0x12fbe, 0x1dac0, 0x1ed70, 0x1f6bc, 0x1da60, 0x1ed38, 0x1f69e, 0x1b440, 0x1da30, 0x1ed1c, 0x1b420, 0x1da18, 0x1ed0e, 0x1b410, 0x1da0c, 0x192c0, 0x1c970, 0x1e4bc, 0x1b6c0, 0x19260, 0x1c938, 0x1e49e, 0x1b660, 0x1db38, 0x1ed9e, 0x16c40, 0x12420, 0x19218, 0x1c90e, 0x16c20, 0x1b618, 0x16c10, 0x126c0, 0x19370, 0x1c9bc, 0x16ec0, 0x12660, 0x19338, 0x1c99e, 0x16e60, 0x1b738, 0x1db9e, 0x16e30, 0x12618, 0x16e18, 0x12770, 0x193bc, 0x16f70, 0x12738, 0x1939e, 0x16f38, 0x1b79e, 0x16f1c, 0x127bc, 0x16fbc, 0x1279e, 0x16f9e, 0x1d960, 0x1ecb8, 0x1f65e, 0x1b240, 0x1d930, 0x1ec9c, 0x1b220, 0x1d918, 0x1ec8e, 0x1b210, 0x1d90c, 0x1b208, 0x1b204, 0x19160, 0x1c8b8, 0x1e45e, 0x1b360, 0x19130, 0x1c89c, 0x16640, 0x12220, 0x1d99c, 0x1c88e, 0x16620, 0x12210, 0x1910c, 0x16610, 0x1b30c, 0x19106, 0x12204, 0x12360, 0x191b8, 0x1c8de, 0x16760, 0x12330, 0x1919c, 0x16730, 0x1b39c, 0x1918e, 0x16718, 0x1230c, 0x12306, 0x123b8, 0x191de, 0x167b8, 0x1239c, 0x1679c, 0x1238e, 0x1678e, 0x167de, 0x1b140, 0x1d8b0, 0x1ec5c, 0x1b120, 0x1d898, 0x1ec4e, 0x1b110, 0x1d88c, 0x1b108, 0x1d886, 0x1b104, 0x1b102, 0x12140, 0x190b0, 0x1c85c, 0x16340, 0x12120, 0x19098, 0x1c84e, 0x16320, 0x1b198, 0x1d8ce, 0x16310, 0x12108, 0x19086, 0x16308, 0x1b186, 0x16304, 0x121b0, 0x190dc, 0x163b0, 0x12198, 0x190ce, 0x16398, 0x1b1ce, 0x1638c, 0x12186, 0x16386, 0x163dc, 0x163ce, 0x1b0a0, 0x1d858, 0x1ec2e, 0x1b090, 0x1d84c, 0x1b088, 0x1d846, 0x1b084, 0x1b082, 0x120a0, 0x19058, 0x1c82e, 0x161a0, 0x12090, 0x1904c, 0x16190, 0x1b0cc, 0x19046, 0x16188, 0x12084, 0x16184, 0x12082, 0x120d8, 0x161d8, 0x161cc, 0x161c6, 0x1d82c, 0x1d826, 0x1b042, 0x1902c, 0x12048, 0x160c8, 0x160c4, 0x160c2, 0x18ac0, 0x1c570, 0x1e2bc, 0x18a60, 0x1c538, 0x11440, 0x18a30, 0x1c51c, 0x11420, 0x18a18, 0x11410, 0x11408, 0x116c0, 0x18b70, 0x1c5bc, 0x11660, 0x18b38, 0x1c59e, 0x11630, 0x18b1c, 0x11618, 0x1160c, 0x11770, 0x18bbc, 0x11738, 0x18b9e, 0x1171c, 0x117bc, 0x1179e, 0x1cd60, 0x1e6b8, 0x1f35e, 0x19a40, 0x1cd30, 0x1e69c, 0x19a20, 0x1cd18, 0x1e68e, 0x19a10, 0x1cd0c, 0x19a08, 0x1cd06, 0x18960, 0x1c4b8, 0x1e25e, 0x19b60, 0x18930, 0x1c49c, 0x13640, 0x11220, 0x1cd9c, 0x1c48e, 0x13620, 0x19b18, 0x1890c, 0x13610, 0x11208, 0x13608, 0x11360, 0x189b8, 0x1c4de, 0x13760, 0x11330, 0x1cdde, 0x13730, 0x19b9c, 0x1898e, 0x13718, 0x1130c, 0x1370c, 0x113b8, 0x189de, 0x137b8, 0x1139c, 0x1379c, 0x1138e, 0x113de, 0x137de, 0x1dd40, 0x1eeb0, 0x1f75c, 0x1dd20, 0x1ee98, 0x1f74e, 0x1dd10, 0x1ee8c, 0x1dd08, 0x1ee86, 0x1dd04, 0x19940, 0x1ccb0, 0x1e65c, 0x1bb40, 0x19920, 0x1eedc, 0x1e64e, 0x1bb20, 0x1dd98, 0x1eece, 0x1bb10, 0x19908, 0x1cc86, 0x1bb08, 0x1dd86, 0x19902, 0x11140, 0x188b0, 0x1c45c, 0x13340, 0x11120, 0x18898, 0x1c44e, 0x17740, 0x13320, 0x19998, 0x1ccce, 0x17720, 0x1bb98, 0x1ddce, 0x18886, 0x17710, 0x13308, 0x19986, 0x17708, 0x11102, 0x111b0, 0x188dc, 0x133b0, 0x11198, 0x188ce, 0x177b0, 0x13398, 0x199ce, 0x17798, 0x1bbce, 0x11186, 0x13386, 0x111dc, 0x133dc, 0x111ce, 0x177dc, 0x133ce, 0x1dca0, 0x1ee58, 0x1f72e, 0x1dc90, 0x1ee4c, 0x1dc88, 0x1ee46, 0x1dc84, 0x1dc82, 0x198a0, 0x1cc58, 0x1e62e, 0x1b9a0, 0x19890, 0x1ee6e, 0x1b990, 0x1dccc, 0x1cc46, 0x1b988, 0x19884, 0x1b984, 0x19882, 0x1b982, 0x110a0, 0x18858, 0x1c42e, 0x131a0, 0x11090, 0x1884c, 0x173a0, 0x13190, 0x198cc, 0x18846, 0x17390, 0x1b9cc, 0x11084, 0x17388, 0x13184, 0x11082, 0x13182, 0x110d8, 0x1886e, 0x131d8, 0x110cc, 0x173d8, 0x131cc, 0x110c6, 0x173cc, 0x131c6, 0x110ee, 0x173ee, 0x1dc50, 0x1ee2c, 0x1dc48, 0x1ee26, 0x1dc44, 0x1dc42, 0x19850, 0x1cc2c, 0x1b8d0, 0x19848, 0x1cc26, 0x1b8c8, 0x1dc66, 0x1b8c4, 0x19842, 0x1b8c2, 0x11050, 0x1882c, 0x130d0, 0x11048, 0x18826, 0x171d0, 0x130c8, 0x19866, 0x171c8, 0x1b8e6, 0x11042, 0x171c4, 0x130c2, 0x171c2, 0x130ec, 0x171ec, 0x171e6, 0x1ee16, 0x1dc22, 0x1cc16, 0x19824, 0x19822, 0x11028, 0x13068, 0x170e8, 0x11022, 0x13062, 0x18560, 0x10a40, 0x18530, 0x10a20, 0x18518, 0x1c28e, 0x10a10, 0x1850c, 0x10a08, 0x18506, 0x10b60, 0x185b8, 0x1c2de, 0x10b30, 0x1859c, 0x10b18, 0x1858e, 0x10b0c, 0x10b06, 0x10bb8, 0x185de, 0x10b9c, 0x10b8e, 0x10bde, 0x18d40, 0x1c6b0, 0x1e35c, 0x18d20, 0x1c698, 0x18d10, 0x1c68c, 0x18d08, 0x1c686, 0x18d04, 0x10940, 0x184b0, 0x1c25c, 0x11b40, 0x10920, 0x1c6dc, 0x1c24e, 0x11b20, 0x18d98, 0x1c6ce, 0x11b10, 0x10908, 0x18486, 0x11b08, 0x18d86, 0x10902, 0x109b0, 0x184dc, 0x11bb0, 0x10998, 0x184ce, 0x11b98, 0x18dce, 0x11b8c, 0x10986, 0x109dc, 0x11bdc, 0x109ce, 0x11bce, 0x1cea0, 0x1e758, 0x1f3ae, 0x1ce90, 0x1e74c, 0x1ce88, 0x1e746, 0x1ce84, 0x1ce82, 0x18ca0, 0x1c658, 0x19da0, 0x18c90, 0x1c64c, 0x19d90, 0x1cecc, 0x1c646, 0x19d88, 0x18c84, 0x19d84, 0x18c82, 0x19d82, 0x108a0, 0x18458, 0x119a0, 0x10890, 0x1c66e, 0x13ba0, 0x11990, 0x18ccc, 0x18446, 0x13b90, 0x19dcc, 0x10884, 0x13b88, 0x11984, 0x10882, 0x11982, 0x108d8, 0x1846e, 0x119d8, 0x108cc, 0x13bd8, 0x119cc, 0x108c6, 0x13bcc, 0x119c6, 0x108ee, 0x119ee, 0x13bee, 0x1ef50, 0x1f7ac, 0x1ef48, 0x1f7a6, 0x1ef44, 0x1ef42, 0x1ce50, 0x1e72c, 0x1ded0, 0x1ef6c, 0x1e726, 0x1dec8, 0x1ef66, 0x1dec4, 0x1ce42, 0x1dec2, 0x18c50, 0x1c62c, 0x19cd0, 0x18c48, 0x1c626, 0x1bdd0, 0x19cc8, 0x1ce66, 0x1bdc8, 0x1dee6, 0x18c42, 0x1bdc4, 0x19cc2, 0x1bdc2, 0x10850, 0x1842c, 0x118d0, 0x10848, 0x18426, 0x139d0, 0x118c8, 0x18c66, 0x17bd0, 0x139c8, 0x19ce6, 0x10842, 0x17bc8, 0x1bde6, 0x118c2, 0x17bc4, 0x1086c, 0x118ec, 0x10866, 0x139ec, 0x118e6, 0x17bec, 0x139e6, 0x17be6, 0x1ef28, 0x1f796, 0x1ef24, 0x1ef22, 0x1ce28, 0x1e716, 0x1de68, 0x1ef36, 0x1de64, 0x1ce22, 0x1de62, 0x18c28, 0x1c616, 0x19c68, 0x18c24, 0x1bce8, 0x19c64, 0x18c22, 0x1bce4, 0x19c62, 0x1bce2, 0x10828, 0x18416, 0x11868, 0x18c36, 0x138e8, 0x11864, 0x10822, 0x179e8, 0x138e4, 0x11862, 0x179e4, 0x138e2, 0x179e2, 0x11876, 0x179f6, 0x1ef12, 0x1de34, 0x1de32, 0x19c34, 0x1bc74, 0x1bc72, 0x11834, 0x13874, 0x178f4, 0x178f2, 0x10540, 0x10520, 0x18298, 0x10510, 0x10508, 0x10504, 0x105b0, 0x10598, 0x1058c, 0x10586, 0x105dc, 0x105ce, 0x186a0, 0x18690, 0x1c34c, 0x18688, 0x1c346, 0x18684, 0x18682, 0x104a0, 0x18258, 0x10da0, 0x186d8, 0x1824c, 0x10d90, 0x186cc, 0x10d88, 0x186c6, 0x10d84, 0x10482, 0x10d82, 0x104d8, 0x1826e, 0x10dd8, 0x186ee, 0x10dcc, 0x104c6, 0x10dc6, 0x104ee, 0x10dee, 0x1c750, 0x1c748, 0x1c744, 0x1c742, 0x18650, 0x18ed0, 0x1c76c, 0x1c326, 0x18ec8, 0x1c766, 0x18ec4, 0x18642, 0x18ec2, 0x10450, 0x10cd0, 0x10448, 0x18226, 0x11dd0, 0x10cc8, 0x10444, 0x11dc8, 0x10cc4, 0x10442, 0x11dc4, 0x10cc2, 0x1046c, 0x10cec, 0x10466, 0x11dec, 0x10ce6, 0x11de6, 0x1e7a8, 0x1e7a4, 0x1e7a2, 0x1c728, 0x1cf68, 0x1e7b6, 0x1cf64, 0x1c722, 0x1cf62, 0x18628, 0x1c316, 0x18e68, 0x1c736, 0x19ee8, 0x18e64, 0x18622, 0x19ee4, 0x18e62, 0x19ee2, 0x10428, 0x18216, 0x10c68, 0x18636, 0x11ce8, 0x10c64, 0x10422, 0x13de8, 0x11ce4, 0x10c62, 0x13de4, 0x11ce2, 0x10436, 0x10c76, 0x11cf6, 0x13df6, 0x1f7d4, 0x1f7d2, 0x1e794, 0x1efb4, 0x1e792, 0x1efb2, 0x1c714, 0x1cf34, 0x1c712, 0x1df74, 0x1cf32, 0x1df72, 0x18614, 0x18e34, 0x18612, 0x19e74, 0x18e32, 0x1bef4], [0x1f560, 0x1fab8, 0x1ea40, 0x1f530, 0x1fa9c, 0x1ea20, 0x1f518, 0x1fa8e, 0x1ea10, 0x1f50c, 0x1ea08, 0x1f506, 0x1ea04, 0x1eb60, 0x1f5b8, 0x1fade, 0x1d640, 0x1eb30, 0x1f59c, 0x1d620, 0x1eb18, 0x1f58e, 0x1d610, 0x1eb0c, 0x1d608, 0x1eb06, 0x1d604, 0x1d760, 0x1ebb8, 0x1f5de, 0x1ae40, 0x1d730, 0x1eb9c, 0x1ae20, 0x1d718, 0x1eb8e, 0x1ae10, 0x1d70c, 0x1ae08, 0x1d706, 0x1ae04, 0x1af60, 0x1d7b8, 0x1ebde, 0x15e40, 0x1af30, 0x1d79c, 0x15e20, 0x1af18, 0x1d78e, 0x15e10, 0x1af0c, 0x15e08, 0x1af06, 0x15f60, 0x1afb8, 0x1d7de, 0x15f30, 0x1af9c, 0x15f18, 0x1af8e, 0x15f0c, 0x15fb8, 0x1afde, 0x15f9c, 0x15f8e, 0x1e940, 0x1f4b0, 0x1fa5c, 0x1e920, 0x1f498, 0x1fa4e, 0x1e910, 0x1f48c, 0x1e908, 0x1f486, 0x1e904, 0x1e902, 0x1d340, 0x1e9b0, 0x1f4dc, 0x1d320, 0x1e998, 0x1f4ce, 0x1d310, 0x1e98c, 0x1d308, 0x1e986, 0x1d304, 0x1d302, 0x1a740, 0x1d3b0, 0x1e9dc, 0x1a720, 0x1d398, 0x1e9ce, 0x1a710, 0x1d38c, 0x1a708, 0x1d386, 0x1a704, 0x1a702, 0x14f40, 0x1a7b0, 0x1d3dc, 0x14f20, 0x1a798, 0x1d3ce, 0x14f10, 0x1a78c, 0x14f08, 0x1a786, 0x14f04, 0x14fb0, 0x1a7dc, 0x14f98, 0x1a7ce, 0x14f8c, 0x14f86, 0x14fdc, 0x14fce, 0x1e8a0, 0x1f458, 0x1fa2e, 0x1e890, 0x1f44c, 0x1e888, 0x1f446, 0x1e884, 0x1e882, 0x1d1a0, 0x1e8d8, 0x1f46e, 0x1d190, 0x1e8cc, 0x1d188, 0x1e8c6, 0x1d184, 0x1d182, 0x1a3a0, 0x1d1d8, 0x1e8ee, 0x1a390, 0x1d1cc, 0x1a388, 0x1d1c6, 0x1a384, 0x1a382, 0x147a0, 0x1a3d8, 0x1d1ee, 0x14790, 0x1a3cc, 0x14788, 0x1a3c6, 0x14784, 0x14782, 0x147d8, 0x1a3ee, 0x147cc, 0x147c6, 0x147ee, 0x1e850, 0x1f42c, 0x1e848, 0x1f426, 0x1e844, 0x1e842, 0x1d0d0, 0x1e86c, 0x1d0c8, 0x1e866, 0x1d0c4, 0x1d0c2, 0x1a1d0, 0x1d0ec, 0x1a1c8, 0x1d0e6, 0x1a1c4, 0x1a1c2, 0x143d0, 0x1a1ec, 0x143c8, 0x1a1e6, 0x143c4, 0x143c2, 0x143ec, 0x143e6, 0x1e828, 0x1f416, 0x1e824, 0x1e822, 0x1d068, 0x1e836, 0x1d064, 0x1d062, 0x1a0e8, 0x1d076, 0x1a0e4, 0x1a0e2, 0x141e8, 0x1a0f6, 0x141e4, 0x141e2, 0x1e814, 0x1e812, 0x1d034, 0x1d032, 0x1a074, 0x1a072, 0x1e540, 0x1f2b0, 0x1f95c, 0x1e520, 0x1f298, 0x1f94e, 0x1e510, 0x1f28c, 0x1e508, 0x1f286, 0x1e504, 0x1e502, 0x1cb40, 0x1e5b0, 0x1f2dc, 0x1cb20, 0x1e598, 0x1f2ce, 0x1cb10, 0x1e58c, 0x1cb08, 0x1e586, 0x1cb04, 0x1cb02, 0x19740, 0x1cbb0, 0x1e5dc, 0x19720, 0x1cb98, 0x1e5ce, 0x19710, 0x1cb8c, 0x19708, 0x1cb86, 0x19704, 0x19702, 0x12f40, 0x197b0, 0x1cbdc, 0x12f20, 0x19798, 0x1cbce, 0x12f10, 0x1978c, 0x12f08, 0x19786, 0x12f04, 0x12fb0, 0x197dc, 0x12f98, 0x197ce, 0x12f8c, 0x12f86, 0x12fdc, 0x12fce, 0x1f6a0, 0x1fb58, 0x16bf0, 0x1f690, 0x1fb4c, 0x169f8, 0x1f688, 0x1fb46, 0x168fc, 0x1f684, 0x1f682, 0x1e4a0, 0x1f258, 0x1f92e, 0x1eda0, 0x1e490, 0x1fb6e, 0x1ed90, 0x1f6cc, 0x1f246, 0x1ed88, 0x1e484, 0x1ed84, 0x1e482, 0x1ed82, 0x1c9a0, 0x1e4d8, 0x1f26e, 0x1dba0, 0x1c990, 0x1e4cc, 0x1db90, 0x1edcc, 0x1e4c6, 0x1db88, 0x1c984, 0x1db84, 0x1c982, 0x1db82, 0x193a0, 0x1c9d8, 0x1e4ee, 0x1b7a0, 0x19390, 0x1c9cc, 0x1b790, 0x1dbcc, 0x1c9c6, 0x1b788, 0x19384, 0x1b784, 0x19382, 0x1b782, 0x127a0, 0x193d8, 0x1c9ee, 0x16fa0, 0x12790, 0x193cc, 0x16f90, 0x1b7cc, 0x193c6, 0x16f88, 0x12784, 0x16f84, 0x12782, 0x127d8, 0x193ee, 0x16fd8, 0x127cc, 0x16fcc, 0x127c6, 0x16fc6, 0x127ee, 0x1f650, 0x1fb2c, 0x165f8, 0x1f648, 0x1fb26, 0x164fc, 0x1f644, 0x1647e, 0x1f642, 0x1e450, 0x1f22c, 0x1ecd0, 0x1e448, 0x1f226, 0x1ecc8, 0x1f666, 0x1ecc4, 0x1e442, 0x1ecc2, 0x1c8d0, 0x1e46c, 0x1d9d0, 0x1c8c8, 0x1e466, 0x1d9c8, 0x1ece6, 0x1d9c4, 0x1c8c2, 0x1d9c2, 0x191d0, 0x1c8ec, 0x1b3d0, 0x191c8, 0x1c8e6, 0x1b3c8, 0x1d9e6, 0x1b3c4, 0x191c2, 0x1b3c2, 0x123d0, 0x191ec, 0x167d0, 0x123c8, 0x191e6, 0x167c8, 0x1b3e6, 0x167c4, 0x123c2, 0x167c2, 0x123ec, 0x167ec, 0x123e6, 0x167e6, 0x1f628, 0x1fb16, 0x162fc, 0x1f624, 0x1627e, 0x1f622, 0x1e428, 0x1f216, 0x1ec68, 0x1f636, 0x1ec64, 0x1e422, 0x1ec62, 0x1c868, 0x1e436, 0x1d8e8, 0x1c864, 0x1d8e4, 0x1c862, 0x1d8e2, 0x190e8, 0x1c876, 0x1b1e8, 0x1d8f6, 0x1b1e4, 0x190e2, 0x1b1e2, 0x121e8, 0x190f6, 0x163e8, 0x121e4, 0x163e4, 0x121e2, 0x163e2, 0x121f6, 0x163f6, 0x1f614, 0x1617e, 0x1f612, 0x1e414, 0x1ec34, 0x1e412, 0x1ec32, 0x1c834, 0x1d874, 0x1c832, 0x1d872, 0x19074, 0x1b0f4, 0x19072, 0x1b0f2, 0x120f4, 0x161f4, 0x120f2, 0x161f2, 0x1f60a, 0x1e40a, 0x1ec1a, 0x1c81a, 0x1d83a, 0x1903a, 0x1b07a, 0x1e2a0, 0x1f158, 0x1f8ae, 0x1e290, 0x1f14c, 0x1e288, 0x1f146, 0x1e284, 0x1e282, 0x1c5a0, 0x1e2d8, 0x1f16e, 0x1c590, 0x1e2cc, 0x1c588, 0x1e2c6, 0x1c584, 0x1c582, 0x18ba0, 0x1c5d8, 0x1e2ee, 0x18b90, 0x1c5cc, 0x18b88, 0x1c5c6, 0x18b84, 0x18b82, 0x117a0, 0x18bd8, 0x1c5ee, 0x11790, 0x18bcc, 0x11788, 0x18bc6, 0x11784, 0x11782, 0x117d8, 0x18bee, 0x117cc, 0x117c6, 0x117ee, 0x1f350, 0x1f9ac, 0x135f8, 0x1f348, 0x1f9a6, 0x134fc, 0x1f344, 0x1347e, 0x1f342, 0x1e250, 0x1f12c, 0x1e6d0, 0x1e248, 0x1f126, 0x1e6c8, 0x1f366, 0x1e6c4, 0x1e242, 0x1e6c2, 0x1c4d0, 0x1e26c, 0x1cdd0, 0x1c4c8, 0x1e266, 0x1cdc8, 0x1e6e6, 0x1cdc4, 0x1c4c2, 0x1cdc2, 0x189d0, 0x1c4ec, 0x19bd0, 0x189c8, 0x1c4e6, 0x19bc8, 0x1cde6, 0x19bc4, 0x189c2, 0x19bc2, 0x113d0, 0x189ec, 0x137d0, 0x113c8, 0x189e6, 0x137c8, 0x19be6, 0x137c4, 0x113c2, 0x137c2, 0x113ec, 0x137ec, 0x113e6, 0x137e6, 0x1fba8, 0x175f0, 0x1bafc, 0x1fba4, 0x174f8, 0x1ba7e, 0x1fba2, 0x1747c, 0x1743e, 0x1f328, 0x1f996, 0x132fc, 0x1f768, 0x1fbb6, 0x176fc, 0x1327e, 0x1f764, 0x1f322, 0x1767e, 0x1f762, 0x1e228, 0x1f116, 0x1e668, 0x1e224, 0x1eee8, 0x1f776, 0x1e222, 0x1eee4, 0x1e662, 0x1eee2, 0x1c468, 0x1e236, 0x1cce8, 0x1c464, 0x1dde8, 0x1cce4, 0x1c462, 0x1dde4, 0x1cce2, 0x1dde2, 0x188e8, 0x1c476, 0x199e8, 0x188e4, 0x1bbe8, 0x199e4, 0x188e2, 0x1bbe4, 0x199e2, 0x1bbe2, 0x111e8, 0x188f6, 0x133e8, 0x111e4, 0x177e8, 0x133e4, 0x111e2, 0x177e4, 0x133e2, 0x177e2, 0x111f6, 0x133f6, 0x1fb94, 0x172f8, 0x1b97e, 0x1fb92, 0x1727c, 0x1723e, 0x1f314, 0x1317e, 0x1f734, 0x1f312, 0x1737e, 0x1f732, 0x1e214, 0x1e634, 0x1e212, 0x1ee74, 0x1e632, 0x1ee72, 0x1c434, 0x1cc74, 0x1c432, 0x1dcf4, 0x1cc72, 0x1dcf2, 0x18874, 0x198f4, 0x18872, 0x1b9f4, 0x198f2, 0x1b9f2, 0x110f4, 0x131f4, 0x110f2, 0x173f4, 0x131f2, 0x173f2, 0x1fb8a, 0x1717c, 0x1713e, 0x1f30a, 0x1f71a, 0x1e20a, 0x1e61a, 0x1ee3a, 0x1c41a, 0x1cc3a, 0x1dc7a, 0x1883a, 0x1987a, 0x1b8fa, 0x1107a, 0x130fa, 0x171fa, 0x170be, 0x1e150, 0x1f0ac, 0x1e148, 0x1f0a6, 0x1e144, 0x1e142, 0x1c2d0, 0x1e16c, 0x1c2c8, 0x1e166, 0x1c2c4, 0x1c2c2, 0x185d0, 0x1c2ec, 0x185c8, 0x1c2e6, 0x185c4, 0x185c2, 0x10bd0, 0x185ec, 0x10bc8, 0x185e6, 0x10bc4, 0x10bc2, 0x10bec, 0x10be6, 0x1f1a8, 0x1f8d6, 0x11afc, 0x1f1a4, 0x11a7e, 0x1f1a2, 0x1e128, 0x1f096, 0x1e368, 0x1e124, 0x1e364, 0x1e122, 0x1e362, 0x1c268, 0x1e136, 0x1c6e8, 0x1c264, 0x1c6e4, 0x1c262, 0x1c6e2, 0x184e8, 0x1c276, 0x18de8, 0x184e4, 0x18de4, 0x184e2, 0x18de2, 0x109e8, 0x184f6, 0x11be8, 0x109e4, 0x11be4, 0x109e2, 0x11be2, 0x109f6, 0x11bf6, 0x1f9d4, 0x13af8, 0x19d7e, 0x1f9d2, 0x13a7c, 0x13a3e, 0x1f194, 0x1197e, 0x1f3b4, 0x1f192, 0x13b7e, 0x1f3b2, 0x1e114, 0x1e334, 0x1e112, 0x1e774, 0x1e332, 0x1e772, 0x1c234, 0x1c674, 0x1c232, 0x1cef4, 0x1c672, 0x1cef2, 0x18474, 0x18cf4, 0x18472, 0x19df4, 0x18cf2, 0x19df2, 0x108f4, 0x119f4, 0x108f2, 0x13bf4, 0x119f2, 0x13bf2, 0x17af0, 0x1bd7c, 0x17a78, 0x1bd3e, 0x17a3c, 0x17a1e, 0x1f9ca, 0x1397c, 0x1fbda, 0x17b7c, 0x1393e, 0x17b3e, 0x1f18a, 0x1f39a, 0x1f7ba, 0x1e10a, 0x1e31a, 0x1e73a, 0x1ef7a, 0x1c21a, 0x1c63a, 0x1ce7a, 0x1defa, 0x1843a, 0x18c7a, 0x19cfa, 0x1bdfa, 0x1087a, 0x118fa, 0x139fa, 0x17978, 0x1bcbe, 0x1793c, 0x1791e, 0x138be, 0x179be, 0x178bc, 0x1789e, 0x1785e, 0x1e0a8, 0x1e0a4, 0x1e0a2, 0x1c168, 0x1e0b6, 0x1c164, 0x1c162, 0x182e8, 0x1c176, 0x182e4, 0x182e2, 0x105e8, 0x182f6, 0x105e4, 0x105e2, 0x105f6, 0x1f0d4, 0x10d7e, 0x1f0d2, 0x1e094, 0x1e1b4, 0x1e092, 0x1e1b2, 0x1c134, 0x1c374, 0x1c132, 0x1c372, 0x18274, 0x186f4, 0x18272, 0x186f2, 0x104f4, 0x10df4, 0x104f2, 0x10df2, 0x1f8ea, 0x11d7c, 0x11d3e, 0x1f0ca, 0x1f1da, 0x1e08a, 0x1e19a, 0x1e3ba, 0x1c11a, 0x1c33a, 0x1c77a, 0x1823a, 0x1867a, 0x18efa, 0x1047a, 0x10cfa, 0x11dfa, 0x13d78, 0x19ebe, 0x13d3c, 0x13d1e, 0x11cbe, 0x13dbe, 0x17d70, 0x1bebc, 0x17d38, 0x1be9e, 0x17d1c, 0x17d0e, 0x13cbc, 0x17dbc, 0x13c9e, 0x17d9e, 0x17cb8, 0x1be5e, 0x17c9c, 0x17c8e, 0x13c5e, 0x17cde, 0x17c5c, 0x17c4e, 0x17c2e, 0x1c0b4, 0x1c0b2, 0x18174, 0x18172, 0x102f4, 0x102f2, 0x1e0da, 0x1c09a, 0x1c1ba, 0x1813a, 0x1837a, 0x1027a, 0x106fa, 0x10ebe, 0x11ebc, 0x11e9e, 0x13eb8, 0x19f5e, 0x13e9c, 0x13e8e, 0x11e5e, 0x13ede, 0x17eb0, 0x1bf5c, 0x17e98, 0x1bf4e, 0x17e8c, 0x17e86, 0x13e5c, 0x17edc, 0x13e4e, 0x17ece, 0x17e58, 0x1bf2e, 0x17e4c, 0x17e46, 0x13e2e, 0x17e6e, 0x17e2c, 0x17e26, 0x10f5e, 0x11f5c, 0x11f4e, 0x13f58, 0x19fae, 0x13f4c, 0x13f46, 0x11f2e, 0x13f6e, 0x13f2c, 0x13f26], [0x1abe0, 0x1d5f8, 0x153c0, 0x1a9f0, 0x1d4fc, 0x151e0, 0x1a8f8, 0x1d47e, 0x150f0, 0x1a87c, 0x15078, 0x1fad0, 0x15be0, 0x1adf8, 0x1fac8, 0x159f0, 0x1acfc, 0x1fac4, 0x158f8, 0x1ac7e, 0x1fac2, 0x1587c, 0x1f5d0, 0x1faec, 0x15df8, 0x1f5c8, 0x1fae6, 0x15cfc, 0x1f5c4, 0x15c7e, 0x1f5c2, 0x1ebd0, 0x1f5ec, 0x1ebc8, 0x1f5e6, 0x1ebc4, 0x1ebc2, 0x1d7d0, 0x1ebec, 0x1d7c8, 0x1ebe6, 0x1d7c4, 0x1d7c2, 0x1afd0, 0x1d7ec, 0x1afc8, 0x1d7e6, 0x1afc4, 0x14bc0, 0x1a5f0, 0x1d2fc, 0x149e0, 0x1a4f8, 0x1d27e, 0x148f0, 0x1a47c, 0x14878, 0x1a43e, 0x1483c, 0x1fa68, 0x14df0, 0x1a6fc, 0x1fa64, 0x14cf8, 0x1a67e, 0x1fa62, 0x14c7c, 0x14c3e, 0x1f4e8, 0x1fa76, 0x14efc, 0x1f4e4, 0x14e7e, 0x1f4e2, 0x1e9e8, 0x1f4f6, 0x1e9e4, 0x1e9e2, 0x1d3e8, 0x1e9f6, 0x1d3e4, 0x1d3e2, 0x1a7e8, 0x1d3f6, 0x1a7e4, 0x1a7e2, 0x145e0, 0x1a2f8, 0x1d17e, 0x144f0, 0x1a27c, 0x14478, 0x1a23e, 0x1443c, 0x1441e, 0x1fa34, 0x146f8, 0x1a37e, 0x1fa32, 0x1467c, 0x1463e, 0x1f474, 0x1477e, 0x1f472, 0x1e8f4, 0x1e8f2, 0x1d1f4, 0x1d1f2, 0x1a3f4, 0x1a3f2, 0x142f0, 0x1a17c, 0x14278, 0x1a13e, 0x1423c, 0x1421e, 0x1fa1a, 0x1437c, 0x1433e, 0x1f43a, 0x1e87a, 0x1d0fa, 0x14178, 0x1a0be, 0x1413c, 0x1411e, 0x141be, 0x140bc, 0x1409e, 0x12bc0, 0x195f0, 0x1cafc, 0x129e0, 0x194f8, 0x1ca7e, 0x128f0, 0x1947c, 0x12878, 0x1943e, 0x1283c, 0x1f968, 0x12df0, 0x196fc, 0x1f964, 0x12cf8, 0x1967e, 0x1f962, 0x12c7c, 0x12c3e, 0x1f2e8, 0x1f976, 0x12efc, 0x1f2e4, 0x12e7e, 0x1f2e2, 0x1e5e8, 0x1f2f6, 0x1e5e4, 0x1e5e2, 0x1cbe8, 0x1e5f6, 0x1cbe4, 0x1cbe2, 0x197e8, 0x1cbf6, 0x197e4, 0x197e2, 0x1b5e0, 0x1daf8, 0x1ed7e, 0x169c0, 0x1b4f0, 0x1da7c, 0x168e0, 0x1b478, 0x1da3e, 0x16870, 0x1b43c, 0x16838, 0x1b41e, 0x1681c, 0x125e0, 0x192f8, 0x1c97e, 0x16de0, 0x124f0, 0x1927c, 0x16cf0, 0x1b67c, 0x1923e, 0x16c78, 0x1243c, 0x16c3c, 0x1241e, 0x16c1e, 0x1f934, 0x126f8, 0x1937e, 0x1fb74, 0x1f932, 0x16ef8, 0x1267c, 0x1fb72, 0x16e7c, 0x1263e, 0x16e3e, 0x1f274, 0x1277e, 0x1f6f4, 0x1f272, 0x16f7e, 0x1f6f2, 0x1e4f4, 0x1edf4, 0x1e4f2, 0x1edf2, 0x1c9f4, 0x1dbf4, 0x1c9f2, 0x1dbf2, 0x193f4, 0x193f2, 0x165c0, 0x1b2f0, 0x1d97c, 0x164e0, 0x1b278, 0x1d93e, 0x16470, 0x1b23c, 0x16438, 0x1b21e, 0x1641c, 0x1640e, 0x122f0, 0x1917c, 0x166f0, 0x12278, 0x1913e, 0x16678, 0x1b33e, 0x1663c, 0x1221e, 0x1661e, 0x1f91a, 0x1237c, 0x1fb3a, 0x1677c, 0x1233e, 0x1673e, 0x1f23a, 0x1f67a, 0x1e47a, 0x1ecfa, 0x1c8fa, 0x1d9fa, 0x191fa, 0x162e0, 0x1b178, 0x1d8be, 0x16270, 0x1b13c, 0x16238, 0x1b11e, 0x1621c, 0x1620e, 0x12178, 0x190be, 0x16378, 0x1213c, 0x1633c, 0x1211e, 0x1631e, 0x121be, 0x163be, 0x16170, 0x1b0bc, 0x16138, 0x1b09e, 0x1611c, 0x1610e, 0x120bc, 0x161bc, 0x1209e, 0x1619e, 0x160b8, 0x1b05e, 0x1609c, 0x1608e, 0x1205e, 0x160de, 0x1605c, 0x1604e, 0x115e0, 0x18af8, 0x1c57e, 0x114f0, 0x18a7c, 0x11478, 0x18a3e, 0x1143c, 0x1141e, 0x1f8b4, 0x116f8, 0x18b7e, 0x1f8b2, 0x1167c, 0x1163e, 0x1f174, 0x1177e, 0x1f172, 0x1e2f4, 0x1e2f2, 0x1c5f4, 0x1c5f2, 0x18bf4, 0x18bf2, 0x135c0, 0x19af0, 0x1cd7c, 0x134e0, 0x19a78, 0x1cd3e, 0x13470, 0x19a3c, 0x13438, 0x19a1e, 0x1341c, 0x1340e, 0x112f0, 0x1897c, 0x136f0, 0x11278, 0x1893e, 0x13678, 0x19b3e, 0x1363c, 0x1121e, 0x1361e, 0x1f89a, 0x1137c, 0x1f9ba, 0x1377c, 0x1133e, 0x1373e, 0x1f13a, 0x1f37a, 0x1e27a, 0x1e6fa, 0x1c4fa, 0x1cdfa, 0x189fa, 0x1bae0, 0x1dd78, 0x1eebe, 0x174c0, 0x1ba70, 0x1dd3c, 0x17460, 0x1ba38, 0x1dd1e, 0x17430, 0x1ba1c, 0x17418, 0x1ba0e, 0x1740c, 0x132e0, 0x19978, 0x1ccbe, 0x176e0, 0x13270, 0x1993c, 0x17670, 0x1bb3c, 0x1991e, 0x17638, 0x1321c, 0x1761c, 0x1320e, 0x1760e, 0x11178, 0x188be, 0x13378, 0x1113c, 0x17778, 0x1333c, 0x1111e, 0x1773c, 0x1331e, 0x1771e, 0x111be, 0x133be, 0x177be, 0x172c0, 0x1b970, 0x1dcbc, 0x17260, 0x1b938, 0x1dc9e, 0x17230, 0x1b91c, 0x17218, 0x1b90e, 0x1720c, 0x17206, 0x13170, 0x198bc, 0x17370, 0x13138, 0x1989e, 0x17338, 0x1b99e, 0x1731c, 0x1310e, 0x1730e, 0x110bc, 0x131bc, 0x1109e, 0x173bc, 0x1319e, 0x1739e, 0x17160, 0x1b8b8, 0x1dc5e, 0x17130, 0x1b89c, 0x17118, 0x1b88e, 0x1710c, 0x17106, 0x130b8, 0x1985e, 0x171b8, 0x1309c, 0x1719c, 0x1308e, 0x1718e, 0x1105e, 0x130de, 0x171de, 0x170b0, 0x1b85c, 0x17098, 0x1b84e, 0x1708c, 0x17086, 0x1305c, 0x170dc, 0x1304e, 0x170ce, 0x17058, 0x1b82e, 0x1704c, 0x17046, 0x1302e, 0x1706e, 0x1702c, 0x17026, 0x10af0, 0x1857c, 0x10a78, 0x1853e, 0x10a3c, 0x10a1e, 0x10b7c, 0x10b3e, 0x1f0ba, 0x1e17a, 0x1c2fa, 0x185fa, 0x11ae0, 0x18d78, 0x1c6be, 0x11a70, 0x18d3c, 0x11a38, 0x18d1e, 0x11a1c, 0x11a0e, 0x10978, 0x184be, 0x11b78, 0x1093c, 0x11b3c, 0x1091e, 0x11b1e, 0x109be, 0x11bbe, 0x13ac0, 0x19d70, 0x1cebc, 0x13a60, 0x19d38, 0x1ce9e, 0x13a30, 0x19d1c, 0x13a18, 0x19d0e, 0x13a0c, 0x13a06, 0x11970, 0x18cbc, 0x13b70, 0x11938, 0x18c9e, 0x13b38, 0x1191c, 0x13b1c, 0x1190e, 0x13b0e, 0x108bc, 0x119bc, 0x1089e, 0x13bbc, 0x1199e, 0x13b9e, 0x1bd60, 0x1deb8, 0x1ef5e, 0x17a40, 0x1bd30, 0x1de9c, 0x17a20, 0x1bd18, 0x1de8e, 0x17a10, 0x1bd0c, 0x17a08, 0x1bd06, 0x17a04, 0x13960, 0x19cb8, 0x1ce5e, 0x17b60, 0x13930, 0x19c9c, 0x17b30, 0x1bd9c, 0x19c8e, 0x17b18, 0x1390c, 0x17b0c, 0x13906, 0x17b06, 0x118b8, 0x18c5e, 0x139b8, 0x1189c, 0x17bb8, 0x1399c, 0x1188e, 0x17b9c, 0x1398e, 0x17b8e, 0x1085e, 0x118de, 0x139de, 0x17bde, 0x17940, 0x1bcb0, 0x1de5c, 0x17920, 0x1bc98, 0x1de4e, 0x17910, 0x1bc8c, 0x17908, 0x1bc86, 0x17904, 0x17902, 0x138b0, 0x19c5c, 0x179b0, 0x13898, 0x19c4e, 0x17998, 0x1bcce, 0x1798c, 0x13886, 0x17986, 0x1185c, 0x138dc, 0x1184e, 0x179dc, 0x138ce, 0x179ce, 0x178a0, 0x1bc58, 0x1de2e, 0x17890, 0x1bc4c, 0x17888, 0x1bc46, 0x17884, 0x17882, 0x13858, 0x19c2e, 0x178d8, 0x1384c, 0x178cc, 0x13846, 0x178c6, 0x1182e, 0x1386e, 0x178ee, 0x17850, 0x1bc2c, 0x17848, 0x1bc26, 0x17844, 0x17842, 0x1382c, 0x1786c, 0x13826, 0x17866, 0x17828, 0x1bc16, 0x17824, 0x17822, 0x13816, 0x17836, 0x10578, 0x182be, 0x1053c, 0x1051e, 0x105be, 0x10d70, 0x186bc, 0x10d38, 0x1869e, 0x10d1c, 0x10d0e, 0x104bc, 0x10dbc, 0x1049e, 0x10d9e, 0x11d60, 0x18eb8, 0x1c75e, 0x11d30, 0x18e9c, 0x11d18, 0x18e8e, 0x11d0c, 0x11d06, 0x10cb8, 0x1865e, 0x11db8, 0x10c9c, 0x11d9c, 0x10c8e, 0x11d8e, 0x1045e, 0x10cde, 0x11dde, 0x13d40, 0x19eb0, 0x1cf5c, 0x13d20, 0x19e98, 0x1cf4e, 0x13d10, 0x19e8c, 0x13d08, 0x19e86, 0x13d04, 0x13d02, 0x11cb0, 0x18e5c, 0x13db0, 0x11c98, 0x18e4e, 0x13d98, 0x19ece, 0x13d8c, 0x11c86, 0x13d86, 0x10c5c, 0x11cdc, 0x10c4e, 0x13ddc, 0x11cce, 0x13dce, 0x1bea0, 0x1df58, 0x1efae, 0x1be90, 0x1df4c, 0x1be88, 0x1df46, 0x1be84, 0x1be82, 0x13ca0, 0x19e58, 0x1cf2e, 0x17da0, 0x13c90, 0x19e4c, 0x17d90, 0x1becc, 0x19e46, 0x17d88, 0x13c84, 0x17d84, 0x13c82, 0x17d82, 0x11c58, 0x18e2e, 0x13cd8, 0x11c4c, 0x17dd8, 0x13ccc, 0x11c46, 0x17dcc, 0x13cc6, 0x17dc6, 0x10c2e, 0x11c6e, 0x13cee, 0x17dee, 0x1be50, 0x1df2c, 0x1be48, 0x1df26, 0x1be44, 0x1be42, 0x13c50, 0x19e2c, 0x17cd0, 0x13c48, 0x19e26, 0x17cc8, 0x1be66, 0x17cc4, 0x13c42, 0x17cc2, 0x11c2c, 0x13c6c, 0x11c26, 0x17cec, 0x13c66, 0x17ce6, 0x1be28, 0x1df16, 0x1be24, 0x1be22, 0x13c28, 0x19e16, 0x17c68, 0x13c24, 0x17c64, 0x13c22, 0x17c62, 0x11c16, 0x13c36, 0x17c76, 0x1be14, 0x1be12, 0x13c14, 0x17c34, 0x13c12, 0x17c32, 0x102bc, 0x1029e, 0x106b8, 0x1835e, 0x1069c, 0x1068e, 0x1025e, 0x106de, 0x10eb0, 0x1875c, 0x10e98, 0x1874e, 0x10e8c, 0x10e86, 0x1065c, 0x10edc, 0x1064e, 0x10ece, 0x11ea0, 0x18f58, 0x1c7ae, 0x11e90, 0x18f4c, 0x11e88, 0x18f46, 0x11e84, 0x11e82, 0x10e58, 0x1872e, 0x11ed8, 0x18f6e, 0x11ecc, 0x10e46, 0x11ec6, 0x1062e, 0x10e6e, 0x11eee, 0x19f50, 0x1cfac, 0x19f48, 0x1cfa6, 0x19f44, 0x19f42, 0x11e50, 0x18f2c, 0x13ed0, 0x19f6c, 0x18f26, 0x13ec8, 0x11e44, 0x13ec4, 0x11e42, 0x13ec2, 0x10e2c, 0x11e6c, 0x10e26, 0x13eec, 0x11e66, 0x13ee6, 0x1dfa8, 0x1efd6, 0x1dfa4, 0x1dfa2, 0x19f28, 0x1cf96, 0x1bf68, 0x19f24, 0x1bf64, 0x19f22, 0x1bf62, 0x11e28, 0x18f16, 0x13e68, 0x11e24, 0x17ee8, 0x13e64, 0x11e22, 0x17ee4, 0x13e62, 0x17ee2, 0x10e16, 0x11e36, 0x13e76, 0x17ef6, 0x1df94, 0x1df92, 0x19f14, 0x1bf34, 0x19f12, 0x1bf32, 0x11e14, 0x13e34, 0x11e12, 0x17e74, 0x13e32, 0x17e72, 0x1df8a, 0x19f0a, 0x1bf1a, 0x11e0a, 0x13e1a, 0x17e3a, 0x1035c, 0x1034e, 0x10758, 0x183ae, 0x1074c, 0x10746, 0x1032e, 0x1076e, 0x10f50, 0x187ac, 0x10f48, 0x187a6, 0x10f44, 0x10f42, 0x1072c, 0x10f6c, 0x10726, 0x10f66, 0x18fa8, 0x1c7d6, 0x18fa4, 0x18fa2, 0x10f28, 0x18796, 0x11f68, 0x18fb6, 0x11f64, 0x10f22, 0x11f62, 0x10716, 0x10f36, 0x11f76, 0x1cfd4, 0x1cfd2, 0x18f94, 0x19fb4, 0x18f92, 0x19fb2, 0x10f14, 0x11f34, 0x10f12, 0x13f74, 0x11f32, 0x13f72, 0x1cfca, 0x18f8a, 0x19f9a, 0x10f0a, 0x11f1a, 0x13f3a, 0x103ac, 0x103a6, 0x107a8, 0x183d6, 0x107a4, 0x107a2, 0x10396, 0x107b6, 0x187d4, 0x187d2, 0x10794, 0x10fb4, 0x10792, 0x10fb2, 0x1c7ea]]; private static var MIN_COLS:int = 2; private static var MAX_COLS:int = 30; private static var MAX_ROWS:int = 30; private static var MIN_ROWS:int = 2; private static var DEFAULT_MODULE_WIDTH:Number = 0.357; //1px in mm private static var HEIGHT:Number = 16.0; //mm private var errorCorrectionLevel:int; private var barcodeMatrix:BarcodeMatrix; public function getBarcodeMatrix():BarcodeMatrix { return barcodeMatrix; } /** * Calculates the necessary number of rows as described in annex Q of ISO/IEC 15438:2001(E). * * @param m the number of source codewords prior to the additional of the Symbol Length * Descriptor and any pad codewords * @param k the number of error correction codewords * @param c the number of columns in the symbol in the data region (excluding start, stop and * row indicator codewords) * @return the number of rows in the symbol (r) */ private static function getNumberOfRows(m:int, k:int, c:int):int { var r:int = calculateNumberOfRows(m, k, c); if (r > 90) { throw new WriterException( "The message doesn't fit in the configured symbol size." + " The resultant number of rows for this barcode exceeds 90." + " Please increase the number of columns or decrease the error correction" + " level to reduce the number of rows."); } if (r < 2) { throw new WriterException( "The message is too short for the configured symbol size." + " The resultant number of rows is less than 3." + " Please decrease the number of columns or increase the error correction" + " level to increase the number of rows."); } return r; } /** * Calculates the necessary number of rows as described in annex Q of ISO/IEC 15438:2001(E). * * @param m the number of source codewords prior to the additional of the Symbol Length * Descriptor and any pad codewords * @param k the number of error correction codewords * @param c the number of columns in the symbol in the data region (excluding start, stop and * row indicator codewords) * @return the number of rows in the symbol (r) */ private static function calculateNumberOfRows(m:int, k:int, c:int):int { var r:int = int((m + 1 + k) / c) + 1; if (c * r >= (m + 1 + k + c)) { r--; } return r; } /** * Calculates the number of pad codewords as described in 4.9.2 of ISO/IEC 15438:2001(E). * * @param m the number of source codewords prior to the additional of the Symbol Length * Descriptor and any pad codewords * @param k the number of error correction codewords * @param c the number of columns in the symbol in the data region (excluding start, stop and * row indicator codewords) * @param r the number of rows in the symbol * @return the number of pad codewords */ private static function getNumberOfPadCodewords(m:int, k:int, c:int, r:int):int { var n:int = c * r - k; return n > m + 1 ? n - m - 1 : 0; } /** * Calculates the number of data codewords (equals the Symbol Length Descriptor). * * @param m the number of source codewords prior to the additional of the Symbol Length * Descriptor and any pad codewords * @param errorCorrectionLevel the error correction level (value between 0 and 8) * @param c the number of columns in the symbol in the data region (excluding start, stop and * row indicator codewords) * @return the number of data codewords */ private static function getNumberOfDataCodewords(m:int, errorCorrectionLevel:int, c:int):int { var k:int = PDF417ErrorCorrection.getErrorCorrectionCodewordCount(errorCorrectionLevel); var r:int = getNumberOfRows(m, k, c); return c * r - k; } private static function encodeChar(pattern:int, len:int, logic:BarcodeRow):void { var map:int = 1 << len - 1; var last:Boolean = (pattern & map) != 0; //Initialize to inverse of first bit var width:int = 0; for (var i:int = 0; i < len; i++) { var black:Boolean = (pattern & map) != 0; if (last == black) { width++; } else { logic.addBar(last, width); last = black; width = 1; } map >>= 1; } logic.addBar(last, width); } private function encodeLowLevel(fullCodewords:String, c:int, r:int, errorCorrectionLevel:int, logic:BarcodeMatrix ):void { this.errorCorrectionLevel = errorCorrectionLevel; var idx:int = 0; for (var y:int = 0; y < r; y++) { var cluster:int = y % 3; logic.startRow(); var bcr:BarcodeRow = logic.getCurrentRow(); encodeChar(START_PATTERN, 17, bcr ); var left:int; var right:int; if (cluster == 0) { left = (30 * int(y / 3)) + int((r - 1) / 3); right = (30 * int(y / 3)) + (c - 1); } else if (cluster == 1) { left = (30 * int(y / 3)) + (errorCorrectionLevel * 3) + int((r - 1) % 3); right = (30 * int(y / 3)) + int((r - 1) / 3); } else { left = (30 * int(y / 3)) + (c - 1); right = (30 * int(y / 3)) + (errorCorrectionLevel * 3) + int((r - 1) % 3); } var pattern:int = CODEWORD_TABLE[cluster][left]; encodeChar(pattern, 17, logic.getCurrentRow()); for (var x:int = 0; x < c; x++) { pattern = CODEWORD_TABLE[cluster][fullCodewords.charCodeAt(idx)]; encodeChar(pattern, 17, logic.getCurrentRow()); idx++; } pattern = CODEWORD_TABLE[cluster][right]; encodeChar(pattern, 17, logic.getCurrentRow()); encodeChar(STOP_PATTERN, 18, logic.getCurrentRow()); } } /** * Generates the barcode logic. * * @param msg the message to encode */ public function generateBarcodeLogic(msg:String, errorCorrectionLevel:int):void { //1. step: High-level encoding var errorCorrectionCodeWords:int = PDF417ErrorCorrection.getErrorCorrectionCodewordCount(errorCorrectionLevel); // actionscript does not allow static code parts so we need an instance of the PDF417HighLevelEncoder var phe:PDF417HighLevelEncoder = new PDF417HighLevelEncoder(); var highLevel:String = phe.encodeHighLevel(msg); var sourceCodeWords:int = highLevel.length; var dimension:Array = determineDimensions(sourceCodeWords); if (dimension == null) { throw new WriterException("Unable to fit message in columns"); } var cols:int = dimension[0]; var rows:int = dimension[1]; var pad:int = getNumberOfPadCodewords(sourceCodeWords, errorCorrectionCodeWords, cols, rows); //2. step: construct data codewords var n:int = getNumberOfDataCodewords(sourceCodeWords, errorCorrectionLevel, cols); if (n > 929) { throw new WriterException( "Encoded message contains to many code words, message to big (" + msg.length + " bytes)"); } var sb:StringBuilder = new StringBuilder(n); sb.Append(String.fromCharCode(n)); sb.Append(highLevel); for (var i:int = 0; i < pad; i++) { sb.Append("900"); //PAD characters } var dataCodewords:String = sb.toString(); //3. step: Error correction var ec:String = PDF417ErrorCorrection.generateErrorCorrection(dataCodewords, errorCorrectionLevel); var fullCodewords:String = dataCodewords + ec; //4. step: low-level encoding barcodeMatrix = new BarcodeMatrix(rows, cols); encodeLowLevel(fullCodewords, cols, rows, errorCorrectionLevel, barcodeMatrix); } /** * Determine optimal nr of columns and rows for the specified number of * codewords. * * @param sourceCodeWords number of code words * @return dimension object containing cols as width and rows as height */ public function determineDimensions(sourceCodeWords:int):Array { var ratio:Number = 0.0; var dimension:Array = null; var errorCorrectionCodeWords:int = PDF417ErrorCorrection.getErrorCorrectionCodewordCount(errorCorrectionLevel); for (var cols:int = MIN_COLS; cols <= MAX_COLS; cols++) { var rows:int = calculateNumberOfRows(sourceCodeWords, errorCorrectionCodeWords, cols); if (rows < MIN_ROWS) { break; } if (rows > MAX_ROWS) { continue; } var newRatio:Number = ((17 * cols + 69) * DEFAULT_MODULE_WIDTH) / (rows * HEIGHT); // ignore if previous ratio is closer to preferred ratio var preferredRatio:Number = 3.0; if (dimension != null && Math.abs(newRatio - preferredRatio) > Math.abs(ratio - preferredRatio)) { continue; } ratio = newRatio; dimension = [cols, rows]; } return dimension; } } }
package com.playfab.ServerModels { public class GetSharedGroupDataResult { public var Data:Object; public var Members:Vector.<String>; public function GetSharedGroupDataResult(data:Object=null) { if(data == null) return; if(data.Data) { Data = {}; for(var Data_iter:String in data.Data) { Data[Data_iter] = new SharedGroupDataRecord(data.Data[Data_iter]); }} Members = data.Members ? Vector.<String>(data.Members) : null; } } }