commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
dcc72cfec1f403de0b83a82002e32dddbfd6d540
OSMF/org/osmf/net/httpstreaming/flv/FLVParser.as
OSMF/org/osmf/net/httpstreaming/flv/FLVParser.as
/***************************************************** * * 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.net.httpstreaming.flv { import flash.utils.ByteArray; import flash.utils.IDataInput; import flash.utils.IDataOutput; [ExcludeClass] /** * @private */ public class FLVParser { public function FLVParser(startWithFileHeader:Boolean) { super(); savedBytes = new ByteArray(); if (startWithFileHeader) { state = FLVParserState.FILE_HEADER; } else { state = FLVParserState.TYPE; } } public function flush(output:IDataOutput):void { output.writeBytes(savedBytes); } public function parse(input:IDataInput, consumeAll:Boolean, onEachFLVTag:Function):void { var continueParsing:Boolean = true; var source:IDataInput; var date:Date = new Date(); while (continueParsing) { switch (state) { case FLVParserState.FILE_HEADER: source = byteSource(input, FLVHeader.MIN_FILE_HEADER_BYTE_COUNT); if (source != null) { flvHeader = new FLVHeader(); flvHeader.readHeader(source); state = FLVParserState.FILE_HEADER_REST; } else { continueParsing = false; } break; case FLVParserState.FILE_HEADER_REST: source = byteSource(input, flvHeader.restBytesNeeded); if (source != null) { flvHeader.readRest(source); state = FLVParserState.TYPE; } else { continueParsing = false; } break; case FLVParserState.TYPE: source = byteSource(input, 1); // just the first byte of the header if (source != null) { var type:int = source.readByte(); switch (type) { case FLVTag.TAG_TYPE_AUDIO: case FLVTag.TAG_TYPE_ENCRYPTED_AUDIO: currentTag = new FLVTagAudio(type); break; case FLVTag.TAG_TYPE_VIDEO: case FLVTag.TAG_TYPE_ENCRYPTED_VIDEO: currentTag = new FLVTagVideo(type); break; case FLVTag.TAG_TYPE_SCRIPTDATAOBJECT: case FLVTag.TAG_TYPE_ENCRYPTED_SCRIPTDATAOBJECT: currentTag = new FLVTagScriptDataObject(type); break; default: trace("Unknown tag type " + type); currentTag = new FLVTag(type); // the generic case break; } state = FLVParserState.HEADER; } else { continueParsing = false; } break; case FLVParserState.HEADER: source = byteSource(input, FLVTag.TAG_HEADER_BYTE_COUNT - 1); // first byte was read in previous state if (source != null) { currentTag.readRemainingHeader(source); if (currentTag.dataSize) { state = FLVParserState.DATA; } else { state = FLVParserState.PREV_TAG; } } else { continueParsing = false; } break; case FLVParserState.DATA: source = byteSource(input, currentTag.dataSize); if (source != null) { currentTag.readData(source); state = FLVParserState.PREV_TAG; } else { continueParsing = false; } break; case FLVParserState.PREV_TAG: source = byteSource(input, FLVTag.PREV_TAG_BYTE_COUNT); if (source != null) { currentTag.readPrevTag(source); state = FLVParserState.TYPE; continueParsing = onEachFLVTag(currentTag); } else { continueParsing = false; } break; default: throw new Error("FLVParser state machine in unknown state"); break; } // switch } // while continueParsing if (consumeAll) { input.readBytes(savedBytes, savedBytes.length); } trace("savedBytes.length = " + savedBytes.length); } // parse private function byteSource(input:IDataInput, numBytes:int):IDataInput { //trace("byteSource - " + numBytes); if (savedBytes.bytesAvailable + input.bytesAvailable < numBytes) { //trace("byteSource - " + numBytes + " not available"); return null; } if (savedBytes.bytesAvailable) { var needed:int = numBytes - savedBytes.bytesAvailable; if (needed > 0) { input.readBytes(savedBytes, savedBytes.length, needed); } return savedBytes; } savedBytes.length = 0; return input; } private var state:String; private var savedBytes:ByteArray; private var currentTag:FLVTag = null; private var flvHeader:FLVHeader; } }
/***************************************************** * * 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.net.httpstreaming.flv { import flash.utils.ByteArray; import flash.utils.IDataInput; import flash.utils.IDataOutput; [ExcludeClass] /** * @private */ public class FLVParser { public function FLVParser(startWithFileHeader:Boolean) { super(); savedBytes = new ByteArray(); if (startWithFileHeader) { state = FLVParserState.FILE_HEADER; } else { state = FLVParserState.TYPE; } } public function flush(output:IDataOutput):void { output.writeBytes(savedBytes); } public function parse(input:IDataInput, consumeAll:Boolean, onEachFLVTag:Function):void { var continueParsing:Boolean = true; var source:IDataInput; var date:Date = new Date(); while (continueParsing) { switch (state) { case FLVParserState.FILE_HEADER: source = byteSource(input, FLVHeader.MIN_FILE_HEADER_BYTE_COUNT); if (source != null) { flvHeader = new FLVHeader(); flvHeader.readHeader(source); state = FLVParserState.FILE_HEADER_REST; } else { continueParsing = false; } break; case FLVParserState.FILE_HEADER_REST: source = byteSource(input, flvHeader.restBytesNeeded); if (source != null) { flvHeader.readRest(source); state = FLVParserState.TYPE; } else { continueParsing = false; } break; case FLVParserState.TYPE: source = byteSource(input, 1); // just the first byte of the header if (source != null) { var type:int = source.readByte(); switch (type) { case FLVTag.TAG_TYPE_AUDIO: case FLVTag.TAG_TYPE_ENCRYPTED_AUDIO: currentTag = new FLVTagAudio(type); break; case FLVTag.TAG_TYPE_VIDEO: case FLVTag.TAG_TYPE_ENCRYPTED_VIDEO: currentTag = new FLVTagVideo(type); break; case FLVTag.TAG_TYPE_SCRIPTDATAOBJECT: case FLVTag.TAG_TYPE_ENCRYPTED_SCRIPTDATAOBJECT: currentTag = new FLVTagScriptDataObject(type); break; default: trace("Unknown tag type " + type); currentTag = new FLVTag(type); // the generic case break; } state = FLVParserState.HEADER; } else { continueParsing = false; } break; case FLVParserState.HEADER: source = byteSource(input, FLVTag.TAG_HEADER_BYTE_COUNT - 1); // first byte was read in previous state if (source != null) { currentTag.readRemainingHeader(source); if (currentTag.dataSize) { state = FLVParserState.DATA; } else { state = FLVParserState.PREV_TAG; } } else { continueParsing = false; } break; case FLVParserState.DATA: source = byteSource(input, currentTag.dataSize); if (source != null) { currentTag.readData(source); state = FLVParserState.PREV_TAG; } else { continueParsing = false; } break; case FLVParserState.PREV_TAG: source = byteSource(input, FLVTag.PREV_TAG_BYTE_COUNT); if (source != null) { currentTag.readPrevTag(source); state = FLVParserState.TYPE; continueParsing = onEachFLVTag(currentTag); } else { continueParsing = false; } break; default: throw new Error("FLVParser state machine in unknown state"); break; } // switch } // while continueParsing if (consumeAll) { input.readBytes(savedBytes, savedBytes.length); } //trace("savedBytes.length = " + savedBytes.length); } // parse private function byteSource(input:IDataInput, numBytes:int):IDataInput { //trace("byteSource - " + numBytes); if (savedBytes.bytesAvailable + input.bytesAvailable < numBytes) { //trace("byteSource - " + numBytes + " not available"); return null; } if (savedBytes.bytesAvailable) { var needed:int = numBytes - savedBytes.bytesAvailable; if (needed > 0) { input.readBytes(savedBytes, savedBytes.length, needed); } return savedBytes; } savedBytes.length = 0; return input; } private var state:String; private var savedBytes:ByteArray; private var currentTag:FLVTag = null; private var flvHeader:FLVHeader; } }
Disable unneeded logging.
Disable unneeded logging.
ActionScript
agpl-3.0
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
ef396dfd71f86e157eea3a8ca57f7ce123a31323
src/Impetus.as
src/Impetus.as
package io.github.jwhile.impetus { import flash.display.Sprite; import flash.external.ExternalInterface; public class Impetus extends Sprite { public function Impetus():void { } } }
package io.github.jwhile.impetus { import flash.display.Sprite; import flash.external.ExternalInterface; public class Impetus extends Sprite { public function Impetus():void { if(ExternalInterface.available) { ExternalInterface.addCallback('getPlayer', getPlayer); ExternalInterface.call("console.log", "Impetus loaded. (https://github.com/JWhile/Impetus)"); } } } }
Load ExternalInterface if available
Load ExternalInterface if available
ActionScript
mit
Julow/Impetus
e6c6536939fe437943c571ab0d0a6552a216e474
src/com/axis/audioclient/AxisTransmit.as
src/com/axis/audioclient/AxisTransmit.as
package com.axis.audioclient { import flash.events.Event; import flash.events.ProgressEvent; import flash.events.ErrorEvent; import flash.events.SampleDataEvent; import flash.events.StatusEvent; import flash.events.SecurityErrorEvent; import flash.events.IOErrorEvent; import flash.net.Socket; import flash.media.Microphone; import flash.media.SoundCodec; import flash.utils.ByteArray; import com.axis.codec.g711; import com.axis.http.url; import com.axis.http.auth; import com.axis.http.request; public class AxisTransmit { private var urlParsed:Object = {}; private var conn:Socket = new Socket(); private var authState:String = 'none'; private var authOpts:Object = {}; public function AxisTransmit() { } private function onMicStatus(event:StatusEvent):void { if (conn.connected) { authState = 'none'; conn.close(); } if ('Microphone.Muted' === event.code) { trace('AxisTransmit: Denied access to microphone'); return; } if (urlParsed.host && urlParsed.port) { conn.connect(urlParsed.host, urlParsed.port); } } public function start(iurl:String):void { if (conn.connected) { trace('already connected'); return; } var mic:Microphone = Microphone.getMicrophone(); mic.rate = 16; mic.setSilenceLevel(0, -1); mic.addEventListener(StatusEvent.STATUS, onMicStatus); mic.addEventListener(SampleDataEvent.SAMPLE_DATA, onMicSampleData); this.urlParsed = url.parse(iurl); conn = new Socket(); conn.addEventListener(Event.CONNECT, onConnected); conn.addEventListener(Event.CLOSE, onClosed); conn.addEventListener(ProgressEvent.SOCKET_DATA, onRequestData); conn.addEventListener(IOErrorEvent.IO_ERROR, onError); conn.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); if (true === mic.muted) { trace('Not allowed access to microphone, delay connect'); return; } conn.connect(urlParsed.host, urlParsed.port); } public function stop():void { if (!conn.connected) { trace('not connected'); return; } var mic:Microphone = Microphone.getMicrophone(); mic.removeEventListener(StatusEvent.STATUS, onMicStatus); mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, onMicSampleData); conn.close(); } private function writeAuthorizationHeader():void { var a:String = ''; switch (authState) { case "basic": a = auth.basic(this.urlParsed.user, this.urlParsed.pass) + "\r\n"; break; case "digest": a = auth.digest( this.urlParsed.user, this.urlParsed.pass, "POST", authOpts.digestRealm, urlParsed.urlpath, authOpts.qop, authOpts.nonce, 1 ); break; default: case "none": return; } conn.writeUTFBytes('Authorization: ' + a + "\r\n"); } private function onConnected(event:Event):void { conn.writeUTFBytes("POST " + this.urlParsed.urlpath + " HTTP/1.0\r\n"); conn.writeUTFBytes("Content-Type: audio/axis-mulaw-128\r\n"); conn.writeUTFBytes("Content-Length: 9999999\r\n"); conn.writeUTFBytes("Connection: Keep-Alive\r\n"); conn.writeUTFBytes("Cache-Control: no-cache\r\n"); writeAuthorizationHeader(); conn.writeUTFBytes("\r\n"); } private function onClosed(event:Event):void { trace('axis audio closed'); } private function onMicSampleData(event:SampleDataEvent):void { if (!conn.connected) { return; } while (event.data.bytesAvailable) { var encoded:uint = g711.linearToMulaw(event.data.readFloat()); conn.writeByte(encoded); } conn.flush(); } private function onRequestData(event:ProgressEvent):void { var data:ByteArray = new ByteArray(); var parsed:* = request.readHeaders(conn, data); if (false === parsed) { return; } if (401 === parsed.code) { /* Unauthorized, change authState and (possibly) try again */ authOpts = parsed.headers['www-authenticate']; var newAuthState:String = auth.nextMethod(authState, authOpts); if (authState === newAuthState) { trace('AxisTransmit: Exhausted all authentication methods.'); trace('AxisTransmit: Unable to authorize to ' + urlParsed.host); return; } trace('AxisTransmit: switching http-authorization from ' + authState + ' to ' + newAuthState); authState = newAuthState; conn.close(); conn.connect(this.urlParsed.host, this.urlParsed.port); return; } } private function onError(e:ErrorEvent):void { trace('axis transmit error'); } } }
package com.axis.audioclient { import flash.events.Event; import flash.events.ProgressEvent; import flash.events.ErrorEvent; import flash.events.SampleDataEvent; import flash.events.StatusEvent; import flash.events.SecurityErrorEvent; import flash.events.IOErrorEvent; import flash.net.Socket; import flash.media.Microphone; import flash.media.SoundCodec; import flash.utils.ByteArray; import com.axis.codec.g711; import com.axis.http.url; import com.axis.http.auth; import com.axis.http.request; public class AxisTransmit { private var urlParsed:Object = {}; private var conn:Socket = new Socket(); private var authState:String = 'none'; private var authOpts:Object = {}; private var savedUrl:String = null; public function AxisTransmit() { } private function onMicStatus(event:StatusEvent):void { if (conn.connected) { authState = 'none'; conn.close(); } if ('Microphone.Muted' === event.code) { trace('AxisTransmit: Denied access to microphone'); return; } if (urlParsed.host && urlParsed.port) { conn.connect(urlParsed.host, urlParsed.port); } } public function start(iurl:String = null):void { if (conn.connected) { trace('already connected'); return; } var currentUrl:String = (iurl) ? iurl : savedUrl; if (!currentUrl) { trace("no url provided"); return; } this.savedUrl = currentUrl; var mic:Microphone = Microphone.getMicrophone(); mic.rate = 16; mic.setSilenceLevel(0, -1); mic.addEventListener(StatusEvent.STATUS, onMicStatus); mic.addEventListener(SampleDataEvent.SAMPLE_DATA, onMicSampleData); this.urlParsed = url.parse(currentUrl); conn = new Socket(); conn.addEventListener(Event.CONNECT, onConnected); conn.addEventListener(Event.CLOSE, onClosed); conn.addEventListener(ProgressEvent.SOCKET_DATA, onRequestData); conn.addEventListener(IOErrorEvent.IO_ERROR, onError); conn.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); if (true === mic.muted) { trace('Not allowed access to microphone, delay connect'); return; } conn.connect(urlParsed.host, urlParsed.port); } public function stop():void { if (!conn.connected) { trace('not connected'); return; } var mic:Microphone = Microphone.getMicrophone(); mic.removeEventListener(StatusEvent.STATUS, onMicStatus); mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, onMicSampleData); conn.close(); } private function writeAuthorizationHeader():void { var a:String = ''; switch (authState) { case "basic": a = auth.basic(this.urlParsed.user, this.urlParsed.pass) + "\r\n"; break; case "digest": a = auth.digest( this.urlParsed.user, this.urlParsed.pass, "POST", authOpts.digestRealm, urlParsed.urlpath, authOpts.qop, authOpts.nonce, 1 ); break; default: case "none": return; } conn.writeUTFBytes('Authorization: ' + a + "\r\n"); } private function onConnected(event:Event):void { conn.writeUTFBytes("POST " + this.urlParsed.urlpath + " HTTP/1.0\r\n"); conn.writeUTFBytes("Content-Type: audio/axis-mulaw-128\r\n"); conn.writeUTFBytes("Content-Length: 9999999\r\n"); conn.writeUTFBytes("Connection: Keep-Alive\r\n"); conn.writeUTFBytes("Cache-Control: no-cache\r\n"); writeAuthorizationHeader(); conn.writeUTFBytes("\r\n"); } private function onClosed(event:Event):void { trace('axis audio closed'); } private function onMicSampleData(event:SampleDataEvent):void { if (!conn.connected) { return; } while (event.data.bytesAvailable) { var encoded:uint = g711.linearToMulaw(event.data.readFloat()); conn.writeByte(encoded); } conn.flush(); } private function onRequestData(event:ProgressEvent):void { var data:ByteArray = new ByteArray(); var parsed:* = request.readHeaders(conn, data); if (false === parsed) { return; } if (401 === parsed.code) { /* Unauthorized, change authState and (possibly) try again */ authOpts = parsed.headers['www-authenticate']; var newAuthState:String = auth.nextMethod(authState, authOpts); if (authState === newAuthState) { trace('AxisTransmit: Exhausted all authentication methods.'); trace('AxisTransmit: Unable to authorize to ' + urlParsed.host); return; } trace('AxisTransmit: switching http-authorization from ' + authState + ' to ' + newAuthState); authState = newAuthState; conn.close(); conn.connect(this.urlParsed.host, this.urlParsed.port); return; } } private function onError(e:ErrorEvent):void { trace('axis transmit error'); } } }
Save url
Save url Implemented property to save the url which is needed to manage muting and unmuting of the microphone.
ActionScript
bsd-3-clause
AxisCommunications/locomote-video-player,gaetancollaud/locomote-video-player
dfca372df5e9a8c2fc3ac10ddb0ff6e80d839b5b
src/aerys/minko/type/loader/parser/ParserOptions.as
src/aerys/minko/type/loader/parser/ParserOptions.as
package aerys.minko.type.loader.parser { import aerys.minko.render.Effect; import aerys.minko.scene.node.Mesh; import aerys.minko.type.animation.SkinningMethod; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.TextureLoader; import flash.net.URLRequest; /** * ParserOptions objects provide properties and function references * to customize how a LoaderGroup object will load and interpret * content. * * @author Jean-Marc Le Roux * */ public final class ParserOptions { private var _loadDependencies : Boolean = false; private var _dependencyLoaderFunction : Function = defaultDependencyLoaderFunction; private var _loadSkin : Boolean = false; private var _skinningMethod : uint = SkinningMethod.SHADER_DUAL_QUATERNION; private var _mipmapTextures : Boolean = true; private var _meshEffect : Effect = null; private var _vertexStreamUsage : uint = 0; private var _indexStreamUsage : uint = 0; private var _parser : Class = null; public function get skinningMethod() : uint { return _skinningMethod; } public function set skinningMethod(value : uint) : void { _skinningMethod = value; } public function get parser() : Class { return _parser; } public function set parser(value : Class) : void { _parser = value; } public function get indexStreamUsage() : uint { return _indexStreamUsage; } public function set indexStreamUsage(value : uint) : void { _indexStreamUsage = value; } public function get vertexStreamUsage() : uint { return _vertexStreamUsage; } public function set vertexStreamUsage(value : uint) : void { _vertexStreamUsage = value; } public function get effect() : Effect { return _meshEffect; } public function set effect(value : Effect) : void { _meshEffect = value; } public function get mipmapTextures() : Boolean { return _mipmapTextures; } public function set mipmapTextures(value : Boolean) : void { _mipmapTextures = value; } public function get dependencyLoaderFunction() : Function { return _dependencyLoaderFunction; } public function set dependencyLoaderFunction(value : Function) : void { _dependencyLoaderFunction = value; } public function get loadDependencies() : Boolean { return _loadDependencies; } public function set loadDependencies(value : Boolean) : void { _loadDependencies = value; } public function get loadSkin() : Boolean { return _loadSkin; } public function set loadSkin(value : Boolean) : void { _loadSkin = value; } public function clone() : ParserOptions { return new ParserOptions( _loadDependencies, _dependencyLoaderFunction, _loadSkin, _skinningMethod, _mipmapTextures, _meshEffect, _vertexStreamUsage, _indexStreamUsage, _parser ); } public function ParserOptions(loadDependencies : Boolean = false, dependencyLoaderClosure : Function = null, loadSkin : Boolean = true, skinningMethod : uint = 2, mipmapTextures : Boolean = true, meshEffect : Effect = null, vertexStreamUsage : uint = 0, indexStreamUsage : uint = 0, parser : Class = null) { _loadDependencies = loadDependencies; _dependencyLoaderFunction = dependencyLoaderClosure || _dependencyLoaderFunction; _loadSkin = loadSkin; _skinningMethod = skinningMethod; _mipmapTextures = mipmapTextures; _meshEffect = meshEffect || Mesh.DEFAULT_MATERIAL.effect; _vertexStreamUsage = vertexStreamUsage; _indexStreamUsage = indexStreamUsage; _parser = parser; } private function defaultDependencyLoaderFunction(dependencyPath : String, isTexture : Boolean, options : ParserOptions) : ILoader { var loader : ILoader; if (isTexture) { loader = new TextureLoader(true); loader.load(new URLRequest(dependencyPath)); } else { loader = new SceneLoader(options); loader.load(new URLRequest(dependencyPath)); } return loader; } } }
package aerys.minko.type.loader.parser { import aerys.minko.render.Effect; import aerys.minko.scene.node.Mesh; import aerys.minko.type.animation.SkinningMethod; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.TextureLoader; import flash.net.URLRequest; /** * ParserOptions objects provide properties and function references * to customize how a LoaderGroup object will load and interpret * content. * * @author Jean-Marc Le Roux * */ public final class ParserOptions { private var _dependencyLoaderFunction : Function; private var _loadSkin : Boolean; private var _skinningMethod : uint; private var _mipmapTextures : Boolean; private var _meshEffect : Effect; private var _vertexStreamUsage : uint; private var _indexStreamUsage : uint; private var _parser : Class; public function get skinningMethod() : uint { return _skinningMethod; } public function set skinningMethod(value : uint) : void { _skinningMethod = value; } public function get parser() : Class { return _parser; } public function set parser(value : Class) : void { _parser = value; } public function get indexStreamUsage() : uint { return _indexStreamUsage; } public function set indexStreamUsage(value : uint) : void { _indexStreamUsage = value; } public function get vertexStreamUsage() : uint { return _vertexStreamUsage; } public function set vertexStreamUsage(value : uint) : void { _vertexStreamUsage = value; } public function get effect() : Effect { return _meshEffect; } public function set effect(value : Effect) : void { _meshEffect = value; } public function get mipmapTextures() : Boolean { return _mipmapTextures; } public function set mipmapTextures(value : Boolean) : void { _mipmapTextures = value; } public function get dependencyLoaderFunction() : Function { return _dependencyLoaderFunction; } public function set dependencyLoaderFunction(value : Function) : void { _dependencyLoaderFunction = value; } public function get loadSkin() : Boolean { return _loadSkin; } public function set loadSkin(value : Boolean) : void { _loadSkin = value; } public function clone() : ParserOptions { return new ParserOptions( _dependencyLoaderFunction, _loadSkin, _skinningMethod, _mipmapTextures, _meshEffect, _vertexStreamUsage, _indexStreamUsage, _parser ); } public function ParserOptions(dependencyLoaderFunction : Function = null, loadSkin : Boolean = true, skinningMethod : uint = 2, mipmapTextures : Boolean = true, meshEffect : Effect = null, vertexStreamUsage : uint = 0, indexStreamUsage : uint = 0, parser : Class = null) { _dependencyLoaderFunction = dependencyLoaderFunction || defaultDependencyLoaderFunction; _loadSkin = loadSkin; _skinningMethod = skinningMethod; _mipmapTextures = mipmapTextures; _meshEffect = meshEffect || Mesh.DEFAULT_MATERIAL.effect; _vertexStreamUsage = vertexStreamUsage; _indexStreamUsage = indexStreamUsage; _parser = parser; } private function defaultDependencyLoaderFunction(dependencyPath : String, isTexture : Boolean, options : ParserOptions) : ILoader { var loader : ILoader; if (isTexture) { loader = new TextureLoader(true); loader.load(new URLRequest(dependencyPath)); } else { loader = new SceneLoader(options); loader.load(new URLRequest(dependencyPath)); } return loader; } } }
remove ParserOptions.loadDependencies, parser should now use ParserOptions.dependencyLoaderFunction != null instead
remove ParserOptions.loadDependencies, parser should now use ParserOptions.dependencyLoaderFunction != null instead
ActionScript
mit
aerys/minko-as3
a3489f581c9c3b71564f4b4ee47a91e98311487d
flexEditor/src/org/arisgames/editor/util/AppConstants.as
flexEditor/src/org/arisgames/editor/util/AppConstants.as
package org.arisgames.editor.util { public class AppConstants { //public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://davembp.local/server/services/aris/uploadhandler.php"; //davembp // public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server/services/aris/uploadhandler.php"; //dev public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://www.arisgames.org/stagingserver1/services/aris/uploadHandler.php"; //staging // public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAArdp0t4v0pcA_JogLZhjrjBTf4EykMftsP7dwAfDsLsFl_zB7rBTq5-3Hy0k3tU1tgyomozB1YmIfNg"; //davembp // public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBQsvlSBtAWfm4N2P3iTGfWOp-UrmRRTU3pFPQwMJB92SZ3plLjvRpMIIw"; //dev public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //staging // Dynamic Events public static const APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED:String = "ApplicationDynamicEventCurrentStateChanged"; public static const APPLICATIONDYNAMICEVENT_REDRAWOBJECTPALETTE:String = "ApplicationDynamicEventRedrawObjectPalette"; public static const APPLICATIONDYNAMICEVENT_GAMEPLACEMARKSLOADED:String = "ApplicationDynamicEventGamePlacemarksLoaded"; public static const DYNAMICEVENT_GEOSEARCH:String = "DynamicEventGeoSearch"; public static const DYNAMICEVENT_PLACEMARKSELECTED:String = "DynamicEventPlaceMarkSelected"; public static const DYNAMICEVENT_PLACEMARKREQUESTSDELETION:String = "DynamicEventPlaceMarkRequestsDeletion"; public static const DYNAMICEVENT_EDITOBJECTPALETTEITEM:String = "EditObjectPaletteItem"; public static const DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR:String = "CloseObjectPaletteItemEditor"; public static const DYNAMICEVENT_CLOSEMEDIAPICKER:String = "CloseMediaPicker"; public static const DYNAMICEVENT_CLOSEMEDIAUPLOADER:String = "CloseMediaUploader"; public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITOR:String = "CloseRequirementsEditor"; public static const DYNAMICEVENT_REFRESHDATAINREQUIREMENTSEDITOR:String = "RefreshDataInRequirementsEditor"; public static const DYNAMICEVENT_OPENREQUIREMENTSEDITORMAP:String = "OpenRequirementsEditorMap"; public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITORMAP:String = "CloseRequirementsEditorMap"; public static const DYNAMICEVENT_SAVEREQUIREMENTDUETOMAPDATACHANGE:String = "SaveRequirementDueToMapDataChange"; public static const DYNAMICEVENT_OPENQUESTSMAP:String = "OpenQuestsMap"; public static const DYNAMICEVENT_CLOSEQUESTSMAP:String = "CloseQuestsMap"; public static const DYNAMICEVENT_REFRESHDATAINQUESTSEDITOR:String = "RefreshDataInQuestsEditor"; public static const DYNAMICEVENT_OPENQUESTSEDITOR:String = "OpenQuestsEditor"; public static const DYNAMICEVENT_CLOSEQUESTSEDITOR:String = "CloseQuestsEditor"; public static const DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR:String = "DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR"; public static const DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR:String = "DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR"; public static const DYNAMICEVENT_REFRESHDATAINCONVERSATIONS:String = "DYNAMICEVENT_DYNAMICEVENT_REFRESHDATAINCONVERSATIONS"; // Placemark Content public static const CONTENTTYPE_PAGE:String = "Plaque"; public static const CONTENTTYPE_CHARACTER:String = "Character"; public static const CONTENTTYPE_ITEM:String = "Item"; public static const CONTENTTYPE_QRCODEGROUP:String = "QR Code Group"; public static const CONTENTTYPE_PAGE_VAL:Number = 0; public static const CONTENTTYPE_CHARACTER_VAL:Number = 1; public static const CONTENTTYPE_ITEM_VAL:Number = 2; public static const CONTENTTYPE_QRCODEGROUP_VAL:Number = 3; public static const CONTENTTYPE_PAGE_DATABASE:String = "Node"; public static const CONTENTTYPE_CHARACTER_DATABASE:String = "Npc"; public static const CONTENTTYPE_ITEM_DATABASE:String = "Item"; public static const PLACEMARK_DEFAULT_ERROR_RANGE:Number = 30; // Label Constants public static const BUTTON_LOGIN:String = "Login!"; public static const BUTTON_REGISTER:String = "Register!"; public static const RADIO_FORGOTPASSWORD:String = "Forgot Password"; public static const RADIO_FORGOTUSERNAME:String = "Forgot Username"; // Media Types public static const MEDIATYPE:String = "Media Types"; public static const MEDIATYPE_IMAGE:String = "Image"; public static const MEDIATYPE_AUDIO:String = "Audio"; public static const MEDIATYPE_VIDEO:String = "Video"; public static const MEDIATYPE_ICON:String = "Icon"; public static const MEDIATYPE_UPLOADNEW:String = "Upload New"; //Player State Changes public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM"; public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NODE:String = "VIEW_NODE"; public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NPC:String = "VIEW_NPC"; public static const PLAYERSTATECHANGE_ACTION_GIVEITEM:String = "GIVE_ITEM"; public static const PLAYERSTATECHANGE_ACTION_GIVEITEM_HUMAN:String = "Give Item"; public static const PLAYERSTATECHANGE_ACTION_TAKEITEM:String = "TAKE_ITEM"; public static const PLAYERSTATECHANGE_ACTION_TAKEITEM_HUMAN:String = "Take Item"; // Requirement Types public static const REQUIREMENTTYPE_LOCATION:String = "Location"; public static const REQUIREMENTTYPE_QUESTDISPLAY:String = "QuestDisplay"; public static const REQUIREMENTTYPE_QUESTCOMPLETE:String = "QuestComplete"; public static const REQUIREMENTTYPE_NODE:String = "Node"; // Requirement Options public static const REQUIREMENT_PLAYER_HAS_ITEM_DATABASE:String = "PLAYER_HAS_ITEM"; public static const REQUIREMENT_PLAYER_HAS_ITEM_HUMAN:String = "Player Has At Least qty of an Item"; public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_DATABASE:String = "PLAYER_DOES_NOT_HAVE_ITEM"; public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_HUMAN:String = "Player Has Less Than qty of an Item"; public static const REQUIREMENT_PLAYER_VIEWED_ITEM_DATABASE:String = "PLAYER_VIEWED_ITEM"; public static const REQUIREMENT_PLAYER_VIEWED_ITEM_HUMAN:String = "Player Viewed Item"; public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_ITEM"; public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_HUMAN:String = "Player Never Viewed Item"; public static const REQUIREMENT_PLAYER_VIEWED_NODE_DATABASE:String = "PLAYER_VIEWED_NODE"; public static const REQUIREMENT_PLAYER_VIEWED_NODE_HUMAN:String = "Player Viewed Plaque"; public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NODE"; public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_HUMAN:String = "Player Never Viewed Plaque"; public static const REQUIREMENT_PLAYER_VIEWED_NPC_DATABASE:String = "PLAYER_VIEWED_NPC"; public static const REQUIREMENT_PLAYER_VIEWED_NPC_HUMAN:String = "Player Greeted By Character"; public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NPC"; public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_HUMAN:String = "Player Never Greeted By Character"; public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_DATABASE:String = "PLAYER_HAS_UPLOADED_MEDIA_ITEM"; public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_HUMAN:String = "Player Has Uploaded Media Item"; public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_DATABASE:String = "PLAYER_HAS_COMPLETED_QUEST"; public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST:String = "Player Has Completed Quest"; public static const REQUIREMENT_BOOLEAN_AND_DATABASE:String = "AND"; public static const REQUIREMENT_BOOLEAN_AND_HUMAN:String = "All"; public static const REQUIREMENT_BOOLEAN_OR_DATABASE:String = "OR"; public static const REQUIREMENT_BOOLEAN_OR_HUMAN:String = "Only this one"; // Defaults public static const DEFAULT_ICON_MEDIA_ID_NPC:Number = 1; public static const DEFAULT_ICON_MEDIA_ID_ITEM:Number = 2; public static const DEFAULT_ICON_MEDIA_ID_PLAQUE:Number = 3; /** * Constructor */ public function AppConstants() { super(); } } }
package org.arisgames.editor.util { public class AppConstants { //public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://davembp.local/server/services/aris/uploadhandler.php"; //davembp // public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server/services/aris/uploadhandler.php"; //dev public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://www.arisgames.org/stagingserver1/services/aris/uploadHandler.php"; //staging // public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAArdp0t4v0pcA_JogLZhjrjBTf4EykMftsP7dwAfDsLsFl_zB7rBTq5-3Hy0k3tU1tgyomozB1YmIfNg"; //davembp // public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBQsvlSBtAWfm4N2P3iTGfWOp-UrmRRTU3pFPQwMJB92SZ3plLjvRpMIIw"; //dev public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //staging // Dynamic Events public static const APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED:String = "ApplicationDynamicEventCurrentStateChanged"; public static const APPLICATIONDYNAMICEVENT_REDRAWOBJECTPALETTE:String = "ApplicationDynamicEventRedrawObjectPalette"; public static const APPLICATIONDYNAMICEVENT_GAMEPLACEMARKSLOADED:String = "ApplicationDynamicEventGamePlacemarksLoaded"; public static const DYNAMICEVENT_GEOSEARCH:String = "DynamicEventGeoSearch"; public static const DYNAMICEVENT_PLACEMARKSELECTED:String = "DynamicEventPlaceMarkSelected"; public static const DYNAMICEVENT_PLACEMARKREQUESTSDELETION:String = "DynamicEventPlaceMarkRequestsDeletion"; public static const DYNAMICEVENT_EDITOBJECTPALETTEITEM:String = "EditObjectPaletteItem"; public static const DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR:String = "CloseObjectPaletteItemEditor"; public static const DYNAMICEVENT_CLOSEMEDIAPICKER:String = "CloseMediaPicker"; public static const DYNAMICEVENT_CLOSEMEDIAUPLOADER:String = "CloseMediaUploader"; public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITOR:String = "CloseRequirementsEditor"; public static const DYNAMICEVENT_REFRESHDATAINREQUIREMENTSEDITOR:String = "RefreshDataInRequirementsEditor"; public static const DYNAMICEVENT_OPENREQUIREMENTSEDITORMAP:String = "OpenRequirementsEditorMap"; public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITORMAP:String = "CloseRequirementsEditorMap"; public static const DYNAMICEVENT_SAVEREQUIREMENTDUETOMAPDATACHANGE:String = "SaveRequirementDueToMapDataChange"; public static const DYNAMICEVENT_OPENQUESTSMAP:String = "OpenQuestsMap"; public static const DYNAMICEVENT_CLOSEQUESTSMAP:String = "CloseQuestsMap"; public static const DYNAMICEVENT_REFRESHDATAINQUESTSEDITOR:String = "RefreshDataInQuestsEditor"; public static const DYNAMICEVENT_OPENQUESTSEDITOR:String = "OpenQuestsEditor"; public static const DYNAMICEVENT_CLOSEQUESTSEDITOR:String = "CloseQuestsEditor"; public static const DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR:String = "DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR"; public static const DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR:String = "DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR"; public static const DYNAMICEVENT_REFRESHDATAINCONVERSATIONS:String = "DYNAMICEVENT_DYNAMICEVENT_REFRESHDATAINCONVERSATIONS"; // Placemark Content public static const CONTENTTYPE_PAGE:String = "Plaque"; public static const CONTENTTYPE_CHARACTER:String = "Character"; public static const CONTENTTYPE_ITEM:String = "Item"; public static const CONTENTTYPE_QRCODEGROUP:String = "QR Code Group"; public static const CONTENTTYPE_PAGE_VAL:Number = 0; public static const CONTENTTYPE_CHARACTER_VAL:Number = 1; public static const CONTENTTYPE_ITEM_VAL:Number = 2; public static const CONTENTTYPE_QRCODEGROUP_VAL:Number = 3; public static const CONTENTTYPE_PAGE_DATABASE:String = "Node"; public static const CONTENTTYPE_CHARACTER_DATABASE:String = "Npc"; public static const CONTENTTYPE_ITEM_DATABASE:String = "Item"; public static const PLACEMARK_DEFAULT_ERROR_RANGE:Number = 30; // Label Constants public static const BUTTON_LOGIN:String = "Login!"; public static const BUTTON_REGISTER:String = "Register!"; public static const RADIO_FORGOTPASSWORD:String = "Forgot Password"; public static const RADIO_FORGOTUSERNAME:String = "Forgot Username"; // Media Types public static const MEDIATYPE:String = "Media Types"; public static const MEDIATYPE_IMAGE:String = "Image"; public static const MEDIATYPE_AUDIO:String = "Audio"; public static const MEDIATYPE_VIDEO:String = "Video"; public static const MEDIATYPE_ICON:String = "Icon"; public static const MEDIATYPE_UPLOADNEW:String = "Upload New"; //Player State Changes public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM"; public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NODE:String = "VIEW_NODE"; public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NPC:String = "VIEW_NPC"; public static const PLAYERSTATECHANGE_ACTION_GIVEITEM:String = "GIVE_ITEM"; public static const PLAYERSTATECHANGE_ACTION_GIVEITEM_HUMAN:String = "Give Item"; public static const PLAYERSTATECHANGE_ACTION_TAKEITEM:String = "TAKE_ITEM"; public static const PLAYERSTATECHANGE_ACTION_TAKEITEM_HUMAN:String = "Take Item"; // Requirement Types public static const REQUIREMENTTYPE_LOCATION:String = "Location"; public static const REQUIREMENTTYPE_QUESTDISPLAY:String = "QuestDisplay"; public static const REQUIREMENTTYPE_QUESTCOMPLETE:String = "QuestComplete"; public static const REQUIREMENTTYPE_NODE:String = "Node"; // Requirement Options public static const REQUIREMENT_PLAYER_HAS_ITEM_DATABASE:String = "PLAYER_HAS_ITEM"; public static const REQUIREMENT_PLAYER_HAS_ITEM_HUMAN:String = "Player Has At Least Qty of an Item"; public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_DATABASE:String = "PLAYER_DOES_NOT_HAVE_ITEM"; public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_HUMAN:String = "Player Has Less Than Qty of an Item"; public static const REQUIREMENT_PLAYER_VIEWED_ITEM_DATABASE:String = "PLAYER_VIEWED_ITEM"; public static const REQUIREMENT_PLAYER_VIEWED_ITEM_HUMAN:String = "Player Viewed Item"; public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_ITEM"; public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_HUMAN:String = "Player Never Viewed Item"; public static const REQUIREMENT_PLAYER_VIEWED_NODE_DATABASE:String = "PLAYER_VIEWED_NODE"; public static const REQUIREMENT_PLAYER_VIEWED_NODE_HUMAN:String = "Player Viewed Plaque/Script"; public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NODE"; public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_HUMAN:String = "Player Never Viewed Plaque/Script"; public static const REQUIREMENT_PLAYER_VIEWED_NPC_DATABASE:String = "PLAYER_VIEWED_NPC"; public static const REQUIREMENT_PLAYER_VIEWED_NPC_HUMAN:String = "Player Greeted By Character"; public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NPC"; public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_HUMAN:String = "Player Never Greeted By Character"; public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_DATABASE:String = "PLAYER_HAS_UPLOADED_MEDIA_ITEM"; public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_HUMAN:String = "Player Has Uploaded Media Item"; public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_DATABASE:String = "PLAYER_HAS_COMPLETED_QUEST"; public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST:String = "Player Has Completed Quest"; public static const REQUIREMENT_BOOLEAN_AND_DATABASE:String = "AND"; public static const REQUIREMENT_BOOLEAN_AND_HUMAN:String = "All"; public static const REQUIREMENT_BOOLEAN_OR_DATABASE:String = "OR"; public static const REQUIREMENT_BOOLEAN_OR_HUMAN:String = "Only this one"; // Defaults public static const DEFAULT_ICON_MEDIA_ID_NPC:Number = 1; public static const DEFAULT_ICON_MEDIA_ID_ITEM:Number = 2; public static const DEFAULT_ICON_MEDIA_ID_PLAQUE:Number = 3; /** * Constructor */ public function AppConstants() { super(); } } }
rename requirement to plaque/script
rename requirement to plaque/script
ActionScript
mit
inesaloulou21/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,augustozuniga/arisgames
ea2028bb160485752d4f7e27307d1549919bfc66
WeaveCore/src/weave/core/LinkableFunction.as
WeaveCore/src/weave/core/LinkableFunction.as
/* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave 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 Weave. If not, see <http://www.gnu.org/licenses/>. */ package weave.core { import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; import mx.utils.StringUtil; import weave.api.WeaveAPI; import weave.api.core.ILinkableHashMap; import weave.api.getCallbackCollection; import weave.api.reportError; import weave.compiler.Compiler; import weave.compiler.ICompiledObject; import weave.compiler.ProxyObject; import weave.compiler.StandardLib; /** * LinkableFunction allows a function to be defined by a String that can use macros defined in the static macros hash map. * Libraries listed in macroLibraries variable will be included when compiling the function. * * @author adufilie */ public class LinkableFunction extends LinkableString { /** * Debug mode. */ public static var debug:Boolean = false; /** * @param defaultValue The default function definition. * @param ignoreRuntimeErrors If this is true, errors thrown during evaluation of the function will be caught and values of undefined will be returned. * @param useThisScope When true, variable lookups will be evaluated as if the function were in the scope of the thisArg passed to the apply() function. * @param paramNames An Array of parameter names that can be used in the function definition. */ public function LinkableFunction(defaultValue:String = null, ignoreRuntimeErrors:Boolean = false, useThisScope:Boolean = false, paramNames:Array = null) { super(unIndent(defaultValue)); _allLinkableFunctions[this] = true; // register this instance so the callbacks will trigger when the libraries change _ignoreRuntimeErrors = ignoreRuntimeErrors; _useThisScope = useThisScope; _paramNames = paramNames && paramNames.concat(); getCallbackCollection(this).addImmediateCallback(this, handleChange); } private var _ignoreRuntimeErrors:Boolean = false; private var _useThisScope:Boolean = false; private var _compiledMethod:Function = null; private var _paramNames:Array = null; private var _isFunctionDefinition:Boolean = false; /** * This is called whenever the session state changes. */ private function handleChange():void { // do not compile immediately because we don't want to throw an error at this time. _compiledMethod = null; } /** * This is used as a placeholder to prevent re-compiling erroneous code. */ private static function RETURN_UNDEFINED(..._):* { return undefined; } /** * This will attempt to compile the function. An Error will be thrown if this fails. */ public function validate():void { if (_compiledMethod == null) { // in case compile fails, prevent re-compiling erroneous code _compiledMethod = RETURN_UNDEFINED; _isFunctionDefinition = false; if (_macroProxy == null) _macroProxy = new ProxyObject(_hasMacro, _getMacro, null, evaluateMacro); // allows evaluating macros but not setting them var object:ICompiledObject = _compiler.compileToObject(value); _isFunctionDefinition = _compiler.compiledObjectIsFunction(object); _compiledMethod = _compiler.compileObjectToFunction(object, _macroProxy, errorHandler, _useThisScope, _paramNames); } } private function errorHandler(e:*):Boolean { if (debug) reportError(e); if (_ignoreRuntimeErrors || debug) return true; throw e; } /** * This gets the length property of the generated Function. */ public function get length():int { if (_compiledMethod == null) validate(); return _compiledMethod.length; } /** * This will evaluate the function with the specified parameters. * @param thisArg The value of 'this' to be used when evaluating the function. * @param argArray An Array of arguments to be passed to the compiled function. * @return The result of evaluating the function. */ public function apply(thisArg:* = null, argArray:Array = null):* { if (_compiledMethod == null) validate(); return _compiledMethod.apply(thisArg, argArray); } /** * This will evaluate the function with the specified parameters. * @param thisArg The value of 'this' to be used when evaluating the function. * @param args Arguments to be passed to the compiled function. * @return The result of evaluating the function. */ public function call(thisArg:* = null, ...args):* { if (_compiledMethod == null) validate(); return _compiledMethod.apply(thisArg, args); } ///////////////////////////////////////////////////////////////////////////////////////////// // static section /** * This is a proxy object for use as a symbol table for the compiler. */ private static var _macroProxy:ProxyObject = null; /** * This function checks if a macro exists. * @param macroName The name of a macro to check. * @return A value of true if the specified macro exists, or false if it does not. */ private static function _hasMacro(macroName:String):Boolean { return macros.getObject(macroName) != null; } private static function _getMacro(macroName:String):* { var lf:LinkableFunction = macros.getObject(macroName) as LinkableFunction; if (!lf) return undefined; if (lf._isFunctionDefinition) return lf; return lf.apply(); } /** * This function evaluates a macro specified in the macros hash map. * @param macroName The name of the macro to evaluate. * @param params The parameters to pass to the macro. * @return The result of evaluating the macro. */ public static function evaluateMacro(macroName:String, ...params):* { var lf:LinkableFunction = macros.getObject(macroName) as LinkableFunction; return lf ? lf.apply(null, params) : undefined; } /** * This is a list of macros that can be used in any LinkableFunction expression. */ public static const macros:ILinkableHashMap = new LinkableHashMap(LinkableFunction); /** * This is a list of libraries to include in the static compiler for macros. */ public static const macroLibraries:LinkableString = new LinkableString(); /** * This function will add a library to the static list of macro libraries if it is not already added. * @param libraryQName A library to add to the list of static libraries. */ public static function includeMacroLibrary(libraryQName:String):void { var rows:Array = WeaveAPI.CSVParser.parseCSV(macroLibraries.value); for each (var row:Array in rows) if (row.indexOf(libraryQName) >= 0) return; rows.push([libraryQName]); macroLibraries.value = WeaveAPI.CSVParser.createCSV(rows); } staticInit(); /** * This function will initialize static variables. */ private static function staticInit():void { // when the libraries change, we need to update the compiler macroLibraries.addImmediateCallback(null, handleLibrariesChange); macroLibraries.value = getQualifiedClassName(WeaveAPI); } /** * This is the static compiler to be used by every LinkableFunction. */ private static var _compiler:Compiler = null; private static var _allLinkableFunctions:Dictionary = new Dictionary(true); // the keys in this are LinkableFunction instances /** * This function will update the static compiler when the static libraries change. */ private static function handleLibrariesChange():void { _compiler = _getNewCompiler(true); for (var linkableFunction:Object in _allLinkableFunctions) { var lf:LinkableFunction = linkableFunction as LinkableFunction; if (!lf.wasDisposed) lf.triggerCallbacks(); } } /** * This function returns a new compiler initialized with the libraries specified by the public static libraries variable. * @param reportErrors If this is true, errors will be reported through WeaveAPI.ErrorManager. * @return A new initialized compiler. */ private static function _getNewCompiler(reportErrors:Boolean):Compiler { var compiler:Compiler = new Compiler(); for each (var row:Array in WeaveAPI.CSVParser.parseCSV(macroLibraries.value)) { try { compiler.includeLibraries.apply(null, row); } catch (e:Error) { if (reportErrors) reportError(e); } } return compiler; } // /** // * This function returns a new compiler initialized with the libraries specified by the public static libraries variable. // * @return A new initialized compiler. // */ // public static function getNewCompiler():Compiler // { // return _getNewCompiler(false); // } /** * Takes a script where all lines have been indented, removes the common indentation from all lines and replaces each tab with four spaces. * The common indentation is naively assumed to be the same as the first non-blank line in the script. * @param script A script. * @return The modified script. */ public static function unIndent(script:String):String { if (script == null) return null; script = StandardLib.replace(script, '\r\n','\n','\r','\n'); while (StringUtil.isWhitespace(script.substr(-1))) script = script.substr(0, -1); var lines:Array = script.split('\n'); while (!lines[0]) lines.shift(); var indent:int = 0; var line:String = lines[0]; while (line.charAt(indent) == '\t') indent++; lines.forEach( function(line:String, index:int, lines:Array):void { var i:int = 0; var spaces:String = ''; while (line.charAt(i) == '\t') if (i++ >= indent) spaces += ' '; lines[index] = spaces + line.substr(i); } ); return lines.join('\n') + '\n'; } } }
/* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave 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 Weave. If not, see <http://www.gnu.org/licenses/>. */ package weave.core { import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; import mx.utils.StringUtil; import weave.api.WeaveAPI; import weave.api.core.ILinkableHashMap; import weave.api.getCallbackCollection; import weave.api.reportError; import weave.compiler.Compiler; import weave.compiler.ICompiledObject; import weave.compiler.ProxyObject; import weave.compiler.StandardLib; /** * LinkableFunction allows a function to be defined by a String that can use macros defined in the static macros hash map. * Libraries listed in macroLibraries variable will be included when compiling the function. * * @author adufilie */ public class LinkableFunction extends LinkableString { /** * Debug mode. */ public static var debug:Boolean = false; /** * @param defaultValue The default function definition. * @param ignoreRuntimeErrors If this is true, errors thrown during evaluation of the function will be caught and values of undefined will be returned. * @param useThisScope When true, variable lookups will be evaluated as if the function were in the scope of the thisArg passed to the apply() function. * @param paramNames An Array of parameter names that can be used in the function definition. */ public function LinkableFunction(defaultValue:String = null, ignoreRuntimeErrors:Boolean = false, useThisScope:Boolean = false, paramNames:Array = null) { super(unIndent(defaultValue)); _allLinkableFunctions[this] = true; // register this instance so the callbacks will trigger when the libraries change _ignoreRuntimeErrors = ignoreRuntimeErrors; _useThisScope = useThisScope; _paramNames = paramNames && paramNames.concat(); getCallbackCollection(this).addImmediateCallback(this, handleChange); } private var _ignoreRuntimeErrors:Boolean = false; private var _useThisScope:Boolean = false; private var _compiledMethod:Function = null; private var _paramNames:Array = null; private var _isFunctionDefinition:Boolean = false; /** * This is called whenever the session state changes. */ private function handleChange():void { // do not compile immediately because we don't want to throw an error at this time. _compiledMethod = null; } /** * This is used as a placeholder to prevent re-compiling erroneous code. */ private static function RETURN_UNDEFINED(..._):* { return undefined; } /** * This will attempt to compile the function. An Error will be thrown if this fails. */ public function validate():void { if (_compiledMethod == null) { // in case compile fails, prevent re-compiling erroneous code _compiledMethod = RETURN_UNDEFINED; _isFunctionDefinition = false; if (_macroProxy == null) _macroProxy = new ProxyObject(_hasMacro, _getMacro, null, evaluateMacro); // allows evaluating macros but not setting them var object:ICompiledObject = _compiler.compileToObject(value); _isFunctionDefinition = _compiler.compiledObjectIsFunction(object); _compiledMethod = _compiler.compileObjectToFunction(object, _macroProxy, errorHandler, _useThisScope, _paramNames); } } private function errorHandler(e:*):Boolean { if (debug) reportError(e); if (_ignoreRuntimeErrors || debug) return true; throw e; } /** * This gets the length property of the generated Function. */ public function get length():int { if (_compiledMethod == null) validate(); return _compiledMethod.length; } /** * This will evaluate the function with the specified parameters. * @param thisArg The value of 'this' to be used when evaluating the function. * @param argArray An Array of arguments to be passed to the compiled function. * @return The result of evaluating the function. */ public function apply(thisArg:* = null, argArray:Array = null):* { if (_compiledMethod == null) validate(); return _compiledMethod.apply(thisArg, argArray); } /** * This will evaluate the function with the specified parameters. * @param thisArg The value of 'this' to be used when evaluating the function. * @param args Arguments to be passed to the compiled function. * @return The result of evaluating the function. */ public function call(thisArg:* = null, ...args):* { if (_compiledMethod == null) validate(); return _compiledMethod.apply(thisArg, args); } ///////////////////////////////////////////////////////////////////////////////////////////// // static section /** * This is a proxy object for use as a symbol table for the compiler. */ private static var _macroProxy:ProxyObject = null; /** * This function checks if a macro exists. * @param macroName The name of a macro to check. * @return A value of true if the specified macro exists, or false if it does not. */ private static function _hasMacro(macroName:String):Boolean { return macros.getObject(macroName) != null; } private static function _getMacro(macroName:String):* { var lf:LinkableFunction = macros.getObject(macroName) as LinkableFunction; if (!lf) return undefined; if (lf._isFunctionDefinition) return lf; return lf.apply(); } /** * This function evaluates a macro specified in the macros hash map. * @param macroName The name of the macro to evaluate. * @param params The parameters to pass to the macro. * @return The result of evaluating the macro. */ public static function evaluateMacro(macroName:String, ...params):* { var lf:LinkableFunction = macros.getObject(macroName) as LinkableFunction; return lf ? lf.apply(null, params) : undefined; } /** * This is a list of macros that can be used in any LinkableFunction expression. */ public static const macros:ILinkableHashMap = new LinkableHashMap(LinkableFunction); /** * This is a list of libraries to include in the static compiler for macros. */ public static const macroLibraries:LinkableString = new LinkableString(); /** * This function will add a library to the static list of macro libraries if it is not already added. * @param libraryQName A library to add to the list of static libraries. */ public static function includeMacroLibrary(libraryQName:String):void { var rows:Array = WeaveAPI.CSVParser.parseCSV(macroLibraries.value); for each (var row:Array in rows) if (row.indexOf(libraryQName) >= 0) return; rows.push([libraryQName]); macroLibraries.value = WeaveAPI.CSVParser.createCSV(rows); } staticInit(); /** * This function will initialize static variables. */ private static function staticInit():void { // when the libraries change, we need to update the compiler macroLibraries.addImmediateCallback(null, handleLibrariesChange); macroLibraries.value = getQualifiedClassName(WeaveAPI); } /** * This is the static compiler to be used by every LinkableFunction. */ private static var _compiler:Compiler = null; private static var _allLinkableFunctions:Dictionary = new Dictionary(true); // the keys in this are LinkableFunction instances /** * This function will update the static compiler when the static libraries change. */ private static function handleLibrariesChange():void { _compiler = _getNewCompiler(true); for (var linkableFunction:Object in _allLinkableFunctions) { var lf:LinkableFunction = linkableFunction as LinkableFunction; if (!lf.wasDisposed) lf.triggerCallbacks(); } } /** * This function returns a new compiler initialized with the libraries specified by the public static libraries variable. * @param reportErrors If this is true, errors will be reported through WeaveAPI.ErrorManager. * @return A new initialized compiler. */ private static function _getNewCompiler(reportErrors:Boolean):Compiler { var compiler:Compiler = new Compiler(); for each (var row:Array in WeaveAPI.CSVParser.parseCSV(macroLibraries.value)) { try { compiler.includeLibraries.apply(null, row); } catch (e:Error) { if (reportErrors) reportError(e); } } return compiler; } // /** // * This function returns a new compiler initialized with the libraries specified by the public static libraries variable. // * @return A new initialized compiler. // */ // public static function getNewCompiler():Compiler // { // return _getNewCompiler(false); // } /** * Takes a script where all lines have been indented, removes the common indentation from all lines and replaces each tab with four spaces. * The common indentation is naively assumed to be the same as the first non-blank line in the script. * @param script A script. * @return The modified script. */ public static function unIndent(script:String):String { if (script == null) return null; script = StandardLib.replace(script, '\r\n','\n','\r','\n'); while (StringUtil.isWhitespace(script.substr(-1))) script = script.substr(0, -1); var lines:Array = script.split('\n'); while (!lines[0]) lines.shift(); var indent:int = 0; var line:String = lines[0]; while (line.charAt(indent) == '\t') indent++; for (var i:int = 0; i < lines.length; i++) { var line:String = lines[i]; var t:int = 0; var spaces:String = ''; while (line.charAt(t) == '\t') if (t++ >= indent) spaces += ' '; lines[i] = spaces + line.substr(t); } return lines.join('\n') + '\n'; } } }
rewrite for loop
rewrite for loop
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
3f0ddad48a9871a24d692b45e2ce6457c45a4a14
src/aerys/minko/scene/controller/mesh/MeshController.as
src/aerys/minko/scene/controller/mesh/MeshController.as
package aerys.minko.scene.controller.mesh { import aerys.minko.render.geometry.Geometry; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.TransformController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.Mesh; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import aerys.minko.type.math.Matrix4x4; public final class MeshController extends AbstractController { private var _data : DataProvider; private var _geometry : Geometry; private var _frame : uint; private var _localToWorld : Matrix4x4; private var _worldToLocal : Matrix4x4; public function get geometry() : Geometry { return _geometry; } public function set geometry(value : Geometry) : void { _geometry = value; if (_data) _data.setProperty('geometry', value); } public function get frame() : uint { return _frame; } public function set frame(value : uint) : void { _frame = value; if (_data) _data.setProperty('frame', value); } public function MeshController() { super(Mesh); initialize(); } private function initialize() : void { targetAdded.add(targetAddedHandler); } private function targetAddedHandler(ctrl : MeshController, target : Mesh) : void { target.added.add(addedHandler); target.removed.add(removedHandler); } private function addedHandler(target : Mesh, ancestor : Group) : void { if (!target.scene) return ; _localToWorld = new Matrix4x4(); _worldToLocal = new Matrix4x4(); var transformController : TransformController = target.scene.getControllersByType(TransformController)[0] as TransformController; // transformController.setSharedLocalToWorldTransformReference(target, _localToWorld); // transformController.setSharedWorldToLocalTransformReference(target, _worldToLocal); _localToWorld = transformController.getLocalToWorldTransform(target, true); _worldToLocal = transformController.getWorldToLocalTransform(target, true); transformController.synchronizeTransforms(target, true); transformController.lockTransformsBeforeUpdate(target, true); _data = new DataProvider( null, target.name + '_transforms', DataProviderUsage.EXCLUSIVE ); _data.setProperty('geometry', _geometry); _data.setProperty('frame', _frame); _data.setProperty('localToWorld', _localToWorld); _data.setProperty('worldToLocal', _worldToLocal); target.bindings.addProvider(_data); } private function removedHandler(target : Mesh, ancestor : Group) : void { if (!ancestor.scene) return ; target.bindings.removeProvider(_data); _data.dispose(); _data = null; _localToWorld = null; _worldToLocal = null; } } }
package aerys.minko.scene.controller.mesh { import aerys.minko.render.geometry.Geometry; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.TransformController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.Mesh; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import aerys.minko.type.math.Matrix4x4; public final class MeshController extends AbstractController { private var _data : DataProvider; private var _geometry : Geometry; private var _frame : uint; private var _localToWorld : Matrix4x4; private var _worldToLocal : Matrix4x4; public function get geometry() : Geometry { return _geometry; } public function set geometry(value : Geometry) : void { _geometry = value; if (_data) _data.setProperty('geometry', value); } public function get frame() : uint { return _frame; } public function set frame(value : uint) : void { _frame = value; if (_data) _data.setProperty('frame', value); } public function MeshController() { super(Mesh); initialize(); } private function initialize() : void { targetAdded.add(targetAddedHandler); } private function targetAddedHandler(ctrl : MeshController, target : Mesh) : void { target.added.add(addedHandler); target.removed.add(removedHandler); } private function addedHandler(target : Mesh, ancestor : Group) : void { if (!target.scene) return ; _localToWorld = new Matrix4x4(); _worldToLocal = new Matrix4x4(); var transformController : TransformController = target.scene.getControllersByType(TransformController)[0] as TransformController; _localToWorld = transformController.getLocalToWorldTransform(target, true); _worldToLocal = transformController.getWorldToLocalTransform(target, true); transformController.synchronizeTransforms(target, true); transformController.lockTransformsBeforeUpdate(target, true); _data = new DataProvider( null, target.name + '_transforms', DataProviderUsage.EXCLUSIVE ); _data.setProperty('geometry', _geometry); _data.setProperty('frame', _frame); _data.setProperty('localToWorld', _localToWorld); _data.setProperty('worldToLocal', _worldToLocal); target.bindings.addProvider(_data); } private function removedHandler(target : Mesh, ancestor : Group) : void { if (!ancestor.scene) return ; target.bindings.removeProvider(_data); _data.dispose(); _data = null; _localToWorld = null; _worldToLocal = null; } } }
remove dead code
remove dead code
ActionScript
mit
aerys/minko-as3
79b9a97417955670f92a2b020e2ae0c1005c75a1
src/aerys/minko/scene/node/light/PointLight.as
src/aerys/minko/scene/node/light/PointLight.as
package aerys.minko.scene.node.light { import aerys.minko.ns.minko_scene; import aerys.minko.render.resource.texture.CubeTextureResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.scene.controller.light.PointLightController; import aerys.minko.scene.node.AbstractSceneNode; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.ShadowMappingType; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; use namespace minko_scene; /** * * @author Romain Gilliotte * @author Jean-Marc Le Roux * */ public class PointLight extends AbstractLight { public static const LIGHT_TYPE : uint = 2; private static const MAP_NAMES : Vector.<String> = new <String>[ 'shadowMapCube', 'shadowMapDPFront', 'shadowMapDPBack' ]; private static const TMP_VECTOR : Vector4 = new Vector4(); private var _shadowMapSize : uint; public function get diffuse() : Number { return lightData.getLightProperty('diffuse') as Number; } public function set diffuse(v : Number) : void { lightData.setLightProperty('diffuse', v); if (lightData.getLightProperty('diffuseEnabled') != (v != 0)) lightData.setLightProperty('diffuseEnabled', v != 0); } public function get specular() : Number { return lightData.getLightProperty('specular') as Number; } public function set specular(v : Number) : void { lightData.setLightProperty('specular', v); if (lightData.getLightProperty('specularEnabled') != (v != 0)) lightData.setLightProperty('specularEnabled', v != 0); } public function get shininess() : Number { return lightData.getLightProperty('shininess') as Number; } public function set shininess(v : Number) : void { lightData.setLightProperty('shininess', v); } public function get attenuationDistance() : Number { return lightData.getLightProperty('attenuationDistance') as Number; } public function set attenuationDistance(v : Number) : void { lightData.setLightProperty('attenuationDistance', v); if (lightData.getLightProperty('attenuationEnabled') != (v != 0)) lightData.setLightProperty('attenuationEnabled', v != 0); } public function get shadowMapSize() : uint { return _shadowMapSize; } public function set shadowMapSize(v : uint) : void { _shadowMapSize = v; this.shadowCastingType = this.shadowCastingType } public function get shadowZNear() : Number { return lightData.getLightProperty('shadowZNear'); } public function set shadowZNear(v : Number) : void { lightData.setLightProperty('shadowZNear', v); } public function get shadowZFar() : Number { return lightData.getLightProperty('shadowZFar'); } public function set shadowZFar(v : Number) : void { lightData.setLightProperty('shadowZFar', v); } override public function set shadowCastingType(v : uint) : void { var shadowMap : ITextureResource; // start by clearing current shadow maps. for each (var mapName : String in MAP_NAMES) { shadowMap = lightData.getLightProperty(mapName) as ITextureResource; if (shadowMap !== null) { shadowMap.dispose(); lightData.removeProperty(mapName); } } switch (v) { case ShadowMappingType.NONE: lightData.setLightProperty('shadowCastingType', ShadowMappingType.NONE); break; case ShadowMappingType.DUAL_PARABOLOID: if (!((_shadowMapSize & (~_shadowMapSize + 1)) == _shadowMapSize && _shadowMapSize <= 2048)) throw new Error(_shadowMapSize + ' is an invalid size for dual paraboloid shadow maps'); // set textures and shadowmaptype shadowMap = new TextureResource(_shadowMapSize, _shadowMapSize); lightData.setLightProperty('shadowMapDPFront', shadowMap); shadowMap = new TextureResource(_shadowMapSize, _shadowMapSize); lightData.setLightProperty('shadowMapDPBack', shadowMap); lightData.setLightProperty('shadowCastingType', ShadowMappingType.DUAL_PARABOLOID); break; case ShadowMappingType.CUBE: if (!((_shadowMapSize & (~_shadowMapSize + 1)) == _shadowMapSize && _shadowMapSize <= 1024)) throw new Error(_shadowMapSize + ' is an invalid size for cubic shadow maps'); shadowMap = new CubeTextureResource(_shadowMapSize); lightData.setLightProperty('shadowMapCube', shadowMap); lightData.setLightProperty('shadowCastingType', ShadowMappingType.CUBE); break; default: throw new ArgumentError('Invalid shadow casting type.'); } } public function PointLight(color : uint = 0xFFFFFFFF, diffuse : Number = .6, specular : Number = .8, shininess : Number = 64, attenuationDistance : Number = 0, emissionMask : uint = 0x1, shadowCastingType : uint = 0, shadowMapSize : uint = 512, shadowMapZNear : Number = 0.1, shadowMapZFar : Number = 1000) { _shadowMapSize = shadowMapSize; super( new PointLightController(), LIGHT_TYPE, color, emissionMask, shadowCastingType ); this.diffuse = diffuse; this.specular = specular; this.shininess = shininess; this.attenuationDistance = attenuationDistance; this.shadowZNear = shadowMapZNear; this.shadowZFar = shadowMapZFar; if ([ShadowMappingType.NONE, ShadowMappingType.DUAL_PARABOLOID, ShadowMappingType.CUBE].indexOf(shadowCastingType) == -1) throw new Error('Invalid ShadowMappingType.'); } override minko_scene function cloneNode() : AbstractSceneNode { var light : PointLight = new PointLight( color, diffuse, specular, shininess, attenuationDistance, emissionMask, shadowCastingType, shadowMapSize ); light.name = this.name; light.transform.copyFrom(this.transform); return light; } } }
package aerys.minko.scene.node.light { import aerys.minko.ns.minko_scene; import aerys.minko.render.resource.texture.CubeTextureResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.scene.controller.light.PointLightController; import aerys.minko.scene.node.AbstractSceneNode; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.ShadowMappingType; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; use namespace minko_scene; /** * * @author Romain Gilliotte * @author Jean-Marc Le Roux * */ public class PointLight extends AbstractLight { public static const LIGHT_TYPE : uint = 2; private static const MAP_NAMES : Vector.<String> = new <String>[ 'shadowMapCube', 'shadowMapDPFront', 'shadowMapDPBack' ]; private static const TMP_VECTOR : Vector4 = new Vector4(); private var _shadowMapSize : uint; public function get diffuse() : Number { return lightData.getLightProperty('diffuse') as Number; } public function set diffuse(v : Number) : void { lightData.setLightProperty('diffuse', v); if (lightData.getLightProperty('diffuseEnabled') != (v != 0)) lightData.setLightProperty('diffuseEnabled', v != 0); } public function get specular() : Number { return lightData.getLightProperty('specular') as Number; } public function set specular(v : Number) : void { lightData.setLightProperty('specular', v); if (lightData.getLightProperty('specularEnabled') != (v != 0)) lightData.setLightProperty('specularEnabled', v != 0); } public function get shininess() : Number { return lightData.getLightProperty('shininess') as Number; } public function set shininess(v : Number) : void { lightData.setLightProperty('shininess', v); } public function get attenuationDistance() : Number { return lightData.getLightProperty('attenuationDistance') as Number; } public function set attenuationDistance(v : Number) : void { lightData.setLightProperty('attenuationDistance', v); if (lightData.getLightProperty('attenuationEnabled') != (v != 0)) lightData.setLightProperty('attenuationEnabled', v != 0); } public function get shadowMapSize() : uint { return _shadowMapSize; } public function set shadowMapSize(v : uint) : void { _shadowMapSize = v; this.shadowCastingType = this.shadowCastingType } public function get shadowZNear() : Number { return lightData.getLightProperty('shadowZNear'); } public function set shadowZNear(v : Number) : void { lightData.setLightProperty('shadowZNear', v); } public function get shadowZFar() : Number { return lightData.getLightProperty('shadowZFar'); } public function set shadowZFar(v : Number) : void { lightData.setLightProperty('shadowZFar', v); } override public function set shadowCastingType(v : uint) : void { var shadowMap : ITextureResource; // start by clearing current shadow maps. for each (var mapName : String in MAP_NAMES) { shadowMap = lightData.getLightProperty(mapName) as ITextureResource; if (shadowMap !== null) { shadowMap.dispose(); lightData.removeProperty(mapName); } } switch (v) { case ShadowMappingType.NONE: lightData.setLightProperty('shadowCastingType', ShadowMappingType.NONE); break; case ShadowMappingType.DUAL_PARABOLOID: if (!((_shadowMapSize & (~_shadowMapSize + 1)) == _shadowMapSize && _shadowMapSize <= 2048)) throw new Error(_shadowMapSize + ' is an invalid size for dual paraboloid shadow maps'); // set textures and shadowmaptype shadowMap = new TextureResource(_shadowMapSize, _shadowMapSize); lightData.setLightProperty('shadowMapDPFront', shadowMap); shadowMap = new TextureResource(_shadowMapSize, _shadowMapSize); lightData.setLightProperty('shadowMapDPBack', shadowMap); lightData.setLightProperty('shadowCastingType', ShadowMappingType.DUAL_PARABOLOID); break; case ShadowMappingType.CUBE: if (!((_shadowMapSize & (~_shadowMapSize + 1)) == _shadowMapSize && _shadowMapSize <= 1024)) throw new Error(_shadowMapSize + ' is an invalid size for cubic shadow maps'); shadowMap = new CubeTextureResource(_shadowMapSize); lightData.setLightProperty('shadowMapCube', shadowMap); lightData.setLightProperty('shadowCastingType', ShadowMappingType.CUBE); break; default: throw new ArgumentError('Invalid shadow casting type.'); } } public function PointLight(color : uint = 0xFFFFFFFF, diffuse : Number = .6, specular : Number = .8, shininess : Number = 64, attenuationDistance : Number = 0, emissionMask : uint = 0x1, shadowCastingType : uint = 0, shadowMapSize : uint = 512, shadowMapZNear : Number = 0.1, shadowMapZFar : Number = 1000) { _shadowMapSize = shadowMapSize; super( new PointLightController(), LIGHT_TYPE, color, emissionMask, shadowCastingType ); this.diffuse = diffuse; this.specular = specular; this.shininess = shininess; this.attenuationDistance = attenuationDistance; this.shadowZNear = shadowMapZNear; this.shadowZFar = shadowMapZFar; if ([ShadowMappingType.NONE, ShadowMappingType.DUAL_PARABOLOID, ShadowMappingType.CUBE].indexOf(shadowCastingType) == -1) throw new Error('Invalid ShadowMappingType.'); } override minko_scene function cloneNode() : AbstractSceneNode { var light : PointLight = new PointLight( color, diffuse, specular, shininess, attenuationDistance, emissionMask, shadowCastingType, shadowMapSize ); light.name = this.name; light.transform.copyFrom(this.transform); return light; } } }
fix coding style
fix coding style
ActionScript
mit
aerys/minko-as3
ced8c055b62569fa1f21f78b3345c5cf4c30443f
ext/template/project/src/template.as
ext/template/project/src/template.as
package { public class @@project_name@@{ public function @@project_name@@(){ } } }
package{ import flash.display.Sprite; public class @@project_name@@ extends Sprite{ public function @@project_name@@(){ } } }
fix : the main class need to extend Sprite
fix : the main class need to extend Sprite
ActionScript
mit
wolfired/flex_ant_project_template,wolfired/flex_ant_project_template,wolfired/flex_ant_project_template,wolfired/flex_ant_project_template
f2b5003f3852d03ab3b5b39c2d1f3f9866f37c38
src/aerys/minko/scene/controller/debug/WireframeDebugController.as
src/aerys/minko/scene/controller/debug/WireframeDebugController.as
package aerys.minko.scene.controller.debug { import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.primitive.LineGeometry; import aerys.minko.render.geometry.stream.iterator.TriangleIterator; import aerys.minko.render.geometry.stream.iterator.TriangleReference; import aerys.minko.render.material.line.LineMaterial; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.type.math.Matrix4x4; import flash.utils.Dictionary; public final class WireframeDebugController extends AbstractController { private static var _wireframeMaterial : LineMaterial; private var _targetToWireframe : Dictionary = new Dictionary(); private var _geometryToMesh : Dictionary = new Dictionary(); private var _visible : Boolean = true; public function get material() : LineMaterial { return _wireframeMaterial || (_wireframeMaterial = new LineMaterial({diffuseColor : 0x509dc7ff, lineThickness : 1.})); } public function set visible(value : Boolean) : void { _visible = value; for each (var wireframe : Mesh in _targetToWireframe) wireframe.visible = value; } public function get visible() : Boolean { return _visible; } public function WireframeDebugController() { super(Mesh); initialize(); } private function initialize() : void { targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(ctrl : WireframeDebugController, target : Mesh) : void { if (target.scene) addedHandler(target, target.parent); else target.added.add(addedHandler); target.removed.add(removedHandler); } private function addedHandler(target : Mesh, ancestor : Group) : void { if (!target.scene || target.geometry == null) return ; var triangles : TriangleIterator = new TriangleIterator( target.geometry.getVertexStream(), target.geometry.indexStream ); var linesGeom : LineGeometry = new LineGeometry(); for each (var triangle : TriangleReference in triangles) { linesGeom.moveTo(triangle.v0.x, triangle.v0.y, triangle.v0.z) .lineTo(triangle.v1.x, triangle.v1.y, triangle.v1.z) .lineTo(triangle.v2.x, triangle.v2.y, triangle.v2.z) .lineTo(triangle.v0.x, triangle.v0.y, triangle.v0.z); } var lines : Mesh = new Mesh(linesGeom, this.material); lines.visible = _visible; _targetToWireframe[target] = lines; target.localToWorldTransformChanged.add(updateTransform); updateTransform(target, target.getLocalToWorldTransform()); target.scene.addChild(lines); } private function updateTransform(child : ISceneNode, childLocalToWorld : Matrix4x4) : void { var lineMesh : Mesh = _targetToWireframe[child]; if (lineMesh == null) child.localToWorldTransformChanged.remove(updateTransform); else lineMesh.transform.copyFrom(childLocalToWorld); } private function removeWireframes(target : Mesh) : void { if (_targetToWireframe[target]) _targetToWireframe[target].parent = null; _targetToWireframe[target] = null; } private function targetRemovedHandler(ctrl : WireframeDebugController, target : Mesh) : void { if (target.added.hasCallback(addedHandler)) target.added.remove(addedHandler); target.removed.remove(removedHandler); if (target.localToWorldTransformChanged.hasCallback(updateTransform)) target.localToWorldTransformChanged.remove(updateTransform); removeWireframes(target); } private function removedHandler(target : Mesh, ancestor : Group) : void { removeWireframes(target); } override public function clone():AbstractController { return null; } } }
package aerys.minko.scene.controller.debug { import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.primitive.LineGeometry; import aerys.minko.render.geometry.stream.iterator.TriangleIterator; import aerys.minko.render.geometry.stream.iterator.TriangleReference; import aerys.minko.render.material.line.LineMaterial; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.type.math.Matrix4x4; import flash.utils.Dictionary; public final class WireframeDebugController extends AbstractController { private static var _wireframeMaterial : LineMaterial; private var _targetToWireframe : Dictionary = new Dictionary(); private var _geometryToMesh : Dictionary = new Dictionary(); private var _visible : Boolean = true; public function get material() : LineMaterial { return _wireframeMaterial || (_wireframeMaterial = new LineMaterial({diffuseColor : 0x509dc7ff, lineThickness : 1.})); } public function set visible(value : Boolean) : void { _visible = value; for each (var wireframe : Mesh in _targetToWireframe) wireframe.visible = value; } public function get visible() : Boolean { return _visible; } public function WireframeDebugController() { super(Mesh); initialize(); } private function initialize() : void { targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(ctrl : WireframeDebugController, target : Mesh) : void { if (target.scene) addedHandler(target, target.parent); else target.added.add(addedHandler); target.removed.add(removedHandler); } private function addedHandler(target : Mesh, ancestor : Group) : void { if (!target.scene || target.geometry == null) return ; var triangles : TriangleIterator = new TriangleIterator( target.geometry.getVertexStream(), target.geometry.indexStream ); var linesGeom : LineGeometry = new LineGeometry(); for each (var triangle : TriangleReference in triangles) { linesGeom.moveTo(triangle.v0.x, triangle.v0.y, triangle.v0.z) .lineTo(triangle.v1.x, triangle.v1.y, triangle.v1.z) .lineTo(triangle.v2.x, triangle.v2.y, triangle.v2.z) .lineTo(triangle.v0.x, triangle.v0.y, triangle.v0.z); } var lines : Mesh = new Mesh(linesGeom, this.material); lines.visible = _visible; _targetToWireframe[target] = lines; if (!target.localToWorldTransformChanged.hasCallback(updateTransform)) target.localToWorldTransformChanged.add(updateTransform); updateTransform(target, target.getLocalToWorldTransform()); target.scene.addChild(lines); } private function updateTransform(child : ISceneNode, childLocalToWorld : Matrix4x4) : void { var lineMesh : Mesh = _targetToWireframe[child]; if (lineMesh == null) child.localToWorldTransformChanged.remove(updateTransform); else lineMesh.transform.copyFrom(childLocalToWorld); } private function removeWireframes(target : Mesh) : void { if (_targetToWireframe[target]) _targetToWireframe[target].parent = null; _targetToWireframe[target] = null; } private function targetRemovedHandler(ctrl : WireframeDebugController, target : Mesh) : void { if (target.added.hasCallback(addedHandler)) target.added.remove(addedHandler); target.removed.remove(removedHandler); if (target.localToWorldTransformChanged.hasCallback(updateTransform)) target.localToWorldTransformChanged.remove(updateTransform); removeWireframes(target); } private function removedHandler(target : Mesh, ancestor : Group) : void { removeWireframes(target); } override public function clone():AbstractController { return null; } } }
Fix bug when a callback was already listened
Fix bug when a callback was already listened
ActionScript
mit
aerys/minko-as3
ab6e6f2f29fea12d996e0736b4e2fec5d100f0a5
src/main/as/flump/export/Packer.as
src/main/as/flump/export/Packer.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.geom.Rectangle; import flump.xfl.XflLibrary; import flump.xfl.XflTexture; import com.threerings.util.Comparators; public class Packer { public static const BIN_SIZES :Vector.<int> = new <int>[8, 16, 32, 64, 128, 256, 512, 1024]; public const atlases :Vector.<Atlas> = new Vector.<Atlas>(); public function Packer (lib :XflLibrary) { for each (var tex :XflTexture in lib.textures) { _unpacked.push(new PackedTexture(tex, lib)); } _unpacked.sort(Comparators.createReverse(Comparators.createFields(["a", "w", "h"]))); var minBin :int = findOptimalMinBin(); atlases.push(new Atlas(lib.location + "/atlas0", minBin, minBin)); while (_unpacked.length > 0) pack(_unpacked.shift()); } protected function pack (tex :PackedTexture) :void { for each (var atlas :Atlas in atlases) { for each (var bin :Rectangle in atlas.bins) { if (tex.w <= bin.width && tex.h <= bin.height) { atlas.place(tex, bin, false); return; } else if (tex.h <= bin.width && tex.w <= bin.height) { atlas.place(tex, bin, true); return; } } } // TODO - allocate another atlas throw new Error("Doesn't fit " + tex); } protected function findOptimalMinBin () :int { var area :int = 0; var maxExtent :int = 0; for each (var tex :PackedTexture in _unpacked) { area += tex.a; maxExtent = Math.max(maxExtent, tex.w, tex.h); } for each (var size :int in BIN_SIZES) { if (size >= maxExtent && size * size >= area) return size; } return BIN_SIZES[BIN_SIZES.length -1]; } protected var _unpacked :Vector.<PackedTexture> = new Vector.<PackedTexture>(); } }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.geom.Rectangle; import flump.xfl.XflLibrary; import flump.xfl.XflTexture; import com.threerings.util.Comparators; public class Packer { public const atlases :Vector.<Atlas> = new Vector.<Atlas>(); public function Packer (lib :XflLibrary) { _lib = lib; for each (var tex :XflTexture in _lib.textures) { _unpacked.push(new PackedTexture(tex, _lib)); } _unpacked.sort(Comparators.createReverse(Comparators.createFields(["a", "w", "h"]))); while (_unpacked.length > 0) pack(); } protected function pack () :void { const tex :PackedTexture = _unpacked[0]; if (tex.w > LARGEST_BIN || tex.h > LARGEST_BIN) throw new Error("Too large to fit in bin"); for each (var atlas :Atlas in atlases) { for each (var bin :Rectangle in atlas.bins) { if (tex.w <= bin.width && tex.h <= bin.height) { atlas.place(_unpacked.shift(), bin, false); return; } else if (tex.h <= bin.width && tex.w <= bin.height) { atlas.place(_unpacked.shift(), bin, true); return; } } } var minBin :int = findOptimalMinBin(); atlases.push(new Atlas(_lib.location + "/atlas" + atlases.length, minBin, minBin)); pack(); } protected function findOptimalMinBin () :int { var area :int = 0; var maxExtent :int = 0; for each (var tex :PackedTexture in _unpacked) { area += tex.a; maxExtent = Math.max(maxExtent, tex.w, tex.h); } for each (var size :int in BIN_SIZES) { if (size >= maxExtent && size * size >= area) return size; } return LARGEST_BIN; } protected var _unpacked :Vector.<PackedTexture> = new Vector.<PackedTexture>(); protected var _lib :XflLibrary; private static const BIN_SIZES :Vector.<int> = new <int>[8, 16, 32, 64, 128, 256, 512, 1024]; private static const LARGEST_BIN :int = BIN_SIZES[BIN_SIZES.length - 1]; } }
Add additional atlases as textures don't fit
Add additional atlases as textures don't fit
ActionScript
mit
mathieuanthoine/flump,funkypandagame/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump
c36c4f7cdb38afcbea9bc94a6fec5760dba7373f
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2016 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 com.esri.builder.controllers.supportClasses { import com.esri.builder.model.CustomWidgetType; import com.esri.builder.model.WidgetType; import com.esri.builder.supportClasses.FileUtil; import com.esri.builder.supportClasses.LogUtil; import flash.events.EventDispatcher; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; import modules.IBuilderModule; import modules.supportClasses.CustomXMLModule; import mx.core.FlexGlobals; import mx.events.ModuleEvent; import mx.logging.ILogger; import mx.logging.Log; import mx.modules.IModuleInfo; import mx.modules.ModuleManager; public class WidgetTypeLoader extends EventDispatcher { private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader); internal static var loadedModuleInfos:Array = []; private var swf:File; private var config:File; //need reference when loading to avoid being garbage collected before load completes private var moduleInfo:IModuleInfo; //requires either swf or config public function WidgetTypeLoader(swf:File = null, config:File = null) { this.swf = swf; this.config = config; } public function get name():String { var fileName:String; if (swf && swf.exists) { fileName = FileUtil.getFileName(swf); } else if (config && config.exists) { fileName = FileUtil.getFileName(config); } return fileName; } public function load():void { if (swf && swf.exists) { loadModule(); } else if (config && config.exists) { loadConfigModule(); } else { dispatchError(); } } private function loadConfigModule():void { if (Log.isInfo()) { LOG.info('Loading XML module: {0}', config.url); } var moduleConfig:XML = readModuleConfig(config); if (moduleConfig) { var customWidgetType:CustomWidgetType = parseCustomWidgetType(moduleConfig); if (customWidgetType) { dispatchComplete(customWidgetType); return; } } dispatchError(); } private function loadModule():void { if (Log.isInfo()) { LOG.info('Loading SWF module: {0}', swf.url); } moduleInfo = ModuleManager.getModule(swf.url); if (moduleInfo.ready) { if (Log.isInfo()) { LOG.info('Unloading module: {0}', swf.url); } moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler); moduleInfo.release(); moduleInfo.unload(); } else { if (Log.isInfo()) { LOG.info('Loading module: {0}', swf.url); } var fileBytes:ByteArray = new ByteArray(); var fileStream:FileStream = new FileStream(); fileStream.open(swf, FileMode.READ); fileStream.readBytes(fileBytes); fileStream.close(); //Use ModuleEvent.PROGRESS instead of ModuleEvent.READY to avoid the case where the latter is never dispatched. moduleInfo.addEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler); moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); moduleInfo.load(null, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory); } } private function moduleInfo_progressHandler(event:ModuleEvent):void { if (event.bytesLoaded == event.bytesTotal) { var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo; moduleInfo.removeEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler); moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); FlexGlobals.topLevelApplication.callLater(processModuleInfo, [ moduleInfo ]); } } private function moduleInfo_unloadHandler(event:ModuleEvent):void { if (Log.isInfo()) { LOG.info('Module unloaded: {0}', swf.url); } var moduleInfo:IModuleInfo = event.module; moduleInfo.removeEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler); var moduleInfoIndex:int = loadedModuleInfos.indexOf(moduleInfo); if (moduleInfoIndex > -1) { loadedModuleInfos.splice(moduleInfoIndex, 1); } this.moduleInfo = null; FlexGlobals.topLevelApplication.callLater(loadModule); } private function processModuleInfo(moduleInfo:IModuleInfo):void { if (Log.isInfo()) { LOG.info('Module loaded: {0}', swf.url); } if (config && config.exists) { if (Log.isInfo()) { LOG.info('Reading module config: {0}', config.url); } var moduleConfig:XML = readModuleConfig(config); } const builderModule:IBuilderModule = moduleInfo.factory.create() as IBuilderModule; if (builderModule) { if (Log.isInfo()) { LOG.info('Widget type created for module: {0}', swf.url); } var widgetType:WidgetType = getWidgetType(moduleInfo, builderModule, moduleConfig); } loadedModuleInfos.push(moduleInfo); this.moduleInfo = null; dispatchComplete(widgetType); } private function dispatchComplete(widgetType:WidgetType):void { if (Log.isInfo()) { LOG.info('Module load complete: {0}', name); } dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_COMPLETE, widgetType)); } private function getWidgetType(moduleInfo:IModuleInfo, builderModule:IBuilderModule, moduleConfig:XML):WidgetType { var customModulesDirectoryURL:String = WellKnownDirectories.getInstance().customModules.url; var isCustomModule:Boolean = (moduleInfo.url.indexOf(customModulesDirectoryURL) > -1); if (moduleConfig) { var configXML:XML = moduleConfig.configuration[0]; var version:String = moduleConfig.widgetversion[0]; } return isCustomModule ? new CustomWidgetType(builderModule, version, configXML) : new WidgetType(builderModule); } private function readModuleConfig(configFile:File):XML { var configXML:XML; var fileStream:FileStream = new FileStream(); try { fileStream.open(configFile, FileMode.READ); configXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable)); } catch (e:Error) { //ignore if (Log.isInfo()) { LOG.info('Could not read module config: {0}', e.toString()); } } finally { fileStream.close(); } return configXML; } private function moduleInfo_errorHandler(event:ModuleEvent):void { var moduleInfo:IModuleInfo = event.module; moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); moduleInfo.removeEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler); this.moduleInfo = null; dispatchError(); } private function dispatchError():void { if (Log.isInfo()) { LOG.info('Module load failed: {0}', name); } dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_ERROR)); } private function parseCustomWidgetType(configXML:XML):CustomWidgetType { if (Log.isInfo()) { LOG.info('Creating widget type from XML: {0}', configXML); } var customModule:CustomXMLModule = new CustomXMLModule(); customModule.widgetName = configXML.name; customModule.isOpenByDefault = (configXML.openbydefault == 'true'); var widgetLabel:String = configXML.label[0]; var widgetDescription:String = configXML.description[0]; var widgetHelpURL:String = configXML.helpurl[0]; var widgetConfiguration:XML = configXML.configuration[0] ? configXML.configuration[0] : <configuration/>; var widgetVersion:String = configXML.widgetversion[0]; customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName); customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName; customModule.widgetDescription = widgetDescription ? widgetDescription : ""; customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : ""; return new CustomWidgetType(customModule, widgetVersion, widgetConfiguration); } private function createWidgetIconPath(iconPath:String, widgetName:String):String { var widgetIconPath:String; if (iconPath) { widgetIconPath = "widgets/" + widgetName + "/" + iconPath; } else { widgetIconPath = "assets/images/i_widget.png"; } return widgetIconPath; } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2016 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 com.esri.builder.controllers.supportClasses { import com.esri.builder.model.CustomWidgetType; import com.esri.builder.model.WidgetType; import com.esri.builder.supportClasses.FileUtil; import com.esri.builder.supportClasses.LogUtil; import flash.events.EventDispatcher; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; import modules.IBuilderModule; import modules.supportClasses.CustomXMLModule; import mx.core.FlexGlobals; import mx.events.ModuleEvent; import mx.logging.ILogger; import mx.logging.Log; import mx.modules.IModuleInfo; import mx.modules.ModuleManager; public class WidgetTypeLoader extends EventDispatcher { private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader); internal static var loadedModuleInfos:Array = []; private var swf:File; private var config:File; //need reference when loading to avoid being garbage collected before load completes private var moduleInfo:IModuleInfo; //requires either swf or config public function WidgetTypeLoader(swf:File = null, config:File = null) { this.swf = swf; this.config = config; } public function get name():String { var fileName:String; if (swf && swf.exists) { fileName = FileUtil.getFileName(swf); } else if (config && config.exists) { fileName = FileUtil.getFileName(config); } return fileName; } public function load():void { if (swf && swf.exists) { loadModule(); } else if (config && config.exists) { loadConfigModule(); } else { dispatchError(); } } private function loadModule():void { if (Log.isInfo()) { LOG.info('Loading SWF module: {0}', swf.url); } moduleInfo = ModuleManager.getModule(swf.url); if (moduleInfo.ready) { if (Log.isInfo()) { LOG.info('Unloading module: {0}', swf.url); } moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler); moduleInfo.release(); moduleInfo.unload(); } else { if (Log.isInfo()) { LOG.info('Loading module: {0}', swf.url); } var fileBytes:ByteArray = new ByteArray(); var fileStream:FileStream = new FileStream(); fileStream.open(swf, FileMode.READ); fileStream.readBytes(fileBytes); fileStream.close(); //Use ModuleEvent.PROGRESS instead of ModuleEvent.READY to avoid the case where the latter is never dispatched. moduleInfo.addEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler); moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); moduleInfo.load(null, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory); } } private function moduleInfo_unloadHandler(event:ModuleEvent):void { if (Log.isInfo()) { LOG.info('Module unloaded: {0}', swf.url); } var moduleInfo:IModuleInfo = event.module; moduleInfo.removeEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler); var moduleInfoIndex:int = loadedModuleInfos.indexOf(moduleInfo); if (moduleInfoIndex > -1) { loadedModuleInfos.splice(moduleInfoIndex, 1); } this.moduleInfo = null; FlexGlobals.topLevelApplication.callLater(loadModule); } private function moduleInfo_progressHandler(event:ModuleEvent):void { if (event.bytesLoaded == event.bytesTotal) { var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo; moduleInfo.removeEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler); moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); FlexGlobals.topLevelApplication.callLater(processModuleInfo, [ moduleInfo ]); } } private function processModuleInfo(moduleInfo:IModuleInfo):void { if (Log.isInfo()) { LOG.info('Module loaded: {0}', swf.url); } if (config && config.exists) { if (Log.isInfo()) { LOG.info('Reading module config: {0}', config.url); } var moduleConfig:XML = readModuleConfig(config); } const builderModule:IBuilderModule = moduleInfo.factory.create() as IBuilderModule; if (builderModule) { if (Log.isInfo()) { LOG.info('Widget type created for module: {0}', swf.url); } var widgetType:WidgetType = getWidgetType(moduleInfo, builderModule, moduleConfig); } loadedModuleInfos.push(moduleInfo); this.moduleInfo = null; dispatchComplete(widgetType); } private function getWidgetType(moduleInfo:IModuleInfo, builderModule:IBuilderModule, moduleConfig:XML):WidgetType { var customModulesDirectoryURL:String = WellKnownDirectories.getInstance().customModules.url; var isCustomModule:Boolean = (moduleInfo.url.indexOf(customModulesDirectoryURL) > -1); if (moduleConfig) { var configXML:XML = moduleConfig.configuration[0]; var version:String = moduleConfig.widgetversion[0]; } return isCustomModule ? new CustomWidgetType(builderModule, version, configXML) : new WidgetType(builderModule); } private function dispatchComplete(widgetType:WidgetType):void { if (Log.isInfo()) { LOG.info('Module load complete: {0}', name); } dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_COMPLETE, widgetType)); } private function moduleInfo_errorHandler(event:ModuleEvent):void { var moduleInfo:IModuleInfo = event.module; moduleInfo.removeEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler); moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); this.moduleInfo = null; dispatchError(); } private function dispatchError():void { if (Log.isInfo()) { LOG.info('Module load failed: {0}', name); } dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_ERROR)); } private function loadConfigModule():void { if (Log.isInfo()) { LOG.info('Loading XML module: {0}', config.url); } var moduleConfig:XML = readModuleConfig(config); if (moduleConfig) { var customWidgetType:CustomWidgetType = parseCustomWidgetType(moduleConfig); if (customWidgetType) { dispatchComplete(customWidgetType); return; } } dispatchError(); } private function readModuleConfig(configFile:File):XML { var configXML:XML; var fileStream:FileStream = new FileStream(); try { fileStream.open(configFile, FileMode.READ); configXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable)); } catch (e:Error) { //ignore if (Log.isInfo()) { LOG.info('Could not read module config: {0}', e.toString()); } } finally { fileStream.close(); } return configXML; } private function parseCustomWidgetType(configXML:XML):CustomWidgetType { if (Log.isInfo()) { LOG.info('Creating widget type from XML: {0}', configXML); } var customModule:CustomXMLModule = new CustomXMLModule(); customModule.widgetName = configXML.name; customModule.isOpenByDefault = (configXML.openbydefault == 'true'); var widgetLabel:String = configXML.label[0]; var widgetDescription:String = configXML.description[0]; var widgetHelpURL:String = configXML.helpurl[0]; var widgetConfiguration:XML = configXML.configuration[0] ? configXML.configuration[0] : <configuration/>; var widgetVersion:String = configXML.widgetversion[0]; customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName); customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName; customModule.widgetDescription = widgetDescription ? widgetDescription : ""; customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : ""; return new CustomWidgetType(customModule, widgetVersion, widgetConfiguration); } private function createWidgetIconPath(iconPath:String, widgetName:String):String { var widgetIconPath:String; if (iconPath) { widgetIconPath = "widgets/" + widgetName + "/" + iconPath; } else { widgetIconPath = "assets/images/i_widget.png"; } return widgetIconPath; } } }
Arrange methods closer to usage.
Arrange methods closer to usage.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
4fb21a01a9b5f26b12a466fa6f0d708d62f087eb
src/as/com/threerings/flash/Siner.as
src/as/com/threerings/flash/Siner.as
package com.threerings.flash { import flash.utils.getTimer; /** * Tracks multiple sine waves with different periods and amplitudes, and * returns a */ public class Siner { /** * @param args: amplitude1, period1, amplitude2, period2... * Periods are specified in seconds. * * If constructed with more than one amplitude, the amplitudes are * additive. * * The Siner will start in the reset() state. */ public function Siner (... args) { if (args.length == 0 || (args.length % 2 != 0)) { throw new ArgumentError(); } while (args.length > 0) { if (!(args[0] is Number) || !(args[1] is Number)) { throw new ArgumentError(); } var amp :Number = args.shift(); var per :Number = args.shift(); _incs.push(TWO_PI / (per * 1000)); _amps.push(amp); } reset(); } /** * Reset to 0, with the amplitude about to increase. */ public function reset () :void { for (var ii :int = _amps.length - 1; ii >= 0; ii--) { _values[ii] = 3 * Math.PI / 2; } _stamp = getTimer(); } /** * Randomize the value. */ public function randomize () :void { for (var ii :int = _amps.length - 1; ii >= 0; ii--) { _values[ii] = Math.random() * TWO_PI; } } /** * Access the instantaneous value, which can range from * [ -totalAmplitude, totalAmplitude ]. * * Note: timestamps are only kept relative to the last access of the value, * and floating point math is used, so things could get a little "off" after * a while, and the frequency with which you sample the value will impact * the error. You cope. */ public function get value () :Number { var now :Number = getTimer(); var elapsed :Number = now - _stamp; _stamp = now; var accum :Number = 0; for (var ii :int = _values.length - 1; ii >= 0; ii--) { var val :Number = (_values[ii] + (_incs[ii] * elapsed)) % TWO_PI; _values[ii] = val; accum += _amps[ii] * Math.sin(val); } return accum; } protected var _values :Array = []; protected var _incs :Array = []; protected var _amps :Array = []; protected var _stamp :Number; protected static const TWO_PI :Number = 2 * Math.PI; } }
package com.threerings.flash { import flash.utils.getTimer; /** * Tracks multiple sine waves with different periods and amplitudes, and * returns an instantaneous additive amplitude. */ public class Siner { /** * @param args: amplitude1, period1, amplitude2, period2... * Periods are specified in seconds. * * If constructed with more than one amplitude, the amplitudes are * additive. * * The Siner will start in the reset() state. */ public function Siner (... args) { if (args.length == 0 || (args.length % 2 != 0)) { throw new ArgumentError(); } while (args.length > 0) { if (!(args[0] is Number) || !(args[1] is Number)) { throw new ArgumentError(); } var amp :Number = args.shift(); var per :Number = args.shift(); _incs.push(TWO_PI / (per * 1000)); _amps.push(amp); } reset(); } /** * Reset to 0, with the amplitude about to increase. */ public function reset () :void { for (var ii :int = _amps.length - 1; ii >= 0; ii--) { _values[ii] = 3 * Math.PI / 2; } _stamp = getTimer(); } /** * Randomize the value. */ public function randomize () :void { for (var ii :int = _amps.length - 1; ii >= 0; ii--) { _values[ii] = Math.random() * TWO_PI; } } /** * Access the instantaneous value, which can range from * [ -totalAmplitude, totalAmplitude ]. * * Note: timestamps are only kept relative to the last access of the value, * and floating point math is used, so things could get a little "off" after * a while, and the frequency with which you sample the value will impact * the error. You cope. */ public function get value () :Number { var now :Number = getTimer(); var elapsed :Number = now - _stamp; _stamp = now; var accum :Number = 0; for (var ii :int = _values.length - 1; ii >= 0; ii--) { var val :Number = (_values[ii] + (_incs[ii] * elapsed)) % TWO_PI; _values[ii] = val; accum += _amps[ii] * Math.sin(val); } return accum; } protected var _values :Array = []; protected var _incs :Array = []; protected var _amps :Array = []; protected var _stamp :Number; protected static const TWO_PI :Number = 2 * Math.PI; } }
Comment fixup.
Comment fixup. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@171 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
f2ba0ebd326673dd1ed50602db85ae77aaee1790
src/com/esri/builder/supportClasses/FileUtil.as
src/com/esri/builder/supportClasses/FileUtil.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 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 com.esri.builder.supportClasses { import flash.filesystem.File; public class FileUtil { private static const CRLF_LINE_ENDING:String = "\r\n"; private static const LF_LINE_ENDING:String = "\n"; public static function generateUniqueRelativePath(baseDirectory:File, relativeFilePath:String, relativePathBlackList:Array = null):String { var extensionIndex:int = relativeFilePath.lastIndexOf("."); var extension:String = ""; if (extensionIndex > -1) { extension = relativeFilePath.substr(extensionIndex); relativeFilePath = relativeFilePath.substr(0, extensionIndex); } var filenameTemplate:String = relativeFilePath + "_{0}" + extension; var uniqueWidgetConfigPath:String = LabelUtil.generateUniqueLabel(filenameTemplate, relativePathBlackList, function isNonExistentFile(uniqueFilePath:String, availableNames:Array):Boolean { if (availableNames && availableNames.indexOf(uniqueFilePath) > -1) { return false; } return !baseDirectory.resolvePath(uniqueFilePath).exists; }); return uniqueWidgetConfigPath; } public static function getFileName(file:File):String { return file.name.replace("." + file.extension, ""); } public static function findMatchingFiles(directory:File, pattern:RegExp):Array { var moduleFiles:Array = []; if (directory.isDirectory) { const files:Array = directory.getDirectoryListing(); for each (var file:File in files) { if (file.isDirectory) { moduleFiles = moduleFiles.concat(findMatchingFiles(file, pattern)); } else if (pattern.test(file.name)) { moduleFiles.push(file); } } } return moduleFiles; } public static function findMatchingFile(directory:File, pattern:RegExp):File { var matchingFile:File; if (directory.isDirectory) { const files:Array = directory.getDirectoryListing(); //sort files first to reduce unnecessary directory listing calls. files.sortOn("isDirectory"); for each (var file:File in files) { if (file.isDirectory) { matchingFile = findMatchingFile(file, pattern); } else if (pattern.test(file.name)) { matchingFile = file; } if (matchingFile) { break; } } } return matchingFile; } public static function ensureOSLineEndings(text:String):String { if (File.lineEnding == CRLF_LINE_ENDING) { return ensureCRLF(text); } if (File.lineEnding == LF_LINE_ENDING) { return ensureLF(text); } return text ? text : ""; } private static function ensureCRLF(text:String):String { return text ? text.replace(/(?<!\r)\n/g, CRLF_LINE_ENDING) : ""; } private static function ensureLF(text:String):String { return text ? text.replace(/\r\n/g, LF_LINE_ENDING) : ""; } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 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 com.esri.builder.supportClasses { import flash.filesystem.File; public class FileUtil { private static const CRLF_LINE_ENDING:String = "\r\n"; private static const LF_LINE_ENDING:String = "\n"; public static function ensureOSLineEndings(text:String):String { if (File.lineEnding == CRLF_LINE_ENDING) { return ensureCRLF(text); } if (File.lineEnding == LF_LINE_ENDING) { return ensureLF(text); } return text ? text : ""; } private static function ensureCRLF(text:String):String { return text ? text.replace(/(?<!\r)\n/g, CRLF_LINE_ENDING) : ""; } private static function ensureLF(text:String):String { return text ? text.replace(/\r\n/g, LF_LINE_ENDING) : ""; } public static function generateUniqueRelativePath(baseDirectory:File, relativeFilePath:String, relativePathBlackList:Array = null):String { var extensionIndex:int = relativeFilePath.lastIndexOf("."); var extension:String = ""; if (extensionIndex > -1) { extension = relativeFilePath.substr(extensionIndex); relativeFilePath = relativeFilePath.substr(0, extensionIndex); } var filenameTemplate:String = relativeFilePath + "_{0}" + extension; var uniqueWidgetConfigPath:String = LabelUtil.generateUniqueLabel(filenameTemplate, relativePathBlackList, function isNonExistentFile(uniqueFilePath:String, availableNames:Array):Boolean { if (availableNames && availableNames.indexOf(uniqueFilePath) > -1) { return false; } return !baseDirectory.resolvePath(uniqueFilePath).exists; }); return uniqueWidgetConfigPath; } public static function getFileName(file:File):String { return file.name.replace("." + file.extension, ""); } public static function findMatchingFiles(directory:File, pattern:RegExp):Array { var moduleFiles:Array = []; if (directory.isDirectory) { const files:Array = directory.getDirectoryListing(); for each (var file:File in files) { if (file.isDirectory) { moduleFiles = moduleFiles.concat(findMatchingFiles(file, pattern)); } else if (pattern.test(file.name)) { moduleFiles.push(file); } } } return moduleFiles; } public static function findMatchingFile(directory:File, pattern:RegExp):File { var matchingFile:File; if (directory.isDirectory) { const files:Array = directory.getDirectoryListing(); //sort files first to reduce unnecessary directory listing calls. files.sortOn("isDirectory"); for each (var file:File in files) { if (file.isDirectory) { matchingFile = findMatchingFile(file, pattern); } else if (pattern.test(file.name)) { matchingFile = file; } if (matchingFile) { break; } } } return matchingFile; } } }
Clean up.
Clean up.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
7ffda1c60a484682d4b816e581772b75a1ccac55
Arguments/src/Controller/logic/DisjunctiveSyllogism.as
Arguments/src/Controller/logic/DisjunctiveSyllogism.as
package Controller.logic { import Model.AGORAModel; import Model.ArgumentTypeModel; import Model.SimpleStatementModel; import Model.StatementModel; import ValueObjects.AGORAParameters; import components.ArgumentPanel; import classes.Language; import mx.controls.Alert; public class DisjunctiveSyllogism extends ParentArg { private static var instance:DisjunctiveSyllogism; public function DisjunctiveSyllogism() { label = AGORAParameters.getInstance().DIS_SYLL; } public static function getInstance():DisjunctiveSyllogism{ if(instance == null){ instance = new DisjunctiveSyllogism; } return instance; } override public function formText(argumentTypeModel:ArgumentTypeModel):void{ var output:String = ""; var reasonText:String = ""; var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels; var claimModel:StatementModel = argumentTypeModel.claimModel; var inferenceModel:StatementModel = argumentTypeModel.inferenceModel; var i:int; output = "Either "; //TODO: Need a translation for this if(reasonModels.length < inferenceModel.statements.length){ for(i=0; i<reasonModels.length; i++){ inferenceModel.statements[i+1].text = reasonModels[i].statement.positiveText; reasonText = reasonText + reasonModels[i].statement.positiveText + Language.lookup("ArgOr"); } inferenceModel.statements[0].text = claimModel.statement.text; output = output + reasonText + claimModel.statement.text; inferenceModel.statement.text = output; } } override public function deleteLinks(argumentTypeModel:ArgumentTypeModel):void{ var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels; var claimModel:StatementModel = argumentTypeModel.claimModel; var inferenceModel:StatementModel = argumentTypeModel.inferenceModel; //remove negativity of the reason reasonModels[0].negated = false; //remove links from reason to inference var simpleStatement:SimpleStatementModel; var stmtToBeUnlinked:SimpleStatementModel; simpleStatement = reasonModels[0].statement; stmtToBeUnlinked = inferenceModel.statements[1]; removeDependence(simpleStatement, stmtToBeUnlinked); simpleStatement = claimModel.statement; stmtToBeUnlinked = inferenceModel.statements[0]; removeDependence(simpleStatement, stmtToBeUnlinked); } override public function link(argumentTypeModel:ArgumentTypeModel):void{ var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels; var claimModel:StatementModel = argumentTypeModel.claimModel; var inferenceModel:StatementModel = argumentTypeModel.inferenceModel; claimModel.statement.forwardList.push(inferenceModel.statements[0]); for(var i:int=0; i<reasonModels.length; i++){ reasonModels[i].statement.forwardList.push(inferenceModel.statements[i+1]); reasonModels[i].negated = true; } inferenceModel.connectingString = StatementModel.DISJUNCTION; } } }
package Controller.logic { import Model.AGORAModel; import Model.ArgumentTypeModel; import Model.SimpleStatementModel; import Model.StatementModel; import ValueObjects.AGORAParameters; import components.ArgumentPanel; import classes.Language; import mx.controls.Alert; public class DisjunctiveSyllogism extends ParentArg { private static var instance:DisjunctiveSyllogism; public function DisjunctiveSyllogism() { label = AGORAParameters.getInstance().DIS_SYLL; } public static function getInstance():DisjunctiveSyllogism{ if(instance == null){ instance = new DisjunctiveSyllogism; } return instance; } override public function formText(argumentTypeModel:ArgumentTypeModel):void{ var output:String = ""; var reasonText:String = ""; var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels; var claimModel:StatementModel = argumentTypeModel.claimModel; var inferenceModel:StatementModel = argumentTypeModel.inferenceModel; var i:int; output = Language.lookup("ArgEitherCap"); //TODO: Need a translation for this if(reasonModels.length < inferenceModel.statements.length){ for(i=0; i<reasonModels.length; i++){ inferenceModel.statements[i+1].text = reasonModels[i].statement.positiveText; reasonText = reasonText + reasonModels[i].statement.positiveText + Language.lookup("ArgOr"); } inferenceModel.statements[0].text = claimModel.statement.text; output = output + reasonText + claimModel.statement.text; inferenceModel.statement.text = output; } } override public function deleteLinks(argumentTypeModel:ArgumentTypeModel):void{ var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels; var claimModel:StatementModel = argumentTypeModel.claimModel; var inferenceModel:StatementModel = argumentTypeModel.inferenceModel; //remove negativity of the reason reasonModels[0].negated = false; //remove links from reason to inference var simpleStatement:SimpleStatementModel; var stmtToBeUnlinked:SimpleStatementModel; simpleStatement = reasonModels[0].statement; stmtToBeUnlinked = inferenceModel.statements[1]; removeDependence(simpleStatement, stmtToBeUnlinked); simpleStatement = claimModel.statement; stmtToBeUnlinked = inferenceModel.statements[0]; removeDependence(simpleStatement, stmtToBeUnlinked); } override public function link(argumentTypeModel:ArgumentTypeModel):void{ var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels; var claimModel:StatementModel = argumentTypeModel.claimModel; var inferenceModel:StatementModel = argumentTypeModel.inferenceModel; claimModel.statement.forwardList.push(inferenceModel.statements[0]); for(var i:int=0; i<reasonModels.length; i++){ reasonModels[i].statement.forwardList.push(inferenceModel.statements[i+1]); reasonModels[i].negated = true; } inferenceModel.connectingString = StatementModel.DISJUNCTION; } } }
Add translation for Either
Add translation for Either
ActionScript
agpl-3.0
mbjornas3/AGORA,mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA
a20bad21bfae144295af90b3b76066b7f77f8cd9
dolly-framework/src/test/actionscript/dolly/CopierTest.as
dolly-framework/src/test/actionscript/dolly/CopierTest.as
package dolly { import dolly.core.dolly_internal; import dolly.data.ClassLevelCopyable; import dolly.data.ClassLevelCopyableCloneable; import dolly.data.PropertyLevelCopyable; import dolly.data.PropertyLevelCopyableCloneable; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertNotNull; import org.flexunit.asserts.assertNull; use namespace dolly_internal; public class CopierTest { private var classLevelCopyable:ClassLevelCopyable; private var classLevelCopyableType:Type; private var classLevelCopyableCloneable:ClassLevelCopyableCloneable; private var classLevelCopyableCloneableType:Type; private var propertyLevelCopyable:PropertyLevelCopyable; private var propertyLevelCopyableType:Type; private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable; private var propertyLevelCopyableCloneableType:Type; [Before] public function before():void { classLevelCopyable = new ClassLevelCopyable(); classLevelCopyable.property1 = "value 1"; classLevelCopyable.property2 = "value 2"; classLevelCopyable.property3 = "value 3"; classLevelCopyable.writableField = "value 4"; classLevelCopyableType = Type.forInstance(classLevelCopyable); classLevelCopyableCloneable = new ClassLevelCopyableCloneable(); classLevelCopyableCloneable.property1 = "value 1"; classLevelCopyableCloneable.property2 = "value 2"; classLevelCopyableCloneable.property3 = "value 3"; classLevelCopyableCloneable.writableField = "value 4"; classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable); propertyLevelCopyable = new PropertyLevelCopyable(); propertyLevelCopyable.property1 = "value 1"; propertyLevelCopyable.property2 = "value 2"; propertyLevelCopyable.property3 = "value 3"; propertyLevelCopyable.writableField = "value 4"; propertyLevelCopyableType = Type.forInstance(propertyLevelCopyable); propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable(); propertyLevelCopyableCloneable.property1 = "value 1"; propertyLevelCopyableCloneable.property2 = "value 2"; propertyLevelCopyableCloneable.property3 = "value 3"; propertyLevelCopyableCloneable.writableField = "value 4"; propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable); } [After] public function after():void { classLevelCopyable = null; classLevelCopyableType = null; classLevelCopyableCloneable = null; classLevelCopyableCloneableType = null; propertyLevelCopyable = null; propertyLevelCopyableType = null; propertyLevelCopyableCloneable = null; propertyLevelCopyableCloneableType = null; } [Test] public function testGetCopyableFieldsForTypeClassLevelCopyable():void { const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableType); assertNotNull(copyableFields); assertEquals(4, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); assertNotNull(copyableFields[3]); } [Test] public function testGetCopyableFieldsForTypeClassLevelCopyableCloneable():void { const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableCloneableType); assertNotNull(copyableFields); assertEquals(4, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); assertNotNull(copyableFields[3]); } [Test] public function testGetCopyableFieldsForTypePropertyLevelCopyable():void { const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(propertyLevelCopyableType); assertNotNull(copyableFields); assertEquals(3, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); } [Test] public function testGetCopyableFieldsForTypePropertyLevelCopyableCloneable():void { const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(propertyLevelCopyableCloneableType); assertNotNull(copyableFields); assertEquals(3, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); } [Test] public function testCopyClassLevelCopyable():void { const copy:ClassLevelCopyable = Copier.copy(classLevelCopyable); assertNotNull(copy); assertNotNull(copy.property1); assertEquals(copy.property1, classLevelCopyable.property1); assertNotNull(copy.property2); assertEquals(copy.property2, classLevelCopyable.property2); assertNotNull(copy.property3); assertEquals(copy.property3, classLevelCopyable.property3); assertNotNull(copy.writableField); assertEquals(copy.writableField, classLevelCopyable.writableField); } [Test] public function testCopyClassLevelCopyableCloneable():void { const copy:ClassLevelCopyableCloneable = Copier.copy(classLevelCopyableCloneable); assertNotNull(copy); assertNotNull(copy.property1); assertEquals(copy.property1, classLevelCopyable.property1); assertNotNull(copy.property2); assertEquals(copy.property2, classLevelCopyable.property2); assertNotNull(copy.property3); assertEquals(copy.property3, classLevelCopyable.property3); assertNotNull(copy.writableField); assertEquals(copy.writableField, classLevelCopyable.writableField); } [Test] public function testCopyWithPropertyLevelMetadata():void { const copy1:PropertyLevelCopyable = Copier.copy(propertyLevelCopyable); assertNotNull(copy1); assertNull(copy1.property1); assertNotNull(copy1.property2); assertEquals(copy1.property2, classLevelCopyable.property2); assertNotNull(copy1.property3); assertEquals(copy1.property3, classLevelCopyable.property3); assertNotNull(copy1.writableField); assertEquals(copy1.writableField, classLevelCopyable.writableField); const copy2:PropertyLevelCopyableCloneable = Copier.copy(propertyLevelCopyableCloneable); assertNotNull(copy2); assertNull(copy2.property1); assertNotNull(copy2.property2); assertEquals(copy2.property2, classLevelCopyable.property2); assertNotNull(copy2.property3); assertEquals(copy2.property3, classLevelCopyable.property3); assertNotNull(copy2.writableField); assertEquals(copy2.writableField, classLevelCopyable.writableField); } } }
package dolly { import dolly.core.dolly_internal; import dolly.data.ClassLevelCopyable; import dolly.data.ClassLevelCopyableCloneable; import dolly.data.PropertyLevelCopyable; import dolly.data.PropertyLevelCopyableCloneable; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertNotNull; import org.flexunit.asserts.assertNull; use namespace dolly_internal; public class CopierTest { private var classLevelCopyable:ClassLevelCopyable; private var classLevelCopyableType:Type; private var classLevelCopyableCloneable:ClassLevelCopyableCloneable; private var classLevelCopyableCloneableType:Type; private var propertyLevelCopyable:PropertyLevelCopyable; private var propertyLevelCopyableType:Type; private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable; private var propertyLevelCopyableCloneableType:Type; [Before] public function before():void { classLevelCopyable = new ClassLevelCopyable(); classLevelCopyable.property1 = "value 1"; classLevelCopyable.property2 = "value 2"; classLevelCopyable.property3 = "value 3"; classLevelCopyable.writableField = "value 4"; classLevelCopyableType = Type.forInstance(classLevelCopyable); classLevelCopyableCloneable = new ClassLevelCopyableCloneable(); classLevelCopyableCloneable.property1 = "value 1"; classLevelCopyableCloneable.property2 = "value 2"; classLevelCopyableCloneable.property3 = "value 3"; classLevelCopyableCloneable.writableField = "value 4"; classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable); propertyLevelCopyable = new PropertyLevelCopyable(); propertyLevelCopyable.property1 = "value 1"; propertyLevelCopyable.property2 = "value 2"; propertyLevelCopyable.property3 = "value 3"; propertyLevelCopyable.writableField = "value 4"; propertyLevelCopyableType = Type.forInstance(propertyLevelCopyable); propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable(); propertyLevelCopyableCloneable.property1 = "value 1"; propertyLevelCopyableCloneable.property2 = "value 2"; propertyLevelCopyableCloneable.property3 = "value 3"; propertyLevelCopyableCloneable.writableField = "value 4"; propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable); } [After] public function after():void { classLevelCopyable = null; classLevelCopyableType = null; classLevelCopyableCloneable = null; classLevelCopyableCloneableType = null; propertyLevelCopyable = null; propertyLevelCopyableType = null; propertyLevelCopyableCloneable = null; propertyLevelCopyableCloneableType = null; } [Test] public function testGetCopyableFieldsForTypeClassLevelCopyable():void { const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableType); assertNotNull(copyableFields); assertEquals(4, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); assertNotNull(copyableFields[3]); } [Test] public function testGetCopyableFieldsForTypeClassLevelCopyableCloneable():void { const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableCloneableType); assertNotNull(copyableFields); assertEquals(4, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); assertNotNull(copyableFields[3]); } [Test] public function testGetCopyableFieldsForTypePropertyLevelCopyable():void { const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(propertyLevelCopyableType); assertNotNull(copyableFields); assertEquals(3, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); } [Test] public function testGetCopyableFieldsForTypePropertyLevelCopyableCloneable():void { const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(propertyLevelCopyableCloneableType); assertNotNull(copyableFields); assertEquals(3, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); } [Test] public function testCopyClassLevelCopyable():void { const copy:ClassLevelCopyable = Copier.copy(classLevelCopyable); assertNotNull(copy); assertNotNull(copy.property1); assertEquals(copy.property1, classLevelCopyable.property1); assertNotNull(copy.property2); assertEquals(copy.property2, classLevelCopyable.property2); assertNotNull(copy.property3); assertEquals(copy.property3, classLevelCopyable.property3); assertNotNull(copy.writableField); assertEquals(copy.writableField, classLevelCopyable.writableField); } [Test] public function testCopyClassLevelCopyableCloneable():void { const copy:ClassLevelCopyableCloneable = Copier.copy(classLevelCopyableCloneable); assertNotNull(copy); assertNotNull(copy.property1); assertEquals(copy.property1, classLevelCopyable.property1); assertNotNull(copy.property2); assertEquals(copy.property2, classLevelCopyable.property2); assertNotNull(copy.property3); assertEquals(copy.property3, classLevelCopyable.property3); assertNotNull(copy.writableField); assertEquals(copy.writableField, classLevelCopyable.writableField); } [Test] public function testCopyPropertyLevelCopyable():void { const copy:PropertyLevelCopyable = Copier.copy(propertyLevelCopyable); assertNotNull(copy); assertNull(copy.property1); assertNotNull(copy.property2); assertEquals(copy.property2, classLevelCopyable.property2); assertNotNull(copy.property3); assertEquals(copy.property3, classLevelCopyable.property3); assertNotNull(copy.writableField); assertEquals(copy.writableField, classLevelCopyable.writableField); } [Test] public function testCopyPropertyLevelCopyableCloneable():void { const copy:PropertyLevelCopyableCloneable = Copier.copy(propertyLevelCopyableCloneable); assertNotNull(copy); assertNull(copy.property1); assertNotNull(copy.property2); assertEquals(copy.property2, classLevelCopyable.property2); assertNotNull(copy.property3); assertEquals(copy.property3, classLevelCopyable.property3); assertNotNull(copy.writableField); assertEquals(copy.writableField, classLevelCopyable.writableField); } } }
Split method "testCopyWithPropertyLevelMetadata" to a few.
Split method "testCopyWithPropertyLevelMetadata" to a few.
ActionScript
mit
Yarovoy/dolly
787996985ef4803e4f5c9721cfce3e7a0f378316
flash/jasmine-flex/src/spec/AddUser.as
flash/jasmine-flex/src/spec/AddUser.as
import com.infrared5.application.command.AddUserCommand; import com.infrared5.application.model.Session; import com.infrared5.application.model.User; import com.infrared5.application.service.UserService; import flash.events.Event; import flash.net.URLLoader; import mockolate.stub; import org.jasmineflex.global.*; import support.Prepare; describe("Add User", function():void { var user:User; var session:Session; var command:AddUserCommand; var userService:UserService; var dispatcher:URLLoader = new URLLoader(); const USER_ID:String = new Date().time.toString(); beforeEach(function():void { user = new User(USER_ID); session = new Session(); command = new AddUserCommand(); Prepare.UserServicePrep(function(mockService:UserService):void { userService = mockService; command.session = session; command.userService = userService; command.setUser(user); stub(userService).method('addUser').returns(dispatcher); }); }); afterEach(function():void { user = null; session = null; }); describe("add previously non-existant user", function():void { it("should return user on success", function():void { var responseUser:User; command.execute(function(response:Object):void { responseUser = response as User; }, null); dispatcher.dispatchEvent(new Event(Event.COMPLETE)); waitsFor(function():* { return responseUser != null; }, "Could not properly test add user. Timeout.", 500); runs(function():void { expect(responseUser).toEqual(user); }); }); }); });
import com.infrared5.application.command.AddUserCommand; import com.infrared5.application.model.Session; import com.infrared5.application.model.User; import com.infrared5.application.service.UserService; import flash.events.Event; import flash.events.IOErrorEvent; import flash.net.URLLoader; import mockolate.stub; import org.jasmineflex.global.*; import support.Prepare; describe("Add User", function():void { var user:User; var session:Session; var command:AddUserCommand; var userService:UserService; var dispatcher:URLLoader = new URLLoader(); const USER_ID:String = new Date().time.toString(); beforeEach(function():void { user = new User(USER_ID); session = new Session(); command = new AddUserCommand(); Prepare.UserServicePrep(function(mockService:UserService):void { userService = mockService; command.session = session; command.userService = userService; command.setUser(user); stub(userService).method('addUser').returns(dispatcher); }); }); afterEach(function():void { user = null; session = null; }); describe("add previously non-existant user", function():void { it("should return user on success", function():void { var responseUser:User; command.execute(function(response:Object):void { responseUser = response as User; }, null); dispatcher.dispatchEvent(new Event(Event.COMPLETE)); waitsFor(function():* { return responseUser != null; }, "Could not properly test add user. Timeout.", 500); runs(function():void { expect(responseUser).toEqual(user); }); }); it("should append previously non-existant user to session listing.", function():void { var responseUser:User; command.execute(function(response:Object):void { responseUser = response as User; }, null); dispatcher.dispatchEvent(new Event(Event.COMPLETE)); waitsFor(function():* { return responseUser != null; }, "Could not properly test add user. Timeout.", 500); runs(function():void { expect(session.users.length).toEqual(1); expect(session.users[0]).toEqual(user); }); }); }); describe("add previously existant user", function():void { it("should respond on fault if user not added", function():void { var responseMessage:String; command.execute(null, function(response:Object):void { responseMessage = response as String; }); dispatcher.dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR)); waitsFor(function():* { return responseMessage != null; }, "Could not properly test add user. Timeout.", 500); runs(function():void { expect(responseMessage as String).not.toBeNull(); }); }); it("should not affect session user list on fault", function():void { var responseMessage:String; var previousSessionUserLength:int = session.users.length; command.execute(null, function(response:Object):void { responseMessage = response as String; }); dispatcher.dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR)); waitsFor(function():* { return responseMessage != null; }, "Could not properly test add user. Timeout.", 500); runs(function():void { expect(session.users.length).toEqual(previousSessionUserLength); }); }); }); });
add user specs for jasmine-flex
add user specs for jasmine-flex
ActionScript
mit
infrared5/unit-testing
3da5425f97c8e09f8839a41e1849575083346732
src/org/robotlegs/mvcs/Context.as
src/org/robotlegs/mvcs/Context.as
/* * Copyright (c) 2009 the original author or authors * * Permission is hereby granted to use, modify, and distribute this file * in accordance with the terms of the license agreement accompanying it. */ package org.robotlegs.mvcs { import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.IEventDispatcher; import flash.system.ApplicationDomain; import org.robotlegs.adapters.SwiftSuspendersInjector; import org.robotlegs.adapters.SwiftSuspendersReflector; import org.robotlegs.base.CommandMap; import org.robotlegs.base.ContextBase; import org.robotlegs.base.ContextEvent; import org.robotlegs.base.EventMap; import org.robotlegs.base.MediatorMap; import org.robotlegs.base.ViewMap; import org.robotlegs.core.ICommandMap; import org.robotlegs.core.IContext; import org.robotlegs.core.IEventMap; import org.robotlegs.core.IInjector; import org.robotlegs.core.IMediatorMap; import org.robotlegs.core.IReflector; import org.robotlegs.core.IViewMap; /** * Abstract MVCS <code>IContext</code> implementation */ public class Context extends ContextBase implements IContext { /** * @private */ protected var _injector:IInjector; /** * @private */ protected var _reflector:IReflector; /** * @private */ protected var _autoStartup:Boolean; /** * @private */ protected var _contextView:DisplayObjectContainer; /** * @private */ protected var _commandMap:ICommandMap; /** * @private */ protected var _mediatorMap:IMediatorMap; /** * @private */ protected var _viewMap:IViewMap; //--------------------------------------------------------------------- // Constructor //--------------------------------------------------------------------- /** * Abstract Context Implementation * * <p>Extend this class to create a Framework or Application context</p> * * @param contextView The root view node of the context. The context will listen for ADDED_TO_STAGE events on this node * @param autoStartup Should this context automatically invoke it's <code>startup</code> method when it's <code>contextView</code> arrives on Stage? */ public function Context(contextView:DisplayObjectContainer = null, autoStartup:Boolean = true) { super(); _contextView = contextView; _autoStartup = autoStartup; mapInjections(); checkAutoStartup(); } //--------------------------------------------------------------------- // API //--------------------------------------------------------------------- /** * The Startup Hook * * <p>Override this in your Application context</p> */ public function startup():void { dispatchEvent(new ContextEvent(ContextEvent.STARTUP_COMPLETE)); } /** * The Startup Hook * * <p>Override this in your Application context</p> */ public function shutdown():void { dispatchEvent(new ContextEvent(ContextEvent.SHUTDOWN_COMPLETE)); } /** * The <code>DisplayObjectContainer</code> that scopes this <code>IContext</code> */ public function get contextView():DisplayObjectContainer { return _contextView; } /** * @private */ public function set contextView(value:DisplayObjectContainer):void { if (_contextView != value) { _contextView = value; // Hack: We have to clear these out and re-map them _injector.applicationDomain = getApplicationDomainFromContextView(); _commandMap = null; _mediatorMap = null; _viewMap = null; mapInjections(); checkAutoStartup(); } } //--------------------------------------------------------------------- // Protected, Lazy Getters and Setters //--------------------------------------------------------------------- /** * The <code>IInjector</code> for this <code>IContext</code> */ protected function get injector():IInjector { return _injector ||= createInjector(); } /** * @private */ protected function set injector(value:IInjector):void { _injector = value; } /** * The <code>IReflector</code> for this <code>IContext</code> */ protected function get reflector():IReflector { return _reflector ||= new SwiftSuspendersReflector(); } /** * @private */ protected function set reflector(value:IReflector):void { _reflector = value; } /** * The <code>ICommandMap</code> for this <code>IContext</code> */ protected function get commandMap():ICommandMap { return _commandMap ||= new CommandMap(eventDispatcher, createChildInjector(), reflector); } /** * @private */ protected function set commandMap(value:ICommandMap):void { _commandMap = value; } /** * The <code>IMediatorMap</code> for this <code>IContext</code> */ protected function get mediatorMap():IMediatorMap { return _mediatorMap ||= new MediatorMap(contextView, createChildInjector(), reflector); } /** * @private */ protected function set mediatorMap(value:IMediatorMap):void { _mediatorMap = value; } /** * The <code>IViewMap</code> for this <code>IContext</code> */ protected function get viewMap():IViewMap { return _viewMap ||= new ViewMap(contextView, injector); } /** * @private */ protected function set viewMap(value:IViewMap):void { _viewMap = value; } //--------------------------------------------------------------------- // Framework Hooks //--------------------------------------------------------------------- /** * Injection Mapping Hook * * <p>Override this in your Framework context to change the default configuration</p> * * <p>Beware of collisions in your container</p> */ protected function mapInjections():void { injector.mapValue(IReflector, reflector); injector.mapValue(IInjector, injector); injector.mapValue(IEventDispatcher, eventDispatcher); injector.mapValue(DisplayObjectContainer, contextView); injector.mapValue(ICommandMap, commandMap); injector.mapValue(IMediatorMap, mediatorMap); injector.mapValue(IViewMap, viewMap); injector.mapClass(IEventMap, EventMap); } //--------------------------------------------------------------------- // Internal //--------------------------------------------------------------------- /** * @private */ protected function checkAutoStartup():void { if (_autoStartup && contextView) { contextView.stage ? startup() : contextView.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true); } } /** * @private */ protected function onAddedToStage(e:Event):void { contextView.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); startup(); } /** * @private */ protected function createInjector():IInjector { var injector:IInjector = new SwiftSuspendersInjector(); injector.applicationDomain = getApplicationDomainFromContextView(); return injector; } /** * @private */ protected function createChildInjector():IInjector { return injector.createChild(getApplicationDomainFromContextView()); } /** * @private */ protected function getApplicationDomainFromContextView():ApplicationDomain { if (contextView && contextView.loaderInfo) return contextView.loaderInfo.applicationDomain; return ApplicationDomain.currentDomain; } } }
/* * Copyright (c) 2009 the original author or authors * * Permission is hereby granted to use, modify, and distribute this file * in accordance with the terms of the license agreement accompanying it. */ package org.robotlegs.mvcs { import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.IEventDispatcher; import flash.system.ApplicationDomain; import org.robotlegs.adapters.SwiftSuspendersInjector; import org.robotlegs.adapters.SwiftSuspendersReflector; import org.robotlegs.base.CommandMap; import org.robotlegs.base.ContextBase; import org.robotlegs.base.ContextEvent; import org.robotlegs.base.EventMap; import org.robotlegs.base.MediatorMap; import org.robotlegs.base.ViewMap; import org.robotlegs.core.ICommandMap; import org.robotlegs.core.IContext; import org.robotlegs.core.IEventMap; import org.robotlegs.core.IInjector; import org.robotlegs.core.IMediatorMap; import org.robotlegs.core.IReflector; import org.robotlegs.core.IViewMap; /** * Dispatched by the <code>startup()</code> method when it finishes * executing. * * <p>One common pattern for application startup/bootstrapping makes use * of the <code>startupComplete</code> event. In this pattern, you do the * following:</p> * <ul> * <li>Override the <code>startup()</code> method in your Context * subclass and set up application mappings in your * <code>startup()</code> override as you always do in Robotlegs.</li> * <li>Create commands that perform startup/bootstrapping operations * such as loading the initial data, checking for application updates, * etc.</li> * <li><p>Map those commands to the <code>ContextEvent.STARTUP_COMPLETE</code> * event:</p> * <listing>commandMap.mapEvent(ContextEvent.STARTUP_COMPLETE, LoadInitialDataCommand, ContextEvent, true):</listing> * </li> * <li>Dispatch the <code>startupComplete</code> (<code>ContextEvent.STARTUP_COMPLETE</code>) * event from your <code>startup()</code> override. You can do this * in one of two ways: dispatch the event yourself, or call * <code>super.startup()</code>. (The Context class's * <code>startup()</code> method dispatches the * <code>startupComplete</code> event.)</li> * </ul> * * @eventType org.robotlegs.base.ContextEvent.STARTUP_COMPLETE * * @see #startup() */ [Event(name="startupComplete", type="org.robotlegs.base.ContextEvent")] /** * Abstract MVCS <code>IContext</code> implementation */ public class Context extends ContextBase implements IContext { /** * @private */ protected var _injector:IInjector; /** * @private */ protected var _reflector:IReflector; /** * @private */ protected var _autoStartup:Boolean; /** * @private */ protected var _contextView:DisplayObjectContainer; /** * @private */ protected var _commandMap:ICommandMap; /** * @private */ protected var _mediatorMap:IMediatorMap; /** * @private */ protected var _viewMap:IViewMap; //--------------------------------------------------------------------- // Constructor //--------------------------------------------------------------------- /** * Abstract Context Implementation * * <p>Extend this class to create a Framework or Application context</p> * * @param contextView The root view node of the context. The context will listen for ADDED_TO_STAGE events on this node * @param autoStartup Should this context automatically invoke it's <code>startup</code> method when it's <code>contextView</code> arrives on Stage? */ public function Context(contextView:DisplayObjectContainer = null, autoStartup:Boolean = true) { super(); _contextView = contextView; _autoStartup = autoStartup; mapInjections(); checkAutoStartup(); } //--------------------------------------------------------------------- // API //--------------------------------------------------------------------- /** * The Startup Hook * * <p>Override this in your Application context</p> * * @event startupComplete ContextEvent.STARTUP_COMPLETE Dispatched at the end of the * <code>startup()</code> method's execution. This * is often used to trigger startup/bootstrapping * commands by wiring them to this event and * calling <code>super.startup()</code> in the * last line of your <code>startup()</code> * override. */ public function startup():void { dispatchEvent(new ContextEvent(ContextEvent.STARTUP_COMPLETE)); } /** * The Startup Hook * * <p>Override this in your Application context</p> */ public function shutdown():void { dispatchEvent(new ContextEvent(ContextEvent.SHUTDOWN_COMPLETE)); } /** * The <code>DisplayObjectContainer</code> that scopes this <code>IContext</code> */ public function get contextView():DisplayObjectContainer { return _contextView; } /** * @private */ public function set contextView(value:DisplayObjectContainer):void { if (_contextView != value) { _contextView = value; // Hack: We have to clear these out and re-map them _injector.applicationDomain = getApplicationDomainFromContextView(); _commandMap = null; _mediatorMap = null; _viewMap = null; mapInjections(); checkAutoStartup(); } } //--------------------------------------------------------------------- // Protected, Lazy Getters and Setters //--------------------------------------------------------------------- /** * The <code>IInjector</code> for this <code>IContext</code> */ protected function get injector():IInjector { return _injector ||= createInjector(); } /** * @private */ protected function set injector(value:IInjector):void { _injector = value; } /** * The <code>IReflector</code> for this <code>IContext</code> */ protected function get reflector():IReflector { return _reflector ||= new SwiftSuspendersReflector(); } /** * @private */ protected function set reflector(value:IReflector):void { _reflector = value; } /** * The <code>ICommandMap</code> for this <code>IContext</code> */ protected function get commandMap():ICommandMap { return _commandMap ||= new CommandMap(eventDispatcher, createChildInjector(), reflector); } /** * @private */ protected function set commandMap(value:ICommandMap):void { _commandMap = value; } /** * The <code>IMediatorMap</code> for this <code>IContext</code> */ protected function get mediatorMap():IMediatorMap { return _mediatorMap ||= new MediatorMap(contextView, createChildInjector(), reflector); } /** * @private */ protected function set mediatorMap(value:IMediatorMap):void { _mediatorMap = value; } /** * The <code>IViewMap</code> for this <code>IContext</code> */ protected function get viewMap():IViewMap { return _viewMap ||= new ViewMap(contextView, injector); } /** * @private */ protected function set viewMap(value:IViewMap):void { _viewMap = value; } //--------------------------------------------------------------------- // Framework Hooks //--------------------------------------------------------------------- /** * Injection Mapping Hook * * <p>Override this in your Framework context to change the default configuration</p> * * <p>Beware of collisions in your container</p> */ protected function mapInjections():void { injector.mapValue(IReflector, reflector); injector.mapValue(IInjector, injector); injector.mapValue(IEventDispatcher, eventDispatcher); injector.mapValue(DisplayObjectContainer, contextView); injector.mapValue(ICommandMap, commandMap); injector.mapValue(IMediatorMap, mediatorMap); injector.mapValue(IViewMap, viewMap); injector.mapClass(IEventMap, EventMap); } //--------------------------------------------------------------------- // Internal //--------------------------------------------------------------------- /** * @private */ protected function checkAutoStartup():void { if (_autoStartup && contextView) { contextView.stage ? startup() : contextView.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true); } } /** * @private */ protected function onAddedToStage(e:Event):void { contextView.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); startup(); } /** * @private */ protected function createInjector():IInjector { var injector:IInjector = new SwiftSuspendersInjector(); injector.applicationDomain = getApplicationDomainFromContextView(); return injector; } /** * @private */ protected function createChildInjector():IInjector { return injector.createChild(getApplicationDomainFromContextView()); } /** * @private */ protected function getApplicationDomainFromContextView():ApplicationDomain { if (contextView && contextView.loaderInfo) return contextView.loaderInfo.applicationDomain; return ApplicationDomain.currentDomain; } } }
Add documentation for the startupComplete event dispatched by the Context.startup() method. The docs describe a common pattern for using the startupComplete event to trigger traditional "app entrypoint" bootstrapping operations.
Add documentation for the startupComplete event dispatched by the Context.startup() method. The docs describe a common pattern for using the startupComplete event to trigger traditional "app entrypoint" bootstrapping operations.
ActionScript
mit
eric-stanley/robotlegs-framework,eric-stanley/robotlegs-framework,robotlegs/robotlegs-framework,robotlegs/robotlegs-framework
9cddf046562389c5a03c1c8e24fd781b63a07ccb
frameworks/projects/HTML/as/src/org/apache/flex/html/DropDownList.as
frameworks/projects/HTML/as/src/org/apache/flex/html/DropDownList.as
//////////////////////////////////////////////////////////////////////////////// // // 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.flex.html { import org.apache.flex.core.ISelectionModel; COMPILE::JS { import goog.events; import org.apache.flex.core.WrappedHTMLElement; import org.apache.flex.html.beads.models.ArraySelectionModel; } //-------------------------------------- // Events //-------------------------------------- /** * Dispatched when the user selects an item. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="change", type="org.apache.flex.events.Event")] /** * The DropDownList class implements the basic equivalent of * the <code>&lt;select&gt;</code> tag in HTML. * The default implementation only lets the user see and * choose from an array of strings. More complex controls * would display icons as well as strings, or colors instead * of strings or just about anything. * * The default behavior only lets the user choose one and * only one item. More complex controls would allow * mutiple selection by not dismissing the dropdown as soon * as a selection is made. * * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class DropDownList extends Button { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function DropDownList() { COMPILE::JS { model = new ArraySelectionModel(); } } /** * The data set to be displayed. Usually a simple * array of strings. A more complex component * would allow more complex data and data sets. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get dataProvider():Object { return ISelectionModel(model).dataProvider; } /** * @private * @flexjsignorecoercion HTMLOptionElement * @flexjsignorecoercion HTMLSelectElement */ public function set dataProvider(value:Object):void { ISelectionModel(model).dataProvider = value; COMPILE::JS { var dp:HTMLOptionsCollection; var i:int; var n:int; var opt:HTMLOptionElement; var dd:HTMLSelectElement = element as HTMLSelectElement; model.dataProvider = value; dp = dd.options; n = dp.length; for (i = 0; i < n; i++) { dd.remove(0); } var lf:String = labelField; n = value.length; for (i = 0; i < n; i++) { opt = document.createElement('option') as HTMLOptionElement; if (lf) opt.text = value[i][lf]; else opt.text = value[i]; dd.add(opt, null); } } } [Bindable("change")] /** * @copy org.apache.flex.core.ISelectionModel#selectedIndex * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get selectedIndex():int { return ISelectionModel(model).selectedIndex; } /** * @private */ public function set selectedIndex(value:int):void { ISelectionModel(model).selectedIndex = value; } [Bindable("change")] /** * @copy org.apache.flex.core.ISelectionModel#selectedItem * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get selectedItem():Object { return ISelectionModel(model).selectedItem; } /** * @private */ public function set selectedItem(value:Object):void { ISelectionModel(model).selectedItem = value; } /** * The name of field within the data used for display. Each item of the * data should have a property with this name. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get labelField():String { return ISelectionModel(model).labelField; } public function set labelField(value:String):void { ISelectionModel(model).labelField = value; } /** * @flexjsignorecoercion org.apache.flex.core.WrappedHTMLElement * @flexjsignorecoercion HTMLSelectElement */ COMPILE::JS override protected function createElement():WrappedHTMLElement { element = document.createElement('select') as WrappedHTMLElement; (element as HTMLSelectElement).size = 1; goog.events.listen(element, 'change', changeHandler); positioner = element; positioner.style.position = 'relative'; element.flexjs_wrapper = this; return element; } /** * @flexjsignorecoercion HTMLSelectElement */ COMPILE::JS protected function changeHandler(event:Event):void { model.selectedIndex = (element as HTMLSelectElement).selectedIndex; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.flex.html { import org.apache.flex.core.ISelectionModel; COMPILE::JS { import goog.events; import org.apache.flex.core.WrappedHTMLElement; import org.apache.flex.html.beads.models.ArraySelectionModel; } //-------------------------------------- // Events //-------------------------------------- /** * Dispatched when the user selects an item. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="change", type="org.apache.flex.events.Event")] /** * The DropDownList class implements the basic equivalent of * the <code>&lt;select&gt;</code> tag in HTML. * The default implementation only lets the user see and * choose from an array of strings. More complex controls * would display icons as well as strings, or colors instead * of strings or just about anything. * * The default behavior only lets the user choose one and * only one item. More complex controls would allow * mutiple selection by not dismissing the dropdown as soon * as a selection is made. * * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class DropDownList extends Button { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function DropDownList() { COMPILE::JS { model = new ArraySelectionModel(); } } /** * The data set to be displayed. Usually a simple * array of strings. A more complex component * would allow more complex data and data sets. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get dataProvider():Object { return ISelectionModel(model).dataProvider; } /** * @private * @flexjsignorecoercion HTMLOptionElement * @flexjsignorecoercion HTMLSelectElement */ public function set dataProvider(value:Object):void { ISelectionModel(model).dataProvider = value; COMPILE::JS { var dp:HTMLOptionsCollection; var i:int; var n:int; var opt:HTMLOptionElement; var dd:HTMLSelectElement = element as HTMLSelectElement; model.dataProvider = value; dp = dd.options; n = dp.length; for (i = 0; i < n; i++) { dd.remove(0); } var lf:String = labelField; n = value.length; for (i = 0; i < n; i++) { opt = document.createElement('option') as HTMLOptionElement; if (lf) opt.text = value[i][lf]; else opt.text = value[i]; dd.add(opt, null); } } } [Bindable("change")] /** * @copy org.apache.flex.core.ISelectionModel#selectedIndex * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get selectedIndex():int { return ISelectionModel(model).selectedIndex; } /** * @private * @flexjsignorecoercion HTMLSelectElement */ public function set selectedIndex(value:int):void { ISelectionModel(model).selectedIndex = value; COMPILE::JS { (element as HTMLSelectElement).selectedIndex = ISelectionModel(model).selectedIndex; } } [Bindable("change")] /** * @copy org.apache.flex.core.ISelectionModel#selectedItem * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get selectedItem():Object { return ISelectionModel(model).selectedItem; } /** * @private * @flexjsignorecoercion HTMLSelectElement */ public function set selectedItem(value:Object):void { ISelectionModel(model).selectedItem = value; COMPILE::JS { (element as HTMLSelectElement).selectedIndex = ISelectionModel(model).selectedIndex; } } /** * The name of field within the data used for display. Each item of the * data should have a property with this name. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get labelField():String { return ISelectionModel(model).labelField; } public function set labelField(value:String):void { ISelectionModel(model).labelField = value; } /** * @flexjsignorecoercion org.apache.flex.core.WrappedHTMLElement * @flexjsignorecoercion HTMLSelectElement */ COMPILE::JS override protected function createElement():WrappedHTMLElement { element = document.createElement('select') as WrappedHTMLElement; (element as HTMLSelectElement).size = 1; goog.events.listen(element, 'change', changeHandler); positioner = element; positioner.style.position = 'relative'; element.flexjs_wrapper = this; return element; } /** * @flexjsignorecoercion HTMLSelectElement */ COMPILE::JS protected function changeHandler(event:Event):void { model.selectedIndex = (element as HTMLSelectElement).selectedIndex; } } }
Fix dropdownlist selection
Fix dropdownlist selection
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
c5d60fea58814b11483281ee7f82b2f28ba697f3
lib/src/com/amanitadesign/steam/ISteamWorks.as
lib/src/com/amanitadesign/steam/ISteamWorks.as
/* * ISteamWorks.as * This file is part of FRESteamWorks. * * Created by Ventero <http://github.com/Ventero> on 2013-08-28 * Copyright (c) 2013 Level Up Labs, LLC. All rights reserved. */ package com.amanitadesign.steam { import flash.display.DisplayObjectContainer; import flash.events.IEventDispatcher; import flash.utils.ByteArray; public interface ISteamWorks extends IEventDispatcher { [Event(name="steamResponse", type="com.amanitadesign.steam.SteamEvent")] function ISteamWorks(target:IEventDispatcher = null); function init():Boolean; function dispose():void; function addOverlayWorkaround(container:DisplayObjectContainer, alwaysVisible:Boolean = false, color:uint = 0x000000):void; function runCallbacks():Boolean; function getUserID():String; function getAppID():uint; function getPersonaName():String; function useCrashHandler(appID:uint, version:String, date:String, time:String):Boolean; /* stats/achievements */ function requestStats():Boolean; function setAchievement(name:String):Boolean; function clearAchievement(name:String):Boolean; function isAchievement(name:String):Boolean; function getStatInt(name:String):int; function getStatFloat(name:String):Number; function setStatInt(name:String, value:int):Boolean; function setStatFloat(name:String, value:Number):Boolean; function storeStats():Boolean; function resetAllStats(achievementsToo:Boolean):Boolean; /* cloud */ function getFileCount():int; function getFileSize(name:String):int; function fileExists(name:String):Boolean; function fileWrite(name:String, data:ByteArray):Boolean; function fileRead(name:String, data:ByteArray):Boolean; function fileDelete(name:String):Boolean; function fileShare(name:String):Boolean; function fileShareResult():String; function isCloudEnabledForApp():Boolean; function setCloudEnabledForApp(enabled:Boolean):Boolean; function getQuota():Array; /* ugc/workshop */ function UGCDownload(handle:String, priority:int):Boolean; function UGCRead(handle:String, size:int, offset:uint, data:ByteArray):Boolean; function getUGCDownloadProgress(handle:String):Array; function getUGCDownloadResult(handle:String):DownloadUGCResult; function publishWorkshopFile(name:String, preview:String, appId:uint, title:String, description:String, visibility:uint, tags:Array, fileType:uint):Boolean; function publishWorkshopFileResult():String; function deletePublishedFile(file:String):Boolean; function getPublishedFileDetails(file:String, maxAge:int):Boolean; function getPublishedFileDetailsResult(file:String):FileDetailsResult; function enumerateUserPublishedFiles(startIndex:uint):Boolean; function enumerateUserPublishedFilesResult():UserFilesResult; function enumeratePublishedWorkshopFiles(type:uint, start:uint, count:uint, days:uint, tags:Array, userTags:Array):Boolean; function enumeratePublishedWorkshopFilesResult():WorkshopFilesResult; function enumerateUserSubscribedFiles(startIndex:uint):Boolean; function enumerateUserSubscribedFilesResult():SubscribedFilesResult; function enumerateUserSharedWorkshopFiles(steamID:String, start:uint, required:Array, excluded:Array):Boolean; function enumerateUserSharedWorkshopFilesResult():UserFilesResult; function enumeratePublishedFilesByUserAction(action:uint, startIndex:uint):Boolean; function enumeratePublishedFilesByUserActionResult():FilesByUserActionResult; function subscribePublishedFile(file:String):Boolean; function unsubscribePublishedFile(file:String):Boolean; function createPublishedFileUpdateRequest(file:String):String; function updatePublishedFileFile(handle:String, file:String):Boolean; function updatePublishedFilePreviewFile(handle:String, preview:String):Boolean; function updatePublishedFileTitle(handle:String, title:String):Boolean; function updatePublishedFileDescription(handle:String, description:String):Boolean; function updatePublishedFileSetChangeDescription(handle:String, changeDesc:String):Boolean; function updatePublishedFileVisibility(handle:String, visibility:uint):Boolean; function updatePublishedFileTags(handle:String, tags:Array):Boolean; function commitPublishedFileUpdate(handle:String):Boolean; function getPublishedItemVoteDetails(file:String):Boolean; function getPublishedItemVoteDetailsResult():ItemVoteDetailsResult; function getUserPublishedItemVoteDetails(file:String):Boolean; function getUserPublishedItemVoteDetailsResult():UserVoteDetails; function updateUserPublishedItemVote(file:String, upvote:Boolean):Boolean; function setUserPublishedFileAction(file:String, action:uint):Boolean; /* overlay */ function activateGameOverlay(dialog:String):Boolean; function activateGameOverlayToUser(dialog:String, steamId:String):Boolean; function activateGameOverlayToWebPage(url:String):Boolean; function activateGameOverlayToStore(appId:uint, flag:uint):Boolean; function activateGameOverlayInviteDialog(steamIdLobby:String):Boolean; function isOverlayEnabled():Boolean; /* DLC / subscriptions */ function isSubscribedApp(appId:uint):Boolean; function isDLCInstalled(appId:uint):Boolean; function getDLCCount():int; function installDLC(appId:uint):Boolean; function uninstallDLC(appId:uint):Boolean; function DLCInstalledResult():uint; } }
/* * ISteamWorks.as * This file is part of FRESteamWorks. * * Created by Ventero <http://github.com/Ventero> on 2013-08-28 * Copyright (c) 2013 Level Up Labs, LLC. All rights reserved. */ package com.amanitadesign.steam { import flash.display.DisplayObjectContainer; import flash.events.IEventDispatcher; import flash.utils.ByteArray; public interface ISteamWorks extends IEventDispatcher { [Event(name="steamResponse", type="com.amanitadesign.steam.SteamEvent")] function ISteamWorks(target:IEventDispatcher = null); function init():Boolean; function dispose():void; function addOverlayWorkaround(container:DisplayObjectContainer, alwaysVisible:Boolean = false, color:uint = 0x000000):void; function runCallbacks():Boolean function getUserID():String function getAppID():uint function getPersonaName():String function useCrashHandler(appID:uint, version:String, date:String, time:String):Boolean /* stats/achievements */ function requestStats():Boolean function setAchievement(name:String):Boolean function clearAchievement(name:String):Boolean function isAchievement(name:String):Boolean function getStatInt(name:String):int function getStatFloat(name:String):Number function setStatInt(name:String, value:int):Boolean function setStatFloat(name:String, value:Number):Boolean function storeStats():Boolean function resetAllStats(achievementsToo:Boolean):Boolean /* cloud */ function getFileCount():int function getFileSize(name:String):int function fileExists(name:String):Boolean function fileWrite(name:String, data:ByteArray):Boolean function fileRead(name:String, data:ByteArray):Boolean function fileDelete(name:String):Boolean function fileShare(name:String):Boolean function fileShareResult():String function isCloudEnabledForApp():Boolean function setCloudEnabledForApp(enabled:Boolean):Boolean function getQuota():Array /* ugc/workshop */ function UGCDownload(handle:String, priority:int):Boolean function UGCRead(handle:String, size:int, offset:uint, data:ByteArray):Boolean function getUGCDownloadProgress(handle:String):Array function getUGCDownloadResult(handle:String):DownloadUGCResult function publishWorkshopFile(name:String, preview:String, appId:uint, title:String, description:String, visibility:uint, tags:Array, fileType:uint):Boolean function publishWorkshopFileResult():String function deletePublishedFile(file:String):Boolean function getPublishedFileDetails(file:String, maxAge:int = 0):Boolean function getPublishedFileDetailsResult(file:String):FileDetailsResult function enumerateUserPublishedFiles(startIndex:uint):Boolean function enumerateUserPublishedFilesResult():UserFilesResult function enumeratePublishedWorkshopFiles(type:uint, start:uint, count:uint, days:uint, tags:Array, userTags:Array):Boolean function enumeratePublishedWorkshopFilesResult():WorkshopFilesResult function enumerateUserSubscribedFiles(startIndex:uint):Boolean function enumerateUserSubscribedFilesResult():SubscribedFilesResult function enumerateUserSharedWorkshopFiles(steamID:String, start:uint, required:Array, excluded:Array):Boolean function enumerateUserSharedWorkshopFilesResult():UserFilesResult function enumeratePublishedFilesByUserAction(action:uint, startIndex:uint):Boolean function enumeratePublishedFilesByUserActionResult():FilesByUserActionResult function subscribePublishedFile(file:String):Boolean function unsubscribePublishedFile(file:String):Boolean function createPublishedFileUpdateRequest(file:String):String function updatePublishedFileFile(handle:String, file:String):Boolean function updatePublishedFilePreviewFile(handle:String, preview:String):Boolean function updatePublishedFileTitle(handle:String, title:String):Boolean function updatePublishedFileDescription(handle:String, description:String):Boolean function updatePublishedFileSetChangeDescription(handle:String, changeDesc:String):Boolean function updatePublishedFileVisibility(handle:String, visibility:uint):Boolean function updatePublishedFileTags(handle:String, tags:Array):Boolean function commitPublishedFileUpdate(handle:String):Boolean function getPublishedItemVoteDetails(file:String):Boolean function getPublishedItemVoteDetailsResult():ItemVoteDetailsResult function getUserPublishedItemVoteDetails(file:String):Boolean function getUserPublishedItemVoteDetailsResult():UserVoteDetails function updateUserPublishedItemVote(file:String, upvote:Boolean):Boolean function setUserPublishedFileAction(file:String, action:uint):Boolean /* overlay */ function activateGameOverlay(dialog:String):Boolean function activateGameOverlayToUser(dialog:String, steamId:String):Boolean function activateGameOverlayToWebPage(url:String):Boolean function activateGameOverlayToStore(appId:uint, flag:uint):Boolean function activateGameOverlayInviteDialog(steamIdLobby:String):Boolean function isOverlayEnabled():Boolean /* DLC / subscriptions */ function isSubscribedApp(appId:uint):Boolean function isDLCInstalled(appId:uint):Boolean function getDLCCount():int function installDLC(appId:uint):Boolean function uninstallDLC(appId:uint):Boolean function DLCInstalledResult():uint } }
Remove unnecessary semicolons.
Remove unnecessary semicolons.
ActionScript
bsd-2-clause
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
035a499329d123525031ad2fbe049624f45dce1b
src/org/flintparticles/common/events/UpdateEvent.as
src/org/flintparticles/common/events/UpdateEvent.as
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2010 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.common.events { import flash.events.Event; /** * The class for particle related events dispatched by classes in the Flint project. */ public class UpdateEvent extends Event { /** * The event dispatched on the enter frame */ public static var UPDATE:String = "update"; /** * The particle to which the event relates. */ public var time:Number; /** * The constructor creates a ParticleEvent object. * * @param type The type of the event, accessible as Event.type. * @param particle The particle to which teh event relates. * @param bubbles Determines whether the Event object participates * in the bubbling stage of the event flow. The default value is false. * @param cancelable Determines whether the Event object can be * canceled. The default values is false. */ public function UpdateEvent( type : String, time:Number = NaN, bubbles : Boolean = false, cancelable : Boolean = false ) { super(type, bubbles, cancelable); this.time = time; } /** * Creates a copy of this event. * * @return The copy of this event. */ override public function clone():Event { return new UpdateEvent( type, time, bubbles, cancelable ); } } }
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2010 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.common.events { import flash.events.Event; /** * The UpdateEvent is dispatched from the FrameUpdater utility every frame, to all emitters that are * being updated by Flint, to trigger the update cycle on each emitter. */ public class UpdateEvent extends Event { /** * The event dispatched on the enter frame */ public static var UPDATE:String = "update"; /** * The particle to which the event relates. */ public var time:Number; /** * The constructor creates a ParticleEvent object. * * @param type The type of the event, accessible as Event.type. * @param particle The particle to which teh event relates. * @param bubbles Determines whether the Event object participates * in the bubbling stage of the event flow. The default value is false. * @param cancelable Determines whether the Event object can be * canceled. The default values is false. */ public function UpdateEvent( type : String, time:Number = NaN, bubbles : Boolean = false, cancelable : Boolean = false ) { super(type, bubbles, cancelable); this.time = time; } /** * Creates a copy of this event. * * @return The copy of this event. */ override public function clone():Event { return new UpdateEvent( type, time, bubbles, cancelable ); } } }
Fix documentation on UpdateEvent class
Fix documentation on UpdateEvent class
ActionScript
mit
richardlord/Flint
613b712831be9613167fd7e47a368de4b5194e94
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.external.ExternalInterface; import flash.text.TextField; import flash.text.TextFormat; import flash.net.Socket; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.utils.setTimeout; public class swfcat extends Sprite { private const RTMFP_URL:String = "rtmfp://tor-facilitator.bamsoftware.com"; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "tor-facilitator.bamsoftware.com", port: 9002 }; /* Local Tor client to use in case of RTMFP connection. */ private const DEFAULT_LOCAL_TOR_CLIENT_ADDR:Object = { host: "127.0.0.1", port: 9002 }; private const MAX_NUM_PROXY_PAIRS:uint = 100; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; // Bytes per second. Set to undefined to disable limit. public static const RATE_LIMIT:Number = undefined; // Seconds. private static const RATE_LIMIT_HISTORY:Number = 5.0; /* TextField for debug output. */ private var output_text:TextField; /* UI shown when debug is off. */ private var badge:Badge; /* Proxy pairs currently connected (up to MAX_NUM_PROXY_PAIRS). */ private var proxy_pairs:Array; private var fac_addr:Object; private var local_addr:Object; public var debug:Boolean; public var rate_limit:RateLimit; public function puts(s:String):void { if (output_text) { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } } public function swfcat() { // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; badge = new Badge(); proxy_pairs = []; if (RATE_LIMIT) rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY); else rate_limit = new RateUnlimit(); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { debug = this.loaderInfo.parameters["debug"]; if (debug || this.loaderInfo.parameters["client"]) { output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; addChild(output_text); } else { addChild(badge); } puts("Parameters loaded."); fac_addr = get_param_addr("facilitator", DEFAULT_FACILITATOR_ADDR); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } local_addr = get_param_addr("local", DEFAULT_LOCAL_TOR_CLIENT_ADDR); if (!local_addr) { puts("Error: Local spec must be in the form \"host:port\"."); return; } if (this.loaderInfo.parameters["client"]) client_main(); else proxy_main(); } /* Get an address structure from the given movie parameter, or the given default. Returns null on error. */ private function get_param_addr(param:String, default_addr:Object):Object { var spec:String; spec = this.loaderInfo.parameters[param]; if (spec) return parse_addr_spec(spec); else return default_addr; } /* The main logic begins here, after start-up issues are taken care of. */ private function proxy_main():void { var fac_url:String; var loader:URLLoader; if (proxy_pairs.length >= MAX_NUM_PROXY_PAIRS) { setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL); return; } loader = new URLLoader(); /* Get the x-www-form-urlencoded values. */ loader.dataFormat = URLLoaderDataFormat.VARIABLES; loader.addEventListener(Event.COMPLETE, fac_complete); loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); }); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); }); fac_url = "http://" + encodeURIComponent(fac_addr.host) + ":" + encodeURIComponent(fac_addr.port) + "/"; puts("Facilitator: connecting to " + fac_url + "."); loader.load(new URLRequest(fac_url)); } private function fac_complete(e:Event):void { var loader:URLLoader; var client_spec:String; var relay_spec:String; var proxy_pair:Object; setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL); loader = e.target as URLLoader; client_spec = loader.data.client; if (client_spec == "") { puts("No clients."); return; } else if (!client_spec) { puts("Error: missing \"client\" in response."); return; } relay_spec = loader.data.relay; if (!relay_spec) { puts("Error: missing \"relay\" in response."); return; } puts("Facilitator: got client:\"" + client_spec + "\" " + "relay:\"" + relay_spec + "\"."); try { proxy_pair = make_proxy_pair(client_spec, relay_spec); } catch (e:ArgumentError) { puts("Error: " + e); return; } proxy_pairs.push(proxy_pair); proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void { proxy_pair.log("Complete."); /* Delete from the list of active proxy pairs. */ proxy_pairs.splice(proxy_pairs.indexOf(proxy_pair), 1); badge.proxy_end(); }); proxy_pair.connect(); badge.proxy_begin(); } private function client_main():void { var rs:RTMFPSocket; puts("Making RTMFP socket."); rs = new RTMFPSocket(RTMFP_URL); rs.addEventListener(Event.COMPLETE, function (e:Event):void { puts("Got RTMFP id " + rs.id); register(rs); }); rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, client_accept); rs.listen(); } private function client_accept(e:Event):void { var rs:RTMFPSocket; var s_t:Socket; var proxy_pair:ProxyPair; rs = e.target as RTMFPSocket; s_t = new Socket(); puts("Got RTMFP connection from " + rs.peer_id); proxy_pair = new ProxyPair(this, rs, function ():void { /* Do nothing; already connected. */ }, s_t, function ():void { s_t.connect(local_addr.host, local_addr.port); }); proxy_pair.connect(); } private function register(rs:RTMFPSocket):void { var fac_url:String; var loader:URLLoader; var request:URLRequest; loader = new URLLoader(); loader.addEventListener(Event.COMPLETE, function (e:Event):void { puts("Facilitator: registered."); }); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); rs.close(); }); loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); rs.close(); }); fac_url = "http://" + encodeURIComponent(fac_addr.host) + ":" + encodeURIComponent(fac_addr.port) + "/"; request = new URLRequest(fac_url); request.method = URLRequestMethod.POST; request.data = new URLVariables(); request.data["client"] = rs.id; puts("Facilitator: connecting to " + fac_url + "."); loader.load(request); } private function make_proxy_pair(client_spec:String, relay_spec:String):ProxyPair { var proxy_pair:ProxyPair; var addr_c:Object; var addr_r:Object; var s_c:*; var s_r:Socket; addr_r = swfcat.parse_addr_spec(relay_spec); if (!addr_r) throw new ArgumentError("Relay spec must be in the form \"host:port\"."); addr_c = swfcat.parse_addr_spec(client_spec); if (addr_c) { s_c = new Socket(); s_r = new Socket(); proxy_pair = new ProxyPair(this, s_c, function ():void { s_c.connect(addr_c.host, addr_c.port); }, s_r, function ():void { s_r.connect(addr_r.host, addr_r.port); }); proxy_pair.set_name("<" + addr_c.host + ":" + addr_c.port + "," + addr_r.host + ":" + addr_r.port + ">"); return proxy_pair; } if (client_spec.match(/^[0-9A-Fa-f]{64}$/)) { s_c = new RTMFPSocket(RTMFP_URL); s_r = new Socket(); proxy_pair = new ProxyPair(this, s_c, function ():void { s_c.connect(client_spec); }, s_r, function ():void { s_r.connect(addr_r.host, addr_r.port); }); proxy_pair.set_name("<" + client_spec.substr(0, 4) + "...," + addr_r.host + ":" + addr_r.port + ">"); return proxy_pair; } throw new ArgumentError("Can't parse client spec \"" + client_spec + "\"."); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private static function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.text.TextFormat; import flash.text.TextField; import flash.utils.getTimer; class Badge extends flash.display.Sprite { /* Number of proxy pairs currently connected. */ private var num_proxy_pairs:int = 0; /* Number of proxy pairs ever connected. */ private var total_proxy_pairs:int = 0; [Embed(source="badge.png")] private var BadgeImage:Class; private var tot_client_count_tf:TextField; private var tot_client_count_fmt:TextFormat; private var cur_client_count_tf:TextField; private var cur_client_count_fmt:TextFormat; public function Badge() { /* Setup client counter for badge. */ tot_client_count_fmt = new TextFormat(); tot_client_count_fmt.color = 0xFFFFFF; tot_client_count_fmt.align = "center"; tot_client_count_fmt.font = "courier-new"; tot_client_count_fmt.bold = true; tot_client_count_fmt.size = 10; tot_client_count_tf = new TextField(); tot_client_count_tf.width = 20; tot_client_count_tf.height = 17; tot_client_count_tf.background = false; tot_client_count_tf.defaultTextFormat = tot_client_count_fmt; tot_client_count_tf.x=47; tot_client_count_tf.y=0; cur_client_count_fmt = new TextFormat(); cur_client_count_fmt.color = 0xFFFFFF; cur_client_count_fmt.align = "center"; cur_client_count_fmt.font = "courier-new"; cur_client_count_fmt.bold = true; cur_client_count_fmt.size = 10; cur_client_count_tf = new TextField(); cur_client_count_tf.width = 20; cur_client_count_tf.height = 17; cur_client_count_tf.background = false; cur_client_count_tf.defaultTextFormat = cur_client_count_fmt; cur_client_count_tf.x=47; cur_client_count_tf.y=6; addChild(new BadgeImage()); addChild(tot_client_count_tf); addChild(cur_client_count_tf); /* Update the client counter on badge. */ update_client_count(); } public function proxy_begin():void { num_proxy_pairs++; total_proxy_pairs++; update_client_count(); } public function proxy_end():void { num_proxy_pairs--; update_client_count(); } private function update_client_count():void { /* Update total client count. */ if (String(total_proxy_pairs).length == 1) tot_client_count_tf.text = "0" + String(total_proxy_pairs); else tot_client_count_tf.text = String(total_proxy_pairs); /* Update current client count. */ cur_client_count_tf.text = ""; for(var i:Number = 0; i < num_proxy_pairs; i++) cur_client_count_tf.appendText("."); } } class RateLimit { public function RateLimit() { } public function update(n:Number):Boolean { return true; } public function when():Number { return 0.0; } public function is_limited():Boolean { return false; } } class RateUnlimit extends RateLimit { public function RateUnlimit() { } public override function update(n:Number):Boolean { return true; } public override function when():Number { return 0.0; } public override function is_limited():Boolean { return false; } } class BucketRateLimit extends RateLimit { private var amount:Number; private var capacity:Number; private var time:Number; private var last_update:uint; public function BucketRateLimit(capacity:Number, time:Number) { this.amount = 0.0; /* capacity / time is the rate we are aiming for. */ this.capacity = capacity; this.time = time; this.last_update = getTimer(); } private function age():void { var now:uint; var delta:Number; now = getTimer(); delta = (now - last_update) / 1000.0; last_update = now; amount -= delta * capacity / time; if (amount < 0.0) amount = 0.0; } public override function update(n:Number):Boolean { age(); amount += n; return amount <= capacity; } public override function when():Number { age(); return (amount - capacity) / (capacity / time); } public override function is_limited():Boolean { age(); return amount > capacity; } }
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.external.ExternalInterface; import flash.text.TextField; import flash.text.TextFormat; import flash.net.Socket; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.utils.setTimeout; public class swfcat extends Sprite { private const RTMFP_URL:String = "rtmfp://tor-facilitator.bamsoftware.com"; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "tor-facilitator.bamsoftware.com", port: 9002 }; /* Local Tor client to use in case of RTMFP connection. */ private const DEFAULT_LOCAL_TOR_CLIENT_ADDR:Object = { host: "127.0.0.1", port: 9002 }; private const MAX_NUM_PROXY_PAIRS:uint = 100; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; // Bytes per second. Set to undefined to disable limit. public static const RATE_LIMIT:Number = undefined; // Seconds. private static const RATE_LIMIT_HISTORY:Number = 5.0; /* TextField for debug output. */ private var output_text:TextField; /* UI shown when debug is off. */ private var badge:Badge; /* Proxy pairs currently connected (up to MAX_NUM_PROXY_PAIRS). */ private var proxy_pairs:Array; private var fac_addr:Object; private var local_addr:Object; public var debug:Boolean; public var rate_limit:RateLimit; public function puts(s:String):void { if (output_text) { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } } public function swfcat() { // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; badge = new Badge(); proxy_pairs = []; if (RATE_LIMIT) rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY); else rate_limit = new RateUnlimit(); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { debug = this.loaderInfo.parameters["debug"]; if (debug || this.loaderInfo.parameters["client"]) { output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; addChild(output_text); } else { addChild(badge); } puts("Parameters loaded."); fac_addr = get_param_addr("facilitator", DEFAULT_FACILITATOR_ADDR); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } local_addr = get_param_addr("local", DEFAULT_LOCAL_TOR_CLIENT_ADDR); if (!local_addr) { puts("Error: Local spec must be in the form \"host:port\"."); return; } if (this.loaderInfo.parameters["client"]) client_main(); else proxy_main(); } /* Get an address structure from the given movie parameter, or the given default. Returns null on error. */ private function get_param_addr(param:String, default_addr:Object):Object { var spec:String; spec = this.loaderInfo.parameters[param]; if (spec) return parse_addr_spec(spec); else return default_addr; } /* The main logic begins here, after start-up issues are taken care of. */ private function proxy_main():void { var fac_url:String; var loader:URLLoader; if (proxy_pairs.length >= MAX_NUM_PROXY_PAIRS) { setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL); return; } loader = new URLLoader(); /* Get the x-www-form-urlencoded values. */ loader.dataFormat = URLLoaderDataFormat.VARIABLES; loader.addEventListener(Event.COMPLETE, fac_complete); loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); }); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); }); fac_url = "http://" + encodeURIComponent(fac_addr.host) + ":" + encodeURIComponent(fac_addr.port) + "/"; puts("Facilitator: connecting to " + fac_url + "."); loader.load(new URLRequest(fac_url)); } private function fac_complete(e:Event):void { var loader:URLLoader; var client_spec:String; var relay_spec:String; var proxy_pair:Object; setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL); loader = e.target as URLLoader; client_spec = loader.data.client; if (client_spec == "") { puts("No clients."); return; } else if (!client_spec) { puts("Error: missing \"client\" in response."); return; } relay_spec = loader.data.relay; if (!relay_spec) { puts("Error: missing \"relay\" in response."); return; } puts("Facilitator: got client:\"" + client_spec + "\" " + "relay:\"" + relay_spec + "\"."); try { proxy_pair = make_proxy_pair(client_spec, relay_spec); } catch (e:ArgumentError) { puts("Error: " + e); return; } proxy_pairs.push(proxy_pair); proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void { proxy_pair.log("Complete."); /* Delete from the list of active proxy pairs. */ proxy_pairs.splice(proxy_pairs.indexOf(proxy_pair), 1); badge.proxy_end(); }); proxy_pair.connect(); badge.proxy_begin(); } private function client_main():void { var rs:RTMFPSocket; puts("Making RTMFP socket."); rs = new RTMFPSocket(RTMFP_URL); rs.addEventListener(Event.COMPLETE, function (e:Event):void { puts("Got RTMFP id " + rs.id); register(rs); }); rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, client_accept); rs.listen(); } private function client_accept(e:Event):void { var rs:RTMFPSocket; var s_t:Socket; var proxy_pair:ProxyPair; rs = e.target as RTMFPSocket; s_t = new Socket(); puts("Got RTMFP connection from " + rs.peer_id); proxy_pair = new ProxyPair(this, rs, function ():void { /* Do nothing; already connected. */ }, s_t, function ():void { s_t.connect(local_addr.host, local_addr.port); }); proxy_pair.connect(); } private function register(rs:RTMFPSocket):void { var fac_url:String; var loader:URLLoader; var request:URLRequest; loader = new URLLoader(); loader.addEventListener(Event.COMPLETE, function (e:Event):void { puts("Facilitator: registered."); }); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); rs.close(); }); loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); rs.close(); }); fac_url = "http://" + encodeURIComponent(fac_addr.host) + ":" + encodeURIComponent(fac_addr.port) + "/"; request = new URLRequest(fac_url); request.method = URLRequestMethod.POST; request.data = new URLVariables(); request.data["client"] = rs.id; puts("Facilitator: connecting to " + fac_url + "."); loader.load(request); } private function make_proxy_pair(client_spec:String, relay_spec:String):ProxyPair { var proxy_pair:ProxyPair; var addr_c:Object; var addr_r:Object; var s_c:*; var s_r:Socket; addr_r = swfcat.parse_addr_spec(relay_spec); if (!addr_r) throw new ArgumentError("Relay spec must be in the form \"host:port\"."); addr_c = swfcat.parse_addr_spec(client_spec); if (addr_c) { s_c = new Socket(); s_r = new Socket(); proxy_pair = new ProxyPair(this, s_c, function ():void { s_c.connect(addr_c.host, addr_c.port); }, s_r, function ():void { s_r.connect(addr_r.host, addr_r.port); }); proxy_pair.set_name("<" + addr_c.host + ":" + addr_c.port + "," + addr_r.host + ":" + addr_r.port + ">"); return proxy_pair; } if (client_spec.match(/^[0-9A-Fa-f]{64}$/)) { s_c = new RTMFPSocket(RTMFP_URL); s_r = new Socket(); proxy_pair = new ProxyPair(this, s_c, function ():void { s_c.connect(client_spec); }, s_r, function ():void { s_r.connect(addr_r.host, addr_r.port); }); proxy_pair.set_name("<" + client_spec.substr(0, 4) + "...," + addr_r.host + ":" + addr_r.port + ">"); return proxy_pair; } throw new ArgumentError("Can't parse client spec \"" + client_spec + "\"."); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private static function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.events.MouseEvent; import flash.net.navigateToURL; import flash.net.URLRequest; import flash.text.TextFormat; import flash.text.TextField; import flash.utils.getTimer; class Badge extends flash.display.Sprite { private const FLASHPROXY_INFO_URL:String = "https://crypto.stanford.edu/flashproxy/"; /* Number of proxy pairs currently connected. */ private var num_proxy_pairs:int = 0; /* Number of proxy pairs ever connected. */ private var total_proxy_pairs:int = 0; [Embed(source="badge.png")] private var BadgeImage:Class; private var tot_client_count_tf:TextField; private var tot_client_count_fmt:TextFormat; private var cur_client_count_tf:TextField; private var cur_client_count_fmt:TextFormat; public function Badge() { /* Setup client counter for badge. */ tot_client_count_fmt = new TextFormat(); tot_client_count_fmt.color = 0xFFFFFF; tot_client_count_fmt.align = "center"; tot_client_count_fmt.font = "courier-new"; tot_client_count_fmt.bold = true; tot_client_count_fmt.size = 10; tot_client_count_tf = new TextField(); tot_client_count_tf.width = 20; tot_client_count_tf.height = 17; tot_client_count_tf.background = false; tot_client_count_tf.defaultTextFormat = tot_client_count_fmt; tot_client_count_tf.x=47; tot_client_count_tf.y=0; cur_client_count_fmt = new TextFormat(); cur_client_count_fmt.color = 0xFFFFFF; cur_client_count_fmt.align = "center"; cur_client_count_fmt.font = "courier-new"; cur_client_count_fmt.bold = true; cur_client_count_fmt.size = 10; cur_client_count_tf = new TextField(); cur_client_count_tf.width = 20; cur_client_count_tf.height = 17; cur_client_count_tf.background = false; cur_client_count_tf.defaultTextFormat = cur_client_count_fmt; cur_client_count_tf.x=47; cur_client_count_tf.y=6; addChild(new BadgeImage()); addChild(tot_client_count_tf); addChild(cur_client_count_tf); /* Update the client counter on badge. */ update_client_count(); addEventListener(MouseEvent.CLICK, mouse_clicked); } public function proxy_begin():void { num_proxy_pairs++; total_proxy_pairs++; update_client_count(); } public function proxy_end():void { num_proxy_pairs--; update_client_count(); } private function update_client_count():void { /* Update total client count. */ if (String(total_proxy_pairs).length == 1) tot_client_count_tf.text = "0" + String(total_proxy_pairs); else tot_client_count_tf.text = String(total_proxy_pairs); /* Update current client count. */ cur_client_count_tf.text = ""; for(var i:Number = 0; i < num_proxy_pairs; i++) cur_client_count_tf.appendText("."); } /* Show a web page with detailed information when the badge is clicked. */ private function mouse_clicked(e:MouseEvent):void { try { navigateToURL(new URLRequest(FLASHPROXY_INFO_URL)); } catch (err:Error) { } } } class RateLimit { public function RateLimit() { } public function update(n:Number):Boolean { return true; } public function when():Number { return 0.0; } public function is_limited():Boolean { return false; } } class RateUnlimit extends RateLimit { public function RateUnlimit() { } public override function update(n:Number):Boolean { return true; } public override function when():Number { return 0.0; } public override function is_limited():Boolean { return false; } } class BucketRateLimit extends RateLimit { private var amount:Number; private var capacity:Number; private var time:Number; private var last_update:uint; public function BucketRateLimit(capacity:Number, time:Number) { this.amount = 0.0; /* capacity / time is the rate we are aiming for. */ this.capacity = capacity; this.time = time; this.last_update = getTimer(); } private function age():void { var now:uint; var delta:Number; now = getTimer(); delta = (now - last_update) / 1000.0; last_update = now; amount -= delta * capacity / time; if (amount < 0.0) amount = 0.0; } public override function update(n:Number):Boolean { age(); amount += n; return amount <= capacity; } public override function when():Number { age(); return (amount - capacity) / (capacity / time); } public override function is_limited():Boolean { age(); return amount > capacity; } }
Make the badge clickable.
Make the badge clickable.
ActionScript
mit
glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy
98c1e816c57d5899bcfe658eadcb291ef1d29f0a
src/aerys/minko/scene/node/light/PointLight.as
src/aerys/minko/scene/node/light/PointLight.as
package aerys.minko.scene.node.light { import aerys.minko.ns.minko_scene; import aerys.minko.render.material.phong.PhongProperties; import aerys.minko.render.resource.texture.CubeTextureResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.scene.controller.light.PointLightController; import aerys.minko.scene.node.AbstractSceneNode; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.ShadowMappingType; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; use namespace minko_scene; /** * * @author Romain Gilliotte * @author Jean-Marc Le Roux * */ public class PointLight extends AbstractLight { public static const LIGHT_TYPE : uint = 2; private static const TMP_VECTOR : Vector4 = new Vector4(); private var _shadowMapSize : uint; public function get diffuse() : Number { return lightData.getLightProperty('diffuse') as Number; } public function set diffuse(v : Number) : void { lightData.setLightProperty('diffuse', v); if (lightData.getLightProperty('diffuseEnabled') != (v != 0)) lightData.setLightProperty('diffuseEnabled', v != 0); } public function get specular() : Number { return lightData.getLightProperty('specular') as Number; } public function set specular(v : Number) : void { lightData.setLightProperty('specular', v); if (lightData.getLightProperty('specularEnabled') != (v != 0)) lightData.setLightProperty('specularEnabled', v != 0); } public function get shininess() : Number { return lightData.getLightProperty('shininess') as Number; } public function set shininess(v : Number) : void { lightData.setLightProperty('shininess', v); } public function get attenuationDistance() : Number { return lightData.getLightProperty('attenuationDistance') as Number; } public function set attenuationDistance(v : Number) : void { lightData.setLightProperty('attenuationDistance', v); if (lightData.getLightProperty('attenuationEnabled') != (v != 0)) lightData.setLightProperty('attenuationEnabled', v != 0); } public function get shadowMapSize() : uint { return lightData.getLightProperty('shadowMapSize'); } public function set shadowMapSize(v : uint) : void { lightData.setLightProperty('shadowMapSize', v); } public function get shadowZNear() : Number { return lightData.getLightProperty('shadowZNear'); } public function set shadowZNear(v : Number) : void { lightData.setLightProperty('shadowZNear', v); } public function get shadowZFar() : Number { return lightData.getLightProperty('shadowZFar'); } public function set shadowZFar(v : Number) : void { lightData.setLightProperty('shadowZFar', v); } public function get shadowCastingType() : uint { return lightData.getProperty('shadowCastingType'); } public function set shadowCastingType(value : uint) : void { lightData.setLightProperty('shadowCastingType', value); } public function get shadowBias() : Number { return lightData.getLightProperty(PhongProperties.SHADOW_BIAS); } public function set shadowBias(value : Number) : void { lightData.setLightProperty(PhongProperties.SHADOW_BIAS, value); } public function PointLight(color : uint = 0xFFFFFFFF, diffuse : Number = .6, specular : Number = .8, shininess : Number = 64, attenuationDistance : Number = 0, emissionMask : uint = 0x1, shadowCastingType : uint = 0, shadowMapSize : uint = 512, shadowZNear : Number = 0.1, shadowZFar : Number = 1000., shadowBias : uint = 1. / 256. / 256.) { _shadowMapSize = shadowMapSize; super( new PointLightController(), LIGHT_TYPE, color, emissionMask ); this.diffuse = diffuse; this.specular = specular; this.shininess = shininess; this.attenuationDistance = attenuationDistance; this.shadowCastingType = shadowCastingType; this.shadowZNear = shadowZNear; this.shadowZFar = shadowZFar; this.shadowBias = shadowBias; } override minko_scene function cloneNode() : AbstractSceneNode { var light : PointLight = new PointLight( color, diffuse, specular, shininess, attenuationDistance, emissionMask, shadowCastingType, shadowMapSize, shadowZFar, shadowZNear, shadowBias ); light.name = this.name; light.transform.copyFrom(this.transform); return light; } } }
package aerys.minko.scene.node.light { import aerys.minko.ns.minko_scene; import aerys.minko.render.material.phong.PhongProperties; import aerys.minko.render.resource.texture.CubeTextureResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.scene.controller.light.PointLightController; import aerys.minko.scene.node.AbstractSceneNode; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.ShadowMappingType; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; use namespace minko_scene; /** * * @author Romain Gilliotte * @author Jean-Marc Le Roux * */ public class PointLight extends AbstractLight { public static const LIGHT_TYPE : uint = 2; private static const TMP_VECTOR : Vector4 = new Vector4(); public function get diffuse() : Number { return lightData.getLightProperty('diffuse') as Number; } public function set diffuse(v : Number) : void { lightData.setLightProperty('diffuse', v); if (lightData.getLightProperty('diffuseEnabled') != (v != 0)) lightData.setLightProperty('diffuseEnabled', v != 0); } public function get specular() : Number { return lightData.getLightProperty('specular') as Number; } public function set specular(v : Number) : void { lightData.setLightProperty('specular', v); if (lightData.getLightProperty('specularEnabled') != (v != 0)) lightData.setLightProperty('specularEnabled', v != 0); } public function get shininess() : Number { return lightData.getLightProperty('shininess') as Number; } public function set shininess(v : Number) : void { lightData.setLightProperty('shininess', v); } public function get attenuationDistance() : Number { return lightData.getLightProperty('attenuationDistance') as Number; } public function set attenuationDistance(v : Number) : void { lightData.setLightProperty('attenuationDistance', v); if (lightData.getLightProperty('attenuationEnabled') != (v != 0)) lightData.setLightProperty('attenuationEnabled', v != 0); } public function get shadowMapSize() : uint { return lightData.getLightProperty('shadowMapSize'); } public function set shadowMapSize(v : uint) : void { lightData.setLightProperty('shadowMapSize', v); } public function get shadowZNear() : Number { return lightData.getLightProperty('shadowZNear'); } public function set shadowZNear(v : Number) : void { lightData.setLightProperty('shadowZNear', v); } public function get shadowZFar() : Number { return lightData.getLightProperty('shadowZFar'); } public function set shadowZFar(v : Number) : void { lightData.setLightProperty('shadowZFar', v); } public function get shadowCastingType() : uint { return lightData.getProperty('shadowCastingType'); } public function set shadowCastingType(value : uint) : void { lightData.setLightProperty('shadowCastingType', value); } public function get shadowBias() : Number { return lightData.getLightProperty(PhongProperties.SHADOW_BIAS); } public function set shadowBias(value : Number) : void { lightData.setLightProperty(PhongProperties.SHADOW_BIAS, value); } public function PointLight(color : uint = 0xFFFFFFFF, diffuse : Number = .6, specular : Number = .8, shininess : Number = 64, attenuationDistance : Number = 0, emissionMask : uint = 0x1, shadowCastingType : uint = 0, shadowMapSize : uint = 512, shadowZNear : Number = 0.1, shadowZFar : Number = 1000., shadowBias : uint = 1. / 256. / 256.) { super( new PointLightController(), LIGHT_TYPE, color, emissionMask ); this.diffuse = diffuse; this.specular = specular; this.shininess = shininess; this.attenuationDistance = attenuationDistance; this.shadowCastingType = shadowCastingType; this.shadowMapSize = shadowMapSize; this.shadowZNear = shadowZNear; this.shadowZFar = shadowZFar; this.shadowBias = shadowBias; } override minko_scene function cloneNode() : AbstractSceneNode { var light : PointLight = new PointLight( color, diffuse, specular, shininess, attenuationDistance, emissionMask, shadowCastingType, shadowMapSize, shadowZFar, shadowZNear, shadowBias ); light.name = this.name; light.transform.copyFrom(this.transform); return light; } } }
fix shadowMapSize init in PointLight constructor
fix shadowMapSize init in PointLight constructor
ActionScript
mit
aerys/minko-as3
a5d6afc5ed2f97e328591ca9446b8ac0185a368b
vivified/compiler/test/hello-world.as
vivified/compiler/test/hello-world.as
// makeswf -v 7 -s 200x150 -r 1 -o movie23.swf movie23.as trace ("Hello World!"); loadMovie ("fscommand:quit", "");
// makeswf -v 7 -s 200x150 -r 1 -o hello-world.swf hello-world.as trace ("Hello World!"); loadMovie ("fscommand:quit", "");
fix comment
fix comment
ActionScript
lgpl-2.1
mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec
106f8df371de3f4947109375ffdf0b564859e476
src/flexlib/containers/WindowShade.as
src/flexlib/containers/WindowShade.as
/* Copyright (c) 2007 FlexLib Contributors. See: http://code.google.com/p/flexlib/wiki/ProjectContributors 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 flexlib.containers { import flash.events.MouseEvent; import mx.controls.Button; import mx.core.EdgeMetrics; import mx.core.IFactory; import mx.core.LayoutContainer; import mx.core.ScrollPolicy; import mx.effects.Resize; import mx.styles.CSSStyleDeclaration; import mx.styles.StyleManager; import mx.utils.StringUtil; /** * This is the icon displayed on the headerButton when the WindowShade is in the open state. */ [Style(name="openIcon", type="Class", inherit="no")] /** * This is the icon displayed on the headerButton when the WindowShade is in the closed state. */ [Style(name="closeIcon", type="Class", inherit="no")] /** * The duration of the WindowShade opening transition, in milliseconds. The value 0 specifies no transition. * * @default 250 */ [Style(name="openDuration", type="Number", format="Time", inherit="no")] /** * The duration of the WindowShade closing transition, in milliseconds. The value 0 specifies no transition. * * @default 250 */ [Style(name="closeDuration", type="Number", format="Time", inherit="no")] /** * The class from which the headerButton will be instantiated. Must be mx.controls.Button * or a subclass. * * @default mx.controls.Button */ [Style(name="headerClass", type="Class", inherit="no")] /** * Name of CSS style declaration that specifies styles for the headerButton. */ [Style(name="headerStyleName", type="String", inherit="no")] /** * Alignment of text on the headerButton. The value set for this style is used as * the textAlign style on the headerButton. Valid values are "left", "center" and "right". * * @default "right" */ [Style(name="headerTextAlign", type="String", inherit="no")] /** * If true, the value of the headerButton's <code>toggle</code> property will be set to true; * otherwise the <code>toggle</code> property will be left in its default state. * * @default false */ [Style(name="toggleHeader", type="Boolean", inherit="no")] /** * This control displays a button, which when clicked, will cause a panel to "unroll" beneath * it like a windowshade being pulled down; or if the panel is already displayed it * will be "rolled up" like a windowshade being rolled up. When multiple WindowShades are stacked * in a VBox, the result will be similar to an mx.containers.Accordian container, except that multiple * WindowShades can be opened simultaneously whereas an Accordian acts like a tab navigator, with only * one panel visible at a time. */ public class WindowShade extends LayoutContainer { [Embed (source="../assets/assets.swf", symbol="right_arrow")] private static var DEFAULT_CLOSE_ICON:Class; [Embed (source="../assets/assets.swf", symbol="down_arrow")] private static var DEFAULT_OPEN_ICON:Class; private static var styleDefaults:Object = { openDuration:250 ,closeDuration:250 ,paddingTop:10 ,headerClass:Button ,headerTextAlign:"left" ,toggleHeader:false ,headerStyleName:null ,closeIcon:DEFAULT_CLOSE_ICON ,openIcon:DEFAULT_OPEN_ICON }; private static var classConstructed:Boolean = constructClass(); private static function constructClass():Boolean { var css:CSSStyleDeclaration = StyleManager.getStyleDeclaration("WindowShade") var changed:Boolean = false; if(!css) { // If there is no CSS definition for WindowShade, // then create one and set the default value. css = new CSSStyleDeclaration(); changed = true; } // make sure we have a valid values for each style. If not, set the defaults. for(var styleProp:String in styleDefaults) { if(!StyleManager.isValidStyleValue(css.getStyle(styleProp))) { css.setStyle(styleProp, styleDefaults[styleProp]); changed = true; } } if(changed) { StyleManager.setStyleDeclaration("WindowShade", css, true); } return true; } /** * @private * A reference to the Button that will be used for the header. Must always be a Button or subclass of Button. */ private var _headerButton:Button = null; private var headerChanged:Boolean; /** * @private * The header renderer factory that will get used to create the header. */ private var _headerRenderer:IFactory; /** * To control the header used on the WindowShade component you can either set the <code>headerClass</code> or the * <code>headerRenderer</code>. The <code>headerRenderer</code> works similar to the itemRenderer of a List control. * You can set this using MXML using any Button control. This would let you customize things like button skin. You could * even combine this with the CanvasButton component to make complex headers. */ public function set headerRenderer(value:IFactory):void { _headerRenderer = value; headerChanged = true; invalidateProperties(); } public function get headerRenderer():IFactory { return _headerRenderer; } /** * @private * Boolean dirty flag to let us know if we need to change the icon in the commitProperties method. */ private var _openedChanged:Boolean = false; public function WindowShade() { super(); //default scroll policies are off this.verticalScrollPolicy = ScrollPolicy.OFF; this.horizontalScrollPolicy = ScrollPolicy.OFF; } protected function createOrReplaceHeaderButton():void { if(_headerButton) { _headerButton.removeEventListener(MouseEvent.CLICK, headerButton_clickHandler); if(rawChildren.contains(_headerButton)) { rawChildren.removeChild(_headerButton); } } if(_headerRenderer) { _headerButton = _headerRenderer.newInstance() as Button; } else { var headerClass:Class = getStyle("headerClass"); _headerButton = new headerClass(); } applyHeaderButtonStyles(_headerButton); _headerButton.addEventListener(MouseEvent.CLICK, headerButton_clickHandler); rawChildren.addChild(_headerButton); } protected function applyHeaderButtonStyles(button:Button):void { button.setStyle("textAlign", getStyle("headerTextAlign")); var headerStyleName:String = getStyle("headerStyleName"); if(headerStyleName) { headerStyleName = StringUtil.trim(headerStyleName); button.styleName = headerStyleName; } button.toggle = getStyle("toggleHeader"); button.label = label; if(_opened) { button.setStyle('icon', getStyle("openIcon")); } else { button.setStyle('icon', getStyle("closeIcon")); } if(button.toggle) { button.selected = _opened; } } /** * @private */ override public function set label(value:String):void { super.label = value; if(_headerButton) _headerButton.label = value; } /** * @private */ private var _opened:Boolean = true; /** * Sets or gets the state of this WindowShade, either opened (true) or closed (false). */ public function get opened():Boolean { return _opened; } private var _headerLocation:String = "top"; [Bindable] [Inspectable(enumeration="top,bottom", defaultValue="top")] /** * Specifies where the header button is placed relative tot he content of this WindowShade. Possible * values are <code>top</code> and <code>bottom</code>. */ public function set headerLocation(value:String):void { _headerLocation = value; invalidateSize(); invalidateDisplayList(); } public function get headerLocation():String { return _headerLocation; } /** * @private */ [Bindable] public function set opened(value:Boolean):void { var old:Boolean = _opened; _opened = value; _openedChanged = _openedChanged || old != _opened; if(_openedChanged && initialized) { measure(); runResizeEffect(); invalidateProperties(); } } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); if(styleProp == "headerClass") { headerChanged = true; invalidateProperties(); } else if(styleProp == "headerStyleName" || styleProp == "headerTextAlign" || styleProp == "toggleHeader" || styleProp == "openIcon" || styleProp == "closeIcon") { applyHeaderButtonStyles(_headerButton); } invalidateDisplayList(); } /** * @private */ override protected function createChildren():void { super.createChildren(); createOrReplaceHeaderButton(); } /** * @private */ override protected function commitProperties():void { super.commitProperties(); if(headerChanged) { createOrReplaceHeaderButton(); headerChanged = false; } if(_openedChanged) { if(_opened) { _headerButton.setStyle('icon', getStyle("openIcon")); } else { _headerButton.setStyle('icon', getStyle("closeIcon")); } _openedChanged = false; } } /** * @private */ override protected function updateDisplayList(w:Number, h:Number):void { super.updateDisplayList(w, h); if(_headerLocation == "top") { _headerButton.move(0,0); } else if(_headerLocation == "bottom") { _headerButton.move(0,h - _headerButton.getExplicitOrMeasuredHeight()); } _headerButton.setActualSize(w, _headerButton.getExplicitOrMeasuredHeight()); } /** * @private */ private var _viewMetrics:EdgeMetrics; override public function get viewMetrics():EdgeMetrics { // The getViewMetrics function needs to return its own object. // Rather than allocating a new one each time, we'll allocate // one once and then hold a pointer to it. if (!_viewMetrics) _viewMetrics = new EdgeMetrics(0, 0, 0, 0); var vm:EdgeMetrics = _viewMetrics; var o:EdgeMetrics = super.viewMetrics; vm.left = o.left; vm.top = o.top; vm.right = o.right; vm.bottom = o.bottom; var hHeight:Number = _headerButton.getExplicitOrMeasuredHeight(); if (!isNaN(hHeight)) { if(_headerLocation == "top") { vm.top += hHeight; } else if(_headerLocation == "bottom") { vm.bottom += hHeight; } } return vm; } /** * @private */ override protected function measure():void { super.measure(); if(_opened) { //if this WindowShade is opened then we have to include the height of the header button //measuredHeight += _headerButton.getExplicitOrMeasuredHeight(); } else { //if the WindowShade is closed then the height is only the height of the header button measuredHeight = _headerButton.getExplicitOrMeasuredHeight(); } } /** * @private */ private var resize:Resize; /** * @private */ protected function runResizeEffect():void { if(resize && resize.isPlaying) { resize.end(); } var duration:Number = _opened ? getStyle("openDuration") : getStyle("closeDuration"); if(duration == 0) { this.setActualSize(getExplicitOrMeasuredWidth(), measuredHeight); invalidateSize(); invalidateDisplayList(); return; } resize = new Resize(this); resize.heightTo = Math.min(maxHeight, measuredHeight); resize.duration = duration; resize.play(); } /** * @private */ protected function headerButton_clickHandler(event:MouseEvent):void { opened = !_opened; } } }
/* Copyright (c) 2007 FlexLib Contributors. See: http://code.google.com/p/flexlib/wiki/ProjectContributors 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 flexlib.containers { import flash.events.MouseEvent; import mx.controls.Button; import mx.core.EdgeMetrics; import mx.core.IFactory; import mx.core.LayoutContainer; import mx.core.ScrollPolicy; import mx.effects.Resize; import mx.effects.effectClasses.ResizeInstance; import mx.events.EffectEvent; import mx.styles.CSSStyleDeclaration; import mx.styles.StyleManager; import mx.utils.StringUtil; /** * This is the icon displayed on the headerButton when the WindowShade is in the open state. */ [Style(name="openIcon", type="Class", inherit="no")] /** * This is the icon displayed on the headerButton when the WindowShade is in the closed state. */ [Style(name="closeIcon", type="Class", inherit="no")] /** * The duration of the WindowShade opening transition, in milliseconds. The value 0 specifies no transition. * * @default 250 */ [Style(name="openDuration", type="Number", format="Time", inherit="no")] /** * The duration of the WindowShade closing transition, in milliseconds. The value 0 specifies no transition. * * @default 250 */ [Style(name="closeDuration", type="Number", format="Time", inherit="no")] /** * The class from which the headerButton will be instantiated. Must be mx.controls.Button * or a subclass. * * @default mx.controls.Button */ [Style(name="headerClass", type="Class", inherit="no")] /** * Name of CSS style declaration that specifies styles for the headerButton. */ [Style(name="headerStyleName", type="String", inherit="no")] /** * Alignment of text on the headerButton. The value set for this style is used as * the textAlign style on the headerButton. Valid values are "left", "center" and "right". * * @default "right" */ [Style(name="headerTextAlign", type="String", inherit="no")] /** * If true, the value of the headerButton's <code>toggle</code> property will be set to true; * otherwise the <code>toggle</code> property will be left in its default state. * * @default false */ [Style(name="toggleHeader", type="Boolean", inherit="no")] /** * This control displays a button, which when clicked, will cause a panel to "unroll" beneath * it like a windowshade being pulled down; or if the panel is already displayed it * will be "rolled up" like a windowshade being rolled up. When multiple WindowShades are stacked * in a VBox, the result will be similar to an mx.containers.Accordian container, except that multiple * WindowShades can be opened simultaneously whereas an Accordian acts like a tab navigator, with only * one panel visible at a time. */ public class WindowShade extends LayoutContainer { [Embed (source="../assets/assets.swf", symbol="right_arrow")] private static var DEFAULT_CLOSE_ICON:Class; [Embed (source="../assets/assets.swf", symbol="down_arrow")] private static var DEFAULT_OPEN_ICON:Class; private static var styleDefaults:Object = { openDuration:250 ,closeDuration:250 ,paddingTop:10 ,headerClass:Button ,headerTextAlign:"left" ,toggleHeader:false ,headerStyleName:null ,closeIcon:DEFAULT_CLOSE_ICON ,openIcon:DEFAULT_OPEN_ICON }; private static var classConstructed:Boolean = constructClass(); private static function constructClass():Boolean { var css:CSSStyleDeclaration = StyleManager.getStyleDeclaration("WindowShade") var changed:Boolean = false; if(!css) { // If there is no CSS definition for WindowShade, // then create one and set the default value. css = new CSSStyleDeclaration(); changed = true; } // make sure we have a valid values for each style. If not, set the defaults. for(var styleProp:String in styleDefaults) { if(!StyleManager.isValidStyleValue(css.getStyle(styleProp))) { css.setStyle(styleProp, styleDefaults[styleProp]); changed = true; } } if(changed) { StyleManager.setStyleDeclaration("WindowShade", css, true); } return true; } /** * @private * A reference to the Button that will be used for the header. Must always be a Button or subclass of Button. */ private var _headerButton:Button = null; private var headerChanged:Boolean; /** * @private * The header renderer factory that will get used to create the header. */ private var _headerRenderer:IFactory; /** * To control the header used on the WindowShade component you can either set the <code>headerClass</code> or the * <code>headerRenderer</code>. The <code>headerRenderer</code> works similar to the itemRenderer of a List control. * You can set this using MXML using any Button control. This would let you customize things like button skin. You could * even combine this with the CanvasButton component to make complex headers. */ public function set headerRenderer(value:IFactory):void { _headerRenderer = value; headerChanged = true; invalidateProperties(); } public function get headerRenderer():IFactory { return _headerRenderer; } /** * @private * Boolean dirty flag to let us know if we need to change the icon in the commitProperties method. */ private var _openedChanged:Boolean = false; public function WindowShade() { super(); //default scroll policies are off this.verticalScrollPolicy = ScrollPolicy.OFF; this.horizontalScrollPolicy = ScrollPolicy.OFF; addEventListener(EffectEvent.EFFECT_END, onEffectEnd); } protected function createOrReplaceHeaderButton():void { if(_headerButton) { _headerButton.removeEventListener(MouseEvent.CLICK, headerButton_clickHandler); if(rawChildren.contains(_headerButton)) { rawChildren.removeChild(_headerButton); } } if(_headerRenderer) { _headerButton = _headerRenderer.newInstance() as Button; } else { var headerClass:Class = getStyle("headerClass"); _headerButton = new headerClass(); } applyHeaderButtonStyles(_headerButton); _headerButton.addEventListener(MouseEvent.CLICK, headerButton_clickHandler); rawChildren.addChild(_headerButton); } protected function applyHeaderButtonStyles(button:Button):void { button.setStyle("textAlign", getStyle("headerTextAlign")); var headerStyleName:String = getStyle("headerStyleName"); if(headerStyleName) { headerStyleName = StringUtil.trim(headerStyleName); button.styleName = headerStyleName; } button.toggle = getStyle("toggleHeader"); button.label = label; if(_opened) { button.setStyle('icon', getStyle("openIcon")); } else { button.setStyle('icon', getStyle("closeIcon")); } if(button.toggle) { button.selected = _opened; } } /** * @private */ override public function set label(value:String):void { super.label = value; if(_headerButton) _headerButton.label = value; } /** * @private */ private var _opened:Boolean = true; /** * Sets or gets the state of this WindowShade, either opened (true) or closed (false). */ public function get opened():Boolean { return _opened; } private var _headerLocation:String = "top"; [Bindable] [Inspectable(enumeration="top,bottom", defaultValue="top")] /** * Specifies where the header button is placed relative tot he content of this WindowShade. Possible * values are <code>top</code> and <code>bottom</code>. */ public function set headerLocation(value:String):void { _headerLocation = value; invalidateSize(); invalidateDisplayList(); } public function get headerLocation():String { return _headerLocation; } /** * @private */ [Bindable] public function set opened(value:Boolean):void { var old:Boolean = _opened; _opened = value; _openedChanged = _openedChanged || old != _opened; if(_openedChanged && initialized) { measure(); runResizeEffect(); invalidateProperties(); } } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); if(styleProp == "headerClass") { headerChanged = true; invalidateProperties(); } else if(styleProp == "headerStyleName" || styleProp == "headerTextAlign" || styleProp == "toggleHeader" || styleProp == "openIcon" || styleProp == "closeIcon") { applyHeaderButtonStyles(_headerButton); } invalidateDisplayList(); } /** * @private */ override protected function createChildren():void { super.createChildren(); createOrReplaceHeaderButton(); } /** * @private */ override protected function commitProperties():void { super.commitProperties(); if(headerChanged) { createOrReplaceHeaderButton(); headerChanged = false; } if(_openedChanged) { if(_opened) { _headerButton.setStyle('icon', getStyle("openIcon")); } else { _headerButton.setStyle('icon', getStyle("closeIcon")); } _openedChanged = false; } } /** * @private */ override protected function updateDisplayList(w:Number, h:Number):void { super.updateDisplayList(w, h); if(_headerLocation == "top") { _headerButton.move(0,0); } else if(_headerLocation == "bottom") { _headerButton.move(0,h - _headerButton.getExplicitOrMeasuredHeight()); } _headerButton.setActualSize(w, _headerButton.getExplicitOrMeasuredHeight()); } /** * @private */ private var _viewMetrics:EdgeMetrics; override public function get viewMetrics():EdgeMetrics { // The getViewMetrics function needs to return its own object. // Rather than allocating a new one each time, we'll allocate // one once and then hold a pointer to it. if (!_viewMetrics) _viewMetrics = new EdgeMetrics(0, 0, 0, 0); var vm:EdgeMetrics = _viewMetrics; var o:EdgeMetrics = super.viewMetrics; vm.left = o.left; vm.top = o.top; vm.right = o.right; vm.bottom = o.bottom; var hHeight:Number = _headerButton.getExplicitOrMeasuredHeight(); if (!isNaN(hHeight)) { if(_headerLocation == "top") { vm.top += hHeight; } else if(_headerLocation == "bottom") { vm.bottom += hHeight; } } return vm; } /** * @private */ override protected function measure():void { super.measure(); if(_opened) { //if this WindowShade is opened then we have to include the height of the header button //measuredHeight += _headerButton.getExplicitOrMeasuredHeight(); } else { //if the WindowShade is closed then the height is only the height of the header button measuredHeight = _headerButton.getExplicitOrMeasuredHeight(); } } /** * @private */ private var resize:Resize; /** * @private */ private var resizeInstance:ResizeInstance; /** * @private */ private var resetExplicitHeight:Boolean; /** * @private */ protected function runResizeEffect():void { if(resize && resize.isPlaying) { // before the call to end() returns, the onEffectEnd method will have been called // for the currently playing resize. resize.end(); } var duration:Number = _opened ? getStyle("openDuration") : getStyle("closeDuration"); if(duration == 0) { this.setActualSize(getExplicitOrMeasuredWidth(), measuredHeight); invalidateSize(); invalidateDisplayList(); return; } resize = new Resize(this); // If this WindowShade currently has no explicit height set, we want to // restore that state when the resize effect is finished, in the onEffectEnd method. // If it does, then the final height set by the effect will be retained. resetExplicitHeight = isNaN(explicitHeight); resize.heightTo = Math.min(maxHeight, measuredHeight); resize.duration = duration; var instances:Array = resize.play(); if(instances && instances.length) { resizeInstance = instances[0]; } } /** * @private */ protected function onEffectEnd(evt:EffectEvent):void { // Make sure this is our effect ending if(evt.effectInstance == resizeInstance) { if(resetExplicitHeight) explicitHeight = NaN; resizeInstance = null; } } /** * @private */ protected function headerButton_clickHandler(event:MouseEvent):void { opened = !_opened; } } }
Fix for bugs #81 and #91.
Fix for bugs #81 and #91.
ActionScript
mit
Acidburn0zzz/flexlib
207013164e9ff9891ae6038ffc0d27522d54958b
net/flashpunk/utils/Draw.as
net/flashpunk/utils/Draw.as
package net.flashpunk.utils { import flash.display.BitmapData; import flash.display.Graphics; import flash.display.LineScaleMode; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import net.flashpunk.Entity; import net.flashpunk.FP; /** * Static class with access to miscellanious drawing functions. * These functions are not meant to replace Graphic components * for Entities, but rather to help with testing and debugging. */ public class Draw { /** * The blending mode used by Draw functions. This will not * apply to Draw.line(), but will apply to Draw.linePlus(). */ public static var blend:String; /** * Sets the drawing target for Draw functions. * @param target The buffer to draw to. * @param camera The camera offset (use null for none). * @param blend The blend mode to use. */ public static function setTarget(target:BitmapData, camera:Point = null, blend:String = null):void { _target = target; _camera = camera ? camera : FP.zero; Draw.blend = blend; } /** * Resets the drawing target to the default. The same as calling Draw.setTarget(FP.buffer, FP.camera). */ public static function resetTarget():void { _target = FP.buffer; _camera = FP.camera; blend = null; } /** * Draws a pixelated, non-antialiased line. * @param x1 Starting x position. * @param y1 Starting y position. * @param x2 Ending x position. * @param y2 Ending y position. * @param color Color of the line. */ public static function line(x1:int, y1:int, x2:int, y2:int, color:uint = 0xFFFFFF):void { color &= 0xFFFFFF; // get the drawing positions x1 -= _camera.x; y1 -= _camera.y; x2 -= _camera.x; y2 -= _camera.y; // get the drawing difference var screen:BitmapData = _target, X:Number = Math.abs(x2 - x1), Y:Number = Math.abs(y2 - y1), xx:int, yy:int; // draw a single pixel if (X == 0) { if (Y == 0) { screen.setPixel(x1, y1, color); return; } // draw a straight vertical line yy = y2 > y1 ? 1 : -1; while (y1 != y2) { screen.setPixel(x1, y1, color); y1 += yy; } screen.setPixel(x2, y2, color); return; } if (Y == 0) { // draw a straight horizontal line xx = x2 > x1 ? 1 : -1; while (x1 != x2) { screen.setPixel(x1, y1, color); x1 += xx; } screen.setPixel(x2, y2, color); return; } xx = x2 > x1 ? 1 : -1; yy = y2 > y1 ? 1 : -1; var c:Number = 0, slope:Number; if (X > Y) { slope = Y / X; c = .5; while (x1 != x2) { screen.setPixel(x1, y1, color); x1 += xx; c += slope; if (c >= 1) { y1 += yy; c -= 1; } } screen.setPixel(x2, y2, color); return; } else { slope = X / Y; c = .5; while (y1 != y2) { screen.setPixel(x1, y1, color); y1 += yy; c += slope; if (c >= 1) { x1 += xx; c -= 1; } } screen.setPixel(x2, y2, color); return; } } /** * Draws a smooth, antialiased line with optional alpha and thickness. * @param x1 Starting x position. * @param y1 Starting y position. * @param x2 Ending x position. * @param y2 Ending y position. * @param color Color of the line. * @param alpha Alpha of the line. * @param thick The thickness of the line. */ public function linePlus(x1:int, y1:int, x2:int, y2:int, color:uint = 0xFF000000, alpha:Number = 1, thick:Number = 1):void { _graphics.clear(); _graphics.lineStyle(thick, color, alpha, false, LineScaleMode.NONE); _graphics.moveTo(x1 - _camera.x, y1 - _camera.y); _graphics.lineTo(x2 - _camera.x, y2 - _camera.y); _target.draw(FP.sprite, null, null, blend); } /** * Draws a filled rectangle. * @param x X position of the rectangle. * @param y Y position of the rectangle. * @param width Width of the rectangle. * @param height Height of the rectangle. * @param color Color of the rectangle. * @param alpha Alpha of the rectangle. */ public static function rect(x:int, y:int, width:uint, height:uint, color:uint = 0xFFFFFF, alpha:Number = 1):void { if (alpha >= 1 && !blend) { if (color < 0xFF000000) color += 0xFF000000; _rect.x = x - _camera.x; _rect.y = y - _camera.y; _rect.width = width; _rect.height = height; _target.fillRect(_rect, color); } _graphics.clear(); _graphics.beginFill(color, alpha); _graphics.drawRect(x - _camera.x, y - _camera.y, width, height); _target.draw(FP.sprite, null, null, blend); } /** * Draws a filled circle. * @param x X position of the circle's center. * @param y Y position of the circle's center. * @param radius Radius of the circle. * @param color Color of the circle. * @param alpha Alpha of the circle. */ public static function circle(x:int, y:int, radius:Number, color:uint = 0x000000, alpha:Number = 1):void { _graphics.clear(); _graphics.beginFill(color & 0xFFFFFF, alpha); _graphics.drawCircle(x - _camera.x, y - _camera.y, radius); _graphics.endFill(); _target.draw(FP.sprite, null, null, blend); } /** * Draws the Entity's hitbox. * @param e The Entity whose hitbox is to be drawn. * @param outline If just the hitbox's outline should be drawn. * @param color Color of the hitbox. * @param alpha Alpha of the hitbox. */ public static function hitbox(e:Entity, outline:Boolean = true, color:uint = 0xFFFFFF, alpha:Number = 1):void { if (outline) { if (color < 0xFF000000) color += 0xFF000000; var x:int = e.x - e.originX - _camera.x, y:int = e.y - e.originY - _camera.y; _rect.x = x; _rect.y = y; _rect.width = e.width; _rect.height = 1; _target.fillRect(_rect, color); _rect.y += e.height - 1; _target.fillRect(_rect, color); _rect.y = y; _rect.width = 1; _rect.height = e.height; _target.fillRect(_rect, color); _rect.x += e.width - 1; _target.fillRect(_rect, color); return; } if (alpha >= 1) { if (color < 0xFF000000) color += 0xFF000000; _rect.x = e.x - e.originX - _camera.x; _rect.y = e.y - e.originY - _camera.y; _rect.width = e.width; _rect.height = e.height; _target.fillRect(_rect, color); } _graphics.clear(); _graphics.beginFill(color, alpha); _graphics.drawRect(e.x - e.originX - _camera.x, e.y - e.originY - _camera.y, e.width, e.height); _target.draw(FP.sprite, null, null, blend); } /** * Draws a quadratic curve to the screen. * @param x1 X start. * @param y1 Y start. * @param x2 X control point, used to determine the curve. * @param y2 Y control point, used to determine the curve. * @param x3 X finish. * @param y3 Y finish. */ public static function curve(x1:int, y1:int, x2:int, y2:int, x3:int, y3:int):void { _graphics.clear(); _graphics.lineStyle(1, 0xFF0000); _graphics.moveTo(x1, y1); _graphics.curveTo(x2, y2, x3, y3); _target.draw(FP.sprite, null, null, blend); } // Drawing information. /** @private */ private static var _target:BitmapData; /** @private */ private static var _camera:Point; /** @private */ private static var _graphics:Graphics = FP.sprite.graphics; /** @private */ private static var _rect:Rectangle = FP.rect; /** @private */ private static var _matrix:Matrix = new Matrix; } }
package net.flashpunk.utils { import flash.display.BitmapData; import flash.display.Graphics; import flash.display.LineScaleMode; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import net.flashpunk.Entity; import net.flashpunk.FP; /** * Static class with access to miscellanious drawing functions. * These functions are not meant to replace Graphic components * for Entities, but rather to help with testing and debugging. */ public class Draw { /** * The blending mode used by Draw functions. This will not * apply to Draw.line(), but will apply to Draw.linePlus(). */ public static var blend:String; /** * Sets the drawing target for Draw functions. * @param target The buffer to draw to. * @param camera The camera offset (use null for none). * @param blend The blend mode to use. */ public static function setTarget(target:BitmapData, camera:Point = null, blend:String = null):void { _target = target; _camera = camera ? camera : FP.zero; Draw.blend = blend; } /** * Resets the drawing target to the default. The same as calling Draw.setTarget(FP.buffer, FP.camera). */ public static function resetTarget():void { _target = FP.buffer; _camera = FP.camera; blend = null; } /** * Draws a pixelated, non-antialiased line. * @param x1 Starting x position. * @param y1 Starting y position. * @param x2 Ending x position. * @param y2 Ending y position. * @param color Color of the line. */ public static function line(x1:int, y1:int, x2:int, y2:int, color:uint = 0xFFFFFF):void { color &= 0xFFFFFF; // get the drawing positions x1 -= _camera.x; y1 -= _camera.y; x2 -= _camera.x; y2 -= _camera.y; // get the drawing difference var screen:BitmapData = _target, X:Number = Math.abs(x2 - x1), Y:Number = Math.abs(y2 - y1), xx:int, yy:int; // draw a single pixel if (X == 0) { if (Y == 0) { screen.setPixel(x1, y1, color); return; } // draw a straight vertical line yy = y2 > y1 ? 1 : -1; while (y1 != y2) { screen.setPixel(x1, y1, color); y1 += yy; } screen.setPixel(x2, y2, color); return; } if (Y == 0) { // draw a straight horizontal line xx = x2 > x1 ? 1 : -1; while (x1 != x2) { screen.setPixel(x1, y1, color); x1 += xx; } screen.setPixel(x2, y2, color); return; } xx = x2 > x1 ? 1 : -1; yy = y2 > y1 ? 1 : -1; var c:Number = 0, slope:Number; if (X > Y) { slope = Y / X; c = .5; while (x1 != x2) { screen.setPixel(x1, y1, color); x1 += xx; c += slope; if (c >= 1) { y1 += yy; c -= 1; } } screen.setPixel(x2, y2, color); return; } else { slope = X / Y; c = .5; while (y1 != y2) { screen.setPixel(x1, y1, color); y1 += yy; c += slope; if (c >= 1) { x1 += xx; c -= 1; } } screen.setPixel(x2, y2, color); return; } } /** * Draws a smooth, antialiased line with optional alpha and thickness. * @param x1 Starting x position. * @param y1 Starting y position. * @param x2 Ending x position. * @param y2 Ending y position. * @param color Color of the line. * @param alpha Alpha of the line. * @param thick The thickness of the line. */ public static function linePlus(x1:int, y1:int, x2:int, y2:int, color:uint = 0xFF000000, alpha:Number = 1, thick:Number = 1):void { _graphics.clear(); _graphics.lineStyle(thick, color, alpha, false, LineScaleMode.NONE); _graphics.moveTo(x1 - _camera.x, y1 - _camera.y); _graphics.lineTo(x2 - _camera.x, y2 - _camera.y); _target.draw(FP.sprite, null, null, blend); } /** * Draws a filled rectangle. * @param x X position of the rectangle. * @param y Y position of the rectangle. * @param width Width of the rectangle. * @param height Height of the rectangle. * @param color Color of the rectangle. * @param alpha Alpha of the rectangle. */ public static function rect(x:int, y:int, width:uint, height:uint, color:uint = 0xFFFFFF, alpha:Number = 1):void { if (alpha >= 1 && !blend) { if (color < 0xFF000000) color += 0xFF000000; _rect.x = x - _camera.x; _rect.y = y - _camera.y; _rect.width = width; _rect.height = height; _target.fillRect(_rect, color); } _graphics.clear(); _graphics.beginFill(color, alpha); _graphics.drawRect(x - _camera.x, y - _camera.y, width, height); _target.draw(FP.sprite, null, null, blend); } /** * Draws a filled circle. * @param x X position of the circle's center. * @param y Y position of the circle's center. * @param radius Radius of the circle. * @param color Color of the circle. * @param alpha Alpha of the circle. */ public static function circle(x:int, y:int, radius:Number, color:uint = 0x000000, alpha:Number = 1):void { _graphics.clear(); _graphics.beginFill(color & 0xFFFFFF, alpha); _graphics.drawCircle(x - _camera.x, y - _camera.y, radius); _graphics.endFill(); _target.draw(FP.sprite, null, null, blend); } /** * Draws the Entity's hitbox. * @param e The Entity whose hitbox is to be drawn. * @param outline If just the hitbox's outline should be drawn. * @param color Color of the hitbox. * @param alpha Alpha of the hitbox. */ public static function hitbox(e:Entity, outline:Boolean = true, color:uint = 0xFFFFFF, alpha:Number = 1):void { if (outline) { if (color < 0xFF000000) color += 0xFF000000; var x:int = e.x - e.originX - _camera.x, y:int = e.y - e.originY - _camera.y; _rect.x = x; _rect.y = y; _rect.width = e.width; _rect.height = 1; _target.fillRect(_rect, color); _rect.y += e.height - 1; _target.fillRect(_rect, color); _rect.y = y; _rect.width = 1; _rect.height = e.height; _target.fillRect(_rect, color); _rect.x += e.width - 1; _target.fillRect(_rect, color); return; } if (alpha >= 1) { if (color < 0xFF000000) color += 0xFF000000; _rect.x = e.x - e.originX - _camera.x; _rect.y = e.y - e.originY - _camera.y; _rect.width = e.width; _rect.height = e.height; _target.fillRect(_rect, color); } _graphics.clear(); _graphics.beginFill(color, alpha); _graphics.drawRect(e.x - e.originX - _camera.x, e.y - e.originY - _camera.y, e.width, e.height); _target.draw(FP.sprite, null, null, blend); } /** * Draws a quadratic curve to the screen. * @param x1 X start. * @param y1 Y start. * @param x2 X control point, used to determine the curve. * @param y2 Y control point, used to determine the curve. * @param x3 X finish. * @param y3 Y finish. */ public static function curve(x1:int, y1:int, x2:int, y2:int, x3:int, y3:int):void { _graphics.clear(); _graphics.lineStyle(1, 0xFF0000); _graphics.moveTo(x1, y1); _graphics.curveTo(x2, y2, x3, y3); _target.draw(FP.sprite, null, null, blend); } // Drawing information. /** @private */ private static var _target:BitmapData; /** @private */ private static var _camera:Point; /** @private */ private static var _graphics:Graphics = FP.sprite.graphics; /** @private */ private static var _rect:Rectangle = FP.rect; /** @private */ private static var _matrix:Matrix = new Matrix; } }
fix for #7, add static function modifier to linePlus.
fix for #7, add static function modifier to linePlus.
ActionScript
mit
Ken69267/config-stuff,Ken69267/config-stuff,Ken69267/config-stuff,Ken69267/config-stuff,Ken69267/config-stuff
67987fc3dcd4f38ad1e920e4678e288fc6f21edc
src/main/actionscript/com/dotfold/dotvimstat/model/image/EntityImageCollection.as
src/main/actionscript/com/dotfold/dotvimstat/model/image/EntityImageCollection.as
package com.dotfold.dotvimstat.model.image { import asx.array.reduce; import com.dotfold.dotvimstat.model.enum.ImageSize; import flash.utils.Dictionary; /** * Collection class for a list of <code>EntityImage</code>. * * @author jamesmcnamee * */ public class EntityImageCollection { private var _list:Array; protected var sizes:Array = [30, 75, 100, 300]; /** * Constructor. */ public function EntityImageCollection(list:Array = null) { super(); _list = list; } /** * Adds an item to the internal collection, and sorts on the <code>dimension</code> field. */ public function addItem(item:Object):void { _list ||= []; _list.push(item); _list.sortOn('dimension', Array.NUMERIC); } /** * Retrieves an <code>EntityImage</code> from the list corresponding to the * supplied size parameter. * * @param size ImageSize Enum of desired image size. */ public function getImageForSize(size:ImageSize):EntityImage { var dimension:int = EntityImage.ENTITY_IMAGE_SIZES[size]; var index:int = sizes.indexOf(dimension); var image:EntityImage; if (index != -1) { image = _list[index]; } return image; } /** * Returns the sorted <code>Array</code> of <code>EntityImage</code>. */ public function get list():Array { return _list; } /** * Binary Search for the closest <code>EntityImage</code> to the * supplied width parameter. * * Assumes that all Vimeo images are square, so width and height are the same value. */ public function findClosestMatchForWidth(width:int):* { var low:int = 0; var high:int = sizes.length; var result:Array = []; while (low < high) { var mid:int = (low + high) >>> 1; sizes[mid] < width ? low = mid + 1 : high = mid; } if (sizes[low] == width) { result.push(low); // because it's an ordered list, just check onwards while(sizes[++low] === width) { result.push(low); } } if (result.length > 0) { return result; } if (sizes[low] !== width) { var iterate:Array = [sizes[low - 1], sizes[low]]; var diff:Object = reduce(0, iterate, function(memo:Number, val:Number):Number { var d1:Number = Math.abs(memo - width); var d2:Number = Math.abs(val - width); return d1 > d2 ? val : memo; }); low = sizes.indexOf(diff); } return _list[low]; } } }
package com.dotfold.dotvimstat.model.image { import asx.array.empty; import asx.array.reduce; import com.dotfold.dotvimstat.model.enum.ImageSize; import flash.utils.Dictionary; /** * Collection class for a list of <code>EntityImage</code>. * * @author jamesmcnamee * */ public class EntityImageCollection { private var _list:Array; protected var sizes:Array = [30, 75, 100, 300]; // TODO: `addItems` add many method /** * Constructor. */ public function EntityImageCollection(list:Array = null) { super(); _list = list; } /** * Adds an item to the internal collection, and sorts on the <code>dimension</code> field. */ public function addItem(item:EntityImage):void { _list ||= []; _list.push(item); _list.sortOn('dimension', Array.NUMERIC); } /** * Retrieves an <code>EntityImage</code> from the list corresponding to the * supplied size parameter. * * @param size ImageSize Enum of desired image size. */ public function getImageForSize(size:ImageSize):EntityImage { var dimension:int = EntityImage.ENTITY_IMAGE_SIZES[size]; var index:int = sizes.indexOf(dimension); var image:EntityImage; if (index != -1) { image = _list[index]; } return image; } /** * Returns <code>true</code> if internal list is empty. */ public function isEmpty():Boolean { return empty(_list); } /** * Returns length of internal list. */ public function get length():int { return _list.length; } /** * Returns the sorted <code>Array</code> of <code>EntityImage</code>. */ public function get list():Array { return _list; } /** * Binary Search for the closest <code>EntityImage</code> to the * supplied width parameter. * * Assumes that all Vimeo images are square, so width and height are the same value. */ public function findClosestMatchForWidth(width:int):* { var low:int = 0; var high:int = sizes.length; var result:Array = []; while (low < high) { var mid:int = (low + high) >>> 1; sizes[mid] < width ? low = mid + 1 : high = mid; } if (sizes[low] == width) { result.push(low); // because it's an ordered list, just check onwards while(sizes[++low] === width) { result.push(low); } } if (result.length > 0) { return result; } if (sizes[low] !== width) { var iterate:Array = [sizes[low - 1], sizes[low]]; var diff:Object = reduce(0, iterate, function(memo:Number, val:Number):Number { var d1:Number = Math.abs(memo - width); var d2:Number = Math.abs(val - width); return d1 > d2 ? val : memo; }); low = sizes.indexOf(diff); } return _list[low]; } } }
fix parameter typing
[fix] fix parameter typing - EntityImageCollection addItem
ActionScript
mit
dotfold/dotvimstat
9ac5247a6683832b03721a1f3a69686ed23897ea
src/org/jivesoftware/xiff/core/XMPPBOSHConnection.as
src/org/jivesoftware/xiff/core/XMPPBOSHConnection.as
package org.jivesoftware.xiff.core { import flash.events.ErrorEvent; import flash.events.TimerEvent; import flash.utils.Timer; import flash.xml.XMLDocument; import flash.xml.XMLNode; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.http.HTTPService; import org.jivesoftware.xiff.auth.Plain; import org.jivesoftware.xiff.auth.SASLAuth; import org.jivesoftware.xiff.data.IQ; import org.jivesoftware.xiff.data.bind.BindExtension; import org.jivesoftware.xiff.data.session.SessionExtension; import org.jivesoftware.xiff.events.ConnectionSuccessEvent; import org.jivesoftware.xiff.events.DisconnectionEvent; import org.jivesoftware.xiff.events.IncomingDataEvent; import org.jivesoftware.xiff.events.LoginEvent; import org.jivesoftware.xiff.util.Callback; public class XMPPBOSHConnection extends XMPPConnection { private var maxConcurrentRequests:uint = 2; private var boshVersion:Number = 1.6; private var headers:Object = { "post": [], "get": ['Cache-Control', 'no-store', 'Cache-Control', 'no-cache', 'Pragma', 'no-cache'] }; private var requestCount:int = 0; private var failedRequests:Array = []; private var lastPollTime:int = 0; private var requestQueue:Array = []; private var responseQueue:Array = []; private const responseTimer:Timer = new Timer(0.0, 1); private var isDisconnecting:Boolean = false; private var boshPollingInterval:Number = 10000; private var sid:String; private var rid:Number; private var wait:int; private var inactivity:int; private var pollTimer:Timer; private var isCurrentlyPolling:Boolean = false; private var auth:SASLAuth; private var authHandler:Function; private var https:Boolean = false; private var _port:Number = -1; private var callbacks:Object = {}; public override function connect(streamType:String=null):Boolean { BindExtension.enable(); active = false; loggedIn = false; var attrs:Object = { xmlns: "http://jabber.org/protocol/httpbind", hold: maxConcurrentRequests, rid: nextRID, secure: https, wait: 10, ver: boshVersion } var result:XMLNode = new XMLNode(1, "body"); result.attributes = attrs; sendRequests(result); return true; } public function set secure(flag:Boolean):void { https = flag; } public override function set port(portnum:Number):void { _port = portnum; } public override function get port():Number { if(_port == -1) return https ? 8483 : 8080; return _port; } public function get httpServer():String { return (https ? "https" : "http") + "://" + server + ":" + port + "/http-bind/"; } public override function disconnect():void { dispatchEvent(new DisconnectionEvent()); } public function processConnectionResponse(responseBody:XMLNode):void { var attributes:Object = responseBody.attributes; sid = attributes.sid; boshPollingInterval = attributes.polling * 1000; // if we have a polling interval of 1, we want to add an extra second for a little bit of // padding. if(boshPollingInterval <= 1000 && boshPollingInterval > 0) boshPollingInterval += 1000; wait = attributes.wait; inactivity = attributes.inactivity; var serverRequests:int = attributes.requests; if (serverRequests) maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests); active = true; configureConnection(responseBody); responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse); pollTimer = new Timer(boshPollingInterval, 1); pollTimer.addEventListener(TimerEvent.TIMER, pollServer); } private function processResponse(event:TimerEvent=null):void { // Read the data and send it to the appropriate parser var currentNode:XMLNode = responseQueue.shift(); var nodeName:String = currentNode.nodeName.toLowerCase(); switch( nodeName ) { case "stream:features": //we already handled this in httpResponse() break; case "stream:error": handleStreamError( currentNode ); break; case "iq": handleIQ( currentNode ); break; case "message": handleMessage( currentNode ); break; case "presence": handlePresence( currentNode ); break; case "success": handleAuthentication( currentNode ); break; default: dispatchError( "undefined-condition", "Unknown Error", "modify", 500 ); break; } resetResponseProcessor(); } private function resetResponseProcessor():void { if(responseQueue.length > 0) { responseTimer.reset(); responseTimer.start(); } } private function httpResponse(req:XMLNode, isPollResponse:Boolean, evt:ResultEvent):void { requestCount--; var rawXML:String = evt.result as String; var xmlData:XMLDocument = new XMLDocument(); xmlData.ignoreWhite = this.ignoreWhite; xmlData.parseXML( rawXML ); var bodyNode:XMLNode = xmlData.firstChild; var event:IncomingDataEvent = new IncomingDataEvent(); event.data = xmlData; dispatchEvent( event ); if(bodyNode.attributes["type"] == "terminal") { dispatchError( "BOSH Error", bodyNode.attributes["condition"], "", -1 ); active = false; } for each(var childNode:XMLNode in bodyNode.childNodes) { if(childNode.nodeName == "stream:features") { _expireTagSearch = false; processConnectionResponse( bodyNode ); } else responseQueue.push(childNode); } resetResponseProcessor(); //if we just processed a poll response, we're no longer in mid-poll if(isPollResponse) isCurrentlyPolling = false; //if we have queued requests we want to send them before attempting to poll again //otherwise, if we don't already have a countdown going for the next poll, start one if (!sendQueuedRequests() && !pollTimer.running) resetPollTimer(); } private function httpError(req:XMLNode, isPollResponse:Boolean, evt:FaultEvent):void { active = false; trace("ERROR: " + req + ", \n" + evt.message); } protected override function sendXML(body:*):void { sendQueuedRequests(body); } private function sendQueuedRequests(body:*=null):Boolean { if(body) requestQueue.push(body); else if(requestQueue.length == 0) return false; return sendRequests(); } //returns true if any requests were sent private function sendRequests(data:XMLNode = null, isPoll:Boolean=false):Boolean { if(requestCount >= maxConcurrentRequests) return false; requestCount++; if(!data) { if(isPoll) { data = createRequest(); } else { var temp:Array = []; for(var i:uint = 0; i < 10 && requestQueue.length > 0; i++) { temp.push(requestQueue.shift()); } data = createRequest(temp); } } //build the http request var request:HTTPService = new HTTPService(); request.method = "post"; request.headers = headers[request.method]; request.url = httpServer; request.resultFormat = HTTPService.RESULT_FORMAT_TEXT; request.contentType = "text/xml"; var responseCallback:Callback = new Callback(this, httpResponse, data, isPoll); var errorCallback:Callback = new Callback(this, httpError, data, isPoll); request.addEventListener(ResultEvent.RESULT, responseCallback.call, false); request.addEventListener(FaultEvent.FAULT, errorCallback.call, false); request.send(data); resetPollTimer(); return true; } private function resetPollTimer():void { if(!pollTimer) return; pollTimer.reset(); pollTimer.start(); } private function pollServer(evt:TimerEvent):void { //We shouldn't poll if the connection is dead, if we had requests to send instead, or if there's already one in progress if(!isActive() || sendQueuedRequests() || isCurrentlyPolling) return; //this should be safe since sendRequests checks to be sure it's not over the concurrent requests limit, and we just ensured that the queue is empty by calling sendQueuedRequests() isCurrentlyPolling = sendRequests(null, true); } private function get nextRID():Number { if(!rid) rid = Math.floor(Math.random() * 1000000); return ++rid; } private function createRequest(bodyContent:Array=null):XMLNode { var attrs:Object = { xmlns: "http://jabber.org/protocol/httpbind", rid: nextRID, sid: sid } var req:XMLNode = new XMLNode(1, "body"); if(bodyContent) for each(var content:XMLNode in bodyContent) req.appendChild(content); req.attributes = attrs; return req; } private function login(username:String, password:String, resource:String):void { // if (!myUsername) { // auth = new XMPP.SASLAuth.Anonymous(); // } // else { auth = new Plain(username, password, server); // } authHandler = handleAuthentication; sendXML(auth.request); } private function handleAuthentication(responseBody:XMLNode):void { // if(!response || response.length == 0) { // return; // } var status:Object = auth.handleResponse(0, responseBody); if (status.authComplete) { if (status.authSuccess) { bindConnection(); } else { dispatchEvent(new ErrorEvent(ErrorEvent.ERROR)); disconnect(); } } } private function configureConnection(responseBody:XMLNode):void { var features:XMLNode = responseBody.firstChild; var authentication:Object = {}; for each(var feature:XMLNode in features.childNodes) { if (feature.nodeName == "mechanisms") authentication.auth = configureAuthMechanisms(feature); else if (feature.nodeName == "bind") authentication.bind = true; else if (feature.nodeName == "session") authentication.session = true; } auth = authentication.auth; dispatchEvent(new ConnectionSuccessEvent()); login(myUsername, myPassword, myResource); } private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth { var authMechanism:SASLAuth; for each(var mechanism:XMLNode in mechanisms.childNodes) { if (mechanism.firstChild.nodeValue == "PLAIN") return new Plain(myUsername, myPassword, server); // else if (mechanism.firstChild.nodeValue == "ANONYMOUS") { // authMechanism["anonymous"] = true; // } } if (!authMechanism) { throw new Error("No auth mechanisms found"); } return authMechanism; } public function handleBindResponse(packet:IQ):void { var bind:BindExtension = packet.getExtension("bind") as BindExtension; var jid:String = bind.getJID(); var parts:Array = jid.split("/"); myResource = parts[1]; parts = parts[0].split("@"); myUsername = parts[0]; server = parts[1]; establishSession(); } private function bindConnection():void { var bindIQ:IQ = new IQ(null, "set"); bindIQ.addExtension(new BindExtension()); //this is laaaaaame, it should be a function bindIQ.callbackName = "handleBindResponse"; bindIQ.callbackScope = this; send(bindIQ); } public function handleSessionResponse(packet:IQ):void { dispatchEvent(new LoginEvent()); } private function establishSession():void { var sessionIQ:IQ = new IQ(null, "set"); sessionIQ.addExtension(new SessionExtension()); sessionIQ.callbackName = "handleSessionResponse"; sessionIQ.callbackScope = this; send(sessionIQ); } //do nothing, we use polling instead public override function sendKeepAlive():void {} } }
package org.jivesoftware.xiff.core { import flash.events.ErrorEvent; import flash.events.TimerEvent; import flash.utils.Timer; import flash.xml.XMLDocument; import flash.xml.XMLNode; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.http.HTTPService; import org.jivesoftware.xiff.auth.Plain; import org.jivesoftware.xiff.auth.SASLAuth; import org.jivesoftware.xiff.data.IQ; import org.jivesoftware.xiff.data.bind.BindExtension; import org.jivesoftware.xiff.data.session.SessionExtension; import org.jivesoftware.xiff.events.ConnectionSuccessEvent; import org.jivesoftware.xiff.events.DisconnectionEvent; import org.jivesoftware.xiff.events.IncomingDataEvent; import org.jivesoftware.xiff.events.LoginEvent; import org.jivesoftware.xiff.util.Callback; public class XMPPBOSHConnection extends XMPPConnection { private var maxConcurrentRequests:uint = 2; private var boshVersion:Number = 1.6; private var headers:Object = { "post": [], "get": ['Cache-Control', 'no-store', 'Cache-Control', 'no-cache', 'Pragma', 'no-cache'] }; private var requestCount:int = 0; private var failedRequests:Array = []; private var lastPollTime:int = 0; private var requestQueue:Array = []; private var responseQueue:Array = []; private const responseTimer:Timer = new Timer(0.0, 1); private var isDisconnecting:Boolean = false; private var boshPollingInterval:Number = 10000; private var sid:String; private var rid:Number; private var wait:int; private var inactivity:int; private var pollTimer:Timer; private var isCurrentlyPolling:Boolean = false; private var auth:SASLAuth; private var authHandler:Function; private var https:Boolean = false; private var _port:Number = -1; private var callbacks:Object = {}; public override function connect(streamType:String=null):Boolean { BindExtension.enable(); active = false; loggedIn = false; var attrs:Object = { xmlns: "http://jabber.org/protocol/httpbind", hold: maxConcurrentRequests, rid: nextRID, secure: https, wait: 10, ver: boshVersion } var result:XMLNode = new XMLNode(1, "body"); result.attributes = attrs; sendRequests(result); return true; } public function set secure(flag:Boolean):void { https = flag; } public override function set port(portnum:Number):void { _port = portnum; } public override function get port():Number { if(_port == -1) return https ? 8483 : 8080; return _port; } public function get httpServer():String { return (https ? "https" : "http") + "://" + server + ":" + port + "/http-bind/"; } public override function disconnect():void { dispatchEvent(new DisconnectionEvent()); } public function processConnectionResponse(responseBody:XMLNode):void { var attributes:Object = responseBody.attributes; sid = attributes.sid; boshPollingInterval = attributes.polling * 1000; // if we have a polling interval of 1, we want to add an extra second for a little bit of // padding. if(boshPollingInterval <= 1000 && boshPollingInterval > 0) boshPollingInterval += 1000; wait = attributes.wait; inactivity = attributes.inactivity; var serverRequests:int = attributes.requests; if (serverRequests) maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests); active = true; configureConnection(responseBody); responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse); pollTimer = new Timer(boshPollingInterval, 1); pollTimer.addEventListener(TimerEvent.TIMER, pollServer); } private function processResponse(event:TimerEvent=null):void { // Read the data and send it to the appropriate parser var currentNode:XMLNode = responseQueue.shift(); var nodeName:String = currentNode.nodeName.toLowerCase(); switch( nodeName ) { case "stream:features": //we already handled this in httpResponse() break; case "stream:error": handleStreamError( currentNode ); break; case "iq": handleIQ( currentNode ); break; case "message": handleMessage( currentNode ); break; case "presence": handlePresence( currentNode ); break; case "success": handleAuthentication( currentNode ); break; default: dispatchError( "undefined-condition", "Unknown Error", "modify", 500 ); break; } resetResponseProcessor(); } private function resetResponseProcessor():void { if(responseQueue.length > 0) { responseTimer.reset(); responseTimer.start(); } } private function httpResponse(req:XMLNode, isPollResponse:Boolean, evt:ResultEvent):void { requestCount--; var rawXML:String = evt.result as String; var xmlData:XMLDocument = new XMLDocument(); xmlData.ignoreWhite = this.ignoreWhite; xmlData.parseXML( rawXML ); var bodyNode:XMLNode = xmlData.firstChild; var event:IncomingDataEvent = new IncomingDataEvent(); event.data = xmlData; dispatchEvent( event ); if(bodyNode.attributes["type"] == "terminal") { dispatchError( "BOSH Error", bodyNode.attributes["condition"], "", -1 ); active = false; } for each(var childNode:XMLNode in bodyNode.childNodes) { if(childNode.nodeName == "stream:features") { _expireTagSearch = false; processConnectionResponse( bodyNode ); } else responseQueue.push(childNode); } resetResponseProcessor(); //if we just processed a poll response, we're no longer in mid-poll if(isPollResponse) isCurrentlyPolling = false; //if we have queued requests we want to send them before attempting to poll again //otherwise, if we don't already have a countdown going for the next poll, start one if (!sendQueuedRequests() && !pollTimer.running) resetPollTimer(); } private function httpError(req:XMLNode, isPollResponse:Boolean, evt:FaultEvent):void { active = false; trace("ERROR: " + req + ", \n" + evt.message); } protected override function sendXML(body:*):void { sendQueuedRequests(body); } private function sendQueuedRequests(body:*=null):Boolean { if(body) requestQueue.push(body); else if(requestQueue.length == 0) return false; return sendRequests(); } //returns true if any requests were sent private function sendRequests(data:XMLNode = null, isPoll:Boolean=false):Boolean { if(requestCount >= maxConcurrentRequests) return false; requestCount++; if(!data) { if(isPoll) { data = createRequest(); } else { var temp:Array = []; for(var i:uint = 0; i < 10 && requestQueue.length > 0; i++) { temp.push(requestQueue.shift()); } data = createRequest(temp); } } //build the http request var request:HTTPService = new HTTPService(); request.method = "post"; request.headers = headers[request.method]; request.url = httpServer; request.resultFormat = HTTPService.RESULT_FORMAT_TEXT; request.contentType = "text/xml"; var responseCallback:Callback = new Callback(this, httpResponse, data, isPoll); var errorCallback:Callback = new Callback(this, httpError, data, isPoll); request.addEventListener(ResultEvent.RESULT, responseCallback.call, false); request.addEventListener(FaultEvent.FAULT, errorCallback.call, false); request.send(data); resetPollTimer(); return true; } private function resetPollTimer():void { if(!pollTimer) return; pollTimer.reset(); pollTimer.start(); } private function pollServer(evt:TimerEvent):void { //We shouldn't poll if the connection is dead, if we had requests to send instead, or if there's already one in progress if(!isActive() || sendQueuedRequests() || isCurrentlyPolling) return; //this should be safe since sendRequests checks to be sure it's not over the concurrent requests limit, and we just ensured that the queue is empty by calling sendQueuedRequests() isCurrentlyPolling = sendRequests(null, true); } private function get nextRID():Number { if(!rid) rid = Math.floor(Math.random() * 1000000); return ++rid; } private function createRequest(bodyContent:Array=null):XMLNode { var attrs:Object = { xmlns: "http://jabber.org/protocol/httpbind", rid: nextRID, sid: sid } var req:XMLNode = new XMLNode(1, "body"); if(bodyContent) for each(var content:XMLNode in bodyContent) req.appendChild(content); req.attributes = attrs; return req; } private function login(username:String, password:String, resource:String):void { // if (!myUsername) { // auth = new XMPP.SASLAuth.Anonymous(); // } // else { if(!auth) auth = new Plain(username, password, server); // } authHandler = handleAuthentication; sendXML(auth.request); } private function handleAuthentication(responseBody:XMLNode):void { // if(!response || response.length == 0) { // return; // } var status:Object = auth.handleResponse(0, responseBody); if (status.authComplete) { if (status.authSuccess) { bindConnection(); } else { dispatchEvent(new ErrorEvent(ErrorEvent.ERROR)); disconnect(); } } } private function configureConnection(responseBody:XMLNode):void { var features:XMLNode = responseBody.firstChild; var authentication:Object = {}; for each(var feature:XMLNode in features.childNodes) { if (feature.nodeName == "mechanisms") authentication.auth = configureAuthMechanisms(feature); else if (feature.nodeName == "bind") authentication.bind = true; else if (feature.nodeName == "session") authentication.session = true; } auth = authentication.auth; dispatchEvent(new ConnectionSuccessEvent()); login(myUsername, myPassword, myResource); } private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth { var authMechanism:SASLAuth; for each(var mechanism:XMLNode in mechanisms.childNodes) { if (mechanism.firstChild.nodeValue == "PLAIN") return new Plain(myUsername, myPassword, server); // else if (mechanism.firstChild.nodeValue == "ANONYMOUS") { // authMechanism["anonymous"] = true; // } } if (!authMechanism) { throw new Error("No auth mechanisms found"); } return authMechanism; } public function handleBindResponse(packet:IQ):void { var bind:BindExtension = packet.getExtension("bind") as BindExtension; var jid:String = bind.getJID(); var parts:Array = jid.split("/"); myResource = parts[1]; parts = parts[0].split("@"); myUsername = parts[0]; server = parts[1]; establishSession(); } private function bindConnection():void { var bindIQ:IQ = new IQ(null, "set"); bindIQ.addExtension(new BindExtension()); //this is laaaaaame, it should be a function bindIQ.callbackName = "handleBindResponse"; bindIQ.callbackScope = this; send(bindIQ); } public function handleSessionResponse(packet:IQ):void { dispatchEvent(new LoginEvent()); } private function establishSession():void { var sessionIQ:IQ = new IQ(null, "set"); sessionIQ.addExtension(new SessionExtension()); sessionIQ.callbackName = "handleSessionResponse"; sessionIQ.callbackScope = this; send(sessionIQ); } //do nothing, we use polling instead public override function sendKeepAlive():void {} } }
Make use of Plain conditional on no other mechanisms being found... really I think this should be deleted, but I need to investigate that
Make use of Plain conditional on no other mechanisms being found... really I think this should be deleted, but I need to investigate that
ActionScript
apache-2.0
igniterealtime/XIFF
ec21fae67f1ade82ff54466340250cbc4a26e6b2
src/aerys/minko/render/shader/compiler/CRC32.as
src/aerys/minko/render/shader/compiler/CRC32.as
package aerys.minko.render.shader.compiler { import flash.utils.ByteArray; /** * The CRC32 class provides a set of static methods to create CRC32 values. * @author promethe * */ public class CRC32 { private static const POLYNOMIAL : uint = 0x04c11db7; private static const CRC_TABLE : Vector.<uint> = new Vector.<uint>(256, true); private static const TMP_BYTEARRAY : ByteArray = new ByteArray(); private static var CRC_TABLE_READY : Boolean = false; private static function generateCrcTable() : void { for (var i : uint = 0; i < 256; ++i) { var crcAccum : uint = (i << 24) & 0xffffffff; for (var j : uint = 0; j < 8; ++j) { if (crcAccum & 0x80000000) crcAccum = (crcAccum << 1) ^ POLYNOMIAL; else crcAccum = (crcAccum << 1); } CRC_TABLE[i] = crcAccum; } CRC_TABLE_READY = true; } public static function computeForByteArrayChunk(source : ByteArray, length : uint) : uint { if (!CRC_TABLE_READY) generateCrcTable(); var crcTable : Vector.<uint> = CRC_TABLE; var crcAccum : uint = uint(-1); var length1 : uint = (length >> 2) << 2; var j : uint = 0; var i : uint; for (; j < length1; j += 4) { var data : uint = source.readUnsignedInt(); i = ((crcAccum >> 24) ^ data) & 0xFF; crcAccum = (crcAccum << 8) ^ crcTable[i]; data >>>= 8; i = ((crcAccum >> 24) ^ data) & 0xFF; crcAccum = (crcAccum << 8) ^ crcTable[i]; data >>>= 8; i = ((crcAccum >> 24) ^ data) & 0xFF; crcAccum = (crcAccum << 8) ^ crcTable[i]; data >>>= 8; i = ((crcAccum >> 24) ^ data) & 0xFF; crcAccum = (crcAccum << 8) ^ crcTable[i]; data >>>= 8; } for (; j < length; ++j) { i = ((crcAccum >> 24) ^ source.readUnsignedByte()) & 0xFF; crcAccum = (crcAccum << 8) ^ crcTable[i]; } crcAccum = ~crcAccum; return crcAccum; } public static function computeForByteArray(source : ByteArray) : uint { source.position = 0; return computeForByteArrayChunk(source, source.length); } public static function computeForString(s : String) : uint { TMP_BYTEARRAY.length = TMP_BYTEARRAY.position = 0; TMP_BYTEARRAY.writeUTFBytes(s); return computeForByteArray(TMP_BYTEARRAY); } public static function computeForUintVector(v : Vector.<uint>) : uint { var length : uint = v.length; TMP_BYTEARRAY.length = TMP_BYTEARRAY.position = 0; for (var i : uint = 0; i < length; ++i) TMP_BYTEARRAY.writeUnsignedInt(v[i]); return computeForByteArray(TMP_BYTEARRAY); } public static function computeForNumberVector(v : Vector.<Number>) : uint { var length : uint = v.length; TMP_BYTEARRAY.length = TMP_BYTEARRAY.position = 0; for (var i : uint = 0; i < length; ++i) TMP_BYTEARRAY.writeDouble(v[i]); return computeForByteArray(TMP_BYTEARRAY); } } }
package aerys.minko.render.shader.compiler { import flash.utils.ByteArray; /** * The CRC32 class provides a set of static methods to create CRC32 values. * @author promethe * */ public class CRC32 { private static const POLYNOMIAL : uint = 0x04c11db7; private static const CRC_TABLE : Vector.<uint> = new Vector.<uint>(256, true); private static const TMP_BYTEARRAY : ByteArray = new ByteArray(); private static var CRC_TABLE_READY : Boolean = false; private static function generateCrcTable() : void { for (var i : uint = 0; i < 256; ++i) { var crcAccum : uint = (i << 24) & 0xffffffff; for (var j : uint = 0; j < 8; ++j) { if (crcAccum & 0x80000000) crcAccum = (crcAccum << 1) ^ POLYNOMIAL; else crcAccum = (crcAccum << 1); } CRC_TABLE[i] = crcAccum; } CRC_TABLE_READY = true; } public static function computeForByteArrayChunk(source : ByteArray, length : uint) : uint { if (!CRC_TABLE_READY) generateCrcTable(); var crcTable : Vector.<uint> = CRC_TABLE; var crcAccum : uint = uint(-1); var length1 : uint = (length >> 2) << 2; var j : uint = 0; var i : uint; for (; j < length1; j += 4) { var data : uint = source.readUnsignedInt(); i = ((crcAccum >> 24) ^ data) & 0xFF; crcAccum = (crcAccum << 8) ^ crcTable[i]; data >>>= 8; i = ((crcAccum >> 24) ^ data) & 0xFF; crcAccum = (crcAccum << 8) ^ crcTable[i]; data >>>= 8; i = ((crcAccum >> 24) ^ data) & 0xFF; crcAccum = (crcAccum << 8) ^ crcTable[i]; data >>>= 8; i = ((crcAccum >> 24) ^ data) & 0xFF; crcAccum = (crcAccum << 8) ^ crcTable[i]; data >>>= 8; } for (; j < length; ++j) { i = ((crcAccum >> 24) ^ source.readUnsignedByte()) & 0xFF; crcAccum = (crcAccum << 8) ^ crcTable[i]; } crcAccum = ~crcAccum; return crcAccum; } public static function computeForByteArray(source : ByteArray) : uint { source.position = 0; return computeForByteArrayChunk(source, source.length); } public static function computeForString(s : String) : uint { TMP_BYTEARRAY.length = TMP_BYTEARRAY.position = 0; TMP_BYTEARRAY.writeUTFBytes(s); return computeForByteArray(TMP_BYTEARRAY); } public static function computeForUintVector(v : Vector.<uint>) : uint { var length : uint = v.length; TMP_BYTEARRAY.length = TMP_BYTEARRAY.position = 0; for (var i : uint = 0; i < length; ++i) TMP_BYTEARRAY.writeUnsignedInt(v[i]); return computeForByteArray(TMP_BYTEARRAY); } public static function computeForNumberVector(v : Vector.<Number>, begin : uint = 0, length : uint = 0) : uint { if (length == 0) length = v.length; var limit : uint = length + begin; TMP_BYTEARRAY.length = TMP_BYTEARRAY.position = 0; for (var i : uint = begin; i < limit; ++i) TMP_BYTEARRAY.writeDouble(v[i]); return computeForByteArray(TMP_BYTEARRAY); } } }
Allow user to specify boundaries when computing the CRC32 value of a vector.
Allow user to specify boundaries when computing the CRC32 value of a vector.
ActionScript
mit
aerys/minko-as3
2b3506fda723267832bc0c981d015ae999d2d4d3
src/asfac/src/com/thedevstop/asfac/AsFactory.as
src/asfac/src/com/thedevstop/asfac/AsFactory.as
package com.thedevstop.asfac { import avmplus.getQualifiedClassName; import flash.errors.IllegalOperationError; import flash.utils.describeType; import flash.utils.Dictionary; import flash.utils.getDefinitionByName; /** * The default AsFactory allows for registering instances, types, or callbacks */ public class AsFactory { private var _registrations:Dictionary; private var _descriptions:Dictionary; /** * Constructs a new AsFactory */ public function AsFactory() { _registrations = new Dictionary(); _descriptions = new Dictionary(); } /** * Registers a concrete instance to be returned whenever the target type is requested * @param instance the concrete instance to be returned * @param type the target type for which the instance should be returned at resolution time */ public function registerInstance(instance:Object, type:Class):void { var returnInstance:Function = function():Object { return instance; }; registerCallback(returnInstance, type, false); } /** * Registers a type to be returned whenever the target type is requested * @param instanceType the type to construct at resolution time * @param type the type being requested * @param asSingleton If true, only one instance will be created and returned on each request. If false (default), a new instance * is created and returned at each resolution request */ public function registerType(instanceType:Class, type:Class, asSingleton:Boolean=false):void { if (!instanceType) throw new IllegalOperationError("InstanceType cannot be null when registering a type"); var resolveType:Function = function():Object { return resolveByClass(instanceType); }; registerCallback(resolveType, type, asSingleton); } /** * Registers a callback to be executed, the result of which is returned whenever the target type is requested * @param callback the callback to execute * @param type the type being requested * @param asSingleton If true, callback is only invoked once and the result is returned on each request. If false (default), * callback is invoked on each resolution request */ public function registerCallback(callback:Function, type:Class, asSingleton:Boolean=false):void { if (!type) throw new IllegalOperationError("Type cannot be null when registering a callback"); validateCallback(callback); if (asSingleton) _registrations[type] = (function(callback:Function):Function { var instance:Object = null; return function():Object { if (!instance) instance = callback(this); return instance; }; })(callback); else _registrations[type] = callback; } /** * Returns an instance for the target type, using prior registrations to fulfill constructor parameters * @param type the type being requested * @return resolved instance */ public function resolve(type:Class):* { if (_registrations[type] !== undefined) return _registrations[type](this); return resolveByClass(type); } /** * Resolves the desired type using prior registrations * @param type the type being requested * @return the resolved instance */ private function resolveByClass(type:Class):* { if (!type) throw new IllegalOperationError("Type cannot be null when resolving."); var description:XML = getTypeDescription(type); if (description.factory.extendsClass.length() === 0) throw new IllegalOperationError("Interface {0} must be registered before it can be resolved.".replace("{0}", [email protected]())); var parameters:Array = resolveConstructorParameters(description.factory.constructor); var instance:Object = createObject(type, parameters); injectProperties(instance, description.factory); return instance; } /** * Creates a new instance of the type, using the specified parameters as the constructor parameters * @param type the type being created * @param parameters the parameters to supply to the constructor * @return new instance of type */ private function createObject(type:Class, parameters:Array):* { switch (parameters.length) { case 0 : return new type(); case 1 : return new type(parameters[0]); case 2 : return new type(parameters[0], parameters[1]); case 3 : return new type(parameters[0], parameters[1], parameters[2]); case 4 : return new type(parameters[0], parameters[1], parameters[2], parameters[3]); case 5 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4]); case 6 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5]); case 7 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6]); case 8 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7]); case 9 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8]); case 10 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9]); case 11 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10]); case 12 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11]); case 13 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11], parameters[12]); case 14 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11], parameters[12], parameters[13]); case 15 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11], parameters[12], parameters[13], parameters[14]); default : throw new Error("Too many constructor parameters for createObject"); } } /** * Confirms that a callback is valid for registration. Currently the callback must accept no arguments, or a single AsFactory argument * @param callback the callback being tested */ private function validateCallback(callback:Function):void { if (callback == null) throw new IllegalOperationError("Callback cannot be null when registering a type"); // TODO: How to check type? if (callback.length > 1) throw new IllegalOperationError("Callback function must have no arguments or a single AsFactory argument"); } /** * Gets the class description for the type * @param type The class to be described * @return An XML of the properties and methods for the class */ private function getTypeDescription(type:Class):XML { if (_descriptions[type] !== undefined) return _descriptions[type]; return _descriptions[type] = describeType(type); } /** * Resolves the non-optional parameters for a constructor * @param constructor The constructor node from a class description xml * @return An array of objects to use as constructor arguments */ private function resolveConstructorParameters(constructor:XMLList):Array { var parameters:Array = []; for each (var parameter:XML in constructor.parameter) { if ([email protected]() != "false") break; var parameterType:Class = Class(getDefinitionByName([email protected]())); parameters.push(resolve(parameterType)); } return parameters; } /** * Resolves the properties on the instance object that are marked 'Inject' * @param instance The object to be inspected * @param factory The factory node from a class description xml */ private function injectProperties(instance:Object, factory:XMLList):void { for each (var accessor:XML in factory.accessor) { if (shouldInjectAccessor(accessor)) { var propertyType:Class = Class(getDefinitionByName([email protected]())); instance[[email protected]()] = resolve(propertyType); } } } /** * Determines whether the accessor should be injected * @param accessor An accessor node from a class description xml * @return true is the Inject metadata is present, otherwise false */ private function shouldInjectAccessor(accessor:XML):Boolean { if (accessor.@access == "readwrite" || accessor.@access == "write") { for each (var metadata:XML in accessor.metadata) { if ([email protected]() == "Inject") return true; } } return false; } } }
package com.thedevstop.asfac { import avmplus.getQualifiedClassName; import flash.errors.IllegalOperationError; import flash.utils.describeType; import flash.utils.Dictionary; import flash.utils.getDefinitionByName; /** * The default AsFactory allows for registering instances, types, or callbacks */ public class AsFactory { private var _registrations:Dictionary; private var _descriptions:Dictionary; /** * Constructs a new AsFactory */ public function AsFactory() { _registrations = new Dictionary(); _descriptions = new Dictionary(); } /** * Registers a concrete instance to be returned whenever the target type is requested * @param instance the concrete instance to be returned * @param type the target type for which the instance should be returned at resolution time */ public function registerInstance(instance:Object, type:Class):void { var returnInstance:Function = function():Object { return instance; }; registerCallback(returnInstance, type, false); } /** * Registers a type to be returned whenever the target type is requested * @param instanceType the type to construct at resolution time * @param type the type being requested * @param asSingleton If true, only one instance will be created and returned on each request. If false (default), a new instance * is created and returned at each resolution request */ public function registerType(instanceType:Class, type:Class, asSingleton:Boolean=false):void { if (!instanceType) throw new IllegalOperationError("InstanceType cannot be null when registering a type"); var resolveType:Function = function():Object { return resolveByClass(instanceType); }; registerCallback(resolveType, type, asSingleton); } /** * Registers a callback to be executed, the result of which is returned whenever the target type is requested * @param callback the callback to execute * @param type the type being requested * @param asSingleton If true, callback is only invoked once and the result is returned on each request. If false (default), * callback is invoked on each resolution request */ public function registerCallback(callback:Function, type:Class, asSingleton:Boolean=false):void { if (!type) throw new IllegalOperationError("Type cannot be null when registering a callback"); validateCallback(callback); if (asSingleton) _registrations[type] = (function(callback:Function):Function { var instance:Object = null; return function():Object { if (!instance) instance = callback(this); return instance; }; })(callback); else _registrations[type] = callback; } /** * Returns an instance for the target type, using prior registrations to fulfill constructor parameters * @param type the type being requested * @return resolved instance */ public function resolve(type:Class):* { if (_registrations[type] !== undefined) return _registrations[type](this); return resolveByClass(type); } /** * Resolves the desired type using prior registrations * @param type the type being requested * @return the resolved instance */ private function resolveByClass(type:Class):* { if (!type) throw new IllegalOperationError("Type cannot be null when resolving."); var typeDescription:Object = getTypeDescription(type); if (!typeDescription) throw new IllegalOperationError("Interface must be registered before it can be resolved."); var parameters:Array = resolveConstructorParameters(typeDescription); var instance:Object = createObject(type, parameters); injectProperties(instance, typeDescription); return instance; } /** * Creates a new instance of the type, using the specified parameters as the constructor parameters * @param type the type being created * @param parameters the parameters to supply to the constructor * @return new instance of type */ private function createObject(type:Class, parameters:Array):* { switch (parameters.length) { case 0 : return new type(); case 1 : return new type(parameters[0]); case 2 : return new type(parameters[0], parameters[1]); case 3 : return new type(parameters[0], parameters[1], parameters[2]); case 4 : return new type(parameters[0], parameters[1], parameters[2], parameters[3]); case 5 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4]); case 6 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5]); case 7 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6]); case 8 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7]); case 9 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8]); case 10 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9]); case 11 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10]); case 12 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11]); case 13 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11], parameters[12]); case 14 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11], parameters[12], parameters[13]); case 15 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11], parameters[12], parameters[13], parameters[14]); default : throw new Error("Too many constructor parameters for createObject"); } } /** * Confirms that a callback is valid for registration. Currently the callback must accept no arguments, or a single AsFactory argument * @param callback the callback being tested */ private function validateCallback(callback:Function):void { if (callback == null) throw new IllegalOperationError("Callback cannot be null when registering a type"); // TODO: How to check type? if (callback.length > 1) throw new IllegalOperationError("Callback function must have no arguments or a single AsFactory argument"); } /** * Gets the class description for the type * @param type The class to be described * @return An object of constructor types and injectable properties */ private function getTypeDescription(type:Class):Object { if (_descriptions[type] !== undefined) return _descriptions[type]; return _descriptions[type] = buildTypeDescription(type); } /** * Builds an optimized description of the type. * @param type The type to be described. * @return An optimized description of the constructor and injectable properties */ private function buildTypeDescription(type:Class):Object { var typeDescription:Object = { constructorTypes:[], injectableProperties:[] }; var description:XML = describeType(type); if (description.factory.extendsClass.length() === 0) return null; for each (var parameter:XML in description.factory.constructor.parameter) { if ([email protected]() != "false") break; var parameterType:Class = Class(getDefinitionByName([email protected]())); typeDescription.constructorTypes.push(parameterType); } for each (var accessor:XML in description.factory.accessor) { if (shouldInjectAccessor(accessor)) { var propertyType:Class = Class(getDefinitionByName([email protected]())); typeDescription.injectableProperties.push( { name:[email protected](), type:propertyType } ); } } return typeDescription; } /** * Determines whether the accessor should be injected * @param accessor An accessor node from a class description xml * @return true is the Inject metadata is present, otherwise false */ private function shouldInjectAccessor(accessor:XML):Boolean { if (accessor.@access == "readwrite" || accessor.@access == "write") { for each (var metadata:XML in accessor.metadata) { if ([email protected]() == "Inject") return true; } } return false; } /** * Resolves the non-optional parameters for a constructor * @param typeDescription The optimized description of the type * @return An array of objects to use as constructor arguments */ private function resolveConstructorParameters(typeDescription:Object):Array { var parameters:Array = []; for each (var parameterType:Class in typeDescription.constructorTypes) parameters.push(resolve(parameterType)); return parameters; } /** * Resolves the properties on the instance object that are marked 'Inject' * @param instance The object to be inspected * @param typeDescription The optimized description of the type */ private function injectProperties(instance:Object, typeDescription:Object):void { for each (var injectableProperty:Object in typeDescription.injectableProperties) { instance[injectableProperty.name] = resolve(injectableProperty.type); } } } }
Store an optimized version of type description.
Store an optimized version of type description.
ActionScript
mit
thedevstop/asfac
d7ea2de9e816535e44540c98184663fc9b106009
src/aerys/minko/scene/node/mesh/modifier/BVHMesh.as
src/aerys/minko/scene/node/mesh/modifier/BVHMesh.as
package aerys.minko.scene.node.mesh.modifier { import aerys.minko.ns.minko_stream; import aerys.minko.scene.node.mesh.IMesh; import aerys.minko.scene.visitor.ISceneVisitor; import aerys.minko.type.bounding.BoundingBox; import aerys.minko.type.bounding.BoundingSphere; import aerys.minko.type.math.Vector4; import aerys.minko.type.stream.VertexStream; import aerys.minko.type.vertex.format.VertexComponent; public class BVHMesh extends AbstractMeshModifier { use namespace minko_stream; private var _version : uint = 0; private var _boundingBox : BoundingBox = null; private var _boundingSphere : BoundingSphere = null; override public function get version() : uint { return _version; } public function BVHMesh(target : IMesh) { super(target); } /*public function visited(query : ISceneVisitor) : void { if (target.version != _version || !_boundingBox) { var min : Vector4 = new Vector4(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); var max : Vector4 = new Vector4(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY); var xyzStream : VertexStream = vertexStreamList.getVertexStreamByComponent(VertexComponent.XYZ); var xyzOffset : int = xyzStream.format.getOffsetForComponent(VertexComponent.XYZ); var dwords : Vector.<Number> = xyzStream._data; var dwordsPerVertex : int = xyzStream.format.dwordsPerVertex; var dwordsCount : int = dwords.length; for (var i : int = xyzOffset; i < dwordsCount; i += dwordsPerVertex) { var x : Number = dwords[i]; var y : Number = dwords[int(i + 1)]; var z : Number = dwords[int(i + 2)]; min.x = x < min.x ? x : min.x; min.y = y < min.y ? y : min.y; min.z = z < min.z ? z : min.z; max.x = x > max.x ? x : max.x; max.y = y > max.y ? y : max.y; max.z = z > max.z ? z : max.z; } _boundingSphere = BoundingSphere.fromMinMax(min, max); _boundingBox = new BoundingBox(min, max); _version = target.version; } }*/ } }
package aerys.minko.scene.node.mesh.modifier { import aerys.minko.ns.minko_stream; import aerys.minko.scene.node.mesh.IMesh; import aerys.minko.scene.visitor.ISceneVisitor; import aerys.minko.type.bounding.BoundingBox; import aerys.minko.type.bounding.BoundingSphere; import aerys.minko.type.math.Vector4; import aerys.minko.type.stream.VertexStream; import aerys.minko.type.vertex.format.VertexComponent; public class BVHMesh extends AbstractMeshModifier { use namespace minko_stream; private var _version : uint = 0; private var _boundingBox : BoundingBox = null; private var _boundingSphere : BoundingSphere = null; override public function get version() : uint { return _version; } public function BVHMesh(target : IMesh) { super(target); computeBoundingVolumes(); } public function computeBoundingVolumes() : void { var min : Vector4 = new Vector4(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); var max : Vector4 = new Vector4(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY); var xyzStream : VertexStream = vertexStreamList.getVertexStreamByComponent(VertexComponent.XYZ); var xyzOffset : int = xyzStream.format.getOffsetForComponent(VertexComponent.XYZ); var dwords : Vector.<Number> = xyzStream._data; var dwordsPerVertex : int = xyzStream.format.dwordsPerVertex; var dwordsCount : int = dwords.length; for (var i : int = xyzOffset; i < dwordsCount; i += dwordsPerVertex) { var x : Number = dwords[i]; var y : Number = dwords[int(i + 1)]; var z : Number = dwords[int(i + 2)]; min.x = x < min.x ? x : min.x; min.y = y < min.y ? y : min.y; min.z = z < min.z ? z : min.z; max.x = x > max.x ? x : max.x; max.y = y > max.y ? y : max.y; max.z = z > max.z ? z : max.z; } _boundingSphere = BoundingSphere.fromMinMax(min, max); _boundingBox = new BoundingBox(min, max); } } }
Enable dead code from BVHMesh
Enable dead code from BVHMesh
ActionScript
mit
aerys/minko-as3
157e666227455a2a773cb297d5f0013cde2bd489
src/RTMP.as
src/RTMP.as
package { import flash.display.Sprite; import org.osmf.containers.MediaContainer; import org.osmf.elements.VideoElement; import org.osmf.media.DefaultMediaFactory; import org.osmf.media.MediaElement; import org.osmf.media.MediaPlayer; import org.osmf.media.URLResource; [SWF( width="640", height="360" )] public class RTMP extends Sprite { public function RTMP() { // Store the URL var videoPath:String = "rtmp://cp67126.edgefcs.net/ondemand/mediapm/strobe/content/test/SpaceAloneHD_sounas_640_500_short"; // Create a resource var resource:URLResource = new URLResource( videoPath ); // Create a mediafactory instance var mediaFactory:DefaultMediaFactory = new DefaultMediaFactory(); // Create a MediaElement //var element:VideoElement = new VideoElement( resource ); var element:MediaElement = mediaFactory.createMediaElement( resource ); // Create a media player var mediaPlayer:MediaPlayer = new MediaPlayer( element ); // Create a media container & add the MediaElement var mediaContainer:MediaContainer = new MediaContainer(); mediaContainer.addMediaElement( element ); // Add the container to the display list addChild( mediaContainer ); } } }
package { import flash.display.Sprite; import flash.external.ExternalInterface; import org.osmf.containers.MediaContainer; import org.osmf.elements.VideoElement; import org.osmf.media.DefaultMediaFactory; import org.osmf.media.MediaElement; import org.osmf.media.MediaPlayer; import org.osmf.media.URLResource; [SWF(width="640", height="360")] public class RTMP extends Sprite { private var playbackId:String; private var mediaFactory:DefaultMediaFactory; private var mediaContainer:MediaContainer; public function RTMP() { playbackId = this.root.loaderInfo.parameters.playbackId; mediaFactory = new DefaultMediaFactory(); mediaContainer = new MediaContainer(); setupCallbacks(); _triggerEvent('flashready'); ExternalInterface.call('console.log', 'clappr rtmp 0.0-alpha'); } private function setupCallbacks():void { ExternalInterface.addCallback("playerPlay", play); } private function play(url:String):void { ExternalInterface.call('console.log', 'playing ' + url); var resource:URLResource = new URLResource(url); var element:MediaElement = mediaFactory.createMediaElement(resource); var mediaPlayer:MediaPlayer = new MediaPlayer(element); mediaContainer.addMediaElement(element); addChild(mediaContainer); } private function _triggerEvent(name: String):void { ExternalInterface.call('Clappr.Mediator.trigger("' + playbackId + ':' + name +'")'); } } }
fix identation, add first callback
RTMP.as: fix identation, add first callback
ActionScript
apache-2.0
video-dev/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin
ec8f911691fe2060208fa8ea75f0736af6596b95
src/main/org/shypl/common/util/Path.as
src/main/org/shypl/common/util/Path.as
package org.shypl.common.util { import org.shypl.common.lang.IllegalStateException; public class Path { private var _value:String; public function Path(value:String = null) { if (value === "") { value = null; } else if (value !== null) { while (StringUtils.endsWith(value, "/")) { value = value.substr(0, -1); } } _value = value; } public function get parent():Path { if (_value === null) { throw new IllegalStateException(); } var i:int = _value.lastIndexOf("/"); if (i === -1) { throw new IllegalStateException(); } return factoryPath(_value.substring(0, i)); } public function get empty():Boolean { return _value === null; } protected function get value():String { return _value; } public function resolve(path:String):Path { var i:int; var p:Path = this; while ((i = path.indexOf("../")) >= 0) { p = p.parent; path = path.substr(3); } return factoryPath(p.empty ? path : (p.toString() + "/" + path)); } public function resolveSibling(path:String):Path { return parent.resolve(path); } public function toString():String { return _value; } protected function factoryPath(value:String):Path { return new Path(value); } } }
package org.shypl.common.util { import org.shypl.common.lang.IllegalStateException; public class Path { private var _value:String; public function Path(value:String = null) { if (value === "") { value = null; } else if (value !== null) { while (StringUtils.endsWith(value, "/")) { value = value.substr(0, -1); } } _value = value; } public function get parent():Path { if (_value === null) { throw new IllegalStateException(); } var i:int = _value.lastIndexOf("/"); if (i === -1) { throw new IllegalStateException(); } return factoryPath(_value.substring(0, i)); } public function get empty():Boolean { return _value === null; } public function get value():String { return _value; } public function resolve(path:String):Path { var i:int; var p:Path = this; while ((i = path.indexOf("../")) >= 0) { p = p.parent; path = path.substr(3); } return factoryPath(p.empty ? path : (p.toString() + "/" + path)); } public function resolveSibling(path:String):Path { return parent.resolve(path); } public function toString():String { return _value; } protected function factoryPath(value:String):Path { return new Path(value); } } }
Refactor Path
Refactor Path
ActionScript
apache-2.0
shypl/common-flash
ba76a845e0a6d44d2139c5e09b64b30b43046fed
src/as/com/threerings/media/tile/Tile.as
src/as/com/threerings/media/tile/Tile.as
// // Nenya library - tools for developing networked games // Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.media.tile { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.DisplayObject; public class Tile { /** The key associated with this tile. */ public var key :Tile_Key; /** * Configures this tile with its tile image. */ public function setImage (image :DisplayObject) :void { _image = image; // Notify them all and clear our list. for each (var func :Function in _notifyOnLoad) { func(this); } } public function getImage () :DisplayObject { if (_image is Bitmap) { // TODO - handle this more consistently... return new Bitmap(Bitmap(_image).bitmapData); } else { return _image; } } /** * Returns the width of this tile. */ public function getWidth () :int { return _image.width; } /** * Returns the height of this tile. */ public function getHeight () :int { return _image.height; } /** * Returns true if the specified coordinates within this tile contains * a non-transparent pixel. */ public function hitTest (x :int, y :int) :Boolean { return _image.hitTestPoint(x, y, true); } public function toString () :String { return "[" + toStringBuf(new String()) + "]"; } /** * This should be overridden by derived classes (which should be sure * to call <code>super.toString()</code>) to append the derived class * specific tile information to the string buffer. */ protected function toStringBuf (buf :String) :String { if (_image == null) { return buf.concat("null-image"); } else { return buf.concat(_image.width, "x", _image.height); } } public function notifyOnLoad (func :Function) :void { _notifyOnLoad.push(func); } /** * Returns the x offset into the tile image of the origin (which will be aligned with the * bottom center of the origin tile) or <code>Integer.MIN_VALUE</code> if the origin is not * explicitly specified and should be computed from the image size and tile footprint. */ public function getOriginX () :int { throw new Error("abstract"); } /** * Returns the y offset into the tile image of the origin (which will be aligned with the * bottom center of the origin tile) or <code>Integer.MIN_VALUE</code> if the origin is not * explicitly specified and should be computed from the image size and tile footprint. */ public function getOriginY () :int { throw new Error("abstract") } /** * Returns the object footprint width in tile units. */ public function getBaseWidth () :int { throw new Error("abstract"); } /** * Returns the object footprint height in tile units. */ public function getBaseHeight () :int { throw new Error("abstract"); } /** Our tileset image. */ protected var _image :DisplayObject; /** Everyone who cares when we're loaded. */ protected var _notifyOnLoad :Array = []; } }
// // Nenya library - tools for developing networked games // Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.media.tile { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.DisplayObject; public class Tile { /** The key associated with this tile. */ public var key :Tile_Key; /** * Configures this tile with its tile image. */ public function setImage (image :DisplayObject) :void { _image = image; // Notify them all and clear our list. for each (var func :Function in _notifyOnLoad) { func(this); } } public function getImage () :DisplayObject { if (_image is Bitmap) { // TODO - handle this more consistently... return new Bitmap(Bitmap(_image).bitmapData); } else { return _image; } } /** * Returns the width of this tile. */ public function getWidth () :int { return _image.width; } /** * Returns the height of this tile. */ public function getHeight () :int { return _image.height; } /** * Returns true if the specified coordinates within this tile contains * a non-transparent pixel. */ public function hitTest (x :int, y :int) :Boolean { return _image.hitTestPoint(x, y, true); } public function toString () :String { return "[" + toStringBuf(new String()) + "]"; } /** * This should be overridden by derived classes (which should be sure * to call <code>super.toString()</code>) to append the derived class * specific tile information to the string buffer. */ protected function toStringBuf (buf :String) :String { if (_image == null) { return buf.concat("null-image"); } else { return buf.concat(_image.width, "x", _image.height); } } public function notifyOnLoad (func :Function) :void { if (_image != null) { func(this); } else { _notifyOnLoad.push(func); } } /** * Returns the x offset into the tile image of the origin (which will be aligned with the * bottom center of the origin tile) or <code>Integer.MIN_VALUE</code> if the origin is not * explicitly specified and should be computed from the image size and tile footprint. */ public function getOriginX () :int { throw new Error("abstract"); } /** * Returns the y offset into the tile image of the origin (which will be aligned with the * bottom center of the origin tile) or <code>Integer.MIN_VALUE</code> if the origin is not * explicitly specified and should be computed from the image size and tile footprint. */ public function getOriginY () :int { throw new Error("abstract") } /** * Returns the object footprint width in tile units. */ public function getBaseWidth () :int { throw new Error("abstract"); } /** * Returns the object footprint height in tile units. */ public function getBaseHeight () :int { throw new Error("abstract"); } /** Our tileset image. */ protected var _image :DisplayObject; /** Everyone who cares when we're loaded. */ protected var _notifyOnLoad :Array = []; } }
Make tiles work like tilesets - if you ask to be notified and it's already loaded, notify immediately.
Make tiles work like tilesets - if you ask to be notified and it's already loaded, notify immediately. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@968 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
845250007a931b4e6abd1b164f6d5b991ed80148
src/com/google/analytics/campaign/CampaignTracker.as
src/com/google/analytics/campaign/CampaignTracker.as
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. * Marc Alcaraz <[email protected]>. */ package com.google.analytics.campaign { import com.google.analytics.utils.Variables; /** * Campaign tracker object. * Contains all the data associated with a campaign. * * AdWords: * The following variables * name, source, medium, term, content * are automatically generated for AdWords hits when autotagging * is turned on through the AdWords interface. * * * note: * we can not use a CampaignInfo because here the serialization * to URL have to be injected into __utmz and is then a special case. * * links: * * Understanding campaign variables: The five dimensions of campaign tracking * http://www.google.com/support/googleanalytics/bin/answer.py?answer=55579&hl=en * * How does campaign tracking work? * http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55540 * * What is A/B Testing and how can it help me? * http://www.google.com/support/googleanalytics/bin/answer.py?answer=55589 * * What information do the filter fields represent? * http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55588 */ public class CampaignTracker { /** * @private */ private function _addIfNotEmpty( arr:Array, field:String, value:String ):void { if( value != "" ) { value = value.split( "+" ).join( "%20" ); value = value.split( " " ).join( "%20" ); arr.push( field + value ); } } /** * The campaign code or id can be used to refer to a campaign lookup table, * or chart of referring codes used to define variables in place of multiple request query tags. * variable: utmcid */ public var id:String; /** * The resource that provided the click. * Every referral to a web site has an origin, or source. * Examples of sources are the Google search engine, * the AOL search engine, the name of a newsletter, * or the name of a referring web site. * Other example: "AdWords". * * variable: utmcsr */ public var source:String; //required /** * google ad click id * * variable: utmgclid */ public var clickId:String; /** * Usually refers to name given to the marketing campaign or is used to differentiate campaign source. * The campaign name differentiates product promotions such as "Spring Ski Sale" * or slogan campaigns such as "Get Fit For Summer". * * alternative: * Used for keyword analysis to identify a specific product promotion or strategic campaign. * * variable: utmccn */ public var name:String; //required /** * Method of Delivery. * The medium helps to qualify the source; * together, the source and medium provide specific information * about the origin of a referral. * For example, in the case of a Google search engine source, * the medium might be "cost-per-click", indicating a sponsored link for which the advertiser paid, * or "organic", indicating a link in the unpaid search engine results. * In the case of a newsletter source, examples of medium include "email" and "print". * Other examples: "Organic", "CPC", or "PPC". * * variable: utmcmd */ public var medium:String; //required /** * The term or keyword is the word or phrase that a user types into a search engine. * Used for paid search. * variable: utmctr */ public var term:String; /** * The content dimension describes the version of an advertisement on which a visitor clicked. * <p>It is used in content-targeted advertising and Content (A/B) Testing to determine which version of an advertisement is most effective at attracting profitable leads.</p> * <p>Alternative: Used for A/B testing and content-targeted ads to differentiate ads or links that point to the same URL.</p> * <p>variable: utmcct</p> */ public var content:String; /** * Creates a new CampaingTracker instance. */ public function CampaignTracker( id:String = "", source:String = "", clickId:String = "", name:String = "", medium:String = "", term:String = "", content:String = "" ) { this.id = id; this.source = source; this.clickId = clickId; this.name = name; this.medium = medium; this.term = term; this.content = content; } /** * Returns a flag indicating whether this tracker object is valid. * A tracker object is considered to be valid if and only if one of id, source or clickId is present. */ public function isValid():Boolean { if( (id != "") || (source != "") || (clickId != "") ) { return true; } return false; } /** * Builds the tracker object from a tracker string. * * @private * @param {String} trackerString Tracker string to parse tracker object from. */ public function fromTrackerString( tracker:String ):void { /* note: we are basically deserializing the utmz.campaignTracking property */ var data:String = tracker.split( CampaignManager.trackingDelimiter ).join( "&" ); var vars:Variables = new Variables( data ); if( vars.hasOwnProperty( "utmcid" ) ) { this.id = vars["utmcid"]; } if( vars.hasOwnProperty( "utmcsr" ) ) { this.source = vars["utmcsr"]; } if( vars.hasOwnProperty( "utmccn" ) ) { this.name = vars["utmccn"]; } if( vars.hasOwnProperty( "utmcmd" ) ) { this.medium = vars["utmcmd"]; } if( vars.hasOwnProperty( "utmctr" ) ) { this.term = vars["utmctr"]; } if( vars.hasOwnProperty( "utmcct" ) ) { this.content = vars["utmcct"]; } if( vars.hasOwnProperty( "utmgclid" ) ) { this.clickId = vars["utmgclid"]; } } /** * Format for tracker have the following fields (seperated by "|"): * <table> * <tr><td>utmcid - lookup table id</td></tr> * <tr><td>utmcsr - campaign source</td></tr> * <tr><td>utmgclid - google ad click id</td></tr> * <tr><td>utmccn - campaign name</td></tr> * <tr><td>utmcmd - campaign medium</td></tr> * <tr><td>utmctr - keywords</td></tr> * <tr><td>utmcct - ad content description</td></tr> * * * </table> * should be in this order : utmcid=one|utmcsr=two|utmgclid=three|utmccn=four|utmcmd=five|utmctr=six|utmcct=seven * */ public function toTrackerString():String { var data:Array = []; /* for each value, append key=value if and only if the value is not empty. */ _addIfNotEmpty( data, "utmcid=", id ); _addIfNotEmpty( data, "utmcsr=", source ); _addIfNotEmpty( data, "utmgclid=", clickId ); _addIfNotEmpty( data, "utmccn=", name ); _addIfNotEmpty( data, "utmcmd=", medium ); _addIfNotEmpty( data, "utmctr=", term ); _addIfNotEmpty( data, "utmcct=", content ); return data.join( CampaignManager.trackingDelimiter ); } } }
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. * Marc Alcaraz <[email protected]>. */ package com.google.analytics.campaign { import com.google.analytics.utils.Variables; /* Campaign tracker object. Contains all the data associated with a campaign. AdWords: The following variables name, source, medium, term, content are automatically generated for AdWords hits when autotagging is turned on through the AdWords interface. note: we can not use a CampaignInfo because here the serialization to URL have to be injected into __utmz and is then a special case. links: Understanding campaign variables: The five dimensions of campaign tracking http://www.google.com/support/googleanalytics/bin/answer.py?answer=55579&hl=en How does campaign tracking work? http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55540 What is A/B Testing and how can it help me? http://www.google.com/support/googleanalytics/bin/answer.py?answer=55589 What information do the filter fields represent? http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55588 */ public class CampaignTracker { /** * @private */ private function _addIfNotEmpty( arr:Array, field:String, value:String ):void { if( value != "" ) { value = value.split( "+" ).join( "%20" ); value = value.split( " " ).join( "%20" ); arr.push( field + value ); } } /** * The campaign code or id can be used to refer to a campaign lookup table, * or chart of referring codes used to define variables in place of multiple request query tags. * variable: utmcid */ public var id:String; /** * The resource that provided the click. * Every referral to a web site has an origin, or source. * Examples of sources are the Google search engine, * the AOL search engine, the name of a newsletter, * or the name of a referring web site. * Other example: "AdWords". * * variable: utmcsr */ public var source:String; //required /** * google ad click id * * variable: utmgclid */ public var clickId:String; /** * Usually refers to name given to the marketing campaign or is used to differentiate campaign source. * The campaign name differentiates product promotions such as "Spring Ski Sale" * or slogan campaigns such as "Get Fit For Summer". * * alternative: * Used for keyword analysis to identify a specific product promotion or strategic campaign. * * variable: utmccn */ public var name:String; //required /** * Method of Delivery. * The medium helps to qualify the source; * together, the source and medium provide specific information * about the origin of a referral. * For example, in the case of a Google search engine source, * the medium might be "cost-per-click", indicating a sponsored link for which the advertiser paid, * or "organic", indicating a link in the unpaid search engine results. * In the case of a newsletter source, examples of medium include "email" and "print". * Other examples: "Organic", "CPC", or "PPC". * * variable: utmcmd */ public var medium:String; //required /** * The term or keyword is the word or phrase that a user types into a search engine. * Used for paid search. * variable: utmctr */ public var term:String; /** * The content dimension describes the version of an advertisement on which a visitor clicked. * <p>It is used in content-targeted advertising and Content (A/B) Testing to determine which version of an advertisement is most effective at attracting profitable leads.</p> * <p>Alternative: Used for A/B testing and content-targeted ads to differentiate ads or links that point to the same URL.</p> * <p>variable: utmcct</p> */ public var content:String; /** * Creates a new CampaingTracker instance. */ public function CampaignTracker( id:String = "", source:String = "", clickId:String = "", name:String = "", medium:String = "", term:String = "", content:String = "" ) { this.id = id; this.source = source; this.clickId = clickId; this.name = name; this.medium = medium; this.term = term; this.content = content; } /** * Returns a flag indicating whether this tracker object is valid. * A tracker object is considered to be valid if and only if one of id, source or clickId is present. */ public function isValid():Boolean { if( (id != "") || (source != "") || (clickId != "") ) { return true; } return false; } /** * Builds the tracker object from a tracker string. * * @private * @param {String} trackerString Tracker string to parse tracker object from. */ public function fromTrackerString( tracker:String ):void { /* note: we are basically deserializing the utmz.campaignTracking property */ var data:String = tracker.split( CampaignManager.trackingDelimiter ).join( "&" ); var vars:Variables = new Variables( data ); if( vars.hasOwnProperty( "utmcid" ) ) { this.id = vars["utmcid"]; } if( vars.hasOwnProperty( "utmcsr" ) ) { this.source = vars["utmcsr"]; } if( vars.hasOwnProperty( "utmccn" ) ) { this.name = vars["utmccn"]; } if( vars.hasOwnProperty( "utmcmd" ) ) { this.medium = vars["utmcmd"]; } if( vars.hasOwnProperty( "utmctr" ) ) { this.term = vars["utmctr"]; } if( vars.hasOwnProperty( "utmcct" ) ) { this.content = vars["utmcct"]; } if( vars.hasOwnProperty( "utmgclid" ) ) { this.clickId = vars["utmgclid"]; } } /** * Format for tracker have the following fields (seperated by "|"): * <table> * <tr><td>utmcid - lookup table id</td></tr> * <tr><td>utmcsr - campaign source</td></tr> * <tr><td>utmgclid - google ad click id</td></tr> * <tr><td>utmccn - campaign name</td></tr> * <tr><td>utmcmd - campaign medium</td></tr> * <tr><td>utmctr - keywords</td></tr> * <tr><td>utmcct - ad content description</td></tr> * * * </table> * should be in this order : utmcid=one|utmcsr=two|utmgclid=three|utmccn=four|utmcmd=five|utmctr=six|utmcct=seven * */ public function toTrackerString():String { var data:Array = []; /* for each value, append key=value if and only if the value is not empty. */ _addIfNotEmpty( data, "utmcid=", id ); _addIfNotEmpty( data, "utmcsr=", source ); _addIfNotEmpty( data, "utmgclid=", clickId ); _addIfNotEmpty( data, "utmccn=", name ); _addIfNotEmpty( data, "utmcmd=", medium ); _addIfNotEmpty( data, "utmctr=", term ); _addIfNotEmpty( data, "utmcct=", content ); return data.join( CampaignManager.trackingDelimiter ); } } }
update comment for asdoc
update comment for asdoc
ActionScript
apache-2.0
nsdevaraj/gaforflash,minimedj/gaforflash,nsdevaraj/gaforflash,minimedj/gaforflash
368cca033ffde014c9505201d850815beb091100
dolly-framework/src/main/actionscript/dolly/Cloner.as
dolly-framework/src/main/actionscript/dolly/Cloner.as
package dolly { import dolly.core.dolly_internal; import dolly.core.errors.CloningError; import dolly.core.metadata.MetadataName; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; use namespace dolly_internal; public class Cloner { private static function isTypeCloneable(type:Type):Boolean { return type.hasMetadata(MetadataName.CLONEABLE); } dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> { if (!isTypeCloneable(type)) { throw new CloningError( CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE, CloningError.CLASS_IS_NOT_CLONEABLE_CODE ); } const result:Vector.<Field> = new Vector.<Field>(); for each(var field:Field in type.properties) { if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) { result.push(field); } } return result; } public static function clone(source:*):* { const type:Type = Type.forInstance(source); if (!isTypeCloneable(type)) { throw new CloningError( CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE, CloningError.CLASS_IS_NOT_CLONEABLE_CODE ); } const clonedInstance:* = new (type.clazz)(); // Find all public writable fields in a hierarchy of a source object // and assign their values to a clone object. const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type); var name:String; for each(var field:Field in fieldsToClone) { name = field.name; clonedInstance[name] = source[name]; } return clonedInstance; } } }
package dolly { import dolly.core.dolly_internal; import dolly.core.errors.CloningError; import dolly.core.metadata.MetadataName; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; use namespace dolly_internal; public class Cloner { private static function isTypeCloneable(type:Type):Boolean { return type.hasMetadata(MetadataName.CLONEABLE); } dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> { if (!isTypeCloneable(type)) { throw new CloningError( CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE, CloningError.CLASS_IS_NOT_CLONEABLE_CODE ); } const result:Vector.<Field> = new Vector.<Field>(); for each(var field:Field in type.properties) { if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) { result.push(field); } } return result; } public static function clone(source:*):* { const type:Type = Type.forInstance(source); // Find all public writable fields in a hierarchy of a source object // and assign their values to a clone object. const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type); const clonedInstance:* = new (type.clazz)(); var name:String; for each(var field:Field in fieldsToClone) { name = field.name; clonedInstance[name] = source[name]; } return clonedInstance; } } }
Check for class marking as cloneable only once in method Cloner.findAllWritableFieldsForType().
Check for class marking as cloneable only once in method Cloner.findAllWritableFieldsForType().
ActionScript
mit
Yarovoy/dolly
ef999f9fb052a86c1d46eb80acbb92558e134043
as3/xobjas3/src/com/rpath/xobj/URL.as
as3/xobjas3/src/com/rpath/xobj/URL.as
/* # Copyright (c) 2008-2010 rPath, Inc. # # This program is distributed under the terms of the MIT License as found # in a file called LICENSE. If it is not present, the license # is always available at http://www.opensource.org/licenses/mit-license.php. # # 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 MIT License for full details. # */ package com.rpath.xobj { import mx.utils.URLUtil; /** URL provides more "intelligent" String instances that * wrap up some of the functionality of the URLUtil helper * as well as make URL's more typesafe in general usage */ public class URL { public function URL(v:*="", useHTTPS:Boolean=false) { super(); this.useHTTPS = useHTTPS; if (v is URL) { this.value = (v as URL).value; } else { this.value = v; } } public var useHTTPS:Boolean; public function get value():String { return _value; } private var _value:String; public function set value(value:String):void { _value = value; if (_value && useHTTPS && !isHTTPS) { // make the URL HTTPS if (_value.indexOf("http://") == 0) { _value = _value.replace("http://", "https://"); } } } public function get isHTTPS():Boolean { return URLUtil.isHttpsURL(value); } public function get isHTTP():Boolean { return URLUtil.isHttpURL(value); } public function hasQuery():Boolean { return value.indexOf("?") != -1; } public function toString():String { return value; } } }
/* # Copyright (c) 2008-2010 rPath, Inc. # # This program is distributed under the terms of the MIT License as found # in a file called LICENSE. If it is not present, the license # is always available at http://www.opensource.org/licenses/mit-license.php. # # 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 MIT License for full details. # */ package com.rpath.xobj { import mx.utils.URLUtil; /** URL provides more "intelligent" String instances that * wrap up some of the functionality of the URLUtil helper * as well as make URL's more typesafe in general usage */ public class URL { public function URL(v:*="", useHTTPS:Boolean=false) { super(); this.useHTTPS = useHTTPS; if (v is URL) { this.value = (v as URL).value; } else { this.value = v; } } public var useHTTPS:Boolean; public function get value():String { return _value; } private var _value:String; public function set value(value:String):void { _value = value; if (_value && useHTTPS && !isHTTPS) { // make the URL HTTPS if (_value.indexOf("http://") == 0) { _value = _value.replace("http://", "https://"); } } } public function get isHTTPS():Boolean { return URLUtil.isHttpsURL(value); } public function get isHTTP():Boolean { return URLUtil.isHttpURL(value); } public function hasQuery():Boolean { return value.indexOf("?") != -1; } public function toString():String { return value; } public function set url(s:String):void { value = s; } public function get url():String { return value; } } }
Allow URL.url for lazy modelling
Allow URL.url for lazy modelling
ActionScript
apache-2.0
sassoftware/xobj,sassoftware/xobj,sassoftware/xobj,sassoftware/xobj
2507794f8a52753854b28a397081123e84be148f
src/avm2/tests/performance/c4/basic.as
src/avm2/tests/performance/c4/basic.as
package { var last = new Date(); function clockUnder(max, name) { var elapsed = new Date() - last; // Keep this disabled when committing this file. var elapsedSuffix = false ? " (" + elapsed + ")" : ""; var nameSuffix = name ? ": " + name : ""; if (elapsed > max) { trace("FAIL: > " + max + " ms" + elapsedSuffix + nameSuffix); } else { trace("PASS: < " + max + " ms" + elapsedSuffix + nameSuffix); } last = new Date(); } var K = 1024; var JS_FAST = 200; var AS_FAST = JS_FAST * 5; var VERY_SLOW = 5000; (function () { var s = 0; var COUNT = 1 * K * K; for (var i = 0; i < COUNT; i++) { s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; } trace(s); })(); clockUnder(AS_FAST, "Adding Numbers"); (function () { var s = ""; var COUNT = 1 * K * K; for (var i = 0; i < COUNT; i++) { s = s + i; } trace(s.length); })(); clockUnder(AS_FAST, "Adding Strings + Numbers"); (function () { var s = 0; var COUNT = 1 * K; for (var i = 0; i < COUNT; i++) { var a = []; for (var j = 0; j < K; j++) { a.AS3::push(i); } s += a.length; } trace(s); })(); clockUnder(AS_FAST, "Arrays AS3 Namespace Push"); (function () { var s = 0; var COUNT = 1 * K; for (var i = 0; i < COUNT; i++) { var a = []; for (var j = 0; j < K; j++) { a.push(i); } s += a.length; } trace(s); })(); clockUnder(AS_FAST, "Arrays AS3 Prototype Push"); class C { function foo() { return 2; } } (function () { var s = 0; var COUNT = 1 * K * K; var c = new C(); for (var i = 0; i < COUNT; i++) { s += c.foo(); } trace(s); })(); clockUnder(AS_FAST, "Class Method Call"); (function () { var s = 0; var COUNT = 1 * K * K; var v : Vector.<C> = new Vector.<C>(); v.push(new C()); for (var i = 0; i < COUNT; i++) { s += v[0].foo(); } trace(s); })(); clockUnder(AS_FAST, "Class Method Call - Vector"); (function () { var s = 0; var COUNT = 1 * K * K; var v : Vector.<C> = new Vector.<C>(); var o = new C(); for (var i = 0; i < COUNT; i++) { v[0] = o; } })(); clockUnder(AS_FAST, "Set Vector"); class A { static const staticConstant = 123; const instanceConstant = 234; static var staticVar = 345; var instanceVar = 456; static function staticFunction() { var s = 0; for (var i = 0; i < 10000000; i++) { s += staticConstant; s += staticVar; } clockUnder(5000, "Access Static Constant / Var"); return s; } function instanceFunction() { var s = 0; for (var i = 0; i < 10000000; i++) { s += instanceConstant; s += instanceVar; } clockUnder(5000, "Access Instance Constant / Var"); return s; } } class B extends A { static function staticFunctionB() { var s = 0; for (var i = 0; i < 10000000; i++) { s += staticConstant; s += staticVar; } clockUnder(5000, "Access Static Constant / Var"); return s; } function instanceFunctionB() { var s = 0; for (var i = 0; i < 10000000; i++) { s += instanceConstant; s += instanceVar; } clockUnder(5000, "Access Instance Constant / Var"); return s; } } A.staticFunction(); (new A()).instanceFunction(); B.staticFunctionB(); (new B()).instanceFunctionB(); (function () { var s = 0; for (var i = 0; i < 5000000; i++) { s += -Number.MAX_VALUE; s += Number.MAX_VALUE; s += Math.abs(i); } clockUnder(5000, "Math.abs()"); return s; })(); class D { var foobar = 0; var y = 0; function D(x, y) { this.foobar = x; this.y = y; } } (function () { var s = 0; for (var i = 0; i < 1000000; i++) { s += (new D(2, 3)).foobar; s += (new D(2, 3)).y; } clockUnder(500, "Object allocation with property access"); return s; })(); }
package { var last = new Date(); function clockUnder(max, name) { var elapsed = new Date() - last; // Keep this disabled when committing this file. var elapsedSuffix = true ? " (" + elapsed + ")" : ""; var nameSuffix = name ? ": " + name : ""; if (elapsed > max) { trace("FAIL: > " + max + " ms" + elapsedSuffix + nameSuffix); } else { trace("PASS: < " + max + " ms" + elapsedSuffix + nameSuffix); } last = new Date(); } var K = 1024; var JS_FAST = 200; var AS_FAST = JS_FAST * 5; var VERY_SLOW = 5000; (function () { var s = 0; var COUNT = 1 * K * K; for (var i = 0; i < COUNT; i++) { s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; s = s + i; } trace(s); })(); clockUnder(AS_FAST, "Adding Numbers"); (function () { var s = ""; var COUNT = 1 * K * K; for (var i = 0; i < COUNT; i++) { s = s + i; } trace(s.length); })(); clockUnder(AS_FAST, "Adding Strings + Numbers"); (function () { var s = 0; var COUNT = 1 * K; for (var i = 0; i < COUNT; i++) { var a = []; for (var j = 0; j < K; j++) { a.AS3::push(i); } s += a.length; } trace(s); })(); clockUnder(AS_FAST, "Arrays AS3 Namespace Push"); (function () { var s = 0; var COUNT = 1 * K; for (var i = 0; i < COUNT; i++) { var a = []; for (var j = 0; j < K; j++) { a.push(i); } s += a.length; } trace(s); })(); clockUnder(AS_FAST, "Arrays AS3 Prototype Push"); class C { function foo() { return 2; } } (function () { var s = 0; var COUNT = 1 * K * K; var c = new C(); for (var i = 0; i < COUNT; i++) { s += c.foo(); } trace(s); })(); clockUnder(AS_FAST, "Class Method Call"); (function () { var s = 0; var COUNT = 1 * K * K; var v : Vector.<C> = new Vector.<C>(); v.push(new C()); for (var i = 0; i < COUNT; i++) { s += v[0].foo(); } trace(s); })(); clockUnder(AS_FAST, "Class Method Call - Vector"); (function () { var s = 0; var COUNT = 1 * K * K; var v : Vector.<C> = new Vector.<C>(); var o = new C(); for (var i = 0; i < COUNT; i++) { v[0] = o; } })(); clockUnder(AS_FAST, "Set Vector"); class A { static const staticConstant = 123; const instanceConstant = 234; static var staticVar = 345; var instanceVar = 456; static function staticFunction() { var s = 0; for (var i = 0; i < 10000000; i++) { s += staticConstant; s += staticVar; } clockUnder(5000, "Access Static Constant / Var"); return s; } function instanceFunction() { var s = 0; for (var i = 0; i < 10000000; i++) { s += instanceConstant; s += instanceVar; } clockUnder(5000, "Access Instance Constant / Var"); return s; } } class B extends A { static function staticFunctionB() { var s = 0; for (var i = 0; i < 10000000; i++) { s += staticConstant; s += staticVar; } clockUnder(5000, "Access Static Constant / Var"); return s; } function instanceFunctionB() { var s = 0; for (var i = 0; i < 10000000; i++) { s += instanceConstant; s += instanceVar; } clockUnder(5000, "Access Instance Constant / Var"); return s; } } A.staticFunction(); (new A()).instanceFunction(); B.staticFunctionB(); (new B()).instanceFunctionB(); (function () { var s = 0; for (var i = 0; i < 4000000; i++) { s += -Number.MAX_VALUE; s += Number.MAX_VALUE; s += Math.abs(i); } clockUnder(5000, "Math.abs()"); return s; })(); class D { var foobar = 0; var y = 0; function D(x, y) { this.foobar = x; this.y = y; } } (function () { var s = 0; for (var i = 0; i < 1000000; i++) { s += (new D(2, 3)).foobar; s += (new D(2, 3)).y; } clockUnder(500, "Object allocation with property access"); return s; })(); }
Tweak perf timings
Tweak perf timings
ActionScript
apache-2.0
mozilla/shumway,mozilla/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,yurydelendik/shumway,mozilla/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway
efce146e0a8bf369f097a762001643ef7380c3f5
actionscript/src/com/freshplanet/ane/AirCapabilities/AirCapabilities.as
actionscript/src/com/freshplanet/ane/AirCapabilities/AirCapabilities.as
/* * Copyright 2017 FreshPlanet * 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.freshplanet.ane.AirCapabilities { import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesLowMemoryEvent; import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesOpenURLEvent; import flash.display.BitmapData; import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class AirCapabilities extends EventDispatcher { // --------------------------------------------------------------------------------------// // // // PUBLIC API // // // // --------------------------------------------------------------------------------------// /** * Is the ANE supported on the current platform */ static public function get isSupported():Boolean { return (Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0) || Capabilities.manufacturer.indexOf("Android") > -1; } /** * If <code>true</code>, logs will be displayed at the ActionScript and native level. */ public function setLogging(value:Boolean):void { _doLogging = value; if (isSupported) _extContext.call("setLogging", value); } public function get nativeLogger():ILogger { return _logger; } /** * AirCapabilities instance */ static public function get instance():AirCapabilities { return _instance != null ? _instance : new AirCapabilities() } /** * Is SMS available * @return */ public function hasSmsEnabled():Boolean { if (isSupported) return _extContext.call("hasSMS"); return false; } /** * Is Twitter available * @return */ public function hasTwitterEnabled():Boolean { if (isSupported) return _extContext.call("hasTwitter"); return false; } /** * Sends an SMS message * @param message to send * @param recipient phonenumber */ public function sendMsgWithSms(message:String, recipient:String = null):void { if (isSupported) _extContext.call("sendWithSms", message, recipient); } /** * Sends a Twitter message * @param message */ public function sendMsgWithTwitter(message:String):void { if (isSupported) _extContext.call("sendWithTwitter", message); } /** * Redirect user to Rating page * @param appId * @param appName */ public function redirecToRating(appId:String, appName:String):void { if (isSupported) _extContext.call("redirectToRating", appId, appName); } /** * Model of the device * @return */ public function getDeviceModel():String { if (isSupported) return _extContext.call("getDeviceModel") as String; return ""; } /** * Name of the machine * @return */ public function getMachineName():String { if (isSupported) return _extContext.call("getMachineName") as String; return ""; } /** * Opens the referral link URL * @param url */ public function processReferralLink(url:String):void { if (isSupported) _extContext.call("processReferralLink", url); } /** * Opens Facebook page * @param pageId id of the facebook page */ public function redirectToPageId(pageId:String):void { if (isSupported) _extContext.call("redirectToPageId", pageId); } /** * Opens Twitter account * @param twitterAccount */ public function redirectToTwitterAccount(twitterAccount:String):void { if (isSupported) _extContext.call("redirectToTwitterAccount", twitterAccount); } /** * Is posting pictures on Twitter enabled * @return */ public function canPostPictureOnTwitter():Boolean { if (isSupported) return _extContext.call("canPostPictureOnTwitter"); return false; } /** * Post new picture on Twitter * @param message * @param bitmapData */ public function postPictureOnTwitter(message:String, bitmapData:BitmapData):void { if (isSupported) _extContext.call("postPictureOnTwitter", message, bitmapData); } /** * Is Instagram enabled * @return */ public function hasInstagramEnabled():Boolean { if (isSupported) return _extContext.call("hasInstagramEnabled"); return false; } /** * Post new picture on Instagram * @param message * @param bitmapData * @param x * @param y * @param width * @param height */ public function postPictureOnInstagram(message:String, bitmapData:BitmapData, x:int, y:int, width:int, height:int):void { if (isSupported) _extContext.call("postPictureOnInstagram", message, bitmapData, x, y, width, height); } /** * Open an application (if installed on the Device) or send the player to the appstore. iOS Only * @param schemes List of schemes (String) that the application accepts. Examples : @"sms://", @"twit://". You can find schemes in http://handleopenurl.com/ * @param appStoreURL (optional) Link to the AppStore page for the Application for the player to download. URL can be generated via Apple's linkmaker (itunes.apple.com/linkmaker?) */ public function openExternalApplication(schemes:Array, appStoreURL:String = null):void { if (isSupported && Capabilities.manufacturer.indexOf("Android") == -1) _extContext.call("openExternalApplication", schemes, appStoreURL); } /** * Is opening URLs available * @param url * @return */ public function canOpenURL(url:String):Boolean { return isSupported ? _extContext.call("canOpenURL", url) as Boolean : false; } /** * Open URL * @param url */ public function openURL(url:String):void { if (canOpenURL(url)) _extContext.call("openURL", url); } /** * Opens modal app store. Available on iOS only * @param appStoreId id of the app to open a modal view to (do not include the "id" at the beginning of the number) */ public function openModalAppStoreIOS(appStoreId:String):void { if (Capabilities.manufacturer.indexOf("iOS") > -1) _extContext.call("openModalAppStore", appStoreId); } /** * Version of the operating system * @return */ public function getOSVersion():String { if (isSupported) return _extContext.call("getOSVersion") as String; return ""; } /** * @return current amount of RAM being used in bytes */ public function getCurrentMem():Number { if (!isSupported) return -1; var ret:Object = _extContext.call("getCurrentMem"); if (ret is Error) throw ret; else return ret ? ret as Number : 0; } /** * @return amount of RAM used by the VM */ public function getCurrentVirtualMem():Number { if (Capabilities.manufacturer.indexOf("iOS") == -1) return -1; var ret:Object = _extContext.call("getCurrentVirtualMem"); if (ret is Error) throw ret; else return ret ? ret as Number : 0; } /** * @return is requesting review available. Available on iOS only */ public function canRequestReview():Boolean { if (!isSupported) return false; if (Capabilities.manufacturer.indexOf("iOS") == -1) return false; return _extContext.call("canRequestReview"); } /** * Request AppStore review. Available on iOS only */ public function requestReview():void { if (!canRequestReview()) return; _extContext.call("requestReview"); } // --------------------------------------------------------------------------------------// // // // PRIVATE API // // // // --------------------------------------------------------------------------------------// static private const EXTENSION_ID:String = "com.freshplanet.ane.AirCapabilities"; static private var _instance:AirCapabilities = null; private var _extContext:ExtensionContext = null; private var _doLogging:Boolean = false; private var _logger:ILogger; /** * "private" singleton constructor */ public function AirCapabilities() { super(); if (_instance) throw new Error("singleton class, use .instance"); _extContext = ExtensionContext.createExtensionContext(EXTENSION_ID, null); _extContext.addEventListener(StatusEvent.STATUS, _handleStatusEvent); if (isSupported) _logger = new NativeLogger(_extContext); else _logger = new DefaultLogger(); _instance = this; } private function _handleStatusEvent(event:StatusEvent):void { if (event.code == "log") _doLogging && trace("[AirCapabilities] " + event.level); else if (event.code == "OPEN_URL") this.dispatchEvent(new AirCapabilitiesOpenURLEvent(AirCapabilitiesOpenURLEvent.OPEN_URL_SUCCESS, event.level)); else if (event.code == AirCapabilitiesLowMemoryEvent.LOW_MEMORY_WARNING) { var memory:Number = Number(event.level); this.dispatchEvent(new AirCapabilitiesLowMemoryEvent(event.code, memory)); } else this.dispatchEvent(event); } } }
/* * Copyright 2017 FreshPlanet * 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.freshplanet.ane.AirCapabilities { import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesLowMemoryEvent; import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesOpenURLEvent; import flash.display.BitmapData; import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class AirCapabilities extends EventDispatcher { // --------------------------------------------------------------------------------------// // // // PUBLIC API // // // // --------------------------------------------------------------------------------------// /** * Is the ANE supported on the current platform */ static public function get isSupported():Boolean { return (Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0) || Capabilities.manufacturer.indexOf("Android") > -1; } /** * If <code>true</code>, logs will be displayed at the ActionScript and native level. */ public function setLogging(value:Boolean):void { _doLogging = value; if (isSupported) _extContext.call("setLogging", value); } public function get nativeLogger():ILogger { return _logger; } /** * AirCapabilities instance */ static public function get instance():AirCapabilities { return _instance != null ? _instance : new AirCapabilities() } /** * Is SMS available * @return */ public function hasSmsEnabled():Boolean { if (isSupported) return _extContext.call("hasSMS"); return false; } /** * Is Twitter available * @return */ public function hasTwitterEnabled():Boolean { if (isSupported) return _extContext.call("hasTwitter"); return false; } /** * Sends an SMS message * @param message to send * @param recipient phonenumber */ public function sendMsgWithSms(message:String, recipient:String = null):void { if (isSupported) _extContext.call("sendWithSms", message, recipient); } /** * Sends a Twitter message * @param message */ public function sendMsgWithTwitter(message:String):void { if (isSupported) _extContext.call("sendWithTwitter", message); } /** * Redirect user to Rating page * @param appId * @param appName */ public function redirecToRating(appId:String, appName:String):void { if (isSupported) _extContext.call("redirectToRating", appId, appName); } /** * Model of the device * @return */ public function getDeviceModel():String { if (isSupported) return _extContext.call("getDeviceModel") as String; return ""; } /** * Name of the machine * @return */ public function getMachineName():String { if (isSupported) return _extContext.call("getMachineName") as String; return ""; } /** * Opens the referral link URL * @param url */ public function processReferralLink(url:String):void { if (isSupported) _extContext.call("processReferralLink", url); } /** * Opens Facebook page * @param pageId id of the facebook page */ public function redirectToPageId(pageId:String):void { if (isSupported) _extContext.call("redirectToPageId", pageId); } /** * Opens Twitter account * @param twitterAccount */ public function redirectToTwitterAccount(twitterAccount:String):void { if (isSupported) _extContext.call("redirectToTwitterAccount", twitterAccount); } /** * Is posting pictures on Twitter enabled * @return */ public function canPostPictureOnTwitter():Boolean { if (isSupported) return _extContext.call("canPostPictureOnTwitter"); return false; } /** * Post new picture on Twitter * @param message * @param bitmapData */ public function postPictureOnTwitter(message:String, bitmapData:BitmapData):void { if (isSupported) _extContext.call("postPictureOnTwitter", message, bitmapData); } /** * Is Instagram enabled * @return */ public function hasInstagramEnabled():Boolean { if (isSupported) return _extContext.call("hasInstagramEnabled"); return false; } /** * Post new picture on Instagram * @param message * @param bitmapData * @param x * @param y * @param width * @param height */ public function postPictureOnInstagram(message:String, bitmapData:BitmapData, x:int, y:int, width:int, height:int):void { if (isSupported) _extContext.call("postPictureOnInstagram", message, bitmapData, x, y, width, height); } /** * Open an application (if installed on the Device) or send the player to the appstore. iOS Only * @param schemes List of schemes (String) that the application accepts. Examples : @"sms://", @"twit://". You can find schemes in http://handleopenurl.com/ * @param appStoreURL (optional) Link to the AppStore page for the Application for the player to download. URL can be generated via Apple's linkmaker (itunes.apple.com/linkmaker?) */ public function openExternalApplication(schemes:Array, appStoreURL:String = null):void { if (isSupported && Capabilities.manufacturer.indexOf("Android") == -1) _extContext.call("openExternalApplication", schemes, appStoreURL); } /** * Is opening URLs available * @param url * @return */ public function canOpenURL(url:String):Boolean { return isSupported ? _extContext.call("canOpenURL", url) as Boolean : false; } /** * Open URL * @param url */ public function openURL(url:String):void { if (canOpenURL(url)) _extContext.call("openURL", url); } /** * Opens modal app store. Available on iOS only * @param appStoreId id of the app to open a modal view to (do not include the "id" at the beginning of the number) */ public function openModalAppStoreIOS(appStoreId:String):void { if (Capabilities.manufacturer.indexOf("iOS") > -1) _extContext.call("openModalAppStore", appStoreId); } /** * Version of the operating system * @return */ public function getOSVersion():String { if (isSupported) return _extContext.call("getOSVersion") as String; return ""; } /** * @return current amount of RAM being used in bytes */ public function getCurrentMem():Number { if (!isSupported) return -1; var ret:Object = _extContext.call("getCurrentMem"); if (ret is Error) throw ret; else return ret ? ret as Number : 0; } /** * @return amount of RAM used by the VM */ public function getCurrentVirtualMem():Number { if(!isSupported) return -1; if (Capabilities.manufacturer.indexOf("iOS") == -1) return -1; var ret:Object = _extContext.call("getCurrentVirtualMem"); if (ret is Error) throw ret; else return ret ? ret as Number : 0; } /** * @return is requesting review available. Available on iOS only */ public function canRequestReview():Boolean { if (!isSupported) return false; if (Capabilities.manufacturer.indexOf("iOS") == -1) return false; return _extContext.call("canRequestReview"); } /** * Request AppStore review. Available on iOS only */ public function requestReview():void { if (!canRequestReview()) return; _extContext.call("requestReview"); } // --------------------------------------------------------------------------------------// // // // PRIVATE API // // // // --------------------------------------------------------------------------------------// static private const EXTENSION_ID:String = "com.freshplanet.ane.AirCapabilities"; static private var _instance:AirCapabilities = null; private var _extContext:ExtensionContext = null; private var _doLogging:Boolean = false; private var _logger:ILogger; /** * "private" singleton constructor */ public function AirCapabilities() { super(); if (_instance) throw new Error("singleton class, use .instance"); _extContext = ExtensionContext.createExtensionContext(EXTENSION_ID, null); _extContext.addEventListener(StatusEvent.STATUS, _handleStatusEvent); if (isSupported) _logger = new NativeLogger(_extContext); else _logger = new DefaultLogger(); _instance = this; } private function _handleStatusEvent(event:StatusEvent):void { if (event.code == "log") _doLogging && trace("[AirCapabilities] " + event.level); else if (event.code == "OPEN_URL") this.dispatchEvent(new AirCapabilitiesOpenURLEvent(AirCapabilitiesOpenURLEvent.OPEN_URL_SUCCESS, event.level)); else if (event.code == AirCapabilitiesLowMemoryEvent.LOW_MEMORY_WARNING) { var memory:Number = Number(event.level); this.dispatchEvent(new AirCapabilitiesLowMemoryEvent(event.code, memory)); } else this.dispatchEvent(event); } } }
fix for simulator
fix for simulator
ActionScript
apache-2.0
freshplanet/ANE-AirCapabilities,freshplanet/ANE-AirCapabilities,freshplanet/ANE-AirCapabilities
03dec963f11e33f33238ec37faad8f061333d023
src/as/com/threerings/flex/ChatControl.as
src/as/com/threerings/flex/ChatControl.as
// // $Id$ package com.threerings.flex { import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.FocusEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TextEvent; import flash.ui.Keyboard; import mx.containers.HBox; import mx.core.Application; import mx.controls.TextInput; import mx.events.FlexEvent; import com.threerings.util.ArrayUtil; import com.threerings.util.StringUtil; import com.threerings.flex.CommandButton; import com.threerings.flex.CommandMenu; import com.threerings.crowd.chat.client.ChatDirector; import com.threerings.crowd.chat.data.ChatCodes; import com.threerings.crowd.util.CrowdContext; /** * The chat control widget. */ public class ChatControl extends HBox { /** * Request focus for the oldest ChatControl. */ public static function grabFocus () :void { if (_controls.length > 0) { (_controls[0] as ChatControl).setFocus(); } } public function ChatControl ( ctx :CrowdContext, sendButtonLabel :String = "send", height :Number = NaN, controlHeight :Number = NaN) { _ctx = ctx; _chatDtr = _ctx.getChatDirector(); this.height = height; styleName = "chatControl"; addChild(_txt = new ChatInput()); _txt.addEventListener(FlexEvent.ENTER, sendChat, false, 0, true); _but = new CommandButton(sendButtonLabel, sendChat); addChild(_but); if (!isNaN(controlHeight)) { _txt.height = controlHeight; _but.height = controlHeight; } addEventListener(Event.ADDED_TO_STAGE, handleAddRemove); addEventListener(Event.REMOVED_FROM_STAGE, handleAddRemove); } /** * Request focus to this chat control. */ override public function setFocus () :void { _txt.setFocus(); } /** * Enables or disables our chat input. */ public function setEnabled (enabled :Boolean) :void { _txt.enabled = enabled; _but.enabled = enabled; } /** * Configures the chat director to which we should send our chat. Pass null to restore our * default chat director. */ public function setChatDirector (chatDtr :ChatDirector) :void { _chatDtr = (chatDtr == null) ? _ctx.getChatDirector() : chatDtr; } /** * Configures the background color of the text entry area. */ public function setChatColor (color :int) :void { _txt.setStyle("backgroundColor", color); } /** * Handles FlexEvent.ENTER and the action from the send button. */ protected function sendChat (... ignored) :void { var message :String = StringUtil.trim(_txt.text); if ("" == message) { return; } var result :String = _chatDtr.requestChat(null, message, true); if (result != ChatCodes.SUCCESS) { _chatDtr.displayFeedback(null, result); return; } // if there was no error, clear the entry area in prep for the next entry event _txt.text = ""; } /** * Handles Event.ADDED_TO_STAGE and Event.REMOVED_FROM_STAGE. */ protected function handleAddRemove (event :Event) :void { if (event.type == Event.ADDED_TO_STAGE) { // set up any already-configured text _txt.text = _curLine; // request focus callLater(_txt.setFocus); _controls.push(this); } else { _curLine = _txt.text; ArrayUtil.removeAll(_controls, this); } } /** Our client-side context. */ protected var _ctx :CrowdContext; /** The director to which we are sending chat requests. */ protected var _chatDtr :ChatDirector; /** The place where the user may enter chat. */ protected var _txt :ChatInput; /** The button for sending chat. */ protected var _but :CommandButton; /** An array of the currently shown-controls. */ protected static var _controls :Array = []; /** The preserved current line of text when traversing history or carried between instances of * ChatControl. */ protected static var _curLine :String; } }
// // $Id$ package com.threerings.flex { import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.FocusEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TextEvent; import flash.ui.Keyboard; import mx.containers.HBox; import mx.core.Application; import mx.controls.TextInput; import mx.events.FlexEvent; import com.threerings.util.ArrayUtil; import com.threerings.util.StringUtil; import com.threerings.flex.CommandButton; import com.threerings.flex.CommandMenu; import com.threerings.crowd.chat.client.ChatDirector; import com.threerings.crowd.chat.data.ChatCodes; import com.threerings.crowd.util.CrowdContext; /** * The chat control widget. */ public class ChatControl extends HBox { /** * Request focus for the oldest ChatControl. */ public static function grabFocus () :void { if (_controls.length > 0) { (_controls[0] as ChatControl).setFocus(); } } public function ChatControl ( ctx :CrowdContext, sendButtonLabel :String = "send", height :Number = NaN, controlHeight :Number = NaN) { _ctx = ctx; _chatDtr = _ctx.getChatDirector(); this.height = height; styleName = "chatControl"; addChild(_txt = new ChatInput()); _txt.addEventListener(FlexEvent.ENTER, sendChat, false, 0, true); _but = new CommandButton(sendButtonLabel, sendChat); addChild(_but); if (!isNaN(controlHeight)) { _txt.height = controlHeight; _but.height = controlHeight; } addEventListener(Event.ADDED_TO_STAGE, handleAddRemove); addEventListener(Event.REMOVED_FROM_STAGE, handleAddRemove); } /** * Provides access to the text field we use to accept chat. */ public function get chatInput () :ChatInput { return _txt; } /** * Request focus to this chat control. */ override public function setFocus () :void { _txt.setFocus(); } /** * Enables or disables our chat input. */ public function setEnabled (enabled :Boolean) :void { _txt.enabled = enabled; _but.enabled = enabled; } /** * Configures the chat director to which we should send our chat. Pass null to restore our * default chat director. */ public function setChatDirector (chatDtr :ChatDirector) :void { _chatDtr = (chatDtr == null) ? _ctx.getChatDirector() : chatDtr; } /** * Configures the background color of the text entry area. */ public function setChatColor (color :int) :void { _txt.setStyle("backgroundColor", color); } /** * Handles FlexEvent.ENTER and the action from the send button. */ protected function sendChat (... ignored) :void { var message :String = StringUtil.trim(_txt.text); if ("" == message) { return; } var result :String = _chatDtr.requestChat(null, message, true); if (result != ChatCodes.SUCCESS) { _chatDtr.displayFeedback(null, result); return; } // if there was no error, clear the entry area in prep for the next entry event _txt.text = ""; } /** * Handles Event.ADDED_TO_STAGE and Event.REMOVED_FROM_STAGE. */ protected function handleAddRemove (event :Event) :void { if (event.type == Event.ADDED_TO_STAGE) { // set up any already-configured text _txt.text = _curLine; // request focus callLater(_txt.setFocus); _controls.push(this); } else { _curLine = _txt.text; ArrayUtil.removeAll(_controls, this); } } /** Our client-side context. */ protected var _ctx :CrowdContext; /** The director to which we are sending chat requests. */ protected var _chatDtr :ChatDirector; /** The place where the user may enter chat. */ protected var _txt :ChatInput; /** The button for sending chat. */ protected var _but :CommandButton; /** An array of the currently shown-controls. */ protected static var _controls :Array = []; /** The preserved current line of text when traversing history or carried between instances of * ChatControl. */ protected static var _curLine :String; } }
Add an accessor for our chatInput field.
Add an accessor for our chatInput field. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@446 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
6dccc4c5932e83061c877fa3d4a6483ef78961d2
tests/GAv4/com/google/analytics/core/BrowserInfoTest.as
tests/GAv4/com/google/analytics/core/BrowserInfoTest.as
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. */ package com.google.analytics.core { import library.ASTUce.framework.TestCase; import com.google.analytics.utils.Environment; import com.google.analytics.utils.FakeEnvironment; import com.google.analytics.utils.Variables; import com.google.analytics.utils.Version; import com.google.analytics.v4.Configuration; public class BrowserInfoTest extends TestCase { private var _config:Configuration; private var _browserInfo0:BrowserInfo; private var _env0:Environment; public function BrowserInfoTest(name:String="") { super(name); } public function testHitId():void { assertEquals(1,1); } public function setUp():void { _config = new Configuration(); _env0 = new FakeEnvironment("",null,"","","","","","",new Version(9,0,115,0),"en-GB","UTF-8","","","",null,800,600,"24"); _browserInfo0 = new BrowserInfo( _config, _env0 ); } public function testFlashVersion():void { assertEquals( "9.0 r115", _browserInfo0.utmfl ); } public function testScreenInfo():void { assertEquals( "800x600", _browserInfo0.utmsr ); assertEquals( "24-bit", _browserInfo0.utmsc ); } public function testLangInfo():void { assertEquals( "en-gb", _browserInfo0.utmul ); assertEquals( "UTF-8", _browserInfo0.utmcs ); } public function testToVariables():void { var vars:Variables = _browserInfo0.toVariables(); assertEquals( "UTF-8", vars.utmcs ); assertEquals( "800x600", vars.utmsr ); assertEquals( "24-bit", vars.utmsc ); assertEquals( "en-gb", vars.utmul ); assertEquals( "0", vars.utmje ); assertEquals( "9.0 r115", vars.utmfl ); } public function testToURLString():void { var vars:Variables = _browserInfo0.toVariables(); var varsA:Variables = new Variables(); varsA.URIencode = true; varsA.utmcs = vars.utmcs; assertEquals( "utmcs=UTF-8", varsA.toString() ); var varsB:Variables = new Variables(); varsB.URIencode = true; varsB.utmsr = vars.utmsr; assertEquals( "utmsr=800x600", varsB.toString() ); var varsC:Variables = new Variables(); varsC.URIencode = true; varsC.utmsc = vars.utmsc; assertEquals( "utmsc=24-bit", varsC.toString() ); var varsD:Variables = new Variables(); varsD.URIencode = true; varsD.utmul = vars.utmul; assertEquals( "utmul=en-gb", varsD.toString() ); var varsE:Variables = new Variables(); varsE.URIencode = true; varsE.utmje = vars.utmje; assertEquals( "utmje=0", varsE.toString() ); var varsF:Variables = new Variables(); varsF.URIencode = true; varsF.utmfl = vars.utmfl; assertEquals( "utmfl=9.0%20r115", varsF.toString() ); } } }
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. */ package com.google.analytics.core { import com.google.analytics.utils.Environment; import com.google.analytics.utils.FakeEnvironment; import com.google.analytics.utils.Variables; import com.google.analytics.v4.Configuration; import core.version; import library.ASTUce.framework.TestCase; public class BrowserInfoTest extends TestCase { private var _config:Configuration; private var _browserInfo0:BrowserInfo; private var _env0:Environment; public function BrowserInfoTest(name:String="") { super(name); } public function testHitId():void { assertEquals(1,1); } public function setUp():void { _config = new Configuration(); _env0 = new FakeEnvironment("",null,"","","","","","",new version(9,0,115,0),"en-GB","UTF-8","","","",null,800,600,"24"); _browserInfo0 = new BrowserInfo( _config, _env0 ); } public function testFlashVersion():void { assertEquals( "9.0 r115", _browserInfo0.utmfl ); } public function testScreenInfo():void { assertEquals( "800x600", _browserInfo0.utmsr ); assertEquals( "24-bit", _browserInfo0.utmsc ); } public function testLangInfo():void { assertEquals( "en-gb", _browserInfo0.utmul ); assertEquals( "UTF-8", _browserInfo0.utmcs ); } public function testToVariables():void { var vars:Variables = _browserInfo0.toVariables(); assertEquals( "UTF-8", vars.utmcs ); assertEquals( "800x600", vars.utmsr ); assertEquals( "24-bit", vars.utmsc ); assertEquals( "en-gb", vars.utmul ); assertEquals( "0", vars.utmje ); assertEquals( "9.0 r115", vars.utmfl ); } public function testToURLString():void { var vars:Variables = _browserInfo0.toVariables(); var varsA:Variables = new Variables(); varsA.URIencode = true; varsA.utmcs = vars.utmcs; assertEquals( "utmcs=UTF-8", varsA.toString() ); var varsB:Variables = new Variables(); varsB.URIencode = true; varsB.utmsr = vars.utmsr; assertEquals( "utmsr=800x600", varsB.toString() ); var varsC:Variables = new Variables(); varsC.URIencode = true; varsC.utmsc = vars.utmsc; assertEquals( "utmsc=24-bit", varsC.toString() ); var varsD:Variables = new Variables(); varsD.URIencode = true; varsD.utmul = vars.utmul; assertEquals( "utmul=en-gb", varsD.toString() ); var varsE:Variables = new Variables(); varsE.URIencode = true; varsE.utmje = vars.utmje; assertEquals( "utmje=0", varsE.toString() ); var varsF:Variables = new Variables(); varsF.URIencode = true; varsF.utmfl = vars.utmfl; assertEquals( "utmfl=9.0%20r115", varsF.toString() ); } } }
replace class Version by core.version
replace class Version by core.version
ActionScript
apache-2.0
Vigmar/gaforflash,DimaBaliakin/gaforflash,Vigmar/gaforflash,jeremy-wischusen/gaforflash,Miyaru/gaforflash,jeremy-wischusen/gaforflash,jisobkim/gaforflash,jisobkim/gaforflash,dli-iclinic/gaforflash,drflash/gaforflash,DimaBaliakin/gaforflash,mrthuanvn/gaforflash,Miyaru/gaforflash,drflash/gaforflash,soumavachakraborty/gaforflash,dli-iclinic/gaforflash,soumavachakraborty/gaforflash,mrthuanvn/gaforflash
fa6a2663a7250870c121fa4d8ad5cb62e949df62
src/flexlib/containers/WindowShade.as
src/flexlib/containers/WindowShade.as
/* Copyright (c) 2007 FlexLib Contributors. See: http://code.google.com/p/flexlib/wiki/ProjectContributors 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 flexlib.containers { import flash.events.MouseEvent; import mx.controls.Button; import mx.core.EdgeMetrics; import mx.core.IFactory; import mx.core.LayoutContainer; import mx.core.ScrollPolicy; import mx.effects.Resize; import mx.effects.effectClasses.ResizeInstance; import mx.events.EffectEvent; import mx.styles.CSSStyleDeclaration; import mx.styles.StyleManager; import mx.utils.StringUtil; /** * This is the icon displayed on the headerButton when the WindowShade is in the open state. */ [Style(name="openIcon", type="Class", inherit="no")] /** * This is the icon displayed on the headerButton when the WindowShade is in the closed state. */ [Style(name="closeIcon", type="Class", inherit="no")] /** * The duration of the WindowShade opening transition, in milliseconds. The value 0 specifies no transition. * * @default 250 */ [Style(name="openDuration", type="Number", format="Time", inherit="no")] /** * The duration of the WindowShade closing transition, in milliseconds. The value 0 specifies no transition. * * @default 250 */ [Style(name="closeDuration", type="Number", format="Time", inherit="no")] /** * The class from which the headerButton will be instantiated. Must be mx.controls.Button * or a subclass. * * @default mx.controls.Button */ [Style(name="headerClass", type="Class", inherit="no")] /** * Name of CSS style declaration that specifies styles for the headerButton. */ [Style(name="headerStyleName", type="String", inherit="no")] /** * Alignment of text on the headerButton. The value set for this style is used as * the textAlign style on the headerButton. Valid values are "left", "center" and "right". * * @default "right" */ [Style(name="headerTextAlign", type="String", inherit="no")] /** * If true, the value of the headerButton's <code>toggle</code> property will be set to true; * otherwise the <code>toggle</code> property will be left in its default state. * * @default false */ [Style(name="toggleHeader", type="Boolean", inherit="no")] /** * This control displays a button, which when clicked, will cause a panel to "unroll" beneath * it like a windowshade being pulled down; or if the panel is already displayed it * will be "rolled up" like a windowshade being rolled up. When multiple WindowShades are stacked * in a VBox, the result will be similar to an mx.containers.Accordian container, except that multiple * WindowShades can be opened simultaneously whereas an Accordian acts like a tab navigator, with only * one panel visible at a time. */ public class WindowShade extends LayoutContainer { [Embed (source="../assets/assets.swf", symbol="right_arrow")] private static var DEFAULT_CLOSE_ICON:Class; [Embed (source="../assets/assets.swf", symbol="down_arrow")] private static var DEFAULT_OPEN_ICON:Class; private static var styleDefaults:Object = { openDuration:250 ,closeDuration:250 ,paddingTop:10 ,headerClass:Button ,headerTextAlign:"left" ,toggleHeader:false ,headerStyleName:null ,closeIcon:DEFAULT_CLOSE_ICON ,openIcon:DEFAULT_OPEN_ICON }; private static var classConstructed:Boolean = constructClass(); private static function constructClass():Boolean { var css:CSSStyleDeclaration = StyleManager.getStyleDeclaration("WindowShade") var changed:Boolean = false; if(!css) { // If there is no CSS definition for WindowShade, // then create one and set the default value. css = new CSSStyleDeclaration(); changed = true; } // make sure we have a valid values for each style. If not, set the defaults. for(var styleProp:String in styleDefaults) { if(!StyleManager.isValidStyleValue(css.getStyle(styleProp))) { css.setStyle(styleProp, styleDefaults[styleProp]); changed = true; } } if(changed) { StyleManager.setStyleDeclaration("WindowShade", css, true); } return true; } /** * @private * A reference to the Button that will be used for the header. Must always be a Button or subclass of Button. */ private var _headerButton:Button = null; private var headerChanged:Boolean; /** * @private * The header renderer factory that will get used to create the header. */ private var _headerRenderer:IFactory; /** * To control the header used on the WindowShade component you can either set the <code>headerClass</code> or the * <code>headerRenderer</code>. The <code>headerRenderer</code> works similar to the itemRenderer of a List control. * You can set this using MXML using any Button control. This would let you customize things like button skin. You could * even combine this with the CanvasButton component to make complex headers. */ public function set headerRenderer(value:IFactory):void { _headerRenderer = value; headerChanged = true; invalidateProperties(); } public function get headerRenderer():IFactory { return _headerRenderer; } /** * @private * Boolean dirty flag to let us know if we need to change the icon in the commitProperties method. */ private var _openedChanged:Boolean = false; public function WindowShade() { super(); //default scroll policies are off this.verticalScrollPolicy = ScrollPolicy.OFF; this.horizontalScrollPolicy = ScrollPolicy.OFF; addEventListener(EffectEvent.EFFECT_END, onEffectEnd); } protected function createOrReplaceHeaderButton():void { if(_headerButton) { _headerButton.removeEventListener(MouseEvent.CLICK, headerButton_clickHandler); if(rawChildren.contains(_headerButton)) { rawChildren.removeChild(_headerButton); } } if(_headerRenderer) { _headerButton = _headerRenderer.newInstance() as Button; } else { var headerClass:Class = getStyle("headerClass"); _headerButton = new headerClass(); } applyHeaderButtonStyles(_headerButton); _headerButton.addEventListener(MouseEvent.CLICK, headerButton_clickHandler); rawChildren.addChild(_headerButton); } protected function applyHeaderButtonStyles(button:Button):void { button.setStyle("textAlign", getStyle("headerTextAlign")); var headerStyleName:String = getStyle("headerStyleName"); if(headerStyleName) { headerStyleName = StringUtil.trim(headerStyleName); button.styleName = headerStyleName; } button.toggle = getStyle("toggleHeader"); button.label = label; if(_opened) { button.setStyle('icon', getStyle("openIcon")); } else { button.setStyle('icon', getStyle("closeIcon")); } if(button.toggle) { button.selected = _opened; } } /** * @private */ override public function set label(value:String):void { super.label = value; if(_headerButton) _headerButton.label = value; } /** * @private */ private var _opened:Boolean = true; /** * Sets or gets the state of this WindowShade, either opened (true) or closed (false). */ public function get opened():Boolean { return _opened; } private var _headerLocation:String = "top"; [Bindable] [Inspectable(enumeration="top,bottom", defaultValue="top")] /** * Specifies where the header button is placed relative tot he content of this WindowShade. Possible * values are <code>top</code> and <code>bottom</code>. */ public function set headerLocation(value:String):void { _headerLocation = value; invalidateSize(); invalidateDisplayList(); } public function get headerLocation():String { return _headerLocation; } /** * @private */ [Bindable] public function set opened(value:Boolean):void { var old:Boolean = _opened; _opened = value; _openedChanged = _openedChanged || old != _opened; if(_openedChanged && initialized) { measure(); runResizeEffect(); invalidateProperties(); } } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); if(styleProp == "headerClass") { headerChanged = true; invalidateProperties(); } else if(styleProp == "headerStyleName" || styleProp == "headerTextAlign" || styleProp == "toggleHeader" || styleProp == "openIcon" || styleProp == "closeIcon") { applyHeaderButtonStyles(_headerButton); } invalidateDisplayList(); } /** * @private */ override protected function createChildren():void { super.createChildren(); createOrReplaceHeaderButton(); } /** * @private */ override protected function commitProperties():void { super.commitProperties(); if(headerChanged) { createOrReplaceHeaderButton(); headerChanged = false; } if(_openedChanged) { if(_opened) { _headerButton.setStyle('icon', getStyle("openIcon")); } else { _headerButton.setStyle('icon', getStyle("closeIcon")); } _openedChanged = false; } } /** * @private */ override protected function updateDisplayList(w:Number, h:Number):void { super.updateDisplayList(w, h); if(_headerLocation == "top") { _headerButton.move(0,0); } else if(_headerLocation == "bottom") { _headerButton.move(0,h - _headerButton.getExplicitOrMeasuredHeight()); } _headerButton.setActualSize(w, _headerButton.getExplicitOrMeasuredHeight()); } /** * @private */ private var _viewMetrics:EdgeMetrics; override public function get viewMetrics():EdgeMetrics { // The getViewMetrics function needs to return its own object. // Rather than allocating a new one each time, we'll allocate // one once and then hold a pointer to it. if (!_viewMetrics) _viewMetrics = new EdgeMetrics(0, 0, 0, 0); var vm:EdgeMetrics = _viewMetrics; var o:EdgeMetrics = super.viewMetrics; vm.left = o.left; vm.top = o.top; vm.right = o.right; vm.bottom = o.bottom; var hHeight:Number = _headerButton.getExplicitOrMeasuredHeight(); if (!isNaN(hHeight)) { if(_headerLocation == "top") { vm.top += hHeight; } else if(_headerLocation == "bottom") { vm.bottom += hHeight; } } return vm; } /** * @private */ override protected function measure():void { super.measure(); if(_opened) { //if this WindowShade is opened then we have to include the height of the header button //measuredHeight += _headerButton.getExplicitOrMeasuredHeight(); } else { //if the WindowShade is closed then the height is only the height of the header button measuredHeight = _headerButton.getExplicitOrMeasuredHeight(); } } /** * @private */ private var resize:Resize; /** * @private */ private var resizeInstance:ResizeInstance; /** * @private */ private var resetExplicitHeight:Boolean; /** * @private */ protected function runResizeEffect():void { if(resize && resize.isPlaying) { // before the call to end() returns, the onEffectEnd method will have been called // for the currently playing resize. resize.end(); } var duration:Number = _opened ? getStyle("openDuration") : getStyle("closeDuration"); if(duration == 0) { this.setActualSize(getExplicitOrMeasuredWidth(), measuredHeight); invalidateSize(); invalidateDisplayList(); return; } resize = new Resize(this); // If this WindowShade currently has no explicit height set, we want to // restore that state when the resize effect is finished, in the onEffectEnd method. // If it does, then the final height set by the effect will be retained. resetExplicitHeight = isNaN(explicitHeight); resize.heightTo = Math.min(maxHeight, measuredHeight); resize.duration = duration; var instances:Array = resize.play(); if(instances && instances.length) { resizeInstance = instances[0]; } } /** * @private */ protected function onEffectEnd(evt:EffectEvent):void { // Make sure this is our effect ending if(evt.effectInstance == resizeInstance) { if(resetExplicitHeight) explicitHeight = NaN; resizeInstance = null; } } /** * @private */ protected function headerButton_clickHandler(event:MouseEvent):void { opened = !_opened; } } }
/* Copyright (c) 2007 FlexLib Contributors. See: http://code.google.com/p/flexlib/wiki/ProjectContributors 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 flexlib.containers { import flash.events.MouseEvent; import mx.controls.Button; import mx.core.EdgeMetrics; import mx.core.IFactory; import mx.core.LayoutContainer; import mx.core.ScrollPolicy; import mx.effects.Resize; import mx.effects.effectClasses.ResizeInstance; import mx.events.EffectEvent; import mx.styles.CSSStyleDeclaration; import mx.styles.StyleManager; import mx.utils.StringUtil; /** * This is the icon displayed on the headerButton when the WindowShade is in the open state. */ [Style(name="openIcon", type="Class", inherit="no")] /** * This is the icon displayed on the headerButton when the WindowShade is in the closed state. */ [Style(name="closeIcon", type="Class", inherit="no")] /** * The duration of the WindowShade opening transition, in milliseconds. The value 0 specifies no transition. * * @default 250 */ [Style(name="openDuration", type="Number", format="Time", inherit="no")] /** * The duration of the WindowShade closing transition, in milliseconds. The value 0 specifies no transition. * * @default 250 */ [Style(name="closeDuration", type="Number", format="Time", inherit="no")] /** * The class from which the headerButton will be instantiated. Must be mx.controls.Button * or a subclass. * * @default mx.controls.Button */ [Style(name="headerClass", type="Class", inherit="no")] /** * Name of CSS style declaration that specifies styles for the headerButton. */ [Style(name="headerStyleName", type="String", inherit="no")] /** * Alignment of text on the headerButton. The value set for this style is used as * the textAlign style on the headerButton. Valid values are "left", "center" and "right". * * @default "right" */ [Style(name="headerTextAlign", type="String", inherit="no")] /** * If true, the value of the headerButton's <code>toggle</code> property will be set to true; * otherwise the <code>toggle</code> property will be left in its default state. * * @default false */ [Style(name="toggleHeader", type="Boolean", inherit="no")] /** * This control displays a button, which when clicked, will cause a panel to "unroll" beneath * it like a windowshade being pulled down; or if the panel is already displayed it * will be "rolled up" like a windowshade being rolled up. When multiple WindowShades are stacked * in a VBox, the result will be similar to an mx.containers.Accordian container, except that multiple * WindowShades can be opened simultaneously whereas an Accordian acts like a tab navigator, with only * one panel visible at a time. */ public class WindowShade extends LayoutContainer { [Embed (source="../assets/assets.swf", symbol="right_arrow")] private static var DEFAULT_CLOSE_ICON:Class; [Embed (source="../assets/assets.swf", symbol="down_arrow")] private static var DEFAULT_OPEN_ICON:Class; private static var styleDefaults:Object = { openDuration:250 ,closeDuration:250 ,paddingTop:10 ,headerClass:Button ,headerTextAlign:"left" ,toggleHeader:false ,headerStyleName:null ,closeIcon:DEFAULT_CLOSE_ICON ,openIcon:DEFAULT_OPEN_ICON }; private static var classConstructed:Boolean = constructClass(); private static function constructClass():Boolean { var css:CSSStyleDeclaration = StyleManager.getStyleDeclaration("WindowShade") var changed:Boolean = false; if(!css) { // If there is no CSS definition for WindowShade, // then create one and set the default value. css = new CSSStyleDeclaration(); changed = true; } // make sure we have a valid values for each style. If not, set the defaults. for(var styleProp:String in styleDefaults) { if(!StyleManager.isValidStyleValue(css.getStyle(styleProp))) { css.setStyle(styleProp, styleDefaults[styleProp]); changed = true; } } if(changed) { StyleManager.setStyleDeclaration("WindowShade", css, true); } return true; } /** * @private * A reference to the Button that will be used for the header. Must always be a Button or subclass of Button. */ private var _headerButton:Button = null; private var headerChanged:Boolean; /** * @private * The header renderer factory that will get used to create the header. */ private var _headerRenderer:IFactory; /** * To control the header used on the WindowShade component you can either set the <code>headerClass</code> or the * <code>headerRenderer</code>. The <code>headerRenderer</code> works similar to the itemRenderer of a List control. * You can set this using MXML using any Button control. This would let you customize things like button skin. You could * even combine this with the CanvasButton component to make complex headers. */ public function set headerRenderer(value:IFactory):void { _headerRenderer = value; headerChanged = true; invalidateProperties(); } public function get headerRenderer():IFactory { return _headerRenderer; } /** * @private * Boolean dirty flag to let us know if we need to change the icon in the commitProperties method. */ private var _openedChanged:Boolean = false; public function WindowShade() { super(); //default scroll policies are off this.verticalScrollPolicy = ScrollPolicy.OFF; this.horizontalScrollPolicy = ScrollPolicy.OFF; addEventListener(EffectEvent.EFFECT_END, onEffectEnd); } protected function createOrReplaceHeaderButton():void { if(_headerButton) { _headerButton.removeEventListener(MouseEvent.CLICK, headerButton_clickHandler); if(rawChildren.contains(_headerButton)) { rawChildren.removeChild(_headerButton); } } if(_headerRenderer) { _headerButton = _headerRenderer.newInstance() as Button; } else { var headerClass:Class = getStyle("headerClass"); _headerButton = new headerClass(); } applyHeaderButtonStyles(_headerButton); _headerButton.addEventListener(MouseEvent.CLICK, headerButton_clickHandler); rawChildren.addChild(_headerButton); // Fix for Issue #85 _headerButton.tabEnabled = false; } protected function applyHeaderButtonStyles(button:Button):void { button.setStyle("textAlign", getStyle("headerTextAlign")); var headerStyleName:String = getStyle("headerStyleName"); if(headerStyleName) { headerStyleName = StringUtil.trim(headerStyleName); button.styleName = headerStyleName; } button.toggle = getStyle("toggleHeader"); button.label = label; if(_opened) { button.setStyle('icon', getStyle("openIcon")); } else { button.setStyle('icon', getStyle("closeIcon")); } if(button.toggle) { button.selected = _opened; } } /** * @private */ override public function set label(value:String):void { super.label = value; if(_headerButton) _headerButton.label = value; } /** * @private */ private var _opened:Boolean = true; /** * Sets or gets the state of this WindowShade, either opened (true) or closed (false). */ public function get opened():Boolean { return _opened; } private var _headerLocation:String = "top"; [Bindable] [Inspectable(enumeration="top,bottom", defaultValue="top")] /** * Specifies where the header button is placed relative tot he content of this WindowShade. Possible * values are <code>top</code> and <code>bottom</code>. */ public function set headerLocation(value:String):void { _headerLocation = value; invalidateSize(); invalidateDisplayList(); } public function get headerLocation():String { return _headerLocation; } /** * @private */ [Bindable] public function set opened(value:Boolean):void { var old:Boolean = _opened; _opened = value; _openedChanged = _openedChanged || old != _opened; if(_openedChanged && initialized) { measure(); runResizeEffect(); invalidateProperties(); } } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); if(styleProp == "headerClass") { headerChanged = true; invalidateProperties(); } else if(styleProp == "headerStyleName" || styleProp == "headerTextAlign" || styleProp == "toggleHeader" || styleProp == "openIcon" || styleProp == "closeIcon") { applyHeaderButtonStyles(_headerButton); } invalidateDisplayList(); } /** * @private */ override protected function createChildren():void { super.createChildren(); createOrReplaceHeaderButton(); } /** * @private */ override protected function commitProperties():void { super.commitProperties(); if(headerChanged) { createOrReplaceHeaderButton(); headerChanged = false; } if(_openedChanged) { if(_opened) { _headerButton.setStyle('icon', getStyle("openIcon")); } else { _headerButton.setStyle('icon', getStyle("closeIcon")); } _openedChanged = false; } } /** * @private */ override protected function updateDisplayList(w:Number, h:Number):void { super.updateDisplayList(w, h); if(_headerLocation == "top") { _headerButton.move(0,0); } else if(_headerLocation == "bottom") { _headerButton.move(0,h - _headerButton.getExplicitOrMeasuredHeight()); } _headerButton.setActualSize(w, _headerButton.getExplicitOrMeasuredHeight()); } /** * @private */ private var _viewMetrics:EdgeMetrics; override public function get viewMetrics():EdgeMetrics { // The getViewMetrics function needs to return its own object. // Rather than allocating a new one each time, we'll allocate // one once and then hold a pointer to it. if (!_viewMetrics) _viewMetrics = new EdgeMetrics(0, 0, 0, 0); var vm:EdgeMetrics = _viewMetrics; var o:EdgeMetrics = super.viewMetrics; vm.left = o.left; vm.top = o.top; vm.right = o.right; vm.bottom = o.bottom; var hHeight:Number = _headerButton.getExplicitOrMeasuredHeight(); if (!isNaN(hHeight)) { if(_headerLocation == "top") { vm.top += hHeight; } else if(_headerLocation == "bottom") { vm.bottom += hHeight; } } return vm; } /** * @private */ override protected function measure():void { super.measure(); if(_opened) { //if this WindowShade is opened then we have to include the height of the header button //measuredHeight += _headerButton.getExplicitOrMeasuredHeight(); } else { //if the WindowShade is closed then the height is only the height of the header button measuredHeight = _headerButton.getExplicitOrMeasuredHeight(); } } /** * @private */ private var resize:Resize; /** * @private */ private var resizeInstance:ResizeInstance; /** * @private */ private var resetExplicitHeight:Boolean; /** * @private */ protected function runResizeEffect():void { if(resize && resize.isPlaying) { // before the call to end() returns, the onEffectEnd method will have been called // for the currently playing resize. resize.end(); } var duration:Number = _opened ? getStyle("openDuration") : getStyle("closeDuration"); if(duration == 0) { this.setActualSize(getExplicitOrMeasuredWidth(), measuredHeight); invalidateSize(); invalidateDisplayList(); return; } resize = new Resize(this); // If this WindowShade currently has no explicit height set, we want to // restore that state when the resize effect is finished, in the onEffectEnd method. // If it does, then the final height set by the effect will be retained. resetExplicitHeight = isNaN(explicitHeight); resize.heightTo = Math.min(maxHeight, measuredHeight); resize.duration = duration; var instances:Array = resize.play(); if(instances && instances.length) { resizeInstance = instances[0]; } } /** * @private */ protected function onEffectEnd(evt:EffectEvent):void { // Make sure this is our effect ending if(evt.effectInstance == resizeInstance) { if(resetExplicitHeight) explicitHeight = NaN; resizeInstance = null; } } /** * @private */ protected function headerButton_clickHandler(event:MouseEvent):void { opened = !_opened; } } }
Fix for Issue #85.
Fix for Issue #85.
ActionScript
mit
Acidburn0zzz/flexlib
a5a8c17714bdb7b5e3f74440d62d52950542321f
src/com/merlinds/miracle_tool/controllers/converters/AnimationConverterCommand.as
src/com/merlinds/miracle_tool/controllers/converters/AnimationConverterCommand.as
/** * User: MerlinDS * Date: 16.07.2014 * Time: 22:22 */ package com.merlinds.miracle_tool.controllers.converters { import com.merlinds.debug.log; import com.merlinds.miracle_tool.events.ActionEvent; import com.merlinds.miracle_tool.events.EditorEvent; import com.merlinds.miracle_tool.models.ProjectModel; import com.merlinds.miracle_tool.models.vo.AnimSourcesVO; import com.merlinds.miracle_tool.models.vo.AnimationVO; import com.merlinds.miracle_tool.models.vo.FrameVO; import com.merlinds.miracle_tool.models.vo.SourceVO; import com.merlinds.miracle_tool.models.vo.TimelineVO; import com.merlinds.miracle_tool.services.ActionService; import com.merlinds.miracle_tool.utils.XMLConverters; import flash.debugger.enterDebugger; import flash.geom.Matrix; import flash.geom.Point; import org.robotlegs.mvcs.Command; public class AnimationConverterCommand extends Command { [Inject] public var projectModel:ProjectModel; [Inject] public var actionService:ActionService; [Inject] public var event:ActionEvent; private var _inputLayers:Array; private var _animation:AnimationVO; private var _namespace:Namespace; //============================================================================== //{region PUBLIC METHODS public function AnimationConverterCommand() { super(); } override public function execute():void { log(this, "execute"); //search for animation in file var data:AnimSourcesVO = this.event.body as AnimSourcesVO; var source:SourceVO = this.projectModel.selected; if(source == null)source = this.projectModel.inProgress; var n:int = source.animations.length; for(var i:int = 0; i < n; i++){ var animation:AnimationVO = source.animations[i]; for(var sourceName:String in data){ if(animation.name + '.xml' == sourceName){ _animation = animation; _animation.name = animation.name; _animation.file = this.projectModel.tempFile; _animation.added = true; this.prepareData4Animation(data[sourceName] as XML); this.convert2Animation(); } } } this.dispatch(new EditorEvent(EditorEvent.ANIMATION_ATTACHED, source.name)); } //} endregion PUBLIC METHODS =================================================== //============================================================================== //{region PRIVATE\PROTECTED METHODS private function prepareData4Animation(xml:XML):void { _namespace = new Namespace(xml.inScopeNamespaces()[0], xml.inScopeNamespaces()[1]); default xml namespace = _namespace; xml.normalize(); var layers:XMLList = xml.timeline.DOMTimeline.layers.children(); var n:int = layers.length(); //get all layers and prepare for converting _inputLayers = []; for(var i:int = 0; i < n; i++){ var layer:XML = layers[i]; if(layer.@layerType != "folder"){ //exclude Folders from list _inputLayers = _inputLayers.concat( this.readSourceLayer(layer) ); } } } private function convert2Animation():void { var n:int = _inputLayers.length; _animation.timelines.length = n; for(var i:int = 0; i < n; i++){ var layer:Array = _inputLayers[i]; var timeline:TimelineVO = new TimelineVO(); var m:int = layer.length; timeline.frames.length = m; for(var j:int = 0; j < m; j++){ timeline.frames[j] = layer[j]; } _animation.timelines[i] = timeline; } } private function readSourceLayer(layer:XML):Array { default xml namespace = _namespace; /* * This array will contains layer that was separated from current source layer * Will contains minimum one layer. * In case when source layer contains more than one symbol, * this layer will be separated to N output layers, where N - count of symbols on source layer */ //get all frames of the source layer var frames:XMLList = layer.frames.DOMFrame; var separatedLayer:Array = this.createEmptyLayers(frames); var m:int = separatedLayer.length; var n:int = frames.length(); for(var i:int = 0; i < n; i++){ var frame:XML = frames[i]; //read all symbols on the frame var symbols:XMLList = frame.elements.DOMSymbolInstance; var o:int = symbols.length();//number of symbols for(var j:int = 0; j < m; j++){ var frameVO:FrameVO = new FrameVO(frame.@index, frame.@duration); if(j < o){ var symbol:XML = symbols[j]; //convert symbol to frame object and save it to sublayer frameVO.type = frame.@tweenType; this.parseSymbols(symbol, frameVO); } separatedLayer[j][i] = frameVO; } } return separatedLayer; } private function createEmptyLayers(frames:XMLList):Array { default xml namespace = _namespace; var separatedLayer:Array = []; var n:int = frames.length(); for(var i:int = 0; i < n; i++){ var frame:XML = frames[i]; //read all symbols on the frame var symbols:XMLList = frame.elements.DOMSymbolInstance; var m:int = symbols.length(); for(var j:int = 0; j < m; j++){ if(j + 1 > separatedLayer.length){//Sublayer does not exit in separatedLayer separatedLayer[j] = []; separatedLayer[j].length = n; } } } return separatedLayer; } private function parseSymbols(elements:XML, frameVO:FrameVO):void { default xml namespace = _namespace; var n:int = elements.length(); for(var i:int = 0; i < n; i++) { var element:XML = elements[i]; frameVO.name = element.@libraryItemName; //get element matrix frameVO.matrix = XMLConverters.convertToObject(element.matrix.Matrix, Matrix); frameVO.transformationPoint = XMLConverters.convertToObject( element.transformationPoint.Point, Point); frameVO.color = new XMLColorConverter(element.color.Color); } } //} endregion PRIVATE\PROTECTED METHODS ======================================== //============================================================================== //{region EVENTS HANDLERS //} endregion EVENTS HANDLERS ================================================== //============================================================================== //{region GETTERS/SETTERS //} endregion GETTERS/SETTERS ================================================== } }
/** * User: MerlinDS * Date: 16.07.2014 * Time: 22:22 */ package com.merlinds.miracle_tool.controllers.converters { import com.merlinds.debug.log; import com.merlinds.miracle_tool.events.ActionEvent; import com.merlinds.miracle_tool.events.EditorEvent; import com.merlinds.miracle_tool.models.ProjectModel; import com.merlinds.miracle_tool.models.vo.AnimSourcesVO; import com.merlinds.miracle_tool.models.vo.AnimationVO; import com.merlinds.miracle_tool.models.vo.FrameVO; import com.merlinds.miracle_tool.models.vo.SourceVO; import com.merlinds.miracle_tool.models.vo.TimelineVO; import com.merlinds.miracle_tool.services.ActionService; import com.merlinds.miracle_tool.utils.XMLConverters; import flash.geom.Matrix; import flash.geom.Point; import org.robotlegs.mvcs.Command; public class AnimationConverterCommand extends Command { [Inject] public var projectModel:ProjectModel; [Inject] public var actionService:ActionService; [Inject] public var event:ActionEvent; private var _inputLayers:Array; private var _animation:AnimationVO; private var _namespace:Namespace; //============================================================================== //{region PUBLIC METHODS public function AnimationConverterCommand() { super(); } override public function execute():void { log(this, "execute"); //search for animation in file var data:AnimSourcesVO = this.event.body as AnimSourcesVO; var source:SourceVO = this.projectModel.selected; if(source == null)source = this.projectModel.inProgress; var n:int = source.animations.length; for(var i:int = 0; i < n; i++){ var animation:AnimationVO = source.animations[i]; for(var sourceName:String in data){ if(animation.name + '.xml' == sourceName){ _animation = animation; _animation.name = animation.name; _animation.file = this.projectModel.tempFile; _animation.added = true; this.prepareData4Animation(data[sourceName] as XML); this.convert2Animation(); } } } this.dispatch(new EditorEvent(EditorEvent.ANIMATION_ATTACHED, source.name)); } //} endregion PUBLIC METHODS =================================================== //============================================================================== //{region PRIVATE\PROTECTED METHODS private function prepareData4Animation(xml:XML):void { _namespace = new Namespace(xml.inScopeNamespaces()[0], xml.inScopeNamespaces()[1]); default xml namespace = _namespace; xml.normalize(); var layers:XMLList = xml.timeline.DOMTimeline.layers.children(); var n:int = layers.length(); //get all layers and prepare for converting _inputLayers = []; for(var i:int = 0; i < n; i++){ var layer:XML = layers[i]; if(layer.@layerType != "folder"){ //exclude Folders from list _inputLayers = _inputLayers.concat( this.readSourceLayer(layer) ); } } } private function convert2Animation():void { var n:int = _inputLayers.length; _animation.timelines.length = n; for(var i:int = 0; i < n; i++){ var layer:Array = _inputLayers[i]; var timeline:TimelineVO = new TimelineVO(); var m:int = layer.length; timeline.frames.length = m; for(var j:int = 0; j < m; j++){ timeline.frames[j] = layer[j]; } _animation.timelines[i] = timeline; } } private function readSourceLayer(layer:XML):Array { default xml namespace = _namespace; /* * This array will contains layer that was separated from current source layer * Will contains minimum one layer. * In case when source layer contains more than one symbol, * this layer will be separated to N output layers, where N - count of symbols on source layer */ //get all frames of the source layer var frames:XMLList = layer.frames.DOMFrame; var separatedLayer:Array = this.createEmptyLayers(frames); var m:int = separatedLayer.length; var n:int = frames.length(); for(var i:int = 0; i < n; i++){ var frame:XML = frames[i]; //read all symbols on the frame var symbols:XMLList = frame.elements.DOMSymbolInstance; var o:int = symbols.length();//number of symbols for(var j:int = 0; j < m; j++){ var frameVO:FrameVO = new FrameVO(frame.@index, frame.@duration); if(j < o){ var symbol:XML = symbols[j]; //convert symbol to frame object and save it to sublayer frameVO.type = frame.@tweenType; this.parseSymbols(symbol, frameVO); } separatedLayer[j][i] = frameVO; } } return separatedLayer; } private function createEmptyLayers(frames:XMLList):Array { default xml namespace = _namespace; var separatedLayer:Array = []; var n:int = frames.length(); for(var i:int = 0; i < n; i++){ var frame:XML = frames[i]; //read all symbols on the frame var symbols:XMLList = frame.elements.DOMSymbolInstance; var m:int = symbols.length(); for(var j:int = 0; j < m; j++){ if(j + 1 > separatedLayer.length){//Sublayer does not exit in separatedLayer separatedLayer[j] = []; separatedLayer[j].length = n; } } } return separatedLayer; } private function parseSymbols(elements:XML, frameVO:FrameVO):void { default xml namespace = _namespace; var n:int = elements.length(); for(var i:int = 0; i < n; i++) { var element:XML = elements[i]; frameVO.name = element.@libraryItemName; //get element matrix frameVO.matrix = XMLConverters.convertToObject(element.matrix.Matrix, Matrix); frameVO.transformationPoint = XMLConverters.convertToObject( element.transformationPoint.Point, Point); frameVO.color = new XMLColorConverter(element.color.Color); } } //} endregion PRIVATE\PROTECTED METHODS ======================================== //============================================================================== //{region EVENTS HANDLERS //} endregion EVENTS HANDLERS ================================================== //============================================================================== //{region GETTERS/SETTERS //} endregion GETTERS/SETTERS ================================================== } }
remove excess imports
remove excess imports
ActionScript
mit
MerlinDS/miracle_tool
e9321140fd4c95176a3fc44d993bd0e371cf0d2a
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
package dolly { import dolly.core.dolly_internal; import dolly.data.CompositeCloneableClass; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertFalse; import org.flexunit.asserts.assertNotNull; import org.hamcrest.assertThat; import org.hamcrest.collection.array; import org.hamcrest.collection.arrayWithSize; import org.hamcrest.collection.everyItem; import org.hamcrest.core.isA; import org.hamcrest.object.equalTo; use namespace dolly_internal; public class CloningOfCompositeCloneableClassTest { private var compositeCloneableClass:CompositeCloneableClass; private var compositeCloneableClassType:Type; [Before] public function before():void { compositeCloneableClass = new CompositeCloneableClass(); compositeCloneableClassType = Type.forInstance(compositeCloneableClass); } [After] public function after():void { compositeCloneableClass = null; compositeCloneableClassType = null; } [Test] public function findingAllWritableFieldsForType():void { const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType); assertNotNull(writableFields); assertEquals(4, writableFields.length); } [Test] public function cloningOfArray():void { const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass); assertNotNull(clone.array); assertThat(clone.array, arrayWithSize(5)); assertThat(clone.array, compositeCloneableClass.array); assertFalse(clone.array == compositeCloneableClass.array); assertThat(clone.array, everyItem(isA(Number))); assertThat(clone.array, array(equalTo(0), equalTo(1), equalTo(2), equalTo(3), equalTo(4))); } } }
package dolly { import dolly.core.dolly_internal; import dolly.data.CompositeCloneableClass; import mx.collections.ArrayCollection; import mx.collections.ArrayList; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertFalse; import org.flexunit.asserts.assertNotNull; import org.hamcrest.assertThat; import org.hamcrest.collection.array; import org.hamcrest.collection.arrayWithSize; import org.hamcrest.collection.everyItem; import org.hamcrest.core.isA; import org.hamcrest.object.equalTo; use namespace dolly_internal; public class CloningOfCompositeCloneableClassTest { private var compositeCloneableClass:CompositeCloneableClass; private var compositeCloneableClassType:Type; [Before] public function before():void { compositeCloneableClass = new CompositeCloneableClass(); compositeCloneableClass.array = [1, 2, 3, 4, 5]; compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]); compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]); compositeCloneableClassType = Type.forInstance(compositeCloneableClass); } [After] public function after():void { compositeCloneableClass = null; compositeCloneableClassType = null; } [Test] public function findingAllWritableFieldsForType():void { const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType); assertNotNull(writableFields); assertEquals(4, writableFields.length); } [Test] public function cloningOfArray():void { const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass); assertNotNull(clone.array); assertThat(clone.array, arrayWithSize(5)); assertThat(clone.array, compositeCloneableClass.array); assertFalse(clone.array == compositeCloneableClass.array); assertThat(clone.array, everyItem(isA(Number))); assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5))); } } }
Edit values of test objects.
Edit values of test objects.
ActionScript
mit
Yarovoy/dolly
05d40c02b8ba328e8ac024bcf10b5476adfc982b
src/aerys/minko/scene/controller/TransformController.as
src/aerys/minko/scene/controller/TransformController.as
package aerys.minko.scene.controller { import aerys.minko.ns.minko_math; import aerys.minko.render.Viewport; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.camera.Camera; import aerys.minko.type.Signal; import aerys.minko.type.math.Matrix4x4; import flash.display.BitmapData; import flash.utils.Dictionary; import flash.utils.getTimer; use namespace minko_math; /** * The TransformController handles the batched update of all the local to world matrices * of a sub-scene. As such, it will only be active on the root node of a sub-scene and will * automatically disable itself on other nodes. * * @author Jean-Marc Le Roux * */ public final class TransformController extends AbstractController { private static const FLAG_NONE : uint = 0; private static const FLAG_INIT_LOCAL_TO_WORLD : uint = 1; private static const FLAG_INIT_WORLD_TO_LOCAL : uint = 2; private static const FLAG_SYNCHRONIZE_TRANSFORMS : uint = 4; private static const FLAG_LOCK_TRANSFORMS : uint = 8; private var _target : ISceneNode; private var _invalidList : Boolean; private var _nodeToId : Dictionary; private var _idToNode : Vector.<ISceneNode> private var _transforms : Vector.<Matrix4x4>; private var _flags : Vector.<uint>; private var _localToWorldTransforms : Vector.<Matrix4x4>; private var _worldToLocalTransforms : Vector.<Matrix4x4>; private var _numChildren : Vector.<uint>; private var _firstChildId : Vector.<uint>; private var _parentId : Vector.<int>; public function TransformController() { super(); targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function renderingBeginHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { if (_invalidList) updateTransformsList(); if (_transforms.length) updateLocalToWorld(); } private function updateRootLocalToWorld(nodeId : uint = 0) : void { var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var rootTransform : Matrix4x4 = _transforms[nodeId]; var root : ISceneNode = _idToNode[nodeId]; var rootFlags : uint = _flags[nodeId]; if (rootTransform._hasChanged || !(rootFlags & FLAG_INIT_LOCAL_TO_WORLD)) { if (rootFlags & FLAG_LOCK_TRANSFORMS) rootLocalToWorld.lock(); rootLocalToWorld.copyFrom(rootTransform); if (nodeId != 0) rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]); if (rootFlags & FLAG_LOCK_TRANSFORMS) rootLocalToWorld.unlock(); rootTransform._hasChanged = false; rootFlags = (rootFlags | FLAG_INIT_LOCAL_TO_WORLD) & ~FLAG_INIT_WORLD_TO_LOCAL; if (rootFlags & FLAG_SYNCHRONIZE_TRANSFORMS) { var rootWorldToLocal : Matrix4x4 = _worldToLocalTransforms[nodeId] || (_worldToLocalTransforms[nodeId] = new Matrix4x4()); if (rootFlags & FLAG_LOCK_TRANSFORMS) rootWorldToLocal.lock(); rootWorldToLocal.copyFrom(rootLocalToWorld).invert(); rootFlags |= FLAG_INIT_WORLD_TO_LOCAL; if (rootFlags & FLAG_LOCK_TRANSFORMS) rootWorldToLocal.unlock(); } _flags[nodeId] = rootFlags; var localToWorldTransformChanged : Signal = root.localToWorldTransformChanged; if (root.localToWorldTransformChanged.enabled) root.localToWorldTransformChanged.execute(root, rootLocalToWorld); } } private function updateLocalToWorld(nodeId : uint = 0) : void { var numNodes : uint = _transforms.length; var subtreeMax : uint = nodeId; updateRootLocalToWorld(nodeId); while (nodeId < numNodes) { var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var numChildren : uint = _numChildren[nodeId]; var firstChildId : uint = _firstChildId[nodeId]; var lastChildId : uint = firstChildId + numChildren; var isDirty : Boolean = localToWorld._hasChanged; localToWorld._hasChanged = false; if (lastChildId > subtreeMax) subtreeMax = lastChildId; for (var childId : uint = firstChildId; childId < lastChildId; ++childId) { var childTransform : Matrix4x4 = _transforms[childId]; var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId]; var childFlags : uint = _flags[childId]; var childIsDirty : Boolean = isDirty || childTransform._hasChanged || !(childFlags & FLAG_INIT_LOCAL_TO_WORLD); if (childIsDirty) { var child : ISceneNode = _idToNode[childId]; if (childFlags & FLAG_LOCK_TRANSFORMS) childLocalToWorld.lock(); childLocalToWorld .copyFrom(childTransform) .append(localToWorld); if (childFlags & FLAG_LOCK_TRANSFORMS) childLocalToWorld.unlock(); childTransform._hasChanged = false; childFlags = (childFlags | FLAG_INIT_LOCAL_TO_WORLD) & ~FLAG_INIT_WORLD_TO_LOCAL; if (childFlags & FLAG_SYNCHRONIZE_TRANSFORMS) { var childWorldToLocal : Matrix4x4 = _worldToLocalTransforms[childId] || (_worldToLocalTransforms[childId] = new Matrix4x4()); if (childFlags & FLAG_LOCK_TRANSFORMS) childWorldToLocal.lock(); childWorldToLocal.copyFrom(childLocalToWorld).invert(); childFlags |= FLAG_INIT_WORLD_TO_LOCAL; if (childFlags & FLAG_LOCK_TRANSFORMS) childWorldToLocal.unlock(); } _flags[childId] = childFlags; var localToWorldTransformChanged : Signal = child.localToWorldTransformChanged; if (localToWorldTransformChanged.enabled) localToWorldTransformChanged.execute(child, childLocalToWorld); } } ++nodeId; } } private function updateLocalToWorldPath(path : Vector.<uint> = null) : void { var numNodes : uint = path.length; var nodeId : uint = path[uint(numNodes - 1)]; var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; updateRootLocalToWorld(nodeId); for (var i : int = numNodes - 2; i >= 0; --i) { var childId : uint = path[i]; var childTransform : Matrix4x4 = _transforms[childId]; var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId]; var childFlags : uint = _flags[childId]; var child : ISceneNode = _idToNode[childId]; if (childFlags & FLAG_LOCK_TRANSFORMS) childLocalToWorld.lock(); childLocalToWorld .copyFrom(childTransform) .append(localToWorld); if (childFlags & FLAG_LOCK_TRANSFORMS) childLocalToWorld.unlock(); childTransform._hasChanged = false; childFlags = (childFlags | FLAG_INIT_LOCAL_TO_WORLD) & ~FLAG_INIT_WORLD_TO_LOCAL; if (childFlags & FLAG_SYNCHRONIZE_TRANSFORMS) { var childWorldToLocal : Matrix4x4 = _worldToLocalTransforms[childId] || (_worldToLocalTransforms[childId] = new Matrix4x4()); if (childFlags & FLAG_LOCK_TRANSFORMS) childWorldToLocal.lock(); childWorldToLocal.copyFrom(childLocalToWorld).invert(); childFlags |= FLAG_INIT_WORLD_TO_LOCAL; if (childFlags & FLAG_LOCK_TRANSFORMS) childWorldToLocal.unlock(); } _flags[childId] = childFlags; var localToWorldTransformChanged : Signal = child.localToWorldTransformChanged; if (localToWorldTransformChanged.enabled) localToWorldTransformChanged.execute(child, childLocalToWorld); localToWorld = childLocalToWorld; } } private function updateAncestorsAndSelfLocalToWorld(nodeId : uint) : void { var dirtyRoot : int = -1; var tmpNodeId : int = nodeId; var path : Vector.<uint> = new <uint>[]; var numNodes : uint = 0; while (tmpNodeId >= 0) { if ((_transforms[tmpNodeId] as Matrix4x4)._hasChanged || !(_flags[nodeId] & FLAG_INIT_LOCAL_TO_WORLD)) dirtyRoot = tmpNodeId; path[numNodes] = tmpNodeId; ++numNodes; tmpNodeId = _parentId[tmpNodeId]; } if (dirtyRoot >= 0) updateLocalToWorldPath(path); // updateLocalToWorld(dirtyRoot, nodeId); } private function targetAddedHandler(ctrl : TransformController, target : ISceneNode) : void { if (_target) throw new Error('The TransformController cannot have more than one target.'); _target = target; _invalidList = true; if (target is Scene) { (target as Scene).renderingBegin.add(renderingBeginHandler); return; } if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.add(descendantAddedHandler); targetGroup.descendantRemoved.add(descendantRemovedHandler); } target.added.add(addedHandler); } private function targetRemovedHandler(ctrl : TransformController, target : ISceneNode) : void { target.added.remove(addedHandler); if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.remove(descendantAddedHandler); targetGroup.descendantRemoved.remove(descendantRemovedHandler); } _invalidList = false; _target = null; _nodeToId = null; _transforms = null; _flags = null; _localToWorldTransforms = null; _worldToLocalTransforms = null; _numChildren = null; _idToNode = null; _parentId = null; } private function addedHandler(target : ISceneNode, ancestor : Group) : void { // the controller will remove itself from the node when it's not its own root anymore // but it will watch for the 'removed' signal to add itself back if the node becomes // its own root again _target.removed.add(removedHandler); _target.removeController(this); } private function removedHandler(target : ISceneNode, ancestor : Group) : void { if (target.root == target) { target.removed.remove(removedHandler); target.addController(this); } } private function descendantAddedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function descendantRemovedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function getNodeId(node : ISceneNode) : uint { if (_invalidList || !(node in _nodeToId)) updateTransformsList(); return _nodeToId[node]; } private function updateTransformsList() : void { var root : ISceneNode = _target.root; var nodes : Vector.<ISceneNode> = new <ISceneNode>[root]; var nodeId : uint = 0; var oldNodeToId : Dictionary = _nodeToId; var oldInitialized : Vector.<uint> = _flags; var oldLocalToWorldTransforms : Vector.<Matrix4x4> = _localToWorldTransforms; var oldWorldToLocalTransform : Vector.<Matrix4x4> = _worldToLocalTransforms; _nodeToId = new Dictionary(true); _transforms = new <Matrix4x4>[]; _flags = new <uint>[]; _localToWorldTransforms = new <Matrix4x4>[]; _worldToLocalTransforms = new <Matrix4x4>[]; _numChildren = new <uint>[]; _firstChildId = new <uint>[]; _idToNode = new <ISceneNode>[]; _parentId = new <int>[-1]; while (nodes.length) { var node : ISceneNode = nodes.shift(); var group : Group = node as Group; _nodeToId[node] = nodeId; _idToNode[nodeId] = node; _transforms[nodeId] = node.transform; if (oldNodeToId && node in oldNodeToId) { var oldNodeId : uint = oldNodeToId[node]; _localToWorldTransforms[nodeId] = oldLocalToWorldTransforms[oldNodeId]; _worldToLocalTransforms[nodeId] = oldWorldToLocalTransform[oldNodeId]; _flags[nodeId] = oldInitialized[oldNodeId]; } else { _localToWorldTransforms[nodeId] = new Matrix4x4().lock(); _worldToLocalTransforms[nodeId] = null; _flags[nodeId] = FLAG_NONE; } if (group) { var numChildren : uint = group.numChildren; var firstChildId : uint = nodeId + nodes.length + 1; _numChildren[nodeId] = numChildren; _firstChildId[nodeId] = firstChildId; for (var childId : uint = 0; childId < numChildren; ++childId) { _parentId[uint(firstChildId + childId)] = nodeId; nodes.push(group.getChildAt(childId)); } } else { _numChildren[nodeId] = 0; _firstChildId[nodeId] = 0; } ++nodeId; } _worldToLocalTransforms.length = _localToWorldTransforms.length; _invalidList = false; } public function getLocalToWorldTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { var nodeId : uint = getNodeId(node); if (forceUpdate) updateAncestorsAndSelfLocalToWorld(nodeId); return _localToWorldTransforms[nodeId]; } public function getWorldToLocalTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { var nodeId : uint = getNodeId(node); var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId]; if (!worldToLocalTransform) { _worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4(); if (!forceUpdate) { worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert(); _flags[nodeId] |= FLAG_INIT_WORLD_TO_LOCAL; } } if (forceUpdate) updateAncestorsAndSelfLocalToWorld(nodeId); var flags : uint = _flags[nodeId]; if (!(flags & FLAG_INIT_WORLD_TO_LOCAL)) { _flags[nodeId] |= FLAG_INIT_WORLD_TO_LOCAL; if (flags & FLAG_LOCK_TRANSFORMS) worldToLocalTransform.lock(); worldToLocalTransform .copyFrom(_localToWorldTransforms[nodeId]) .invert(); if (flags & FLAG_LOCK_TRANSFORMS) worldToLocalTransform.unlock(); } return worldToLocalTransform; } public function synchronizeTransforms(node : ISceneNode, enabled : Boolean) : void { var nodeId : uint = getNodeId(node); _flags[nodeId] = enabled ? _flags[nodeId] | FLAG_SYNCHRONIZE_TRANSFORMS : _flags[nodeId] & ~FLAG_SYNCHRONIZE_TRANSFORMS; } public function lockTransformsBeforeUpdate(node : ISceneNode, enabled : Boolean) : void { var nodeId : uint = getNodeId(node); _flags[nodeId] = enabled ? _flags[nodeId] | FLAG_LOCK_TRANSFORMS : _flags[nodeId] & ~FLAG_LOCK_TRANSFORMS; } } }
package aerys.minko.scene.controller { import aerys.minko.ns.minko_math; import aerys.minko.render.Viewport; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.camera.Camera; import aerys.minko.type.Signal; import aerys.minko.type.math.Matrix4x4; import flash.display.BitmapData; import flash.utils.Dictionary; import flash.utils.getTimer; use namespace minko_math; /** * The TransformController handles the batched update of all the local to world matrices * of a sub-scene. As such, it will only be active on the root node of a sub-scene and will * automatically disable itself on other nodes. * * @author Jean-Marc Le Roux * */ public final class TransformController extends AbstractController { private static const FLAG_NONE : uint = 0; private static const FLAG_INIT_LOCAL_TO_WORLD : uint = 1; private static const FLAG_INIT_WORLD_TO_LOCAL : uint = 2; private static const FLAG_SYNCHRONIZE_TRANSFORMS : uint = 4; private static const FLAG_LOCK_TRANSFORMS : uint = 8; private var _target : ISceneNode; private var _invalidList : Boolean; private var _nodeToId : Dictionary; private var _idToNode : Vector.<ISceneNode> private var _transforms : Vector.<Matrix4x4>; private var _flags : Vector.<uint>; private var _localToWorldTransforms : Vector.<Matrix4x4>; private var _worldToLocalTransforms : Vector.<Matrix4x4>; private var _numChildren : Vector.<uint>; private var _firstChildId : Vector.<uint>; private var _parentId : Vector.<int>; public function TransformController() { super(); targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function renderingBeginHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { if (_invalidList) updateTransformsList(); if (_transforms.length) updateLocalToWorld(); } private function updateRootLocalToWorld(nodeId : uint = 0) : void { var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var rootTransform : Matrix4x4 = _transforms[nodeId]; var root : ISceneNode = _idToNode[nodeId]; var rootFlags : uint = _flags[nodeId]; if (rootTransform._hasChanged || !(rootFlags & FLAG_INIT_LOCAL_TO_WORLD)) { if (rootFlags & FLAG_LOCK_TRANSFORMS) rootLocalToWorld.lock(); rootLocalToWorld.copyFrom(rootTransform); if (nodeId != 0) rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]); if (rootFlags & FLAG_LOCK_TRANSFORMS) rootLocalToWorld.unlock(); rootTransform._hasChanged = false; rootFlags = (rootFlags | FLAG_INIT_LOCAL_TO_WORLD) & ~FLAG_INIT_WORLD_TO_LOCAL; if (rootFlags & FLAG_SYNCHRONIZE_TRANSFORMS) { var rootWorldToLocal : Matrix4x4 = _worldToLocalTransforms[nodeId] || (_worldToLocalTransforms[nodeId] = new Matrix4x4()); if (rootFlags & FLAG_LOCK_TRANSFORMS) rootWorldToLocal.lock(); rootWorldToLocal.copyFrom(rootLocalToWorld).invert(); rootFlags |= FLAG_INIT_WORLD_TO_LOCAL; if (rootFlags & FLAG_LOCK_TRANSFORMS) rootWorldToLocal.unlock(); } _flags[nodeId] = rootFlags; var localToWorldTransformChanged : Signal = root.localToWorldTransformChanged; if (root.localToWorldTransformChanged.enabled) root.localToWorldTransformChanged.execute(root, rootLocalToWorld); } } private function updateLocalToWorld(nodeId : uint = 0) : void { var numNodes : uint = _transforms.length; var subtreeMax : uint = nodeId; updateRootLocalToWorld(nodeId); while (nodeId < numNodes) { var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; var numChildren : uint = _numChildren[nodeId]; var firstChildId : uint = _firstChildId[nodeId]; var lastChildId : uint = firstChildId + numChildren; var isDirty : Boolean = localToWorld._hasChanged; localToWorld._hasChanged = false; if (lastChildId > subtreeMax) subtreeMax = lastChildId; for (var childId : uint = firstChildId; childId < lastChildId; ++childId) { var childTransform : Matrix4x4 = _transforms[childId]; var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId]; var childFlags : uint = _flags[childId]; var childIsDirty : Boolean = isDirty || childTransform._hasChanged || !(childFlags & FLAG_INIT_LOCAL_TO_WORLD); if (childIsDirty) { var child : ISceneNode = _idToNode[childId]; if (childFlags & FLAG_LOCK_TRANSFORMS) childLocalToWorld.lock(); childLocalToWorld .copyFrom(childTransform) .append(localToWorld); if (childFlags & FLAG_LOCK_TRANSFORMS) childLocalToWorld.unlock(); childTransform._hasChanged = false; childFlags = (childFlags | FLAG_INIT_LOCAL_TO_WORLD) & ~FLAG_INIT_WORLD_TO_LOCAL; if (childFlags & FLAG_SYNCHRONIZE_TRANSFORMS) { var childWorldToLocal : Matrix4x4 = _worldToLocalTransforms[childId] || (_worldToLocalTransforms[childId] = new Matrix4x4()); if (childFlags & FLAG_LOCK_TRANSFORMS) childWorldToLocal.lock(); childWorldToLocal.copyFrom(childLocalToWorld).invert(); childFlags |= FLAG_INIT_WORLD_TO_LOCAL; if (childFlags & FLAG_LOCK_TRANSFORMS) childWorldToLocal.unlock(); } _flags[childId] = childFlags; var localToWorldTransformChanged : Signal = child.localToWorldTransformChanged; if (localToWorldTransformChanged.enabled) localToWorldTransformChanged.execute(child, childLocalToWorld); } } ++nodeId; } } private function updateLocalToWorldPath(path : Vector.<uint> = null) : void { var numNodes : uint = path.length; var nodeId : uint = path[uint(numNodes - 1)]; var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; updateRootLocalToWorld(nodeId); for (var i : int = numNodes - 2; i >= 0; --i) { var childId : uint = path[i]; var childTransform : Matrix4x4 = _transforms[childId]; var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId]; var childFlags : uint = _flags[childId]; var child : ISceneNode = _idToNode[childId]; if (childFlags & FLAG_LOCK_TRANSFORMS) childLocalToWorld.lock(); childLocalToWorld .copyFrom(childTransform) .append(localToWorld); if (childFlags & FLAG_LOCK_TRANSFORMS) childLocalToWorld.unlock(); childTransform._hasChanged = false; childFlags = (childFlags | FLAG_INIT_LOCAL_TO_WORLD) & ~FLAG_INIT_WORLD_TO_LOCAL; if (childFlags & FLAG_SYNCHRONIZE_TRANSFORMS) { var childWorldToLocal : Matrix4x4 = _worldToLocalTransforms[childId] || (_worldToLocalTransforms[childId] = new Matrix4x4()); if (childFlags & FLAG_LOCK_TRANSFORMS) childWorldToLocal.lock(); childWorldToLocal.copyFrom(childLocalToWorld).invert(); childFlags |= FLAG_INIT_WORLD_TO_LOCAL; if (childFlags & FLAG_LOCK_TRANSFORMS) childWorldToLocal.unlock(); } _flags[childId] = childFlags; var localToWorldTransformChanged : Signal = child.localToWorldTransformChanged; if (localToWorldTransformChanged.enabled) localToWorldTransformChanged.execute(child, childLocalToWorld); localToWorld = childLocalToWorld; } } private function updateAncestorsAndSelfLocalToWorld(nodeId : uint) : void { var dirtyRoot : int = -1; var tmpNodeId : int = nodeId; var path : Vector.<uint> = new <uint>[]; var numNodes : uint = 0; while (tmpNodeId >= 0) { if ((_transforms[tmpNodeId] as Matrix4x4)._hasChanged || !(_flags[nodeId] & FLAG_INIT_LOCAL_TO_WORLD)) dirtyRoot = tmpNodeId; path[numNodes] = tmpNodeId; ++numNodes; tmpNodeId = _parentId[tmpNodeId]; } if (dirtyRoot >= 0) updateLocalToWorldPath(path); // updateLocalToWorld(dirtyRoot, nodeId); } private function targetAddedHandler(ctrl : TransformController, target : ISceneNode) : void { if (_target) throw new Error('The TransformController cannot have more than one target.'); _target = target; _invalidList = true; if (target is Scene) { (target as Scene).renderingBegin.add(renderingBeginHandler); return; } if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.add(descendantAddedHandler); targetGroup.descendantRemoved.add(descendantRemovedHandler); } target.added.add(addedHandler); } private function targetRemovedHandler(ctrl : TransformController, target : ISceneNode) : void { target.added.remove(addedHandler); if (target is Group) { var targetGroup : Group = target as Group; targetGroup.descendantAdded.remove(descendantAddedHandler); targetGroup.descendantRemoved.remove(descendantRemovedHandler); } _invalidList = false; _target = null; _nodeToId = null; _transforms = null; _flags = null; _localToWorldTransforms = null; _worldToLocalTransforms = null; _numChildren = null; _idToNode = null; _parentId = null; } private function addedHandler(target : ISceneNode, ancestor : Group) : void { // the controller will remove itself from the node when it's not its own root anymore // but it will watch for the 'removed' signal to add itself back if the node becomes // its own root again _target.removed.add(removedHandler); _target.removeController(this); } private function removedHandler(target : ISceneNode, ancestor : Group) : void { if (target.root == target) { target.removed.remove(removedHandler); target.addController(this); } } private function descendantAddedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function descendantRemovedHandler(root : Group, descendant : ISceneNode) : void { _invalidList = true; } private function getNodeId(node : ISceneNode) : uint { if (_invalidList || !(node in _nodeToId)) updateTransformsList(); return _nodeToId[node]; } private function updateTransformsList() : void { var root : ISceneNode = _target.root; var nodes : Vector.<ISceneNode> = new <ISceneNode>[root]; var nodeId : uint = 0; var oldNodeToId : Dictionary = _nodeToId; var oldInitialized : Vector.<uint> = _flags; var oldLocalToWorldTransforms : Vector.<Matrix4x4> = _localToWorldTransforms; var oldWorldToLocalTransform : Vector.<Matrix4x4> = _worldToLocalTransforms; _nodeToId = new Dictionary(true); _transforms.length = 0; _flags.length = 0; _localToWorldTransforms.length = 0; _worldToLocalTransforms.length = 0; _numChildren.length = 0; _firstChildId.length = 0; _idToNode.length = 0; _parentId.length = 1; _parentId[0] = -1; while (nodes.length) { var node : ISceneNode = nodes.shift(); var group : Group = node as Group; _nodeToId[node] = nodeId; _idToNode[nodeId] = node; _transforms[nodeId] = node.transform; if (oldNodeToId && node in oldNodeToId) { var oldNodeId : uint = oldNodeToId[node]; _localToWorldTransforms[nodeId] = oldLocalToWorldTransforms[oldNodeId]; _worldToLocalTransforms[nodeId] = oldWorldToLocalTransform[oldNodeId]; _flags[nodeId] = oldInitialized[oldNodeId]; } else { _localToWorldTransforms[nodeId] = new Matrix4x4().lock(); _worldToLocalTransforms[nodeId] = null; _flags[nodeId] = FLAG_NONE; } if (group) { var numChildren : uint = group.numChildren; var firstChildId : uint = nodeId + nodes.length + 1; _numChildren[nodeId] = numChildren; _firstChildId[nodeId] = firstChildId; for (var childId : uint = 0; childId < numChildren; ++childId) { _parentId[uint(firstChildId + childId)] = nodeId; nodes.push(group.getChildAt(childId)); } } else { _numChildren[nodeId] = 0; _firstChildId[nodeId] = 0; } ++nodeId; } _worldToLocalTransforms.length = _localToWorldTransforms.length; _invalidList = false; } public function getLocalToWorldTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { var nodeId : uint = getNodeId(node); if (forceUpdate) updateAncestorsAndSelfLocalToWorld(nodeId); return _localToWorldTransforms[nodeId]; } public function getWorldToLocalTransform(node : ISceneNode, forceUpdate : Boolean = false) : Matrix4x4 { var nodeId : uint = getNodeId(node); var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId]; if (!worldToLocalTransform) { _worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4(); if (!forceUpdate) { worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert(); _flags[nodeId] |= FLAG_INIT_WORLD_TO_LOCAL; } } if (forceUpdate) updateAncestorsAndSelfLocalToWorld(nodeId); var flags : uint = _flags[nodeId]; if (!(flags & FLAG_INIT_WORLD_TO_LOCAL)) { _flags[nodeId] |= FLAG_INIT_WORLD_TO_LOCAL; if (flags & FLAG_LOCK_TRANSFORMS) worldToLocalTransform.lock(); worldToLocalTransform .copyFrom(_localToWorldTransforms[nodeId]) .invert(); if (flags & FLAG_LOCK_TRANSFORMS) worldToLocalTransform.unlock(); } return worldToLocalTransform; } public function synchronizeTransforms(node : ISceneNode, enabled : Boolean) : void { var nodeId : uint = getNodeId(node); _flags[nodeId] = enabled ? _flags[nodeId] | FLAG_SYNCHRONIZE_TRANSFORMS : _flags[nodeId] & ~FLAG_SYNCHRONIZE_TRANSFORMS; } public function lockTransformsBeforeUpdate(node : ISceneNode, enabled : Boolean) : void { var nodeId : uint = getNodeId(node); _flags[nodeId] = enabled ? _flags[nodeId] | FLAG_LOCK_TRANSFORMS : _flags[nodeId] & ~FLAG_LOCK_TRANSFORMS; } } }
fix TransformController.updateTransformList() to avoid instanciating new vectors and use Vector.length = 0 instead
fix TransformController.updateTransformList() to avoid instanciating new vectors and use Vector.length = 0 instead
ActionScript
mit
aerys/minko-as3
262cbe993173537d3bb35fa548f6721a225be5ef
src/aerys/minko/render/shader/sprite/SpriteShader.as
src/aerys/minko/render/shader/sprite/SpriteShader.as
package aerys.minko.render.shader.sprite { import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.render.shader.ShaderSettings; import aerys.minko.render.shader.part.DiffuseShaderPart; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.DepthTest; import aerys.minko.type.enum.SamplerFiltering; import aerys.minko.type.enum.SamplerMipMapping; import aerys.minko.type.enum.SamplerWrapping; public class SpriteShader extends Shader { private var _diffuse : DiffuseShaderPart; private var _uv : SFloat; public function SpriteShader() { super(); _diffuse = new DiffuseShaderPart(this); } override protected function initializeSettings(settings : ShaderSettings) : void { // settings.blending = Blending.ALPHA; settings.depthTest = DepthTest.LESS; } override protected function getVertexPosition() : SFloat { var vertexXY : SFloat = vertexXY.xy; _uv = multiply(add(vertexXY, 0.5), float2(1, -1)); var depth : SFloat = meshBindings.getParameter('depth', 1); var xy : SFloat = float2( meshBindings.getParameter('x', 1), meshBindings.getParameter('y', 1) ); var size : SFloat = float2( meshBindings.getParameter('width', 1), meshBindings.getParameter('height', 1) ); var vpSize : SFloat = float2( sceneBindings.getParameter('viewportWidth', 1), sceneBindings.getParameter('viewportHeight', 1) ); xy = divide(add(xy, divide(size, 2)), vpSize); xy = multiply(subtract(xy, 0.5), float2(2, -2)); vertexXY.scaleBy(divide(size, divide(vpSize, 2))); vertexXY.incrementBy(xy); return float4(vertexXY, depth, 1); } override protected function getPixelColor() : SFloat { return _diffuse.getDiffuseColor(true, _uv); } } }
package aerys.minko.render.shader.sprite { import aerys.minko.render.material.basic.BasicProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.render.shader.ShaderSettings; import aerys.minko.render.shader.part.DiffuseShaderPart; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.BlendingSource; import aerys.minko.type.enum.DepthTest; public class SpriteShader extends Shader { private var _diffuse : DiffuseShaderPart; private var _uv : SFloat; public function SpriteShader() { super(); _diffuse = new DiffuseShaderPart(this); } override protected function initializeSettings(settings : ShaderSettings) : void { var blending : uint = meshBindings.getProperty( BasicProperties.BLENDING, Blending.OPAQUE ); settings.depthWriteEnabled = meshBindings.getProperty( BasicProperties.DEPTH_WRITE_ENABLED, true ); settings.depthTest = meshBindings.getProperty( BasicProperties.DEPTH_TEST, DepthTest.LESS ); if ((blending & 0xff) == BlendingSource.SOURCE_ALPHA) { settings.priority -= 0.5; settings.depthSortDrawCalls = true; } settings.blending = blending; settings.enabled = true; settings.scissorRectangle = null; } override protected function getVertexPosition() : SFloat { var vertexXY : SFloat = vertexXY.xy; _uv = multiply(add(vertexXY, 0.5), float2(1, -1)); var depth : SFloat = meshBindings.getParameter('depth', 1); var xy : SFloat = float2( meshBindings.getParameter('x', 1), meshBindings.getParameter('y', 1) ); var size : SFloat = float2( meshBindings.getParameter('width', 1), meshBindings.getParameter('height', 1) ); var vpSize : SFloat = float2( sceneBindings.getParameter('viewportWidth', 1), sceneBindings.getParameter('viewportHeight', 1) ); xy = divide(add(xy, divide(size, 2)), vpSize); xy = multiply(subtract(xy, 0.5), float2(2, -2)); vertexXY.scaleBy(divide(size, divide(vpSize, 2))); vertexXY.incrementBy(xy); return float4(vertexXY, depth, 1); } override protected function getPixelColor() : SFloat { return _diffuse.getDiffuseColor(true, _uv); } } }
Add alpha properties on spriteShader
Add alpha properties on spriteShader
ActionScript
mit
aerys/minko-as3
61277f830d846053b7a86d439c13d83b5841ac45
src/Main.as
src/Main.as
package { import net.flashpunk.Engine; import net.flashpunk.FP; import worlds.World1; public class Main extends Engine { public function Main() { super(800, 640, 100, false); } override public function init():void { FP.screen.color = 0xffffff; FP.world = new World1; FP.console.enable(); } } }
package { import net.flashpunk.Engine; import net.flashpunk.FP; import worlds.World1; public class Main extends Engine { public function Main() { super(800, 640, 100, false); } override public function init():void { FP.screen.color = 0xffffff; FP.world = new World1; } } }
remove console
remove console
ActionScript
mit
lusv/batracio
17e365fec3af0dab30ed7986f3ee1b517eb729e2
src/aerys/minko/scene/controller/EnterFrameController.as
src/aerys/minko/scene/controller/EnterFrameController.as
package aerys.minko.scene.controller { import aerys.minko.render.Viewport; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import flash.display.BitmapData; /** * EnterFrameController are controllers triggered whenever the Scene.enterFrame * signal is executed. * * The best way to * * @author Jean-Marc Le Roux * */ public class EnterFrameController extends AbstractController { private var _targetsInScene : uint = 0; public function EnterFrameController(targetType : Class = null) { super(targetType); targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } protected function targetAddedHandler(ctrl : EnterFrameController, target : ISceneNode) : void { if (target.root is Scene) targetAddedToSceneHandler(target, target.root as Scene); else target.addedToScene.add(targetAddedToSceneHandler); } protected function targetRemovedHandler(ctrl : EnterFrameController, target : ISceneNode) : void { if (target.root is Scene) target.removedFromScene.remove(targetRemovedFromSceneHandler); else target.addedToScene.remove(targetAddedToSceneHandler); } protected function targetAddedToSceneHandler(target : ISceneNode, scene : Scene) : void { if (target.addedToScene.hasCallback(targetAddedToSceneHandler)) target.addedToScene.remove(targetAddedToSceneHandler); target.removedFromScene.add(targetRemovedFromSceneHandler); ++_targetsInScene; if (_targetsInScene == 1) scene.enterFrame.add(sceneEnterFrameHandler); } protected function targetRemovedFromSceneHandler(target : ISceneNode, scene : Scene) : void { --_targetsInScene; target.removedFromScene.remove(targetRemovedFromSceneHandler); target.addedToScene.add(targetAddedToSceneHandler); if (_targetsInScene == 0) scene.enterFrame.remove(sceneEnterFrameHandler); } protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { throw new Error( 'The method EnterFrameController.sceneEnterFrameHandler must be overriden.' ); } } }
package aerys.minko.scene.controller { import aerys.minko.render.Viewport; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import flash.display.BitmapData; /** * EnterFrameController are controllers triggered whenever the Scene.enterFrame * signal is executed. * * The best way to * * @author Jean-Marc Le Roux * */ public class EnterFrameController extends AbstractController { private var _targetsInScene : uint = 0; public function get numTargetsInScene() : uint { return _targetsInScene; } public function EnterFrameController(targetType : Class = null) { super(targetType); targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } protected function targetAddedHandler(ctrl : EnterFrameController, target : ISceneNode) : void { if (target.root is Scene) targetAddedToSceneHandler(target, target.root as Scene); else target.addedToScene.add(targetAddedToSceneHandler); } protected function targetRemovedHandler(ctrl : EnterFrameController, target : ISceneNode) : void { if (target.root is Scene) target.removedFromScene.remove(targetRemovedFromSceneHandler); else target.addedToScene.remove(targetAddedToSceneHandler); } protected function targetAddedToSceneHandler(target : ISceneNode, scene : Scene) : void { if (target.addedToScene.hasCallback(targetAddedToSceneHandler)) target.addedToScene.remove(targetAddedToSceneHandler); target.removedFromScene.add(targetRemovedFromSceneHandler); ++_targetsInScene; if (_targetsInScene == 1) scene.enterFrame.add(sceneEnterFrameHandler); } protected function targetRemovedFromSceneHandler(target : ISceneNode, scene : Scene) : void { --_targetsInScene; target.removedFromScene.remove(targetRemovedFromSceneHandler); target.addedToScene.add(targetAddedToSceneHandler); if (_targetsInScene == 0) scene.enterFrame.remove(sceneEnterFrameHandler); } protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { throw new Error( 'The method EnterFrameController.sceneEnterFrameHandler must be overriden.' ); } } }
add EnterFrameController.numTargetsInScene property
add EnterFrameController.numTargetsInScene property
ActionScript
mit
aerys/minko-as3
51db48ff0d7d1ccb4eebc0717b6f52a857c7b557
examples/DataGridExample/src/mybeads/RowHeightBead.as
examples/DataGridExample/src/mybeads/RowHeightBead.as
//////////////////////////////////////////////////////////////////////////////// // // 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 mybeads { import flash.display.DisplayObject; import org.apache.flex.core.IBead; import org.apache.flex.core.IDataGridModel; import org.apache.flex.core.IItemRenderer; import org.apache.flex.core.IItemRendererParent; import org.apache.flex.core.IStrand; import org.apache.flex.core.UIBase; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.html.List; import org.apache.flex.html.beads.DataGridView; import org.apache.flex.html.beads.IListView; public class RowHeightBead implements IBead { public function RowHeightBead() { } private var _strand:IStrand; public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(_strand).addEventListener("layoutComplete",handleLayoutComplete); } private var _rowHeight:Number = 30; public function get rowHeight():Number { return _rowHeight; } public function set rowHeight(value:Number):void { _rowHeight = value; // dispatch some event which will trigger layout recalculation } private var _minRowHeight:Number = 30; public function get minRowHeight():Number { return _minRowHeight; } public function set minRowHeight(value:Number):void { _minRowHeight = value; // dispatch some event which will trigger layout recalculation } private var _variableRowHeight:Boolean = false; public function get variableRowHeight():Boolean { return _variableRowHeight; } public function set variableRowHeight(value:Boolean):void { _variableRowHeight = value; // dispatch some event which will trigger a layout recalculation } private function handleLayoutComplete(event:Event):void { if (variableRowHeight) { makeAllRowsVariableHeight(minRowHeight); } else { makeAllRowsSameHeight(rowHeight); } } private function makeAllRowsSameHeight(newHeight:Number):void { // this function forces every cell in the DataGrid to be the same height var view:DataGridView = _strand.getBeadByType(DataGridView) as DataGridView; var lists:Array = view.getColumnLists(); for(var i:int=0; i < lists.length; i++) { var list:List = lists[i] as List; var listView:IListView = list.getBeadByType(IListView) as IListView; var p:IItemRendererParent = listView.dataGroup; var n:Number = (list.dataProvider as Array).length; for(var j:int=0; j < n; j++) { var c:UIBase = p.getItemRendererForIndex(j) as UIBase; c.height = newHeight; } IEventDispatcher(list).dispatchEvent( new Event("layoutNeeded") ); } } private function makeAllRowsVariableHeight(minHeight:Number):void { // this function makes every cell in a row the same height // (at least minHeight) but all the rows can have different // heights var view:DataGridView = _strand.getBeadByType(DataGridView) as DataGridView; var lists:Array = view.getColumnLists(); // future: maybe IDataGridModel.dataProvider should implement IDataProvider which // can have a length property and not assume that the .dataProvider is an Array. var n:Number = ((_strand.getBeadByType(IDataGridModel) as IDataGridModel).dataProvider as Array).length; for(var i:int=0; i < n; i++) { var maxHeight:Number = minHeight; for(var j:int=0; j < lists.length; j++) { var list:List = lists[j] as List; var listView:IListView = list.getBeadByType(IListView) as IListView; var p:IItemRendererParent = listView.dataGroup; var c:UIBase = p.getItemRendererForIndex(i) as UIBase; maxHeight = Math.max(maxHeight,c.height); } for(j=0; j < lists.length; j++) { list = lists[j] as List; listView = list.getBeadByType(IListView) as IListView; p = listView.dataGroup; c = p.getItemRendererForIndex(i) as UIBase; c.height = maxHeight; } } for(j=0; j < lists.length; j++) { list = lists[j] as List; IEventDispatcher(list).dispatchEvent( new Event("layoutNeeded") ); } } } }
//////////////////////////////////////////////////////////////////////////////// // // 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 mybeads { import org.apache.flex.core.IBead; import org.apache.flex.core.IDataGridModel; import org.apache.flex.core.IItemRendererParent; import org.apache.flex.core.IStrand; import org.apache.flex.core.UIBase; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.html.List; import org.apache.flex.html.beads.DataGridView; import org.apache.flex.html.beads.IListView; public class RowHeightBead implements IBead { public function RowHeightBead() { } private var _strand:IStrand; public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(_strand).addEventListener("layoutComplete",handleLayoutComplete); } private var _rowHeight:Number = 30; public function get rowHeight():Number { return _rowHeight; } public function set rowHeight(value:Number):void { _rowHeight = value; // dispatch some event which will trigger layout recalculation } private var _minRowHeight:Number = 30; public function get minRowHeight():Number { return _minRowHeight; } public function set minRowHeight(value:Number):void { _minRowHeight = value; // dispatch some event which will trigger layout recalculation } private var _variableRowHeight:Boolean = false; public function get variableRowHeight():Boolean { return _variableRowHeight; } public function set variableRowHeight(value:Boolean):void { _variableRowHeight = value; // dispatch some event which will trigger a layout recalculation } private function handleLayoutComplete(event:Event):void { if (variableRowHeight) { makeAllRowsVariableHeight(minRowHeight); } else { makeAllRowsSameHeight(rowHeight); } } private function makeAllRowsSameHeight(newHeight:Number):void { // this function forces every cell in the DataGrid to be the same height var view:DataGridView = _strand.getBeadByType(DataGridView) as DataGridView; var lists:Array = view.getColumnLists(); for(var i:int=0; i < lists.length; i++) { var list:List = lists[i] as List; var listView:IListView = list.getBeadByType(IListView) as IListView; var p:IItemRendererParent = listView.dataGroup; var n:Number = (list.dataProvider as Array).length; for(var j:int=0; j < n; j++) { var c:UIBase = p.getItemRendererForIndex(j) as UIBase; c.height = newHeight; } IEventDispatcher(list).dispatchEvent( new Event("layoutNeeded") ); } } private function makeAllRowsVariableHeight(minHeight:Number):void { // this function makes every cell in a row the same height // (at least minHeight) but all the rows can have different // heights var view:DataGridView = _strand.getBeadByType(DataGridView) as DataGridView; var lists:Array = view.getColumnLists(); // future: maybe IDataGridModel.dataProvider should implement IDataProvider which // can have a length property and not assume that the .dataProvider is an Array. var n:Number = ((_strand.getBeadByType(IDataGridModel) as IDataGridModel).dataProvider as Array).length; for(var i:int=0; i < n; i++) { var maxHeight:Number = minHeight; for(var j:int=0; j < lists.length; j++) { var list:List = lists[j] as List; var listView:IListView = list.getBeadByType(IListView) as IListView; var p:IItemRendererParent = listView.dataGroup; var c:UIBase = p.getItemRendererForIndex(i) as UIBase; maxHeight = Math.max(maxHeight,c.height); } for(j=0; j < lists.length; j++) { list = lists[j] as List; listView = list.getBeadByType(IListView) as IListView; p = listView.dataGroup; c = p.getItemRendererForIndex(i) as UIBase; c.height = maxHeight; } } for(j=0; j < lists.length; j++) { list = lists[j] as List; IEventDispatcher(list).dispatchEvent( new Event("layoutNeeded") ); } } } }
Remove unused imports
Remove unused imports
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
c9c11f0946954f9eaf25e02c816a559329af52d4
core/JSON.as
core/JSON.as
/* -*- c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */ /* ***** 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) 2010 * 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 ***** */ // JSON according to the ECMAScript 5 specification. // Based on ECMA-262-5 and Errata as of 31 July 2010 (no JSON errata at that time). // // Deliberate deviations from the specification // - There are additional type checks on JSON.parse and JSON.stringify - that fits AS3 better. // - Property enumeration order is indeterminate in AS3, so there is no attempt to extract // keys in any particular order when enumerating properties during filtering. // // Compiling it // - This code must be compilable with -strict. // - The code ought to work even if compiled with -AS3 because public:: qualifiers are // used where they matter. package { include "api-versions.as" [API(CONFIG::SWF_13)] [native(cls="JSONClass", classgc="exact", methods="auto", construct="none")] public final class JSON { private static const as3ns:Namespace = AS3; private native static function parseCore(text:String):Object; // specialized stringify procedure private native static function stringifySpecializedToString(value:Object, replacerArray:Array, replacerFunction:Function, gap:String):String; public static function parse(text:String, reviver:Function = null):Object { if (text === null || text === undefined) { Error.throwError( SyntaxError, 1132 /*kJSONInvalidParseInput*/ ); } // at this point, we should be assured that text is String. var unfiltered: Object = parseCore(text); if (reviver === null) return unfiltered; return (new Walker(reviver)).walk({ "": unfiltered }, ""); } public static function stringify(value:Object, replacer=null, space=null):String { // We deliberately deviate from ECMA-262 and throw on // invalid replacer parameter. if (!(replacer === null || replacer is Function || replacer is Array)) Error.throwError( TypeError, 1131 /*kJSONInvalidReplacer*/ ); // We follow ECMA-262 and silently ignore invalid space parameter. if (!(space === null || space is String || space is Number)) space = null; var gap = ""; if (space is String) gap = space.length > 10 ? space.AS3::substring(0,10) : space; else if (space is Number) gap = " ".AS3::substring(0,Math.min(10,Math.floor(space))); if (replacer === null) { return stringifySpecializedToString(value, null, null, gap); } else if (replacer is Array) { return stringifySpecializedToString(value, computePropertyList(replacer), null, gap); } else { // replacer is Function return stringifySpecializedToString(value, null, replacer, gap); } } // ECMA-262 5th ed, section 15.12.3 stringify, step 4.b private static function computePropertyList(r:Array):Array { var propertyList = []; var alreadyAdded = {}; for (var i:uint=0, ilim:uint = r.length; i < ilim; i++) { if (!r.AS3::hasOwnProperty(i)) continue; var v = r[i]; var item: String = null; if (v is String) item = v; else if (v is Number) item = String(v); if (item !== null && !alreadyAdded[item]) { alreadyAdded[item] = true; propertyList[propertyList.length] = item; } } return propertyList; } } internal final class Walker { function Walker(reviver:Function) { this.reviver = reviver; } function walk(holder:Object, name:String):* { var val:Object = holder[name]; if (val is Array) { var v:Array = val as Array; for (var i:uint=0, limit:uint=v.length; i < limit; i++) { var newElement:* = walk(v, String(i)); if (newElement === undefined) delete v[i]; else v[i] = newElement; } } else if (val !== null && !(val is Boolean) && !(val is Number) && !(val is String)) { // // See earlier note about unsafe for-in enumeration in AS3. for (var p:String in val) { if (!val.AS3::hasOwnProperty(p)) break; var newElement:* = walk(val, p); if (newElement === undefined) delete val[p]; else val[p] = newElement; } } return reviver.AS3::call(holder, name, val); } var reviver:Function; } }
/* -*- c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */ /* ***** 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) 2010 * 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 ***** */ // JSON according to the ECMAScript 5 specification. // Based on ECMA-262-5 and Errata as of 31 July 2010 (no JSON errata at that time). // // Deliberate deviations from the specification // - There are additional type checks on JSON.parse and JSON.stringify - that fits AS3 better. // - Property enumeration order is indeterminate in AS3, so there is no attempt to extract // keys in any particular order when enumerating properties during filtering. // // Compiling it // - This code must be compilable with -strict. // - The code ought to work even if compiled with -AS3 because public:: qualifiers are // used where they matter. package { include "api-versions.as" /** * The JSON class lets developers import and export data to and from JavaScript Object Notation (JSON) format. JSON is an industry standard data-interchange * format that is described at <a href="http://www.json.org">http://www.json.org</a>. * * <p>This class supports most ActionScript classes. ActionScript classes that do not support JSON typically return their class name as a string.</p> * @playerversion Flash 11 * @playerversion AIR 3.0 * @langversion 3.0 */ [API(CONFIG::SWF_13)] [native(cls="JSONClass", classgc="exact", methods="auto", construct="none")] public final class JSON { private static const as3ns:Namespace = AS3; private native static function parseCore(text:String):Object; // specialized stringify procedure private native static function stringifySpecializedToString(value:Object, replacerArray:Array, replacerFunction:Function, gap:String):String; /** * Accepts a JSON-formatted String and returns an Actionscript Object that represents that value. JSON objects, * arrays, strings, numbers, booleans, and null map to corresponding Actionscript values, as shown below: * <p> * <table class="innertable"> * <tr><th>JSON type</th><th>ActionScript type</th></tr> * <tr><td>array</td><td>Array</td></tr> * <tr><td>string</td><td>String</td></tr> * <tr><td>number</td><td>Number</td></tr> * <tr><td>boolean</td><td>Boolean</td></tr> * <tr><td>null</td><td>null</td></tr> * </table> * </p> * * <p>The <code>reviver</code> parameter is a function that takes two parameters: a key and a value. You can use this * function to transform or filter each key/value pair as it is parsed. If you supply a <code>reviver</code> function, your transformed * or filtered value for each pair, rather than the default parsing, is returned in the <code>parse()</code> function output. If * the <code>reviver</code> function returns <code>undefined</code> for any pair, the property is deleted from the final result. * </p> * * <p>If the <code>parse()</code> function encounters duplicate name strings within the object being parsed, the value of the duplicate * key encountered last becomes the value for all preceding occurrences of that key. * </p> * * @param text The JSON string to be parsed * @param reviver (Optional) A function that transforms each key/value pair that is parsed ( * @playerversion Flash 11 * @playerversion AIR 3.0 * @langversion 3.0 */ public static function parse(text:String, reviver:Function = null):Object { if (text === null || text === undefined) { Error.throwError( SyntaxError, 1132 /*kJSONInvalidParseInput*/ ); } // at this point, we should be assured that text is String. var unfiltered: Object = parseCore(text); if (reviver === null) return unfiltered; return (new Walker(reviver)).walk({ "": unfiltered }, ""); } /** * Returns a String, in JSON format, that represents an Actionscript value. The <code>stringify</code> method can take three parameters. * * <p>The <code>value</code> parameter is required. This parameter is an Actionscript value. Typically, it is an Object or Array, * but it can also be a String, Boolean, Number, or null. * </p> * * <p>The optional <code>replacer</code> parameter can be either a function or an array of strings or numbers. If it is a function, * the function takes two parameters: a key and a value. You can use this * function to transform or filter each key/value pair as it is parsed. If you supply a <code>replacer</code> function, your transformed * or filtered value for each pair, rather than the default parsing, is returned in the <code>parse()</code> function output. If * the <code>replacer</code> function returns <code>undefined</code> for any pair, the property is deleted from the final result. If <code>replacer</code> * is an array, it is used as a filter for designating which properties should be included in the output. * </p> * * <p>The optional <code>space</code> parameter is a String or Number that allows white space to be injected into the returned string to improve human readability. * Entries in generated JSON objects and JSON arrays are separated by a gap derived from the <code>space</code> parameter. This gap is * always between 0 and 10 characters wide. If space is a string, then the derived gap is the first ten characters of that string. If space * is a non-negative number <i>x</i>, then the gap is <i>x</i> space characters, to a maximum of ten spaces. * </p> * * @param value The ActionScript value to be converted into a JSON string * @param replacer (Optional) A function or an array that transforms or filters key/value pairs in the <code>stringify</code> output * @param space (Optional) A string or number that controls added white space in the returned String * * @playerversion Flash 11 * @playerversion AIR 3.0 * @langversion 3.0 */ public static function stringify(value:Object, replacer=null, space=null):String { // We deliberately deviate from ECMA-262 and throw on // invalid replacer parameter. if (!(replacer === null || replacer is Function || replacer is Array)) Error.throwError( TypeError, 1131 /*kJSONInvalidReplacer*/ ); // We follow ECMA-262 and silently ignore invalid space parameter. if (!(space === null || space is String || space is Number)) space = null; var gap = ""; if (space is String) gap = space.length > 10 ? space.AS3::substring(0,10) : space; else if (space is Number) gap = " ".AS3::substring(0,Math.min(10,Math.floor(space))); if (replacer === null) { return stringifySpecializedToString(value, null, null, gap); } else if (replacer is Array) { return stringifySpecializedToString(value, computePropertyList(replacer), null, gap); } else { // replacer is Function return stringifySpecializedToString(value, null, replacer, gap); } } // ECMA-262 5th ed, section 15.12.3 stringify, step 4.b private static function computePropertyList(r:Array):Array { var propertyList = []; var alreadyAdded = {}; for (var i:uint=0, ilim:uint = r.length; i < ilim; i++) { if (!r.AS3::hasOwnProperty(i)) continue; var v = r[i]; var item: String = null; if (v is String) item = v; else if (v is Number) item = String(v); if (item !== null && !alreadyAdded[item]) { alreadyAdded[item] = true; propertyList[propertyList.length] = item; } } return propertyList; } } internal final class Walker { function Walker(reviver:Function) { this.reviver = reviver; } function walk(holder:Object, name:String):* { var val:Object = holder[name]; if (val is Array) { var v:Array = val as Array; for (var i:uint=0, limit:uint=v.length; i < limit; i++) { var newElement:* = walk(v, String(i)); if (newElement === undefined) delete v[i]; else v[i] = newElement; } } else if (val !== null && !(val is Boolean) && !(val is Number) && !(val is String)) { // // See earlier note about unsafe for-in enumeration in AS3. for (var p:String in val) { if (!val.AS3::hasOwnProperty(p)) break; var newElement:* = walk(val, p); if (newElement === undefined) delete val[p]; else val[p] = newElement; } } return reviver.AS3::call(holder, name, val); } var reviver:Function; } }
Update asdocs in JSON.as (no bug, r=stejohns)
Update asdocs in JSON.as (no bug, r=stejohns)
ActionScript
mpl-2.0
pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux
1e2abca489e9807c8cb1da8b004646f09ba08989
frameworks/projects/framework/src/mx/formatters/DateBase.as
frameworks/projects/framework/src/mx/formatters/DateBase.as
//////////////////////////////////////////////////////////////////////////////// // // 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.formatters { import flash.events.Event; import mx.core.mx_internal; import mx.resources.IResourceManager; import mx.resources.ResourceManager; use namespace mx_internal; [ResourceBundle("formatters")] [ResourceBundle("SharedResources")] /** * The DateBase class contains the localized string information * used by the mx.formatters.DateFormatter class and the parsing function * that renders the pattern. * This is a helper class for the DateFormatter class that is not usually * used independently. * * @see mx.formatters.DateFormatter * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class DateBase { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- /** * @private */ private static var initialized:Boolean = false; /** * @private * Storage for the resourceManager getter. * This gets initialized on first access, * not at static initialization time, in order to ensure * that the Singleton registry has already been initialized. */ private static var _resourceManager:IResourceManager; /** * @private * A reference to the object which manages * all of the application's localized resources. * This is a singleton instance which implements * the IResourceManager interface. */ private static function get resourceManager():IResourceManager { if (!_resourceManager) _resourceManager = ResourceManager.getInstance(); return _resourceManager; } //-------------------------------------------------------------------------- // // Class properties // //-------------------------------------------------------------------------- //---------------------------------- // dayNamesLong //---------------------------------- /** * @private * Storage for the dayNamesLong property. */ private static var _dayNamesLong:Array; /* of String */ /** * @private */ private static var dayNamesLongOverride:Array; /* of String */ /** * Long format of day names. * * @default ["Sunday", "Monday", "Tuesday", "Wednesday", * "Thursday", "Friday", "Saturday"] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get dayNamesLong():Array /* of String */ { initialize(); return _dayNamesLong; } /** * @private */ public static function set dayNamesLong(value:Array /* of String*/):void { dayNamesLongOverride = value; _dayNamesLong = value != null ? value : resourceManager.getStringArray( "SharedResources", "dayNames"); } //---------------------------------- // dayNamesShort //---------------------------------- /** * @private * Storage for the dayNamesShort property. */ private static var _dayNamesShort:Array; /* of String */ /** * @private */ private static var dayNamesShortOverride:Array; /* of String */ /** * Short format of day names. * * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get dayNamesShort():Array /* of String */ { initialize(); return _dayNamesShort; } /** * @private */ public static function set dayNamesShort(value:Array /* of String*/):void { dayNamesShortOverride = value; _dayNamesShort = value != null ? value : resourceManager.getStringArray( "formatters", "dayNamesShort"); } //---------------------------------- // defaultStringKey //---------------------------------- /** * @private */ mx_internal static function get defaultStringKey():Array /* of String */ { initialize(); return monthNamesLong.concat(timeOfDay); } //---------------------------------- // monthNamesLong //---------------------------------- /** * @private * Storage for the monthNamesLong property. */ private static var _monthNamesLong:Array; /* of String */ /** * @private */ private static var monthNamesLongOverride:Array; /* of String */ /** * Long format of month names. * * @default ["January", "February", "March", "April", "May", "June", * "July", "August", "September", "October", "November", "December"]. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get monthNamesLong():Array /* of String */ { initialize(); return _monthNamesLong; } /** * @private */ public static function set monthNamesLong(value:Array /* of String*/):void { monthNamesLongOverride = value; _monthNamesLong = value != null ? value : resourceManager.getStringArray( "SharedResources", "monthNames"); if (value == null) { // Currently there is no way to get a null // string from resourceBundles using getString // Hence monthSymbol is a space in English, but // we actually want it to be a null string. var monthSymbol:String = resourceManager.getString( "SharedResources", "monthSymbol"); if (monthSymbol != " ") { // _monthNamesLong will be null if there are no resources. var n:int = _monthNamesLong ? _monthNamesLong.length : 0; for (var i:int = 0; i < n; i++) { _monthNamesLong[i] += monthSymbol; } } } } //---------------------------------- // monthNamesShort //---------------------------------- /** * @private * Storage for the monthNamesShort property. */ private static var _monthNamesShort:Array; /* of String */ /** * @private */ private static var monthNamesShortOverride:Array; /* of String */ /** * Short format of month names. * * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", * "Jul", "Aug", "Sep", "Oct","Nov", "Dec"] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get monthNamesShort():Array /* of String */ { initialize(); return _monthNamesShort; } /** * @private */ public static function set monthNamesShort(value:Array /* of String*/):void { monthNamesShortOverride = value; _monthNamesShort = value != null ? value : resourceManager.getStringArray( "formatters", "monthNamesShort"); if (value == null) { // Currently there is no way to get a null // string from resourceBundles using getString // Hence monthSymbol is a space in English, but // we actually want it to be a null string. var monthSymbol:String = resourceManager.getString( "SharedResources", "monthSymbol"); if (monthSymbol != " ") { // _monthNamesShort will be null if there are no resources. var n:int = _monthNamesShort ? _monthNamesShort.length : 0; for (var i:int = 0; i < n; i++) { _monthNamesShort[i] += monthSymbol; } } } } //---------------------------------- // timeOfDay //---------------------------------- /** * @private * Storage for the timeOfDay property. */ private static var _timeOfDay:Array; /* of String */ /** * @private */ private static var timeOfDayOverride:Array; /* of String */ /** * Time of day names. * * @default ["AM", "PM"] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get timeOfDay():Array /* of String */ { initialize(); return _timeOfDay; } /** * @private */ public static function set timeOfDay(value:Array /* of String */):void { timeOfDayOverride = value; var am:String = resourceManager.getString("formatters", "am"); var pm:String = resourceManager.getString("formatters", "pm"); _timeOfDay = value != null ? value : [ am, pm ]; } //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- /** * @private */ private static function initialize():void { if (!initialized) { // Register as a weak listener for "change" events // from ResourceManager. resourceManager.addEventListener( Event.CHANGE, static_resourceManager_changeHandler, false, 0, true); static_resourcesChanged(); initialized = true; } } /** * @private */ private static function static_resourcesChanged():void { dayNamesLong = dayNamesLongOverride; dayNamesShort = dayNamesShortOverride; monthNamesLong = monthNamesLongOverride; monthNamesShort = monthNamesShortOverride; timeOfDay = timeOfDayOverride; } /** * @private * Parses token objects and renders the elements of the formatted String. * For details about token objects, see StringFormatter. * * @param date Date object. * * @param tokenInfo Array object that contains token object descriptions. * * @return Formatted string. */ mx_internal static function extractTokenDate(date:Date, tokenInfo:Object):String { initialize(); var result:String = ""; var key:int = int(tokenInfo.end) - int(tokenInfo.begin); var day:int; var hours:int; switch (tokenInfo.token) { case "Y": { // year var year:String = date.getFullYear().toString(); if (key < 3) return year.substr(2); else if (key > 4) return setValue(Number(year), key); else return year; } case "M": { // month in year var month:int = int(date.getMonth()); if (key < 3) { month++; // zero based result += setValue(month, key); return result; } else if (key == 3) { return monthNamesShort[month]; } else { return monthNamesLong[month]; } } case "D": { // day in month day = int(date.getDate()); result += setValue(day, key); return result; } case "E": { // day in the week day = int(date.getDay()); if (key < 3) { result += setValue(day, key); return result; } else if (key == 3) { return dayNamesShort[day]; } else { return dayNamesLong[day]; } } case "A": { // am/pm marker hours = int(date.getHours()); if (hours < 12) return timeOfDay[0]; else return timeOfDay[1]; } case "H": { // hour in day (1-24) hours = int(date.getHours()); if (hours == 0) hours = 24; result += setValue(hours, key); return result; } case "J": { // hour in day (0-23) hours = int(date.getHours()); result += setValue(hours, key); return result; } case "K": { // hour in am/pm (0-11) hours = int(date.getHours()); if (hours >= 12) hours = hours - 12; result += setValue(hours, key); return result; } case "L": { // hour in am/pm (1-12) hours = int(date.getHours()); if (hours == 0) hours = 12; else if (hours > 12) hours = hours - 12; result += setValue(hours, key); return result; } case "N": { // minutes in hour var mins:int = int(date.getMinutes()); result += setValue(mins, key); return result; } case "S": { // seconds in minute var sec:int = int(date.getSeconds()); result += setValue(sec, key); return result; } case "Q": { // milliseconds in second var ms:int = int(date.getMilliseconds()); result += setValue(ms, key); return result; } case "Z": case "O": { // timezone offset var offset:int = int(date.timezoneOffset); hours = offset/60; mins = offset - hours*60; var tzStr:String = ""; if (tokenInfo.token == "Z") tzStr = "Z"; if (key < 2 && mins == 0) tzStr += setValue(hours, key); else if (key < 3) tzStr += setValue(hours, key) + ":" + setValue(mins, key); if (offset >= 0) tzStr = "+" + tzStr; result += tzStr; return result; } } return result; } /** * @private * Makes a given length of digits longer by padding with zeroes. * * @param value Value to pad. * * @param key Length of the string to pad. * * @return Formatted string. */ private static function setValue(value:Object, key:int):String { var result:String = ""; var vLen:int = value.toString().length; if (vLen < key) { var n:int = key - vLen; for (var i:int = 0; i < n; i++) { result += "0" } } result += value.toString(); return result; } //-------------------------------------------------------------------------- // // Class event handlers // //-------------------------------------------------------------------------- /** * @private */ private static function static_resourceManager_changeHandler(event:Event):void { static_resourcesChanged(); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.formatters { import flash.events.Event; import mx.core.mx_internal; import mx.resources.IResourceManager; import mx.resources.ResourceManager; use namespace mx_internal; [ResourceBundle("formatters")] [ResourceBundle("SharedResources")] /** * The DateBase class contains the localized string information * used by the mx.formatters.DateFormatter class and the parsing function * that renders the pattern. * This is a helper class for the DateFormatter class that is not usually * used independently. * * @see mx.formatters.DateFormatter * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class DateBase { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- /** * @private */ private static var initialized:Boolean = false; /** * @private * Storage for the resourceManager getter. * This gets initialized on first access, * not at static initialization time, in order to ensure * that the Singleton registry has already been initialized. */ private static var _resourceManager:IResourceManager; /** * @private * A reference to the object which manages * all of the application's localized resources. * This is a singleton instance which implements * the IResourceManager interface. */ private static function get resourceManager():IResourceManager { if (!_resourceManager) _resourceManager = ResourceManager.getInstance(); return _resourceManager; } //-------------------------------------------------------------------------- // // Class properties // //-------------------------------------------------------------------------- //---------------------------------- // dayNamesLong //---------------------------------- /** * @private * Storage for the dayNamesLong property. */ private static var _dayNamesLong:Array; /* of String */ /** * @private */ private static var dayNamesLongOverride:Array; /* of String */ /** * Long format of day names. * * @default ["Sunday", "Monday", "Tuesday", "Wednesday", * "Thursday", "Friday", "Saturday"] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get dayNamesLong():Array /* of String */ { initialize(); return _dayNamesLong; } /** * @private */ public static function set dayNamesLong(value:Array /* of String*/):void { dayNamesLongOverride = value; _dayNamesLong = value != null ? value : resourceManager.getStringArray( "SharedResources", "dayNames"); } //---------------------------------- // dayNamesShort //---------------------------------- /** * @private * Storage for the dayNamesShort property. */ private static var _dayNamesShort:Array; /* of String */ /** * @private */ private static var dayNamesShortOverride:Array; /* of String */ /** * Short format of day names. * * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get dayNamesShort():Array /* of String */ { initialize(); return _dayNamesShort; } /** * @private */ public static function set dayNamesShort(value:Array /* of String*/):void { dayNamesShortOverride = value; _dayNamesShort = value != null ? value : resourceManager.getStringArray( "formatters", "dayNamesShort"); } //---------------------------------- // defaultStringKey //---------------------------------- /** * @private */ mx_internal static function get defaultStringKey():Array /* of String */ { initialize(); return monthNamesLong.concat(timeOfDay); } //---------------------------------- // monthNamesLong //---------------------------------- /** * @private * Storage for the monthNamesLong property. */ private static var _monthNamesLong:Array; /* of String */ /** * @private */ private static var monthNamesLongOverride:Array; /* of String */ /** * Long format of month names. * * @default ["January", "February", "March", "April", "May", "June", * "July", "August", "September", "October", "November", "December"]. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get monthNamesLong():Array /* of String */ { initialize(); return _monthNamesLong; } /** * @private */ public static function set monthNamesLong(value:Array /* of String*/):void { monthNamesLongOverride = value; _monthNamesLong = value != null ? value : resourceManager.getStringArray( "SharedResources", "monthNames"); if (value == null) { // Currently there is no way to get a null // string from resourceBundles using getString // Hence monthSymbol is a space in English, but // we actually want it to be a null string. var monthSymbol:String = resourceManager.getString( "SharedResources", "monthSymbol"); if (monthSymbol != " ") { // _monthNamesLong will be null if there are no resources. var n:int = _monthNamesLong ? _monthNamesLong.length : 0; for (var i:int = 0; i < n; i++) { _monthNamesLong[i] += monthSymbol; } } } } //---------------------------------- // monthNamesShort //---------------------------------- /** * @private * Storage for the monthNamesShort property. */ private static var _monthNamesShort:Array; /* of String */ /** * @private */ private static var monthNamesShortOverride:Array; /* of String */ /** * Short format of month names. * * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", * "Jul", "Aug", "Sep", "Oct","Nov", "Dec"] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get monthNamesShort():Array /* of String */ { initialize(); return _monthNamesShort; } /** * @private */ public static function set monthNamesShort(value:Array /* of String*/):void { monthNamesShortOverride = value; _monthNamesShort = value != null ? value : resourceManager.getStringArray( "formatters", "monthNamesShort"); if (value == null) { // Currently there is no way to get a null // string from resourceBundles using getString // Hence monthSymbol is a space in English, but // we actually want it to be a null string. var monthSymbol:String = resourceManager.getString( "SharedResources", "monthSymbol"); if (monthSymbol != " ") { // _monthNamesShort will be null if there are no resources. var n:int = _monthNamesShort ? _monthNamesShort.length : 0; for (var i:int = 0; i < n; i++) { _monthNamesShort[i] += monthSymbol; } } } } //---------------------------------- // timeOfDay //---------------------------------- /** * @private * Storage for the timeOfDay property. */ private static var _timeOfDay:Array; /* of String */ /** * @private */ private static var timeOfDayOverride:Array; /* of String */ /** * Time of day names. * * @default ["AM", "PM"] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get timeOfDay():Array /* of String */ { initialize(); return _timeOfDay; } /** * @private */ public static function set timeOfDay(value:Array /* of String */):void { timeOfDayOverride = value; var am:String = resourceManager.getString("formatters", "am"); var pm:String = resourceManager.getString("formatters", "pm"); _timeOfDay = value != null ? value : [ am, pm ]; } //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- /** * @private */ private static function initialize():void { if (!initialized) { // Register as a weak listener for "change" events // from ResourceManager. resourceManager.addEventListener( Event.CHANGE, static_resourceManager_changeHandler, false, 0, true); static_resourcesChanged(); initialized = true; } } /** * @private */ private static function static_resourcesChanged():void { dayNamesLong = dayNamesLongOverride; dayNamesShort = dayNamesShortOverride; monthNamesLong = monthNamesLongOverride; monthNamesShort = monthNamesShortOverride; timeOfDay = timeOfDayOverride; } /** * @private * Parses token objects and renders the elements of the formatted String. * For details about token objects, see StringFormatter. * * @param date Date object. * * @param tokenInfo Array object that contains token object descriptions. * * @return Formatted string. */ mx_internal static function extractTokenDate(date:Date, tokenInfo:Object):String { initialize(); var result:String = ""; var key:int = int(tokenInfo.end) - int(tokenInfo.begin); var day:int; var hours:int; switch (tokenInfo.token) { case "Y": { // year var year:String = date.getFullYear().toString(); if (key < 3) return year.substr(2); else if (key > 4) return setValue(Number(year), key); else return year; } case "M": { // month in year var month:int = int(date.getMonth()); if (key < 3) { month++; // zero based result += setValue(month, key); return result; } else if (key == 3) { return monthNamesShort[month]; } else { return monthNamesLong[month]; } } case "D": { // day in month day = int(date.getDate()); result += setValue(day, key); return result; } case "E": { // day in the week day = int(date.getDay()); if (key < 3) { result += setValue(day, key); return result; } else if (key == 3) { return dayNamesShort[day]; } else { return dayNamesLong[day]; } } case "A": { // am/pm marker hours = int(date.getHours()); if (hours < 12) return timeOfDay[0]; else return timeOfDay[1]; } case "H": { // hour in day (1-24) hours = int(date.getHours()); if (hours == 0) hours = 24; result += setValue(hours, key); return result; } case "J": { // hour in day (0-23) hours = int(date.getHours()); result += setValue(hours, key); return result; } case "K": { // hour in am/pm (0-11) hours = int(date.getHours()); if (hours >= 12) hours = hours - 12; result += setValue(hours, key); return result; } case "L": { // hour in am/pm (1-12) hours = int(date.getHours()); if (hours == 0) hours = 12; else if (hours > 12) hours = hours - 12; result += setValue(hours, key); return result; } case "N": { // minutes in hour var mins:int = int(date.getMinutes()); result += setValue(mins, key); return result; } case "S": { // seconds in minute var sec:int = int(date.getSeconds()); result += setValue(sec, key); return result; } case "Q": { // milliseconds in second var ms:int = int(date.getMilliseconds()); result += setValue(ms, key); return result; } case "Z": case "O": { // timezone offset var offset:int = -1 * int(date.timezoneOffset); hours = offset/60; mins = offset - hours*60; var tzStr:String = ""; if (tokenInfo.token == "Z") tzStr = "Z"; if (key < 2 && mins == 0) tzStr += setValue(hours, key); else if (key < 3) tzStr += setValue(hours, key) + ":" + setValue(mins, key); if (offset >= 0) tzStr = "+" + tzStr; result += tzStr; return result; } } return result; } /** * @private * Makes a given length of digits longer by padding with zeroes. * * @param value Value to pad. * * @param key Length of the string to pad. * * @return Formatted string. */ private static function setValue(value:Object, key:int):String { var result:String = ""; var vLen:int = value.toString().length; if (vLen < key) { var n:int = key - vLen; for (var i:int = 0; i < n; i++) { result += "0" } } result += value.toString(); return result; } //-------------------------------------------------------------------------- // // Class event handlers // //-------------------------------------------------------------------------- /** * @private */ private static function static_resourceManager_changeHandler(event:Event):void { static_resourcesChanged(); } } }
fix time zone offset sign
fix time zone offset sign
ActionScript
apache-2.0
adufilie/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk
2d811d7c2a9c787b645978b70682b0e1329a0013
runtime/src/main/as/flump/mold/MovieMold.as
runtime/src/main/as/flump/mold/MovieMold.as
// // Flump - Copyright 2013 Flump Authors package flump.mold { import flump.display.Movie; /** @private */ public class MovieMold { public var id :String; public var layers :Vector.<LayerMold> = new <LayerMold>[]; public var labels :Vector.<Vector.<String>>; public static function fromJSON (o :Object) :MovieMold { const mold :MovieMold = new MovieMold(); mold.id = require(o, "id"); for each (var layer :Object in require(o, "layers")) mold.layers.push(LayerMold.fromJSON(layer)); return mold; } public function get frames () :int { var frames :int = 0; for each (var layer :LayerMold in layers) frames = Math.max(frames, layer.frames); return frames; } public function get flipbook () :Boolean { return (layers.length > 0 && layers[0].flipbook); } public function fillLabels () :void { labels = new Vector.<Vector.<String>>(frames, true); if (labels.length == 0) { return; } labels[0] = new <String>[]; labels[0].push(Movie.FIRST_FRAME); labels[frames - 1] = new <String>[]; labels[frames - 1].push(Movie.LAST_FRAME); for each (var layer :LayerMold in layers) { for each (var kf :KeyframeMold in layer.keyframes) { if (kf.label == null) continue; if (labels[kf.index] == null) labels[kf.index] = new <String>[]; labels[kf.index].push(kf.label); } } } public function scale (scale :Number) :MovieMold { const clone :MovieMold = fromJSON(JSON.parse(JSON.stringify(this))); for each (var layer :LayerMold in clone.layers) { for each (var kf :KeyframeMold in layer.keyframes) { kf.x *= scale; kf.y *= scale; kf.pivotX *= scale; kf.pivotY *= scale; } } return clone; } public function toJSON (_:*) :Object { const json :Object = { id: id, layers: layers }; return json } public function toXML () :XML { var xml :XML = <movie name={id}/>; for each (var layer :LayerMold in layers) xml.appendChild(layer.toXML()); return xml; } } }
// // Flump - Copyright 2013 Flump Authors package flump.mold { import flump.display.Movie; /** @private */ public class MovieMold { public var id :String; public var layers :Vector.<LayerMold> = new <LayerMold>[]; public var labels :Vector.<Vector.<String>>; public static function fromJSON (o :Object) :MovieMold { const mold :MovieMold = new MovieMold(); mold.id = require(o, "id"); for each (var layer :Object in require(o, "layers")) mold.layers.push(LayerMold.fromJSON(layer)); return mold; } public function get frames () :int { var frames :int = 0; for each (var layer :LayerMold in layers) frames = Math.max(frames, layer.frames); return frames; } public function get flipbook () :Boolean { return (layers.length > 0 && layers[0].flipbook); } public function fillLabels () :void { labels = new Vector.<Vector.<String>>(frames, true); if (labels.length == 0) { return; } labels[0] = new <String>[]; labels[0].push(Movie.FIRST_FRAME); if (labels.length > 1) { // If we only have 1 frame, don't overwrite labels[0] labels[frames - 1] = new <String>[]; } labels[frames - 1].push(Movie.LAST_FRAME); for each (var layer :LayerMold in layers) { for each (var kf :KeyframeMold in layer.keyframes) { if (kf.label == null) continue; if (labels[kf.index] == null) labels[kf.index] = new <String>[]; labels[kf.index].push(kf.label); } } } public function scale (scale :Number) :MovieMold { const clone :MovieMold = fromJSON(JSON.parse(JSON.stringify(this))); for each (var layer :LayerMold in clone.layers) { for each (var kf :KeyframeMold in layer.keyframes) { kf.x *= scale; kf.y *= scale; kf.pivotX *= scale; kf.pivotY *= scale; } } return clone; } public function toJSON (_:*) :Object { const json :Object = { id: id, layers: layers }; return json } public function toXML () :XML { var xml :XML = <movie name={id}/>; for each (var layer :LayerMold in layers) xml.appendChild(layer.toXML()); return xml; } } }
Fix fillLabels for 1-frame movies
Fix fillLabels for 1-frame movies
ActionScript
mit
tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump
363f403235067ceb1c627955091ff103cfd5b800
WEB-INF/lps/lfc/kernel/swf9/LzMouseKernel.as
WEB-INF/lps/lfc/kernel/swf9/LzMouseKernel.as
/** * LzMouseKernel.as * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ // Receives mouse events from the runtime class LzMouseKernel { #passthrough (toplevel:true) { import flash.display.*; import flash.events.*; import flash.utils.*; import flash.ui.*; }# // sends mouse events to the callback static function __sendEvent(view, eventname) { if (LzMouseKernel.__callback) LzMouseKernel.__scope[LzMouseKernel.__callback](eventname, view); //Debug.write('LzMouseKernel event', eventname); } static var __callback = null; static var __scope = null; static var __lastMouseDown = null; static var __listeneradded:Boolean = false ; /** * Shows or hides the hand cursor for all clickable views. */ static var showhandcursor:Boolean = true; static function setCallback (scope, funcname) { LzMouseKernel.__scope = scope; LzMouseKernel.__callback = funcname; if (LzMouseKernel.__listeneradded == false) { LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_UP, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_DOWN, __mouseHandler); LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, __mouseLeavesHandler); LzMouseKernel.__listeneradded = true; } } // Handles global mouse events static function __mouseHandler(event:MouseEvent):void { var eventname = 'on' + event.type.toLowerCase(); //Debug.write('__mouseHandler', eventname); if (eventname == 'onmouseup' && __lastMouseDown != null) { // call mouseup on the sprite that got the last mouse down LzMouseKernel.__lastMouseDown.__globalmouseup(event); __lastMouseDown = null; } else { LzMouseKernel.__sendEvent(null, eventname); } } // handles MOUSE_LEAVES event static function __mouseLeavesHandler(event:Event):void { var eventname = 'on' + event.type.toLowerCase(); LzMouseKernel.__sendEvent(null, eventname); } /** * Shows or hides the hand cursor for all clickable views. * @param Boolean show: true shows the hand cursor for buttons, false hides it */ static function showHandCursor (show) { LzMouseKernel.showhandcursor = show; } static var __amLocked:Boolean = false; static var cursorSprite:Sprite = null; static var globalCursorResource:String = null; static var lastCursorResource:String = null; /** * Sets the cursor to a resource * @param String what: The resource to use as the cursor. */ static function setCursorGlobal ( what:String ){ globalCursorResource = what; setCursorLocal(what); } static function setCursorLocal ( what:String ) { if ( LzMouseKernel.__amLocked ) { return; } Mouse.hide(); cursorSprite.x = LFCApplication.stage.mouseX ; cursorSprite.y = LFCApplication.stage.mouseY ; LFCApplication.setChildIndex(cursorSprite, LFCApplication._sprite.numChildren-1); if (lastCursorResource != what) { if (cursorSprite.numChildren > 0) { cursorSprite.removeChildAt(0); } var resourceSprite = getCursorResource(what); resourceSprite.y = 1; cursorSprite.addChild( resourceSprite ); lastCursorResource = what; } // respond to mouse move events cursorSprite.startDrag(); LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler); cursorSprite.visible = true; } static function mouseLeaveHandler(evt:Event):void { cursorSprite.visible = false; } static function getCursorResource (resource:String):Sprite { var resinfo = LzResourceLibrary[resource]; var assetclass; var frames = resinfo.frames; var asset:DisplayObject; // single frame resources get an entry in LzResourceLibrary which has // 'assetclass' pointing to the resource Class object. if (resinfo.assetclass is Class) { assetclass = resinfo.assetclass; } else { // Multiframe resources have an array of Class objects in frames[] assetclass = frames[0]; } if (! assetclass) return; asset = new assetclass(); asset.scaleX = 1.0; asset.scaleY = 1.0; //Debug.write('cursor asset', asset); return asset; } /** * This function restores the default cursor if there is no locked cursor on * the screen. * * @access private */ static function restoreCursor ( ){ if ( LzMouseKernel.__amLocked ) { return; } cursorSprite.stopDrag(); cursorSprite.visible = false; globalCursorResource = null; Mouse.show(); } /** Called by LzSprite to restore cursor to global value. */ static function restoreCursorLocal ( ){ if ( LzMouseKernel.__amLocked ) { return; } if (globalCursorResource == null) { // Restore to system default pointer restoreCursor(); } else { // Restore to the last value set by setCursorGlobal setCursorLocal(globalCursorResource); } } /** * Prevents the cursor from being changed until unlock is called. * */ static function lock (){ LzMouseKernel.__amLocked = true; } /** * Restores the default cursor. * */ static function unlock (){ LzMouseKernel.__amLocked = false; LzMouseKernel.restoreCursor(); } static function initCursor () { cursorSprite = new Sprite(); cursorSprite.mouseEnabled = false; // Add the cursor DisplayObject to the root sprite LFCApplication.addChild(cursorSprite); cursorSprite.x = -10000; cursorSprite.y = -10000; } }
/** * LzMouseKernel.as * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ // Receives mouse events from the runtime class LzMouseKernel { #passthrough (toplevel:true) { import flash.display.*; import flash.events.*; import flash.utils.*; import flash.ui.*; }# // sends mouse events to the callback static function __sendEvent(view, eventname) { if (LzMouseKernel.__callback) LzMouseKernel.__scope[LzMouseKernel.__callback](eventname, view); //Debug.write('LzMouseKernel event', eventname); } static var __callback = null; static var __scope = null; static var __lastMouseDown = null; static var __listeneradded:Boolean = false ; /** * Shows or hides the hand cursor for all clickable views. */ static var showhandcursor:Boolean = true; static function setCallback (scope, funcname) { LzMouseKernel.__scope = scope; LzMouseKernel.__callback = funcname; if (LzMouseKernel.__listeneradded == false) { LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_UP, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_DOWN, __mouseHandler); LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, __mouseLeavesHandler); LzMouseKernel.__listeneradded = true; } } // Handles global mouse events static function __mouseHandler(event:MouseEvent):void { var eventname = 'on' + event.type.toLowerCase(); //Debug.write('__mouseHandler', eventname); if (eventname == 'onmouseup' && __lastMouseDown != null) { // call mouseup on the sprite that got the last mouse down LzMouseKernel.__lastMouseDown.__globalmouseup(event); __lastMouseDown = null; } else { LzMouseKernel.__sendEvent(null, eventname); } } // handles MOUSE_LEAVES event static function __mouseLeavesHandler(event:Event):void { var eventname = 'on' + event.type.toLowerCase(); LzMouseKernel.__sendEvent(null, eventname); } /** * Shows or hides the hand cursor for all clickable views. * @param Boolean show: true shows the hand cursor for buttons, false hides it */ static function showHandCursor (show) { LzMouseKernel.showhandcursor = show; } static var __amLocked:Boolean = false; static var cursorSprite:Sprite = null; static var globalCursorResource:String = null; static var lastCursorResource:String = null; /** * Sets the cursor to a resource * @param String what: The resource to use as the cursor. */ static function setCursorGlobal ( what:String ){ globalCursorResource = what; setCursorLocal(what); } static function setCursorLocal ( what:String ) { if ( LzMouseKernel.__amLocked ) { return; } Mouse.hide(); cursorSprite.x = LFCApplication.stage.mouseX + 1; cursorSprite.y = LFCApplication.stage.mouseY + 1; LFCApplication.setChildIndex(cursorSprite, LFCApplication._sprite.numChildren-1); if (lastCursorResource != what) { if (cursorSprite.numChildren > 0) { cursorSprite.removeChildAt(0); } var resourceSprite = getCursorResource(what); cursorSprite.addChild( resourceSprite ); lastCursorResource = what; } // respond to mouse move events cursorSprite.startDrag(); LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler); cursorSprite.visible = true; } static function mouseLeaveHandler(evt:Event):void { cursorSprite.visible = false; } static function getCursorResource (resource:String):Sprite { var resinfo = LzResourceLibrary[resource]; var assetclass; var frames = resinfo.frames; var asset:DisplayObject; // single frame resources get an entry in LzResourceLibrary which has // 'assetclass' pointing to the resource Class object. if (resinfo.assetclass is Class) { assetclass = resinfo.assetclass; } else { // Multiframe resources have an array of Class objects in frames[] assetclass = frames[0]; } if (! assetclass) return; asset = new assetclass(); asset.scaleX = 1.0; asset.scaleY = 1.0; //Debug.write('cursor asset', asset); return asset; } /** * This function restores the default cursor if there is no locked cursor on * the screen. * * @access private */ static function restoreCursor ( ){ if ( LzMouseKernel.__amLocked ) { return; } cursorSprite.stopDrag(); cursorSprite.visible = false; globalCursorResource = null; Mouse.show(); } /** Called by LzSprite to restore cursor to global value. */ static function restoreCursorLocal ( ){ if ( LzMouseKernel.__amLocked ) { return; } if (globalCursorResource == null) { // Restore to system default pointer restoreCursor(); } else { // Restore to the last value set by setCursorGlobal setCursorLocal(globalCursorResource); } } /** * Prevents the cursor from being changed until unlock is called. * */ static function lock (){ LzMouseKernel.__amLocked = true; } /** * Restores the default cursor. * */ static function unlock (){ LzMouseKernel.__amLocked = false; LzMouseKernel.restoreCursor(); } static function initCursor () { cursorSprite = new Sprite(); cursorSprite.mouseEnabled = false; // Add the cursor DisplayObject to the root sprite LFCApplication.addChild(cursorSprite); cursorSprite.x = -10000; cursorSprite.y = -10000; } }
Change 20080825-hqm-A by [email protected] on 2008-08-25 17:01:30 EDT in /Users/hqm/openlaszlo/trunk/WEB-INF/lps/lfc for http://svn.openlaszlo.org/openlaszlo/trunk/WEB-INF/lps/lfc
Change 20080825-hqm-A by [email protected] on 2008-08-25 17:01:30 EDT in /Users/hqm/openlaszlo/trunk/WEB-INF/lps/lfc for http://svn.openlaszlo.org/openlaszlo/trunk/WEB-INF/lps/lfc Summary: slight improvement for swf9 cursor tracking New Features: Bugs Fixed: Technical Reviewer: (pending) QA Reviewer: (pending) Doc Reviewer: (pending) Documentation: Release Notes: Details: The sprite only needs to be offset from the mouse position while loading, it can then track the mouse exactly via startDrag as usual. Tests: examples/components/grid_example.lzx -- cursor changes to arrows and does not blink when over column resizer. git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@10770 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
736682536f49fd2ff75131649a522c519d6d3022
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
package dolly { import dolly.core.dolly_internal; import dolly.data.CompositeCloneableClass; import org.as3commons.reflect.Type; use namespace dolly_internal; public class CloningOfCompositeCloneableClassTest { private var compositeCloneableClass:CompositeCloneableClass; private var compositeCloneableClassType:Type; [Before] public function before():void { compositeCloneableClass = new CompositeCloneableClass(); compositeCloneableClassType = Type.forInstance(compositeCloneableClass); } [After] public function after():void { compositeCloneableClass = null; compositeCloneableClassType = null; } } }
package dolly { import dolly.core.dolly_internal; import dolly.data.CompositeCloneableClass; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertNotNull; use namespace dolly_internal; public class CloningOfCompositeCloneableClassTest { private var compositeCloneableClass:CompositeCloneableClass; private var compositeCloneableClassType:Type; [Before] public function before():void { compositeCloneableClass = new CompositeCloneableClass(); compositeCloneableClassType = Type.forInstance(compositeCloneableClass); } [After] public function after():void { compositeCloneableClass = null; compositeCloneableClassType = null; } [Test] public function findingAllWritableFieldsForType():void { const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType); assertNotNull(writableFields); assertEquals(4, writableFields.length); } } }
Test for calculation of cloneable fields in CompositeCloneableClass.
Test for calculation of cloneable fields in CompositeCloneableClass.
ActionScript
mit
Yarovoy/dolly
0a31da2adef5b6c3f19d0741607996c1f446c6ea
src/net/manaca/preloaders/PreloaderBase.as
src/net/manaca/preloaders/PreloaderBase.as
package net.manaca.preloaders { import flash.display.MovieClip; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.system.Capabilities; import flash.utils.getDefinitionByName; import net.manaca.application.IApplication; /** * The Preloader class is used by the application to monitor * the download and initialization status of a flash application. * It is also responsible for downloading the runtime shared libraries (RSLs). * @author Sean Zou * */ public class PreloaderBase extends MovieClip { //========================================================================== // Variables //========================================================================== //========================================================================== // Constructor //========================================================================== /** * Application Constructor. */ public function PreloaderBase() { //stop at the first frame stop(); stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; if(root && root.loaderInfo) { root.loaderInfo.addEventListener(Event.INIT, initHanlder); } } //========================================================================== // Methods //========================================================================== /** * Create a PreloaderDisplay. * the default create a DownloadProgressBar. * @return * */ protected function initDisplay():void { } /** * Create a application. * @param params * @return * */ protected function createApplication():Object { var mainClassName:String; if (mainClassName == null) { var url:String = loaderInfo.loaderURL; var dot:int = url.lastIndexOf("."); var slash:int = url.lastIndexOf("/"); mainClassName = url.substring(slash + 1, dot); /* modify at flex 2 debuging error. */ if(Capabilities.isDebugger && mainClassName.indexOf("_debug") != -1) { mainClassName = mainClassName.slice(0, -6); } mainClassName = decodeURIComponent(mainClassName); } var mainClass:Class = Class(getDefinitionByName(mainClassName)); return mainClass ? new mainClass() : null; } /** * @private * initialize the application. */ protected function initialize():void { nextFrame(); var app:Object = createApplication(); addChild(app as Sprite); if(app is IApplication) { IApplication(app).initialize(); } } //========================================================================== // Event handlers //========================================================================== /** * Handler the init event. * @param e * */ protected function initHanlder(event:Event):void { initDisplay(); addEventListener(Event.ENTER_FRAME, enterFrameHandler); } /** * Use frame based loading */ protected function enterFrameHandler(event:Event):void { if (loaderInfo.bytesLoaded == loaderInfo.bytesTotal) { removeEventListener(Event.ENTER_FRAME, enterFrameHandler); initialize(); } } } }
package net.manaca.preloaders { import flash.display.MovieClip; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.system.Capabilities; import flash.utils.getDefinitionByName; import net.manaca.application.IApplication; /** * The Preloader class is used by the application to monitor * the download and initialization status of a flash application. * It is also responsible for downloading the runtime shared libraries (RSLs). * @author Sean Zou * */ public class PreloaderBase extends MovieClip { //========================================================================== // Variables //========================================================================== //========================================================================== // Constructor //========================================================================== /** * Application Constructor. */ public function PreloaderBase() { //stop at the first frame stop(); stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; if(root && root.loaderInfo) { root.loaderInfo.addEventListener(Event.INIT, initHanlder); } } //========================================================================== // Methods //========================================================================== /** * Create a PreloaderDisplay. * the default create a DownloadProgressBar. * @return * */ protected function initDisplay():void { } /** * Create a application. * @param params * @return * */ protected function createApplication():Object { var mainClassName:String; if (mainClassName == null) { var url:String = loaderInfo.loaderURL; var dot:int = url.lastIndexOf("."); var slash:int = url.lastIndexOf("/"); mainClassName = url.substring(slash + 1, dot); /* modify at flex 2 debuging error. */ if(Capabilities.isDebugger && mainClassName.indexOf("_debug") != -1) { mainClassName = mainClassName.slice(0, -6); } mainClassName = decodeURIComponent(mainClassName); } var mainClass:Class = Class(getDefinitionByName(mainClassName)); return mainClass ? new mainClass() : null; } /** * @private * initialize the application. */ protected function initialize():void { nextFrame(); var app:Object = createApplication(); addChild(app as Sprite); if(app is IApplication) { IApplication(app).initialize(); } } //========================================================================== // Event handlers //========================================================================== /** * Handler the init event. * @param e * */ protected function initHanlder(event:Event):void { initDisplay(); addEventListener(Event.ENTER_FRAME, enterFrameHandler); } /** * Use frame based loading */ protected function enterFrameHandler(event:Event):void { var loaded:uint = loaderInfo.bytesLoaded; var total:uint = loaderInfo.bytesTotal; if((loaded >= total && total > 0) || (total == 0 && loaded > 0) || (root is MovieClip && (MovieClip(root).totalFrames > 2) && (MovieClip(root).framesLoaded >= 2))) { removeEventListener(Event.ENTER_FRAME, enterFrameHandler); initialize(); } } } }
修正在带有gzip的请求时,导致无法判断flash是否加载完成的错误.
修正在带有gzip的请求时,导致无法判断flash是否加载完成的错误.
ActionScript
mit
wersling/manaca,wersling/manaca
0fa1480dc35a0dca5f4c6fa0ab19a2bb958504cf
WeaveCore/src/weave/core/LinkableXML.as
WeaveCore/src/weave/core/LinkableXML.as
/* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave 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 Weave. If not, see <http://www.gnu.org/licenses/>. */ package weave.core { /** * LinkableBoolean, LinkableString and LinkableNumber contain simple, immutable data types. LinkableXML * is an exception because it contains an XML object that can be manipulated. Changes to the internal * XML object cannot be detected automatically, so a detectChanges() function is provided. However, if * two LinkableXML objects have the same internal XML object, modifying the internal XML of one object * would inadvertently modify the internal XML of another. To avoid this situation, LinkableXML creates * a copy of the XML that you set as the session state. * * @author adufilie * @see weave.core.LinkableVariable */ public class LinkableXML extends LinkableVariable { public function LinkableXML(allowNull:Boolean = true) { super(String, allowNull ? null : notNull); } private function notNull(value:Object):Boolean { return value != null; } /** * This function will run the callbacks attached to this LinkableXML if the session state has changed. * This function should be called if the XML is modified without calling set value() or setSessionState(). */ public function detectChanges():void { value = value; } /** * This is the sessioned XML value for this object. */ public function get value():XML { // validate local XML version of the session state String if necessary if (_prevTriggerCount != triggerCounter) { _prevTriggerCount = triggerCounter; _sessionStateXML = null; try { if (_sessionState) // false if empty string (prefer null over empty xml) _sessionStateXML = XML(_sessionState); } catch (e:Error) { // xml parsing failed, so keep null } } return _sessionStateXML; } /** * This will save a COPY of the value passed in to prevent multiple LinkableXML objects from having the same internal XML object. * @param value An XML to copy and save as the sessioned value for this object. */ public function set value(value:XML):void { var str:String = value ? value.toXMLString() : null; setSessionState(str); } override public function setSessionState(value:Object):void { if (value && value.hasOwnProperty(XML_STRING)) value = value[XML_STRING]; if (value is XML) value = (value as XML).toXMLString(); super.setSessionState(value); } override public function getSessionState():Object { // return an XMLString wrapper object for use with WeaveXMLEncoder. var result:Object = {}; result[XML_STRING] = _sessionState; return result; } public static const XML_STRING:String = "XMLString"; /** * This is used to store an XML value, which is separate from the actual session state String. */ private var _sessionStateXML:XML = null; /** * This is the trigger count at the time when _sessionStateXML was last updated. */ private var _prevTriggerCount:uint = triggerCounter; } }
/* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave 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 Weave. If not, see <http://www.gnu.org/licenses/>. */ package weave.core { /** * LinkableBoolean, LinkableString and LinkableNumber contain simple, immutable data types. LinkableXML * is an exception because it contains an XML object that can be manipulated. Changes to the internal * XML object cannot be detected automatically, so a detectChanges() function is provided. However, if * two LinkableXML objects have the same internal XML object, modifying the internal XML of one object * would inadvertently modify the internal XML of another. To avoid this situation, LinkableXML creates * a copy of the XML that you set as the session state. * * @author adufilie * @see weave.core.LinkableVariable */ public class LinkableXML extends LinkableVariable { public function LinkableXML(allowNull:Boolean = true) { super(String, verifyXMLString); _allowNull = allowNull; } private var _allowNull:Boolean; private function verifyXMLString(value:String):Boolean { if (value == null) return _allowNull; try { XML(value); return true; } catch (e:*) { } return false; } /** * This function will run the callbacks attached to this LinkableXML if the session state has changed. * This function should be called if the XML is modified without calling set value() or setSessionState(). */ public function detectChanges():void { value = value; } /** * This is the sessioned XML value for this object. */ public function get value():XML { // validate local XML version of the session state String if necessary if (_prevTriggerCount != triggerCounter) { _prevTriggerCount = triggerCounter; _sessionStateXML = null; try { if (_sessionState) // false if empty string (prefer null over empty xml) _sessionStateXML = XML(_sessionState); } catch (e:Error) { // xml parsing failed, so keep null } } return _sessionStateXML; } /** * This will save a COPY of the value passed in to prevent multiple LinkableXML objects from having the same internal XML object. * @param value An XML to copy and save as the sessioned value for this object. */ public function set value(value:XML):void { var str:String = value ? value.toXMLString() : null; setSessionState(str); } override public function setSessionState(value:Object):void { if (value && value.hasOwnProperty(XML_STRING)) value = value[XML_STRING]; if (value is XML) value = (value as XML).toXMLString(); super.setSessionState(value); } override public function getSessionState():Object { // return an XMLString wrapper object for use with WeaveXMLEncoder. var result:Object = {}; result[XML_STRING] = _sessionState; return result; } public static const XML_STRING:String = "XMLString"; /** * This is used to store an XML value, which is separate from the actual session state String. */ private var _sessionStateXML:XML = null; /** * This is the trigger count at the time when _sessionStateXML was last updated. */ private var _prevTriggerCount:uint = triggerCounter; } }
verify function now checks for valid xml
verify function now checks for valid xml
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
f7adc1f33149ca93f28c295e299bf1f8d4d29d18
runtime/src/main/as/flump/display/Movie.as
runtime/src/main/as/flump/display/Movie.as
// // Flump - Copyright 2013 Flump Authors package flump.display { import flump.mold.MovieMold; import react.Signal; import starling.animation.IAnimatable; import starling.display.DisplayObject; import starling.display.Sprite; import starling.events.Event; /** * A movie created from flump-exported data. It has children corresponding to the layers in the * movie in Flash, in the same order and with the same names. It fills in those children * initially with the image or movie of the symbol on that exported layer. After the initial * population, it only applies the keyframe-based transformations to the child at the index * corresponding to the layer. This means it's safe to swap in other DisplayObjects at those * positions to have them animated in place of the initial child. * * <p>A Movie will not animate unless it's added to a Juggler (or its advanceTime() function * is otherwise called). When the movie is added to a juggler, it advances its playhead with the * frame ticks if isPlaying is true. It will automatically remove itself from its juggler when * removed from the stage.</p> * * @see Library and LibraryLoader to create instances of Movie. */ public class Movie extends Sprite implements IAnimatable { /** A label fired by all movies when entering their first frame. */ public static const FIRST_FRAME :String = "flump.movie.FIRST_FRAME"; /** A label fired by all movies when entering their last frame. */ public static const LAST_FRAME :String = "flump.movie.LAST_FRAME"; /** Fires the label string whenever it's passed in playing. */ public const labelPassed :Signal = new Signal(String); /** @private */ public function Movie (src :MovieMold, frameRate :Number, library :Library) { this.name = src.id; _labels = src.labels; _frameRate = frameRate; if (src.flipbook) { _layers = new Vector.<Layer>(1, true); _layers[0] = new Layer(this, src.layers[0], library, /*flipbook=*/true); _numFrames = src.layers[0].frames; } else { _layers = new Vector.<Layer>(src.layers.length, true); for (var ii :int = 0; ii < _layers.length; ii++) { _layers[ii] = new Layer(this, src.layers[ii], library, /*flipbook=*/false); _numFrames = Math.max(src.layers[ii].frames, _numFrames); } } _duration = _numFrames / _frameRate; updateFrame(0, 0); // When we're removed from the stage, remove ourselves from any juggler animating us. addEventListener(Event.REMOVED_FROM_STAGE, function (..._) :void { dispatchEventWith(Event.REMOVE_FROM_JUGGLER); }); } /** @return the frame being displayed. */ public function get frame () :int { return _frame; } /** @return the number of frames in the movie. */ public function get numFrames () :int { return _numFrames; } /** @return true if the movie is currently playing. */ public function get isPlaying () :Boolean { return _playing; } /** @return true if the movie contains the given label. */ public function hasLabel (label :String) :Boolean { return getFrameForLabel(label) >= 0; } /** Plays the movie from its current frame. The movie will loop forever. */ public function loop () :Movie { _playing = true; _stopFrame = NO_FRAME; return this; } /** Plays the movie from its current frame, stopping when it reaches its last frame. */ public function playOnce () :Movie { return playTo(LAST_FRAME); } /** * Moves to the given String label or int frame. Doesn't alter playing status or stop frame. * If there are labels at the given position, they're fired as part of the goto, even if the * current frame is equal to the destination. Labels between the current frame and the * destination frame are not fired. * * @param position the int frame or String label to goto. * * @return this movie for chaining * * @throws Error if position isn't an int or String, or if it is a String and that String isn't * a label on this movie */ public function goTo (position :Object) :Movie { const frame :int = extractFrame(position); updateFrame(frame, 0); return this; } /** * Plays the movie from its current frame. The movie will stop when it reaches the given label * or frame. * * @param position to int frame or String label to stop at * * @return this movie for chaining * * @throws Error if position isn't an int or String, or if it is a String and that String isn't * a label on this movie. */ public function playTo (position :Object) :Movie { // won't play if we're already at the stop position return stopAt(position).play(); } /** Sets the stop frame for this Movie. * * @param position the int frame or String label to stop at. * * @return this movie for chaining * * @throws Error if position isn't an int or String, or if it is a String and that String isn't * a label on this movie. */ public function stopAt (position :Object) :Movie { _stopFrame = extractFrame(position); return this; } /** Sets the movie playing. Movie will automatically stop at its stopFrame, if one is set, * otherwise it will loop forever. * * @return this movie for chaining */ public function play () :Movie { // set playing to true unless movie is at the stop frame _playing = (_frame != _stopFrame) || (_stopFrame == NO_FRAME); return this; } /** Stops playback if it's currently active. Doesn't alter the current frame or stop frame. */ public function stop () :Movie { _playing = false; return this; } /** Advances the playhead by the give number of seconds. From IAnimatable. */ public function advanceTime (dt :Number) :void { if (dt < 0) throw new Error("Invalid time [dt=" + dt + "]"); if (_skipAdvanceTime) { _skipAdvanceTime = false; return; } if (!_playing) return; if (_numFrames > 1) { _playTime += dt; var actualPlaytime :Number = _playTime; if (_playTime >= _duration) _playTime %= _duration; // If _playTime is very close to _duration, rounding error can cause us to // land on lastFrame + 1. Protect against that. var newFrame :int = clamp(int(_playTime * _frameRate), 0, _numFrames - 1); // If the update crosses or goes to the stopFrame: // go to the stopFrame, stop the movie, clear the stopFrame if (_stopFrame != NO_FRAME) { // how many frames remain to the stopframe? var framesRemaining :int = (_frame <= _stopFrame ? _stopFrame - _frame : _numFrames - _frame + _stopFrame); var framesElapsed :int = int(actualPlaytime * _frameRate) - _frame; if (framesElapsed >= framesRemaining) { _playing = false; newFrame = _stopFrame; } } updateFrame(newFrame, dt); } for (var ii :int = this.numChildren - 1; ii >= 0; --ii) { var child :DisplayObject = getChildAt(ii); if (child is Movie) { Movie(child).advanceTime(dt); } } } /** * @private * * Called when the Movie has been newly added to a layer. */ internal function addedToLayer () :void { goTo(0); _skipAdvanceTime = true; } /** @private */ protected function extractFrame (position :Object) :int { if (position is int) return int(position); if (!(position is String)) throw new Error("Movie position must be an int frame or String label"); const label :String = String(position); var frame :int = getFrameForLabel(label); if (frame < 0) { throw new Error("No such label '" + label + "'"); } return frame; } /** * @private * * Returns the frame index for the given label, or -1 if the label doesn't exist. */ protected function getFrameForLabel (label :String) :int { for (var ii :int = 0; ii < _labels.length; ii++) { if (_labels[ii] != null && _labels[ii].indexOf(label) != -1) return ii; } return -1; } /** * @private * * @param dt the timeline's elapsed time since the last update. This should be 0 * for updates that are the result of a "goTo" call. */ protected function updateFrame (newFrame :int, dt :Number) :void { if (newFrame < 0 || newFrame >= _numFrames) { throw new Error("Invalid frame [frame=" + newFrame, " validRange=0-" + (_numFrames - 1) + "]"); } if (_isUpdatingFrame) { _pendingFrame = newFrame; return; } else { _pendingFrame = NO_FRAME; _isUpdatingFrame = true; } const isGoTo :Boolean = (dt <= 0); const wrapped :Boolean = (dt >= _duration) || (newFrame < _frame); if (newFrame != _frame) { if (wrapped) { for each (var layer :Layer in _layers) { layer.movieLooped(); } } for each (layer in _layers) layer.drawFrame(newFrame); } if (isGoTo) _playTime = newFrame / _frameRate; // Update the frame before firing frame label signals, so if firing changes the frame, // it sticks. const oldFrame :int = _frame; _frame = newFrame; // determine which labels to fire signals for var startFrame :int; var frameCount :int; if (isGoTo) { startFrame = newFrame; frameCount = 1; } else { startFrame = (oldFrame + 1 < _numFrames ? oldFrame + 1 : 0); frameCount = (_frame - oldFrame); if (wrapped) frameCount += _numFrames; } // Fire signals. Stop if pendingFrame is updated, which indicates that the client // has called goTo() var frameIdx :int = startFrame; for (var ii :int = 0; ii < frameCount; ++ii) { if (_pendingFrame != NO_FRAME) break; if (_labels[frameIdx] != null) { for each (var label :String in _labels[frameIdx]) { labelPassed.emit(label); if (_pendingFrame != NO_FRAME) break; } } // avoid modulo division by updating frameIdx each time through the loop if (++frameIdx == _numFrames) { frameIdx = 0; } } _isUpdatingFrame = false; // If we were interrupted by a goTo(), update to that frame now. if (_pendingFrame != NO_FRAME) { newFrame = _pendingFrame; updateFrame(newFrame, 0); } } protected static function clamp (n :Number, min :Number, max :Number) :Number { return Math.min(Math.max(n, min), max); } /** @private */ protected var _isUpdatingFrame :Boolean; /** @private */ protected var _pendingFrame :int = NO_FRAME; /** @private */ protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME; /** @private */ protected var _playing :Boolean = true; /** @private */ protected var _playTime :Number, _duration :Number; /** @private */ protected var _layers :Vector.<Layer>; /** @private */ protected var _numFrames :int; /** @private */ protected var _frameRate :Number; /** @private */ protected var _labels :Vector.<Vector.<String>>; /** @private */ private var _skipAdvanceTime :Boolean = false; /** @private */ internal var _playerData :MoviePlayerNode; private static const NO_FRAME :int = -1; } }
// // Flump - Copyright 2013 Flump Authors package flump.display { import flump.mold.MovieMold; import react.Signal; import starling.animation.IAnimatable; import starling.display.DisplayObject; import starling.display.Sprite; import starling.events.Event; /** * A movie created from flump-exported data. It has children corresponding to the layers in the * movie in Flash, in the same order and with the same names. It fills in those children * initially with the image or movie of the symbol on that exported layer. After the initial * population, it only applies the keyframe-based transformations to the child at the index * corresponding to the layer. This means it's safe to swap in other DisplayObjects at those * positions to have them animated in place of the initial child. * * <p>A Movie will not animate unless it's added to a Juggler (or its advanceTime() function * is otherwise called). When the movie is added to a juggler, it advances its playhead with the * frame ticks if isPlaying is true. It will automatically remove itself from its juggler when * removed from the stage.</p> * * @see Library and LibraryLoader to create instances of Movie. */ public class Movie extends Sprite implements IAnimatable { /** A label fired by all movies when entering their first frame. */ public static const FIRST_FRAME :String = "flump.movie.FIRST_FRAME"; /** A label fired by all movies when entering their last frame. */ public static const LAST_FRAME :String = "flump.movie.LAST_FRAME"; /** Fires the label string whenever it's passed in playing. */ public const labelPassed :Signal = new Signal(String); /** @private */ public function Movie (src :MovieMold, frameRate :Number, library :Library) { this.name = src.id; _labels = src.labels; _frameRate = frameRate; if (src.flipbook) { _layers = new Vector.<Layer>(1, true); _layers[0] = new Layer(this, src.layers[0], library, /*flipbook=*/true); _numFrames = src.layers[0].frames; } else { _layers = new Vector.<Layer>(src.layers.length, true); for (var ii :int = 0; ii < _layers.length; ii++) { _layers[ii] = new Layer(this, src.layers[ii], library, /*flipbook=*/false); _numFrames = Math.max(src.layers[ii].frames, _numFrames); } } _duration = _numFrames / _frameRate; updateFrame(0, 0); // When we're removed from the stage, remove ourselves from any juggler animating us. addEventListener(Event.REMOVED_FROM_STAGE, function (..._) :void { dispatchEventWith(Event.REMOVE_FROM_JUGGLER); }); } /** @return the frame being displayed. */ public function get frame () :int { return _frame; } /** @return the number of frames in the movie. */ public function get numFrames () :int { return _numFrames; } /** @return true if the movie is currently playing. */ public function get isPlaying () :Boolean { return _playing; } /** @return true if the movie contains the given label. */ public function hasLabel (label :String) :Boolean { return getFrameForLabel(label) >= 0; } /** Plays the movie from its current frame. The movie will loop forever. */ public function loop () :Movie { _playing = true; _stopFrame = NO_FRAME; return this; } /** Plays the movie from its current frame, stopping when it reaches its last frame. */ public function playOnce () :Movie { return playTo(LAST_FRAME); } /** * Moves to the given String label or int frame. Doesn't alter playing status or stop frame. * If there are labels at the given position, they're fired as part of the goto, even if the * current frame is equal to the destination. Labels between the current frame and the * destination frame are not fired. * * @param position the int frame or String label to goto. * * @return this movie for chaining * * @throws Error if position isn't an int or String, or if it is a String and that String isn't * a label on this movie */ public function goTo (position :Object) :Movie { const frame :int = extractFrame(position); updateFrame(frame, 0); return this; } /** * Plays the movie from its current frame. The movie will stop when it reaches the given label * or frame. * * @param position to int frame or String label to stop at * * @return this movie for chaining * * @throws Error if position isn't an int or String, or if it is a String and that String isn't * a label on this movie. */ public function playTo (position :Object) :Movie { // won't play if we're already at the stop position return stopAt(position).play(); } /** * Sets the stop frame for this Movie. * * @param position the int frame or String label to stop at. * * @return this movie for chaining * * @throws Error if position isn't an int or String, or if it is a String and that String isn't * a label on this movie. */ public function stopAt (position :Object) :Movie { _stopFrame = extractFrame(position); return this; } /** * Sets the movie playing. It will automatically stop at its stopFrame, if one is set, * otherwise it will loop forever. * * @return this movie for chaining */ public function play () :Movie { // set playing to true unless movie is at the stop frame _playing = (_frame != _stopFrame); return this; } /** Stops playback if it's currently active. Doesn't alter the current frame or stop frame. */ public function stop () :Movie { _playing = false; return this; } /** Advances the playhead by the give number of seconds. From IAnimatable. */ public function advanceTime (dt :Number) :void { if (dt < 0) throw new Error("Invalid time [dt=" + dt + "]"); if (_skipAdvanceTime) { _skipAdvanceTime = false; return; } if (!_playing) return; if (_numFrames > 1) { _playTime += dt; var actualPlaytime :Number = _playTime; if (_playTime >= _duration) _playTime %= _duration; // If _playTime is very close to _duration, rounding error can cause us to // land on lastFrame + 1. Protect against that. var newFrame :int = clamp(int(_playTime * _frameRate), 0, _numFrames - 1); // If the update crosses or goes to the stopFrame: // go to the stopFrame, stop the movie, clear the stopFrame if (_stopFrame != NO_FRAME) { // how many frames remain to the stopframe? var framesRemaining :int = (_frame <= _stopFrame ? _stopFrame - _frame : _numFrames - _frame + _stopFrame); var framesElapsed :int = int(actualPlaytime * _frameRate) - _frame; if (framesElapsed >= framesRemaining) { _playing = false; newFrame = _stopFrame; } } updateFrame(newFrame, dt); } for (var ii :int = this.numChildren - 1; ii >= 0; --ii) { var child :DisplayObject = getChildAt(ii); if (child is Movie) { Movie(child).advanceTime(dt); } } } /** * @private * * Called when the Movie has been newly added to a layer. */ internal function addedToLayer () :void { goTo(0); _skipAdvanceTime = true; } /** @private */ protected function extractFrame (position :Object) :int { if (position is int) return int(position); if (!(position is String)) throw new Error("Movie position must be an int frame or String label"); const label :String = String(position); var frame :int = getFrameForLabel(label); if (frame < 0) { throw new Error("No such label '" + label + "'"); } return frame; } /** * @private * * Returns the frame index for the given label, or -1 if the label doesn't exist. */ protected function getFrameForLabel (label :String) :int { for (var ii :int = 0; ii < _labels.length; ii++) { if (_labels[ii] != null && _labels[ii].indexOf(label) != -1) return ii; } return -1; } /** * @private * * @param dt the timeline's elapsed time since the last update. This should be 0 * for updates that are the result of a "goTo" call. */ protected function updateFrame (newFrame :int, dt :Number) :void { if (newFrame < 0 || newFrame >= _numFrames) { throw new Error("Invalid frame [frame=" + newFrame, " validRange=0-" + (_numFrames - 1) + "]"); } if (_isUpdatingFrame) { _pendingFrame = newFrame; return; } else { _pendingFrame = NO_FRAME; _isUpdatingFrame = true; } const isGoTo :Boolean = (dt <= 0); const wrapped :Boolean = (dt >= _duration) || (newFrame < _frame); if (newFrame != _frame) { if (wrapped) { for each (var layer :Layer in _layers) { layer.movieLooped(); } } for each (layer in _layers) layer.drawFrame(newFrame); } if (isGoTo) _playTime = newFrame / _frameRate; // Update the frame before firing frame label signals, so if firing changes the frame, // it sticks. const oldFrame :int = _frame; _frame = newFrame; // determine which labels to fire signals for var startFrame :int; var frameCount :int; if (isGoTo) { startFrame = newFrame; frameCount = 1; } else { startFrame = (oldFrame + 1 < _numFrames ? oldFrame + 1 : 0); frameCount = (_frame - oldFrame); if (wrapped) frameCount += _numFrames; } // Fire signals. Stop if pendingFrame is updated, which indicates that the client // has called goTo() var frameIdx :int = startFrame; for (var ii :int = 0; ii < frameCount; ++ii) { if (_pendingFrame != NO_FRAME) break; if (_labels[frameIdx] != null) { for each (var label :String in _labels[frameIdx]) { labelPassed.emit(label); if (_pendingFrame != NO_FRAME) break; } } // avoid modulo division by updating frameIdx each time through the loop if (++frameIdx == _numFrames) { frameIdx = 0; } } _isUpdatingFrame = false; // If we were interrupted by a goTo(), update to that frame now. if (_pendingFrame != NO_FRAME) { newFrame = _pendingFrame; updateFrame(newFrame, 0); } } protected static function clamp (n :Number, min :Number, max :Number) :Number { return Math.min(Math.max(n, min), max); } /** @private */ protected var _isUpdatingFrame :Boolean; /** @private */ protected var _pendingFrame :int = NO_FRAME; /** @private */ protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME; /** @private */ protected var _playing :Boolean = true; /** @private */ protected var _playTime :Number, _duration :Number; /** @private */ protected var _layers :Vector.<Layer>; /** @private */ protected var _numFrames :int; /** @private */ protected var _frameRate :Number; /** @private */ protected var _labels :Vector.<Vector.<String>>; /** @private */ private var _skipAdvanceTime :Boolean = false; /** @private */ internal var _playerData :MoviePlayerNode; private static const NO_FRAME :int = -1; } }
Remove superfluous conditional
Remove superfluous conditional If _stopFrame is NO_FRAME (-1) _frame should never equal it
ActionScript
mit
funkypandagame/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,tconkling/flump,mathieuanthoine/flump
d37ff600011ff6265e00905468be62e0f9c4afef
Bin/Data/Scripts/Editor/EditorSpawn.as
Bin/Data/Scripts/Editor/EditorSpawn.as
// Urho3D spawn editor LineEdit@ randomRotationX; LineEdit@ randomRotationY; LineEdit@ randomRotationZ; LineEdit@ randomScaleMinEdit; LineEdit@ randomScaleMaxEdit; LineEdit@ NumberSpawnedObjectsEdit; LineEdit@ spawnRadiusEdit; LineEdit@ spawnCountEdit; Window@ spawnWindow; Vector3 randomRotation = Vector3(0, 0, 0); float randomScaleMin = 1; float randomScaleMax = 1; float spawnCount = 1; float spawnRadius = 0; bool useNormal = true; int numberSpawnedObjects = 1; Array<String> spawnedObjectsNames; void CreateSpawnEditor() { if (spawnWindow !is null) return; spawnWindow = ui.LoadLayout(cache.GetResource("XMLFile", "UI/EditorSpawnWindow.xml")); ui.root.AddChild(spawnWindow); spawnWindow.opacity = uiMaxOpacity; int height = Min(ui.root.height - 60, 500); spawnWindow.SetSize(300, height); CenterDialog(spawnWindow); HideSpawnEditor(); SubscribeToEvent(spawnWindow.GetChild("CloseButton", true), "Released", "HideSpawnEditor"); randomRotationX = spawnWindow.GetChild("RandomRotation.x", true); randomRotationY = spawnWindow.GetChild("RandomRotation.y", true); randomRotationZ = spawnWindow.GetChild("RandomRotation.z", true); randomRotationX.text = String(randomRotation.x); randomRotationY.text = String(randomRotation.y); randomRotationZ.text = String(randomRotation.z); randomScaleMinEdit = spawnWindow.GetChild("RandomScaleMin", true); randomScaleMaxEdit = spawnWindow.GetChild("RandomScaleMax", true); randomScaleMinEdit.text = String(randomScaleMin); randomScaleMaxEdit.text = String(randomScaleMax); CheckBox@ useNormalToggle = spawnWindow.GetChild("UseNormal", true); useNormalToggle.checked = useNormal; NumberSpawnedObjectsEdit = spawnWindow.GetChild("NumberSpawnedObjects", true); NumberSpawnedObjectsEdit.text = String(numberSpawnedObjects); spawnRadiusEdit = spawnWindow.GetChild("SpawnRadius", true); spawnCountEdit = spawnWindow.GetChild("SpawnCount", true); spawnRadiusEdit.text = String(spawnRadius); spawnCountEdit.text = String(spawnCount); SubscribeToEvent(randomRotationX, "TextChanged", "EditRandomRotation"); SubscribeToEvent(randomRotationY, "TextChanged", "EditRandomRotation"); SubscribeToEvent(randomRotationZ, "TextChanged", "EditRandomRotation"); SubscribeToEvent(randomScaleMinEdit, "TextChanged", "EditRandomScale"); SubscribeToEvent(randomScaleMaxEdit, "TextChanged", "EditRandomScale"); SubscribeToEvent(spawnRadiusEdit, "TextChanged", "EditSpawnRadius"); SubscribeToEvent(spawnCountEdit, "TextChanged", "EditSpawnCount"); SubscribeToEvent(useNormalToggle, "Toggled", "ToggleUseNormal"); SubscribeToEvent(NumberSpawnedObjectsEdit, "TextFinished", "UpdateNumberSpawnedObjects"); SubscribeToEvent(spawnWindow.GetChild("SetSpawnMode", true), "Released", "SetSpawnMode"); RefreshPickedObjects(); } bool ShowSpawnEditor() { spawnWindow.visible = true; spawnWindow.BringToFront(); return true; } void HideSpawnEditor() { spawnWindow.visible = false; } void PickSpawnObject() { @resourcePicker = GetResourcePicker(ShortStringHash("Node")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector("Pick " + resourcePicker.typeName, "OK", "Cancel", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "PickSpawnObjectDone"); } void EditRandomRotation(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); randomRotation = Vector3(randomRotationX.text.ToFloat(), randomRotationY.text.ToFloat(), randomRotationZ.text.ToFloat()); UpdateHierarchyItem(editorScene); } void EditRandomScale(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); randomScaleMin = randomScaleMinEdit.text.ToFloat(); randomScaleMax = randomScaleMaxEdit.text.ToFloat(); UpdateHierarchyItem(editorScene); } void ToggleUseNormal(StringHash eventType, VariantMap& eventData) { useNormal = cast<CheckBox>(eventData["Element"].GetPtr()).checked; } void UpdateNumberSpawnedObjects(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); numberSpawnedObjects = edit.text.ToFloat(); edit.text = String(numberSpawnedObjects); RefreshPickedObjects(); } void EditSpawnRadius(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); spawnRadius = edit.text.ToFloat(); } void EditSpawnCount(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); spawnCount = edit.text.ToFloat(); } void RefreshPickedObjects() { spawnedObjectsNames.Resize(numberSpawnedObjects); ListView@ list = spawnWindow.GetChild("SpawnedObjects", true); list.RemoveAllItems(); for (uint i = 0; i < numberSpawnedObjects; ++i) { UIElement@ parent = CreateAttributeEditorParentWithSeparatedLabel(list, "Object " +(i+1), i, 0, false); UIElement@ container = UIElement(); container.SetLayout(LM_HORIZONTAL, 4, IntRect(10, 0, 4, 0)); container.SetFixedHeight(ATTR_HEIGHT); parent.AddChild(container); LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, i, 0); nameEdit.name = "TextureNameEdit" + String(i); Button@ pickButton = CreateResourcePickerButton(container, null, i, 0, "Pick"); SubscribeToEvent(pickButton, "Released", "PickSpawnedObject"); nameEdit.text = spawnedObjectsNames[i]; SubscribeToEvent(nameEdit, "TextFinished", "EditSpawnedObjectName"); } } void EditSpawnedObjectName(StringHash eventType, VariantMap& eventData) { LineEdit@ nameEdit = eventData["Element"].GetPtr(); int index = nameEdit.vars["Index"].GetUInt(); String resourceName = nameEdit.text; spawnedObjectsNames[index] = VerifySpawnedObjectFile(resourceName); RefreshPickedObjects(); } String VerifySpawnedObjectFile(const String&in resourceName) { File@ file = cache.GetFile(resourceName); if(file !is null) return resourceName; else return String(); } void PickSpawnedObject(StringHash eventType, VariantMap& eventData) { UIElement@ button = eventData["Element"].GetPtr(); resourcePickIndex = button.vars["Index"].GetUInt(); CreateFileSelector("Pick spawned object", "Pick", "Cancel", uiNodePath, uiSceneFilters, uiNodeFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "PickSpawnedObjectNameDone"); } void PickSpawnedObjectNameDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); if (!eventData["OK"].GetBool()) { @resourcePicker = null; return; } String resourceName = GetResourceNameFromFullName(eventData["FileName"].GetString()); spawnedObjectsNames[resourcePickIndex] = VerifySpawnedObjectFile(resourceName); @resourcePicker = null; RefreshPickedObjects(); } void SetSpawnMode(StringHash eventType, VariantMap& eventData) { editMode = EDIT_SPAWN; } void PlaceObject(Vector3 spawnPosition, Vector3 normal) { Quaternion spawnRotation; if (useNormal) spawnRotation = Quaternion(Vector3(0, 1, 0), normal); spawnRotation = Quaternion(Random(-randomRotation.x, randomRotation.x), Random(-randomRotation.y, randomRotation.y), Random(-randomRotation.z, randomRotation.z)) * spawnRotation; int number = RandomInt(0, spawnedObjectsNames.length); File@ file = cache.GetFile(spawnedObjectsNames[number]); Node@ spawnedObject = InstantiateNodeFromFile(file, spawnPosition, spawnRotation, Random(randomScaleMin, randomScaleMax)); if (spawnedObject is null) { spawnedObjectsNames[number] = spawnedObjectsNames[spawnedObjectsNames.length - 1]; --numberSpawnedObjects; RefreshPickedObjects(); return; } } Vector3 RandomizeSpawnPosition(const Vector3&in position) { float angle = Random() * 360.0; float distance = Random() * spawnRadius; return position + Quaternion(0, angle, 0) * Vector3(0, 0, distance); } void SpawnObject() { if(spawnedObjectsNames.length == 0) return; IntRect view = activeViewport.viewport.rect; for(int i = 0;i<spawnCount;i++) { IntVector2 pos = IntVector2(ui.cursorPosition.x, ui.cursorPosition.y); Ray cameraRay = camera.GetScreenRay( float(pos.x - view.left) / view.width, float(pos.y - view.top) / view.height); if (pickMode < PICK_RIGIDBODIES) { if (editorScene.octree is null) return; RayQueryResult result = editorScene.octree.RaycastSingle(cameraRay, RAY_TRIANGLE, camera.farClip, pickModeDrawableFlags[pickMode], 0x7fffffff); // Randomize in a circle around original hit position if (spawnRadius > 0) { Vector3 position = RandomizeSpawnPosition(result.position); position.y += spawnRadius; result = editorScene.octree.RaycastSingle(Ray(position, Vector3(0, -1, 0)), RAY_TRIANGLE, spawnRadius * 2.0, pickModeDrawableFlags[pickMode], 0x7fffffff); } if (result.drawable !is null) PlaceObject(result.position, result.normal); } else { if (editorScene.physicsWorld is null) return; // If we are not running the actual physics update, refresh collisions before raycasting if (!runUpdate) editorScene.physicsWorld.UpdateCollisions(); PhysicsRaycastResult result = editorScene.physicsWorld.RaycastSingle(cameraRay, camera.farClip); // Randomize in a circle around original hit position if (spawnRadius > 0) { Vector3 position = RandomizeSpawnPosition(result.position); position.y += spawnRadius; result = editorScene.physicsWorld.RaycastSingle(Ray(position, Vector3(0, -1, 0)), spawnRadius * 2.0); } if (result.body !is null) PlaceObject(result.position, result.normal); } } }
// Urho3D spawn editor LineEdit@ randomRotationX; LineEdit@ randomRotationY; LineEdit@ randomRotationZ; LineEdit@ randomScaleMinEdit; LineEdit@ randomScaleMaxEdit; LineEdit@ NumberSpawnedObjectsEdit; LineEdit@ spawnRadiusEdit; LineEdit@ spawnCountEdit; Window@ spawnWindow; Vector3 randomRotation = Vector3(0, 0, 0); float randomScaleMin = 1; float randomScaleMax = 1; uint spawnCount = 1; float spawnRadius = 0; bool useNormal = true; uint numberSpawnedObjects = 1; Array<String> spawnedObjectsNames; void CreateSpawnEditor() { if (spawnWindow !is null) return; spawnWindow = ui.LoadLayout(cache.GetResource("XMLFile", "UI/EditorSpawnWindow.xml")); ui.root.AddChild(spawnWindow); spawnWindow.opacity = uiMaxOpacity; int height = Min(ui.root.height - 60, 500); spawnWindow.SetSize(300, height); CenterDialog(spawnWindow); HideSpawnEditor(); SubscribeToEvent(spawnWindow.GetChild("CloseButton", true), "Released", "HideSpawnEditor"); randomRotationX = spawnWindow.GetChild("RandomRotation.x", true); randomRotationY = spawnWindow.GetChild("RandomRotation.y", true); randomRotationZ = spawnWindow.GetChild("RandomRotation.z", true); randomRotationX.text = String(randomRotation.x); randomRotationY.text = String(randomRotation.y); randomRotationZ.text = String(randomRotation.z); randomScaleMinEdit = spawnWindow.GetChild("RandomScaleMin", true); randomScaleMaxEdit = spawnWindow.GetChild("RandomScaleMax", true); randomScaleMinEdit.text = String(randomScaleMin); randomScaleMaxEdit.text = String(randomScaleMax); CheckBox@ useNormalToggle = spawnWindow.GetChild("UseNormal", true); useNormalToggle.checked = useNormal; NumberSpawnedObjectsEdit = spawnWindow.GetChild("NumberSpawnedObjects", true); NumberSpawnedObjectsEdit.text = String(numberSpawnedObjects); spawnRadiusEdit = spawnWindow.GetChild("SpawnRadius", true); spawnCountEdit = spawnWindow.GetChild("SpawnCount", true); spawnRadiusEdit.text = String(spawnRadius); spawnCountEdit.text = String(spawnCount); SubscribeToEvent(randomRotationX, "TextChanged", "EditRandomRotation"); SubscribeToEvent(randomRotationY, "TextChanged", "EditRandomRotation"); SubscribeToEvent(randomRotationZ, "TextChanged", "EditRandomRotation"); SubscribeToEvent(randomScaleMinEdit, "TextChanged", "EditRandomScale"); SubscribeToEvent(randomScaleMaxEdit, "TextChanged", "EditRandomScale"); SubscribeToEvent(spawnRadiusEdit, "TextChanged", "EditSpawnRadius"); SubscribeToEvent(spawnCountEdit, "TextChanged", "EditSpawnCount"); SubscribeToEvent(useNormalToggle, "Toggled", "ToggleUseNormal"); SubscribeToEvent(NumberSpawnedObjectsEdit, "TextFinished", "UpdateNumberSpawnedObjects"); SubscribeToEvent(spawnWindow.GetChild("SetSpawnMode", true), "Released", "SetSpawnMode"); RefreshPickedObjects(); } bool ShowSpawnEditor() { spawnWindow.visible = true; spawnWindow.BringToFront(); return true; } void HideSpawnEditor() { spawnWindow.visible = false; } void PickSpawnObject() { @resourcePicker = GetResourcePicker(ShortStringHash("Node")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector("Pick " + resourcePicker.typeName, "OK", "Cancel", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "PickSpawnObjectDone"); } void EditRandomRotation(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); randomRotation = Vector3(randomRotationX.text.ToFloat(), randomRotationY.text.ToFloat(), randomRotationZ.text.ToFloat()); UpdateHierarchyItem(editorScene); } void EditRandomScale(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); randomScaleMin = randomScaleMinEdit.text.ToFloat(); randomScaleMax = randomScaleMaxEdit.text.ToFloat(); UpdateHierarchyItem(editorScene); } void ToggleUseNormal(StringHash eventType, VariantMap& eventData) { useNormal = cast<CheckBox>(eventData["Element"].GetPtr()).checked; } void UpdateNumberSpawnedObjects(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); numberSpawnedObjects = edit.text.ToUInt(); edit.text = String(numberSpawnedObjects); RefreshPickedObjects(); } void EditSpawnRadius(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); spawnRadius = edit.text.ToFloat(); } void EditSpawnCount(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); spawnCount = edit.text.ToUInt(); } void RefreshPickedObjects() { spawnedObjectsNames.Resize(numberSpawnedObjects); ListView@ list = spawnWindow.GetChild("SpawnedObjects", true); list.RemoveAllItems(); for (uint i = 0; i < numberSpawnedObjects; ++i) { UIElement@ parent = CreateAttributeEditorParentWithSeparatedLabel(list, "Object " +(i+1), i, 0, false); UIElement@ container = UIElement(); container.SetLayout(LM_HORIZONTAL, 4, IntRect(10, 0, 4, 0)); container.SetFixedHeight(ATTR_HEIGHT); parent.AddChild(container); LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, i, 0); nameEdit.name = "TextureNameEdit" + String(i); Button@ pickButton = CreateResourcePickerButton(container, null, i, 0, "Pick"); SubscribeToEvent(pickButton, "Released", "PickSpawnedObject"); nameEdit.text = spawnedObjectsNames[i]; SubscribeToEvent(nameEdit, "TextFinished", "EditSpawnedObjectName"); } } void EditSpawnedObjectName(StringHash eventType, VariantMap& eventData) { LineEdit@ nameEdit = eventData["Element"].GetPtr(); int index = nameEdit.vars["Index"].GetUInt(); String resourceName = VerifySpawnedObjectFile(nameEdit.text); nameEdit.text = resourceName; spawnedObjectsNames[index] = resourceName; } String VerifySpawnedObjectFile(const String&in resourceName) { File@ file = cache.GetFile(resourceName); if(file !is null) return resourceName; else return String(); } void PickSpawnedObject(StringHash eventType, VariantMap& eventData) { UIElement@ button = eventData["Element"].GetPtr(); resourcePickIndex = button.vars["Index"].GetUInt(); CreateFileSelector("Pick spawned object", "Pick", "Cancel", uiNodePath, uiSceneFilters, uiNodeFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "PickSpawnedObjectNameDone"); } void PickSpawnedObjectNameDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); if (!eventData["OK"].GetBool()) { @resourcePicker = null; return; } String resourceName = GetResourceNameFromFullName(eventData["FileName"].GetString()); spawnedObjectsNames[resourcePickIndex] = VerifySpawnedObjectFile(resourceName); @resourcePicker = null; RefreshPickedObjects(); } void SetSpawnMode(StringHash eventType, VariantMap& eventData) { editMode = EDIT_SPAWN; } void PlaceObject(Vector3 spawnPosition, Vector3 normal) { Quaternion spawnRotation; if (useNormal) spawnRotation = Quaternion(Vector3(0, 1, 0), normal); spawnRotation = Quaternion(Random(-randomRotation.x, randomRotation.x), Random(-randomRotation.y, randomRotation.y), Random(-randomRotation.z, randomRotation.z)) * spawnRotation; int number = RandomInt(0, spawnedObjectsNames.length); File@ file = cache.GetFile(spawnedObjectsNames[number]); Node@ spawnedObject = InstantiateNodeFromFile(file, spawnPosition, spawnRotation, Random(randomScaleMin, randomScaleMax)); if (spawnedObject is null) { spawnedObjectsNames[number] = spawnedObjectsNames[spawnedObjectsNames.length - 1]; --numberSpawnedObjects; RefreshPickedObjects(); return; } } Vector3 RandomizeSpawnPosition(const Vector3&in position) { float angle = Random() * 360.0; float distance = Random() * spawnRadius; return position + Quaternion(0, angle, 0) * Vector3(0, 0, distance); } void SpawnObject() { if(spawnedObjectsNames.length == 0) return; IntRect view = activeViewport.viewport.rect; for(int i = 0;i<spawnCount;i++) { IntVector2 pos = IntVector2(ui.cursorPosition.x, ui.cursorPosition.y); Ray cameraRay = camera.GetScreenRay( float(pos.x - view.left) / view.width, float(pos.y - view.top) / view.height); if (pickMode < PICK_RIGIDBODIES) { if (editorScene.octree is null) return; RayQueryResult result = editorScene.octree.RaycastSingle(cameraRay, RAY_TRIANGLE, camera.farClip, pickModeDrawableFlags[pickMode], 0x7fffffff); // Randomize in a circle around original hit position if (spawnRadius > 0) { Vector3 position = RandomizeSpawnPosition(result.position); position.y += spawnRadius; result = editorScene.octree.RaycastSingle(Ray(position, Vector3(0, -1, 0)), RAY_TRIANGLE, spawnRadius * 2.0, pickModeDrawableFlags[pickMode], 0x7fffffff); } if (result.drawable !is null) PlaceObject(result.position, result.normal); } else { if (editorScene.physicsWorld is null) return; // If we are not running the actual physics update, refresh collisions before raycasting if (!runUpdate) editorScene.physicsWorld.UpdateCollisions(); PhysicsRaycastResult result = editorScene.physicsWorld.RaycastSingle(cameraRay, camera.farClip); // Randomize in a circle around original hit position if (spawnRadius > 0) { Vector3 position = RandomizeSpawnPosition(result.position); position.y += spawnRadius; result = editorScene.physicsWorld.RaycastSingle(Ray(position, Vector3(0, -1, 0)), spawnRadius * 2.0); } if (result.body !is null) PlaceObject(result.position, result.normal); } } }
Correct data type for spawn object counting variable.
Correct data type for spawn object counting variable.
ActionScript
mit
MeshGeometry/Urho3D,MonkeyFirst/Urho3D,codemon66/Urho3D,henu/Urho3D,codedash64/Urho3D,PredatorMF/Urho3D,kostik1337/Urho3D,eugeneko/Urho3D,MonkeyFirst/Urho3D,helingping/Urho3D,iainmerrick/Urho3D,c4augustus/Urho3D,MeshGeometry/Urho3D,weitjong/Urho3D,299299/Urho3D,tommy3/Urho3D,299299/Urho3D,MeshGeometry/Urho3D,victorholt/Urho3D,codemon66/Urho3D,xiliu98/Urho3D,codemon66/Urho3D,MeshGeometry/Urho3D,weitjong/Urho3D,iainmerrick/Urho3D,codedash64/Urho3D,carnalis/Urho3D,kostik1337/Urho3D,cosmy1/Urho3D,orefkov/Urho3D,PredatorMF/Urho3D,fire/Urho3D-1,carnalis/Urho3D,codemon66/Urho3D,eugeneko/Urho3D,codedash64/Urho3D,xiliu98/Urho3D,urho3d/Urho3D,henu/Urho3D,cosmy1/Urho3D,codemon66/Urho3D,abdllhbyrktr/Urho3D,bacsmar/Urho3D,c4augustus/Urho3D,tommy3/Urho3D,urho3d/Urho3D,eugeneko/Urho3D,MonkeyFirst/Urho3D,MonkeyFirst/Urho3D,luveti/Urho3D,SirNate0/Urho3D,helingping/Urho3D,luveti/Urho3D,bacsmar/Urho3D,MeshGeometry/Urho3D,kostik1337/Urho3D,MonkeyFirst/Urho3D,victorholt/Urho3D,abdllhbyrktr/Urho3D,rokups/Urho3D,abdllhbyrktr/Urho3D,henu/Urho3D,weitjong/Urho3D,PredatorMF/Urho3D,SirNate0/Urho3D,299299/Urho3D,SirNate0/Urho3D,abdllhbyrktr/Urho3D,fire/Urho3D-1,fire/Urho3D-1,SirNate0/Urho3D,codedash64/Urho3D,codedash64/Urho3D,helingping/Urho3D,henu/Urho3D,luveti/Urho3D,SuperWangKai/Urho3D,rokups/Urho3D,bacsmar/Urho3D,kostik1337/Urho3D,SirNate0/Urho3D,eugeneko/Urho3D,SuperWangKai/Urho3D,fire/Urho3D-1,xiliu98/Urho3D,xiliu98/Urho3D,carnalis/Urho3D,xiliu98/Urho3D,c4augustus/Urho3D,SuperWangKai/Urho3D,carnalis/Urho3D,299299/Urho3D,iainmerrick/Urho3D,carnalis/Urho3D,urho3d/Urho3D,299299/Urho3D,abdllhbyrktr/Urho3D,helingping/Urho3D,c4augustus/Urho3D,iainmerrick/Urho3D,PredatorMF/Urho3D,luveti/Urho3D,bacsmar/Urho3D,weitjong/Urho3D,victorholt/Urho3D,c4augustus/Urho3D,helingping/Urho3D,rokups/Urho3D,tommy3/Urho3D,fire/Urho3D-1,SuperWangKai/Urho3D,luveti/Urho3D,urho3d/Urho3D,iainmerrick/Urho3D,victorholt/Urho3D,orefkov/Urho3D,rokups/Urho3D,SuperWangKai/Urho3D,victorholt/Urho3D,299299/Urho3D,cosmy1/Urho3D,tommy3/Urho3D,henu/Urho3D,rokups/Urho3D,orefkov/Urho3D,tommy3/Urho3D,weitjong/Urho3D,rokups/Urho3D,kostik1337/Urho3D,cosmy1/Urho3D,cosmy1/Urho3D,orefkov/Urho3D
f030ad327f019ad246d998b1989bbed4deac230e
src/aerys/minko/type/data/DataProvider.as
src/aerys/minko/type/data/DataProvider.as
package aerys.minko.type.data { import aerys.minko.type.Signal; import aerys.minko.type.enum.DataProviderUsage; import flash.utils.Dictionary; import flash.utils.Proxy; import flash.utils.flash_proxy; public dynamic class DataProvider extends Proxy implements IDataProvider { private var _usage : uint = 1; private var _name : String = null; private var _descriptor : Object = {}; private var _changed : Signal = new Signal('DataProvider.changed'); private var _propertyChanged : Signal = new Signal('DataProvider.propertyChanged'); private var _nameToProperty : Object = {}; private var _propertyToNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]] public function get usage() : uint { return _usage; } public function get dataDescriptor() : Object { return _descriptor; } public function get changed() : Signal { return _changed; } public function get propertyChanged() : Signal { return _propertyChanged; } public function DataProvider(properties : Object = null, name : String = null, usage : uint = 1) { _name = name; _usage = usage; initialize(properties); } private function initialize(properties : Object) : void { if (properties) for (var propertyName : String in properties) setProperty(propertyName, properties[propertyName]); } override flash_proxy function getProperty(name : *) : * { return getProperty(String(name)); } override flash_proxy function setProperty(name : *, value : *) : void { setProperty(String(name), value); } override flash_proxy function deleteProperty(name : *) : Boolean { removeProperty(String(name)); return true; } public function getProperty(name : String) : * { return _nameToProperty[name]; } public function setProperty(name : String, newValue : Object) : DataProvider { var oldValue : Object = _nameToProperty[name]; var oldMonitoredValue : IMonitoredData = oldValue as IMonitoredData; var newMonitoredValue : IMonitoredData = newValue as IMonitoredData; var oldPropertyNames : Vector.<String> = _propertyToNames[oldMonitoredValue]; var newPropertyNames : Vector.<String> = _propertyToNames[newMonitoredValue]; if (oldMonitoredValue != null) { if (oldPropertyNames.length == 1) { oldMonitoredValue.changed.remove(propertyChangedHandler); delete _propertyToNames[oldMonitoredValue]; } else oldPropertyNames.splice(oldPropertyNames.indexOf(name), 1); } if (newMonitoredValue != null) { if (newPropertyNames == null) { newPropertyNames = _propertyToNames[newMonitoredValue] = new <String>[name]; newMonitoredValue.changed.add(propertyChangedHandler); } else newPropertyNames.push(name); } _descriptor[name] = name; _nameToProperty[name] = newValue; if (oldValue === null) _changed.execute(this, 'dataDescriptor'); else _changed.execute(this, name); return this; } public function setProperties(properties : Object) : DataProvider { for (var propertyName : String in properties) setProperty(propertyName, properties[propertyName]); return this; } public function removeProperty(name : String) : DataProvider { var oldMonitoredValue : IMonitoredData = _nameToProperty[name] as IMonitoredData; var oldPropertyNames : Vector.<String> = _propertyToNames[oldMonitoredValue]; delete _descriptor[name]; delete _nameToProperty[name]; if (oldMonitoredValue != null) { if (oldPropertyNames.length == 1) { oldMonitoredValue.changed.remove(propertyChangedHandler); delete _propertyToNames[oldMonitoredValue]; } else oldPropertyNames.splice(oldPropertyNames.indexOf(name), 1); } _changed.execute(this, 'dataDescriptor'); return this; } public function removeAllProperties() : DataProvider { for (var propertyName : String in _nameToProperty) removeProperty(propertyName); return this; } public function propertyExists(name : String) : Boolean { return _descriptor.hasOwnProperty(name); } public function invalidate() : DataProvider { _changed.execute(this, null); return this; } public function clone() : IDataProvider { switch (_usage) { case DataProviderUsage.EXCLUSIVE: case DataProviderUsage.SHARED: return new DataProvider(_nameToProperty, _name + '_cloned', _usage); case DataProviderUsage.MANAGED: throw new Error('This dataprovider is managed, and must not be cloned'); default: throw new Error('Unkown usage value'); } } private function propertyChangedHandler(source : IMonitoredData, key : String) : void { var names : Vector.<String> = _propertyToNames[source]; var numNames : uint = names.length; for (var nameId : uint = 0; nameId < numNames; ++nameId) _propertyChanged.execute(this, names[nameId]); } } }
package aerys.minko.type.data { import aerys.minko.type.Signal; import aerys.minko.type.enum.DataProviderUsage; import flash.utils.Dictionary; import flash.utils.Proxy; import flash.utils.flash_proxy; public dynamic class DataProvider extends Proxy implements IDataProvider { private var _usage : uint = 1; private var _name : String = null; private var _descriptor : Object = {}; private var _changed : Signal = new Signal('DataProvider.changed'); private var _propertyChanged : Signal = new Signal('DataProvider.propertyChanged'); private var _nameToProperty : Object = {}; private var _propertyToNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]] public function get usage() : uint { return _usage; } public function get dataDescriptor() : Object { return _descriptor; } public function get changed() : Signal { return _changed; } public function get propertyChanged() : Signal { return _propertyChanged; } public function get name() : String { return _name; } public function set name(v : String) : void { _name = v; } public function DataProvider(properties : Object = null, name : String = null, usage : uint = 1) { _name = name; _usage = usage; initialize(properties); } private function initialize(properties : Object) : void { if (properties) for (var propertyName : String in properties) setProperty(propertyName, properties[propertyName]); } override flash_proxy function getProperty(name : *) : * { return getProperty(String(name)); } override flash_proxy function setProperty(name : *, value : *) : void { setProperty(String(name), value); } override flash_proxy function deleteProperty(name : *) : Boolean { removeProperty(String(name)); return true; } public function getProperty(name : String) : * { return _nameToProperty[name]; } public function setProperty(name : String, newValue : Object) : DataProvider { var oldValue : Object = _nameToProperty[name]; var oldMonitoredValue : IMonitoredData = oldValue as IMonitoredData; var newMonitoredValue : IMonitoredData = newValue as IMonitoredData; var oldPropertyNames : Vector.<String> = _propertyToNames[oldMonitoredValue]; var newPropertyNames : Vector.<String> = _propertyToNames[newMonitoredValue]; if (oldMonitoredValue != null) { if (oldPropertyNames.length == 1) { oldMonitoredValue.changed.remove(propertyChangedHandler); delete _propertyToNames[oldMonitoredValue]; } else oldPropertyNames.splice(oldPropertyNames.indexOf(name), 1); } if (newMonitoredValue != null) { if (newPropertyNames == null) { newPropertyNames = _propertyToNames[newMonitoredValue] = new <String>[name]; newMonitoredValue.changed.add(propertyChangedHandler); } else newPropertyNames.push(name); } _descriptor[name] = name; _nameToProperty[name] = newValue; if (oldValue === null) _changed.execute(this, 'dataDescriptor'); else _changed.execute(this, name); return this; } public function setProperties(properties : Object) : DataProvider { for (var propertyName : String in properties) setProperty(propertyName, properties[propertyName]); return this; } public function removeProperty(name : String) : DataProvider { var oldMonitoredValue : IMonitoredData = _nameToProperty[name] as IMonitoredData; var oldPropertyNames : Vector.<String> = _propertyToNames[oldMonitoredValue]; delete _descriptor[name]; delete _nameToProperty[name]; if (oldMonitoredValue != null) { if (oldPropertyNames.length == 1) { oldMonitoredValue.changed.remove(propertyChangedHandler); delete _propertyToNames[oldMonitoredValue]; } else oldPropertyNames.splice(oldPropertyNames.indexOf(name), 1); } _changed.execute(this, 'dataDescriptor'); return this; } public function removeAllProperties() : DataProvider { for (var propertyName : String in _nameToProperty) removeProperty(propertyName); return this; } public function propertyExists(name : String) : Boolean { return _descriptor.hasOwnProperty(name); } public function invalidate() : DataProvider { _changed.execute(this, null); return this; } public function clone() : IDataProvider { switch (_usage) { case DataProviderUsage.EXCLUSIVE: case DataProviderUsage.SHARED: return new DataProvider(_nameToProperty, _name + '_cloned', _usage); case DataProviderUsage.MANAGED: throw new Error('This dataprovider is managed, and must not be cloned'); default: throw new Error('Unkown usage value'); } } private function propertyChangedHandler(source : IMonitoredData, key : String) : void { var names : Vector.<String> = _propertyToNames[source]; var numNames : uint = names.length; for (var nameId : uint = 0; nameId < numNames; ++nameId) _propertyChanged.execute(this, names[nameId]); } } }
Add name getter/setter to providers
Add name getter/setter to providers
ActionScript
mit
aerys/minko-as3
1c3194e4683a8957376650420210fb127117c358
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
package aerys.minko.scene.controller.mesh { import flash.display.BitmapData; import aerys.minko.ns.minko_math; import aerys.minko.render.Viewport; import aerys.minko.render.geometry.Geometry; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.camera.AbstractCamera; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import aerys.minko.type.enum.FrustumCulling; import aerys.minko.type.math.BoundingBox; import aerys.minko.type.math.BoundingSphere; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; /** * The MeshVisibilityController watches the Mesh and the active Camera of a Scene * to determine whether the object is actually inside the view frustum or not. * * @author Jean-Marc Le Roux * */ public final class MeshVisibilityController extends AbstractController { use namespace minko_math; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_VECTOR4_2 : Vector4 = new Vector4(); private static const STATE_UNDEFINED : uint = 0; private static const STATE_INSIDE : uint = 1; private static const STATE_OUTSIDE : uint = 2; private var _mesh : Mesh; private var _state : uint; private var _lastTest : int; private var _boundingBox : BoundingBox; private var _boundingSphere : BoundingSphere; private var _data : DataProvider; private var _frustumCulling : uint; private var _insideFrustum : Boolean; public function get frustumCulling() : uint { return _frustumCulling; } public function set frustumCulling(value : uint) : void { if (value != _frustumCulling) { _frustumCulling = value; if (value == FrustumCulling.DISABLED) { _data.computedVisibility = true; if (_mesh.localToWorldTransformChanged.hasCallback(meshLocalToWorldChangedHandler)) _mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler); } else if (_mesh && _mesh.scene) { _mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler); testCulling(); } } } public function get insideFrustum() : Boolean { return _insideFrustum; } public function get computedVisibility() : Boolean { return _data.computedVisibility; } public function MeshVisibilityController() { super(Mesh); initialize(); } private function initialize() : void { _data = new DataProvider( { computedVisibility : true }, 'MeshVisibilityDataProvider', DataProviderUsage.EXCLUSIVE ); _boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE); _boundingSphere = new BoundingSphere(Vector4.ZERO, 0.); _state = STATE_UNDEFINED; targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(ctrl : MeshVisibilityController, target : Mesh) : void { if (_mesh != null) throw new Error(); _mesh = target; target.added.add(addedHandler); target.removed.add(removedHandler); if (target.root is Scene) addedHandler(target, target.root as Scene); if (_frustumCulling) testCulling(); } private function targetRemovedHandler(ctrl : MeshVisibilityController, target : Mesh) : void { _mesh = null; target.added.remove(addedHandler); target.removed.remove(removedHandler); if (target.root is Scene) removedHandler(target, target.root as Scene); } private function addedHandler(mesh : Mesh, ancestor : Group) : void { var scene : Scene = mesh.scene; if (!scene) return ; scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler); if (_frustumCulling) scene.renderingBegin.add(sceneRenderingBeginHandler); _mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler); _mesh.bindings.addProvider(_data); } private function sceneRenderingBeginHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { scene.renderingBegin.remove(sceneRenderingBeginHandler); meshLocalToWorldChangedHandler(_mesh, _mesh.getLocalToWorldTransform()); _mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler); } private function removedHandler(mesh : Mesh, ancestor : Group) : void { var scene : Scene = ancestor.scene; if (!scene) return ; if (scene.renderingBegin.hasCallback(sceneRenderingBeginHandler)) scene.renderingBegin.remove(sceneRenderingBeginHandler); if (scene.bindings.hasCallback('worldToScreen', worldToScreenChangedHandler)) scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler); if (_frustumCulling && mesh.localToWorldTransformChanged.hasCallback(meshLocalToWorldChangedHandler)) mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler); if (mesh.computedVisibilityChanged.hasCallback(computedVisiblityChangedHandler)) { mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler); mesh.bindings.removeProvider(_data); } } private function computedVisiblityChangedHandler(node : ISceneNode, computedVisibility : Boolean) : void { _data.computedVisibility = computedVisibility; } private function worldToScreenChangedHandler(bindings : DataBindings, bindingName : String, oldValue : Matrix4x4, value : Matrix4x4) : void { testCulling(); } private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void { var geom : Geometry = _mesh.geometry; var culling : uint = _frustumCulling; if (!geom || !geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED) return ; if (culling & FrustumCulling.BOX) transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices); if (culling & FrustumCulling.SPHERE) { var center : Vector4 = transform.transformVector(geom.boundingSphere.center, TMP_VECTOR4); var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE, TMP_VECTOR4_2); var radius : Number = geom.boundingSphere.radius * Math.max( Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z) ); _boundingSphere.update(center, radius); } testCulling(); } private function testCulling() : void { var culling : uint = _frustumCulling; if (_mesh && _mesh.geometry && _mesh.geometry.boundingBox && _mesh.visible && _mesh.root is Scene) { var camera : AbstractCamera = (_mesh.root as Scene).activeCamera; if (!camera) return ; _lastTest = camera.frustum.testBoundingVolume( _boundingSphere, _boundingBox, null, culling, _lastTest ); var inside : Boolean = _lastTest == -1; if (inside && _state != STATE_INSIDE) { _insideFrustum = true; _data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible; _mesh.computedVisibilityChanged.execute(_mesh, computedVisibility); _state = STATE_INSIDE; } else if (!inside && _state != STATE_OUTSIDE) { _insideFrustum = false; _data.computedVisibility = false; _mesh.computedVisibilityChanged.execute(_mesh, false); _state = STATE_OUTSIDE; } } } override public function clone() : AbstractController { return new MeshVisibilityController(); } } }
package aerys.minko.scene.controller.mesh { import flash.display.BitmapData; import aerys.minko.ns.minko_math; import aerys.minko.render.Viewport; import aerys.minko.render.geometry.Geometry; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.camera.AbstractCamera; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import aerys.minko.type.enum.FrustumCulling; import aerys.minko.type.math.BoundingBox; import aerys.minko.type.math.BoundingSphere; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; /** * The MeshVisibilityController watches the Mesh and the active Camera of a Scene * to determine whether the object is actually inside the view frustum or not. * * @author Jean-Marc Le Roux * */ public final class MeshVisibilityController extends AbstractController { use namespace minko_math; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_VECTOR4_2 : Vector4 = new Vector4(); private static const STATE_UNDEFINED : uint = 0; private static const STATE_INSIDE : uint = 1; private static const STATE_OUTSIDE : uint = 2; private var _mesh : Mesh; private var _state : uint; private var _lastTest : int; private var _boundingBox : BoundingBox; private var _boundingSphere : BoundingSphere; private var _data : DataProvider; private var _frustumCulling : uint; private var _insideFrustum : Boolean; public function get frustumCulling() : uint { return _frustumCulling; } public function set frustumCulling(value : uint) : void { if (value != _frustumCulling) { _frustumCulling = value; if (value == FrustumCulling.DISABLED) { _data.computedVisibility = true; if (_mesh.localToWorldTransformChanged.hasCallback(meshLocalToWorldChangedHandler)) _mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler); } else if (_mesh && _mesh.scene) { _mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler); testCulling(); } } } public function get insideFrustum() : Boolean { return _insideFrustum; } public function get computedVisibility() : Boolean { return _data.computedVisibility; } public function MeshVisibilityController() { super(Mesh); initialize(); } private function initialize() : void { _data = new DataProvider( { computedVisibility : true }, 'MeshVisibilityDataProvider', DataProviderUsage.EXCLUSIVE ); _boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE); _boundingSphere = new BoundingSphere(Vector4.ZERO, 0.); _state = STATE_UNDEFINED; targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(ctrl : MeshVisibilityController, target : Mesh) : void { if (_mesh != null) throw new Error(); _mesh = target; target.added.add(addedHandler); target.removed.add(removedHandler); if (target.root is Scene) addedHandler(target, target.root as Scene); if (_frustumCulling) testCulling(); } private function targetRemovedHandler(ctrl : MeshVisibilityController, target : Mesh) : void { _mesh = null; target.added.remove(addedHandler); target.removed.remove(removedHandler); if (target.root is Scene) removedHandler(target, target.root as Scene); } private function addedHandler(mesh : Mesh, ancestor : Group) : void { var scene : Scene = ancestor.scene; if (!scene) return ; scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler); if (_frustumCulling) scene.renderingBegin.add(sceneRenderingBeginHandler); _mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler); _mesh.bindings.addProvider(_data); } private function sceneRenderingBeginHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { scene.renderingBegin.remove(sceneRenderingBeginHandler); meshLocalToWorldChangedHandler(_mesh, _mesh.getLocalToWorldTransform()); _mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler); } private function removedHandler(mesh : Mesh, ancestor : Group) : void { var scene : Scene = ancestor.scene; if (!scene) return ; if (scene.renderingBegin.hasCallback(sceneRenderingBeginHandler)) scene.renderingBegin.remove(sceneRenderingBeginHandler); scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler); if (_frustumCulling && mesh.localToWorldTransformChanged.hasCallback(meshLocalToWorldChangedHandler)) mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler); mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler); mesh.bindings.removeProvider(_data); } private function computedVisiblityChangedHandler(node : ISceneNode, computedVisibility : Boolean) : void { _data.computedVisibility = computedVisibility; } private function worldToScreenChangedHandler(bindings : DataBindings, bindingName : String, oldValue : Matrix4x4, value : Matrix4x4) : void { testCulling(); } private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void { var geom : Geometry = _mesh.geometry; var culling : uint = _frustumCulling; if (!geom || !geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED) return ; if (culling & FrustumCulling.BOX) transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices); if (culling & FrustumCulling.SPHERE) { var center : Vector4 = transform.transformVector(geom.boundingSphere.center, TMP_VECTOR4); var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE, TMP_VECTOR4_2); var radius : Number = geom.boundingSphere.radius * Math.max( Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z) ); _boundingSphere.update(center, radius); } testCulling(); } private function testCulling() : void { var culling : uint = _frustumCulling; if (_mesh && _mesh.geometry && _mesh.geometry.boundingBox && _mesh.visible && _mesh.root is Scene) { var camera : AbstractCamera = (_mesh.root as Scene).activeCamera; if (!camera) return ; _lastTest = camera.frustum.testBoundingVolume( _boundingSphere, _boundingBox, null, culling, _lastTest ); var inside : Boolean = _lastTest == -1; if (inside && _state != STATE_INSIDE) { _insideFrustum = true; _data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible; _mesh.computedVisibilityChanged.execute(_mesh, computedVisibility); _state = STATE_INSIDE; } else if (!inside && _state != STATE_OUTSIDE) { _insideFrustum = false; _data.computedVisibility = false; _mesh.computedVisibilityChanged.execute(_mesh, false); _state = STATE_OUTSIDE; } } } override public function clone() : AbstractController { return new MeshVisibilityController(); } } }
Fix when a mesh is added to the scene
Fix when a mesh is added to the scene
ActionScript
mit
aerys/minko-as3
85833d4057e0b050a9c975d40df48c2767e4d23d
src/com/ryanberdeen/echonest/api/v3/track/utils/TrackLoader.as
src/com/ryanberdeen/echonest/api/v3/track/utils/TrackLoader.as
package com.ryanberdeen.echonest.api.v3.track.utils { import com.ryanberdeen.echonest.api.v3.EchoNestError; import com.ryanberdeen.echonest.api.v3.EchoNestErrorEvent; import com.ryanberdeen.echonest.api.v3.track.AnalysisEvent; import com.ryanberdeen.echonest.api.v3.track.AnalysisLoader; import com.ryanberdeen.echonest.api.v3.track.TrackApi; import com.ryanberdeen.utils.MD5Calculator; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.media.Sound; import flash.net.FileFilter; import flash.net.FileReference; import org.audiofx.mp3.MP3FileReferenceLoader; import org.audiofx.mp3.MP3SoundEvent; public class TrackLoader extends EventDispatcher { private var trackApi:TrackApi; private var _fileReference:FileReference; private var mp3Loader:MP3FileReferenceLoader; private var _md5Calculator:MD5Calculator; private var _analysisLoader:AnalysisLoader; private var _alwaysUpload:Boolean; private var _sound:Sound; private var _md5:String; private var _id:String; public function TrackLoader(trackApi:TrackApi) { this.trackApi = trackApi; _fileReference = new FileReference(); _md5Calculator = new MD5Calculator(); _analysisLoader = new AnalysisLoader(trackApi); _alwaysUpload = false; } public function set alwaysUpload(alwaysUpload:Boolean):void { _alwaysUpload = alwaysUpload; } public function get fileReference():FileReference { return _fileReference; } public function get md5Calculator():MD5Calculator { return _md5Calculator; } public function get analysisLoader():AnalysisLoader { return _analysisLoader; } public function get sound():Sound { return _sound; } public function load(...properties):void { _analysisLoader.properties = properties; _fileReference.addEventListener(Event.SELECT, fileReferenceSelectHandler); _fileReference.browse([new FileFilter("MP3 Files", "*.mp3")]); } private function fileReferenceSelectHandler(e:Event):void { dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.LOADING_SOUND)); mp3Loader = new MP3FileReferenceLoader(); mp3Loader.addEventListener(Event.COMPLETE, soundLoadCompleteHandler); mp3Loader.getSound(_fileReference); } private function soundLoadCompleteHandler(e:MP3SoundEvent):void { _sound = e.sound; dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.SOUND_LOADED)); mp3Loader.removeEventListener(Event.COMPLETE, soundLoadCompleteHandler); if (_alwaysUpload) { uploadFile(); } else { calculateMd5(); } } private function calculateMd5():void { dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.CALCULATING_MD5)); _md5Calculator.addEventListener(Event.COMPLETE, md5CompleteHandler); _md5Calculator.calculate(_fileReference.data); } private function md5CompleteHandler(e:Event):void { dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.MD5_CALCULATED)); _md5 = _md5Calculator.md5; _md5Calculator = null; dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.CHECKING_ANALYSIS)); loadAnalysis({md5: _md5}); } private function uploadFile():void { dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.UPLOADING_FILE)); trackApi.uploadFileReference({file: _fileReference, wait: "N"}, { onResponse: function(track:Object):void { _id = track.id; dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.FILE_UPLOADED)); dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.LOADING_ANALYSIS)); loadAnalysis({id: _id}); }, onEchoNestError: function(error:EchoNestError):void { dispatchEvent(error.createEvent()); }, onError: dispatchEvent }); } private function loadAnalysis(parameters:Object):void { _analysisLoader.addEventListener(AnalysisEvent.UNKNOWN, analysisUnknownHandler); _analysisLoader.load(parameters); } private function analysisUnknownHandler(e:Event):void { uploadFile(); dispatchEvent(e); } } }
package com.ryanberdeen.echonest.api.v3.track.utils { import com.ryanberdeen.echonest.api.v3.EchoNestError; import com.ryanberdeen.echonest.api.v3.EchoNestErrorEvent; import com.ryanberdeen.echonest.api.v3.track.AnalysisEvent; import com.ryanberdeen.echonest.api.v3.track.AnalysisLoader; import com.ryanberdeen.echonest.api.v3.track.TrackApi; import com.ryanberdeen.utils.MD5Calculator; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.media.Sound; import flash.net.FileFilter; import flash.net.FileReference; import org.audiofx.mp3.MP3FileReferenceLoader; import org.audiofx.mp3.MP3SoundEvent; public class TrackLoader extends EventDispatcher { private var trackApi:TrackApi; private var _fileReference:FileReference; private var mp3Loader:MP3FileReferenceLoader; private var _md5Calculator:MD5Calculator; private var _analysisLoader:AnalysisLoader; private var _alwaysUpload:Boolean; private var _sound:Sound; private var _md5:String; private var _id:String; public function TrackLoader(trackApi:TrackApi) { this.trackApi = trackApi; _fileReference = new FileReference(); _fileReference.addEventListener(Event.SELECT, fileReferenceSelectHandler); _md5Calculator = new MD5Calculator(); _analysisLoader = new AnalysisLoader(trackApi); _alwaysUpload = false; } public function set alwaysUpload(alwaysUpload:Boolean):void { _alwaysUpload = alwaysUpload; } public function get fileReference():FileReference { return _fileReference; } public function get md5Calculator():MD5Calculator { return _md5Calculator; } public function get analysisLoader():AnalysisLoader { return _analysisLoader; } public function get sound():Sound { return _sound; } public function load(...properties):void { _analysisLoader.properties = properties; _fileReference.browse([new FileFilter("MP3 Files", "*.mp3")]); } private function fileReferenceSelectHandler(e:Event):void { dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.LOADING_SOUND)); mp3Loader = new MP3FileReferenceLoader(); mp3Loader.addEventListener(Event.COMPLETE, soundLoadCompleteHandler); mp3Loader.getSound(_fileReference); } private function soundLoadCompleteHandler(e:MP3SoundEvent):void { _sound = e.sound; dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.SOUND_LOADED)); mp3Loader.removeEventListener(Event.COMPLETE, soundLoadCompleteHandler); if (_alwaysUpload) { uploadFile(); } else { calculateMd5(); } } private function calculateMd5():void { dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.CALCULATING_MD5)); _md5Calculator.addEventListener(Event.COMPLETE, md5CompleteHandler); _md5Calculator.calculate(_fileReference.data); } private function md5CompleteHandler(e:Event):void { dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.MD5_CALCULATED)); _md5 = _md5Calculator.md5; _md5Calculator = null; dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.CHECKING_ANALYSIS)); loadAnalysis({md5: _md5}); } private function uploadFile():void { dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.UPLOADING_FILE)); trackApi.uploadFileReference({file: _fileReference, wait: "N"}, { onResponse: function(track:Object):void { _id = track.id; dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.FILE_UPLOADED)); dispatchEvent(new TrackLoaderEvent(TrackLoaderEvent.LOADING_ANALYSIS)); loadAnalysis({id: _id}); }, onEchoNestError: function(error:EchoNestError):void { dispatchEvent(error.createEvent()); }, onError: dispatchEvent }); } private function loadAnalysis(parameters:Object):void { _analysisLoader.addEventListener(AnalysisEvent.UNKNOWN, analysisUnknownHandler); _analysisLoader.load(parameters); } private function analysisUnknownHandler(e:Event):void { uploadFile(); dispatchEvent(e); } } }
fix track loader to only add file selected handler once
fix track loader to only add file selected handler once
ActionScript
mit
also/echo-nest-flash-api
9c5fb24a3e15902dd09e1cdf5bc354ff0bac1884
src/org/hola/JSURLStream.as
src/org/hola/JSURLStream.as
/* 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/. */ package org.hola { import flash.events.*; import flash.external.ExternalInterface; import flash.net.URLRequest; import flash.net.URLStream; import flash.utils.ByteArray; import org.hola.ZExternalInterface; import org.hola.ZErr; import org.hola.Base64; import org.hola.WorkerUtils; import org.hola.HEvent; import org.hola.HSettings; import org.hola.FlashFetchBin; public dynamic class JSURLStream extends URLStream { private static var js_api_inited : Boolean = false; private static var req_count : Number = 0; private static var reqs : Object = {}; private var _connected : Boolean; private var _resource : ByteArray = new ByteArray(); private var _curr_data : Object; private var _hola_managed : Boolean = false; private var _req_id : String; public function JSURLStream(){ _hola_managed = HSettings.hls_mode && ZExternalInterface.avail(); addEventListener(Event.OPEN, onopen); super(); if (!ZExternalInterface.avail() || js_api_inited) return; /* XXX arik: setting this to true will pass js exceptions to * as3 and as3 exceptions to js. this may break current customer * code ExternalInterface.marshallExceptions = true; */ ExternalInterface.addCallback('hola_onFragmentData', hola_onFragmentData); js_api_inited = true; } protected function _trigger(cb : String, data : Object) : void { if (!_hola_managed) return ZErr.log('invalid trigger'); // XXX arik: ZErr.throw ExternalInterface.call('window.hola_'+cb, {objectID: ExternalInterface.objectID, data: data}); } override public function get connected() : Boolean { if (!_hola_managed) return super.connected; return _connected; } override public function get bytesAvailable() : uint { if (!_hola_managed) return super.bytesAvailable; return _resource.bytesAvailable; } override public function readByte() : int { if (!_hola_managed) return super.readByte(); return _resource.readByte(); } override public function readUnsignedShort() : uint { if (!_hola_managed) return super.readUnsignedShort(); return _resource.readUnsignedShort(); } override public function readBytes(bytes : ByteArray, offset : uint = 0, length : uint = 0) : void { if (!_hola_managed) return super.readBytes(bytes, offset, length); _resource.readBytes(bytes, offset, length); } override public function close() : void { if (_hola_managed) { if (reqs[_req_id]) { _delete(); _trigger('abortFragment', {req_id: _req_id}); } WorkerUtils.removeEventListener(HEvent.WORKER_MESSAGE, onmsg); } if (super.connected) super.close(); _connected = false; } override public function load(request : URLRequest) : void { if (_hola_managed) { if (reqs[_req_id]) { _delete(); _trigger('abortFragment', {req_id: _req_id}); } WorkerUtils.removeEventListener(HEvent.WORKER_MESSAGE, onmsg); } _hola_managed = HSettings.enabled && ZExternalInterface.avail(); req_count++; _req_id = 'req'+req_count; if (!_hola_managed) return super.load(request); WorkerUtils.addEventListener(HEvent.WORKER_MESSAGE, onmsg); reqs[_req_id] = this; _resource = new ByteArray(); _trigger('requestFragment', {url: request.url, req_id: _req_id}); this.dispatchEvent(new Event(Event.OPEN)); } private function onopen(e : Event) : void { _connected = true; } private function decode(str : String) : void { if (!str) return on_decoded_data(null); if (!HSettings.use_worker) return on_decoded_data(Base64.decode_str(str)); var data : ByteArray = new ByteArray(); data.shareable = true; data.writeUTFBytes(str); WorkerUtils.send({cmd: "b64.decode", id: _req_id}); WorkerUtils.send(data); } private function onmsg(e : HEvent) : void { var msg : Object = e.data; if (!_req_id || _req_id!=msg.id || msg.cmd!="b64.decode") return; on_decoded_data(WorkerUtils.recv()); } private function on_decoded_data(data : ByteArray) : void { if (data) { data.position = 0; if (_resource) { var prev : uint = _resource.position; data.readBytes(_resource, _resource.length); _resource.position = prev; } else _resource = data; // XXX arik: get finalLength from js var finalLength : uint = _resource.length; dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, _resource.length, finalLength)); } // XXX arik: dispatch httpStatus/httpResponseStatus if (_curr_data.status) resourceLoadingSuccess(); } private function on_fragment_data(o : Object) : void { _curr_data = o; if (o.error) return resourceLoadingError(); if (o.fetchBinReqId) return fetch_bin(o); decode(o.data); } private function fetch_bin(o : Object) : void { if (!(o.fetchBinReq = FlashFetchBin.req_list[o.fetchBinReqId])) throw new Error('fetchBinReqId not found '+o.fetchBinReqId); _fetch_bin(o); } private function _fetch_bin(o : Object) : void { var fetchBinStream : URLStream = o.fetchBinReq.stream; _resource = _resource || new ByteArray(); var prev : Number = _resource.position; var len : Number = Math.min(fetchBinStream.bytesAvailable, HSettings.fetch_bin_chunk_size); if (len) { fetchBinStream.readBytes(_resource, _resource.length, len); _resource.position = prev; dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, _resource.length, o.fetchBinReq.bytesTotal)); } if (_resource.length < o.fetchBinReq.bytesTotal) { FlashFetchBin.consumeDataTimeout(o.fetchBinReqId, _fetch_bin, HSettings.fetch_bin_delay, o); } else { resourceLoadingSuccess(); FlashFetchBin.hola_fetchBinRemove(o.fetchBinReqId); } } private static function hola_onFragmentData(o : Object) : void { var stream : JSURLStream; try { if (!(stream = reqs[o.req_id])) return ZErr.log('req_id not found '+o.req_id); stream.on_fragment_data(o); } catch(err : Error){ ZErr.log('Error in hola_onFragmentData', ''+err, ''+err.getStackTrace()); if (stream) stream.resourceLoadingError(); throw err; } } private function _delete() : void { delete reqs[_req_id]; } protected function resourceLoadingError() : void { _delete(); dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR)); } protected function resourceLoadingSuccess() : void { _delete(); dispatchEvent(new Event(Event.COMPLETE)); } } }
/* 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/. */ package org.hola { import flash.events.*; import flash.external.ExternalInterface; import flash.net.URLRequest; import flash.net.URLStream; import flash.utils.ByteArray; import org.hola.ZExternalInterface; import org.hola.ZErr; import org.hola.Base64; import org.hola.WorkerUtils; import org.hola.HEvent; import org.hola.HSettings; import org.hola.FlashFetchBin; public dynamic class JSURLStream extends URLStream { private static var js_api_inited : Boolean = false; private static var req_count : Number = 0; private static var reqs : Object = {}; private var _connected : Boolean; private var _resource : ByteArray = new ByteArray(); private var _curr_data : Object; private var _hola_managed : Boolean = false; private var _req_id : String; public function JSURLStream(){ _hola_managed = HSettings.hls_mode && ZExternalInterface.avail(); addEventListener(Event.OPEN, onopen); super(); if (!ZExternalInterface.avail() || js_api_inited) return; /* XXX arik: setting this to true will pass js exceptions to * as3 and as3 exceptions to js. this may break current customer * code ExternalInterface.marshallExceptions = true; */ ExternalInterface.addCallback('hola_onFragmentData', hola_onFragmentData); js_api_inited = true; } protected function _trigger(cb : String, data : Object) : void { if (!_hola_managed) return ZErr.log('invalid trigger'); // XXX arik: ZErr.throw ExternalInterface.call('window.hola_'+cb, {objectID: ExternalInterface.objectID, data: data}); } override public function get connected() : Boolean { if (!_hola_managed) return super.connected; return _connected; } override public function get bytesAvailable() : uint { if (!_hola_managed) return super.bytesAvailable; return _resource.bytesAvailable; } override public function readByte() : int { if (!_hola_managed) return super.readByte(); return _resource.readByte(); } override public function readUnsignedShort() : uint { if (!_hola_managed) return super.readUnsignedShort(); return _resource.readUnsignedShort(); } override public function readBytes(bytes : ByteArray, offset : uint = 0, length : uint = 0) : void { if (!_hola_managed) return super.readBytes(bytes, offset, length); _resource.readBytes(bytes, offset, length); } override public function close() : void { if (_hola_managed) { if (reqs[_req_id]) { _delete(); _trigger('abortFragment', {req_id: _req_id}); } WorkerUtils.removeEventListener(HEvent.WORKER_MESSAGE, onmsg); } if (super.connected) super.close(); _connected = false; } override public function load(request : URLRequest) : void { if (_hola_managed) { if (reqs[_req_id]) { _delete(); _trigger('abortFragment', {req_id: _req_id}); } WorkerUtils.removeEventListener(HEvent.WORKER_MESSAGE, onmsg); } _hola_managed = HSettings.enabled && ZExternalInterface.avail(); req_count++; _req_id = 'req'+req_count; if (!_hola_managed) return super.load(request); WorkerUtils.addEventListener(HEvent.WORKER_MESSAGE, onmsg); reqs[_req_id] = this; _resource = new ByteArray(); _trigger('requestFragment', {url: request.url, req_id: _req_id}); this.dispatchEvent(new Event(Event.OPEN)); } private function onopen(e : Event) : void { _connected = true; } private function decode(str : String) : void { if (!str) return on_decoded_data(null); if (!HSettings.use_worker) return on_decoded_data(Base64.decode_str(str)); var data : ByteArray = new ByteArray(); CONFIG::HAVE_WORKER { data.shareable = true; } data.writeUTFBytes(str); WorkerUtils.send({cmd: "b64.decode", id: _req_id}); WorkerUtils.send(data); } private function onmsg(e : HEvent) : void { var msg : Object = e.data; if (!_req_id || _req_id!=msg.id || msg.cmd!="b64.decode") return; on_decoded_data(WorkerUtils.recv()); } private function on_decoded_data(data : ByteArray) : void { if (data) { data.position = 0; if (_resource) { var prev : uint = _resource.position; data.readBytes(_resource, _resource.length); _resource.position = prev; } else _resource = data; // XXX arik: get finalLength from js var finalLength : uint = _resource.length; dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, _resource.length, finalLength)); } // XXX arik: dispatch httpStatus/httpResponseStatus if (_curr_data.status) resourceLoadingSuccess(); } private function on_fragment_data(o : Object) : void { _curr_data = o; if (o.error) return resourceLoadingError(); if (o.fetchBinReqId) return fetch_bin(o); decode(o.data); } private function fetch_bin(o : Object) : void { if (!(o.fetchBinReq = FlashFetchBin.req_list[o.fetchBinReqId])) throw new Error('fetchBinReqId not found '+o.fetchBinReqId); _fetch_bin(o); } private function _fetch_bin(o : Object) : void { var fetchBinStream : URLStream = o.fetchBinReq.stream; _resource = _resource || new ByteArray(); var prev : Number = _resource.position; var len : Number = Math.min(fetchBinStream.bytesAvailable, HSettings.fetch_bin_chunk_size); if (len) { fetchBinStream.readBytes(_resource, _resource.length, len); _resource.position = prev; dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, _resource.length, o.fetchBinReq.bytesTotal)); } if (_resource.length < o.fetchBinReq.bytesTotal) { FlashFetchBin.consumeDataTimeout(o.fetchBinReqId, _fetch_bin, HSettings.fetch_bin_delay, o); } else { resourceLoadingSuccess(); FlashFetchBin.hola_fetchBinRemove(o.fetchBinReqId); } } private static function hola_onFragmentData(o : Object) : void { var stream : JSURLStream; try { if (!(stream = reqs[o.req_id])) return ZErr.log('req_id not found '+o.req_id); stream.on_fragment_data(o); } catch(err : Error){ ZErr.log('Error in hola_onFragmentData', ''+err, ''+err.getStackTrace()); if (stream) stream.resourceLoadingError(); throw err; } } private function _delete() : void { delete reqs[_req_id]; } protected function resourceLoadingError() : void { _delete(); dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR)); } protected function resourceLoadingSuccess() : void { _delete(); dispatchEvent(new Event(Event.COMPLETE)); } } }
support older compiler
support older compiler
ActionScript
mpl-2.0
hola/flashls,hola/flashls
6e7867b3e2ac2914d81cd048e2da6b601eb7f7a1
samples/projects/krew_async/projects/web-project/src/WebMain.as
samples/projects/krew_async/projects/web-project/src/WebMain.as
package { import flash.display.Sprite; import krewfw.KrewConfig; import krewfw.utils.krew; /** * Customize options or components for Flash publishing. */ public class WebMain extends Sprite { public function WebMain() { krew.log("Kicked from WebMain"); KrewConfig.IS_AIR = false; KrewConfig.ASSET_URL_SCHEME = "http://uri/to/assets/"; var main:Main = new Main(this); } } }
package { import flash.display.Sprite; import krewfw.KrewConfig; import krewfw.utils.krew; /** * Customize options or components for Flash publishing. */ public class WebMain extends Sprite { public function WebMain() { krew.log("Kicked from WebMain"); KrewConfig.IS_AIR = false; KrewConfig.ASSET_URL_SCHEME = "http://docs.tatsuya-koyama.com/assets/media/swf/krewsample/"; var main:Main = new Main(this); } } }
Modify sample web project
Modify sample web project
ActionScript
mit
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
e9a56b49c6659304a009598e6a818a518439c3aa
src/aerys/minko/scene/controller/debug/JointsDebugController.as
src/aerys/minko/scene/controller/debug/JointsDebugController.as
package aerys.minko.scene.controller.debug { import aerys.minko.render.geometry.primitive.CubeGeometry; import aerys.minko.render.material.Material; import aerys.minko.render.material.basic.BasicMaterial; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.mesh.skinning.SkinningController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.Mesh; import aerys.minko.type.enum.DepthTest; import aerys.minko.type.math.Vector4; /** * Add debug meshes to see the joints/bones of the skeleton of a skinned Mesh. * This controller can target all the meshes with a SkinningController: * * <pre> * var debugCtrl : JointsDebugController = new JointsDebugController(); * * for each (var mesh : Mesh in scene.get('//mesh[hasController(SkinningController)]')) * mesh.addController(debugCtrl); * </pre> * * @author Jean-Marc Le Roux * */ public final class JointsDebugController extends AbstractController { private var _jointsMaterial : Material; public function JointsDebugController(jointsMaterial : Material = null) { super(Mesh); initialize(jointsMaterial); } private function initialize(jointsMaterial : Material) : void { _jointsMaterial = jointsMaterial; if (!_jointsMaterial) { var jointsBasicMaterial : BasicMaterial = new BasicMaterial(); jointsBasicMaterial.diffuseColor = 0xff0000ff; jointsBasicMaterial.depthWriteEnabled = false; jointsBasicMaterial.depthTest = DepthTest.ALWAYS; _jointsMaterial = jointsBasicMaterial; } targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(ctrl : AbstractController, target : Mesh) : void { var skinningCtrl : SkinningController = target.getControllersByType(SkinningController)[0] as SkinningController; for each (var joint : Group in skinningCtrl.joints) addJointsMeshes(joint); } private function targetRemovedHandler(ctrl : AbstractController, target : Mesh) : void { var skinningCtrl : SkinningController = target.getControllersByType(SkinningController)[0] as SkinningController; for each (var joint : Group in skinningCtrl.joints) joint.getChildByName('__joint__').parent = null; } private function addJointsMeshes(joint : Group) : void { if (joint.getChildByName('__joint__')) return ; var numChildren : uint = joint.numChildren; for (var i : uint = 0; i < numChildren; ++i) { var child : Group = joint.getChildAt(i) as Group; if (child != null) { var jointMesh : Mesh = new Mesh( CubeGeometry.cubeGeometry, _jointsMaterial, '__joint__' ); jointMesh.transform.appendUniformScale(.08); joint.addChild(jointMesh); } } } } }
package aerys.minko.scene.controller.debug { import aerys.minko.render.geometry.primitive.CubeGeometry; import aerys.minko.render.material.Material; import aerys.minko.render.material.basic.BasicMaterial; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.mesh.skinning.SkinningController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.Mesh; import aerys.minko.type.enum.DepthTest; import aerys.minko.type.math.Vector4; /** * Add debug meshes to see the joints/bones of the skeleton of a skinned Mesh. * This controller can target all the meshes with a SkinningController: * * <pre> * var debugCtrl : JointsDebugController = new JointsDebugController(); * * for each (var mesh : Mesh in scene.get('//mesh[hasController(SkinningController)]')) * mesh.addController(debugCtrl); * </pre> * * @author Jean-Marc Le Roux * */ public final class JointsDebugController extends AbstractController { private var _jointSize : Number; private var _jointsMaterial : Material; public function JointsDebugController(jointsSize : Number = 0.08, jointsMaterial : Material = null) { super(Mesh); initialize(jointsSize, jointsMaterial); } private function initialize(jointSize : Number, jointsMaterial : Material) : void { _jointSize = jointSize; _jointsMaterial = jointsMaterial; if (!_jointsMaterial) { var jointsBasicMaterial : BasicMaterial = new BasicMaterial(); jointsBasicMaterial.diffuseColor = 0xff0000ff; jointsBasicMaterial.depthWriteEnabled = false; jointsBasicMaterial.depthTest = DepthTest.ALWAYS; _jointsMaterial = jointsBasicMaterial; } targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(ctrl : AbstractController, target : Mesh) : void { var skinningCtrl : SkinningController = target.getControllersByType(SkinningController)[0] as SkinningController; for each (var joint : Group in skinningCtrl.joints) addJointsMeshes(joint); } private function targetRemovedHandler(ctrl : AbstractController, target : Mesh) : void { var skinningCtrl : SkinningController = target.getControllersByType(SkinningController)[0] as SkinningController; for each (var joint : Group in skinningCtrl.joints) joint.getChildByName('__joint__').parent = null; } private function addJointsMeshes(joint : Group) : void { if (joint.getChildByName('__joint__')) return ; var numChildren : uint = joint.numChildren; for (var i : uint = 0; i < numChildren; ++i) { var child : Group = joint.getChildAt(i) as Group; if (child != null) { var jointMesh : Mesh = new Mesh( CubeGeometry.cubeGeometry, _jointsMaterial, '__joint__' ); jointMesh.transform.appendUniformScale(_jointSize); joint.addChild(jointMesh); } } } } }
add customizable size for the joints debug meshes
add customizable size for the joints debug meshes
ActionScript
mit
aerys/minko-as3
f3816c1080fda2af17eddd1daed430d3c0a87a04
src/Player.as
src/Player.as
package { import com.axis.audioclient.AxisTransmit; import com.axis.ClientEvent; import com.axis.ErrorManager; import com.axis.http.url; import com.axis.httpclient.HTTPClient; import com.axis.IClient; import com.axis.Logger; import com.axis.mjpegclient.MJPEGClient; import com.axis.rtmpclient.RTMPClient; import com.axis.rtspclient.IRTSPHandle; import com.axis.rtspclient.RTSPClient; import com.axis.rtspclient.RTSPoverHTTPHandle; import com.axis.rtspclient.RTSPoverTCPHandle; import flash.display.LoaderInfo; import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageDisplayState; import flash.display.StageScaleMode; import flash.display.DisplayObject; import flash.display.InteractiveObject; import flash.events.Event; import flash.events.MouseEvent; import flash.external.ExternalInterface; import flash.media.Microphone; import flash.media.SoundMixer; import flash.media.SoundTransform; import flash.media.Video; import flash.net.NetStream; import flash.system.Security; import mx.utils.StringUtil; [SWF(frameRate="60")] [SWF(backgroundColor="#efefef")] public class Player extends Sprite { [Embed(source = "../VERSION", mimeType = "application/octet-stream")] private var Version:Class; public static var locomoteID:String = null; private static const EVENT_STREAM_STARTED:String = "streamStarted"; private static const EVENT_STREAM_PAUSED:String = "streamPaused"; private static const EVENT_STREAM_STOPPED:String = "streamStopped"; private static const EVENT_STREAM_ENDED:String = "streamEnded"; private static const EVENT_FULLSCREEN_ENTERED:String = "fullscreenEntered"; private static const EVENT_FULLSCREEN_EXITED:String = "fullscreenExited"; private static const EVENT_FRAME_READY:String = "frameReady"; public static var config:Object = { 'buffer': 3, 'connectionTimeout': 10, 'scaleUp': false, 'allowFullscreen': true, 'debugLogger': false, 'frameByFrame': false }; private var audioTransmit:AxisTransmit = new AxisTransmit(); private var meta:Object = {}; private var client:IClient; private var urlParsed:Object; private var savedSpeakerVolume:Number; private var fullscreenAllowed:Boolean = true; private var currentState:String = "stopped"; private var streamHasAudio:Boolean = false; private var streamHasVideo:Boolean = false; private var newPlaylistItem:Boolean = false; private var startOptions:Object = null; public function Player() { var self:Player = this; Security.allowDomain("*"); Security.allowInsecureDomain("*"); trace('Loaded Locomote, version ' + StringUtil.trim(new Version().toString())); if (ExternalInterface.available) { setupAPICallbacks(); } else { trace("External interface is not available for this container."); } /* Set default speaker volume */ this.speakerVolume(50); /* Stage setup */ this.stage.align = StageAlign.TOP_LEFT; this.stage.scaleMode = StageScaleMode.NO_SCALE; addEventListener(Event.ADDED_TO_STAGE, onStageAdded); /* Fullscreen support setup */ this.stage.doubleClickEnabled = true; this.stage.addEventListener(MouseEvent.DOUBLE_CLICK, fullscreen); this.stage.addEventListener(Event.FULLSCREEN, function(event:Event):void { (StageDisplayState.NORMAL === stage.displayState) ? callAPI(EVENT_FULLSCREEN_EXITED) : callAPI(EVENT_FULLSCREEN_ENTERED); }); this.stage.addEventListener(Event.RESIZE, function(event:Event):void { videoResize(); }); this.setConfig(Player.config); } /** * Registers the appropriate API functions with the container, so that * they can be called, and triggers the apiReady event * which tells the container that the Player is ready to receive API calls. */ public function setupAPICallbacks():void { ExternalInterface.marshallExceptions = true; /* Media player API */ ExternalInterface.addCallback("play", play); ExternalInterface.addCallback("pause", pause); ExternalInterface.addCallback("resume", resume); ExternalInterface.addCallback("stop", stop); ExternalInterface.addCallback("seek", seek); ExternalInterface.addCallback("playFrames", playFrames); ExternalInterface.addCallback("streamStatus", streamStatus); ExternalInterface.addCallback("playerStatus", playerStatus); ExternalInterface.addCallback("speakerVolume", speakerVolume); ExternalInterface.addCallback("muteSpeaker", muteSpeaker); ExternalInterface.addCallback("unmuteSpeaker", unmuteSpeaker); ExternalInterface.addCallback("microphoneVolume", microphoneVolume); ExternalInterface.addCallback("muteMicrophone", muteMicrophone); ExternalInterface.addCallback("unmuteMicrophone", unmuteMicrophone); ExternalInterface.addCallback("setConfig", setConfig); /* Audio Transmission API */ ExternalInterface.addCallback("startAudioTransmit", startAudioTransmit); ExternalInterface.addCallback("stopAudioTransmit", stopAudioTransmit); } public function fullscreen(event:MouseEvent):void { if (config.allowFullscreen) { this.stage.displayState = (StageDisplayState.NORMAL === stage.displayState) ? StageDisplayState.FULL_SCREEN : StageDisplayState.NORMAL; } } public function videoResize():void { if (!this.client) { return; } var stagewidth:uint = (StageDisplayState.NORMAL === stage.displayState) ? stage.stageWidth : stage.fullScreenWidth; var stageheight:uint = (StageDisplayState.NORMAL === stage.displayState) ? stage.stageHeight : stage.fullScreenHeight; var video:DisplayObject = this.client.getDisplayObject(); var scale:Number = ((stagewidth / meta.width) > (stageheight / meta.height)) ? (stageheight / meta.height) : (stagewidth / meta.width); video.width = meta.width; video.height = meta.height; if ((scale < 1.0) || (scale > 1.0 && true === config.scaleUp)) { Logger.log('scaling video, scale:' + scale.toFixed(2) + ' (aspect ratio: ' + (video.width / video.height).toFixed(2) + ')'); video.width = meta.width * scale; video.height = meta.height * scale; } video.x = (stagewidth - video.width) / 2; video.y = (stageheight - video.height) / 2; } public function setConfig(iconfig:Object):void { if (iconfig.buffer !== undefined) { if (this.client) { if (false === this.client.setBuffer(config.buffer)) { ErrorManager.dispatchError(830); } else { config.buffer = iconfig.buffer; } } else { config.buffer = iconfig.buffer; } } if (iconfig.frameByFrame !== undefined) { if (this.client) { if (false === this.client.setFrameByFrame(iconfig.frameByFrame)) { ErrorManager.dispatchError(832); } else { config.frameByFrame = iconfig.frameByFrame; } } else { config.frameByFrame = iconfig.frameByFrame; } } if (iconfig.scaleUp !== undefined) { var scaleUpChanged:Boolean = (config.scaleUp !== iconfig.scaleUp); config.scaleUp = iconfig.scaleUp; if (scaleUpChanged && this.client) this.videoResize(); } if (iconfig.allowFullscreen !== undefined) { config.allowFullscreen = iconfig.allowFullscreen; if (!config.allowFullscreen) this.stage.displayState = StageDisplayState.NORMAL; } if (iconfig.debugLogger !== undefined) { config.debugLogger = iconfig.debugLogger; } if (iconfig.connectionTimeout !== undefined) { config.connectionTimeout = iconfig.connectionTimeout; } } public function play(param:* = null, options:Object = null):void { this.streamHasAudio = false; this.streamHasVideo = false; if (param is String) { urlParsed = url.parse(String(param)); } else { urlParsed = url.parse(param.url); urlParsed.connect = param.url; urlParsed.streamName = param.streamName; } this.newPlaylistItem = true; this.startOptions = options; if (client) { /* Stop the client, and 'onStopped' will start the new stream. */ client.stop(); return; } start(); } private function start():void { switch (urlParsed.protocol) { case 'rtsph': /* RTSP over HTTP */ client = new RTSPClient(urlParsed, new RTSPoverHTTPHandle(urlParsed, false)); break; case 'rtsphs': /* RTSP over HTTPS */ client = new RTSPClient(urlParsed, new RTSPoverHTTPHandle(urlParsed, true)); break; case 'rtsp': /* RTSP over TCP */ client = new RTSPClient(urlParsed, new RTSPoverTCPHandle(urlParsed)); break; case 'http': case 'https': /* Progressive download over HTTP */ client = new HTTPClient(urlParsed); break; case 'httpm': /* Progressive mjpg download over HTTP (x-mixed-replace) */ client = new MJPEGClient(urlParsed); break; case 'rtmp': case 'rtmps': case 'rtmpt': /* RTMP */ client = new RTMPClient(urlParsed); break; default: ErrorManager.dispatchError(811, [urlParsed.protocol]) return; } addChild(this.client.getDisplayObject()); client.addEventListener(ClientEvent.STOPPED, onStopped); client.addEventListener(ClientEvent.START_PLAY, onStartPlay); client.addEventListener(ClientEvent.PAUSED, onPaused); client.addEventListener(ClientEvent.ENDED, onEnded); client.addEventListener(ClientEvent.META, onMeta); client.addEventListener(ClientEvent.FRAME, onFrame); client.start(this.startOptions); this.newPlaylistItem = false; } public function seek(position:String):void { if (!client || !client.seek(Number(position))) { ErrorManager.dispatchError(828); } } public function playFrames(timestamp:Number):void { client && client.playFrames(timestamp); } public function pause():void { try { client.pause() } catch (err:Error) { ErrorManager.dispatchError(808); } } public function resume():void { if (!client || !client.resume()) { ErrorManager.dispatchError(809); } } public function stop():void { if (!client || !client.stop()) { ErrorManager.dispatchError(810); return; } this.currentState = "stopped"; this.streamHasAudio = false; this.streamHasVideo = false; } public function onMeta(event:ClientEvent):void { this.meta = event.data; this.videoResize(); } public function streamStatus():Object { if (this.currentState === 'playing') { /* This causes a crash in some situations */ //this.streamHasAudio = (this.streamHasAudio || this.client.hasAudio()); this.streamHasVideo = (this.streamHasVideo || this.client.hasVideo()); } var status:Object = { 'fps': (this.client) ? this.client.currentFPS() : null, 'resolution': (this.client) ? { width: meta.width, height: meta.height } : null, 'playbackSpeed': (this.client) ? 1.0 : null, 'protocol': (this.urlParsed) ? this.urlParsed.protocol : null, 'audio': (this.client) ? this.streamHasAudio : null, 'video': (this.client) ? this.streamHasVideo : null, 'state': this.currentState, 'streamURL': (this.urlParsed) ? this.urlParsed.full : null, 'duration': meta.duration ? meta.duration : null, 'currentTime': (this.client) ? this.client.getCurrentTime() : -1, 'bufferedTime': (this.client) ? this.client.bufferedTime() : -1 }; return status; } public function playerStatus():Object { var mic:Microphone = Microphone.getMicrophone(); var status:Object = { 'version': StringUtil.trim(new Version().toString()), 'microphoneVolume': audioTransmit.microphoneVolume, 'speakerVolume': this.savedSpeakerVolume, 'microphoneMuted': (mic.gain === 0), 'speakerMuted': (flash.media.SoundMixer.soundTransform.volume === 0), 'fullscreen': (StageDisplayState.FULL_SCREEN === stage.displayState), 'buffer': (client === null) ? 0 : Player.config.buffer }; return status; } public function speakerVolume(volume:Number):void { this.savedSpeakerVolume = volume; var transform:SoundTransform = new SoundTransform(volume / 100.0); flash.media.SoundMixer.soundTransform = transform; } public function muteSpeaker():void { var transform:SoundTransform = new SoundTransform(0); flash.media.SoundMixer.soundTransform = transform; } public function unmuteSpeaker():void { if (flash.media.SoundMixer.soundTransform.volume !== 0) return; var transform:SoundTransform = new SoundTransform(this.savedSpeakerVolume / 100.0); flash.media.SoundMixer.soundTransform = transform; } public function microphoneVolume(volume:Number):void { audioTransmit.microphoneVolume = volume; } public function muteMicrophone():void { audioTransmit.muteMicrophone(); } public function unmuteMicrophone():void { audioTransmit.unmuteMicrophone(); } public function startAudioTransmit(url:String = null, type:String = 'axis'):void { if (type === 'axis') { audioTransmit.start(url); } else { ErrorManager.dispatchError(812); } } public function stopAudioTransmit():void { audioTransmit.stop(); } public function allowFullscreen(state:Boolean):void { this.fullscreenAllowed = state; if (!state) this.stage.displayState = StageDisplayState.NORMAL; } private function onStageAdded(e:Event):void { Player.locomoteID = LoaderInfo(this.root.loaderInfo).parameters.locomoteID.toString(); ExternalInterface.call("LocomoteMap['" + Player.locomoteID + "'].__swfReady"); } private function onStartPlay(event:ClientEvent):void { this.currentState = "playing"; this.callAPI(EVENT_STREAM_STARTED); } private function onEnded(event:ClientEvent):void { this.currentState = "ended"; this.callAPI(EVENT_STREAM_ENDED, event.data); } private function onPaused(event:ClientEvent):void { this.currentState = "paused"; this.callAPI(EVENT_STREAM_PAUSED, event.data); } private function onStopped(event:ClientEvent):void { this.removeChild(this.client.getDisplayObject()); this.client.removeEventListener(ClientEvent.STOPPED, onStopped); this.client.removeEventListener(ClientEvent.START_PLAY, onStartPlay); this.client.removeEventListener(ClientEvent.PAUSED, onPaused); this.client.removeEventListener(ClientEvent.ENDED, onEnded); this.client.removeEventListener(ClientEvent.META, onMeta); this.client.removeEventListener(ClientEvent.FRAME, onFrame); this.client = null; this.callAPI(EVENT_STREAM_STOPPED, event.data); /* If a new `play` has been queued, fire it */ if (this.newPlaylistItem) { start(); } } private function onFrame(event:ClientEvent):void { this.callAPI(EVENT_FRAME_READY, { timestamp: event.data }); } private function callAPI(eventName:String, data:Object = null):void { var functionName:String = "LocomoteMap['" + Player.locomoteID + "'].__playerEvent"; if (data) { ExternalInterface.call(functionName, eventName, data); } else { ExternalInterface.call(functionName, eventName); } } } }
package { import com.axis.audioclient.AxisTransmit; import com.axis.ClientEvent; import com.axis.ErrorManager; import com.axis.http.url; import com.axis.httpclient.HTTPClient; import com.axis.IClient; import com.axis.Logger; import com.axis.mjpegclient.MJPEGClient; import com.axis.rtmpclient.RTMPClient; import com.axis.rtspclient.IRTSPHandle; import com.axis.rtspclient.RTSPClient; import com.axis.rtspclient.RTSPoverHTTPHandle; import com.axis.rtspclient.RTSPoverTCPHandle; import flash.display.LoaderInfo; import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageDisplayState; import flash.display.StageScaleMode; import flash.display.DisplayObject; import flash.display.InteractiveObject; import flash.events.Event; import flash.events.MouseEvent; import flash.external.ExternalInterface; import flash.media.Microphone; import flash.media.SoundMixer; import flash.media.SoundTransform; import flash.media.Video; import flash.net.NetStream; import flash.system.Security; import mx.utils.StringUtil; [SWF(frameRate="60")] [SWF(backgroundColor="#efefef")] public class Player extends Sprite { [Embed(source = "../VERSION", mimeType = "application/octet-stream")] private var Version:Class; public static var locomoteID:String = null; private static const EVENT_STREAM_STARTED:String = "streamStarted"; private static const EVENT_STREAM_PAUSED:String = "streamPaused"; private static const EVENT_STREAM_STOPPED:String = "streamStopped"; private static const EVENT_STREAM_ENDED:String = "streamEnded"; private static const EVENT_FULLSCREEN_ENTERED:String = "fullscreenEntered"; private static const EVENT_FULLSCREEN_EXITED:String = "fullscreenExited"; private static const EVENT_FRAME_READY:String = "frameReady"; public static var config:Object = { 'buffer': 3, 'connectionTimeout': 10, 'scaleUp': false, 'allowFullscreen': true, 'debugLogger': false, 'frameByFrame': false }; private var audioTransmit:AxisTransmit = new AxisTransmit(); private var meta:Object = {}; private var client:IClient; private var urlParsed:Object; private var savedSpeakerVolume:Number; private var fullscreenAllowed:Boolean = true; private var currentState:String = "stopped"; private var streamHasAudio:Boolean = false; private var streamHasVideo:Boolean = false; private var newPlaylistItem:Boolean = false; private var startOptions:Object = null; public function Player() { var self:Player = this; Security.allowDomain("*"); Security.allowInsecureDomain("*"); trace('Loaded Locomote, version ' + StringUtil.trim(new Version().toString())); if (ExternalInterface.available) { setupAPICallbacks(); } else { trace("External interface is not available for this container."); } /* Set default speaker volume */ this.speakerVolume(50); /* Stage setup */ this.stage.align = StageAlign.TOP_LEFT; this.stage.scaleMode = StageScaleMode.NO_SCALE; addEventListener(Event.ADDED_TO_STAGE, onStageAdded); /* Fullscreen support setup */ this.stage.doubleClickEnabled = true; this.stage.addEventListener(MouseEvent.DOUBLE_CLICK, fullscreen); this.stage.addEventListener(Event.FULLSCREEN, function(event:Event):void { (StageDisplayState.NORMAL === stage.displayState) ? callAPI(EVENT_FULLSCREEN_EXITED) : callAPI(EVENT_FULLSCREEN_ENTERED); }); this.stage.addEventListener(Event.RESIZE, function(event:Event):void { videoResize(); }); this.setConfig(Player.config); } /** * Registers the appropriate API functions with the container, so that * they can be called, and triggers the apiReady event * which tells the container that the Player is ready to receive API calls. */ public function setupAPICallbacks():void { ExternalInterface.marshallExceptions = true; /* Media player API */ ExternalInterface.addCallback("play", play); ExternalInterface.addCallback("pause", pause); ExternalInterface.addCallback("resume", resume); ExternalInterface.addCallback("stop", stop); ExternalInterface.addCallback("seek", seek); ExternalInterface.addCallback("playFrames", playFrames); ExternalInterface.addCallback("streamStatus", streamStatus); ExternalInterface.addCallback("playerStatus", playerStatus); ExternalInterface.addCallback("speakerVolume", speakerVolume); ExternalInterface.addCallback("muteSpeaker", muteSpeaker); ExternalInterface.addCallback("unmuteSpeaker", unmuteSpeaker); ExternalInterface.addCallback("microphoneVolume", microphoneVolume); ExternalInterface.addCallback("muteMicrophone", muteMicrophone); ExternalInterface.addCallback("unmuteMicrophone", unmuteMicrophone); ExternalInterface.addCallback("setConfig", setConfig); /* Audio Transmission API */ ExternalInterface.addCallback("startAudioTransmit", startAudioTransmit); ExternalInterface.addCallback("stopAudioTransmit", stopAudioTransmit); } public function fullscreen(event:MouseEvent):void { if (config.allowFullscreen) { this.stage.displayState = (StageDisplayState.NORMAL === stage.displayState) ? StageDisplayState.FULL_SCREEN : StageDisplayState.NORMAL; } } public function videoResize():void { if (!this.client) { return; } var stagewidth:uint = (StageDisplayState.NORMAL === stage.displayState) ? stage.stageWidth : stage.fullScreenWidth; var stageheight:uint = (StageDisplayState.NORMAL === stage.displayState) ? stage.stageHeight : stage.fullScreenHeight; var video:DisplayObject = this.client.getDisplayObject(); var scale:Number = ((stagewidth / meta.width) > (stageheight / meta.height)) ? (stageheight / meta.height) : (stagewidth / meta.width); video.width = meta.width; video.height = meta.height; if ((scale < 1.0) || (scale > 1.0 && true === config.scaleUp)) { Logger.log('scaling video, scale:' + scale.toFixed(2) + ' (aspect ratio: ' + (video.width / video.height).toFixed(2) + ')'); video.width = meta.width * scale; video.height = meta.height * scale; } video.x = (stagewidth - video.width) / 2; video.y = (stageheight - video.height) / 2; } public function setConfig(iconfig:Object):void { if (iconfig.buffer !== undefined) { if (this.client) { if (false === this.client.setBuffer(config.buffer)) { ErrorManager.dispatchError(830); } else { config.buffer = iconfig.buffer; } } else { config.buffer = iconfig.buffer; } } if (iconfig.frameByFrame !== undefined) { if (this.client) { if (false === this.client.setFrameByFrame(iconfig.frameByFrame)) { ErrorManager.dispatchError(832); } else { config.frameByFrame = iconfig.frameByFrame; } } else { config.frameByFrame = iconfig.frameByFrame; } } if (iconfig.scaleUp !== undefined) { var scaleUpChanged:Boolean = (config.scaleUp !== iconfig.scaleUp); config.scaleUp = iconfig.scaleUp; if (scaleUpChanged && this.client) this.videoResize(); } if (iconfig.allowFullscreen !== undefined) { config.allowFullscreen = iconfig.allowFullscreen; if (!config.allowFullscreen) this.stage.displayState = StageDisplayState.NORMAL; } if (iconfig.debugLogger !== undefined) { config.debugLogger = iconfig.debugLogger; } if (iconfig.connectionTimeout !== undefined) { config.connectionTimeout = iconfig.connectionTimeout; } } public function play(param:* = null, options:Object = null):void { this.streamHasAudio = false; this.streamHasVideo = false; if (param is String) { urlParsed = url.parse(String(param)); } else { urlParsed = url.parse(param.url); urlParsed.connect = param.url; urlParsed.streamName = param.streamName; } this.newPlaylistItem = true; this.startOptions = options; if (client) { /* Stop the client, and 'onStopped' will start the new stream. */ client.stop(); return; } start(); } private function start():void { switch (urlParsed.protocol) { case 'rtsph': /* RTSP over HTTP */ client = new RTSPClient(urlParsed, new RTSPoverHTTPHandle(urlParsed, false)); break; case 'rtsphs': /* RTSP over HTTPS */ client = new RTSPClient(urlParsed, new RTSPoverHTTPHandle(urlParsed, true)); break; case 'rtsp': /* RTSP over TCP */ client = new RTSPClient(urlParsed, new RTSPoverTCPHandle(urlParsed)); break; case 'http': case 'https': /* Progressive download over HTTP */ client = new HTTPClient(urlParsed); break; case 'httpm': /* Progressive mjpg download over HTTP (x-mixed-replace) */ client = new MJPEGClient(urlParsed); break; case 'rtmp': case 'rtmps': case 'rtmpt': /* RTMP */ client = new RTMPClient(urlParsed); break; default: ErrorManager.dispatchError(811, [urlParsed.protocol]) return; } addChild(this.client.getDisplayObject()); client.addEventListener(ClientEvent.STOPPED, onStopped); client.addEventListener(ClientEvent.START_PLAY, onStartPlay); client.addEventListener(ClientEvent.PAUSED, onPaused); client.addEventListener(ClientEvent.ENDED, onEnded); client.addEventListener(ClientEvent.META, onMeta); client.addEventListener(ClientEvent.FRAME, onFrame); client.start(this.startOptions); this.newPlaylistItem = false; } public function seek(position:String):void { if (!client || !client.seek(Number(position))) { ErrorManager.dispatchError(828); } } public function playFrames(timestamp:Number):void { client && client.playFrames(timestamp); } public function pause():void { try { client.pause() } catch (err:Error) { ErrorManager.dispatchError(808); } } public function resume():void { if (!client || !client.resume()) { ErrorManager.dispatchError(809); } } public function stop():void { if (!client || !client.stop()) { ErrorManager.dispatchError(810); return; } this.currentState = "stopped"; this.streamHasAudio = false; this.streamHasVideo = false; } public function onMeta(event:ClientEvent):void { this.meta = event.data; this.videoResize(); } public function streamStatus():Object { //if (this.currentState === 'playing') { /* This causes a crash in some situations */ //this.streamHasAudio = (this.streamHasAudio || this.client.hasAudio()); //this.streamHasVideo = (this.streamHasVideo || this.client.hasVideo()); //} var status:Object = { 'fps': (this.client) ? this.client.currentFPS() : null, 'resolution': (this.client) ? { width: meta.width, height: meta.height } : null, 'playbackSpeed': (this.client) ? 1.0 : null, 'protocol': (this.urlParsed) ? this.urlParsed.protocol : null, //'audio': (this.client) ? this.streamHasAudio : null, //'video': (this.client) ? this.streamHasVideo : null, 'state': this.currentState, 'streamURL': (this.urlParsed) ? this.urlParsed.full : null, 'duration': meta.duration ? meta.duration : null, 'currentTime': (this.client) ? this.client.getCurrentTime() : -1, 'bufferedTime': (this.client) ? this.client.bufferedTime() : -1 }; return status; } public function playerStatus():Object { var mic:Microphone = Microphone.getMicrophone(); var status:Object = { 'version': StringUtil.trim(new Version().toString()), 'microphoneVolume': audioTransmit.microphoneVolume, 'speakerVolume': this.savedSpeakerVolume, 'microphoneMuted': (mic.gain === 0), 'speakerMuted': (flash.media.SoundMixer.soundTransform.volume === 0), 'fullscreen': (StageDisplayState.FULL_SCREEN === stage.displayState), 'buffer': (client === null) ? 0 : Player.config.buffer }; return status; } public function speakerVolume(volume:Number):void { this.savedSpeakerVolume = volume; var transform:SoundTransform = new SoundTransform(volume / 100.0); flash.media.SoundMixer.soundTransform = transform; } public function muteSpeaker():void { var transform:SoundTransform = new SoundTransform(0); flash.media.SoundMixer.soundTransform = transform; } public function unmuteSpeaker():void { if (flash.media.SoundMixer.soundTransform.volume !== 0) return; var transform:SoundTransform = new SoundTransform(this.savedSpeakerVolume / 100.0); flash.media.SoundMixer.soundTransform = transform; } public function microphoneVolume(volume:Number):void { audioTransmit.microphoneVolume = volume; } public function muteMicrophone():void { audioTransmit.muteMicrophone(); } public function unmuteMicrophone():void { audioTransmit.unmuteMicrophone(); } public function startAudioTransmit(url:String = null, type:String = 'axis'):void { if (type === 'axis') { audioTransmit.start(url); } else { ErrorManager.dispatchError(812); } } public function stopAudioTransmit():void { audioTransmit.stop(); } public function allowFullscreen(state:Boolean):void { this.fullscreenAllowed = state; if (!state) this.stage.displayState = StageDisplayState.NORMAL; } private function onStageAdded(e:Event):void { Player.locomoteID = LoaderInfo(this.root.loaderInfo).parameters.locomoteID.toString(); ExternalInterface.call("LocomoteMap['" + Player.locomoteID + "'].__swfReady"); } private function onStartPlay(event:ClientEvent):void { this.currentState = "playing"; this.callAPI(EVENT_STREAM_STARTED); } private function onEnded(event:ClientEvent):void { this.currentState = "ended"; this.callAPI(EVENT_STREAM_ENDED, event.data); } private function onPaused(event:ClientEvent):void { this.currentState = "paused"; this.callAPI(EVENT_STREAM_PAUSED, event.data); } private function onStopped(event:ClientEvent):void { this.removeChild(this.client.getDisplayObject()); this.client.removeEventListener(ClientEvent.STOPPED, onStopped); this.client.removeEventListener(ClientEvent.START_PLAY, onStartPlay); this.client.removeEventListener(ClientEvent.PAUSED, onPaused); this.client.removeEventListener(ClientEvent.ENDED, onEnded); this.client.removeEventListener(ClientEvent.META, onMeta); this.client.removeEventListener(ClientEvent.FRAME, onFrame); this.client = null; this.callAPI(EVENT_STREAM_STOPPED, event.data); /* If a new `play` has been queued, fire it */ if (this.newPlaylistItem) { start(); } } private function onFrame(event:ClientEvent):void { this.callAPI(EVENT_FRAME_READY, { timestamp: event.data }); } private function callAPI(eventName:String, data:Object = null):void { var functionName:String = "LocomoteMap['" + Player.locomoteID + "'].__playerEvent"; if (data) { ExternalInterface.call(functionName, eventName, data); } else { ExternalInterface.call(functionName, eventName); } } } }
Fix error in stream status
Fix error in stream status
ActionScript
bsd-3-clause
gaetancollaud/locomote-video-player,AxisCommunications/locomote-video-player
ac79063bd9504534d8974db13879f16ea0d63ab7
HLSPlugin/src/com/kaltura/hls/HLSLoader.as
HLSPlugin/src/com/kaltura/hls/HLSLoader.as
package com.kaltura.hls { import com.kaltura.hls.m2ts.M2TSNetLoader; import com.kaltura.hls.manifest.HLSManifestParser; import com.kaltura.hls.manifest.HLSManifestPlaylist; import com.kaltura.hls.manifest.HLSManifestStream; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; import org.osmf.elements.VideoElement; import org.osmf.elements.proxyClasses.LoadFromDocumentLoadTrait; import org.osmf.events.MediaError; import org.osmf.events.MediaErrorEvent; import org.osmf.media.DefaultMediaFactory; import org.osmf.media.MediaElement; import org.osmf.media.MediaResourceBase; import org.osmf.media.MediaTypeUtil; import org.osmf.media.URLResource; import org.osmf.metadata.Metadata; import org.osmf.metadata.MetadataNamespaces; import org.osmf.net.DynamicStreamingItem; import org.osmf.net.StreamType; import org.osmf.net.StreamingItem; import org.osmf.net.StreamingItemType; import org.osmf.traits.LoadState; import org.osmf.traits.LoadTrait; import org.osmf.traits.LoaderBase; import org.osmf.utils.URL; public class HLSLoader extends LoaderBase { protected var loadTrait:LoadTrait; protected var manifestLoader:URLLoader; protected var parser:HLSManifestParser; protected var factory:DefaultMediaFactory = new DefaultMediaFactory(); private var supportedMimeTypes:Vector.<String> = new Vector.<String>(); public function HLSLoader() { super(); supportedMimeTypes.push( "application/x-mpegURL" ); supportedMimeTypes.push( "application/vnd.apple.mpegURL" ); supportedMimeTypes.push( "vnd.apple.mpegURL" ); supportedMimeTypes.push( "video/MP2T" ); } override protected function executeLoad(loadTrait:LoadTrait):void { this.loadTrait = loadTrait; updateLoadTrait(loadTrait, LoadState.LOADING); var url:String = URLResource(loadTrait.resource).url; manifestLoader = new URLLoader(new URLRequest(url)); manifestLoader.addEventListener(Event.COMPLETE, onComplete); manifestLoader.addEventListener(IOErrorEvent.IO_ERROR, onError); manifestLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); } private function onComplete(event:Event):void { manifestLoader.removeEventListener(Event.COMPLETE, onComplete); manifestLoader.removeEventListener(IOErrorEvent.IO_ERROR, onError); manifestLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); try { var resourceData:String = String((event.target as URLLoader).data); var url:String = URLResource(loadTrait.resource).url; // Start parsing the manifest. parser = new HLSManifestParser(); parser.addEventListener(Event.COMPLETE, onManifestComplete); parser.parse(resourceData, url); } catch (parseError:Error) { updateLoadTrait(loadTrait, LoadState.LOAD_ERROR); loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(parseError.errorID, parseError.message))); } } protected function onManifestComplete(event:Event):void { trace("Manifest is loaded."); var isDVR:Boolean = false; // Construct the streaming resource and set it as our resource. var stream:HLSStreamingResource = new HLSStreamingResource(URLResource(loadTrait.resource).url, "", StreamType.DVR); stream.manifest = parser; var item:DynamicStreamingItem; var items:Vector.<DynamicStreamingItem> = new Vector.<DynamicStreamingItem>(); for(var i:int=0; i<parser.streams.length; i++) { var curStream:HLSManifestStream = parser.streams[i]; //If there is more than one streaming quality available, check to see if filtering is required if (parser.streams.length > 1) { //Checks to see if there are min/max bitrate restrictions then throws out the outliers if(HLSManifestParser.MAX_BITRATE != -1 && curStream.bandwidth > HLSManifestParser.MAX_BITRATE || HLSManifestParser.MIN_BITRATE != -1 && curStream.bandwidth < HLSManifestParser.MIN_BITRATE) { continue; } } item = new DynamicStreamingItem(curStream.uri, curStream.bandwidth, curStream.width, curStream.height); curStream.dynamicStream = item; items.push(item); if ( !(curStream.manifest ? curStream.manifest.streamEnds : false) ) isDVR = true; // Create dynamic streaming items for the backup streams if (!curStream.backupStream) continue; var mainStream:HLSManifestStream = curStream; curStream = curStream.backupStream; while (curStream != mainStream) { curStream.dynamicStream = new DynamicStreamingItem(curStream.uri, curStream.bandwidth, curStream.width, curStream.height); curStream = curStream.backupStream; } } // Deal with single rate M3Us by stuffing a single stream in. if(items.length == 0) { item = new DynamicStreamingItem(URLResource(loadTrait.resource).url, 0, 0, 0); items.push(item); // Also set the DVR state if ( !stream.manifest.streamEnds ) isDVR = true; } var alternateAudioItems:Vector.<StreamingItem> = new <StreamingItem>[]; for ( var j:int = 0; j < parser.playLists.length; j++ ) { var playList:HLSManifestPlaylist = parser.playLists[ j ]; if ( !playList.manifest ) continue; var audioItem:StreamingItem = new StreamingItem( StreamingItemType.AUDIO, playList.name, 0, playList ); alternateAudioItems.push( audioItem ); } stream.streamItems = items; stream.alternativeAudioStreamItems = alternateAudioItems; var preferredIndex:int; //If there is only one stream quality (or less) sets default to first stream if (items.length <= 1) { preferredIndex = 0; } else if (HLSManifestParser.PREF_BITRATE != -1) { //If there is a preferred bitrate set by kaltura, tests all streams to find highest bitrate below the preferred var bitrateDifference:int = HLSManifestParser.PREF_BITRATE - items[0].bitrate; preferredIndex = 0; for(var k:int=1; k<items.length; k++) { if (HLSManifestParser.PREF_BITRATE - items[k].bitrate > 0 && HLSManifestParser.PREF_BITRATE - items[k].bitrate < bitrateDifference) { preferredIndex = k; } } } else { //Sets the preferred index to the middle (or higher of the 2 middle) bitrate streams preferredIndex = items.length / 2; } stream.initialIndex = preferredIndex; stream.addMetadataValue( HLSMetadataNamespaces.PLAYABLE_RESOURCE_METADATA, true ); var loadedElem:MediaElement = new VideoElement( stream, new M2TSNetLoader() ); LoadFromDocumentLoadTrait( loadTrait ).mediaElement = loadedElem; if ( parser.subtitlePlayLists.length > 0 ) { var subtitleTrait:SubtitleTrait = new SubtitleTrait(); subtitleTrait.playLists = parser.subtitlePlayLists; subtitleTrait.owningMediaElement = loadedElem; stream.subtitleTrait = subtitleTrait; } if ( isDVR ) { var dvrMetadata:Metadata = new Metadata(); stream.addMetadataValue(MetadataNamespaces.DVR_METADATA, dvrMetadata); } updateLoadTrait( loadTrait, LoadState.READY ); } private function onError(event:ErrorEvent):void { manifestLoader.removeEventListener(Event.COMPLETE, onComplete); manifestLoader.removeEventListener(IOErrorEvent.IO_ERROR, onError); manifestLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); updateLoadTrait(loadTrait, LoadState.LOAD_ERROR); loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(0, event.text))); } override public function canHandleResource(resource:MediaResourceBase):Boolean { var supported:int = MediaTypeUtil.checkMetadataMatchWithResource(resource, new Vector.<String>(), supportedMimeTypes); if ( supported == MediaTypeUtil.METADATA_MATCH_FOUND ) return true; if (!(resource is URLResource)) return false; var url:URL = new URL((resource as URLResource).url); if (url.extension != "m3u8" && url.extension != "m3u") return false; return true; } } }
package com.kaltura.hls { import com.kaltura.hls.m2ts.M2TSNetLoader; import com.kaltura.hls.manifest.HLSManifestParser; import com.kaltura.hls.manifest.HLSManifestPlaylist; import com.kaltura.hls.manifest.HLSManifestStream; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; import org.osmf.elements.VideoElement; import org.osmf.elements.proxyClasses.LoadFromDocumentLoadTrait; import org.osmf.events.MediaError; import org.osmf.events.MediaErrorEvent; import org.osmf.media.DefaultMediaFactory; import org.osmf.media.MediaElement; import org.osmf.media.MediaResourceBase; import org.osmf.media.MediaTypeUtil; import org.osmf.media.URLResource; import org.osmf.metadata.Metadata; import org.osmf.metadata.MetadataNamespaces; import org.osmf.net.DynamicStreamingItem; import org.osmf.net.StreamType; import org.osmf.net.StreamingItem; import org.osmf.net.StreamingItemType; import org.osmf.traits.LoadState; import org.osmf.traits.LoadTrait; import org.osmf.traits.LoaderBase; import org.osmf.utils.URL; public class HLSLoader extends LoaderBase { protected var loadTrait:LoadTrait; protected var manifestLoader:URLLoader; protected var parser:HLSManifestParser; protected var factory:DefaultMediaFactory = new DefaultMediaFactory(); private var supportedMimeTypes:Vector.<String> = new Vector.<String>(); public function HLSLoader() { super(); supportedMimeTypes.push( "application/x-mpegURL" ); supportedMimeTypes.push( "application/vnd.apple.mpegURL" ); supportedMimeTypes.push( "vnd.apple.mpegURL" ); supportedMimeTypes.push( "video/MP2T" ); } override protected function executeLoad(loadTrait:LoadTrait):void { this.loadTrait = loadTrait; updateLoadTrait(loadTrait, LoadState.LOADING); var url:String = URLResource(loadTrait.resource).url; manifestLoader = new URLLoader(new URLRequest(url)); manifestLoader.addEventListener(Event.COMPLETE, onComplete); manifestLoader.addEventListener(IOErrorEvent.IO_ERROR, onError); manifestLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); } private function onComplete(event:Event):void { manifestLoader.removeEventListener(Event.COMPLETE, onComplete); manifestLoader.removeEventListener(IOErrorEvent.IO_ERROR, onError); manifestLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); try { var resourceData:String = String((event.target as URLLoader).data); var url:String = URLResource(loadTrait.resource).url; // Start parsing the manifest. parser = new HLSManifestParser(); parser.addEventListener(Event.COMPLETE, onManifestComplete); parser.parse(resourceData, url); } catch (parseError:Error) { updateLoadTrait(loadTrait, LoadState.LOAD_ERROR); loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(parseError.errorID, parseError.message))); } } protected function onManifestComplete(event:Event):void { trace("Manifest is loaded."); var isDVR:Boolean = false; // Construct the streaming resource and set it as our resource. var stream:HLSStreamingResource = new HLSStreamingResource(URLResource(loadTrait.resource).url, "", StreamType.DVR); stream.manifest = parser; var item:DynamicStreamingItem; var items:Vector.<DynamicStreamingItem> = new Vector.<DynamicStreamingItem>(); for(var i:int=0; i<parser.streams.length; i++) { var curStream:HLSManifestStream = parser.streams[i]; //If there is more than one streaming quality available, check to see if filtering is required if (parser.streams.length > 1) { //Checks to see if there are min/max bitrate restrictions then throws out the outliers if(HLSManifestParser.MAX_BITRATE != -1 && curStream.bandwidth > HLSManifestParser.MAX_BITRATE || HLSManifestParser.MIN_BITRATE != -1 && curStream.bandwidth < HLSManifestParser.MIN_BITRATE) { continue; } } item = new DynamicStreamingItem(curStream.uri, curStream.bandwidth, curStream.width, curStream.height); curStream.dynamicStream = item; items.push(item); if ( !(curStream.manifest ? curStream.manifest.streamEnds : false) ) isDVR = true; // Create dynamic streaming items for the backup streams if (!curStream.backupStream) continue; var mainStream:HLSManifestStream = curStream; curStream = curStream.backupStream; while (curStream != mainStream) { curStream.dynamicStream = new DynamicStreamingItem(curStream.uri, curStream.bandwidth, curStream.width, curStream.height); curStream = curStream.backupStream; } } // Deal with single rate M3Us by stuffing a single stream in. if(items.length == 0) { item = new DynamicStreamingItem(URLResource(loadTrait.resource).url, 0, 0, 0); items.push(item); // Also set the DVR state if ( !stream.manifest.streamEnds ) isDVR = true; } var alternateAudioItems:Vector.<StreamingItem> = new <StreamingItem>[]; for ( var j:int = 0; j < parser.playLists.length; j++ ) { var playList:HLSManifestPlaylist = parser.playLists[ j ]; if ( !playList.manifest ) continue; var audioItem:StreamingItem = new StreamingItem( StreamingItemType.AUDIO, playList.name, 0, playList ); alternateAudioItems.push( audioItem ); } stream.streamItems = items; stream.alternativeAudioStreamItems = alternateAudioItems; var preferredIndex:int; //If there is only one stream quality (or less) sets default to first stream if (items.length <= 1) { preferredIndex = 0; } else if (HLSManifestParser.PREF_BITRATE != -1) { //If there is a preferred bitrate set by kaltura, tests all streams to find highest bitrate below the preferred preferredIndex = 0; var preferredDistance:Number = Number.MAX_VALUE; for(var k:int=0; k<items.length; k++) { var curItem:DynamicStreamingItem = items[k]; var curDist:Number = items[k].bitrate - HLSManifestParser.PREF_BITRATE; /// Reject too low or not improved items. if(curDist < 0 || curDist >= preferredDistance) continue; preferredIndex = k; preferredDistance = curDist; } } else { //Sets the preferred index to the middle (or higher of the 2 middle) bitrate streams preferredIndex = items.length / 2; } stream.initialIndex = preferredIndex; stream.addMetadataValue( HLSMetadataNamespaces.PLAYABLE_RESOURCE_METADATA, true ); var loadedElem:MediaElement = new VideoElement( stream, new M2TSNetLoader() ); LoadFromDocumentLoadTrait( loadTrait ).mediaElement = loadedElem; if ( parser.subtitlePlayLists.length > 0 ) { var subtitleTrait:SubtitleTrait = new SubtitleTrait(); subtitleTrait.playLists = parser.subtitlePlayLists; subtitleTrait.owningMediaElement = loadedElem; stream.subtitleTrait = subtitleTrait; } if ( isDVR ) { var dvrMetadata:Metadata = new Metadata(); stream.addMetadataValue(MetadataNamespaces.DVR_METADATA, dvrMetadata); } updateLoadTrait( loadTrait, LoadState.READY ); } private function onError(event:ErrorEvent):void { manifestLoader.removeEventListener(Event.COMPLETE, onComplete); manifestLoader.removeEventListener(IOErrorEvent.IO_ERROR, onError); manifestLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); updateLoadTrait(loadTrait, LoadState.LOAD_ERROR); loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(0, event.text))); } override public function canHandleResource(resource:MediaResourceBase):Boolean { var supported:int = MediaTypeUtil.checkMetadataMatchWithResource(resource, new Vector.<String>(), supportedMimeTypes); if ( supported == MediaTypeUtil.METADATA_MATCH_FOUND ) return true; if (!(resource is URLResource)) return false; var url:URL = new URL((resource as URLResource).url); if (url.extension != "m3u8" && url.extension != "m3u") return false; return true; } } }
Update preferred bitrate selection logic to not assume ordered bitrates.
Update preferred bitrate selection logic to not assume ordered bitrates.
ActionScript
agpl-3.0
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
291847fbc7dd94389edf6c58e8c32b8262e3792b
as3/com/netease/protobuf/stringToByteArray.as
as3/com/netease/protobuf/stringToByteArray.as
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved. // // [email protected] // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.utils.ByteArray public function stringToByteArray(s:String):ByteArray { const ba:ByteArray = new ByteArray ba.writeMultiByte(s, "iso-8859-1") return ba } }
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved. // // [email protected] // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.utils.ByteArray public function stringToByteArray(s:String):ByteArray { const ba:ByteArray = new ByteArray for (var i:uint = 0; i < s.length; ++i) { ba.writeByte(s.charCodeAt(i)) } return ba } }
修复字符串中存在 \0 时转换到 ByteArray 会被截断的 bug
修复字符串中存在 \0 时转换到 ByteArray 会被截断的 bug
ActionScript
bsd-2-clause
tconkling/protoc-gen-as3
df8428e710f37a8d088b14dee8544cd96c0c73e6
frameworks/projects/mobiletheme/src/spark/skins/mobile/ButtonSkin.as
frameworks/projects/mobiletheme/src/spark/skins/mobile/ButtonSkin.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.skins.mobile { import flash.display.DisplayObject; import flash.display.GradientType; import mx.core.DPIClassification; import mx.core.mx_internal; import mx.events.FlexEvent; import mx.utils.ColorUtil; import spark.components.supportClasses.StyleableTextField; import spark.skins.mobile.supportClasses.ButtonSkinBase; import spark.skins.mobile120.assets.Button_down; import spark.skins.mobile120.assets.Button_up; import spark.skins.mobile160.assets.Button_down; import spark.skins.mobile160.assets.Button_up; import spark.skins.mobile240.assets.Button_down; import spark.skins.mobile240.assets.Button_up; import spark.skins.mobile320.assets.Button_down; import spark.skins.mobile320.assets.Button_up; import spark.skins.mobile480.assets.Button_down; import spark.skins.mobile480.assets.Button_up; import spark.skins.mobile640.assets.Button_down; import spark.skins.mobile640.assets.Button_up; use namespace mx_internal; /** * ActionScript-based skin for Button controls in mobile applications. The skin supports * iconClass and labelPlacement. It uses FXG classes to * implement the vector drawing. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class ButtonSkin extends ButtonSkinBase { //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * An array of color distribution ratios. * This is used in the chrome color fill. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal static const CHROME_COLOR_RATIOS:Array = [0, 127.5]; /** * An array of alpha values for the corresponding colors in the colors array. * This is used in the chrome color fill. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal static const CHROME_COLOR_ALPHAS:Array = [1, 1]; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function ButtonSkin() { super(); switch (applicationDPI) { case DPIClassification.DPI_640: { upBorderSkin = spark.skins.mobile640.assets.Button_up; downBorderSkin = spark.skins.mobile640.assets.Button_down; layoutGap = 20; layoutCornerEllipseSize = 40; layoutPaddingLeft = 40; layoutPaddingRight = 40; layoutPaddingTop = 40; layoutPaddingBottom = 40; layoutBorderSize = 2; measuredDefaultWidth = 128; measuredDefaultHeight = 172; break; } case DPIClassification.DPI_480: { // Note provisional may need changes upBorderSkin = spark.skins.mobile480.assets.Button_up; downBorderSkin = spark.skins.mobile480.assets.Button_down; layoutGap = 14; layoutCornerEllipseSize = 30; layoutPaddingLeft = 30; layoutPaddingRight = 30; layoutPaddingTop = 30; layoutPaddingBottom = 30; layoutBorderSize = 2; measuredDefaultWidth = 96; measuredDefaultHeight = 130; break; } case DPIClassification.DPI_320: { upBorderSkin = spark.skins.mobile320.assets.Button_up; downBorderSkin = spark.skins.mobile320.assets.Button_down; layoutGap = 10; layoutCornerEllipseSize = 20; layoutPaddingLeft = 20; layoutPaddingRight = 20; layoutPaddingTop = 20; layoutPaddingBottom = 20; layoutBorderSize = 2; measuredDefaultWidth = 64; measuredDefaultHeight = 86; break; } case DPIClassification.DPI_240: { upBorderSkin = spark.skins.mobile240.assets.Button_up; downBorderSkin = spark.skins.mobile240.assets.Button_down; layoutGap = 7; layoutCornerEllipseSize = 15; layoutPaddingLeft = 15; layoutPaddingRight = 15; layoutPaddingTop = 15; layoutPaddingBottom = 15; layoutBorderSize = 1; measuredDefaultWidth = 48; measuredDefaultHeight = 65; break; } case DPIClassification.DPI_120: { upBorderSkin = spark.skins.mobile120.assets.Button_up; downBorderSkin = spark.skins.mobile120.assets.Button_down; layoutGap = 4; layoutCornerEllipseSize = 8; layoutPaddingLeft = 8; layoutPaddingRight = 8; layoutPaddingTop = 8; layoutPaddingBottom = 8; layoutBorderSize = 1; measuredDefaultWidth = 24; measuredDefaultHeight = 33; break; } default: { // default DPI_160 upBorderSkin = spark.skins.mobile160.assets.Button_up; downBorderSkin = spark.skins.mobile160.assets.Button_down; layoutGap = 5; layoutCornerEllipseSize = 10; layoutPaddingLeft = 10; layoutPaddingRight = 10; layoutPaddingTop = 10; layoutPaddingBottom = 10; layoutBorderSize = 1; measuredDefaultWidth = 32; measuredDefaultHeight = 43; break; } } } //-------------------------------------------------------------------------- // // Layout variables // //-------------------------------------------------------------------------- /** * Defines the corner radius. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected var layoutCornerEllipseSize:uint; //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var _border:DisplayObject; private var changeFXGSkin:Boolean = false; private var borderClass:Class; mx_internal var fillColorStyleName:String = "chromeColor"; /** * Defines the shadow for the Button control's label. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public var labelDisplayShadow:StyleableTextField; /** * Read-only button border graphic. Use getBorderClassForCurrentState() * to specify a graphic per-state. * * @see #getBorderClassForCurrentState() */ protected function get border():DisplayObject { return _border; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** * Class to use for the border in the up state. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 * * @default Button_up */ protected var upBorderSkin:Class; /** * Class to use for the border in the down state. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 * * @default Button_down */ protected var downBorderSkin:Class; //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ override protected function createChildren():void { super.createChildren(); if (!labelDisplayShadow && labelDisplay) { labelDisplayShadow = StyleableTextField(createInFontContext(StyleableTextField)); labelDisplayShadow.styleName = this; labelDisplayShadow.colorName = "textShadowColor"; labelDisplayShadow.useTightTextBounds = false; // add shadow before display addChildAt(labelDisplayShadow, getChildIndex(labelDisplay)); } setStyle("textAlign", "center"); } /** * @private */ override protected function commitCurrentState():void { super.commitCurrentState(); borderClass = getBorderClassForCurrentState(); if (!(_border is borderClass)) changeFXGSkin = true; // update borderClass and background invalidateDisplayList(); } /** * @private */ override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void { super.layoutContents(unscaledWidth, unscaledHeight); // size the FXG background if (changeFXGSkin) { changeFXGSkin = false; if (_border) { removeChild(_border); _border = null; } if (borderClass) { _border = new borderClass(); addChildAt(_border, 0); } } layoutBorder(unscaledWidth, unscaledHeight); // update label shadow labelDisplayShadow.alpha = getStyle("textShadowAlpha"); labelDisplayShadow.commitStyles(); // don't use tightText positioning on shadow setElementPosition(labelDisplayShadow, labelDisplay.x, labelDisplay.y + 1); setElementSize(labelDisplayShadow, labelDisplay.width, labelDisplay.height); // if labelDisplay is truncated, then push it down here as well. // otherwise, it would have gotten pushed in the labelDisplay_valueCommitHandler() if (labelDisplay.isTruncated) labelDisplayShadow.text = labelDisplay.text; } /** * Position the background of the skin. Override this function to re-position the background. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function layoutBorder(unscaledWidth:Number, unscaledHeight:Number):void { setElementSize(border, unscaledWidth, unscaledHeight); setElementPosition(border, 0, 0); } override protected function drawBackground(unscaledWidth:Number, unscaledHeight:Number):void { super.drawBackground(unscaledWidth, unscaledHeight); var chromeColor:uint = getStyle(fillColorStyleName); // In the down state, the fill shadow is defined in the FXG asset if (currentState == "down") { graphics.beginFill(chromeColor); } else { var colors:Array = []; colorMatrix.createGradientBox(unscaledWidth, unscaledHeight, Math.PI / 2, 0, 0); colors[0] = ColorUtil.adjustBrightness2(chromeColor, 70); colors[1] = chromeColor; graphics.beginGradientFill(GradientType.LINEAR, colors, CHROME_COLOR_ALPHAS, CHROME_COLOR_RATIOS, colorMatrix); } // inset chrome color by BORDER_SIZE // bottom line is a shadow graphics.drawRoundRect(layoutBorderSize, layoutBorderSize, unscaledWidth - (layoutBorderSize * 2), unscaledHeight - (layoutBorderSize * 2), layoutCornerEllipseSize, layoutCornerEllipseSize); graphics.endFill(); } /** * Returns the borderClass to use based on the currentState. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function getBorderClassForCurrentState():Class { if (currentState == "down") return downBorderSkin; else return upBorderSkin; } //-------------------------------------------------------------------------- // // Event Handlers // //-------------------------------------------------------------------------- /** * @private */ override protected function labelDisplay_valueCommitHandler(event:FlexEvent):void { super.labelDisplay_valueCommitHandler(event); labelDisplayShadow.text = labelDisplay.text; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.skins.mobile { import flash.display.DisplayObject; import flash.display.GradientType; import mx.core.DPIClassification; import mx.core.mx_internal; import mx.events.FlexEvent; import mx.utils.ColorUtil; import spark.components.supportClasses.StyleableTextField; import spark.skins.mobile.supportClasses.ButtonSkinBase; import spark.skins.mobile120.assets.Button_down; import spark.skins.mobile120.assets.Button_up; import spark.skins.mobile160.assets.Button_down; import spark.skins.mobile160.assets.Button_up; import spark.skins.mobile240.assets.Button_down; import spark.skins.mobile240.assets.Button_up; import spark.skins.mobile320.assets.Button_down; import spark.skins.mobile320.assets.Button_up; import spark.skins.mobile480.assets.Button_down; import spark.skins.mobile480.assets.Button_up; import spark.skins.mobile640.assets.Button_down; import spark.skins.mobile640.assets.Button_up; use namespace mx_internal; /** * ActionScript-based skin for Button controls in mobile applications. The skin supports * iconClass and labelPlacement. It uses FXG classes to * implement the vector drawing. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class ButtonSkin extends ButtonSkinBase { //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * An array of color distribution ratios. * This is used in the chrome color fill. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal static const CHROME_COLOR_RATIOS:Array = [0, 127.5]; /** * An array of alpha values for the corresponding colors in the colors array. * This is used in the chrome color fill. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal static const CHROME_COLOR_ALPHAS:Array = [1, 1]; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function ButtonSkin() { super(); switch (applicationDPI) { case DPIClassification.DPI_640: { upBorderSkin = spark.skins.mobile640.assets.Button_up; downBorderSkin = spark.skins.mobile640.assets.Button_down; layoutGap = 20; layoutCornerEllipseSize = 28; layoutPaddingLeft = 40; layoutPaddingRight = 40; layoutPaddingTop = 40; layoutPaddingBottom = 40; layoutBorderSize = 2; measuredDefaultWidth = 128; measuredDefaultHeight = 172; break; } case DPIClassification.DPI_480: { // Note provisional may need changes upBorderSkin = spark.skins.mobile480.assets.Button_up; downBorderSkin = spark.skins.mobile480.assets.Button_down; layoutGap = 14; layoutCornerEllipseSize = 20; layoutPaddingLeft = 30; layoutPaddingRight = 30; layoutPaddingTop = 30; layoutPaddingBottom = 30; layoutBorderSize = 2; measuredDefaultWidth = 96; measuredDefaultHeight = 130; break; } case DPIClassification.DPI_320: { upBorderSkin = spark.skins.mobile320.assets.Button_up; downBorderSkin = spark.skins.mobile320.assets.Button_down; layoutGap = 10; layoutCornerEllipseSize = 10; layoutPaddingLeft = 20; layoutPaddingRight = 20; layoutPaddingTop = 20; layoutPaddingBottom = 20; layoutBorderSize = 2; measuredDefaultWidth = 64; measuredDefaultHeight = 86; break; } case DPIClassification.DPI_240: { upBorderSkin = spark.skins.mobile240.assets.Button_up; downBorderSkin = spark.skins.mobile240.assets.Button_down; layoutGap = 7; layoutCornerEllipseSize = 8; layoutPaddingLeft = 15; layoutPaddingRight = 15; layoutPaddingTop = 15; layoutPaddingBottom = 15; layoutBorderSize = 1; measuredDefaultWidth = 48; measuredDefaultHeight = 65; break; } case DPIClassification.DPI_120: { upBorderSkin = spark.skins.mobile120.assets.Button_up; downBorderSkin = spark.skins.mobile120.assets.Button_down; layoutGap = 4; layoutCornerEllipseSize = 8; layoutPaddingLeft = 8; layoutPaddingRight = 8; layoutPaddingTop = 8; layoutPaddingBottom = 8; layoutBorderSize = 1; measuredDefaultWidth = 24; measuredDefaultHeight = 33; break; } default: { // default DPI_160 upBorderSkin = spark.skins.mobile160.assets.Button_up; downBorderSkin = spark.skins.mobile160.assets.Button_down; layoutGap = 5; layoutCornerEllipseSize = 10; layoutPaddingLeft = 10; layoutPaddingRight = 10; layoutPaddingTop = 10; layoutPaddingBottom = 10; layoutBorderSize = 1; measuredDefaultWidth = 32; measuredDefaultHeight = 43; break; } } } //-------------------------------------------------------------------------- // // Layout variables // //-------------------------------------------------------------------------- /** * Defines the corner radius. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected var layoutCornerEllipseSize:uint; //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var _border:DisplayObject; private var changeFXGSkin:Boolean = false; private var borderClass:Class; mx_internal var fillColorStyleName:String = "chromeColor"; /** * Defines the shadow for the Button control's label. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public var labelDisplayShadow:StyleableTextField; /** * Read-only button border graphic. Use getBorderClassForCurrentState() * to specify a graphic per-state. * * @see #getBorderClassForCurrentState() */ protected function get border():DisplayObject { return _border; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** * Class to use for the border in the up state. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 * * @default Button_up */ protected var upBorderSkin:Class; /** * Class to use for the border in the down state. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 * * @default Button_down */ protected var downBorderSkin:Class; //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ override protected function createChildren():void { super.createChildren(); if (!labelDisplayShadow && labelDisplay) { labelDisplayShadow = StyleableTextField(createInFontContext(StyleableTextField)); labelDisplayShadow.styleName = this; labelDisplayShadow.colorName = "textShadowColor"; labelDisplayShadow.useTightTextBounds = false; // add shadow before display addChildAt(labelDisplayShadow, getChildIndex(labelDisplay)); } setStyle("textAlign", "center"); } /** * @private */ override protected function commitCurrentState():void { super.commitCurrentState(); borderClass = getBorderClassForCurrentState(); if (!(_border is borderClass)) changeFXGSkin = true; // update borderClass and background invalidateDisplayList(); } /** * @private */ override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void { super.layoutContents(unscaledWidth, unscaledHeight); // size the FXG background if (changeFXGSkin) { changeFXGSkin = false; if (_border) { removeChild(_border); _border = null; } if (borderClass) { _border = new borderClass(); addChildAt(_border, 0); } } layoutBorder(unscaledWidth, unscaledHeight); // update label shadow labelDisplayShadow.alpha = getStyle("textShadowAlpha"); labelDisplayShadow.commitStyles(); // don't use tightText positioning on shadow setElementPosition(labelDisplayShadow, labelDisplay.x, labelDisplay.y + 1); setElementSize(labelDisplayShadow, labelDisplay.width, labelDisplay.height); // if labelDisplay is truncated, then push it down here as well. // otherwise, it would have gotten pushed in the labelDisplay_valueCommitHandler() if (labelDisplay.isTruncated) labelDisplayShadow.text = labelDisplay.text; } /** * Position the background of the skin. Override this function to re-position the background. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function layoutBorder(unscaledWidth:Number, unscaledHeight:Number):void { setElementSize(border, unscaledWidth, unscaledHeight); setElementPosition(border, 0, 0); } override protected function drawBackground(unscaledWidth:Number, unscaledHeight:Number):void { super.drawBackground(unscaledWidth, unscaledHeight); var chromeColor:uint = getStyle(fillColorStyleName); // In the down state, the fill shadow is defined in the FXG asset if (currentState == "down") { graphics.beginFill(chromeColor); } else { var colors:Array = []; colorMatrix.createGradientBox(unscaledWidth, unscaledHeight, Math.PI / 2, 0, 0); colors[0] = ColorUtil.adjustBrightness2(chromeColor, 70); colors[1] = chromeColor; graphics.beginGradientFill(GradientType.LINEAR, colors, CHROME_COLOR_ALPHAS, CHROME_COLOR_RATIOS, colorMatrix); } // inset chrome color by BORDER_SIZE // bottom line is a shadow graphics.drawRoundRect(layoutBorderSize, layoutBorderSize, unscaledWidth - (layoutBorderSize * 2), unscaledHeight - (layoutBorderSize * 2), layoutCornerEllipseSize, layoutCornerEllipseSize); graphics.endFill(); } /** * Returns the borderClass to use based on the currentState. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function getBorderClassForCurrentState():Class { if (currentState == "down") return downBorderSkin; else return upBorderSkin; } //-------------------------------------------------------------------------- // // Event Handlers // //-------------------------------------------------------------------------- /** * @private */ override protected function labelDisplay_valueCommitHandler(event:FlexEvent):void { super.labelDisplay_valueCommitHandler(event); labelDisplayShadow.text = labelDisplay.text; } } }
Fix for https://issues.apache.org/jira/browse/FLEX-34117 Changed the layoutCornerEllipseSize in ButtonSkin.as for various DPIs
Fix for https://issues.apache.org/jira/browse/FLEX-34117 Changed the layoutCornerEllipseSize in ButtonSkin.as for various DPIs
ActionScript
apache-2.0
danteinforno/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,apache/flex-sdk
75b187588f8f0a3e651b4e0ff06c96656b291c41
Bin/Data/Scripts/Editor/EditorMaterial.as
Bin/Data/Scripts/Editor/EditorMaterial.as
// Urho3D material editor Window@ materialWindow; Material@ editMaterial; XMLFile@ oldMaterialState; void CreateMaterialEditor() { if (materialWindow !is null) return; materialWindow = ui.LoadLayout(cache.GetResource("XMLFile", "UI/EditorMaterialWindow.xml")); ui.root.AddChild(materialWindow); materialWindow.opacity = uiMaxOpacity; RefreshMaterialEditor(); int height = Min(ui.root.height - 60, 500); materialWindow.SetSize(300, height); CenterDialog(materialWindow); HideMaterialEditor(); SubscribeToEvent(materialWindow.GetChild("NewButton", true), "Released", "NewMaterial"); SubscribeToEvent(materialWindow.GetChild("RevertButton", true), "Released", "RevertMaterial"); SubscribeToEvent(materialWindow.GetChild("SaveButton", true), "Released", "SaveMaterial"); SubscribeToEvent(materialWindow.GetChild("SaveAsButton", true), "Released", "SaveMaterialAs"); SubscribeToEvent(materialWindow.GetChild("CloseButton", true), "Released", "HideMaterialEditor"); SubscribeToEvent(materialWindow.GetChild("NewParameterDropDown", true), "ItemSelected", "CreateShaderParameter"); SubscribeToEvent(materialWindow.GetChild("DeleteParameterButton", true), "Released", "DeleteShaderParameter"); } bool ShowMaterialEditor() { materialWindow.visible = true; materialWindow.BringToFront(); return true; } void HideMaterialEditor() { materialWindow.visible = false; } void EditMaterial(Material@ mat) { editMaterial = mat; RefreshMaterialEditor(); ShowMaterialEditor(); } void RefreshMaterialEditor() { RefreshMaterialName(); RefreshMaterialTechniques(); RefreshMaterialTextures(); RefreshMaterialShaderParameters(); } void RefreshMaterialName() { UIElement@ container = materialWindow.GetChild("NameContainer"); container.RemoveAllChildren(); LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, 0, 0); if (editMaterial !is null) nameEdit.text = editMaterial.name; SubscribeToEvent(nameEdit, "TextFinished", "EditMaterialName"); Button@ pickButton = CreateResourcePickerButton(container, null, 0, 0, "Pick"); SubscribeToEvent(pickButton, "Released", "PickEditMaterial"); } void RefreshMaterialTechniques() { ListView@ list = materialWindow.GetChild("TechniqueList"); list.RemoveAllItems(); } void RefreshMaterialTextures(bool fullUpdate = true) { if (fullUpdate) { ListView@ list = materialWindow.GetChild("TextureList"); list.RemoveAllItems(); for (uint i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i) { UIElement@ parent = CreateAttributeEditorParentWithSeparatedLabel(list, GetTextureUnitName(TextureUnit(i)), i, 0, false); UIElement@ container = UIElement(); container.SetLayout(LM_HORIZONTAL, 4, IntRect(10, 0, 4, 0)); container.SetFixedHeight(ATTR_HEIGHT); parent.AddChild(container); LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, i, 0); nameEdit.name = "TextureNameEdit" + String(i); Button@ pickButton = CreateResourcePickerButton(container, null, i, 0, "Pick"); SubscribeToEvent(pickButton, "Released", "PickMaterialTexture"); Button@ openButton = CreateResourcePickerButton(container, null, i, 0, "Open"); SubscribeToEvent(openButton, "Released", "OpenResource"); if (editMaterial !is null) { Texture@ texture = editMaterial.textures[i]; if (texture !is null) nameEdit.text = texture.name; } SubscribeToEvent(nameEdit, "TextFinished", "EditMaterialTexture"); } } else { for (uint i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i) { LineEdit@ nameEdit = materialWindow.GetChild("TextureNameEdit" + String(i), true); if (nameEdit is null) continue; String textureName; if (editMaterial !is null) { Texture@ texture = editMaterial.textures[i]; if (texture !is null) textureName = texture.name; } nameEdit.text = textureName; } } } void RefreshMaterialShaderParameters() { ListView@ list = materialWindow.GetChild("ShaderParameterList"); list.RemoveAllItems(); if (editMaterial is null) return; Array<String>@ parameterNames = editMaterial.shaderParameterNames; for (uint i = 0; i < parameterNames.length; ++i) { VariantType type = editMaterial.shaderParameters[parameterNames[i]].type; Variant value = editMaterial.shaderParameters[parameterNames[i]]; UIElement@ parent = CreateAttributeEditorParent(list, parameterNames[i], 0, 0); uint numCoords = type - VAR_FLOAT + 1; Array<String> coordValues = value.ToString().Split(' '); for (uint j = 0; j < numCoords; ++j) { LineEdit@ attrEdit = CreateAttributeLineEdit(parent, null, 0, 0); attrEdit.vars["Coordinate"] = j; attrEdit.vars["Name"] = parameterNames[i]; attrEdit.text = coordValues[j]; SubscribeToEvent(attrEdit, "TextChanged", "EditShaderParameter"); SubscribeToEvent(attrEdit, "TextFinished", "EditShaderParameter"); } } } void EditMaterialName(StringHash eventType, VariantMap& eventData) { LineEdit@ nameEdit = eventData["Element"].GetUIElement(); String newMaterialName = nameEdit.text.Trimmed(); if (!newMaterialName.empty) { Material@ newMaterial = cache.GetResource("Material", newMaterialName); if (newMaterial !is null) EditMaterial(newMaterial); } } void PickEditMaterial() { @resourcePicker = GetResourcePicker(ShortStringHash("Material")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector("Pick " + resourcePicker.typeName, "OK", "Cancel", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "PickEditMaterialDone"); } void PickEditMaterialDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); if (!eventData["OK"].GetBool()) { @resourcePicker = null; return; } String resourceName = eventData["FileName"].GetString(); Resource@ res = GetPickedResource(resourceName); if (res !is null) EditMaterial(cast<Material>(res)); @resourcePicker = null; } void NewMaterial() { EditMaterial(Material()); } void RevertMaterial() { if (editMaterial is null) return; cache.ReloadResource(editMaterial); RefreshMaterialEditor(); } void SaveMaterial() { if (editMaterial is null || editMaterial.name.empty) return; String fullName = cache.GetResourceFileName(editMaterial.name); if (fullName.empty) return; File saveFile(fullName, FILE_WRITE); editMaterial.Save(saveFile); } void SaveMaterialAs() { if (editMaterial is null) return; @resourcePicker = GetResourcePicker(ShortStringHash("Material")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector("Save material as", "Save", "Cancel", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "SaveMaterialAsDone"); } void SaveMaterialAsDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); @resourcePicker = null; if (editMaterial is null) return; if (!eventData["OK"].GetBool()) { @resourcePicker = null; return; } String fullName = eventData["FileName"].GetString(); File saveFile(fullName, FILE_WRITE); if (editMaterial.Save(saveFile)) { saveFile.Close(); // Load the new resource to update the name in the editor Material@ newMat = cache.GetResource("Material", GetResourceNameFromFullName(fullName)); if (newMat !is null) EditMaterial(newMat); } } void EditShaderParameter(StringHash eventType, VariantMap& eventData) { if (editMaterial is null) return; LineEdit@ attrEdit = eventData["Element"].GetUIElement(); uint coordinate = attrEdit.vars["Coordinate"].GetUInt(); String name = attrEdit.vars["Name"].GetString(); Variant oldValue = editMaterial.shaderParameters[name]; Array<String> coordValues = oldValue.ToString().Split(' '); coordValues[coordinate] = String(attrEdit.text.ToFloat()); String valueString; for (uint i = 0; i < coordValues.length; ++i) { valueString += coordValues[i]; valueString += " "; } Variant newValue; newValue.FromString(oldValue.type, valueString); BeginMaterialEdit(); editMaterial.shaderParameters[name] = newValue; EndMaterialEdit(); } void CreateShaderParameter(StringHash eventType, VariantMap& eventData) { if (editMaterial is null) return; LineEdit@ nameEdit = materialWindow.GetChild("ParameterNameEdit", true); String newName = nameEdit.text.Trimmed(); if (newName.empty) return; DropDownList@ dropDown = eventData["Element"].GetUIElement(); Variant newValue; switch (dropDown.selection) { case 0: newValue = float(0); break; case 1: newValue = Vector2(0, 0); break; case 2: newValue = Vector3(0, 0, 0); break; case 3: newValue = Vector4(0, 0, 0, 0); break; } BeginMaterialEdit(); editMaterial.shaderParameters[newName] = newValue; EndMaterialEdit(); RefreshMaterialShaderParameters(); } void DeleteShaderParameter() { if (editMaterial is null) return; LineEdit@ nameEdit = materialWindow.GetChild("ParameterNameEdit", true); String name = nameEdit.text.Trimmed(); if (name.empty) return; BeginMaterialEdit(); editMaterial.RemoveShaderParameter(name); EndMaterialEdit(); RefreshMaterialShaderParameters(); } void PickMaterialTexture(StringHash eventType, VariantMap& eventData) { if (editMaterial is null) return; UIElement@ button = eventData["Element"].GetUIElement(); resourcePickIndex = button.vars["Index"].GetUInt(); @resourcePicker = GetResourcePicker(ShortStringHash("Texture2D")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector("Pick " + resourcePicker.typeName, "OK", "Cancel", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "PickMaterialTextureDone"); } void PickMaterialTextureDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); if (!eventData["OK"].GetBool()) { @resourcePicker = null; return; } String resourceName = eventData["FileName"].GetString(); Resource@ res = GetPickedResource(resourceName); if (res !is null && editMaterial !is null) { BeginMaterialEdit(); editMaterial.textures[resourcePickIndex] = res; EndMaterialEdit(); RefreshMaterialTextures(false); } @resourcePicker = null; } void EditMaterialTexture(StringHash eventType, VariantMap& eventData) { if (editMaterial is null) return; LineEdit@ attrEdit = eventData["Element"].GetUIElement(); String textureName = attrEdit.text.Trimmed(); uint index = attrEdit.vars["Index"].GetUInt(); BeginMaterialEdit(); if (!textureName.empty) { Texture@ texture = cache.GetResource(GetExtension(textureName) == ".xml" ? "TextureCube" : "Texture2D", textureName); editMaterial.textures[index] = texture; } else editMaterial.textures[index] =null; EndMaterialEdit(); } void BeginMaterialEdit() { if (editMaterial is null) return; oldMaterialState = XMLFile(); XMLElement materialElem = oldMaterialState.CreateRoot("material"); editMaterial.Save(materialElem); } void EndMaterialEdit() { if (editMaterial is null) return; EditMaterialAction@ action = EditMaterialAction(); action.Define(editMaterial, oldMaterialState); SaveEditAction(action); }
// Urho3D material editor Window@ materialWindow; Material@ editMaterial; XMLFile@ oldMaterialState; void CreateMaterialEditor() { if (materialWindow !is null) return; materialWindow = ui.LoadLayout(cache.GetResource("XMLFile", "UI/EditorMaterialWindow.xml")); ui.root.AddChild(materialWindow); materialWindow.opacity = uiMaxOpacity; RefreshMaterialEditor(); int height = Min(ui.root.height - 60, 500); materialWindow.SetSize(300, height); CenterDialog(materialWindow); HideMaterialEditor(); SubscribeToEvent(materialWindow.GetChild("NewButton", true), "Released", "NewMaterial"); SubscribeToEvent(materialWindow.GetChild("RevertButton", true), "Released", "RevertMaterial"); SubscribeToEvent(materialWindow.GetChild("SaveButton", true), "Released", "SaveMaterial"); SubscribeToEvent(materialWindow.GetChild("SaveAsButton", true), "Released", "SaveMaterialAs"); SubscribeToEvent(materialWindow.GetChild("CloseButton", true), "Released", "HideMaterialEditor"); SubscribeToEvent(materialWindow.GetChild("NewParameterDropDown", true), "ItemSelected", "CreateShaderParameter"); SubscribeToEvent(materialWindow.GetChild("DeleteParameterButton", true), "Released", "DeleteShaderParameter"); } bool ShowMaterialEditor() { materialWindow.visible = true; materialWindow.BringToFront(); return true; } void HideMaterialEditor() { materialWindow.visible = false; } void EditMaterial(Material@ mat) { editMaterial = mat; RefreshMaterialEditor(); ShowMaterialEditor(); } void RefreshMaterialEditor() { RefreshMaterialName(); RefreshMaterialTechniques(); RefreshMaterialTextures(); RefreshMaterialShaderParameters(); } void RefreshMaterialName() { UIElement@ container = materialWindow.GetChild("NameContainer"); container.RemoveAllChildren(); LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, 0, 0); if (editMaterial !is null) nameEdit.text = editMaterial.name; SubscribeToEvent(nameEdit, "TextFinished", "EditMaterialName"); Button@ pickButton = CreateResourcePickerButton(container, null, 0, 0, "Pick"); SubscribeToEvent(pickButton, "Released", "PickEditMaterial"); } void RefreshMaterialTechniques() { ListView@ list = materialWindow.GetChild("TechniqueList"); list.RemoveAllItems(); } void RefreshMaterialTextures(bool fullUpdate = true) { if (fullUpdate) { ListView@ list = materialWindow.GetChild("TextureList"); list.RemoveAllItems(); for (uint i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i) { UIElement@ parent = CreateAttributeEditorParentWithSeparatedLabel(list, GetTextureUnitName(TextureUnit(i)), i, 0, false); UIElement@ container = UIElement(); container.SetLayout(LM_HORIZONTAL, 4, IntRect(10, 0, 4, 0)); container.SetFixedHeight(ATTR_HEIGHT); parent.AddChild(container); LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, i, 0); nameEdit.name = "TextureNameEdit" + String(i); Button@ pickButton = CreateResourcePickerButton(container, null, i, 0, "Pick"); SubscribeToEvent(pickButton, "Released", "PickMaterialTexture"); Button@ openButton = CreateResourcePickerButton(container, null, i, 0, "Open"); SubscribeToEvent(openButton, "Released", "OpenResource"); if (editMaterial !is null) { Texture@ texture = editMaterial.textures[i]; if (texture !is null) nameEdit.text = texture.name; } SubscribeToEvent(nameEdit, "TextFinished", "EditMaterialTexture"); } } else { for (uint i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i) { LineEdit@ nameEdit = materialWindow.GetChild("TextureNameEdit" + String(i), true); if (nameEdit is null) continue; String textureName; if (editMaterial !is null) { Texture@ texture = editMaterial.textures[i]; if (texture !is null) textureName = texture.name; } nameEdit.text = textureName; } } } void RefreshMaterialShaderParameters() { ListView@ list = materialWindow.GetChild("ShaderParameterList"); list.RemoveAllItems(); if (editMaterial is null) return; Array<String>@ parameterNames = editMaterial.shaderParameterNames; for (uint i = 0; i < parameterNames.length; ++i) { VariantType type = editMaterial.shaderParameters[parameterNames[i]].type; Variant value = editMaterial.shaderParameters[parameterNames[i]]; UIElement@ parent = CreateAttributeEditorParent(list, parameterNames[i], 0, 0); uint numCoords = type - VAR_FLOAT + 1; Array<String> coordValues = value.ToString().Split(' '); for (uint j = 0; j < numCoords; ++j) { LineEdit@ attrEdit = CreateAttributeLineEdit(parent, null, 0, 0); attrEdit.vars["Coordinate"] = j; attrEdit.vars["Name"] = parameterNames[i]; attrEdit.text = coordValues[j]; SubscribeToEvent(attrEdit, "TextChanged", "EditShaderParameter"); SubscribeToEvent(attrEdit, "TextFinished", "EditShaderParameter"); } } } void EditMaterialName(StringHash eventType, VariantMap& eventData) { LineEdit@ nameEdit = eventData["Element"].GetUIElement(); String newMaterialName = nameEdit.text.Trimmed(); if (!newMaterialName.empty) { Material@ newMaterial = cache.GetResource("Material", newMaterialName); if (newMaterial !is null) EditMaterial(newMaterial); } } void PickEditMaterial() { @resourcePicker = GetResourcePicker(ShortStringHash("Material")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector("Pick " + resourcePicker.typeName, "OK", "Cancel", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "PickEditMaterialDone"); } void PickEditMaterialDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); if (!eventData["OK"].GetBool()) { @resourcePicker = null; return; } String resourceName = eventData["FileName"].GetString(); Resource@ res = GetPickedResource(resourceName); if (res !is null) EditMaterial(cast<Material>(res)); @resourcePicker = null; } void NewMaterial() { EditMaterial(Material()); } void RevertMaterial() { if (editMaterial is null) return; BeginMaterialEdit(); cache.ReloadResource(editMaterial); EndMaterialEdit(); RefreshMaterialEditor(); } void SaveMaterial() { if (editMaterial is null || editMaterial.name.empty) return; String fullName = cache.GetResourceFileName(editMaterial.name); if (fullName.empty) return; File saveFile(fullName, FILE_WRITE); editMaterial.Save(saveFile); } void SaveMaterialAs() { if (editMaterial is null) return; @resourcePicker = GetResourcePicker(ShortStringHash("Material")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector("Save material as", "Save", "Cancel", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "SaveMaterialAsDone"); } void SaveMaterialAsDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); @resourcePicker = null; if (editMaterial is null) return; if (!eventData["OK"].GetBool()) { @resourcePicker = null; return; } String fullName = eventData["FileName"].GetString(); File saveFile(fullName, FILE_WRITE); if (editMaterial.Save(saveFile)) { saveFile.Close(); // Load the new resource to update the name in the editor Material@ newMat = cache.GetResource("Material", GetResourceNameFromFullName(fullName)); if (newMat !is null) EditMaterial(newMat); } } void EditShaderParameter(StringHash eventType, VariantMap& eventData) { if (editMaterial is null) return; LineEdit@ attrEdit = eventData["Element"].GetUIElement(); uint coordinate = attrEdit.vars["Coordinate"].GetUInt(); String name = attrEdit.vars["Name"].GetString(); Variant oldValue = editMaterial.shaderParameters[name]; Array<String> coordValues = oldValue.ToString().Split(' '); coordValues[coordinate] = String(attrEdit.text.ToFloat()); String valueString; for (uint i = 0; i < coordValues.length; ++i) { valueString += coordValues[i]; valueString += " "; } Variant newValue; newValue.FromString(oldValue.type, valueString); BeginMaterialEdit(); editMaterial.shaderParameters[name] = newValue; EndMaterialEdit(); } void CreateShaderParameter(StringHash eventType, VariantMap& eventData) { if (editMaterial is null) return; LineEdit@ nameEdit = materialWindow.GetChild("ParameterNameEdit", true); String newName = nameEdit.text.Trimmed(); if (newName.empty) return; DropDownList@ dropDown = eventData["Element"].GetUIElement(); Variant newValue; switch (dropDown.selection) { case 0: newValue = float(0); break; case 1: newValue = Vector2(0, 0); break; case 2: newValue = Vector3(0, 0, 0); break; case 3: newValue = Vector4(0, 0, 0, 0); break; } BeginMaterialEdit(); editMaterial.shaderParameters[newName] = newValue; EndMaterialEdit(); RefreshMaterialShaderParameters(); } void DeleteShaderParameter() { if (editMaterial is null) return; LineEdit@ nameEdit = materialWindow.GetChild("ParameterNameEdit", true); String name = nameEdit.text.Trimmed(); if (name.empty) return; BeginMaterialEdit(); editMaterial.RemoveShaderParameter(name); EndMaterialEdit(); RefreshMaterialShaderParameters(); } void PickMaterialTexture(StringHash eventType, VariantMap& eventData) { if (editMaterial is null) return; UIElement@ button = eventData["Element"].GetUIElement(); resourcePickIndex = button.vars["Index"].GetUInt(); @resourcePicker = GetResourcePicker(ShortStringHash("Texture2D")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector("Pick " + resourcePicker.typeName, "OK", "Cancel", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "PickMaterialTextureDone"); } void PickMaterialTextureDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); if (!eventData["OK"].GetBool()) { @resourcePicker = null; return; } String resourceName = eventData["FileName"].GetString(); Resource@ res = GetPickedResource(resourceName); if (res !is null && editMaterial !is null) { BeginMaterialEdit(); editMaterial.textures[resourcePickIndex] = res; EndMaterialEdit(); RefreshMaterialTextures(false); } @resourcePicker = null; } void EditMaterialTexture(StringHash eventType, VariantMap& eventData) { if (editMaterial is null) return; LineEdit@ attrEdit = eventData["Element"].GetUIElement(); String textureName = attrEdit.text.Trimmed(); uint index = attrEdit.vars["Index"].GetUInt(); BeginMaterialEdit(); if (!textureName.empty) { Texture@ texture = cache.GetResource(GetExtension(textureName) == ".xml" ? "TextureCube" : "Texture2D", textureName); editMaterial.textures[index] = texture; } else editMaterial.textures[index] =null; EndMaterialEdit(); } void BeginMaterialEdit() { if (editMaterial is null) return; oldMaterialState = XMLFile(); XMLElement materialElem = oldMaterialState.CreateRoot("material"); editMaterial.Save(materialElem); } void EndMaterialEdit() { if (editMaterial is null) return; EditMaterialAction@ action = EditMaterialAction(); action.Define(editMaterial, oldMaterialState); SaveEditAction(action); }
Make the material revert action undoable.
Make the material revert action undoable.
ActionScript
mit
urho3d/Urho3D,fire/Urho3D-1,MonkeyFirst/Urho3D,xiliu98/Urho3D,SirNate0/Urho3D,victorholt/Urho3D,carnalis/Urho3D,SuperWangKai/Urho3D,victorholt/Urho3D,MeshGeometry/Urho3D,rokups/Urho3D,codedash64/Urho3D,c4augustus/Urho3D,cosmy1/Urho3D,cosmy1/Urho3D,tommy3/Urho3D,MonkeyFirst/Urho3D,orefkov/Urho3D,rokups/Urho3D,iainmerrick/Urho3D,luveti/Urho3D,299299/Urho3D,tommy3/Urho3D,codedash64/Urho3D,urho3d/Urho3D,SuperWangKai/Urho3D,kostik1337/Urho3D,helingping/Urho3D,SirNate0/Urho3D,abdllhbyrktr/Urho3D,urho3d/Urho3D,carnalis/Urho3D,rokups/Urho3D,MonkeyFirst/Urho3D,299299/Urho3D,tommy3/Urho3D,xiliu98/Urho3D,henu/Urho3D,kostik1337/Urho3D,299299/Urho3D,iainmerrick/Urho3D,carnalis/Urho3D,rokups/Urho3D,abdllhbyrktr/Urho3D,bacsmar/Urho3D,orefkov/Urho3D,helingping/Urho3D,PredatorMF/Urho3D,carnalis/Urho3D,codedash64/Urho3D,cosmy1/Urho3D,eugeneko/Urho3D,c4augustus/Urho3D,weitjong/Urho3D,kostik1337/Urho3D,codemon66/Urho3D,abdllhbyrktr/Urho3D,xiliu98/Urho3D,MonkeyFirst/Urho3D,tommy3/Urho3D,carnalis/Urho3D,rokups/Urho3D,299299/Urho3D,cosmy1/Urho3D,kostik1337/Urho3D,abdllhbyrktr/Urho3D,luveti/Urho3D,MeshGeometry/Urho3D,SuperWangKai/Urho3D,codedash64/Urho3D,PredatorMF/Urho3D,weitjong/Urho3D,MeshGeometry/Urho3D,299299/Urho3D,fire/Urho3D-1,codemon66/Urho3D,fire/Urho3D-1,fire/Urho3D-1,fire/Urho3D-1,iainmerrick/Urho3D,tommy3/Urho3D,luveti/Urho3D,orefkov/Urho3D,luveti/Urho3D,PredatorMF/Urho3D,helingping/Urho3D,bacsmar/Urho3D,MeshGeometry/Urho3D,SirNate0/Urho3D,iainmerrick/Urho3D,eugeneko/Urho3D,henu/Urho3D,SuperWangKai/Urho3D,eugeneko/Urho3D,codedash64/Urho3D,henu/Urho3D,victorholt/Urho3D,weitjong/Urho3D,abdllhbyrktr/Urho3D,victorholt/Urho3D,helingping/Urho3D,PredatorMF/Urho3D,helingping/Urho3D,henu/Urho3D,xiliu98/Urho3D,urho3d/Urho3D,weitjong/Urho3D,SuperWangKai/Urho3D,orefkov/Urho3D,victorholt/Urho3D,SirNate0/Urho3D,bacsmar/Urho3D,c4augustus/Urho3D,bacsmar/Urho3D,MeshGeometry/Urho3D,rokups/Urho3D,cosmy1/Urho3D,kostik1337/Urho3D,codemon66/Urho3D,xiliu98/Urho3D,codemon66/Urho3D,299299/Urho3D,SirNate0/Urho3D,MonkeyFirst/Urho3D,c4augustus/Urho3D,iainmerrick/Urho3D,henu/Urho3D,codemon66/Urho3D,luveti/Urho3D,eugeneko/Urho3D,weitjong/Urho3D,c4augustus/Urho3D
5c85da3ec83b90aa008918e6c408b9a7f1599e12
sdk-remote/src/tests/bin/uobject-check.as
sdk-remote/src/tests/bin/uobject-check.as
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*- URBI_INIT # The full path to the *.uob dir: # ../../../../../sdk-remote/src/tests/uobjects/access-and-change/uaccess.uob uob=$(absolute $1.uob) test -d "$uob" || error OSFILE "argument is not a directory: $uob" # The ending part, for our builddir: access-and-change/uaccess.dir. builddir=$(echo "$uob" | sed -e 's,.*/src/tests/uobjects/,uobjects/,;s/\.uob$//').dir # For error messages. me=$(basename "$uob" .uob) # The directory we work in. rm -rf $builddir mkdir -p $builddir cd $builddir # Find urbi-launch. urbi_launch=$(xfind_prog urbi-launch) # The remote component: an executable. umake_remote=$(xfind_prog "umake-remote") xrun "umake-remote" $umake_remote --output=$me $uob test -x "$me" || fatal "$me is not executable" xrun "$me --version" "./$me" --version # The shared component: a dlopen module. umake_shared=$(xfind_prog "umake-shared") xrun "umake-shared" $umake_shared --output=$me $uob test -f "$me.la" || fatal "$me.la does not exist" xrun "urbi-launch $me --version" "$urbi_launch" --start $me -- --version
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*- URBI_INIT # The full path to the *.uob dir: # ../../../../../sdk-remote/src/tests/uobjects/access-and-change/uaccess.uob uob=$(absolute $1.uob) test -d "$uob" || error OSFILE "argument is not a directory: $uob" # The ending part, for our builddir: access-and-change/uaccess.dir. builddir=$(echo "$uob" | sed -e 's,.*/src/tests/uobjects/,uobjects/,;s/\.uob$//').dir # For error messages. me=$(basename "$uob" .uob) # The directory we work in. rm -rf $builddir mkdir -p $builddir cd $builddir # Find urbi-launch. urbi_launch=$(xfind_prog urbi-launch) # The remote component: an executable. umake_remote=$(xfind_prog "umake-remote") xrun "umake-remote" $umake_remote --output=$me $uob test -x "$me" || fatal "$me is not executable" xrun "$me --version" "./$me" --version # The shared component: a dlopen module. umake_shared=$(xfind_prog "umake-shared") xrun "umake-shared" $umake_shared --output=$me $uob test -f "$me.la" || fatal "$me.la does not exist" xrun "urbi-launch $me --version" "$urbi_launch" --start $me.la -- --version
Add ".la" extension to urbi-launch while testing.
Add ".la" extension to urbi-launch while testing. * src/tests/bin/uobject-check.as: Give the full name of the dynamic library.
ActionScript
bsd-3-clause
aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi
4ccbaa2509992b12f38d82891a183c20b207d992
src/aerys/minko/scene/node/group/Group.as
src/aerys/minko/scene/node/group/Group.as
package aerys.minko.scene.node.group { import aerys.minko.scene.action.IAction; import aerys.minko.scene.action.group.GroupAction; import aerys.minko.scene.node.AbstractScene; import aerys.minko.scene.node.IScene; import aerys.minko.scene.node.ISearchableScene; import aerys.minko.scene.visitor.ISceneVisitor; import aerys.minko.scene.visitor.RenderingVisitor; import flash.utils.Proxy; import flash.utils.flash_proxy; import flash.utils.getQualifiedClassName; /** * The Group3D provides a basic support for scene building. * A Group3D can contain any object implementing the IScene3D interface. * * Group3D objects do not affect their children with any specific behaviour. * * @author Jean-Marc Le Roux */ public dynamic class Group extends Proxy implements IGroup { private static var _id : uint = 0; private var _name : String = null; private var _children : Vector.<IScene> = null; private var _numChildren : int = 0; private var _actions : Vector.<IAction> = Vector.<IAction>([GroupAction.groupAction]); public function get actions() : Vector.<IAction> { return _actions; } public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } protected function get rawChildren() : Vector.<IScene> { return _children; } protected function set rawChildren(value : Vector.<IScene>) : void { _children = value; _numChildren = _children.length; } /** * The number of children. */ public function get numChildren() : uint { return _numChildren; } public function Group(...children) { super(); _name = AbstractScene.getDefaultSceneName(this); initialize(children); } private function initialize(children : Array) : void { while (children.length == 1 && children[0] is Array) children = children[0]; _numChildren = children.length; _children = _numChildren ? Vector.<IScene>(children) : new Vector.<IScene>(); } public function contains(scene : IScene) : Boolean { return getChildIndex(scene) >= 0; } public function getChildIndex(child : IScene) : int { for (var i : int = 0; i < _numChildren; i++) if (_children[i] === child) return i; return -1; } public function getChildByName(name : String) : IScene { for (var i : int = 0; i < _numChildren; i++) if (_children[i].name === name) return _children[i]; return null; } /** * Add a child to the container. * * @param scene The child to add. */ public function addChild(scene : IScene) : IGroup { if (!scene) throw new Error(); _children.push(scene); ++_numChildren; //scene.added(this); return this; } public function addChildAt(scene : IScene, position : uint) : IGroup { if (!scene) throw new Error(); var numChildren : int = _children.length; if (position >= numChildren) return addChild(scene); for (var i : int = numChildren; i > position; --i) _children[i] = _children[int(i - 1)]; _children[position] = scene; ++_numChildren; return this; } /** * Remove a child from the container. * * @param myChild The child to remove. * @return Whether the child was actually removed or not. */ public function removeChild(child : IScene) : IGroup { var numChildren : int = _children.length; var i : int = 0; while (i < numChildren && _children[i] !== child) ++i; if (i >= numChildren) return null; return removeChildAt(i); } public function removeChildAt(position : uint) : IGroup { var removed : IScene = null; if (position < _numChildren) { removed = _children[position]; while (position < _numChildren - 1) _children[position] = _children[int(++position)]; _children.length = --_numChildren; } return this; } public function removeAllChildren() : IGroup { _children.length = 0; _numChildren = 0; return this; } public function getChildAt(position : uint) : IScene { return position < _numChildren ? _children[position] : null; } public function swapChildren(child1 : IScene, child2 : IScene) : IGroup { var id1 : int = getChildIndex(child1); var id2 : int = getChildIndex(child2); if (id1 == -1 || id2 == -1) return this; var tmp : IScene = _children[id2]; _children[id2] = _children[id1]; _children[id1] = tmp; return this; } public function getDescendantByName(name : String) : IScene { var descendant : IScene = getChildByName(name); var numChildren : int = numChildren; for (var i : int = 0; i < numChildren && !descendant; ++i) { var searchable : ISearchableScene = _children[i] as ISearchableScene; if (searchable) descendant = searchable.getDescendantByName(name); } return descendant; } public function toString() : String { return "[" + getQualifiedClassName(this) + " " + name + "]"; } override flash_proxy function getProperty(name : *) : * { var index : int = parseInt(name); return index == name ? getChildAt(index) : getChildByName(name as String); } override flash_proxy function setProperty(name : *, value : *) : void { var index : int = parseInt(name); if (index == name) { if (index < numChildren) { removeChildAt(index); addChildAt(value, index); } } else { var old : IScene = getChildByName(name); addChild(value); if (old) { swapChildren(value, old); _children.length = _children.length - 1; } } } override flash_proxy function getDescendants(name : *) : * { return getDescendantByName(name); } override flash_proxy function nextNameIndex(index : int) : int { return index < numChildren ? index + 1 : 0; } override flash_proxy function nextName(index : int) : String { return String(index - 1); } override flash_proxy function nextValue(index : int) : * { return _children[int(index - 1)]; } } }
package aerys.minko.scene.node.group { import aerys.minko.scene.action.IAction; import aerys.minko.scene.action.group.GroupAction; import aerys.minko.scene.node.AbstractScene; import aerys.minko.scene.node.IScene; import aerys.minko.scene.node.ISearchableScene; import aerys.minko.scene.visitor.ISceneVisitor; import aerys.minko.scene.visitor.RenderingVisitor; import flash.utils.Proxy; import flash.utils.flash_proxy; import flash.utils.getQualifiedClassName; /** * The Group3D provides a basic support for scene building. * A Group3D can contain any object implementing the IScene3D interface. * * Group3D objects do not affect their children with any specific behaviour. * * @author Jean-Marc Le Roux */ public dynamic class Group extends Proxy implements IGroup { private static var _id : uint = 0; private var _name : String = null; private var _children : Vector.<IScene> = null; private var _numChildren : int = 0; private var _actions : Vector.<IAction> = Vector.<IAction>([GroupAction.groupAction]); public function get actions() : Vector.<IAction> { return _actions; } public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } protected function get rawChildren() : Vector.<IScene> { return _children; } protected function set rawChildren(value : Vector.<IScene>) : void { _children = value; _numChildren = _children.length; } /** * The number of children. */ public function get numChildren() : uint { return _numChildren; } public function Group(...children) { super(); _name = AbstractScene.getDefaultSceneName(this); initialize(children); } private function initialize(children : Array) : void { while (children.length == 1 && children[0] is Array) children = children[0]; _numChildren = children.length; _children = _numChildren ? Vector.<IScene>(children) : new Vector.<IScene>(); } public function contains(scene : IScene) : Boolean { return getChildIndex(scene) >= 0; } public function getChildIndex(child : IScene) : int { for (var i : int = 0; i < _numChildren; i++) if (_children[i] === child) return i; return -1; } public function getChildByName(name : String) : IScene { for (var i : int = 0; i < _numChildren; i++) if (_children[i].name === name) return _children[i]; return null; } /** * Add a child to the container. * * @param scene The child to add. */ public function addChild(scene : IScene) : IGroup { if (!scene) throw new Error("Parameter child must be non-null."); _children.push(scene); ++_numChildren; //scene.added(this); return this; } public function addChildAt(scene : IScene, position : uint) : IGroup { if (!scene) throw new Error("Parameter child must be non-null."); var numChildren : int = _children.length; if (position >= numChildren) return addChild(scene); for (var i : int = numChildren; i > position; --i) _children[i] = _children[int(i - 1)]; _children[position] = scene; ++_numChildren; return this; } /** * Remove a child from the container. * * @param myChild The child to remove. * @return Whether the child was actually removed or not. */ public function removeChild(child : IScene) : IGroup { var numChildren : int = _children.length; var i : int = 0; while (i < numChildren && _children[i] !== child) ++i; if (i >= numChildren) return null; return removeChildAt(i); } public function removeChildAt(position : uint) : IGroup { var removed : IScene = null; if (position < _numChildren) { removed = _children[position]; while (position < _numChildren - 1) _children[position] = _children[int(++position)]; _children.length = --_numChildren; } return this; } public function removeAllChildren() : IGroup { _children.length = 0; _numChildren = 0; return this; } public function getChildAt(position : uint) : IScene { return position < _numChildren ? _children[position] : null; } public function swapChildren(child1 : IScene, child2 : IScene) : IGroup { var id1 : int = getChildIndex(child1); var id2 : int = getChildIndex(child2); if (id1 == -1 || id2 == -1) return this; var tmp : IScene = _children[id2]; _children[id2] = _children[id1]; _children[id1] = tmp; return this; } public function getDescendantByName(name : String) : IScene { var descendant : IScene = getChildByName(name); var numChildren : int = numChildren; for (var i : int = 0; i < numChildren && !descendant; ++i) { var searchable : ISearchableScene = _children[i] as ISearchableScene; if (searchable) descendant = searchable.getDescendantByName(name); } return descendant; } public function toString() : String { return "[" + getQualifiedClassName(this) + " " + name + "]"; } override flash_proxy function getProperty(name : *) : * { var index : int = parseInt(name); return index == name ? getChildAt(index) : getChildByName(name as String); } override flash_proxy function setProperty(name : *, value : *) : void { var index : int = parseInt(name); if (index == name) { if (index < numChildren) { removeChildAt(index); addChildAt(value, index); } } else { var old : IScene = getChildByName(name); addChild(value); if (old) { swapChildren(value, old); _children.length = _children.length - 1; } } } override flash_proxy function getDescendants(name : *) : * { return getDescendantByName(name); } override flash_proxy function nextNameIndex(index : int) : int { return index < numChildren ? index + 1 : 0; } override flash_proxy function nextName(index : int) : String { return String(index - 1); } override flash_proxy function nextValue(index : int) : * { return _children[int(index - 1)]; } } }
Add better error message when using addChild().
Add better error message when using addChild().
ActionScript
mit
aerys/minko-as3
b7b87a13d5403bf5ea9c228f3f6432f7ba1f41d5
src/org/jivesoftware/xiff/data/Message.as
src/org/jivesoftware/xiff/data/Message.as
/* * Copyright (C) 2003-2007 * Nick Velloff <[email protected]> * Derrick Grigg <[email protected]> * Sean Voisen <[email protected]> * Sean Treadway <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package org.jivesoftware.xiff.data { import org.jivesoftware.xiff.data.ISerializable; import org.jivesoftware.xiff.data.XMPPStanza; import org.jivesoftware.xiff.data.ExtensionClassRegistry; import org.jivesoftware.xiff.data.xhtml.XHTMLExtension; import flash.xml.XMLNode; import org.jivesoftware.xiff.events.XIFFErrorEvent; /** * A class for abstraction and encapsulation of message data. * * @param recipient The JID of the message recipient * @param sender The JID of the message sender - the server should report an error if this is falsified * @param msgID The message ID * @param msgBody The message body in plain-text format * @param msgHTMLBody The message body in XHTML format * @param msgType The message type * @param msgSubject (Optional) The message subject */ public class Message extends XMPPStanza implements ISerializable { // Static variables for specific type strings public static var NORMAL_TYPE:String = "normal"; public static var CHAT_TYPE:String = "chat"; public static var GROUPCHAT_TYPE:String = "groupchat"; public static var HEADLINE_TYPE:String = "headline"; public static var ERROR_TYPE:String = "error"; // Private references to nodes within our XML private var myBodyNode:XMLNode; private var mySubjectNode:XMLNode; private var myThreadNode:XMLNode; private var myTimeStampNode:XMLNode; private static var isMessageStaticCalled:Boolean = MessageStaticConstructor(); private static var staticConstructorDependency:Array = [ XMPPStanza, XHTMLExtension, ExtensionClassRegistry ]; public function Message( recipient:String=null, msgID:String=null, msgBody:String=null, msgHTMLBody:String=null, msgType:String=null, msgSubject:String=null ) { // Flash gives a warning if superconstructor is not first, hence the inline id check var msgId:String = exists( msgID ) ? msgID : generateID("m_"); super( recipient, null, msgType, msgId, "message" ); body = msgBody; htmlBody = msgHTMLBody; subject = msgSubject; } public static function MessageStaticConstructor():Boolean { XHTMLExtension.enable(); return true; } /** * Serializes the Message into XML form for sending to a server. * * @return An indication as to whether serialization was successful */ override public function serialize( parentNode:XMLNode ):Boolean { return super.serialize( parentNode ); } /** * Deserializes an XML object and populates the Message instance with its data. * * @param xmlNode The XML to deserialize * @return An indication as to whether deserialization was sucessful */ override public function deserialize( xmlNode:XMLNode ):Boolean { var isSerialized:Boolean = super.deserialize( xmlNode ); if (isSerialized) { var children:Array = xmlNode.childNodes; for( var i:String in children ) { trace(children[i].nodeName); switch( children[i].nodeName ) { // Adding error handler for 404 sent back by server case "error": break; case "body": myBodyNode = children[i]; break; case "subject": mySubjectNode = children[i]; break; case "thread": myThreadNode = children[i]; break; case "x": if(children[i].attributes.xmlns == "jabber:x:delay") myTimeStampNode = children[i]; break; } } } return isSerialized; } /** * The message body in plain-text format. If a client cannot render HTML-formatted * text, this text is typically used instead. */ public function get body():String { if (!exists(myBodyNode)){ return null; } var value: String = ''; try { value = myBodyNode.firstChild.nodeValue; } catch (error:Error) { trace (error.getStackTrace()); } return value; } /** * @private */ public function set body( bodyText:String ):void { myBodyNode = replaceTextNode(getNode(), myBodyNode, "body", bodyText); } /** * The message body in XHTML format. Internally, this uses the XHTML data extension. * * @see org.jivesoftware.xiff.data.xhtml.XHTMLExtension */ public function get htmlBody():String { try { var ext:XHTMLExtension = getAllExtensionsByNS(XHTMLExtension.NS)[0]; return ext.body; } catch (e:Error) { trace("Error : null trapped. Resuming."); } return null; } /** * @private */ public function set htmlBody( bodyHTML:String ):void { // Removes any existing HTML body text first removeAllExtensions(XHTMLExtension.NS); if (exists(bodyHTML) && bodyHTML.length > 0) { var ext:XHTMLExtension = new XHTMLExtension(getNode()); ext.body = bodyHTML; addExtension(ext); } } /** * The message subject. Typically chat and groupchat-type messages do not use * subjects. Rather, this is reserved for normal and headline-type messages. */ public function get subject():String { if (mySubjectNode == null) return null; return mySubjectNode.firstChild.nodeValue; } /** * @private */ public function set subject( aSubject:String ):void { mySubjectNode = replaceTextNode(getNode(), mySubjectNode, "subject", aSubject); } /** * The message thread ID. Threading is used to group messages of the same discussion together. * The library does not perform message grouping, rather it is up to any client authors to * properly perform this task. */ public function get thread():String { if (myThreadNode == null) return null; return myThreadNode.firstChild.nodeValue; } /** * @private */ public function set thread( theThread:String ):void { myThreadNode = replaceTextNode(getNode(), myThreadNode, "thread", theThread); } public function set time( theTime:Date ): void { } public function get time():Date { if(myTimeStampNode == null) return null; var stamp:String = myTimeStampNode.attributes.stamp; var t:Date = new Date(); //CCYYMMDDThh:mm:ss //20020910T23:41:07 t.setUTCFullYear(stamp.slice(0, 4)); //2002 t.setUTCMonth(stamp.slice(4, 6)); //09 t.setUTCDate(stamp.slice(6, 8)); //10 //T t.setUTCHours(stamp.slice(9, 11)); //23 //: t.setUTCMinutes(stamp.slice(12, 14)); //41 //: t.setUTCSeconds(stamp.slice(15, 17)); //07 return t; } } }
/* * Copyright (C) 2003-2007 * Nick Velloff <[email protected]> * Derrick Grigg <[email protected]> * Sean Voisen <[email protected]> * Sean Treadway <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package org.jivesoftware.xiff.data { import org.jivesoftware.xiff.data.ISerializable; import org.jivesoftware.xiff.data.XMPPStanza; import org.jivesoftware.xiff.data.ExtensionClassRegistry; import org.jivesoftware.xiff.data.xhtml.XHTMLExtension; import flash.xml.XMLNode; import org.jivesoftware.xiff.events.XIFFErrorEvent; /** * A class for abstraction and encapsulation of message data. * * @param recipient The JID of the message recipient * @param sender The JID of the message sender - the server should report an error if this is falsified * @param msgID The message ID * @param msgBody The message body in plain-text format * @param msgHTMLBody The message body in XHTML format * @param msgType The message type * @param msgSubject (Optional) The message subject */ public class Message extends XMPPStanza implements ISerializable { // Static variables for specific type strings public static var NORMAL_TYPE:String = "normal"; public static var CHAT_TYPE:String = "chat"; public static var GROUPCHAT_TYPE:String = "groupchat"; public static var HEADLINE_TYPE:String = "headline"; public static var ERROR_TYPE:String = "error"; // Private references to nodes within our XML private var myBodyNode:XMLNode; private var mySubjectNode:XMLNode; private var myThreadNode:XMLNode; private var myTimeStampNode:XMLNode; private static var isMessageStaticCalled:Boolean = MessageStaticConstructor(); private static var staticConstructorDependency:Array = [ XMPPStanza, XHTMLExtension, ExtensionClassRegistry ]; public function Message( recipient:String=null, msgID:String=null, msgBody:String=null, msgHTMLBody:String=null, msgType:String=null, msgSubject:String=null ) { // Flash gives a warning if superconstructor is not first, hence the inline id check var msgId:String = exists( msgID ) ? msgID : generateID("m_"); super( recipient, null, msgType, msgId, "message" ); body = msgBody; htmlBody = msgHTMLBody; subject = msgSubject; } public static function MessageStaticConstructor():Boolean { XHTMLExtension.enable(); return true; } /** * Serializes the Message into XML form for sending to a server. * * @return An indication as to whether serialization was successful */ override public function serialize( parentNode:XMLNode ):Boolean { return super.serialize( parentNode ); } /** * Deserializes an XML object and populates the Message instance with its data. * * @param xmlNode The XML to deserialize * @return An indication as to whether deserialization was sucessful */ override public function deserialize( xmlNode:XMLNode ):Boolean { var isSerialized:Boolean = super.deserialize( xmlNode ); if (isSerialized) { var children:Array = xmlNode.childNodes; for( var i:String in children ) { trace(children[i].nodeName); switch( children[i].nodeName ) { // Adding error handler for 404 sent back by server case "error": break; case "body": myBodyNode = children[i]; break; case "subject": mySubjectNode = children[i]; break; case "thread": myThreadNode = children[i]; break; case "x": if(children[i].attributes.xmlns == "jabber:x:delay") myTimeStampNode = children[i]; break; } } } return isSerialized; } /** * The message body in plain-text format. If a client cannot render HTML-formatted * text, this text is typically used instead. */ public function get body():String { if (!exists(myBodyNode)){ return null; } var value: String = ''; try { value = myBodyNode.firstChild.nodeValue; } catch (error:Error) { trace (error.getStackTrace()); } return value; } /** * @private */ public function set body( bodyText:String ):void { myBodyNode = replaceTextNode(getNode(), myBodyNode, "body", bodyText); } /** * The message body in XHTML format. Internally, this uses the XHTML data extension. * * @see org.jivesoftware.xiff.data.xhtml.XHTMLExtension */ public function get htmlBody():String { try { var ext:XHTMLExtension = getAllExtensionsByNS(XHTMLExtension.NS)[0]; return ext.body; } catch (e:Error) { trace("Error : null trapped. Resuming."); } return null; } /** * @private */ public function set htmlBody( bodyHTML:String ):void { // Removes any existing HTML body text first removeAllExtensions(XHTMLExtension.NS); if (exists(bodyHTML) && bodyHTML.length > 0) { var ext:XHTMLExtension = new XHTMLExtension(getNode()); ext.body = bodyHTML; addExtension(ext); } } /** * The message subject. Typically chat and groupchat-type messages do not use * subjects. Rather, this is reserved for normal and headline-type messages. */ public function get subject():String { if (mySubjectNode == null) return null; return mySubjectNode.firstChild.nodeValue; } /** * @private */ public function set subject( aSubject:String ):void { mySubjectNode = replaceTextNode(getNode(), mySubjectNode, "subject", aSubject); } /** * The message thread ID. Threading is used to group messages of the same discussion together. * The library does not perform message grouping, rather it is up to any client authors to * properly perform this task. */ public function get thread():String { if (myThreadNode == null) return null; return myThreadNode.firstChild.nodeValue; } /** * @private */ public function set thread( theThread:String ):void { myThreadNode = replaceTextNode(getNode(), myThreadNode, "thread", theThread); } public function set time( theTime:Date ): void { } public function get time():Date { if(myTimeStampNode == null) return null; var stamp:String = myTimeStampNode.attributes.stamp; var t:Date = new Date(); //CCYYMMDDThh:mm:ss //20020910T23:41:07 t.setUTCFullYear(stamp.slice(0, 4)); //2002 t.setUTCMonth(Number(stamp.slice(4, 6)) - 1); //09 t.setUTCDate(stamp.slice(6, 8)); //10 //T t.setUTCHours(stamp.slice(9, 11)); //23 //: t.setUTCMinutes(stamp.slice(12, 14)); //41 //: t.setUTCSeconds(stamp.slice(15, 17)); //07 return t; } } }
Fix an off-by-one error due to the way flex deals with dates. Thanks to Bill Bailey for pointing this out :)
Fix an off-by-one error due to the way flex deals with dates. Thanks to Bill Bailey for pointing this out :)
ActionScript
apache-2.0
igniterealtime/XIFF
134c1e25d0b32bbc5c159d992f106f9e9c0aeb1a
src/goplayer/StreamioAPI.as
src/goplayer/StreamioAPI.as
package goplayer { public class StreamioAPI implements MovieEventReporter { private static const VERSION : String = "/v1" private var baseURL : String private var http : HTTP private var trackerID : String public function StreamioAPI (baseURL : String, http : HTTP, trackerID : String) { this.baseURL = baseURL this.http = http this.trackerID = trackerID } // ----------------------------------------------------- public function fetchMovie (id : String, handler : MovieHandler) : void { fetch(getMoviePath(id), new MovieJSONHandler(handler)) } public function reportMovieViewed(movieID : String) : void { reportMovieEvent(movieID, "views", {}) } public function reportMoviePlayed(movieID : String) : void { reportMovieEvent(movieID, "plays", {}) } public function reportMovieHeatmapData (movieID : String, time : Number) : void { reportMovieEvent(movieID, "heat", { time: time }) } private function reportMovieEvent (movieID : String, event : String, parameters : Object) : void { if (trackerID != null && trackerID != "") post(statsPath, getStatsParameters(movieID, event, parameters)) } private function getStatsParameters (movieID : String, event : String, parameters : Object) : Object { const result : Object = new Object result.tracker_id = trackerID result.movie_id = movieID result.event = event for (var name : String in parameters) result[name] = parameters[name] return result } // ----------------------------------------------------- private function getMoviePath(id : String) : String { return "/videos/" + id + "/public_show.json" } private function get statsPath() : String { return "/stats" } // ----------------------------------------------------- private function fetch(path : String, handler : JSONHandler) : void { http.fetchJSON(getURL(path), handler) } private function post(path : String, parameters : Object) : void { http.post(getURL(path), parameters, new NullHTTPHandler) } private function getURL(path : String) : URL { return URL.parse(baseURL + VERSION + path) } } } import goplayer.* class MovieJSONHandler implements JSONHandler { private var handler : MovieHandler public function MovieJSONHandler(handler : MovieHandler) { this.handler = handler } public function handleJSON(json : Object) : void { handler.handleMovie(new StreamioMovie(json)) } } class NullHTTPHandler implements HTTPResponseHandler { public function handleHTTPResponse(text : String) : void {} }
package goplayer { public class StreamioAPI implements MovieEventReporter { private static const VERSION : String = "/v1" private var baseURL : String private var http : HTTP private var trackerID : String public function StreamioAPI (baseURL : String, http : HTTP, trackerID : String) { this.baseURL = baseURL this.http = http this.trackerID = trackerID } // ----------------------------------------------------- public function fetchMovie (id : String, handler : MovieHandler) : void { fetch(getMoviePath(id), new MovieJSONHandler(handler)) } public function reportMovieViewed(movieID : String) : void { reportMovieEvent(movieID, "views", {}) } public function reportMoviePlayed(movieID : String) : void { reportMovieEvent(movieID, "plays", {}) } public function reportMovieHeatmapData (movieID : String, time : Number) : void { reportMovieEvent(movieID, "heat", { time: time }) } private function reportMovieEvent (movieID : String, event : String, parameters : Object) : void { if (trackerID != null && trackerID != "") post(statsPath, getStatsParameters(movieID, event, parameters)) } private function getStatsParameters (movieID : String, event : String, parameters : Object) : Object { const result : Object = new Object result.tracker_id = trackerID result.video_id = movieID result.event = event for (var name : String in parameters) result[name] = parameters[name] return result } // ----------------------------------------------------- private function getMoviePath(id : String) : String { return "/videos/" + id + "/public_show.json" } private function get statsPath() : String { return "/stats" } // ----------------------------------------------------- private function fetch(path : String, handler : JSONHandler) : void { http.fetchJSON(getURL(path), handler) } private function post(path : String, parameters : Object) : void { http.post(getURL(path), parameters, new NullHTTPHandler) } private function getURL(path : String) : URL { return URL.parse(baseURL + VERSION + path) } } } import goplayer.* class MovieJSONHandler implements JSONHandler { private var handler : MovieHandler public function MovieJSONHandler(handler : MovieHandler) { this.handler = handler } public function handleJSON(json : Object) : void { handler.handleMovie(new StreamioMovie(json)) } } class NullHTTPHandler implements HTTPResponseHandler { public function handleHTTPResponse(text : String) : void {} }
Use `video_id' instead of `movie_id' in stats API call.
Use `video_id' instead of `movie_id' in stats API call.
ActionScript
mit
dbrock/goplayer,dbrock/goplayer
724776245ece2505091f9f5baec78df020c32d71
src/ru/kutu/grindplayer/config/AppConfig.as
src/ru/kutu/grindplayer/config/AppConfig.as
package ru.kutu.grindplayer.config { import org.osmf.media.MediaFactory; import org.osmf.media.MediaPlayer; import org.osmf.media.MediaResourceBase; import org.osmf.player.configuration.ConfigurationFlashvarsDeserializer; import org.osmf.player.configuration.ConfigurationLoader; import org.osmf.player.configuration.ConfigurationProxy; import org.osmf.player.configuration.ConfigurationXMLDeserializer; import robotlegs.bender.extensions.contextView.ContextView; import robotlegs.bender.extensions.mediatorMap.api.IMediatorMap; import robotlegs.bender.framework.api.ILogger; import ru.kutu.grind.config.ConfigurationProxyProvider; import ru.kutu.grind.config.GrindConfig; import ru.kutu.grind.config.JavaScriptBridgeBase; import ru.kutu.grind.config.LocalSettings; import ru.kutu.grind.config.PlayerConfiguration; import ru.kutu.grind.config.ResourceProvider; import ru.kutu.grind.media.GrindMediaFactoryBase; import ru.kutu.grind.views.api.IAlternateMenuButton; import ru.kutu.grind.views.api.IBufferInfo; import ru.kutu.grind.views.api.IControlBarMenuButtonHide; import ru.kutu.grind.views.api.IControlBarView; import ru.kutu.grind.views.api.IFullScreenButton; import ru.kutu.grind.views.api.IFullScreenState; import ru.kutu.grind.views.api.IMainView; import ru.kutu.grind.views.api.IPlayPauseButton; import ru.kutu.grind.views.api.IPlayerView; import ru.kutu.grind.views.api.IQualityMenuButton; import ru.kutu.grind.views.api.IScrubBar; import ru.kutu.grind.views.api.IScrubBarTip; import ru.kutu.grind.views.api.IStatInfo; import ru.kutu.grind.views.api.ITimeInfo; import ru.kutu.grind.views.api.IVolumeComponent; import ru.kutu.grind.views.mediators.AlternateMenuBaseMediator; import ru.kutu.grind.views.mediators.ControlBarBaseMediator; import ru.kutu.grind.views.mediators.ControlBarMenuHideBaseMediator; import ru.kutu.grind.views.mediators.FullScreenStateMediator; import ru.kutu.grind.views.mediators.FullscreenButtonBaseMediator; import ru.kutu.grind.views.mediators.MainViewBaseMediator; import ru.kutu.grind.views.mediators.PlayPauseButtonBaseMediator; import ru.kutu.grind.views.mediators.QualityMenuBaseMediator; import ru.kutu.grind.views.mediators.ScrubBarTipBaseMediator; import ru.kutu.grind.views.mediators.TimeInfoBaseMediator; import ru.kutu.grind.views.mediators.VolumeComponentBaseMediator; import ru.kutu.grindplayer.media.GrindMediaPlayer; import ru.kutu.grindplayer.views.components.Subtitles; import ru.kutu.grindplayer.views.mediators.AutoHideMediator; import ru.kutu.grindplayer.views.mediators.BufferInfoMediator; import ru.kutu.grindplayer.views.mediators.PlayerViewMediator; import ru.kutu.grindplayer.views.mediators.ScrubBarMediator; import ru.kutu.grindplayer.views.mediators.ScrubBarMinimizedMediator; import ru.kutu.grindplayer.views.mediators.ShortcutsMediator; import ru.kutu.grindplayer.views.mediators.StatInfoMediator; import ru.kutu.grindplayer.views.mediators.SubtitlesMediator; import ru.kutu.grindplayer.views.mediators.SubtitlesMenuMediator; import ru.kutu.grindplayer.views.mediators.api.IScrubBarMinimized; import ru.kutu.grindplayer.views.mediators.api.ISubtitlesMenuButton; import spark.components.Application; public class AppConfig extends GrindConfig { [Inject] public var contextView:ContextView; [Inject] public var mediatorMap:IMediatorMap; [Inject] public var logger:ILogger; override public function configure():void { super.configure(); Application(contextView.view).focusManager.deactivate(); injector.map(LocalSettings).asSingleton(); injector.map(JavaScriptBridgeBase).toSingleton(JavaScriptBridge); mediatorMap.map(IMainView).toMediator(MainViewBaseMediator); mediatorMap.map(IPlayerView).toMediator(PlayerViewMediator); mediatorMap.map(IPlayerView).toMediator(AutoHideMediator); mediatorMap.map(IPlayerView).toMediator(ShortcutsMediator); mediatorMap.map(Subtitles).toMediator(SubtitlesMediator); mediatorMap.map(IControlBarView).toMediator(ControlBarBaseMediator); mediatorMap.map(IBufferInfo).toMediator(BufferInfoMediator); mediatorMap.map(IStatInfo).toMediator(StatInfoMediator); mediatorMap.map(IScrubBar).toMediator(ScrubBarMediator); mediatorMap.map(IScrubBarTip).toMediator(ScrubBarTipBaseMediator); mediatorMap.map(IScrubBarMinimized).toMediator(ScrubBarMinimizedMediator); mediatorMap.map(IPlayPauseButton).toMediator(PlayPauseButtonBaseMediator); mediatorMap.map(IVolumeComponent).toMediator(VolumeComponentBaseMediator); mediatorMap.map(ITimeInfo).toMediator(TimeInfoBaseMediator); mediatorMap.map(IControlBarMenuButtonHide).toMediator(ControlBarMenuHideBaseMediator); mediatorMap.map(ISubtitlesMenuButton).toMediator(SubtitlesMenuMediator); mediatorMap.map(IAlternateMenuButton).toMediator(AlternateMenuBaseMediator); mediatorMap.map(IQualityMenuButton).toMediator(QualityMenuBaseMediator); mediatorMap.map(IFullScreenButton).toMediator(FullscreenButtonBaseMediator); mediatorMap.map(IFullScreenState).toMediator(FullScreenStateMediator); } override protected function configuration():void { injector.map(PlayerConfiguration).toSingleton(GrindPlayerConfiguration); injector.map(MediaPlayer).toSingleton(GrindMediaPlayer); injector.map(MediaResourceBase).toProvider(new ResourceProvider()); injector.map(MediaFactory).toSingleton(GrindMediaFactoryBase); injector.map(ConfigurationProxy).toProvider(new ConfigurationProxyProvider()); injector.map(ConfigurationFlashvarsDeserializer).toValue( new ConfigurationFlashvarsDeserializer( injector.getInstance(ConfigurationProxy) )); injector.map(ConfigurationXMLDeserializer).toValue( new ConfigurationXMLDeserializer( injector.getInstance(ConfigurationProxy) )); injector.map(ConfigurationLoader).toValue( new ConfigurationLoader( injector.getInstance(ConfigurationFlashvarsDeserializer), injector.getInstance(ConfigurationXMLDeserializer) )); } } }
package ru.kutu.grindplayer.config { import org.osmf.media.MediaFactory; import org.osmf.media.MediaPlayer; import org.osmf.media.MediaResourceBase; import org.osmf.player.configuration.ConfigurationFlashvarsDeserializer; import org.osmf.player.configuration.ConfigurationLoader; import org.osmf.player.configuration.ConfigurationProxy; import org.osmf.player.configuration.ConfigurationXMLDeserializer; import robotlegs.bender.extensions.contextView.ContextView; import robotlegs.bender.extensions.mediatorMap.api.IMediatorMap; import robotlegs.bender.framework.api.ILogger; import ru.kutu.grind.config.ConfigurationProxyProvider; import ru.kutu.grind.config.GrindConfig; import ru.kutu.grind.config.JavaScriptBridgeBase; import ru.kutu.grind.config.LocalSettings; import ru.kutu.grind.config.PlayerConfiguration; import ru.kutu.grind.config.ResourceProvider; import ru.kutu.grind.media.GrindMediaFactoryBase; import ru.kutu.grind.utils.Thumbnails; import ru.kutu.grind.views.api.IAlternateMenuButton; import ru.kutu.grind.views.api.IBufferInfo; import ru.kutu.grind.views.api.IControlBarMenuButtonHide; import ru.kutu.grind.views.api.IControlBarView; import ru.kutu.grind.views.api.IFullScreenButton; import ru.kutu.grind.views.api.IFullScreenState; import ru.kutu.grind.views.api.IMainView; import ru.kutu.grind.views.api.IPlayPauseButton; import ru.kutu.grind.views.api.IPlayerView; import ru.kutu.grind.views.api.IQualityMenuButton; import ru.kutu.grind.views.api.IScrubBar; import ru.kutu.grind.views.api.IScrubBarTip; import ru.kutu.grind.views.api.IStatInfo; import ru.kutu.grind.views.api.ITimeInfo; import ru.kutu.grind.views.api.IVolumeComponent; import ru.kutu.grind.views.mediators.AlternateMenuBaseMediator; import ru.kutu.grind.views.mediators.ControlBarBaseMediator; import ru.kutu.grind.views.mediators.ControlBarMenuHideBaseMediator; import ru.kutu.grind.views.mediators.FullScreenStateMediator; import ru.kutu.grind.views.mediators.FullscreenButtonBaseMediator; import ru.kutu.grind.views.mediators.MainViewBaseMediator; import ru.kutu.grind.views.mediators.PlayPauseButtonBaseMediator; import ru.kutu.grind.views.mediators.QualityMenuBaseMediator; import ru.kutu.grind.views.mediators.ScrubBarTipBaseMediator; import ru.kutu.grind.views.mediators.TimeInfoBaseMediator; import ru.kutu.grind.views.mediators.VolumeComponentBaseMediator; import ru.kutu.grindplayer.media.GrindMediaPlayer; import ru.kutu.grindplayer.views.components.Subtitles; import ru.kutu.grindplayer.views.mediators.AutoHideMediator; import ru.kutu.grindplayer.views.mediators.BufferInfoMediator; import ru.kutu.grindplayer.views.mediators.PlayerViewMediator; import ru.kutu.grindplayer.views.mediators.ScrubBarMediator; import ru.kutu.grindplayer.views.mediators.ScrubBarMinimizedMediator; import ru.kutu.grindplayer.views.mediators.ShortcutsMediator; import ru.kutu.grindplayer.views.mediators.StatInfoMediator; import ru.kutu.grindplayer.views.mediators.SubtitlesMediator; import ru.kutu.grindplayer.views.mediators.SubtitlesMenuMediator; import ru.kutu.grindplayer.views.mediators.api.IScrubBarMinimized; import ru.kutu.grindplayer.views.mediators.api.ISubtitlesMenuButton; import spark.components.Application; public class AppConfig extends GrindConfig { [Inject] public var contextView:ContextView; [Inject] public var mediatorMap:IMediatorMap; [Inject] public var logger:ILogger; override public function configure():void { super.configure(); Application(contextView.view).focusManager.deactivate(); injector.map(LocalSettings).asSingleton(); injector.map(JavaScriptBridgeBase).toSingleton(JavaScriptBridge); injector.map(Thumbnails).asSingleton(); mediatorMap.map(IMainView).toMediator(MainViewBaseMediator); mediatorMap.map(IPlayerView).toMediator(PlayerViewMediator); mediatorMap.map(IPlayerView).toMediator(AutoHideMediator); mediatorMap.map(IPlayerView).toMediator(ShortcutsMediator); mediatorMap.map(Subtitles).toMediator(SubtitlesMediator); mediatorMap.map(IControlBarView).toMediator(ControlBarBaseMediator); mediatorMap.map(IBufferInfo).toMediator(BufferInfoMediator); mediatorMap.map(IStatInfo).toMediator(StatInfoMediator); mediatorMap.map(IScrubBar).toMediator(ScrubBarMediator); mediatorMap.map(IScrubBarTip).toMediator(ScrubBarTipBaseMediator); mediatorMap.map(IScrubBarMinimized).toMediator(ScrubBarMinimizedMediator); mediatorMap.map(IPlayPauseButton).toMediator(PlayPauseButtonBaseMediator); mediatorMap.map(IVolumeComponent).toMediator(VolumeComponentBaseMediator); mediatorMap.map(ITimeInfo).toMediator(TimeInfoBaseMediator); mediatorMap.map(IControlBarMenuButtonHide).toMediator(ControlBarMenuHideBaseMediator); mediatorMap.map(ISubtitlesMenuButton).toMediator(SubtitlesMenuMediator); mediatorMap.map(IAlternateMenuButton).toMediator(AlternateMenuBaseMediator); mediatorMap.map(IQualityMenuButton).toMediator(QualityMenuBaseMediator); mediatorMap.map(IFullScreenButton).toMediator(FullscreenButtonBaseMediator); mediatorMap.map(IFullScreenState).toMediator(FullScreenStateMediator); } override protected function configuration():void { injector.map(PlayerConfiguration).toSingleton(GrindPlayerConfiguration); injector.map(MediaPlayer).toSingleton(GrindMediaPlayer); injector.map(MediaResourceBase).toProvider(new ResourceProvider()); injector.map(MediaFactory).toSingleton(GrindMediaFactoryBase); injector.map(ConfigurationProxy).toProvider(new ConfigurationProxyProvider()); injector.map(ConfigurationFlashvarsDeserializer).toValue( new ConfigurationFlashvarsDeserializer( injector.getInstance(ConfigurationProxy) )); injector.map(ConfigurationXMLDeserializer).toValue( new ConfigurationXMLDeserializer( injector.getInstance(ConfigurationProxy) )); injector.map(ConfigurationLoader).toValue( new ConfigurationLoader( injector.getInstance(ConfigurationFlashvarsDeserializer), injector.getInstance(ConfigurationXMLDeserializer) )); } } }
make Thumbnails extensible
make Thumbnails extensible
ActionScript
mit
kutu/GrindPlayer
fe3a4fae9285d8801fc35b13af431f897c3c6f5d
src/aerys/minko/type/clone/CloneOptions.as
src/aerys/minko/type/clone/CloneOptions.as
package aerys.minko.type.clone { import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.AnimationController; import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.controller.mesh.VisibilityController; import aerys.minko.scene.controller.mesh.skinning.SkinningController; public class CloneOptions { private var _clonedControllerTypes : Vector.<Class> = new <Class>[]; private var _ignoredControllerTypes : Vector.<Class> = new <Class>[]; private var _reassignedControllerTypes : Vector.<Class> = new <Class>[]; private var _defaultControllerAction : uint = ControllerCloneAction.REASSIGN; public function get defaultControllerAction() : uint { return _defaultControllerAction; } public function set defaultControllerAction(v : uint) : void { if (v != ControllerCloneAction.CLONE && v != ControllerCloneAction.IGNORE && v != ControllerCloneAction.REASSIGN) throw new Error('Unknown action type.'); _defaultControllerAction = v; } public function CloneOptions() { } public static function get defaultOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._clonedControllerTypes.push(AnimationController, SkinningController); cloneOptions._ignoredControllerTypes.push(VisibilityController, CameraController); cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN; return cloneOptions; } public static function get cloneAllOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._ignoredControllerTypes.push(VisibilityController, CameraController); cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE; return cloneOptions; } public function addControllerAction(controllerClass : Class, action : uint) : void { switch (action) { case ControllerCloneAction.CLONE: _clonedControllerTypes.push(controllerClass); break; case ControllerCloneAction.IGNORE: _ignoredControllerTypes.push(controllerClass); break; case ControllerCloneAction.REASSIGN: _reassignedControllerTypes.push(controllerClass); break; default: throw new Error('Unknown action type.'); } } public function removeControllerAction(controllerClass : Class) : void { throw new Error('Implement me.'); } public function getActionForController(controller : AbstractController) : uint { var numControllersToClone : uint = _clonedControllerTypes.length; var numControllersToIgnore : uint = _ignoredControllerTypes.length; var numControllersToReassign : uint = _reassignedControllerTypes.length; var controllerId : uint; for (controllerId = 0; controllerId < numControllersToClone; ++controllerId) if (controller is _clonedControllerTypes[controllerId]) return ControllerCloneAction.CLONE; for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId) if (controller is _ignoredControllerTypes[controllerId]) return ControllerCloneAction.IGNORE; for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId) if (controller is _reassignedControllerTypes[controllerId]) return ControllerCloneAction.REASSIGN; return _defaultControllerAction; } } }
package aerys.minko.type.clone { import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.AnimationController; import aerys.minko.scene.controller.TransformController; import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.controller.mesh.VisibilityController; import aerys.minko.scene.controller.mesh.skinning.SkinningController; public class CloneOptions { private var _clonedControllerTypes : Vector.<Class> = new <Class>[]; private var _ignoredControllerTypes : Vector.<Class> = new <Class>[]; private var _reassignedControllerTypes : Vector.<Class> = new <Class>[]; private var _defaultControllerAction : uint = ControllerCloneAction.REASSIGN; public function get defaultControllerAction() : uint { return _defaultControllerAction; } public function set defaultControllerAction(v : uint) : void { if (v != ControllerCloneAction.CLONE && v != ControllerCloneAction.IGNORE && v != ControllerCloneAction.REASSIGN) throw new Error('Unknown action type.'); _defaultControllerAction = v; } public function CloneOptions() { } public static function get defaultOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._clonedControllerTypes.push( AnimationController, SkinningController ); cloneOptions._ignoredControllerTypes.push( VisibilityController, CameraController, TransformController ); cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN; return cloneOptions; } public static function get cloneAllOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._ignoredControllerTypes.push(VisibilityController, CameraController); cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE; return cloneOptions; } public function addControllerAction(controllerClass : Class, action : uint) : void { switch (action) { case ControllerCloneAction.CLONE: _clonedControllerTypes.push(controllerClass); break; case ControllerCloneAction.IGNORE: _ignoredControllerTypes.push(controllerClass); break; case ControllerCloneAction.REASSIGN: _reassignedControllerTypes.push(controllerClass); break; default: throw new Error('Unknown action type.'); } } public function removeControllerAction(controllerClass : Class) : void { throw new Error('Implement me.'); } public function getActionForController(controller : AbstractController) : uint { var numControllersToClone : uint = _clonedControllerTypes.length; var numControllersToIgnore : uint = _ignoredControllerTypes.length; var numControllersToReassign : uint = _reassignedControllerTypes.length; var controllerId : uint; for (controllerId = 0; controllerId < numControllersToClone; ++controllerId) if (controller is _clonedControllerTypes[controllerId]) return ControllerCloneAction.CLONE; for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId) if (controller is _ignoredControllerTypes[controllerId]) return ControllerCloneAction.IGNORE; for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId) if (controller is _reassignedControllerTypes[controllerId]) return ControllerCloneAction.REASSIGN; return _defaultControllerAction; } } }
fix CloneOptions to ignore the TransformController
fix CloneOptions to ignore the TransformController
ActionScript
mit
aerys/minko-as3
5ea2fefddeb6cd9681f0e8bdc2fd5c7214105327
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
package dolly { import dolly.core.dolly_internal; import dolly.data.CompositeCloneableClass; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertNotNull; use namespace dolly_internal; public class CloningOfCompositeCloneableClassTest { private var compositeCloneableClass:CompositeCloneableClass; private var compositeCloneableClassType:Type; [Before] public function before():void { compositeCloneableClass = new CompositeCloneableClass(); compositeCloneableClassType = Type.forInstance(compositeCloneableClass); } [After] public function after():void { compositeCloneableClass = null; compositeCloneableClassType = null; } [Test] public function findingAllWritableFieldsForType():void { const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType); assertNotNull(writableFields); assertEquals(4, writableFields.length); } } }
package dolly { import dolly.core.dolly_internal; import dolly.data.CompositeCloneableClass; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertFalse; import org.flexunit.asserts.assertNotNull; import org.hamcrest.assertThat; import org.hamcrest.collection.array; import org.hamcrest.collection.arrayWithSize; import org.hamcrest.collection.everyItem; import org.hamcrest.core.isA; import org.hamcrest.object.equalTo; use namespace dolly_internal; public class CloningOfCompositeCloneableClassTest { private var compositeCloneableClass:CompositeCloneableClass; private var compositeCloneableClassType:Type; [Before] public function before():void { compositeCloneableClass = new CompositeCloneableClass(); compositeCloneableClassType = Type.forInstance(compositeCloneableClass); } [After] public function after():void { compositeCloneableClass = null; compositeCloneableClassType = null; } [Test] public function findingAllWritableFieldsForType():void { const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType); assertNotNull(writableFields); assertEquals(4, writableFields.length); } [Test] public function cloningOfArray():void { const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass); assertNotNull(clone.array); assertThat(clone.array, arrayWithSize(5)); assertThat(clone.array, compositeCloneableClass.array); assertFalse(clone.array == compositeCloneableClass.array); assertThat(clone.array, everyItem(isA(Number))); assertThat(clone.array, array(equalTo(0), equalTo(1), equalTo(2), equalTo(3), equalTo(4))); } } }
Test for cloning array in CompositeCloneableClass.
Test for cloning array in CompositeCloneableClass.
ActionScript
mit
Yarovoy/dolly
d3197d6b5c142880fb2c226822c8e4985994bbb4
frameworks/projects/Core/as/src/org/apache/flex/core/Application.as
frameworks/projects/Core/as/src/org/apache/flex/core/Application.as
//////////////////////////////////////////////////////////////////////////////// // // 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.flex.core { import flash.display.DisplayObject; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageQuality; import flash.display.StageScaleMode; import flash.events.Event; import flash.system.ApplicationDomain; import flash.utils.getQualifiedClassName; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.events.MouseEvent; import org.apache.flex.events.utils.MouseEventConverter; import org.apache.flex.utils.MXMLDataInterpreter; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched at startup. Attributes and sub-instances of * the MXML document have been created and assigned. * The component lifecycle is different * than the Flex SDK. There is no creationComplete event. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="initialize", type="org.apache.flex.events.Event")] /** * Dispatched at startup before the instances get created. * Beads can call preventDefault and defer initialization. * This event will be dispatched on every frame until no * listeners call preventDefault(), then the initialize() * method will be called. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="preinitialize", type="org.apache.flex.events.Event")] /** * Dispatched at startup after the initial view has been * put on the display list. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="viewChanged", type="org.apache.flex.events.Event")] /** * Dispatched at startup after the initial view has been * put on the display list. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="applicationComplete", type="org.apache.flex.events.Event")] /** * The Application class is the main class and entry point for a FlexJS * application. This Application class is different than the * Flex SDK's mx:Application or spark:Application in that it does not contain * user interface elements. Those UI elements go in the views. This * Application class expects there to be a main model, a controller, and * an initial view. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class Application extends Sprite implements IStrand, IFlexInfo, IParent, IEventDispatcher { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function Application() { super(); if (stage) { stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; // should be opt-in //stage.quality = StageQuality.HIGH_16X16_LINEAR; } loaderInfo.addEventListener(flash.events.Event.INIT, initHandler); } /** * The document property is used to provide * a property lookup context for non-display objects. * For Application, it points to itself. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var document:Object = this; private function initHandler(event:flash.events.Event):void { if (model is IBead) addBead(model as IBead); if (controller is IBead) addBead(controller as IBead); MouseEventConverter.setupAllConverters(stage); for each (var bead:IBead in beads) addBead(bead); dispatchEvent(new org.apache.flex.events.Event("beadsAdded")); if (dispatchEvent(new org.apache.flex.events.Event("preinitialize", false, true))) initialize(); else addEventListener(flash.events.Event.ENTER_FRAME, enterFrameHandler); } private function enterFrameHandler(event:flash.events.Event):void { if (dispatchEvent(new org.apache.flex.events.Event("preinitialize", false, true))) { removeEventListener(flash.events.Event.ENTER_FRAME, enterFrameHandler); initialize(); } } /** * This method gets called when all preinitialize handlers * no longer call preventDefault(); * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function initialize():void { MXMLDataInterpreter.generateMXMLInstances(this, null, MXMLDescriptor); dispatchEvent(new org.apache.flex.events.Event("initialize")); if (initialView) { initialView.applicationModel = model; if (!isNaN(initialView.percentWidth) && !isNaN(initialView.percentHeight)) initialView.setWidthAndHeight(stage.stageWidth, stage.stageHeight); else if (!isNaN(initialView.percentWidth)) initialView.setWidth(stage.stageWidth); else if (!isNaN(initialView.percentHeight)) initialView.setHeight(stage.stageHeight); this.addElement(initialView); var bgColor:Object = ValuesManager.valuesImpl.getValue(this, "background-color"); if (bgColor != null) { var backgroundColor:uint = ValuesManager.valuesImpl.convertColor(bgColor); graphics.beginFill(backgroundColor); graphics.drawRect(0, 0, initialView.width, initialView.height); graphics.endFill(); } dispatchEvent(new org.apache.flex.events.Event("viewChanged")); } dispatchEvent(new org.apache.flex.events.Event("applicationComplete")); } /** * The org.apache.flex.core.IValuesImpl that will * determine the default values and other values * for the application. The most common choice * is org.apache.flex.core.SimpleCSSValuesImpl. * * @see org.apache.flex.core.SimpleCSSValuesImpl * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set valuesImpl(value:IValuesImpl):void { ValuesManager.valuesImpl = value; ValuesManager.valuesImpl.init(this); } /** * The initial view. * * @see org.apache.flex.core.ViewBase * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var initialView:ViewBase; /** * The data model (for the initial view). * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var model:Object; /** * The controller. The controller typically watches * the UI for events and updates the model accordingly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var controller:Object; /** * An array of data that describes the MXML attributes * and tags in an MXML document. This data is usually * decoded by an MXMLDataInterpreter * * @see org.apache.flex.utils.MXMLDataInterpreter * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get MXMLDescriptor():Array { return null; } /** * An method called by the compiler's generated * code to kick off the setting of MXML attribute * values and instantiation of child tags. * * The call has to be made in the generated code * in order to ensure that the constructors have * completed first. * * @param data The encoded data representing the * MXML attributes. * * @see org.apache.flex.utils.MXMLDataInterpreter * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function generateMXMLAttributes(data:Array):void { MXMLDataInterpreter.generateMXMLProperties(this, data); } /** * The array property that is used to add additional * beads to an MXML tag. From ActionScript, just * call addBead directly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var beads:Array; private var _beads:Vector.<IBead>; /** * @copy org.apache.flex.core.IStrand#addBead() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function addBead(bead:IBead):void { if (!_beads) _beads = new Vector.<IBead>; _beads.push(bead); bead.strand = this; } /** * @copy org.apache.flex.core.IStrand#getBeadByType() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getBeadByType(classOrInterface:Class):IBead { for each (var bead:IBead in _beads) { if (bead is classOrInterface) return bead; } return null; } /** * @copy org.apache.flex.core.IStrand#removeBead() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function removeBead(value:IBead):IBead { var n:int = _beads.length; for (var i:int = 0; i < n; i++) { var bead:IBead = _beads[i]; if (bead == value) { _beads.splice(i, 1); return bead; } } return null; } private var _info:Object; /** * An Object containing information generated * by the compiler that is useful at startup time. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function info():Object { if (!_info) { var mainClassName:String = getQualifiedClassName(this); var initClassName:String = "_" + mainClassName + "_FlexInit"; var c:Class = ApplicationDomain.currentDomain.getDefinition(initClassName) as Class; _info = c.info(); } return _info; } /** * @copy org.apache.flex.core.IParent#addElement() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function addElement(c:Object, dispatchEvent:Boolean = true):void { if (c is IUIBase) { addChild(IUIBase(c).element as DisplayObject); IUIBase(c).addedToParent(); } else addChild(c as DisplayObject); } /** * @copy org.apache.flex.core.IParent#addElementAt() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function addElementAt(c:Object, index:int, dispatchEvent:Boolean = true):void { if (c is IUIBase) { addChildAt(IUIBase(c).element as DisplayObject, index); IUIBase(c).addedToParent(); } else addChildAt(c as DisplayObject, index); } /** * @copy org.apache.flex.core.IParent#getElementAt() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getElementAt(index:int):Object { return getChildAt(index); } /** * @copy org.apache.flex.core.IParent#getElementIndex() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getElementIndex(c:Object):int { if (c is IUIBase) return getChildIndex(IUIBase(c).element as DisplayObject); return getChildIndex(c as DisplayObject); } /** * @copy org.apache.flex.core.IParent#removeElement() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function removeElement(c:Object, dispatchEvent:Boolean = true):void { if (c is IUIBase) { removeChild(IUIBase(c).element as DisplayObject); } else removeChild(c as DisplayObject); } /** * @copy org.apache.flex.core.IParent#numElements * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get numElements():int { return numChildren; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.flex.core { import flash.display.DisplayObject; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageQuality; import flash.display.StageScaleMode; import flash.events.Event; import flash.system.ApplicationDomain; import flash.utils.getQualifiedClassName; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.events.MouseEvent; import org.apache.flex.events.utils.MouseEventConverter; import org.apache.flex.utils.MXMLDataInterpreter; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched at startup. Attributes and sub-instances of * the MXML document have been created and assigned. * The component lifecycle is different * than the Flex SDK. There is no creationComplete event. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="initialize", type="org.apache.flex.events.Event")] /** * Dispatched at startup before the instances get created. * Beads can call preventDefault and defer initialization. * This event will be dispatched on every frame until no * listeners call preventDefault(), then the initialize() * method will be called. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="preinitialize", type="org.apache.flex.events.Event")] /** * Dispatched at startup after the initial view has been * put on the display list. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="viewChanged", type="org.apache.flex.events.Event")] /** * Dispatched at startup after the initial view has been * put on the display list. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="applicationComplete", type="org.apache.flex.events.Event")] /** * The Application class is the main class and entry point for a FlexJS * application. This Application class is different than the * Flex SDK's mx:Application or spark:Application in that it does not contain * user interface elements. Those UI elements go in the views. This * Application class expects there to be a main model, a controller, and * an initial view. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class Application extends Sprite implements IStrand, IFlexInfo, IParent, IEventDispatcher { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function Application() { super(); if (stage) { stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; // should be opt-in //stage.quality = StageQuality.HIGH_16X16_LINEAR; } loaderInfo.addEventListener(flash.events.Event.INIT, initHandler); } /** * The document property is used to provide * a property lookup context for non-display objects. * For Application, it points to itself. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var document:Object = this; private function initHandler(event:flash.events.Event):void { if (model is IBead) addBead(model as IBead); if (controller is IBead) addBead(controller as IBead); MouseEventConverter.setupAllConverters(stage); for each (var bead:IBead in beads) addBead(bead); dispatchEvent(new org.apache.flex.events.Event("beadsAdded")); if (dispatchEvent(new org.apache.flex.events.Event("preinitialize", false, true))) initialize(); else addEventListener(flash.events.Event.ENTER_FRAME, enterFrameHandler); } private function enterFrameHandler(event:flash.events.Event):void { if (dispatchEvent(new org.apache.flex.events.Event("preinitialize", false, true))) { removeEventListener(flash.events.Event.ENTER_FRAME, enterFrameHandler); initialize(); } } /** * This method gets called when all preinitialize handlers * no longer call preventDefault(); * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function initialize():void { MXMLDataInterpreter.generateMXMLInstances(this, null, MXMLDescriptor); dispatchEvent(new org.apache.flex.events.Event("initialize")); if (initialView) { initialView.applicationModel = model; this.addElement(initialView); if (!isNaN(initialView.percentWidth) && !isNaN(initialView.percentHeight)) initialView.setWidthAndHeight(stage.stageWidth, stage.stageHeight, true); else if (!isNaN(initialView.percentWidth)) initialView.setWidth(stage.stageWidth); else if (!isNaN(initialView.percentHeight)) initialView.setHeight(stage.stageHeight); var bgColor:Object = ValuesManager.valuesImpl.getValue(this, "background-color"); if (bgColor != null) { var backgroundColor:uint = ValuesManager.valuesImpl.convertColor(bgColor); graphics.beginFill(backgroundColor); graphics.drawRect(0, 0, initialView.width, initialView.height); graphics.endFill(); } dispatchEvent(new org.apache.flex.events.Event("viewChanged")); } dispatchEvent(new org.apache.flex.events.Event("applicationComplete")); } /** * The org.apache.flex.core.IValuesImpl that will * determine the default values and other values * for the application. The most common choice * is org.apache.flex.core.SimpleCSSValuesImpl. * * @see org.apache.flex.core.SimpleCSSValuesImpl * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set valuesImpl(value:IValuesImpl):void { ValuesManager.valuesImpl = value; ValuesManager.valuesImpl.init(this); } /** * The initial view. * * @see org.apache.flex.core.ViewBase * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var initialView:ViewBase; /** * The data model (for the initial view). * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var model:Object; /** * The controller. The controller typically watches * the UI for events and updates the model accordingly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var controller:Object; /** * An array of data that describes the MXML attributes * and tags in an MXML document. This data is usually * decoded by an MXMLDataInterpreter * * @see org.apache.flex.utils.MXMLDataInterpreter * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get MXMLDescriptor():Array { return null; } /** * An method called by the compiler's generated * code to kick off the setting of MXML attribute * values and instantiation of child tags. * * The call has to be made in the generated code * in order to ensure that the constructors have * completed first. * * @param data The encoded data representing the * MXML attributes. * * @see org.apache.flex.utils.MXMLDataInterpreter * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function generateMXMLAttributes(data:Array):void { MXMLDataInterpreter.generateMXMLProperties(this, data); } /** * The array property that is used to add additional * beads to an MXML tag. From ActionScript, just * call addBead directly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var beads:Array; private var _beads:Vector.<IBead>; /** * @copy org.apache.flex.core.IStrand#addBead() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function addBead(bead:IBead):void { if (!_beads) _beads = new Vector.<IBead>; _beads.push(bead); bead.strand = this; } /** * @copy org.apache.flex.core.IStrand#getBeadByType() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getBeadByType(classOrInterface:Class):IBead { for each (var bead:IBead in _beads) { if (bead is classOrInterface) return bead; } return null; } /** * @copy org.apache.flex.core.IStrand#removeBead() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function removeBead(value:IBead):IBead { var n:int = _beads.length; for (var i:int = 0; i < n; i++) { var bead:IBead = _beads[i]; if (bead == value) { _beads.splice(i, 1); return bead; } } return null; } private var _info:Object; /** * An Object containing information generated * by the compiler that is useful at startup time. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function info():Object { if (!_info) { var mainClassName:String = getQualifiedClassName(this); var initClassName:String = "_" + mainClassName + "_FlexInit"; var c:Class = ApplicationDomain.currentDomain.getDefinition(initClassName) as Class; _info = c.info(); } return _info; } /** * @copy org.apache.flex.core.IParent#addElement() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function addElement(c:Object, dispatchEvent:Boolean = true):void { if (c is IUIBase) { addChild(IUIBase(c).element as DisplayObject); IUIBase(c).addedToParent(); } else addChild(c as DisplayObject); } /** * @copy org.apache.flex.core.IParent#addElementAt() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function addElementAt(c:Object, index:int, dispatchEvent:Boolean = true):void { if (c is IUIBase) { addChildAt(IUIBase(c).element as DisplayObject, index); IUIBase(c).addedToParent(); } else addChildAt(c as DisplayObject, index); } /** * @copy org.apache.flex.core.IParent#getElementAt() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getElementAt(index:int):Object { return getChildAt(index); } /** * @copy org.apache.flex.core.IParent#getElementIndex() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getElementIndex(c:Object):int { if (c is IUIBase) return getChildIndex(IUIBase(c).element as DisplayObject); return getChildIndex(c as DisplayObject); } /** * @copy org.apache.flex.core.IParent#removeElement() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function removeElement(c:Object, dispatchEvent:Boolean = true):void { if (c is IUIBase) { removeChild(IUIBase(c).element as DisplayObject); } else removeChild(c as DisplayObject); } /** * @copy org.apache.flex.core.IParent#numElements * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get numElements():int { return numChildren; } } }
fix percent size handling
fix percent size handling
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
1b054677c282dae3dc5f272ce99ec24de04a9d2b
src/as/com/threerings/util/ValueEvent.as
src/as/com/threerings/util/ValueEvent.as
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { import flash.events.Event; /** * A handy event for simply dispatching a value associated with the event type. */ public class ValueEvent extends Event { /** * Accessor: get the value. */ public function get value () :Object { return _value; } /** * Construct the value event. */ public function ValueEvent (type :String, value :Object) { super(type); _value = value; } override public function clone () :Event { return new ValueEvent(type, _value); } /** The value. */ protected var _value :Object; } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { import flash.events.Event; /** * A handy event for simply dispatching a value associated with the event type. */ public class ValueEvent extends Event { /** * Accessor: get the value. */ public function get value () :Object { return _value; } /** * Construct the value event. */ public function ValueEvent ( type :String, value :Object, bubbles :Boolean = false, cancelable :Boolean = false) { super(type, bubbles, cancelable); _value = value; } override public function clone () :Event { return new ValueEvent(type, _value, bubbles, cancelable); } /** The value. */ protected var _value :Object; } }
Allow ValueEvents to be cancelable.
Allow ValueEvents to be cancelable. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4898 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
12ed7065f523247bd107c2b03cc087d89d9177c3
test/trace/trace_properties.as
test/trace/trace_properties.as
#if __SWF_VERSION__ == 5 // create a _global object, since it doesn't have one, these are ver 6 values _global = new_empty_object (); _global.ASSetNative = ASSetNative; _global.ASSetNativeAccessor = ASSetNativeAccessor; _global.ASSetPropFlags = ASSetPropFlags; _global.ASconstructor = ASconstructor; _global.ASnative = ASnative; _global.Accessibility = Accessibility; _global.Array = Array; _global.AsBroadcaster = AsBroadcaster; _global.AsSetupError = AsSetupError; _global.Boolean = Boolean; _global.Button = Button; _global.Camera = Camera; _global.Color = Color; _global.ContextMenu = ContextMenu; _global.ContextMenuItem = ContextMenuItem; _global.Date = Date; _global.Error = Error; _global.Function = Function; _global.Infinity = Infinity; _global.Key = Key; _global.LoadVars = LoadVars; _global.LocalConnection = LocalConnection; _global.Math = Math; _global.Microphone = Microphone; _global.Mouse = Mouse; _global.MovieClip = MovieClip; _global.MovieClipLoader = MovieClipLoader; _global.NaN = NaN; _global.NetConnection = NetConnection; _global.NetStream = NetStream; _global.Number = Number; _global.Object = Object; _global.PrintJob = PrintJob; _global.RemoteLSOUsage = RemoteLSOUsage; _global.Selection = Selection; _global.SharedObject = SharedObject; _global.Sound = Sound; _global.Stage = Stage; _global.String = String; _global.System = System; _global.TextField = TextField; _global.TextFormat = TextFormat; _global.TextSnapshot = TextSnapshot; _global.Video = Video; _global.XML = XML; _global.XMLNode = XMLNode; _global.XMLSocket = XMLSocket; _global.clearInterval = clearInterval; _global.clearTimeout = clearTimeout; _global.enableDebugConsole = enableDebugConsole; _global.escape = escape; _global.flash = flash; _global.isFinite = isFinite; _global.isNaN = isNaN; _global.o = o; _global.parseFloat = parseFloat; _global.parseInt = parseInt; _global.setInterval = setInterval; _global.setTimeout = setTimeout; _global.showRedrawRegions = showRedrawRegions; _global.textRenderer = textRenderer; _global.trace = trace; _global.unescape = unescape; _global.updateAfterEvent = updateAfterEvent; #endif function new_empty_object () { var hash = new Object (); ASSetPropFlags (hash, null, 0, 7); for (var prop in hash) { hash[prop] = "to-be-deleted"; delete hash[prop]; } return hash; } #if __SWF_VERSION__ >= 6 function hasOwnProperty (o, prop) { if (o.hasOwnProperty != undefined) return o.hasOwnProperty (prop); o.hasOwnProperty = _global.Object.prototype.hasOwnProperty; var result = o.hasOwnProperty (prop); delete o.hasOwnProperty; return result; } #else // this gets the same result as the above, with following limitations: // - if there is a child __proto__[prop] with value that can't be changed, no // test can be done and false is returned // - native properties that have value undefined by default get overwritten by // __proto__[prop]'s value (atleast in version 6 and 7) so their existance // won't be detected by this function function hasOwnProperty (o, prop) { if (o.__proto__ == undefined) { o.__proto__ = new_empty_object (); o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa"; if (o[prop] != o.__proto__[prop]) { result = true; } else { result = false; } o.__proto__ = "to-be-deleted"; delete o.__proto__; if (o.__proto__ != undefined) { trace ("ERROR: Couldn't delete temporary __proto__"); o.__proto__ = undefined; } return result; } if (hasOwnProperty (o.__proto__, prop)) { var constant = false; var old = o.__proto__[prop]; o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa"; if (o.__proto__[prop] != "safdlojasfljsaiofhiwjhefa") { constant = true; ASSetPropFlags (o.__proto__, prop, 0, 4); o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa"; if (o.__proto__[prop] != "safdlojasfljsaiofhiwjhefa") { if (o[prop] != o.__proto__[prop]) { return true; } else { trace ("ERROR: can't test property '" + prop + "', __proto__ has superconstant version"); return false; } } } if (o[prop] != o.__proto__[prop]) { result = true; } else { result = false; } o.__proto__[prop] = old; if (o.__proto__[prop] != old) trace ("Error: Couldn't set __proto__[\"" + prop + "\"] back to old value"); if (constant) ASSetPropFlags (o.__proto__, prop, 4); return result; } else { o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa"; if (o[prop] != o.__proto__[prop]) { result = true; } else { result = false; } ASSetPropFlags (o, prop, 0, 4); o.__proto__[prop] = "to-be-deleted"; delete o.__proto__[prop]; if (o.__proto__[prop] != undefined) trace ("ERROR: Couldn't delete temporary __proto__[\"" + prop + "\"]"); return result; } } #endif function new_info () { return new_empty_object (); } function set_info (info, prop, id, value) { info[prop + "_-_" + id] = value; } function get_info (info, prop, id) { return info[prop + "_-_" + id]; } function is_blaclisted (o, prop) { if (prop == "mySecretId" || prop == "globalSecretId") return true; if (o == _global.Camera && prop == "names") return true; if (o == _global.Microphone && prop == "names") return true; #if __SWF_VERSION__ < 6 if (prop == "__proto__" && o[prop] == undefined) return true; #endif return false; } function trace_properties_recurse (o, prefix, identifier, level) { // to collect info about different properties var info = new_info (); // calculate indentation var indentation = ""; for (var j = 0; j < level; j++) { indentation = indentation + " "; } // mark the ones that are not hidden for (var prop in o) { // only get the ones that are not only in the __proto__ if (is_blaclisted (o, prop) == false) { if (hasOwnProperty (o, prop) == true) set_info (info, prop, "hidden", false); } } // unhide everything ASSetPropFlags (o, null, 0, 1); var all = new Array (); var hidden = new Array (); for (var prop in o) { // only get the ones that are not only in the __proto__ if (is_blaclisted (o, prop) == false) { if (hasOwnProperty (o, prop) == true) { all.push (prop); if (get_info (info, prop, "hidden") != false) { set_info (info, prop, "hidden", true); hidden.push (prop); } } } } all.sort (); // hide the ones that were already hidden ASSetPropFlags (o, hidden, 1, 0); if (all.length == 0) { trace (indentation + "no children"); return nextSecretId; } for (var i = 0; i < all.length; i++) { var prop = all[i]; // try changing value var old = o[prop]; var val = "hello " + o[prop]; o[prop] = val; if (o[prop] != val) { set_info (info, prop, "constant", true); // try changing value after removing constant propflag ASSetPropFlags (o, prop, 0, 4); o[prop] = val; if (o[prop] != val) { set_info (info, prop, "superconstant", true); } else { set_info (info, prop, "superconstant", false); o[prop] = old; } ASSetPropFlags (o, prop, 4); } else { set_info (info, prop, "constant", false); set_info (info, prop, "superconstant", false); o[prop] = old; } } for (var i = 0; i < all.length; i++) { var prop = all[i]; // remove constant flag ASSetPropFlags (o, prop, 0, 4); // try deleting var old = o[prop]; delete o[prop]; if (hasOwnProperty (o, prop)) { set_info (info, prop, "permanent", true); } else { set_info (info, prop, "permanent", false); o[prop] = old; } // put constant flag back, if it was set if (get_info (info, prop, "constant") == true) ASSetPropFlags (o, prop, 4); } for (var i = 0; i < all.length; i++) { var prop = all[i]; // format propflags var flags = ""; if (get_info (info, prop, "hidden") == true) { flags += "h"; } if (get_info (info, prop, "superpermanent") == true) { flags += "P"; } else if (get_info (info, prop, "permanent") == true) { flags += "p"; } if (get_info (info, prop, "superconstant") == true) { flags += "C"; } else if (get_info (info, prop, "constant") == true) { flags += "c"; } if (flags != "") flags = " (" + flags + ")"; var value = ""; // add value depending on the type if (typeof (o[prop]) == "number" || typeof (o[prop]) == "boolean") { value += " : " + o[prop]; } else if (typeof (o[prop]) == "string") { value += " : \"" + o[prop] + "\""; } // recurse if it's object or function and this is the place it has been // named after if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") { if (prefix + (prefix != "" ? "." : "") + identifier + "." + prop == o[prop]["mySecretId"]) { trace (indentation + prop + flags + " = " + typeof (o[prop])); trace_properties_recurse (o[prop], prefix + (prefix != "" ? "." : "") + identifier, prop, level + 1); } else { trace (indentation + prop + flags + " = " + o[prop]["mySecretId"]); } } else { trace (indentation + prop + flags + " = " + typeof (o[prop]) + value); } } } function generate_names (o, prefix, identifier) { // mark the ones that are not hidden var nothidden = new Array (); for (var prop in o) { nothidden.push (prop); } // unhide everything ASSetPropFlags (o, null, 0, 1); var all = new Array (); for (var prop in o) { if (is_blaclisted (o, prop) == false) { // only get the ones that are not only in the __proto__ if (hasOwnProperty (o, prop) == true) { all.push (prop); } } } all.sort (); // hide the ones that were already hidden ASSetPropFlags (o, null, 1, 0); ASSetPropFlags (o, nothidden, 0, 1); for (var i = 0; i < all.length; i++) { var prop = all[i]; if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") { if (hasOwnProperty (o[prop], "mySecretId")) { all[i] = null; // don't recurse to it again } else { o[prop]["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier + "." + prop; } } } for (var i = 0; i < all.length; i++) { var prop = all[i]; if (prop != null) { if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") generate_names (o[prop], prefix + (prefix != "" ? "." : "") + identifier, prop); } } } function trace_properties (o, prefix, identifier) { _global["mySecretId"] = "_global"; _global.Object["mySecretId"] = "_global.Object"; generate_names (_global.Object, "_global", "Object"); generate_names (_global, "", "_global"); if (typeof (o) == "object" || typeof (o) == "function") { if (o["mySecretId"] == undefined) { o["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier; generate_names (o, prefix, identifier); } if (prefix + (prefix != "" ? "." : "") + identifier == o["mySecretId"]) { trace (prefix + (prefix != "" ? "." : "") + identifier + " = " + typeof (o)); } else { trace (prefix + (prefix != "" ? "." : "") + identifier + " = " + o["mySecretId"]); } trace_properties_recurse (o, prefix, identifier, 1); } else { var value = ""; if (typeof (o) == "number" || typeof (o) == "boolean") { value += " : " + o; } else if (typeof (o) == "string") { value += " : \"" + o + "\""; } trace (prefix + (prefix != "" ? "." : "") + identifier + " = " + typeof (o) + value); } }
#if __SWF_VERSION__ == 5 // create a _global object, since it doesn't have one, these are ver 6 values _global = new_empty_object (); _global.ASSetNative = ASSetNative; _global.ASSetNativeAccessor = ASSetNativeAccessor; _global.ASSetPropFlags = ASSetPropFlags; _global.ASconstructor = ASconstructor; _global.ASnative = ASnative; _global.Accessibility = Accessibility; _global.Array = Array; _global.AsBroadcaster = AsBroadcaster; _global.AsSetupError = AsSetupError; _global.Boolean = Boolean; _global.Button = Button; _global.Camera = Camera; _global.Color = Color; _global.ContextMenu = ContextMenu; _global.ContextMenuItem = ContextMenuItem; _global.Date = Date; _global.Error = Error; _global.Function = Function; _global.Infinity = Infinity; _global.Key = Key; _global.LoadVars = LoadVars; _global.LocalConnection = LocalConnection; _global.Math = Math; _global.Microphone = Microphone; _global.Mouse = Mouse; _global.MovieClip = MovieClip; _global.MovieClipLoader = MovieClipLoader; _global.NaN = NaN; _global.NetConnection = NetConnection; _global.NetStream = NetStream; _global.Number = Number; _global.Object = Object; _global.PrintJob = PrintJob; _global.RemoteLSOUsage = RemoteLSOUsage; _global.Selection = Selection; _global.SharedObject = SharedObject; _global.Sound = Sound; _global.Stage = Stage; _global.String = String; _global.System = System; _global.TextField = TextField; _global.TextFormat = TextFormat; _global.TextSnapshot = TextSnapshot; _global.Video = Video; _global.XML = XML; _global.XMLNode = XMLNode; _global.XMLSocket = XMLSocket; _global.clearInterval = clearInterval; _global.clearTimeout = clearTimeout; _global.enableDebugConsole = enableDebugConsole; _global.escape = escape; _global.flash = flash; _global.isFinite = isFinite; _global.isNaN = isNaN; _global.o = o; _global.parseFloat = parseFloat; _global.parseInt = parseInt; _global.setInterval = setInterval; _global.setTimeout = setTimeout; _global.showRedrawRegions = showRedrawRegions; _global.textRenderer = textRenderer; _global.trace = trace; _global.unescape = unescape; _global.updateAfterEvent = updateAfterEvent; #endif function new_empty_object () { var hash = new Object (); ASSetPropFlags (hash, null, 0, 7); for (var prop in hash) { hash[prop] = "to-be-deleted"; delete hash[prop]; } return hash; } #if __SWF_VERSION__ >= 6 function hasOwnProperty (o, prop) { if (o.hasOwnProperty != undefined) return o.hasOwnProperty (prop); o.hasOwnProperty = _global.Object.prototype.hasOwnProperty; var result = o.hasOwnProperty (prop); delete o.hasOwnProperty; return result; } #else // this gets the same result as the above, with following limitations: // - if there is a child __proto__[prop] with value that can't be changed, no // test can be done and false is returned // - native properties that have value undefined by default get overwritten by // __proto__[prop]'s value (atleast in version 6 and 7) so their existance // won't be detected by this function function hasOwnProperty (o, prop) { if (o.__proto__ == undefined) { o.__proto__ = new_empty_object (); o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa"; if (o[prop] != o.__proto__[prop]) { result = true; } else { result = false; } ASSetPropFlags (o, "__proto__", 0, 2); o.__proto__ = "to-be-deleted"; delete o.__proto__; if (o.__proto__ != undefined) { trace ("ERROR: Couldn't delete temporary __proto__"); o.__proto__ = undefined; } return result; } if (hasOwnProperty (o.__proto__, prop)) { var constant = false; var old = o.__proto__[prop]; o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa"; if (o.__proto__[prop] != "safdlojasfljsaiofhiwjhefa") { constant = true; ASSetPropFlags (o.__proto__, prop, 0, 4); o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa"; if (o.__proto__[prop] != "safdlojasfljsaiofhiwjhefa") { if (o[prop] != o.__proto__[prop]) { return true; } else { trace ("ERROR: can't test property '" + prop + "', __proto__ has superconstant version"); return false; } } } if (o[prop] != o.__proto__[prop]) { result = true; } else { result = false; } o.__proto__[prop] = old; if (o.__proto__[prop] != old) trace ("Error: Couldn't set __proto__[\"" + prop + "\"] back to old value"); if (constant) ASSetPropFlags (o.__proto__, prop, 4); return result; } else { o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa"; if (o[prop] != o.__proto__[prop]) { result = true; } else { result = false; } ASSetPropFlags (o, prop, 0, 4); o.__proto__[prop] = "to-be-deleted"; delete o.__proto__[prop]; if (o.__proto__[prop] != undefined) trace ("ERROR: Couldn't delete temporary __proto__[\"" + prop + "\"]"); return result; } } #endif function new_info () { return new_empty_object (); } function set_info (info, prop, id, value) { info[prop + "_-_" + id] = value; } function get_info (info, prop, id) { return info[prop + "_-_" + id]; } function is_blaclisted (o, prop) { if (prop == "mySecretId" || prop == "globalSecretId") return true; if (o == _global.Camera && prop == "names") return true; if (o == _global.Microphone && prop == "names") return true; #if __SWF_VERSION__ < 6 if (prop == "__proto__" && o[prop] == undefined) return true; #endif return false; } function trace_properties_recurse (o, prefix, identifier, level) { // to collect info about different properties var info = new_info (); // calculate indentation var indentation = ""; for (var j = 0; j < level; j++) { indentation = indentation + " "; } // mark the ones that are not hidden for (var prop in o) { // only get the ones that are not only in the __proto__ if (is_blaclisted (o, prop) == false) { if (hasOwnProperty (o, prop) == true) set_info (info, prop, "hidden", false); } } // unhide everything ASSetPropFlags (o, null, 0, 1); var all = new Array (); var hidden = new Array (); for (var prop in o) { // only get the ones that are not only in the __proto__ if (is_blaclisted (o, prop) == false) { if (hasOwnProperty (o, prop) == true) { all.push (prop); if (get_info (info, prop, "hidden") != false) { set_info (info, prop, "hidden", true); hidden.push (prop); } } } } all.sort (); // hide the ones that were already hidden ASSetPropFlags (o, hidden, 1, 0); if (all.length == 0) { trace (indentation + "no children"); return nextSecretId; } for (var i = 0; i < all.length; i++) { var prop = all[i]; // try changing value var old = o[prop]; var val = "hello " + o[prop]; o[prop] = val; if (o[prop] != val) { set_info (info, prop, "constant", true); // try changing value after removing constant propflag ASSetPropFlags (o, prop, 0, 4); o[prop] = val; if (o[prop] != val) { set_info (info, prop, "superconstant", true); } else { set_info (info, prop, "superconstant", false); o[prop] = old; } ASSetPropFlags (o, prop, 4); } else { set_info (info, prop, "constant", false); set_info (info, prop, "superconstant", false); o[prop] = old; } } for (var i = 0; i < all.length; i++) { var prop = all[i]; // remove constant flag ASSetPropFlags (o, prop, 0, 4); // try deleting var old = o[prop]; delete o[prop]; if (hasOwnProperty (o, prop)) { set_info (info, prop, "permanent", true); } else { set_info (info, prop, "permanent", false); o[prop] = old; } // put constant flag back, if it was set if (get_info (info, prop, "constant") == true) ASSetPropFlags (o, prop, 4); } for (var i = 0; i < all.length; i++) { var prop = all[i]; // format propflags var flags = ""; if (get_info (info, prop, "hidden") == true) { flags += "h"; } if (get_info (info, prop, "superpermanent") == true) { flags += "P"; } else if (get_info (info, prop, "permanent") == true) { flags += "p"; } if (get_info (info, prop, "superconstant") == true) { flags += "C"; } else if (get_info (info, prop, "constant") == true) { flags += "c"; } if (flags != "") flags = " (" + flags + ")"; var value = ""; // add value depending on the type if (typeof (o[prop]) == "number" || typeof (o[prop]) == "boolean") { value += " : " + o[prop]; } else if (typeof (o[prop]) == "string") { value += " : \"" + o[prop] + "\""; } // recurse if it's object or function and this is the place it has been // named after if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") { if (prefix + (prefix != "" ? "." : "") + identifier + "." + prop == o[prop]["mySecretId"]) { trace (indentation + prop + flags + " = " + typeof (o[prop])); trace_properties_recurse (o[prop], prefix + (prefix != "" ? "." : "") + identifier, prop, level + 1); } else { trace (indentation + prop + flags + " = " + o[prop]["mySecretId"]); } } else { trace (indentation + prop + flags + " = " + typeof (o[prop]) + value); } } } function generate_names (o, prefix, identifier) { // mark the ones that are not hidden var nothidden = new Array (); for (var prop in o) { nothidden.push (prop); } // unhide everything ASSetPropFlags (o, null, 0, 1); var all = new Array (); for (var prop in o) { if (is_blaclisted (o, prop) == false) { // only get the ones that are not only in the __proto__ if (hasOwnProperty (o, prop) == true) { all.push (prop); } } } all.sort (); // hide the ones that were already hidden ASSetPropFlags (o, null, 1, 0); ASSetPropFlags (o, nothidden, 0, 1); for (var i = 0; i < all.length; i++) { var prop = all[i]; if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") { if (hasOwnProperty (o[prop], "mySecretId")) { all[i] = null; // don't recurse to it again } else { o[prop]["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier + "." + prop; } } } for (var i = 0; i < all.length; i++) { var prop = all[i]; if (prop != null) { if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") generate_names (o[prop], prefix + (prefix != "" ? "." : "") + identifier, prop); } } } function trace_properties (o, prefix, identifier) { _global["mySecretId"] = "_global"; _global.Object["mySecretId"] = "_global.Object"; generate_names (_global.Object, "_global", "Object"); generate_names (_global, "", "_global"); if (typeof (o) == "object" || typeof (o) == "function") { if (o["mySecretId"] == undefined) { o["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier; generate_names (o, prefix, identifier); } if (prefix + (prefix != "" ? "." : "") + identifier == o["mySecretId"]) { trace (prefix + (prefix != "" ? "." : "") + identifier + " = " + typeof (o)); } else { trace (prefix + (prefix != "" ? "." : "") + identifier + " = " + o["mySecretId"]); } trace_properties_recurse (o, prefix, identifier, 1); } else { var value = ""; if (typeof (o) == "number" || typeof (o) == "boolean") { value += " : " + o; } else if (typeof (o) == "string") { value += " : \"" + o + "\""; } trace (prefix + (prefix != "" ? "." : "") + identifier + " = " + typeof (o) + value); } }
set propflags to non-permanent before attempting to delete the property
set propflags to non-permanent before attempting to delete the property
ActionScript
lgpl-2.1
freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec
1aeff994375b0aa491aec1b8d9558e02c47edc49
dorkbots/dorkbots_ui/TruncateTextField.as
dorkbots/dorkbots_ui/TruncateTextField.as
package dorkbots.dorkbots_ui { import flash.text.TextField; public class TruncateTextField { public function TruncateTextField () { } public static function truncateText( textField:TextField, addElipsis:Boolean = true, minimizeLines:uint = 0, ellipsis:String = "\u2026" ):uint { var tempTextField:TextField; var characterRemoveCnt:uint = 0; if ( ! textOverflowing( textField ) ) return characterRemoveCnt; tempTextField = copyTextField( textField ); while( textOverflowing( tempTextField, minimizeLines, ellipsis ) ) { characterRemoveCnt++; tempTextField.text = tempTextField.text.substr( 0, tempTextField.text.length - 1 ); } // Remove any empty spaces and periods at the end while(tempTextField.text.charAt(tempTextField.text.length - 1) == " " || tempTextField.text.charAt(tempTextField.text.length - 1) == ".") { characterRemoveCnt++; tempTextField.text = tempTextField.text.slice(0, -1); // just incase, because while loops make me nervous if (tempTextField.text.length <= 0) break; } tempTextField.appendText( ellipsis ); if (tempTextField.numLines > 1) { // check again, for some reason, adding the ellipsis can increase number of lines while( textOverflowing( tempTextField, minimizeLines, ellipsis ) ) { characterRemoveCnt++; tempTextField.text = tempTextField.text.substr( 0, tempTextField.text.length - ellipsis.length - 1 ); } } tempTextField.appendText( ellipsis ); textField.text = tempTextField.text; return characterRemoveCnt; } private static function textOverflowing( textField:TextField, minimizeLines:uint = 0, suffix:String = null ):Boolean { var margin:Number = 4; //Flash adds this to all textfields; var tempTextField:TextField = copyTextField( textField ); if ( suffix ) tempTextField.appendText( suffix ); if (minimizeLines > 0 && tempTextField.numLines > minimizeLines) { return true; } if ( tempTextField.textWidth > tempTextField.width - margin || tempTextField.textHeight > tempTextField.height - margin ) return true; return false; } private static function copyTextField( original:TextField ):TextField { var copy:TextField = new TextField(); copy.width = original.width; copy.height = original.height; copy.multiline = original.multiline; copy.wordWrap = original.wordWrap; copy.embedFonts = original.embedFonts; copy.antiAliasType = original.antiAliasType; copy.autoSize = original.autoSize; copy.defaultTextFormat = original.getTextFormat(); copy.text = original.text; return copy; } /** * Truncate html text. * @param value The original text value * @param limit The maximum number of characters to show * @param ellipses Boolean value to show elipses at the end of truncation. * @param moreLink Boolean value to show a "[more]" with a TextEvent (TextEvent.LINK) at the end of truncation. * This method is based on Michael Ritchie's work at http://thanksmister.com/2009/07/12/flex-truncating-html-text/ * */ public static function truncateHTMLText(value:String, limit:int, ellipses:Boolean = true, moreLink:Boolean = true):String { if (!ellipses) limit += 3; if (!moreLink) limit += 6; if(limit <= 0) return ""; var original:String = value; value = value.replace("[\\t\\n\\x0B\\f\\r\\u00A0]+", ""); var isTag:Boolean = false; var count:int = 0; var position:int = 0; var limitLength:int = value.length - 1; var closeTag:Boolean = false; for(var i:int = 0; i < value.length; i++) { var c:String = value.charAt(i); if(isTag) { if(c == '>') { isTag = false; if(closeTag || i == limitLength) { position = i; break; } continue; } else { continue; } } else { if(c == '<') { isTag = true; } else { count++; if(i == limitLength || (count == limit)) { if(((i+1) < limitLength) && ((i+2) < limitLength)) { if(value.charAt(i+1) == '<' && value.charAt(i+2) == '/') { closeTag = true; continue; } } position = i; break; } } } } var result:String = value.substring(0, position + 1); var last:String = result.charAt(result.length - 1); var length:int = result.length; var nextChar:String = (length >= value.length) ? ' ' : value.charAt(length); if(last != ' ' && last != '>' && nextChar != ' ' && nextChar != '<') { result = result.substring(0, result.lastIndexOf(' ') + 1); } var lastStartTag:int = result.lastIndexOf('<'); if(lastStartTag != -1) { var ch:String = result.charAt(lastStartTag + 1); if(ch != '/') { result = result.substring(0, lastStartTag); } } if(original.length == result.length) return original; if(result.length == 0) return result; // Remove any empty spaces and periods at the end while(result.charAt(result.length - 1) == " " || result.charAt(result.length - 1) == ".") { result = result.slice(0, -1); // just incase, because while loops make me nervous if (result.length <= 0) break; } var pattern:RegExp = new RegExp("(.*?)(\\s*\.\.\.\\s*)([\</[a-z]*?\>\\s*$]+)", "i"); if(result.search(pattern) == -1 && ellipses) result += "..."; if (moreLink) { return (result + " <a href=\"event:more\">[more]</a>"); } else { return result; } } } }
package dorkbots.dorkbots_ui { import flash.text.TextField; public class TruncateTextField { public function TruncateTextField () { } public static function truncateText( textField:TextField, addEllipsis:Boolean = true, minimizeLines:uint = 0, ellipsis:String = "\u2026" ):uint { var tempTextField:TextField; var characterRemoveCnt:uint = 0; if ( ! textOverflowing( textField ) ) return characterRemoveCnt; tempTextField = copyTextField( textField ); while( textOverflowing( tempTextField, minimizeLines, ellipsis ) ) { characterRemoveCnt++; tempTextField.text = tempTextField.text.substr( 0, tempTextField.text.length - 1 ); } // Remove any empty spaces and periods at the end var continueEndTidying:Boolean = true; while(continueEndTidying) { continueEndTidying = false; if (tempTextField.text.charAt(tempTextField.text.length - 1) == " ") continueEndTidying = true; // remove any periods if we are adding ellipsis if (addEllipsis && tempTextField.text.charAt(tempTextField.text.length - 1) == ".") continueEndTidying = true; if (continueEndTidying) { characterRemoveCnt++; tempTextField.text = tempTextField.text.slice(0, -1); } // just incase, because while loops make me nervous if (tempTextField.text.length <= 0) break; } // add ellipsis if (ellipsis) { tempTextField.appendText( ellipsis ); if (tempTextField.numLines > 1) { // check again, for some reason, adding the ellipsis can increase number of lines while( textOverflowing( tempTextField, minimizeLines, ellipsis ) ) { characterRemoveCnt++; tempTextField.text = tempTextField.text.substr( 0, tempTextField.text.length - ellipsis.length - 1 ); } } tempTextField.appendText( ellipsis ); } textField.text = tempTextField.text; return characterRemoveCnt; } private static function textOverflowing( textField:TextField, minimizeLines:uint = 0, suffix:String = null ):Boolean { var margin:Number = 4; //Flash adds this to all textfields; var tempTextField:TextField = copyTextField( textField ); if ( suffix ) tempTextField.appendText( suffix ); if (minimizeLines > 0 && tempTextField.numLines > minimizeLines) { return true; } if ( tempTextField.textWidth > tempTextField.width - margin || tempTextField.textHeight > tempTextField.height - margin ) return true; return false; } private static function copyTextField( original:TextField ):TextField { var copy:TextField = new TextField(); copy.width = original.width; copy.height = original.height; copy.multiline = original.multiline; copy.wordWrap = original.wordWrap; copy.embedFonts = original.embedFonts; copy.antiAliasType = original.antiAliasType; copy.autoSize = original.autoSize; copy.defaultTextFormat = original.getTextFormat(); copy.text = original.text; return copy; } /** * Truncate html text. * @param value The original text value * @param limit The maximum number of characters to show * @param ellipses Boolean value to show elipses at the end of truncation. * @param moreLink Boolean value to show a "[more]" with a TextEvent (TextEvent.LINK) at the end of truncation. * This method is based on Michael Ritchie's work at http://thanksmister.com/2009/07/12/flex-truncating-html-text/ * */ public static function truncateHTMLText(value:String, limit:int, addEllipsis:Boolean = true, addMoreLink:Boolean = true):String { if (!addEllipsis) limit += 3; if (!addMoreLink) limit += 6; if(limit <= 0) return ""; var original:String = value; value = value.replace("[\\t\\n\\x0B\\f\\r\\u00A0]+", ""); var isTag:Boolean = false; var count:int = 0; var position:int = 0; var limitLength:int = value.length - 1; var closeTag:Boolean = false; for(var i:int = 0; i < value.length; i++) { var c:String = value.charAt(i); if(isTag) { if(c == '>') { isTag = false; if(closeTag || i == limitLength) { position = i; break; } continue; } else { continue; } } else { if(c == '<') { isTag = true; } else { count++; if(i == limitLength || (count == limit)) { if(((i+1) < limitLength) && ((i+2) < limitLength)) { if(value.charAt(i+1) == '<' && value.charAt(i+2) == '/') { closeTag = true; continue; } } position = i; break; } } } } var result:String = value.substring(0, position + 1); var last:String = result.charAt(result.length - 1); var length:int = result.length; var nextChar:String = (length >= value.length) ? ' ' : value.charAt(length); if(last != ' ' && last != '>' && nextChar != ' ' && nextChar != '<') { result = result.substring(0, result.lastIndexOf(' ') + 1); } var lastStartTag:int = result.lastIndexOf('<'); if(lastStartTag != -1) { var ch:String = result.charAt(lastStartTag + 1); if(ch != '/') { result = result.substring(0, lastStartTag); } } if(original.length == result.length) return original; if(result.length == 0) return result; // Remove any empty spaces and periods at the end while(result.charAt(result.length - 1) == " " || result.charAt(result.length - 1) == ".") { result = result.slice(0, -1); // just incase, because while loops make me nervous if (result.length <= 0) break; } // Remove any empty spaces and periods at the end var continueEndTidying:Boolean = true; while(continueEndTidying) { continueEndTidying = false; if (result.charAt(result.length - 1) == " ") continueEndTidying = true; // remove any periods if we are adding ellipsis if (addEllipsis && result.charAt(result.length - 1) == ".") continueEndTidying = true; if (continueEndTidying) { result = result.slice(0, -1); } // just incase, because while loops make me nervous if (result.length <= 0) break; } var pattern:RegExp = new RegExp("(.*?)(\\s*\.\.\.\\s*)([\</[a-z]*?\>\\s*$]+)", "i"); if(result.search(pattern) == -1 && addEllipsis) result += "..."; if (addMoreLink) { return (result + " <a href=\"event:more\">[more]</a>"); } else { return result; } } } }
comment updates
comment updates
ActionScript
mit
dorkbot/Dorkbots-Broadcasters
e9188ffbe369d64e61001fd714345645b0584879
GA_AS3/src/com/google/analytics/GATracker.as
GA_AS3/src/com/google/analytics/GATracker.as
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. */ package com.google.analytics { import com.google.analytics.core.Buffer; import com.google.analytics.core.GIFRequest; import com.google.analytics.core.as3_api; import com.google.analytics.core.ga_internal; import com.google.analytics.core.js_bridge; import com.google.analytics.debug.Layout; import com.google.analytics.events.MessageEvent; import com.google.analytics.external.HTMLDOM; import com.google.analytics.utils.Environment; import com.google.analytics.v4.Bridge; import com.google.analytics.v4.GoogleAnalyticsAPI; import com.google.analytics.v4.Tracker; import flash.display.DisplayObject; /** * @fileoverview Google Analytic Tracker Code (GATC)'s main component. */ public class GATracker { private var _display:DisplayObject; private var _localInfo:Environment; private var _buffer:Buffer; private var _gifRequest:GIFRequest; private var _dom:HTMLDOM; /** * note: * the GATracker need to be instancied and added to the Stage * or at least being placed in a display list. * * We mainly use it for internal test and it's basically a factory. * */ public function GATracker( display:DisplayObject ) { _display = display; debug.layout = new Layout( _display ); debug.active = true; /* note: for unit testing and to avoid 2 different branches AIR/Flash here we will detect if we are in the Flash Player or AIR and pass the infos to the LocalInfo By default we will define "Flash" for our local tests */ _dom = new HTMLDOM(); _localInfo = new Environment( "", "", "", _dom ); _buffer = new Buffer( false ); _gifRequest = new GIFRequest( _buffer, _localInfo ); } /** * version of our source code (not version of the GA API) * * note: * each components will have also their own version */ public static var version:String = "0.5.0." + "$Rev$ ".split( " " )[1]; private function _onInfo( event:MessageEvent ):void { debug.info( event.message ); } private function _onWarning( event:MessageEvent ):void { debug.warning( event.message ); } /** * Factory method for returning a tracker object. * * @param {String} account Urchin Account to record metrics in. * @return {GoogleAnalyticsAPI} */ as3_api function getTracker( account:String ):GoogleAnalyticsAPI { debug.info( "GATracker v" + version +"\naccount: " + account ); config.addEventListener( MessageEvent.INFO, _onInfo ); config.addEventListener( MessageEvent.WARNING, _onWarning ); /* note: To be able to obtain the URL of the main SWF containing the GA API we need to be able to access the stage property of a DisplayObject, here we open the internal namespace to be able to set that reference at instanciation-time. We keep the implementation internal to be able to change it if required later. */ use namespace ga_internal; _localInfo.url = _display.stage.loaderInfo.url; return new Tracker( account, _localInfo, _buffer, _gifRequest, null ); } /** * @private */ js_bridge function getTracker( account:String ):GoogleAnalyticsAPI { return new Bridge( account ); } } }
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. */ package com.google.analytics { import com.google.analytics.core.Buffer; import com.google.analytics.core.GIFRequest; import com.google.analytics.core.as3_api; import com.google.analytics.core.ga_internal; import com.google.analytics.core.js_bridge; import com.google.analytics.debug.Layout; import com.google.analytics.events.MessageEvent; import com.google.analytics.external.HTMLDOM; import com.google.analytics.utils.Environment; import com.google.analytics.utils.Version; import com.google.analytics.v4.Bridge; import com.google.analytics.v4.GoogleAnalyticsAPI; import com.google.analytics.v4.Tracker; import flash.display.DisplayObject; /** * @fileoverview Google Analytic Tracker Code (GATC)'s main component. */ public class GATracker { private var _display:DisplayObject; private var _localInfo:Environment; private var _buffer:Buffer; private var _gifRequest:GIFRequest; private var _dom:HTMLDOM; /** * note: * the GATracker need to be instancied and added to the Stage * or at least being placed in a display list. * * We mainly use it for internal test and it's basically a factory. * */ public function GATracker( display:DisplayObject, debugmode:Boolean = false ) { _display = display; if( debugmode ) { debug.layout = new Layout( _display ); debug.active = debugmode; } /* note: for unit testing and to avoid 2 different branches AIR/Flash here we will detect if we are in the Flash Player or AIR and pass the infos to the LocalInfo By default we will define "Flash" for our local tests */ _dom = new HTMLDOM(); _localInfo = new Environment( "", "", "", _dom ); _buffer = new Buffer( false ); _gifRequest = new GIFRequest( _buffer, _localInfo ); } /** * version of our source code (not version of the GA API) * * note: * each components will have also their own version */ public static var version:Version = new Version(); include "version.properties" version.revision = "$Rev$ ".split( " " )[1]; private function _onInfo( event:MessageEvent ):void { debug.info( event.message ); } private function _onWarning( event:MessageEvent ):void { debug.warning( event.message ); } /** * Factory method for returning a tracker object. * * @param {String} account Urchin Account to record metrics in. * @return {GoogleAnalyticsAPI} */ as3_api function getTracker( account:String ):GoogleAnalyticsAPI { debug.info( "GATracker v" + version +"\naccount: " + account ); config.addEventListener( MessageEvent.INFO, _onInfo ); config.addEventListener( MessageEvent.WARNING, _onWarning ); /* note: To be able to obtain the URL of the main SWF containing the GA API we need to be able to access the stage property of a DisplayObject, here we open the internal namespace to be able to set that reference at instanciation-time. We keep the implementation internal to be able to change it if required later. */ use namespace ga_internal; _localInfo.url = _display.stage.loaderInfo.url; return new Tracker( account, _localInfo, _buffer, _gifRequest, null ); } /** * @private */ js_bridge function getTracker( account:String ):GoogleAnalyticsAPI { return new Bridge( account ); } } }
test rev
test rev
ActionScript
apache-2.0
dli-iclinic/gaforflash,minimedj/gaforflash,Vigmar/gaforflash,DimaBaliakin/gaforflash,nsdevaraj/gaforflash,jeremy-wischusen/gaforflash,drflash/gaforflash,jeremy-wischusen/gaforflash,jisobkim/gaforflash,drflash/gaforflash,Vigmar/gaforflash,minimedj/gaforflash,mrthuanvn/gaforflash,mrthuanvn/gaforflash,Miyaru/gaforflash,nsdevaraj/gaforflash,Miyaru/gaforflash,jisobkim/gaforflash,soumavachakraborty/gaforflash,dli-iclinic/gaforflash,soumavachakraborty/gaforflash,DimaBaliakin/gaforflash
2adf5b2b5bd2bbf947179e4fac6fd22667783fc2
src/aerys/minko/type/clone/CloneOptions.as
src/aerys/minko/type/clone/CloneOptions.as
package aerys.minko.type.clone { import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.AnimationController; import aerys.minko.scene.controller.TransformController; import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.controller.light.DirectionalLightController; import aerys.minko.scene.controller.light.LightController; import aerys.minko.scene.controller.light.PointLightController; import aerys.minko.scene.controller.light.SpotLightController; import aerys.minko.scene.controller.mesh.MeshController; import aerys.minko.scene.controller.mesh.MeshVisibilityController; import aerys.minko.scene.controller.mesh.skinning.SkinningController; import avmplus.getQualifiedClassName; import flash.net.getClassByAlias; public final class CloneOptions { private var _clonedControllerTypes : Vector.<Class>; private var _ignoredControllerTypes : Vector.<Class>; private var _reassignedControllerTypes : Vector.<Class>; private var _defaultControllerAction : uint; public function get defaultControllerAction() : uint { return _defaultControllerAction; } public function set defaultControllerAction(v : uint) : void { if (v != ControllerCloneAction.CLONE && v != ControllerCloneAction.IGNORE && v != ControllerCloneAction.REASSIGN) throw new Error('Unknown action type.'); _defaultControllerAction = v; } public function CloneOptions() { initialize(); } private function initialize() : void { _clonedControllerTypes = new <Class>[]; _ignoredControllerTypes = new <Class>[]; _reassignedControllerTypes = new <Class>[]; _defaultControllerAction = ControllerCloneAction.REASSIGN; } public static function get defaultOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._clonedControllerTypes.push( AnimationController, SkinningController ); cloneOptions._ignoredControllerTypes.push( MeshController, MeshVisibilityController, CameraController, TransformController, LightController, DirectionalLightController, SpotLightController, PointLightController ); cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN; return cloneOptions; } public static function get cloneAllOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._ignoredControllerTypes.push( MeshController, MeshVisibilityController, CameraController, TransformController, LightController, DirectionalLightController, SpotLightController, PointLightController ); cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE; return cloneOptions; } public function setActionForControllerClass(controllerClass : Class, action : uint) : CloneOptions { var index : int = 0; if ((index = _clonedControllerTypes.indexOf(controllerClass)) >= 0) _clonedControllerTypes.slice(index, 1); else if ((index = _ignoredControllerTypes.indexOf(controllerClass)) >= 0) _ignoredControllerTypes.slice(index, 1); else if ((index = _reassignedControllerTypes.indexOf(controllerClass)) >= 0) _reassignedControllerTypes.slice(index, 1); switch (action) { case ControllerCloneAction.CLONE: _clonedControllerTypes.push(controllerClass); break; case ControllerCloneAction.IGNORE: _ignoredControllerTypes.push(controllerClass); break; case ControllerCloneAction.REASSIGN: _reassignedControllerTypes.push(controllerClass); break; default: throw new Error('Unknown action type.'); } return this; } public function getActionForController(controller : AbstractController) : uint { var numControllersToClone : uint = _clonedControllerTypes.length; var numControllersToIgnore : uint = _ignoredControllerTypes.length; var numControllersToReassign : uint = _reassignedControllerTypes.length; var controllerId : uint; for (controllerId = 0; controllerId < numControllersToClone; ++controllerId) if (controller is _clonedControllerTypes[controllerId]) return ControllerCloneAction.CLONE; for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId) if (controller is _ignoredControllerTypes[controllerId]) return ControllerCloneAction.IGNORE; for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId) if (controller is _reassignedControllerTypes[controllerId]) return ControllerCloneAction.REASSIGN; return _defaultControllerAction; } } }
package aerys.minko.type.clone { import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.AnimationController; import aerys.minko.scene.controller.TransformController; import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.controller.light.DirectionalLightController; import aerys.minko.scene.controller.light.LightController; import aerys.minko.scene.controller.light.PointLightController; import aerys.minko.scene.controller.light.SpotLightController; import aerys.minko.scene.controller.mesh.MeshController; import aerys.minko.scene.controller.mesh.MeshVisibilityController; import aerys.minko.scene.controller.mesh.skinning.SkinningController; public final class CloneOptions { private var _clonedControllerTypes : Vector.<Class>; private var _ignoredControllerTypes : Vector.<Class>; private var _reassignedControllerTypes : Vector.<Class>; private var _defaultControllerAction : uint; public function get defaultControllerAction() : uint { return _defaultControllerAction; } public function set defaultControllerAction(v : uint) : void { if (v != ControllerCloneAction.CLONE && v != ControllerCloneAction.IGNORE && v != ControllerCloneAction.REASSIGN) throw new Error('Unknown action type.'); _defaultControllerAction = v; } public function CloneOptions() { initialize(); } private function initialize() : void { _clonedControllerTypes = new <Class>[]; _ignoredControllerTypes = new <Class>[]; _reassignedControllerTypes = new <Class>[]; _defaultControllerAction = ControllerCloneAction.REASSIGN; } public static function get defaultOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._clonedControllerTypes.push( AnimationController, SkinningController ); cloneOptions._ignoredControllerTypes.push( MeshController, MeshVisibilityController, CameraController, TransformController, LightController, DirectionalLightController, SpotLightController, PointLightController ); cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN; return cloneOptions; } public static function get cloneAllOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._ignoredControllerTypes.push( MeshController, MeshVisibilityController, CameraController, TransformController, LightController, DirectionalLightController, SpotLightController, PointLightController ); cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE; return cloneOptions; } public function setActionForControllerClass(controllerClass : Class, action : uint) : CloneOptions { var index : int = 0; if ((index = _clonedControllerTypes.indexOf(controllerClass)) >= 0) _clonedControllerTypes.slice(index, 1); else if ((index = _ignoredControllerTypes.indexOf(controllerClass)) >= 0) _ignoredControllerTypes.slice(index, 1); else if ((index = _reassignedControllerTypes.indexOf(controllerClass)) >= 0) _reassignedControllerTypes.slice(index, 1); switch (action) { case ControllerCloneAction.CLONE: _clonedControllerTypes.push(controllerClass); break; case ControllerCloneAction.IGNORE: _ignoredControllerTypes.push(controllerClass); break; case ControllerCloneAction.REASSIGN: _reassignedControllerTypes.push(controllerClass); break; default: throw new Error('Unknown action type.'); } return this; } public function getActionForController(controller : AbstractController) : uint { var numControllersToClone : uint = _clonedControllerTypes.length; var numControllersToIgnore : uint = _ignoredControllerTypes.length; var numControllersToReassign : uint = _reassignedControllerTypes.length; var controllerId : uint; for (controllerId = 0; controllerId < numControllersToClone; ++controllerId) if (controller is _clonedControllerTypes[controllerId]) return ControllerCloneAction.CLONE; for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId) if (controller is _ignoredControllerTypes[controllerId]) return ControllerCloneAction.IGNORE; for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId) if (controller is _reassignedControllerTypes[controllerId]) return ControllerCloneAction.REASSIGN; return _defaultControllerAction; } } }
remove useless imports
remove useless imports
ActionScript
mit
aerys/minko-as3
53a23114a9c51aa3b1e222391a0da5c100bb609a
dolly-framework/src/test/actionscript/dolly/CloningOfPropertyLevelCloneableClassTest.as
dolly-framework/src/test/actionscript/dolly/CloningOfPropertyLevelCloneableClassTest.as
package dolly { import dolly.core.dolly_internal; import dolly.data.PropertyLevelCloneableClass; import org.as3commons.reflect.Type; use namespace dolly_internal; public class CloningOfPropertyLevelCloneableClassTest { private var propertyLevelCloneable:PropertyLevelCloneableClass; private var propertyLevelCloneableType:Type; [Before] public function before():void { propertyLevelCloneable = new PropertyLevelCloneableClass(); propertyLevelCloneable.property1 = "value 1"; propertyLevelCloneable.writableField1 = "value 4"; propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable); } [After] public function after():void { propertyLevelCloneable = null; propertyLevelCloneableType = null; } /** * <code>Cloner.findingAllWritableFieldsForType()</code> method will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function findingAllWritableFieldsForType():void { Cloner.findAllWritableFieldsForType(propertyLevelCloneableType); } /** * <code>Cloner.clone()</code> method will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function cloningByCloner():void { Cloner.clone(propertyLevelCloneable); } /** * Method <code>clone()</code> will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function cloningByCloneFunction():void { clone(propertyLevelCloneable); } } }
package dolly { import dolly.core.dolly_internal; import dolly.data.PropertyLevelCloneableClass; import org.as3commons.reflect.Type; use namespace dolly_internal; public class CloningOfPropertyLevelCloneableClassTest { private var propertyLevelCloneable:PropertyLevelCloneableClass; private var propertyLevelCloneableType:Type; [Before] public function before():void { propertyLevelCloneable = new PropertyLevelCloneableClass(); propertyLevelCloneable.property1 = "property1 value"; propertyLevelCloneable.writableField1 = "writableField1 value"; propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable); } [After] public function after():void { propertyLevelCloneable = null; propertyLevelCloneableType = null; } /** * <code>Cloner.findingAllWritableFieldsForType()</code> method will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function findingAllWritableFieldsForType():void { Cloner.findAllWritableFieldsForType(propertyLevelCloneableType); } /** * <code>Cloner.clone()</code> method will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function cloningByCloner():void { Cloner.clone(propertyLevelCloneable); } /** * Method <code>clone()</code> will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function cloningByCloneFunction():void { clone(propertyLevelCloneable); } } }
Change properties' values.
Change properties' values.
ActionScript
mit
Yarovoy/dolly
c83e088849e75bb8a11b198fb1718da6ad02ce5e
src/com/esri/builder/supportClasses/FileUtil.as
src/com/esri/builder/supportClasses/FileUtil.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 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 com.esri.builder.supportClasses { import flash.filesystem.File; import mx.utils.StringUtil; public class FileUtil { public static function generateUniqueRelativePath(baseDirectory:File, relativeFilePath:String, relativePathBlackList:Array = null):String { var currentID:int = 1; var extensionIndex:int = relativeFilePath.lastIndexOf("."); var extension:String = ""; if (extensionIndex > -1) { extension = relativeFilePath.substr(extensionIndex); relativeFilePath = relativeFilePath.substr(0, extensionIndex); } var filenameTemplate:String = relativeFilePath + "_{0}" + extension; var uniqueWidgetConfigPath:String; do { uniqueWidgetConfigPath = StringUtil.substitute(filenameTemplate, currentID++); } while (doesFileExist(baseDirectory, uniqueWidgetConfigPath, relativePathBlackList)); return uniqueWidgetConfigPath; } private static function doesFileExist(baseDirectory:File, relativeFilePath:String, relativePathBlackList:Array):Boolean { if (relativePathBlackList && relativePathBlackList.indexOf(relativeFilePath) > -1) { return true; } var fileToCheck:File = baseDirectory.resolvePath(relativeFilePath); return fileToCheck.exists; } public static function getFileName(file:File):String { return file.name.replace("." + file.extension, ""); } public static function findMatchingFiles(directory:File, pattern:RegExp):Array { var moduleFiles:Array = []; if (directory.isDirectory) { const files:Array = directory.getDirectoryListing(); for each (var file:File in files) { if (file.isDirectory) { moduleFiles = moduleFiles.concat(findMatchingFiles(file, pattern)); } else if (pattern.test(file.name)) { moduleFiles.push(file); } } } return moduleFiles; } public static function findMatchingFile(directory:File, pattern:RegExp):File { var matchingFile:File; if (directory.isDirectory) { const files:Array = directory.getDirectoryListing(); //sort files first to reduce unnecessary directory listing calls. files.sortOn("isDirectory"); for each (var file:File in files) { if (file.isDirectory) { matchingFile = findMatchingFile(file, pattern); } else if (pattern.test(file.name)) { matchingFile = file; } if (matchingFile) { break; } } } return matchingFile; } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 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 com.esri.builder.supportClasses { import flash.filesystem.File; public class FileUtil { public static function generateUniqueRelativePath(baseDirectory:File, relativeFilePath:String, relativePathBlackList:Array = null):String { var extensionIndex:int = relativeFilePath.lastIndexOf("."); var extension:String = ""; if (extensionIndex > -1) { extension = relativeFilePath.substr(extensionIndex); relativeFilePath = relativeFilePath.substr(0, extensionIndex); } var filenameTemplate:String = relativeFilePath + "_{0}" + extension; var uniqueWidgetConfigPath:String = LabelUtil.generateUniqueLabel(filenameTemplate, relativePathBlackList, function isNonExistentFile(uniqueFilePath:String, availableNames:Array):Boolean { if (availableNames && availableNames.indexOf(uniqueFilePath) > -1) { return false; } return !baseDirectory.resolvePath(uniqueFilePath).exists; }); return uniqueWidgetConfigPath; } public static function getFileName(file:File):String { return file.name.replace("." + file.extension, ""); } public static function findMatchingFiles(directory:File, pattern:RegExp):Array { var moduleFiles:Array = []; if (directory.isDirectory) { const files:Array = directory.getDirectoryListing(); for each (var file:File in files) { if (file.isDirectory) { moduleFiles = moduleFiles.concat(findMatchingFiles(file, pattern)); } else if (pattern.test(file.name)) { moduleFiles.push(file); } } } return moduleFiles; } public static function findMatchingFile(directory:File, pattern:RegExp):File { var matchingFile:File; if (directory.isDirectory) { const files:Array = directory.getDirectoryListing(); //sort files first to reduce unnecessary directory listing calls. files.sortOn("isDirectory"); for each (var file:File in files) { if (file.isDirectory) { matchingFile = findMatchingFile(file, pattern); } else if (pattern.test(file.name)) { matchingFile = file; } if (matchingFile) { break; } } } return matchingFile; } } }
Use unique label utility in FileUtil.
Use unique label utility in FileUtil.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
6d179d6ad2e3cf34c6ca3c2d424d0084f5771291
src/as/com/threerings/flex/CommandMenu.as
src/as/com/threerings/flex/CommandMenu.as
// // $Id$ // // Nenya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.flex { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.IEventDispatcher; import flash.geom.Point; import flash.geom.Rectangle; import mx.controls.Menu; import mx.controls.listClasses.BaseListData; import mx.controls.listClasses.IListItemRenderer; import mx.controls.menuClasses.IMenuItemRenderer; import mx.controls.menuClasses.MenuListData; import mx.core.mx_internal; import mx.core.Application; import mx.core.ClassFactory; import mx.core.IFlexDisplayObject; import mx.core.ScrollPolicy; import mx.events.MenuEvent; import mx.managers.PopUpManager; import com.threerings.util.CommandEvent; import com.threerings.flex.PopUpUtil; import com.threerings.flex.menuClasses.CommandMenuItemRenderer; import com.threerings.flex.menuClasses.CommandListData; use namespace mx_internal; /** * A pretty standard menu that can submit CommandEvents if menu items have "command" and possibly * "arg" properties. Commands are submitted to controllers for processing. Alternatively, you may * specify "callback" properties that specify a function closure to call, with the "arg" property * containing either a single arg or an array of args. * * Another property now supported is "iconObject", which is an already-instantiated * IFlexDisplayObject to use as the icon. This will only be applied if the "icon" property * (which specifies a Class) is not used. * * Example dataProvider array: * [ { label: "Go home", icon: homeIconClass, * command: Controller.GO_HOME, arg: homeId }, * { type: "separator"}, { label: "Crazytown", callback: setCrazy, arg: [ true, false ] }, * { label: "Other places", children: subMenuArray } * ]; * * See "Defining menu structure and data" in the Flex manual for the full list. * * CommandMenu is scrollable. This can be forced by setting verticalScrollPolicy to * ScrollPolicy.AUTO or ScrollPolicy.ON and setting the maxHeight. Also, if the scrolling isn't * forced on, but the menu does not fit within the vertical bounds given (either the stage size by * default, or the height of the rectangle given in setBounds()), scrolling will be turned on * so that none of the content is lost. * * Note: we don't extend flexlib's ScrollableMenu (or its sub-class ScrollableArrowMenu) because it * does some weird stuff in measure() that forces some of our menus down to a very small height... */ public class CommandMenu extends Menu { /** * Factory method to create a command menu. * * @param items an array of menu items. * @param dispatcher an override event dispatcher to use for command events, rather than * our parent. */ public static function createMenu ( items :Array, dispatcher :IEventDispatcher = null) :CommandMenu { var menu :CommandMenu = new CommandMenu(); menu.owner = DisplayObjectContainer(Application.application); menu.tabEnabled = false; menu.showRoot = true; menu.setDispatcher(dispatcher); Menu.popUpMenu(menu, null, items); // does not actually pop up, but needed. return menu; } /** * Add a separator to the specified menu, unless it would not make sense to do so, because * the menu is empty or already ends with a separator. */ public static function addSeparator (menuItems :Array) :void { const len :int = menuItems.length; if (len > 0 && menuItems[len - 1].type != "separator") { menuItems.push({ type: "separator" }); } } /** * The mx.controls.Menu class overrides setting and getting the verticalScrollPolicy * basically setting the verticalScrollPolicy did nothing, and getting it always returned * ScrollPolicy.OFF. So that's not going to work if we want the menu to scroll. Here we * reinstate the verticalScrollPolicy setter, and keep a local copy of the value in a * protected variable _verticalScrollPolicy. * * This setter is basically a copy of what ScrollControlBase and ListBase do. */ override public function set verticalScrollPolicy (value :String) :void { var newPolicy :String = value.toLowerCase(); itemsSizeChanged = true; if (_verticalScrollPolicy != newPolicy) { _verticalScrollPolicy = newPolicy; dispatchEvent(new Event("verticalScrollPolicyChanged")); } invalidateDisplayList(); } override public function get verticalScrollPolicy () :String { return _verticalScrollPolicy; } public function CommandMenu () { super(); itemRenderer = new ClassFactory(getItemRenderer()); verticalScrollPolicy = ScrollPolicy.OFF; addEventListener(MenuEvent.ITEM_CLICK, itemClicked); } /** * Called in the CommandMenu constructor, this should return the item rendering class for this * CommandMenu. */ protected function getItemRenderer () :Class { return CommandMenuItemRenderer; } /** * Configures the event dispatcher to be used when dispatching this menu's command events. * Normally they will be dispatched on our parent (usually the SystemManager or something). */ public function setDispatcher (dispatcher :IEventDispatcher) :void { _dispatcher = dispatcher; } /** * Sets a Rectangle (in stage coords) that the menu will attempt to keep submenus positioned * within. If a submenu is too large to fit, it will position it in the lower right corner * of this Rectangle (or top if popping upwards, or left if popping leftwards). This * value defaults to the stage bounds. */ public function setBounds (fitting :Rectangle) :void { _fitting = fitting; } /** * Actually pop up the menu. This can be used instead of show(). */ public function popUp ( trigger :DisplayObject, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; var r :Rectangle = trigger.getBounds(trigger.stage); show(_lefting ? r.left : r.right, _upping ? r.top : r.bottom); } /** * Shows the menu at the specified mouse coordinates. */ public function popUpAt ( mx :int, my :int, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; show(mx, my); } /** * Shows the menu at the current mouse location. */ public function popUpAtMouse (popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; show(); // our show, with no args, pops at the mouse } /** * Just like our superclass's show(), except that when invoked with no args, causes the menu to * show at the current mouse location instead of the top-left corner of the application. * Also, we ensure that the resulting menu is in-bounds. */ override public function show (xShow :Object = null, yShow :Object = null) :void { if (xShow == null) { xShow = DisplayObject(Application.application).mouseX; } if (yShow == null) { yShow = DisplayObject(Application.application).mouseY; } super.show(xShow, yShow); // reposition now that we know our size if (_lefting) { y = x - getExplicitOrMeasuredWidth(); } if (_upping) { y = y - getExplicitOrMeasuredHeight(); } var fitting :Rectangle = _fitting || screen; PopUpUtil.fitInRect(this, fitting); // if after fitting as best we can, the menu is outside of the declared bounds, we force // scrolling and set the max height if (y < fitting.y) { verticalScrollPolicy = ScrollPolicy.AUTO; maxHeight = fitting.height; y = fitting.y; } } /** * The Menu class overrode configureScrollBars() and made the function do nothing. That means * the scrollbars don't know how to draw themselves, so here we reinstate configureScrollBars. * This is basically a copy of the same method from the mx.controls.List class. */ override protected function configureScrollBars () :void { var rowCount :int = listItems.length; if (rowCount == 0) { return; } // if there is more than one row and it is a partial row we don't count it if (rowCount > 1 && rowInfo[rowCount - 1].y + rowInfo[rowCount - 1].height > listContent.height) { rowCount--; } // offset, when added to rowCount, is hte index of the dataProvider item for that row. // IOW, row 10 in listItems is showing dataProvider item 10 + verticalScrollPosition - // lockedRowCount - 1 var offset :int = verticalScrollPosition - lockedRowCount - 1; // don't count filler rows at the bottom either. var fillerRows :int = 0; while (rowCount > 0 && listItems[rowCount - 1].length == 0) { if (collection && rowCount + offset >= collection.length) { rowCount--; fillerRows++; } else { break; } } var colCount :int = listItems[0].length; var oldHorizontalScrollBar :Object = horizontalScrollBar; var oldVerticalScrollBar :Object = verticalScrollBar; var roundedWidth :int = Math.round(unscaledWidth); var length :int = collection ? collection.length - lockedRowCount : 0; var numRows :int = rowCount - lockedRowCount; setScrollBarProperties(Math.round(listContent.width), roundedWidth, length, numRows); maxVerticalScrollPosition = Math.max(length - numRows, 0); } /** * Callback for MenuEvent.ITEM_CLICK. */ protected function itemClicked (event :MenuEvent) :void { var arg :Object = getItemProp(event.item, "arg"); var cmdOrFn :Object = getItemProp(event.item, "command"); if (cmdOrFn == null) { cmdOrFn = getItemProp(event.item, "callback"); } if (cmdOrFn != null) { event.stopImmediatePropagation(); CommandEvent.dispatch(_dispatcher == null ? mx_internal::parentDisplayObject : _dispatcher, cmdOrFn, arg); } // else: no warning. There may be non-command menu items mixed in. } // from ScrollableArrowMenu.. override mx_internal function openSubMenu (row :IListItemRenderer) :void { supposedToLoseFocus = true; var r :Menu = getRootMenu(); var menu :CommandMenu; // check to see if the menu exists, if not create it if (!IMenuItemRenderer(row).menu) { // the only differences between this method and the original method in mx.controls.Menu // are these few lines. menu = new CommandMenu(); menu.maxHeight = this.maxHeight; menu.verticalScrollPolicy = this.verticalScrollPolicy; menu.variableRowHeight = this.variableRowHeight; menu.parentMenu = this; menu.owner = this; menu.showRoot = showRoot; menu.dataDescriptor = r.dataDescriptor; menu.styleName = r; menu.labelField = r.labelField; menu.labelFunction = r.labelFunction; menu.iconField = r.iconField; menu.iconFunction = r.iconFunction; menu.itemRenderer = r.itemRenderer; menu.rowHeight = r.rowHeight; menu.scaleY = r.scaleY; menu.scaleX = r.scaleX; // if there's data and it has children then add the items if (row.data && _dataDescriptor.isBranch(row.data) && _dataDescriptor.hasChildren(row.data)) { menu.dataProvider = _dataDescriptor.getChildren(row.data); } menu.sourceMenuBar = sourceMenuBar; menu.sourceMenuBarItem = sourceMenuBarItem; IMenuItemRenderer(row).menu = menu; PopUpManager.addPopUp(menu, r, false); } super.openSubMenu(row); // if we're lefting, upping or fitting make sure our submenu does so as well var submenu :Menu = IMenuItemRenderer(row).menu; if (_lefting) { submenu.x -= submenu.getExplicitOrMeasuredWidth(); } if (_upping) { var displayObj :DisplayObject = DisplayObject(row); var rowLoc :Point = displayObj.localToGlobal(new Point(row.x, row.y)); submenu.y = rowLoc.y - submenu.getExplicitOrMeasuredHeight() + displayObj.height; } var fitting :Rectangle = _fitting || screen; PopUpUtil.fitInRect(submenu, fitting); // if after fitting as best we can, the menu is outside of the declared bounds, we force // scrolling and set the max height if (submenu.y < fitting.y) { submenu.verticalScrollPolicy = ScrollPolicy.AUTO; submenu.maxHeight = fitting.height; submenu.y = fitting.y; } } override protected function measure () :void { super.measure(); if (measuredHeight > this.maxHeight) { measuredHeight = this.maxHeight; } if (verticalScrollPolicy == ScrollPolicy.ON || verticalScrollPolicy == ScrollPolicy.AUTO) { if (verticalScrollBar) { measuredMinWidth = measuredWidth = measuredWidth + verticalScrollBar.minWidth; } } commitProperties(); } // from List override protected function makeListData (data :Object, uid :String, rowNum :int) :BaseListData { // Oh, FFS. // We need to set up these "maxMeasuredIconWidth" fields on the MenuListData, but our // superclass has made those variables private. // We can get the values out of another MenuListData, so we just always call super() // to create one of those, and if we need to make a CommandListData, we construct one // from the fields in the MenuListData. var menuListData :MenuListData = super.makeListData(data, uid, rowNum) as MenuListData; var iconObject :IFlexDisplayObject = getItemProp(data, "iconObject") as IFlexDisplayObject; if (iconObject != null) { var cmdListData :CommandListData = new CommandListData(menuListData.label, menuListData.icon, iconObject, labelField, uid, this, rowNum); cmdListData.maxMeasuredIconWidth = menuListData.maxMeasuredIconWidth; cmdListData.maxMeasuredTypeIconWidth = menuListData.maxMeasuredTypeIconWidth; cmdListData.maxMeasuredBranchIconWidth = menuListData.maxMeasuredBranchIconWidth; cmdListData.useTwoColumns = menuListData.useTwoColumns; return cmdListData; } return menuListData; } /** * Get the specified property for the specified item, if any. Somewhat similar to bits in the * DefaultDataDescriptor. */ protected function getItemProp (item :Object, prop :String) :Object { try { if (item is XML) { return String((item as XML).attribute(prop)); } else if (prop in item) { return item[prop]; } } catch (e :Error) { // alas; fall through } return null; } protected var _dispatcher :IEventDispatcher; protected var _lefting :Boolean = false; protected var _upping :Boolean = false; protected var _fitting :Rectangle = null; protected var _verticalScrollPolicy :String; } }
// // $Id$ // // Nenya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.flex { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.IEventDispatcher; import flash.geom.Point; import flash.geom.Rectangle; import mx.controls.Menu; import mx.controls.listClasses.BaseListData; import mx.controls.listClasses.IListItemRenderer; import mx.controls.menuClasses.IMenuItemRenderer; import mx.controls.menuClasses.MenuListData; import mx.core.mx_internal; import mx.core.Application; import mx.core.ClassFactory; import mx.core.IFlexDisplayObject; import mx.core.ScrollPolicy; import mx.events.MenuEvent; import mx.managers.PopUpManager; import com.threerings.util.CommandEvent; import com.threerings.flex.PopUpUtil; import com.threerings.flex.menuClasses.CommandMenuItemRenderer; import com.threerings.flex.menuClasses.CommandListData; use namespace mx_internal; /** * A pretty standard menu that can submit CommandEvents if menu items have "command" and possibly * "arg" properties. Commands are submitted to controllers for processing. Alternatively, you may * specify "callback" properties that specify a function closure to call, with the "arg" property * containing either a single arg or an array of args. * * Another property now supported is "iconObject", which is an already-instantiated * IFlexDisplayObject to use as the icon. This will only be applied if the "icon" property * (which specifies a Class) is not used. * * Example dataProvider array: * [ { label: "Go home", icon: homeIconClass, * command: Controller.GO_HOME, arg: homeId }, * { type: "separator"}, { label: "Crazytown", callback: setCrazy, arg: [ true, false ] }, * { label: "Other places", children: subMenuArray } * ]; * * See "Defining menu structure and data" in the Flex manual for the full list. * * CommandMenu is scrollable. This can be forced by setting verticalScrollPolicy to * ScrollPolicy.AUTO or ScrollPolicy.ON and setting the maxHeight. Also, if the scrolling isn't * forced on, but the menu does not fit within the vertical bounds given (either the stage size by * default, or the height of the rectangle given in setBounds()), scrolling will be turned on * so that none of the content is lost. * * Note: we don't extend flexlib's ScrollableMenu (or its sub-class ScrollableArrowMenu) because it * does some weird stuff in measure() that forces some of our menus down to a very small height... */ public class CommandMenu extends Menu { /** * Factory method to create a command menu. * * @param items an array of menu items. * @param dispatcher an override event dispatcher to use for command events, rather than * our parent. */ public static function createMenu ( items :Array, dispatcher :IEventDispatcher = null) :CommandMenu { var menu :CommandMenu = new CommandMenu(); menu.owner = DisplayObjectContainer(Application.application); menu.tabEnabled = false; menu.showRoot = true; menu.setDispatcher(dispatcher); Menu.popUpMenu(menu, null, items); // does not actually pop up, but needed. return menu; } /** * Add a separator to the specified menu, unless it would not make sense to do so, because * the menu is empty or already ends with a separator. */ public static function addSeparator (menuItems :Array) :void { const len :int = menuItems.length; if (len > 0 && menuItems[len - 1].type != "separator") { menuItems.push({ type: "separator" }); } } /** * The mx.controls.Menu class overrides setting and getting the verticalScrollPolicy * basically setting the verticalScrollPolicy did nothing, and getting it always returned * ScrollPolicy.OFF. So that's not going to work if we want the menu to scroll. Here we * reinstate the verticalScrollPolicy setter, and keep a local copy of the value in a * protected variable _verticalScrollPolicy. * * This setter is basically a copy of what ScrollControlBase and ListBase do. */ override public function set verticalScrollPolicy (value :String) :void { var newPolicy :String = value.toLowerCase(); itemsSizeChanged = true; if (_verticalScrollPolicy != newPolicy) { _verticalScrollPolicy = newPolicy; dispatchEvent(new Event("verticalScrollPolicyChanged")); } invalidateDisplayList(); } override public function get verticalScrollPolicy () :String { return _verticalScrollPolicy; } public function CommandMenu () { super(); itemRenderer = new ClassFactory(getItemRenderer()); verticalScrollPolicy = ScrollPolicy.OFF; addEventListener(MenuEvent.ITEM_CLICK, itemClicked); } /** * Called in the CommandMenu constructor, this should return the item rendering class for this * CommandMenu. */ protected function getItemRenderer () :Class { return CommandMenuItemRenderer; } /** * Configures the event dispatcher to be used when dispatching this menu's command events. * Normally they will be dispatched on our parent (usually the SystemManager or something). */ public function setDispatcher (dispatcher :IEventDispatcher) :void { _dispatcher = dispatcher; } /** * Sets a Rectangle (in stage coords) that the menu will attempt to keep submenus positioned * within. If a submenu is too large to fit, it will position it in the lower right corner * of this Rectangle (or top if popping upwards, or left if popping leftwards). This * value defaults to the stage bounds. */ public function setBounds (fitting :Rectangle) :void { _fitting = fitting; } /** * Actually pop up the menu. This can be used instead of show(). */ public function popUp ( trigger :DisplayObject, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; var r :Rectangle = trigger.getBounds(trigger.stage); show(_lefting ? r.left : r.right, _upping ? r.top : r.bottom); } /** * Shows the menu at the specified mouse coordinates. */ public function popUpAt ( mx :int, my :int, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; show(mx, my); } /** * Shows the menu at the current mouse location. */ public function popUpAtMouse (popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; show(); // our show, with no args, pops at the mouse } /** * Just like our superclass's show(), except that when invoked with no args, causes the menu to * show at the current mouse location instead of the top-left corner of the application. * Also, we ensure that the resulting menu is in-bounds. */ override public function show (xShow :Object = null, yShow :Object = null) :void { if (xShow == null) { xShow = DisplayObject(Application.application).mouseX; } if (yShow == null) { yShow = DisplayObject(Application.application).mouseY; } super.show(xShow, yShow); // reposition now that we know our size if (_lefting) { y = x - getExplicitOrMeasuredWidth(); } if (_upping) { y = y - getExplicitOrMeasuredHeight(); } var fitting :Rectangle = _fitting || screen; PopUpUtil.fitInRect(this, fitting); // if after fitting as best we can, the menu is outside of the declared bounds, we force // scrolling and set the max height if (y < fitting.y) { verticalScrollPolicy = ScrollPolicy.AUTO; maxHeight = fitting.height; y = fitting.y; } } /** * The Menu class overrode configureScrollBars() and made the function do nothing. That means * the scrollbars don't know how to draw themselves, so here we reinstate configureScrollBars. * This is basically a copy of the same method from the mx.controls.List class. */ override protected function configureScrollBars () :void { var rowCount :int = listItems.length; if (rowCount == 0) { return; } // if there is more than one row and it is a partial row we don't count it if (rowCount > 1 && rowInfo[rowCount - 1].y + rowInfo[rowCount - 1].height > listContent.height) { rowCount--; } // offset, when added to rowCount, is hte index of the dataProvider item for that row. // IOW, row 10 in listItems is showing dataProvider item 10 + verticalScrollPosition - // lockedRowCount - 1 var offset :int = verticalScrollPosition - lockedRowCount - 1; // don't count filler rows at the bottom either. var fillerRows :int = 0; while (rowCount > 0 && listItems[rowCount - 1].length == 0) { if (collection && rowCount + offset >= collection.length) { rowCount--; fillerRows++; } else { break; } } var colCount :int = listItems[0].length; var oldHorizontalScrollBar :Object = horizontalScrollBar; var oldVerticalScrollBar :Object = verticalScrollBar; var roundedWidth :int = Math.round(unscaledWidth); var length :int = collection ? collection.length - lockedRowCount : 0; var numRows :int = rowCount - lockedRowCount; setScrollBarProperties(Math.round(listContent.width), roundedWidth, length, numRows); maxVerticalScrollPosition = Math.max(length - numRows, 0); } /** * Callback for MenuEvent.ITEM_CLICK. */ protected function itemClicked (event :MenuEvent) :void { var arg :Object = getItemProp(event.item, "arg"); var cmdOrFn :Object = getItemProp(event.item, "command"); if (cmdOrFn == null) { cmdOrFn = getItemProp(event.item, "callback"); } if (cmdOrFn != null) { event.stopImmediatePropagation(); CommandEvent.dispatch(_dispatcher == null ? mx_internal::parentDisplayObject : _dispatcher, cmdOrFn, arg); } // else: no warning. There may be non-command menu items mixed in. } // from ScrollableArrowMenu.. override mx_internal function openSubMenu (row :IListItemRenderer) :void { supposedToLoseFocus = true; var r :Menu = getRootMenu(); var menu :CommandMenu; // check to see if the menu exists, if not create it if (!IMenuItemRenderer(row).menu) { // the only differences between this method and the original method in mx.controls.Menu // are these few lines. menu = new CommandMenu(); menu.maxHeight = this.maxHeight; menu.verticalScrollPolicy = this.verticalScrollPolicy; menu.variableRowHeight = this.variableRowHeight; menu.parentMenu = this; menu.owner = this; menu.showRoot = showRoot; menu.dataDescriptor = r.dataDescriptor; menu.styleName = r; menu.labelField = r.labelField; menu.labelFunction = r.labelFunction; menu.iconField = r.iconField; menu.iconFunction = r.iconFunction; menu.itemRenderer = r.itemRenderer; menu.rowHeight = r.rowHeight; menu.scaleY = r.scaleY; menu.scaleX = r.scaleX; // if there's data and it has children then add the items if (row.data && _dataDescriptor.isBranch(row.data) && _dataDescriptor.hasChildren(row.data)) { menu.dataProvider = _dataDescriptor.getChildren(row.data); } menu.sourceMenuBar = sourceMenuBar; menu.sourceMenuBarItem = sourceMenuBarItem; IMenuItemRenderer(row).menu = menu; PopUpManager.addPopUp(menu, r, false); } super.openSubMenu(row); // if we're lefting, upping or fitting make sure our submenu does so as well var submenu :Menu = IMenuItemRenderer(row).menu; if (_lefting) { submenu.x -= submenu.getExplicitOrMeasuredWidth(); } if (_upping) { var displayObj :DisplayObject = DisplayObject(row); var rowLoc :Point = displayObj.localToGlobal(new Point()); submenu.y = rowLoc.y - submenu.getExplicitOrMeasuredHeight() + displayObj.height; } var fitting :Rectangle = _fitting || screen; PopUpUtil.fitInRect(submenu, fitting); // if after fitting as best we can, the menu is outside of the declared bounds, we force // scrolling and set the max height if (submenu.y < fitting.y) { submenu.verticalScrollPolicy = ScrollPolicy.AUTO; submenu.maxHeight = fitting.height; submenu.y = fitting.y; } } override protected function measure () :void { super.measure(); if (measuredHeight > this.maxHeight) { measuredHeight = this.maxHeight; } if (verticalScrollPolicy == ScrollPolicy.ON || verticalScrollPolicy == ScrollPolicy.AUTO) { if (verticalScrollBar) { measuredMinWidth = measuredWidth = measuredWidth + verticalScrollBar.minWidth; } } commitProperties(); } // from List override protected function makeListData (data :Object, uid :String, rowNum :int) :BaseListData { // Oh, FFS. // We need to set up these "maxMeasuredIconWidth" fields on the MenuListData, but our // superclass has made those variables private. // We can get the values out of another MenuListData, so we just always call super() // to create one of those, and if we need to make a CommandListData, we construct one // from the fields in the MenuListData. var menuListData :MenuListData = super.makeListData(data, uid, rowNum) as MenuListData; var iconObject :IFlexDisplayObject = getItemProp(data, "iconObject") as IFlexDisplayObject; if (iconObject != null) { var cmdListData :CommandListData = new CommandListData(menuListData.label, menuListData.icon, iconObject, labelField, uid, this, rowNum); cmdListData.maxMeasuredIconWidth = menuListData.maxMeasuredIconWidth; cmdListData.maxMeasuredTypeIconWidth = menuListData.maxMeasuredTypeIconWidth; cmdListData.maxMeasuredBranchIconWidth = menuListData.maxMeasuredBranchIconWidth; cmdListData.useTwoColumns = menuListData.useTwoColumns; return cmdListData; } return menuListData; } /** * Get the specified property for the specified item, if any. Somewhat similar to bits in the * DefaultDataDescriptor. */ protected function getItemProp (item :Object, prop :String) :Object { try { if (item is XML) { return String((item as XML).attribute(prop)); } else if (prop in item) { return item[prop]; } } catch (e :Error) { // alas; fall through } return null; } protected var _dispatcher :IEventDispatcher; protected var _lefting :Boolean = false; protected var _upping :Boolean = false; protected var _fitting :Rectangle = null; protected var _verticalScrollPolicy :String; } }
fix y position of a submenu on an upwards-popping menu. When transforming from row coords to global coords, don't use a point in the row's parent's coords.
Bugfix: fix y position of a submenu on an upwards-popping menu. When transforming from row coords to global coords, don't use a point in the row's parent's coords. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@804 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
91e1c2a9e2e2b0523303e4e779015d746dc6d9bb
src/aerys/minko/type/math/Vector4.as
src/aerys/minko/type/math/Vector4.as
package aerys.minko.type.math { import aerys.minko.ns.minko_math; import aerys.minko.type.Factory; import aerys.minko.type.Signal; import aerys.minko.type.binding.IWatchable; import flash.geom.Vector3D; public class Vector4 implements IWatchable { use namespace minko_math; public static const X_AXIS : Vector4 = new Vector4(1., 0., 0.); public static const Y_AXIS : Vector4 = new Vector4(0., 1., 0.); public static const Z_AXIS : Vector4 = new Vector4(0., 0., 1.); public static const ZERO : Vector4 = new Vector4(0., 0., 0., 0.); public static const ONE : Vector4 = new Vector4(1., 1., 1., 1.); public static const FORWARD : Vector4 = Z_AXIS; public static const BACKWARD : Vector4 = new Vector4(0., 0., -1.); public static const LEFT : Vector4 = new Vector4(-1, 0., 0.); public static const RIGHT : Vector4 = new Vector4(1, 0., 0.); public static const UP : Vector4 = Y_AXIS; public static const DOWN : Vector4 = new Vector4(0, -1., 0.); private static const FACTORY : Factory = Factory.getFactory(Vector4); private static const UPDATE_NONE : uint = 0; private static const UPDATE_LENGTH : uint = 1; private static const UPDATE_LENGTH_SQ : uint = 2; private static const UPDATE_ALL : uint = 3; // UPDATE_LENGTH | UPDATE_LENGTH_SQ; private static const DATA_DESCRIPTOR : Object = { 'x' : 'x', 'y' : 'y', 'z' : 'z', 'w' : 'w' } minko_math var _vector : Vector3D = new Vector3D(); private var _update : uint = 0; private var _length : Number = 0.; private var _lengthSq : Number = 0.; private var _locked : Boolean = false; private var _changed : Signal = new Signal('Vector4.changed'); public function get x() : Number { return _vector.x; } public function set x(value : Number) : void { if (value != _vector.x) { _vector.x = value; _update = UPDATE_ALL; if (!_locked) _changed.execute(this); } } public function get y() : Number { return _vector.y; } public function set y(value : Number) : void { if (value != _vector.y) { _vector.y = value; _update = UPDATE_ALL; if (!_locked) _changed.execute(this); } } public function get z() : Number { return _vector.z; } public function set z(value : Number) : void { if (value != _vector.z) { _vector.z = value; _update = UPDATE_ALL; if (!_locked) _changed.execute(this); } } public function get w() : Number { return _vector.w; } public function set w(value : Number) : void { if (value != _vector.w) { _vector.w = value; _update = UPDATE_ALL; if (!_locked) _changed.execute(this); } } public function get lengthSquared() : Number { if (_update & UPDATE_LENGTH_SQ) { _update ^= UPDATE_LENGTH_SQ; _lengthSq = _vector.x * _vector.x + _vector.y * _vector.y + _vector.z * _vector.z; } return _lengthSq; } public function get length() : Number { if (_update & UPDATE_LENGTH) { _update ^= UPDATE_LENGTH; _length = Math.sqrt(lengthSquared); } return _length; } public function get locked() : Boolean { return _locked; } public function get changed() : Signal { return _changed; } public function Vector4(x : Number = 0., y : Number = 0., z : Number = 0., w : Number = 1.) { _vector.x = x; _vector.y = y; _vector.z = z; _vector.w = w; _update = UPDATE_ALL; } public static function add(u : Vector4, v : Vector4, out : Vector4 = null) : Vector4 { out = copy(u, out); return out.incrementBy(v); } public static function subtract(u : Vector4, v : Vector4, out : Vector4 = null) : Vector4 { out = copy(u, out); return out.decrementBy(v); } public static function dotProduct(u : Vector4, v : Vector4) : Number { return u._vector.dotProduct(v._vector); } public static function crossProduct(u : Vector4, v : Vector4) : Vector4 { return new Vector4( u._vector.y * v._vector.z - v._vector.y * u._vector.z, u._vector.z * v._vector.x - v._vector.z * u._vector.x, u._vector.x * v._vector.y - v._vector.x * u._vector.y ); } public function compareTo(v : Vector4, allFour : Boolean = false) : Boolean { return _vector.x == v._vector.x && _vector.y == v._vector.y && _vector.z == v._vector.z && (!allFour || (_vector.w == v._vector.w)); } public static function distance(u : Vector4, v : Vector4) : Number { return Vector3D.distance(u._vector, v._vector); } public function copyFrom(source : Vector4) : Vector4 { return set(source.x, source.y, source.z, source.w); } public function incrementBy(vector : Vector4) : Vector4 { _vector.incrementBy(vector._vector); _update = UPDATE_ALL; _changed.execute(this); return this; } public function decrementBy(vector : Vector4) : Vector4 { _vector.decrementBy(vector._vector); _update = UPDATE_ALL; _changed.execute(this); return this; } public function scaleBy(scale : Number) : Vector4 { _vector.scaleBy(scale); _update = UPDATE_ALL; _changed.execute(this); return this; } public function lerp(target : Vector4, ratio : Number) : Vector4 { if (ratio == 1.) return copyFrom(target); if (ratio != 0.) { var x : Number = _vector.x; var y : Number = _vector.y; var z : Number = _vector.z; var w : Number = _vector.w; set( x + (target._vector.x - x) * ratio, y + (target._vector.y - y) * ratio, z + (target._vector.z - z) * ratio, w + (target._vector.w - w) * ratio ); } return this; } public function equals(v : Vector4, allFour : Boolean = false, tolerance : Number = 0.) : Boolean { return tolerance ? _vector.nearEquals(v._vector, tolerance, allFour); : _vector.equals(v._vector, allFour) } public function project() : Vector4 { _vector.x /= _vector.w; _vector.y /= _vector.w; _vector.z /= _vector.w; _update = UPDATE_ALL; _changed.execute(this); return this; } public function normalize() : Vector4 { var l : Number = length; if (l != 0.) { _vector.x /= l; _vector.y /= l; _vector.z /= l; _length = 1.; _lengthSq = 1.; _update = UPDATE_NONE; _changed.execute(this); } return this; } public function crossProduct(vector : Vector4) : Vector4 { var x : Number = _vector.x; var y : Number = _vector.y; var z : Number = _vector.z; _vector.x = y * vector._vector.z - vector._vector.y * z; _vector.y = z * vector._vector.x - vector._vector.z * x; _vector.z = x * vector._vector.y - vector._vector.x * y; _update = UPDATE_ALL; _changed.execute(this); return this; } public function getVector3D() : Vector3D { return _vector.clone(); } public function set(x : Number, y : Number, z : Number, w : Number = 1.) : Vector4 { if (x != _vector.x || y != _vector.y || z != _vector.z || w != _vector.w) { _vector.setTo(x, y, z); _vector.w = w; _update = UPDATE_ALL; if (!_locked) _changed.execute(this); } return this; } public function toString() : String { return '(' + _vector.x + ', ' + _vector.y + ', ' + _vector.z + ', ' + _vector.w + ')'; } public static function scale(v : Vector4, s : Number, out : Vector4 = null) : Vector4 { out ||= FACTORY.create() as Vector4; out.set(v._vector.x * s, v._vector.y * s, v._vector.z * s, v._vector.w * s); return out; } public function toVector3D(out : Vector3D = null) : Vector3D { if (!out) return _vector.clone(); out.x = _vector.x; out.y = _vector.y; out.z = _vector.z; out.w = _vector.w; return out; } public static function normalize(v : Vector4, out : Vector4 = null) : Vector4 { out = copy(v, out); return out.normalize(); } public function lock() : void { _locked = true; } public function unlock() : void { _locked = false; _changed.execute(this); } public function clone() : Vector4 { return new Vector4(_vector.x, _vector.y, _vector.z, _vector.w); } } }
package aerys.minko.type.math { import aerys.minko.ns.minko_math; import aerys.minko.type.Factory; import aerys.minko.type.Signal; import aerys.minko.type.binding.IWatchable; import flash.geom.Vector3D; public class Vector4 implements IWatchable { use namespace minko_math; public static const X_AXIS : Vector4 = new Vector4(1., 0., 0.); public static const Y_AXIS : Vector4 = new Vector4(0., 1., 0.); public static const Z_AXIS : Vector4 = new Vector4(0., 0., 1.); public static const ZERO : Vector4 = new Vector4(0., 0., 0., 0.); public static const ONE : Vector4 = new Vector4(1., 1., 1., 1.); public static const FORWARD : Vector4 = Z_AXIS; public static const BACKWARD : Vector4 = new Vector4(0., 0., -1.); public static const LEFT : Vector4 = new Vector4(-1, 0., 0.); public static const RIGHT : Vector4 = new Vector4(1, 0., 0.); public static const UP : Vector4 = Y_AXIS; public static const DOWN : Vector4 = new Vector4(0, -1., 0.); private static const FACTORY : Factory = Factory.getFactory(Vector4); private static const UPDATE_NONE : uint = 0; private static const UPDATE_LENGTH : uint = 1; private static const UPDATE_LENGTH_SQ : uint = 2; private static const UPDATE_ALL : uint = 3; // UPDATE_LENGTH | UPDATE_LENGTH_SQ; private static const DATA_DESCRIPTOR : Object = { 'x' : 'x', 'y' : 'y', 'z' : 'z', 'w' : 'w' }; minko_math var _vector : Vector3D = new Vector3D(); private var _update : uint = 0; private var _length : Number = 0.; private var _lengthSq : Number = 0.; private var _locked : Boolean = false; private var _changed : Signal = new Signal('Vector4.changed'); public function get x() : Number { return _vector.x; } public function set x(value : Number) : void { if (value != _vector.x) { _vector.x = value; _update = UPDATE_ALL; if (!_locked) _changed.execute(this); } } public function get y() : Number { return _vector.y; } public function set y(value : Number) : void { if (value != _vector.y) { _vector.y = value; _update = UPDATE_ALL; if (!_locked) _changed.execute(this); } } public function get z() : Number { return _vector.z; } public function set z(value : Number) : void { if (value != _vector.z) { _vector.z = value; _update = UPDATE_ALL; if (!_locked) _changed.execute(this); } } public function get w() : Number { return _vector.w; } public function set w(value : Number) : void { if (value != _vector.w) { _vector.w = value; _update = UPDATE_ALL; if (!_locked) _changed.execute(this); } } public function get lengthSquared() : Number { if (_update & UPDATE_LENGTH_SQ) { _update ^= UPDATE_LENGTH_SQ; _lengthSq = _vector.x * _vector.x + _vector.y * _vector.y + _vector.z * _vector.z; } return _lengthSq; } public function get length() : Number { if (_update & UPDATE_LENGTH) { _update ^= UPDATE_LENGTH; _length = Math.sqrt(lengthSquared); } return _length; } public function get locked() : Boolean { return _locked; } public function get changed() : Signal { return _changed; } public function Vector4(x : Number = 0., y : Number = 0., z : Number = 0., w : Number = 1.) { _vector.x = x; _vector.y = y; _vector.z = z; _vector.w = w; _update = UPDATE_ALL; } public static function add(u : Vector4, v : Vector4, out : Vector4 = null) : Vector4 { out ||= new Vector4(); out.copyFrom(u); return out.incrementBy(v); } public static function subtract(u : Vector4, v : Vector4, out : Vector4 = null) : Vector4 { out ||= new Vector4(); out.copyFrom(u); return out.decrementBy(v); } public static function dotProduct(u : Vector4, v : Vector4) : Number { return u._vector.dotProduct(v._vector); } public static function crossProduct(u : Vector4, v : Vector4) : Vector4 { return new Vector4( u._vector.y * v._vector.z - v._vector.y * u._vector.z, u._vector.z * v._vector.x - v._vector.z * u._vector.x, u._vector.x * v._vector.y - v._vector.x * u._vector.y ); } public function compareTo(v : Vector4, allFour : Boolean = false) : Boolean { return _vector.x == v._vector.x && _vector.y == v._vector.y && _vector.z == v._vector.z && (!allFour || (_vector.w == v._vector.w)); } public static function distance(u : Vector4, v : Vector4) : Number { return Vector3D.distance(u._vector, v._vector); } public function copyFrom(source : Vector4) : Vector4 { return set(source.x, source.y, source.z, source.w); } public function incrementBy(vector : Vector4) : Vector4 { _vector.incrementBy(vector._vector); _update = UPDATE_ALL; _changed.execute(this); return this; } public function decrementBy(vector : Vector4) : Vector4 { _vector.decrementBy(vector._vector); _update = UPDATE_ALL; _changed.execute(this); return this; } public function scaleBy(scale : Number) : Vector4 { _vector.scaleBy(scale); _update = UPDATE_ALL; _changed.execute(this); return this; } public function lerp(target : Vector4, ratio : Number) : Vector4 { if (ratio == 1.) return copyFrom(target); if (ratio != 0.) { var x : Number = _vector.x; var y : Number = _vector.y; var z : Number = _vector.z; var w : Number = _vector.w; set( x + (target._vector.x - x) * ratio, y + (target._vector.y - y) * ratio, z + (target._vector.z - z) * ratio, w + (target._vector.w - w) * ratio ); } return this; } public function equals(v : Vector4, allFour : Boolean = false, tolerance : Number = 0.) : Boolean { return tolerance ? _vector.nearEquals(v._vector, tolerance, allFour) : _vector.equals(v._vector, allFour); } public function project() : Vector4 { _vector.x /= _vector.w; _vector.y /= _vector.w; _vector.z /= _vector.w; _update = UPDATE_ALL; _changed.execute(this); return this; } public function normalize() : Vector4 { var l : Number = length; if (l != 0.) { _vector.x /= l; _vector.y /= l; _vector.z /= l; _length = 1.; _lengthSq = 1.; _update = UPDATE_NONE; _changed.execute(this); } return this; } public function crossProduct(vector : Vector4) : Vector4 { var x : Number = _vector.x; var y : Number = _vector.y; var z : Number = _vector.z; _vector.x = y * vector._vector.z - vector._vector.y * z; _vector.y = z * vector._vector.x - vector._vector.z * x; _vector.z = x * vector._vector.y - vector._vector.x * y; _update = UPDATE_ALL; _changed.execute(this); return this; } public function getVector3D() : Vector3D { return _vector.clone(); } public function set(x : Number, y : Number, z : Number, w : Number = 1.) : Vector4 { if (x != _vector.x || y != _vector.y || z != _vector.z || w != _vector.w) { _vector.setTo(x, y, z); _vector.w = w; _update = UPDATE_ALL; if (!_locked) _changed.execute(this); } return this; } public function toString() : String { return '(' + _vector.x + ', ' + _vector.y + ', ' + _vector.z + ', ' + _vector.w + ')'; } public static function scale(v : Vector4, s : Number, out : Vector4 = null) : Vector4 { out ||= FACTORY.create() as Vector4; out.set(v._vector.x * s, v._vector.y * s, v._vector.z * s, v._vector.w * s); return out; } public function toVector3D(out : Vector3D = null) : Vector3D { if (!out) return _vector.clone(); out.x = _vector.x; out.y = _vector.y; out.z = _vector.z; out.w = _vector.w; return out; } public function lock() : void { _locked = true; } public function unlock() : void { _locked = false; _changed.execute(this); } public function clone() : Vector4 { return new Vector4(_vector.x, _vector.y, _vector.z, _vector.w); } } }
fix Vector4::add() and Vector4::subtract()
fix Vector4::add() and Vector4::subtract()
ActionScript
mit
aerys/minko-as3
1ea1e942ba097cb51667354a615eeaed632ea268
src/main/actionscript/com/dotfold/dotvimstat/model/LikeEntity.as
src/main/actionscript/com/dotfold/dotvimstat/model/LikeEntity.as
package com.dotfold.dotvimstat.model { /** * * @author jamesmcnamee * */ public class LikeEntity extends BaseEntity { /** * */ public function LikeEntity() { super(); } public var description:String; public var duration:int; public var embed_privacy:String; public var height:int; public var liked_on:String; public var mobile_url:String; public var stats_number_of_comments:int; public var stats_number_of_likes:int; public var stats_number_of_plays:int; public var tags:String; public var thumbnail_large:String; public var thumbnail_medium:String; public var thumbnail_small:String; public var title:String; public var upload_date:int; public var url:String; public var user_id:int; public var user_name:String; public var user_portrait_huge:String; public var user_portrait_large:String; public var user_portrait_medium:String; public var user_portrait_small:String; public var user_url:String; public var width:int; } }
package com.dotfold.dotvimstat.model { /** * * @author jamesmcnamee * */ public class LikeEntity extends BaseEntity { /** * */ public function LikeEntity() { super(); } public var description:String; public var duration:int; public var embed_privacy:String; public var height:int; public var liked_on:Date; public var mobile_url:String; public var stats_number_of_comments:int; public var stats_number_of_likes:int; public var stats_number_of_plays:int; public var tags:String; public var thumbnail_large:String; public var thumbnail_medium:String; public var thumbnail_small:String; public var title:String; public var upload_date:Date; public var url:String; public var user_id:int; public var user_name:String; public var user_portrait_huge:String; public var user_portrait_large:String; public var user_portrait_medium:String; public var user_portrait_small:String; public var user_url:String; public var width:int; } }
use improved serialization for entity
[feat] use improved serialization for entity - use real Date objects - use Image collections
ActionScript
mit
dotfold/dotvimstat
bd2ea43b96f9f0de446fbd544c053a401aedc4dd
flash-src/WebSocket.as
flash-src/WebSocket.as
// Copyright: Hiroshi Ichikawa <http://gimite.net/en/> // License: New BSD License // Reference: http://dev.w3.org/html5/websockets/ // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-31 package { import flash.display.*; import flash.events.*; import flash.external.*; import flash.net.*; import flash.system.*; import flash.utils.*; import mx.core.*; import mx.controls.*; import mx.events.*; import mx.utils.*; import com.adobe.net.proxies.RFC2817Socket; import com.hurlant.crypto.tls.TLSSocket; import com.hurlant.crypto.tls.TLSConfig; import com.hurlant.crypto.tls.TLSEngine; import com.hurlant.crypto.tls.TLSSecurityParameters; import com.gsolo.encryption.MD5; [Event(name="message", type="WebSocketMessageEvent")] [Event(name="open", type="flash.events.Event")] [Event(name="close", type="flash.events.Event")] [Event(name="error", type="flash.events.Event")] [Event(name="stateChange", type="WebSocketStateEvent")] public class WebSocket extends EventDispatcher { private static var CONNECTING:int = 0; private static var OPEN:int = 1; private static var CLOSING:int = 2; private static var CLOSED:int = 3; //private var rawSocket:RFC2817Socket; private var rawSocket:Socket; private var tlsSocket:TLSSocket; private var tlsConfig:TLSConfig; private var socket:Socket; private var main:WebSocketMain; private var url:String; private var scheme:String; private var host:String; private var port:uint; private var path:String; private var origin:String; private var protocol:String; private var buffer:ByteArray = new ByteArray(); private var headerState:int = 0; private var readyState:int = CONNECTING; private var bufferedAmount:int = 0; private var headers:String; private var noiseChars:Array; private var expectedDigest:String; public function WebSocket( main:WebSocketMain, url:String, protocol:String, proxyHost:String = null, proxyPort:int = 0, headers:String = null) { this.main = main; initNoiseChars(); this.url = url; var m:Array = url.match(/^(\w+):\/\/([^\/:]+)(:(\d+))?(\/.*)?$/); if (!m) main.fatal("SYNTAX_ERR: invalid url: " + url); this.scheme = m[1]; this.host = m[2]; this.port = parseInt(m[4] || "80"); this.path = m[5] || "/"; this.origin = main.getOrigin(); this.protocol = protocol; // if present and not the empty string, headers MUST end with \r\n // headers should be zero or more complete lines, for example // "Header1: xxx\r\nHeader2: yyyy\r\n" this.headers = headers; /* socket = new RFC2817Socket(); // if no proxy information is supplied, it acts like a normal Socket // @see RFC2817Socket::connect if (proxyHost != null && proxyPort != 0){ socket.setProxyInfo(proxyHost, proxyPort); } */ ExternalInterface.call("console.log", "[WebSocket] scheme: " + scheme); rawSocket = new Socket(); rawSocket.addEventListener(Event.CLOSE, onSocketClose); rawSocket.addEventListener(Event.CONNECT, onSocketConnect); rawSocket.addEventListener(IOErrorEvent.IO_ERROR, onSocketIoError); rawSocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSocketSecurityError); if (scheme == "wss") { tlsConfig= new TLSConfig(TLSEngine.CLIENT, null, null, null, null, null, TLSSecurityParameters.PROTOCOL_VERSION); tlsConfig.trustSelfSignedCertificates = true; tlsConfig.ignoreCommonNameMismatch = true; tlsSocket = new TLSSocket(); tlsSocket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData); socket = (tlsSocket as Socket); } else { rawSocket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData); socket = (rawSocket as Socket); } rawSocket.connect(host, port); } public function send(data:String):int { if (readyState == OPEN) { socket.writeByte(0x00); socket.writeUTFBytes(decodeURIComponent(data)); socket.writeByte(0xff); socket.flush(); main.log("sent: " + data); return -1; } else if (readyState == CLOSED) { var bytes:ByteArray = new ByteArray(); bytes.writeUTFBytes(decodeURIComponent(data)); bufferedAmount += bytes.length; // not sure whether it should include \x00 and \xff // We use return value to let caller know bufferedAmount because we cannot fire // stateChange event here which causes weird error: // > You are trying to call recursively into the Flash Player which is not allowed. return bufferedAmount; } else { main.fatal("INVALID_STATE_ERR: invalid state"); return 0; } } public function close():void { main.log("close"); try { socket.close(); } catch (ex:Error) { } readyState = CLOSED; // We don't fire any events here because it causes weird error: // > You are trying to call recursively into the Flash Player which is not allowed. // We do something equivalent in JavaScript WebSocket#close instead. } public function getReadyState():int { return readyState; } public function getBufferedAmount():int { return bufferedAmount; } private function onSocketConnect(event:Event):void { main.log("connected"); if (scheme == "wss") { ExternalInterface.call("console.log", "[WebSocket] starting SSL/TLS"); tlsSocket.startTLS(rawSocket, host, tlsConfig); } var hostValue:String = host + (port == 80 ? "" : ":" + port); var cookie:String = ""; if (main.getCallerHost() == host) { cookie = ExternalInterface.call("function(){return document.cookie}"); } var key1:String = generateKey(); var key2:String = generateKey(); var key3:String = generateKey3(); expectedDigest = getSecurityDigest(key1, key2, key3); var opt:String = ""; if (protocol) opt += "WebSocket-Protocol: " + protocol + "\r\n"; // if caller passes additional headers they must end with "\r\n" if (headers) opt += headers; var req:String = StringUtil.substitute( "GET {0} HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "Host: {1}\r\n" + "Origin: {2}\r\n" + "Cookie: {3}\r\n" + "Sec-WebSocket-Key1: {4}\r\n" + "Sec-WebSocket-Key2: {5}\r\n" + "{6}" + "\r\n", path, hostValue, origin, cookie, key1, key2, opt); main.log("request header:\n" + req); socket.writeUTFBytes(req); main.log("sent key3: " + key3); main.log("expected digest: " + expectedDigest); writeBytes(key3); socket.flush(); } private function onSocketClose(event:Event):void { main.log("closed"); readyState = CLOSED; notifyStateChange(); dispatchEvent(new Event("close")); } private function onSocketIoError(event:IOErrorEvent):void { var message:String; if (readyState == CONNECTING) { message = "cannot connect to Web Socket server at " + url + " (IoError)"; } else { message = "error communicating with Web Socket server at " + url + " (IoError)"; } onError(message); } private function onSocketSecurityError(event:SecurityErrorEvent):void { var message:String; if (readyState == CONNECTING) { message = "cannot connect to Web Socket server at " + url + " (SecurityError)\n" + "make sure the server is running and Flash socket policy file is correctly placed"; } else { message = "error communicating with Web Socket server at " + url + " (SecurityError)"; } onError(message); } private function onError(message:String):void { var state:int = readyState; if (state == CLOSED) return; main.error(message); close(); notifyStateChange(); dispatchEvent(new Event(state == CONNECTING ? "close" : "error")); } private function onSocketData(event:ProgressEvent):void { var pos:int = buffer.length; socket.readBytes(buffer, pos); for (; pos < buffer.length; ++pos) { if (headerState < 4) { // try to find "\r\n\r\n" if ((headerState == 0 || headerState == 2) && buffer[pos] == 0x0d) { ++headerState; } else if ((headerState == 1 || headerState == 3) && buffer[pos] == 0x0a) { ++headerState; } else { headerState = 0; } if (headerState == 4) { var headerStr:String = buffer.readUTFBytes(pos + 1); main.log("response header:\n" + headerStr); if (!validateHeader(headerStr)) return; makeBufferCompact(); pos = -1; } } else if (headerState == 4) { var replyDigest:String = readBytes(buffer, 16); main.log("reply digest: " + replyDigest); if (replyDigest != expectedDigest) { onError("digest doesn't match: " + replyDigest + " != " + expectedDigest); return; } headerState = 5; makeBufferCompact(); pos = -1; readyState = OPEN; notifyStateChange(); dispatchEvent(new Event("open")); } else { if (buffer[pos] == 0xff) { if (buffer.readByte() != 0x00) { onError("data must start with \\x00"); return; } var data:String = buffer.readUTFBytes(pos - 1); main.log("received: " + data); dispatchEvent(new WebSocketMessageEvent("message", encodeURIComponent(data))); buffer.readByte(); makeBufferCompact(); pos = -1; } } } } private function validateHeader(headerStr:String):Boolean { var lines:Array = headerStr.split(/\r\n/); if (!lines[0].match(/^HTTP\/1.1 101 /)) { onError("bad response: " + lines[0]); return false; } var header:Object = {}; for (var i:int = 1; i < lines.length; ++i) { if (lines[i].length == 0) continue; var m:Array = lines[i].match(/^(\S+): (.*)$/); if (!m) { onError("failed to parse response header line: " + lines[i]); return false; } header[m[1]] = m[2]; } if (header["Upgrade"] != "WebSocket") { onError("invalid Upgrade: " + header["Upgrade"]); return false; } if (header["Connection"] != "Upgrade") { onError("invalid Connection: " + header["Connection"]); return false; } var resOrigin:String = header["Sec-WebSocket-Origin"].toLowerCase(); if (resOrigin != origin) { onError("origin doesn't match: '" + resOrigin + "' != '" + origin + "'"); return false; } if (protocol && header["Sec-WebSocket-Protocol"] != protocol) { onError("protocol doesn't match: '" + header["WebSocket-Protocol"] + "' != '" + protocol + "'"); return false; } return true; } private function makeBufferCompact():void { if (buffer.position == 0) return; var nextBuffer:ByteArray = new ByteArray(); buffer.readBytes(nextBuffer); buffer = nextBuffer; } private function notifyStateChange():void { dispatchEvent(new WebSocketStateEvent("stateChange", readyState, bufferedAmount)); } private function initNoiseChars():void { noiseChars = new Array(); for (var i:int = 0x21; i <= 0x2f; ++i) { noiseChars.push(String.fromCharCode(i)); } for (var j:int = 0x3a; j <= 0x7a; ++j) { noiseChars.push(String.fromCharCode(j)); } } private function generateKey():String { var spaces:uint = randomInt(1, 12); var max:uint = uint.MAX_VALUE / spaces; var number:uint = randomInt(0, max); var key:String = (number * spaces).toString(); var noises:int = randomInt(1, 12); var pos:int; for (var i:int = 0; i < noises; ++i) { var char:String = noiseChars[randomInt(0, noiseChars.length - 1)]; pos = randomInt(0, key.length); key = key.substr(0, pos) + char + key.substr(pos); } for (var j:int = 0; j < spaces; ++j) { pos = randomInt(1, key.length - 1); key = key.substr(0, pos) + " " + key.substr(pos); } return key; } private function generateKey3():String { var key3:String = ""; for (var i:int = 0; i < 8; ++i) { key3 += String.fromCharCode(randomInt(0, 255)); } return key3; } private function getSecurityDigest(key1:String, key2:String, key3:String):String { var bytes1:String = keyToBytes(key1); var bytes2:String = keyToBytes(key2); return MD5.rstr_md5(bytes1 + bytes2 + key3); } private function keyToBytes(key:String):String { var keyNum:uint = parseInt(key.replace(/[^\d]/g, "")); var spaces:uint = 0; for (var i:int = 0; i < key.length; ++i) { if (key.charAt(i) == " ") ++spaces; } var resultNum:uint = keyNum / spaces; var bytes:String = ""; for (var j:int = 3; j >= 0; --j) { bytes += String.fromCharCode((resultNum >> (j * 8)) & 0xff); } return bytes; } private function writeBytes(bytes:String):void { for (var i:int = 0; i < bytes.length; ++i) { socket.writeByte(bytes.charCodeAt(i)); } } private function readBytes(buffer:ByteArray, numBytes:int):String { var bytes:String = ""; for (var i:int = 0; i < numBytes; ++i) { // & 0xff is to make \x80-\xff positive number. bytes += String.fromCharCode(buffer.readByte() & 0xff); } return bytes; } private function randomInt(min:uint, max:uint):uint { return min + Math.floor(Math.random() * (Number(max) - min + 1)); } // for debug private function dumpBytes(bytes:String):void { var output:String = ""; for (var i:int = 0; i < bytes.length; ++i) { output += bytes.charCodeAt(i).toString() + ", "; } main.log(output); } } }
// Copyright: Hiroshi Ichikawa <http://gimite.net/en/> // License: New BSD License // Reference: http://dev.w3.org/html5/websockets/ // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-31 package { import flash.display.*; import flash.events.*; import flash.external.*; import flash.net.*; import flash.system.*; import flash.utils.*; import mx.core.*; import mx.controls.*; import mx.events.*; import mx.utils.*; import com.adobe.net.proxies.RFC2817Socket; import com.hurlant.crypto.tls.TLSSocket; import com.hurlant.crypto.tls.TLSConfig; import com.hurlant.crypto.tls.TLSEngine; import com.hurlant.crypto.tls.TLSSecurityParameters; import com.gsolo.encryption.MD5; [Event(name="message", type="WebSocketMessageEvent")] [Event(name="open", type="flash.events.Event")] [Event(name="close", type="flash.events.Event")] [Event(name="error", type="flash.events.Event")] [Event(name="stateChange", type="WebSocketStateEvent")] public class WebSocket extends EventDispatcher { private static var CONNECTING:int = 0; private static var OPEN:int = 1; private static var CLOSING:int = 2; private static var CLOSED:int = 3; //private var rawSocket:RFC2817Socket; private var rawSocket:Socket; private var tlsSocket:TLSSocket; private var tlsConfig:TLSConfig; private var socket:Socket; private var main:WebSocketMain; private var url:String; private var scheme:String; private var host:String; private var port:uint; private var path:String; private var origin:String; private var protocol:String; private var buffer:ByteArray = new ByteArray(); private var headerState:int = 0; private var readyState:int = CONNECTING; private var bufferedAmount:int = 0; private var headers:String; private var noiseChars:Array; private var expectedDigest:String; public function WebSocket( main:WebSocketMain, url:String, protocol:String, proxyHost:String = null, proxyPort:int = 0, headers:String = null) { this.main = main; initNoiseChars(); this.url = url; var m:Array = url.match(/^(\w+):\/\/([^\/:]+)(:(\d+))?(\/.*)?$/); if (!m) main.fatal("SYNTAX_ERR: invalid url: " + url); this.scheme = m[1]; this.host = m[2]; this.port = parseInt(m[4] || "80"); this.path = m[5] || "/"; this.origin = main.getOrigin(); this.protocol = protocol; // if present and not the empty string, headers MUST end with \r\n // headers should be zero or more complete lines, for example // "Header1: xxx\r\nHeader2: yyyy\r\n" this.headers = headers; /* socket = new RFC2817Socket(); // if no proxy information is supplied, it acts like a normal Socket // @see RFC2817Socket::connect if (proxyHost != null && proxyPort != 0){ socket.setProxyInfo(proxyHost, proxyPort); } */ ExternalInterface.call("console.log", "[WebSocket] scheme: " + scheme); rawSocket = new Socket(); rawSocket.addEventListener(Event.CLOSE, onSocketClose); rawSocket.addEventListener(Event.CONNECT, onSocketConnect); rawSocket.addEventListener(IOErrorEvent.IO_ERROR, onSocketIoError); rawSocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSocketSecurityError); if (scheme == "wss") { tlsConfig= new TLSConfig(TLSEngine.CLIENT, null, null, null, null, null, TLSSecurityParameters.PROTOCOL_VERSION); tlsConfig.trustSelfSignedCertificates = true; tlsConfig.ignoreCommonNameMismatch = true; tlsSocket = new TLSSocket(); tlsSocket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData); socket = (tlsSocket as Socket); } else { rawSocket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData); socket = (rawSocket as Socket); } rawSocket.connect(host, port); } public function send(data:String):int { if (readyState == OPEN) { socket.writeByte(0x00); socket.writeUTFBytes(decodeURIComponent(data)); socket.writeByte(0xff); socket.flush(); main.log("sent: " + data); return -1; } else if (readyState == CLOSED) { var bytes:ByteArray = new ByteArray(); bytes.writeUTFBytes(decodeURIComponent(data)); bufferedAmount += bytes.length; // not sure whether it should include \x00 and \xff // We use return value to let caller know bufferedAmount because we cannot fire // stateChange event here which causes weird error: // > You are trying to call recursively into the Flash Player which is not allowed. return bufferedAmount; } else { main.fatal("INVALID_STATE_ERR: invalid state"); return 0; } } public function close():void { main.log("close"); try { socket.close(); } catch (ex:Error) { } readyState = CLOSED; // We don't fire any events here because it causes weird error: // > You are trying to call recursively into the Flash Player which is not allowed. // We do something equivalent in JavaScript WebSocket#close instead. } public function getReadyState():int { return readyState; } public function getBufferedAmount():int { return bufferedAmount; } private function onSocketConnect(event:Event):void { main.log("connected"); if (scheme == "wss") { ExternalInterface.call("console.log", "[WebSocket] starting SSL/TLS"); tlsSocket.startTLS(rawSocket, host, tlsConfig); } var hostValue:String = host + (port == 80 ? "" : ":" + port); var cookie:String = ""; if (main.getCallerHost() == host) { cookie = ExternalInterface.call("function(){return document.cookie}"); } var key1:String = generateKey(); var key2:String = generateKey(); var key3:String = generateKey3(); expectedDigest = getSecurityDigest(key1, key2, key3); var opt:String = ""; if (protocol) opt += "WebSocket-Protocol: " + protocol + "\r\n"; // if caller passes additional headers they must end with "\r\n" if (headers) opt += headers; var req:String = StringUtil.substitute( "GET {0} HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "Host: {1}\r\n" + "Origin: {2}\r\n" + "Cookie: {3}\r\n" + "Sec-WebSocket-Key1: {4}\r\n" + "Sec-WebSocket-Key2: {5}\r\n" + "{6}" + "\r\n", path, hostValue, origin, cookie, key1, key2, opt); main.log("request header:\n" + req); socket.writeUTFBytes(req); main.log("sent key3: " + key3); writeBytes(key3); socket.flush(); } private function onSocketClose(event:Event):void { main.log("closed"); readyState = CLOSED; notifyStateChange(); dispatchEvent(new Event("close")); } private function onSocketIoError(event:IOErrorEvent):void { var message:String; if (readyState == CONNECTING) { message = "cannot connect to Web Socket server at " + url + " (IoError)"; } else { message = "error communicating with Web Socket server at " + url + " (IoError)"; } onError(message); } private function onSocketSecurityError(event:SecurityErrorEvent):void { var message:String; if (readyState == CONNECTING) { message = "cannot connect to Web Socket server at " + url + " (SecurityError)\n" + "make sure the server is running and Flash socket policy file is correctly placed"; } else { message = "error communicating with Web Socket server at " + url + " (SecurityError)"; } onError(message); } private function onError(message:String):void { var state:int = readyState; if (state == CLOSED) return; main.error(message); close(); notifyStateChange(); dispatchEvent(new Event(state == CONNECTING ? "close" : "error")); } private function onSocketData(event:ProgressEvent):void { var pos:int = buffer.length; socket.readBytes(buffer, pos); for (; pos < buffer.length; ++pos) { if (headerState < 4) { // try to find "\r\n\r\n" if ((headerState == 0 || headerState == 2) && buffer[pos] == 0x0d) { ++headerState; } else if ((headerState == 1 || headerState == 3) && buffer[pos] == 0x0a) { ++headerState; } else { headerState = 0; } if (headerState == 4) { var headerStr:String = buffer.readUTFBytes(pos + 1); main.log("response header:\n" + headerStr); if (!validateHeader(headerStr)) return; makeBufferCompact(); pos = -1; } } else if (headerState == 4) { if (pos == 15) { var replyDigest:String = readBytes(buffer, 16); main.log("reply digest: " + replyDigest); if (replyDigest != expectedDigest) { onError("digest doesn't match: " + replyDigest + " != " + expectedDigest); return; } headerState = 5; makeBufferCompact(); pos = -1; readyState = OPEN; notifyStateChange(); dispatchEvent(new Event("open")); } } else { if (buffer[pos] == 0xff) { if (buffer.readByte() != 0x00) { onError("data must start with \\x00"); return; } var data:String = buffer.readUTFBytes(pos - 1); main.log("received: " + data); dispatchEvent(new WebSocketMessageEvent("message", encodeURIComponent(data))); buffer.readByte(); makeBufferCompact(); pos = -1; } } } } private function validateHeader(headerStr:String):Boolean { var lines:Array = headerStr.split(/\r\n/); if (!lines[0].match(/^HTTP\/1.1 101 /)) { onError("bad response: " + lines[0]); return false; } var header:Object = {}; for (var i:int = 1; i < lines.length; ++i) { if (lines[i].length == 0) continue; var m:Array = lines[i].match(/^(\S+): (.*)$/); if (!m) { onError("failed to parse response header line: " + lines[i]); return false; } header[m[1]] = m[2]; } if (header["Upgrade"] != "WebSocket") { onError("invalid Upgrade: " + header["Upgrade"]); return false; } if (header["Connection"] != "Upgrade") { onError("invalid Connection: " + header["Connection"]); return false; } var resOrigin:String = header["Sec-WebSocket-Origin"].toLowerCase(); if (resOrigin != origin) { onError("origin doesn't match: '" + resOrigin + "' != '" + origin + "'"); return false; } if (protocol && header["Sec-WebSocket-Protocol"] != protocol) { onError("protocol doesn't match: '" + header["WebSocket-Protocol"] + "' != '" + protocol + "'"); return false; } return true; } private function makeBufferCompact():void { if (buffer.position == 0) return; var nextBuffer:ByteArray = new ByteArray(); buffer.readBytes(nextBuffer); buffer = nextBuffer; } private function notifyStateChange():void { dispatchEvent(new WebSocketStateEvent("stateChange", readyState, bufferedAmount)); } private function initNoiseChars():void { noiseChars = new Array(); for (var i:int = 0x21; i <= 0x2f; ++i) { noiseChars.push(String.fromCharCode(i)); } for (var j:int = 0x3a; j <= 0x7a; ++j) { noiseChars.push(String.fromCharCode(j)); } } private function generateKey():String { var spaces:uint = randomInt(1, 12); var max:uint = uint.MAX_VALUE / spaces; var number:uint = randomInt(0, max); var key:String = (number * spaces).toString(); var noises:int = randomInt(1, 12); var pos:int; for (var i:int = 0; i < noises; ++i) { var char:String = noiseChars[randomInt(0, noiseChars.length - 1)]; pos = randomInt(0, key.length); key = key.substr(0, pos) + char + key.substr(pos); } for (var j:int = 0; j < spaces; ++j) { pos = randomInt(1, key.length - 1); key = key.substr(0, pos) + " " + key.substr(pos); } return key; } private function generateKey3():String { var key3:String = ""; for (var i:int = 0; i < 8; ++i) { key3 += String.fromCharCode(randomInt(0, 255)); } return key3; } private function getSecurityDigest(key1:String, key2:String, key3:String):String { var bytes1:String = keyToBytes(key1); var bytes2:String = keyToBytes(key2); return MD5.rstr_md5(bytes1 + bytes2 + key3); } private function keyToBytes(key:String):String { var keyNum:uint = parseInt(key.replace(/[^\d]/g, "")); var spaces:uint = 0; for (var i:int = 0; i < key.length; ++i) { if (key.charAt(i) == " ") ++spaces; } var resultNum:uint = keyNum / spaces; var bytes:String = ""; for (var j:int = 3; j >= 0; --j) { bytes += String.fromCharCode((resultNum >> (j * 8)) & 0xff); } return bytes; } private function writeBytes(bytes:String):void { for (var i:int = 0; i < bytes.length; ++i) { socket.writeByte(bytes.charCodeAt(i)); } } private function readBytes(buffer:ByteArray, numBytes:int):String { var bytes:String = ""; for (var i:int = 0; i < numBytes; ++i) { // & 0xff is to make \x80-\xff positive number. bytes += String.fromCharCode(buffer.readByte() & 0xff); } return bytes; } private function randomInt(min:uint, max:uint):uint { return min + Math.floor(Math.random() * (Number(max) - min + 1)); } // for debug private function dumpBytes(bytes:String):void { var output:String = ""; for (var i:int = 0; i < bytes.length; ++i) { output += bytes.charCodeAt(i).toString() + ", "; } main.log(output); } } }
Revert "Remove invalid check of 'pos'."
Revert "Remove invalid check of 'pos'." This reverts commit 79e646611ba35f38060b3dd42fbfcfaeb92253ee.
ActionScript
bsd-3-clause
keiosweb/web-socket-js,nitzo/web-socket-js,keiosweb/web-socket-js,hehuabing/web-socket-js,keiosweb/web-socket-js,gimite/web-socket-js,hehuabing/web-socket-js,zhangxingits/web-socket-js,nitzo/web-socket-js,gimite/web-socket-js,hanicker/web-socket-js,nitzo/web-socket-js,zhangxingits/web-socket-js,hanicker/web-socket-js,hehuabing/web-socket-js,hanicker/web-socket-js,gimite/web-socket-js,zhangxingits/web-socket-js
feaa7424f35e44df95abe7f2186752755ef38535
src/org/mangui/HLS/utils/AES.as
src/org/mangui/HLS/utils/AES.as
package org.mangui.HLS.utils { import com.hurlant.crypto.symmetric.AESKey; import com.hurlant.crypto.symmetric.CBCMode; import com.hurlant.crypto.symmetric.ICipher; import com.hurlant.crypto.symmetric.IPad; import com.hurlant.crypto.symmetric.IVMode; import com.hurlant.crypto.symmetric.NullPad; import com.hurlant.crypto.symmetric.PKCS5; import flash.utils.ByteArray; import flash.utils.Timer; import flash.events.Event; import flash.events.TimerEvent; /** * Contains Utility functions for Decryption */ public class AES { private var _key:AESKey; private var _mode:ICipher; private var _iv:ByteArray; /* callback function upon read complete */ private var _callback:Function; /** Timer for decrypting packets **/ private var _timer:Timer; /** Byte data to be decrypt **/ private var _data:ByteArray; /** Byte data to be decrypt **/ private var _decrypteddata:ByteArray; /** read position **/ private var _read_position:Number; /** chunk size to avoid blocking **/ private static const CHUNK_SIZE:uint = 4096; /** is bytearray full ? **/ private var _data_complete:Boolean; public function AES(key:ByteArray,iv:ByteArray) { var pad:IPad = new PKCS5; _key = new AESKey(key); _mode = new CBCMode(_key, pad); pad.setBlockSize(_mode.getBlockSize()); _iv = iv; if (_mode is IVMode) { var ivmode:IVMode = _mode as IVMode; ivmode.IV = iv; } } public function decrypt(data:ByteArray,callback:Function):void { Log.debug("AES:async decrypt starting"); _data = data; _data_complete = false; _callback = callback; _decrypteddata = new ByteArray(); _read_position = 0; _timer = new Timer(0,0); _timer.addEventListener(TimerEvent.TIMER, _decryptData); _timer.start(); } public function notifyappend():void { //Log.info("notify append"); _timer.start(); } public function notifycomplete():void { //Log.info("notify complete"); _data_complete = true; _timer.start(); } public function cancel():void { if(_timer) { _timer.stop(); _timer = null; } } /** decrypt a small chunk of packets each time to avoid blocking **/ private function _decryptData(e:Event):void { _data.position = _read_position; if(_data.bytesAvailable) { var dumpByteArray:ByteArray = new ByteArray(); var newIv:ByteArray; var pad:IPad; if(_data.bytesAvailable <= CHUNK_SIZE) { if (_data_complete) { //Log.info("data complete, last chunk"); pad = new PKCS5; _read_position+=_data.bytesAvailable; _data.readBytes(dumpByteArray,0,_data.bytesAvailable); } else { //Log.info("data not complete, stop timer"); // data not complete, and available data less than chunk size, stop timer and return _timer.stop(); return; } } else { // bytesAvailable > CHUNK_SIZE //Log.info("process chunk"); pad = new NullPad; _read_position+=CHUNK_SIZE; _data.readBytes(dumpByteArray,0,CHUNK_SIZE); // Save new IV from ciphertext newIv = new ByteArray(); dumpByteArray.position = (CHUNK_SIZE-16); dumpByteArray.readBytes(newIv, 0, 16); } dumpByteArray.position = 0; //Log.info("before decrypt"); _mode = new CBCMode(_key, pad); pad.setBlockSize(_mode.getBlockSize()); (_mode as IVMode).IV = _iv; _mode.decrypt(dumpByteArray); //Log.info("after decrypt"); _decrypteddata.writeBytes(dumpByteArray); // switch IV to new one in case more bytes are available if(newIv) { _iv = newIv; } } else { //Log.info("no bytes available, stop timer"); _timer.stop(); if (_data_complete) { Log.debug("AES:data+decrypt completed, callback"); _timer = null; // callback _decrypteddata.position=0; _callback(_decrypteddata); } } } public function destroy():void { _key.dispose(); _key = null; _mode = null; } } }
package org.mangui.HLS.utils { import com.hurlant.crypto.symmetric.AESKey; import com.hurlant.crypto.symmetric.CBCMode; import com.hurlant.crypto.symmetric.ICipher; import com.hurlant.crypto.symmetric.IPad; import com.hurlant.crypto.symmetric.IVMode; import com.hurlant.crypto.symmetric.NullPad; import com.hurlant.crypto.symmetric.PKCS5; import flash.utils.ByteArray; import flash.utils.Timer; import flash.events.Event; import flash.events.TimerEvent; /** * Contains Utility functions for Decryption */ public class AES { private var _key:AESKey; private var _mode:ICipher; private var _iv:ByteArray; /* callback function upon read complete */ private var _callback:Function; /** Timer for decrypting packets **/ private var _timer:Timer; /** Byte data to be decrypt **/ private var _data:ByteArray; /** Byte data to be decrypt **/ private var _decrypteddata:ByteArray; /** read position **/ private var _read_position:Number; /** chunk size to avoid blocking **/ private static const CHUNK_SIZE:uint = 2048; /** is bytearray full ? **/ private var _data_complete:Boolean; public function AES(key:ByteArray,iv:ByteArray) { var pad:IPad = new PKCS5; _key = new AESKey(key); _mode = new CBCMode(_key, pad); pad.setBlockSize(_mode.getBlockSize()); _iv = iv; if (_mode is IVMode) { var ivmode:IVMode = _mode as IVMode; ivmode.IV = iv; } } public function decrypt(data:ByteArray,callback:Function):void { Log.debug("AES:async decrypt starting"); _data = data; _data_complete = false; _callback = callback; _decrypteddata = new ByteArray(); _read_position = 0; _timer = new Timer(0,0); _timer.addEventListener(TimerEvent.TIMER, _decryptTimer); _timer.start(); } public function notifyappend():void { //Log.info("notify append"); _timer.start(); } public function notifycomplete():void { //Log.info("notify complete"); _data_complete = true; _timer.start(); } public function cancel():void { if(_timer) { _timer.stop(); _timer = null; } } private function _decryptTimer(e:Event):void { var start_time:Number = new Date().getTime(); do { _decryptData(); // dont spend more than 20 ms in the decrypt timer to avoid blocking/freezing video } while (_timer.running && new Date().getTime() - start_time < 20); } /** decrypt a small chunk of packets each time to avoid blocking **/ private function _decryptData():void { _data.position = _read_position; if(_data.bytesAvailable) { var dumpByteArray:ByteArray = new ByteArray(); var newIv:ByteArray; var pad:IPad; if(_data.bytesAvailable <= CHUNK_SIZE) { if (_data_complete) { //Log.info("data complete, last chunk"); pad = new PKCS5; _read_position+=_data.bytesAvailable; _data.readBytes(dumpByteArray,0,_data.bytesAvailable); } else { //Log.info("data not complete, stop timer"); // data not complete, and available data less than chunk size, stop timer and return _timer.stop(); return; } } else { // bytesAvailable > CHUNK_SIZE //Log.info("process chunk"); pad = new NullPad; _read_position+=CHUNK_SIZE; _data.readBytes(dumpByteArray,0,CHUNK_SIZE); // Save new IV from ciphertext newIv = new ByteArray(); dumpByteArray.position = (CHUNK_SIZE-16); dumpByteArray.readBytes(newIv, 0, 16); } dumpByteArray.position = 0; //Log.info("before decrypt"); _mode = new CBCMode(_key, pad); pad.setBlockSize(_mode.getBlockSize()); (_mode as IVMode).IV = _iv; _mode.decrypt(dumpByteArray); //Log.info("after decrypt"); _decrypteddata.writeBytes(dumpByteArray); // switch IV to new one in case more bytes are available if(newIv) { _iv = newIv; } } else { //Log.info("no bytes available, stop timer"); _timer.stop(); if (_data_complete) { Log.debug("AES:data+decrypt completed, callback"); // callback _decrypteddata.position=0; _callback(_decrypteddata); } } } public function destroy():void { _key.dispose(); _key = null; _mode = null; } } }
optimize AES decryption time from 1.8Mb/s to 3.6Mb/s on Core-i5 2410M @2.30 GHz the bottleneck was the timer not restarting quickly. to workaround this, we continue to decrypt chunk of data until we reach a duration of 20ms. related to https://github.com/mangui/HLSprovider/issues/55
optimize AES decryption time from 1.8Mb/s to 3.6Mb/s on Core-i5 2410M @2.30 GHz the bottleneck was the timer not restarting quickly. to workaround this, we continue to decrypt chunk of data until we reach a duration of 20ms. related to https://github.com/mangui/HLSprovider/issues/55
ActionScript
mpl-2.0
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
c29169020ad7c540347caea7e14a7a92a6e0c014
src/org/flintparticles/common/counters/Random.as
src/org/flintparticles/common/counters/Random.as
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2011 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.common.counters { import org.flintparticles.common.emitters.Emitter; /** * The Random counter causes the emitter to emit particles continuously * at a variable random rate between two limits. */ public class Random implements Counter { private var _timeToNext:Number; private var _minRate:Number; private var _maxRate:Number; private var _running:Boolean; /** * The constructor creates a Random counter for use by an emitter. To * add a Random counter to an emitter use the emitter's counter property. * * @param minRate The minimum number of particles to emit per second. * @param maxRate The maximum number of particles to emit per second. * * @see org.flintparticles.common.emitter.Emitter.counter */ public function Random( minRate:Number = 0, maxRate:Number = 0 ) { _running = false; _minRate = minRate; _maxRate = maxRate; } /** * Stops the emitter from emitting particles */ public function stop():void { _running = false; } /** * Resumes the emitter emitting particles after a stop */ public function resume():void { _running = true; } /** * The minimum number of particles to emit per second. */ public function get minRate():Number { return _minRate; } public function set minRate( value:Number ):void { _minRate = value; } /** * The maximum number of particles to emit per second. */ public function get maxRate():Number { return _maxRate; } public function set maxRate( value:Number ):void { _maxRate = value; } /** * Initilizes the counter. Returns 0 to indicate that the emitter should * emit no particles when it starts. * * <p>This method is called within the emitter's start method * and need not be called by the user.</p> * * @param emitter The emitter. * @return 0 * * @see org.flintparticles.common.counters.Counter#startEmitter() */ public function startEmitter( emitter:Emitter ):uint { _timeToNext = newTimeToNext(); return 0; } private function newTimeToNext():Number { var rate:Number = Math.random() * ( _maxRate - _minRate ) + _maxRate; return 1 / rate; } /** * Uses the time, rateMin and rateMax to calculate how many * particles the emitter should emit now. * * <p>This method is called within the emitter's update loop and need not * be called by the user.</p> * * @param emitter The emitter. * @param time The time, in seconds, since the previous call to this method. * @return the number of particles the emitter should create. * * @see org.flintparticles.common.counters.Counter#updateEmitter() */ public function updateEmitter( emitter:Emitter, time:Number ):uint { if( !_running ) { return 0; } var count:uint = 0; _timeToNext -= time; while( _timeToNext <= 0 ) { ++count; _timeToNext += newTimeToNext(); } return count; } /** * Indicates if the counter has emitted all its particles. For this counter * this will always be false. */ public function get complete():Boolean { return false; } /** * Indicates if the counter is currently emitting particles */ public function get running():Boolean { return _running; } } }
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2011 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.common.counters { import org.flintparticles.common.emitters.Emitter; /** * The Random counter causes the emitter to emit particles continuously * at a variable random rate between two limits. */ public class Random implements Counter { private var _timeToNext:Number; private var _minRate:Number; private var _maxRate:Number; private var _running:Boolean; /** * The constructor creates a Random counter for use by an emitter. To * add a Random counter to an emitter use the emitter's counter property. * * @param minRate The minimum number of particles to emit per second. * @param maxRate The maximum number of particles to emit per second. * * @see org.flintparticles.common.emitter.Emitter.counter */ public function Random( minRate:Number = 0, maxRate:Number = 0 ) { _running = false; _minRate = minRate; _maxRate = maxRate; } /** * Stops the emitter from emitting particles */ public function stop():void { _running = false; } /** * Resumes the emitter emitting particles after a stop */ public function resume():void { _running = true; } /** * The minimum number of particles to emit per second. */ public function get minRate():Number { return _minRate; } public function set minRate( value:Number ):void { _minRate = value; } /** * The maximum number of particles to emit per second. */ public function get maxRate():Number { return _maxRate; } public function set maxRate( value:Number ):void { _maxRate = value; } /** * Initilizes the counter. Returns 0 to indicate that the emitter should * emit no particles when it starts. * * <p>This method is called within the emitter's start method * and need not be called by the user.</p> * * @param emitter The emitter. * @return 0 * * @see org.flintparticles.common.counters.Counter#startEmitter() */ public function startEmitter( emitter:Emitter ):uint { _running = true; _timeToNext = newTimeToNext(); return 0; } private function newTimeToNext():Number { var rate:Number = Math.random() * ( _maxRate - _minRate ) + _maxRate; return 1 / rate; } /** * Uses the time, rateMin and rateMax to calculate how many * particles the emitter should emit now. * * <p>This method is called within the emitter's update loop and need not * be called by the user.</p> * * @param emitter The emitter. * @param time The time, in seconds, since the previous call to this method. * @return the number of particles the emitter should create. * * @see org.flintparticles.common.counters.Counter#updateEmitter() */ public function updateEmitter( emitter:Emitter, time:Number ):uint { if( !_running ) { return 0; } var count:uint = 0; _timeToNext -= time; while( _timeToNext <= 0 ) { ++count; _timeToNext += newTimeToNext(); } return count; } /** * Indicates if the counter has emitted all its particles. For this counter * this will always be false. */ public function get complete():Boolean { return false; } /** * Indicates if the counter is currently emitting particles */ public function get running():Boolean { return _running; } } }
Fix bug with Random counter not running
Fix bug with Random counter not running
ActionScript
mit
richardlord/Flint
712ad4a60451dec00a2d0e3b042badbea788dbae
WEB-INF/lps/lfc/kernel/swf9/LFCApplication.as
WEB-INF/lps/lfc/kernel/swf9/LFCApplication.as
/** * LFCApplication.as * * @copyright Copyright 2007, 2008, 2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 * @author Henry Minsky &lt;[email protected]&gt; */ public class LFCApplication { // This serves as the superclass of DefaultApplication, currently that is where // the compiler puts top level code to run. #passthrough (toplevel:true) { import flash.display.*; import flash.events.*; import flash.utils.*; import flash.text.*; import flash.system.*; import flash.net.*; import flash.ui.*; import flash.text.Font; }# // The application sprite static public var _sprite:Sprite; public static function addChild(child:DisplayObject):DisplayObject { return _sprite.addChild(child); } public static function removeChild(child:DisplayObject):DisplayObject { return _sprite.removeChild(child); } public static function setChildIndex(child:DisplayObject, index:int):void { _sprite.setChildIndex(child, index); } // Allow anyone access to the stage object (see ctor below) public static var stage:Stage = null; // Allow anyone access to write to the debugger public static var write:Function; // global tabEnabled flag for TextField public static var textfieldTabEnabled:Boolean = false; public function LFCApplication (sprite:Sprite) { LFCApplication._sprite = sprite; // wait for the ADDED_TO_STAGE event before continuing to init LFCApplication._sprite.addEventListener(Event.ADDED_TO_STAGE, initLFC); } private function initLFC(event:Event = null) { LFCApplication._sprite.removeEventListener(Event.ADDED_TO_STAGE, initLFC); // Allow anyone to access the stage object LFCApplication.stage = LFCApplication._sprite.stage; runToplevelDefinitions() var idleTimerPeriod = 14; // msecs //trace('idle timer period = ', idleTimerPeriod , 'msecs'); LzIdleKernel.startTimer( idleTimerPeriod ); stage.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown); stage.addEventListener(KeyboardEvent.KEY_UP,reportKeyUp); if (Capabilities.playerType == "ActiveX") { // workaround for flash player bug FP-1355 LFCApplication.textfieldTabEnabled = true; stage.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, preventFocusChange); } // necessary for consistent behavior - in netscape browsers HTML is ignored stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; //Stage.align = ('canvassalign' in global && global.canvassalign != null) ? global.canvassalign : "LT"; //Stage.scaleMode = ('canvasscale' in global && global.canvasscale != null) ? global.canvasscale : "noScale"; stage.addEventListener(Event.RESIZE, resizeHandler); // Register for callbacks from the kernel LzMouseKernel.setCallback(lz.ModeManager, 'rawMouseEvent'); LzMouseKernel.initCursor(); /* TODO [hqm 2008-01] Do we want to do anything with other * events, like click, or mousewheel ? stage.addEventListener(MouseEvent.CLICK, reportClick); stage.addEventListener(MouseEvent.MOUSE_WHEEL, reportWheel); */ LzKeyboardKernel.setCallback(lz.Keys, '__keyEvent'); // LPP-7597: This is the fix for LPP-7499 canvas size not intialized to browser size LzScreenKernel.handleResizeEvent(); } function reportWheel(event:MouseEvent):void { /* Debug.write(event.currentTarget.toString() + " dispatches MouseWheelEvent. delta = " + event.delta); */ lz.Keys.__mousewheelEvent(event.delta); } function resizeHandler(event:Event):void { //trace('LFCApplication.resizeHandler stage width/height = ', stage.stageWidth, stage.stageHeight); LzScreenKernel.handleResizeEvent(); } function reportKeyUp(event:KeyboardEvent):void { /* trace("Key Released: " + String.fromCharCode(event.charCode) + " (key code: " + event.keyCode + " character code: " + event.charCode + ")"); */ LzKeyboardKernel.__keyboardEvent(event, 'onkeyup'); } function reportKeyDown(event:KeyboardEvent):void { /* trace("Key Pressed: " + String.fromCharCode(event.charCode) + " (key code: " + event.keyCode + " character code: " + event.charCode + ")"); */ LzKeyboardKernel.__keyboardEvent(event, 'onkeydown'); } function preventFocusChange(event:FocusEvent):void { if (event.keyCode == 9) { event.preventDefault(); } } public function runToplevelDefinitions() { // overridden by swf9 script compiler } } // Resource library // contains {ptype, class, frames, width, height} // ptype is one of "ar" (app relative) or "sr" (system relative) var LzResourceLibrary = {};
/** * LFCApplication.as * * @copyright Copyright 2007, 2008, 2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 * @author Henry Minsky &lt;[email protected]&gt; */ public class LFCApplication { // This serves as the superclass of DefaultApplication, currently that is where // the compiler puts top level code to run. #passthrough (toplevel:true) { import flash.display.*; import flash.events.*; import flash.utils.*; import flash.text.*; import flash.system.*; import flash.net.*; import flash.ui.*; import flash.text.Font; }# // The application sprite static public var _sprite:Sprite; public static function addChild(child:DisplayObject):DisplayObject { return _sprite.addChild(child); } public static function removeChild(child:DisplayObject):DisplayObject { return _sprite.removeChild(child); } public static function setChildIndex(child:DisplayObject, index:int):void { _sprite.setChildIndex(child, index); } // Allow anyone access to the stage object (see ctor below) public static var stage:Stage = null; // Allow anyone access to write to the debugger public static var write:Function; // global tabEnabled flag for TextField public static var textfieldTabEnabled:Boolean = false; public function LFCApplication (sprite:Sprite) { LFCApplication._sprite = sprite; // wait for the ADDED_TO_STAGE event before continuing to init LFCApplication._sprite.addEventListener(Event.ADDED_TO_STAGE, initLFC); } private function initLFC(event:Event = null) { LFCApplication._sprite.removeEventListener(Event.ADDED_TO_STAGE, initLFC); // Allow anyone to access the stage object LFCApplication.stage = LFCApplication._sprite.stage; runToplevelDefinitions() var idleTimerPeriod = 14; // msecs //trace('idle timer period = ', idleTimerPeriod , 'msecs'); LzIdleKernel.startTimer( idleTimerPeriod ); stage.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown); stage.addEventListener(KeyboardEvent.KEY_UP,reportKeyUp); if (Capabilities.playerType == "ActiveX") { // workaround for flash player bug FP-1355 LFCApplication.textfieldTabEnabled = true; stage.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, preventFocusChange); } // necessary for consistent behavior - in netscape browsers HTML is ignored stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; //Stage.align = ('canvassalign' in global && global.canvassalign != null) ? global.canvassalign : "LT"; //Stage.scaleMode = ('canvasscale' in global && global.canvasscale != null) ? global.canvasscale : "noScale"; stage.addEventListener(Event.RESIZE, resizeHandler); // Register for callbacks from the kernel LzMouseKernel.setCallback(lz.ModeManager, 'rawMouseEvent'); LzMouseKernel.initCursor(); /* TODO [hqm 2008-01] Do we want to do anything with other * events, like click? stage.addEventListener(MouseEvent.CLICK, reportClick); */ stage.addEventListener(MouseEvent.MOUSE_WHEEL, reportWheel); LzKeyboardKernel.setCallback(lz.Keys, '__keyEvent'); // LPP-7597: This is the fix for LPP-7499 canvas size not intialized to browser size LzScreenKernel.handleResizeEvent(); } function reportWheel(event:MouseEvent):void { /* Debug.write(event.currentTarget.toString() + " dispatches MouseWheelEvent. delta = " + event.delta); */ lz.Keys.__mousewheelEvent(event.delta); } function resizeHandler(event:Event):void { //trace('LFCApplication.resizeHandler stage width/height = ', stage.stageWidth, stage.stageHeight); LzScreenKernel.handleResizeEvent(); } function reportKeyUp(event:KeyboardEvent):void { /* trace("Key Released: " + String.fromCharCode(event.charCode) + " (key code: " + event.keyCode + " character code: " + event.charCode + ")"); */ LzKeyboardKernel.__keyboardEvent(event, 'onkeyup'); } function reportKeyDown(event:KeyboardEvent):void { /* trace("Key Pressed: " + String.fromCharCode(event.charCode) + " (key code: " + event.keyCode + " character code: " + event.charCode + ")"); */ LzKeyboardKernel.__keyboardEvent(event, 'onkeydown'); } function preventFocusChange(event:FocusEvent):void { if (event.keyCode == 9) { event.preventDefault(); } } public function runToplevelDefinitions() { // overridden by swf9 script compiler } } // Resource library // contains {ptype, class, frames, width, height} // ptype is one of "ar" (app relative) or "sr" (system relative) var LzResourceLibrary = {};
Change 20090207-maxcarlson-I by [email protected] on 2009-02-07 06:56:52 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20090207-maxcarlson-I by [email protected] on 2009-02-07 06:56:52 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk Summary: Fix mousewheel events in swf9 windows Bugs Fixed: LPP-7731 - swf9: mousewheel events not working in swf9 on windows Technical Reviewer: hminsky QA Reviewer: promanik Details: Uncomment the event registration for MOUSE_WHEEL - the method was already set up... braino! Tests: See LPP-7731 git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@12792 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
421ef423174cf3b2e8a9b5cd541a24e5fb9662e4
lib/src/com/amanitadesign/steam/ISteamWorks.as
lib/src/com/amanitadesign/steam/ISteamWorks.as
/* * ISteamWorks.as * This file is part of FRESteamWorks. * * Created by Ventero <http://github.com/Ventero> on 2013-08-28 * Copyright (c) 2013 Level Up Labs, LLC. All rights reserved. */ package com.amanitadesign.steam { import flash.display.DisplayObjectContainer; import flash.events.IEventDispatcher; import flash.utils.ByteArray; public interface ISteamWorks extends IEventDispatcher { [Event(name="steamResponse", type="com.amanitadesign.steam.SteamEvent")] function ISteamWorks(target:IEventDispatcher = null); function init():Boolean; function dispose():void; function addOverlayWorkaround(container:DisplayObjectContainer, alwaysVisible:Boolean = false, color:uint = 0x000000):void; function runCallbacks():Boolean function getUserID():String function getAppID():uint function getPersonaName():String function useCrashHandler(appID:uint, version:String, date:String, time:String):Boolean /* stats/achievements */ function requestStats():Boolean function setAchievement(name:String):Boolean function clearAchievement(name:String):Boolean function isAchievement(name:String):Boolean function getStatInt(name:String):int function getStatFloat(name:String):Number function setStatInt(name:String, value:int):Boolean function setStatFloat(name:String, value:Number):Boolean function storeStats():Boolean function resetAllStats(achievementsToo:Boolean):Boolean /* cloud */ function getFileCount():int function getFileSize(name:String):int function fileExists(name:String):Boolean function fileWrite(name:String, data:ByteArray):Boolean function fileRead(name:String, data:ByteArray):Boolean function fileDelete(name:String):Boolean function fileShare(name:String):Boolean function fileShareResult():String function isCloudEnabledForApp():Boolean function setCloudEnabledForApp(enabled:Boolean):Boolean function getQuota():Array /* ugc/workshop */ function UGCDownload(handle:String, priority:int):Boolean function UGCRead(handle:String, size:int, offset:uint, data:ByteArray):Boolean function getUGCDownloadProgress(handle:String):Array function getUGCDownloadResult(handle:String):DownloadUGCResult function publishWorkshopFile(name:String, preview:String, appId:uint, title:String, description:String, visibility:uint, tags:Array, fileType:uint):Boolean function publishWorkshopFileResult():String function deletePublishedFile(file:String):Boolean function getPublishedFileDetails(file:String, maxAge:int = 0):Boolean function getPublishedFileDetailsResult(file:String):FileDetailsResult function enumerateUserPublishedFiles(startIndex:uint):Boolean function enumerateUserPublishedFilesResult():UserFilesResult function enumeratePublishedWorkshopFiles(type:uint, start:uint, count:uint, days:uint, tags:Array, userTags:Array):Boolean function enumeratePublishedWorkshopFilesResult():WorkshopFilesResult function enumerateUserSubscribedFiles(startIndex:uint):Boolean function enumerateUserSubscribedFilesResult():SubscribedFilesResult function enumerateUserSharedWorkshopFiles(steamID:String, start:uint, required:Array, excluded:Array):Boolean function enumerateUserSharedWorkshopFilesResult():UserFilesResult function enumeratePublishedFilesByUserAction(action:uint, startIndex:uint):Boolean function enumeratePublishedFilesByUserActionResult():FilesByUserActionResult function subscribePublishedFile(file:String):Boolean function unsubscribePublishedFile(file:String):Boolean function createPublishedFileUpdateRequest(file:String):String function updatePublishedFileFile(handle:String, file:String):Boolean function updatePublishedFilePreviewFile(handle:String, preview:String):Boolean function updatePublishedFileTitle(handle:String, title:String):Boolean function updatePublishedFileDescription(handle:String, description:String):Boolean function updatePublishedFileSetChangeDescription(handle:String, changeDesc:String):Boolean function updatePublishedFileVisibility(handle:String, visibility:uint):Boolean function updatePublishedFileTags(handle:String, tags:Array):Boolean function commitPublishedFileUpdate(handle:String):Boolean function getPublishedItemVoteDetails(file:String):Boolean function getPublishedItemVoteDetailsResult():ItemVoteDetailsResult function getUserPublishedItemVoteDetails(file:String):Boolean function getUserPublishedItemVoteDetailsResult():UserVoteDetails function updateUserPublishedItemVote(file:String, upvote:Boolean):Boolean function setUserPublishedFileAction(file:String, action:uint):Boolean /* overlay */ function activateGameOverlay(dialog:String):Boolean function activateGameOverlayToUser(dialog:String, steamId:String):Boolean function activateGameOverlayToWebPage(url:String):Boolean function activateGameOverlayToStore(appId:uint, flag:uint):Boolean function activateGameOverlayInviteDialog(steamIdLobby:String):Boolean function isOverlayEnabled():Boolean /* DLC / subscriptions */ function isSubscribedApp(appId:uint):Boolean function isDLCInstalled(appId:uint):Boolean function getDLCCount():int function installDLC(appId:uint):Boolean function uninstallDLC(appId:uint):Boolean function DLCInstalledResult():uint } }
/* * ISteamWorks.as * This file is part of FRESteamWorks. * * Created by Ventero <http://github.com/Ventero> on 2013-08-28 * Copyright (c) 2013 Level Up Labs, LLC. All rights reserved. */ package com.amanitadesign.steam { import flash.display.DisplayObjectContainer; import flash.events.IEventDispatcher; import flash.utils.ByteArray; public interface ISteamWorks extends IEventDispatcher { [Event(name="steamResponse", type="com.amanitadesign.steam.SteamEvent")] function init():Boolean; function dispose():void; function addOverlayWorkaround(container:DisplayObjectContainer, alwaysVisible:Boolean = false, color:uint = 0x000000):void; function runCallbacks():Boolean function getUserID():String function getAppID():uint function getPersonaName():String function useCrashHandler(appID:uint, version:String, date:String, time:String):Boolean /* stats/achievements */ function requestStats():Boolean function setAchievement(name:String):Boolean function clearAchievement(name:String):Boolean function isAchievement(name:String):Boolean function getStatInt(name:String):int function getStatFloat(name:String):Number function setStatInt(name:String, value:int):Boolean function setStatFloat(name:String, value:Number):Boolean function storeStats():Boolean function resetAllStats(achievementsToo:Boolean):Boolean /* cloud */ function getFileCount():int function getFileSize(name:String):int function fileExists(name:String):Boolean function fileWrite(name:String, data:ByteArray):Boolean function fileRead(name:String, data:ByteArray):Boolean function fileDelete(name:String):Boolean function fileShare(name:String):Boolean function fileShareResult():String function isCloudEnabledForApp():Boolean function setCloudEnabledForApp(enabled:Boolean):Boolean function getQuota():Array /* ugc/workshop */ function UGCDownload(handle:String, priority:int):Boolean function UGCRead(handle:String, size:int, offset:uint, data:ByteArray):Boolean function getUGCDownloadProgress(handle:String):Array function getUGCDownloadResult(handle:String):DownloadUGCResult function publishWorkshopFile(name:String, preview:String, appId:uint, title:String, description:String, visibility:uint, tags:Array, fileType:uint):Boolean function publishWorkshopFileResult():String function deletePublishedFile(file:String):Boolean function getPublishedFileDetails(file:String, maxAge:int = 0):Boolean function getPublishedFileDetailsResult(file:String):FileDetailsResult function enumerateUserPublishedFiles(startIndex:uint):Boolean function enumerateUserPublishedFilesResult():UserFilesResult function enumeratePublishedWorkshopFiles(type:uint, start:uint, count:uint, days:uint, tags:Array, userTags:Array):Boolean function enumeratePublishedWorkshopFilesResult():WorkshopFilesResult function enumerateUserSubscribedFiles(startIndex:uint):Boolean function enumerateUserSubscribedFilesResult():SubscribedFilesResult function enumerateUserSharedWorkshopFiles(steamID:String, start:uint, required:Array, excluded:Array):Boolean function enumerateUserSharedWorkshopFilesResult():UserFilesResult function enumeratePublishedFilesByUserAction(action:uint, startIndex:uint):Boolean function enumeratePublishedFilesByUserActionResult():FilesByUserActionResult function subscribePublishedFile(file:String):Boolean function unsubscribePublishedFile(file:String):Boolean function createPublishedFileUpdateRequest(file:String):String function updatePublishedFileFile(handle:String, file:String):Boolean function updatePublishedFilePreviewFile(handle:String, preview:String):Boolean function updatePublishedFileTitle(handle:String, title:String):Boolean function updatePublishedFileDescription(handle:String, description:String):Boolean function updatePublishedFileSetChangeDescription(handle:String, changeDesc:String):Boolean function updatePublishedFileVisibility(handle:String, visibility:uint):Boolean function updatePublishedFileTags(handle:String, tags:Array):Boolean function commitPublishedFileUpdate(handle:String):Boolean function getPublishedItemVoteDetails(file:String):Boolean function getPublishedItemVoteDetailsResult():ItemVoteDetailsResult function getUserPublishedItemVoteDetails(file:String):Boolean function getUserPublishedItemVoteDetailsResult():UserVoteDetails function updateUserPublishedItemVote(file:String, upvote:Boolean):Boolean function setUserPublishedFileAction(file:String, action:uint):Boolean /* overlay */ function activateGameOverlay(dialog:String):Boolean function activateGameOverlayToUser(dialog:String, steamId:String):Boolean function activateGameOverlayToWebPage(url:String):Boolean function activateGameOverlayToStore(appId:uint, flag:uint):Boolean function activateGameOverlayInviteDialog(steamIdLobby:String):Boolean function isOverlayEnabled():Boolean /* DLC / subscriptions */ function isSubscribedApp(appId:uint):Boolean function isDLCInstalled(appId:uint):Boolean function getDLCCount():int function installDLC(appId:uint):Boolean function uninstallDLC(appId:uint):Boolean function DLCInstalledResult():uint } }
Remove ctor from interface.
Remove ctor from interface.
ActionScript
bsd-2-clause
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
c03294ed45cd5700c3fc377f72477d523620120e
src/Player.as
src/Player.as
package { import com.axis.ClientEvent; import com.axis.IClient; import com.axis.audioclient.AxisTransmit; import com.axis.http.url; import com.axis.httpclient.HTTPClient; import com.axis.rtmpclient.RTMPClient; import com.axis.rtspclient.IRTSPHandle; import com.axis.rtspclient.RTSPClient; import com.axis.rtspclient.RTSPoverHTTPHandle; import com.axis.rtspclient.RTSPoverTCPHandle; import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageDisplayState; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.MouseEvent; import flash.external.ExternalInterface; import flash.media.Microphone; import flash.media.SoundMixer; import flash.media.SoundTransform; import flash.media.Video; import flash.net.NetStream; import flash.system.Security; [SWF(frameRate="60")] [SWF(backgroundColor="#efefef")] public class Player extends Sprite { private var config:Object = { 'buffer': 1, 'scaleUp': false }; private var video:Video; private var audioTransmit:AxisTransmit = new AxisTransmit(); private var meta:Object = {}; private var client:IClient; private var ns:NetStream; private var urlParsed:Object; private var savedSpeakerVolume:Number; private var fullscreenAllowed:Boolean = true; private var currentState:String = "Stopped"; private var streamHasAudio:Boolean = false; private var streamHasVideo:Boolean = false; public function Player() { var self:Player = this; Security.allowDomain("*"); Security.allowInsecureDomain("*"); ExternalInterface.marshallExceptions = true; /* Media player API */ ExternalInterface.addCallback("play", play); ExternalInterface.addCallback("pause", pause); ExternalInterface.addCallback("resume", resume); ExternalInterface.addCallback("stop", stop); ExternalInterface.addCallback("seek", seek); ExternalInterface.addCallback("playbackSpeed", playbackSpeed); ExternalInterface.addCallback("streamStatus", streamStatus); ExternalInterface.addCallback("playerStatus", playerStatus); ExternalInterface.addCallback("speakerVolume", speakerVolume); ExternalInterface.addCallback("muteSpeaker", muteSpeaker); ExternalInterface.addCallback("unmuteSpeaker", unmuteSpeaker); ExternalInterface.addCallback("microphoneVolume", microphoneVolume); ExternalInterface.addCallback("muteMicrophone", muteMicrophone); ExternalInterface.addCallback("unmuteMicrophone", unmuteMicrophone); ExternalInterface.addCallback("allowFullscreen", allowFullscreen); /* Audio Transmission API */ ExternalInterface.addCallback("startAudioTransmit", startAudioTransmit); ExternalInterface.addCallback("stopAudioTransmit", stopAudioTransmit); /* Set default speaker volume */ this.speakerVolume(50); /* Stage setup */ this.stage.align = StageAlign.TOP_LEFT; this.stage.scaleMode = StageScaleMode.NO_SCALE; addEventListener(Event.ADDED_TO_STAGE, onStageAdded); /* Video object setup */ video = new Video(stage.stageWidth, stage.stageHeight); addChild(video); /* Fullscreen support setup */ this.stage.doubleClickEnabled = true; this.stage.addEventListener(MouseEvent.DOUBLE_CLICK, fullscreen); this.stage.addEventListener(Event.FULLSCREEN, function(event:Event):void { videoResize(); }); } public function fullscreen(event:MouseEvent):void { if (this.fullscreenAllowed) this.stage.displayState = (StageDisplayState.NORMAL === stage.displayState) ? StageDisplayState.FULL_SCREEN : StageDisplayState.NORMAL; } public function videoResize():void { var stagewidth:uint = (StageDisplayState.NORMAL === stage.displayState) ? stage.stageWidth : stage.fullScreenWidth; var stageheight:uint = (StageDisplayState.NORMAL === stage.displayState) ? stage.stageHeight : stage.fullScreenHeight; var scale:Number = ((stagewidth / meta.width) > (stageheight / meta.height)) ? (stageheight / meta.height) : (stagewidth / meta.width); video.width = meta.width; video.height = meta.height; if ((scale < 1.0) || (scale > 1.0 && true === config.scaleUp)) { trace('scaling video, scale:', scale.toFixed(2), ' (aspect ratio: ' + (video.width / video.height).toFixed(2) + ')'); video.width = meta.width * scale; video.height = meta.height * scale; } video.x = (stagewidth - video.width) / 2; video.y = (stageheight - video.height) / 2; } public function play(iurl:String = null):void { if (client) { urlParsed = url.parse(iurl); /* Stop the client, and 'onStopped' will start the new stream. */ client.stop(); return; } urlParsed = url.parse(iurl); start(); } private function start():void { switch (urlParsed.protocol) { case 'rtsph': /* RTSP over HTTP */ client = new RTSPClient(this.video, urlParsed, new RTSPoverHTTPHandle(urlParsed)); break; case 'rtsp': /* RTSP over TCP */ client = new RTSPClient(this.video, urlParsed, new RTSPoverTCPHandle(urlParsed)); this.callAPI('streamStarted'); break; case 'http': /* Progressive download over HTTP */ client = new HTTPClient(this.video, urlParsed); break; case 'rtmp': /* RTMP */ client = new RTMPClient(this.video, urlParsed); break; default: trace('Unknown streaming protocol:', urlParsed.protocol) return; } client.addEventListener(ClientEvent.NETSTREAM_CREATED, onNetStreamCreated); client.addEventListener(ClientEvent.STOPPED, onStopped); client.addEventListener(ClientEvent.START_PLAY, onStartPlay); client.start(); } public function pause():void { client.pause(); this.callAPI('streamPaused'); this.currentState = "Paused"; } public function resume():void { client.resume(); this.callAPI('streamResumed'); } public function stop():void { urlParsed = null; ns = null; client.stop(); this.callAPI('streamStopped'); this.currentState = "Stopped"; this.streamHasAudio = false; this.streamHasVideo = false; } public function seek(timestamp:String):void { trace('seek, timestamp->' + timestamp); } public function playbackSpeed(speed:Number):void { trace('playbackSpeed, speed->' + speed); } public function streamStatus():Object { if (this.currentState === 'Playing') { this.streamHasAudio = (this.streamHasAudio || this.ns.info.audioBufferByteLength); this.streamHasVideo = (this.streamHasVideo || this.ns.info.videoBufferByteLength); } var status:Object = { 'fps': (this.ns) ? Math.floor(this.ns.currentFPS + 0.5) : null, 'resolution': (this.ns) ? (meta.width + 'x' + meta.height) : null, 'playbackSpeed': (this.ns) ? 1.0 : null, 'protocol': (this.urlParsed) ? this.urlParsed.protocol: null, 'audio': (this.ns) ? this.streamHasAudio : null, 'video': (this.ns) ? this.streamHasVideo : null, 'state': this.currentState, 'isSeekable': false, 'isPlaybackSpeedChangeable': false, 'streamURL': (this.urlParsed) ? this.urlParsed.full : null }; return status; } public function playerStatus():Object { var mic:Microphone = Microphone.getMicrophone(); var status:Object = { 'microphoneVolume': audioTransmit.microphoneVolume, 'speakerVolume': this.savedSpeakerVolume, 'microphoneMuted': (mic.gain === 0), 'speakerMuted': (flash.media.SoundMixer.soundTransform.volume === 0), 'fullscreen': (StageDisplayState.FULL_SCREEN === stage.displayState) }; return status; } public function speakerVolume(volume:Number):void { this.savedSpeakerVolume = volume; var transform:SoundTransform = new SoundTransform(volume / 100.0); flash.media.SoundMixer.soundTransform = transform; } public function muteSpeaker():void { var transform:SoundTransform = new SoundTransform(0); flash.media.SoundMixer.soundTransform = transform; } public function unmuteSpeaker():void { if (flash.media.SoundMixer.soundTransform.volume !== 0) return; var transform:SoundTransform = new SoundTransform(this.savedSpeakerVolume / 100.0); flash.media.SoundMixer.soundTransform = transform; } public function microphoneVolume(volume:Number):void { audioTransmit.microphoneVolume = volume; } public function muteMicrophone():void { audioTransmit.muteMicrophone(); } public function unmuteMicrophone():void { audioTransmit.unmuteMicrophone(); } public function startAudioTransmit(url:String = null, type:String = 'axis'):void { if (type === 'axis') { audioTransmit.start(url); } else { trace("unsupported type"); } } public function stopAudioTransmit():void { audioTransmit.stop(); } public function allowFullscreen(state:Boolean):void { this.fullscreenAllowed = state; if (!state) this.stage.displayState = StageDisplayState.NORMAL; } private function onStageAdded(e:Event):void { trace('stage added'); } public function onMetaData(item:Object):void { this.meta = item; this.videoResize(); } public function onNetStreamCreated(ev:ClientEvent):void { this.ns = ev.data.ns; ev.data.ns.bufferTime = config.buffer; ev.data.ns.client = this; } private function onStopped(ev:ClientEvent):void { video.clear(); client = null; if (urlParsed) { start(); } } private function onStartPlay(ev:ClientEvent):void { this.currentState = "Playing"; } public function onPlayStatus(ev:Object):void { this.currentState = "Stopped"; } private function callAPI(eventName:String, data:Object = null):void { if (!ExternalInterface.available) { trace("ExternalInterface is not available!"); return; } var functionName:String = "Locomote('" + ExternalInterface.objectID + "').__playerEvent"; if (data) { ExternalInterface.call(functionName, eventName, data); } else { ExternalInterface.call(functionName, eventName); } } } }
package { import com.axis.ClientEvent; import com.axis.IClient; import com.axis.audioclient.AxisTransmit; import com.axis.http.url; import com.axis.httpclient.HTTPClient; import com.axis.rtmpclient.RTMPClient; import com.axis.rtspclient.IRTSPHandle; import com.axis.rtspclient.RTSPClient; import com.axis.rtspclient.RTSPoverHTTPHandle; import com.axis.rtspclient.RTSPoverTCPHandle; import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageDisplayState; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.MouseEvent; import flash.external.ExternalInterface; import flash.media.Microphone; import flash.media.SoundMixer; import flash.media.SoundTransform; import flash.media.Video; import flash.net.NetStream; import flash.system.Security; [SWF(frameRate="60")] [SWF(backgroundColor="#efefef")] public class Player extends Sprite { private var config:Object = { 'buffer': 1, 'scaleUp': false }; private var video:Video; private var audioTransmit:AxisTransmit = new AxisTransmit(); private var meta:Object = {}; private var client:IClient; private var ns:NetStream; private var urlParsed:Object; private var savedSpeakerVolume:Number; private var fullscreenAllowed:Boolean = true; private var currentState:String = "Stopped"; private var streamHasAudio:Boolean = false; private var streamHasVideo:Boolean = false; public function Player() { var self:Player = this; Security.allowDomain("*"); Security.allowInsecureDomain("*"); ExternalInterface.marshallExceptions = true; /* Media player API */ ExternalInterface.addCallback("play", play); ExternalInterface.addCallback("pause", pause); ExternalInterface.addCallback("resume", resume); ExternalInterface.addCallback("stop", stop); ExternalInterface.addCallback("seek", seek); ExternalInterface.addCallback("playbackSpeed", playbackSpeed); ExternalInterface.addCallback("streamStatus", streamStatus); ExternalInterface.addCallback("playerStatus", playerStatus); ExternalInterface.addCallback("speakerVolume", speakerVolume); ExternalInterface.addCallback("muteSpeaker", muteSpeaker); ExternalInterface.addCallback("unmuteSpeaker", unmuteSpeaker); ExternalInterface.addCallback("microphoneVolume", microphoneVolume); ExternalInterface.addCallback("muteMicrophone", muteMicrophone); ExternalInterface.addCallback("unmuteMicrophone", unmuteMicrophone); ExternalInterface.addCallback("allowFullscreen", allowFullscreen); /* Audio Transmission API */ ExternalInterface.addCallback("startAudioTransmit", startAudioTransmit); ExternalInterface.addCallback("stopAudioTransmit", stopAudioTransmit); /* Set default speaker volume */ this.speakerVolume(50); /* Stage setup */ this.stage.align = StageAlign.TOP_LEFT; this.stage.scaleMode = StageScaleMode.NO_SCALE; addEventListener(Event.ADDED_TO_STAGE, onStageAdded); /* Video object setup */ video = new Video(stage.stageWidth, stage.stageHeight); addChild(video); /* Fullscreen support setup */ this.stage.doubleClickEnabled = true; this.stage.addEventListener(MouseEvent.DOUBLE_CLICK, fullscreen); this.stage.addEventListener(Event.FULLSCREEN, function(event:Event):void { videoResize(); }); } public function fullscreen(event:MouseEvent):void { if (this.fullscreenAllowed) this.stage.displayState = (StageDisplayState.NORMAL === stage.displayState) ? StageDisplayState.FULL_SCREEN : StageDisplayState.NORMAL; } public function videoResize():void { var stagewidth:uint = (StageDisplayState.NORMAL === stage.displayState) ? stage.stageWidth : stage.fullScreenWidth; var stageheight:uint = (StageDisplayState.NORMAL === stage.displayState) ? stage.stageHeight : stage.fullScreenHeight; var scale:Number = ((stagewidth / meta.width) > (stageheight / meta.height)) ? (stageheight / meta.height) : (stagewidth / meta.width); video.width = meta.width; video.height = meta.height; if ((scale < 1.0) || (scale > 1.0 && true === config.scaleUp)) { trace('scaling video, scale:', scale.toFixed(2), ' (aspect ratio: ' + (video.width / video.height).toFixed(2) + ')'); video.width = meta.width * scale; video.height = meta.height * scale; } video.x = (stagewidth - video.width) / 2; video.y = (stageheight - video.height) / 2; } public function play(iurl:String = null):void { if (client) { urlParsed = url.parse(iurl); /* Stop the client, and 'onStopped' will start the new stream. */ client.stop(); return; } this.streamHasAudio = false; this.streamHasVideo = false; urlParsed = url.parse(iurl); start(); } private function start():void { switch (urlParsed.protocol) { case 'rtsph': /* RTSP over HTTP */ client = new RTSPClient(this.video, urlParsed, new RTSPoverHTTPHandle(urlParsed)); break; case 'rtsp': /* RTSP over TCP */ client = new RTSPClient(this.video, urlParsed, new RTSPoverTCPHandle(urlParsed)); this.callAPI('streamStarted'); break; case 'http': /* Progressive download over HTTP */ client = new HTTPClient(this.video, urlParsed); break; case 'rtmp': /* RTMP */ client = new RTMPClient(this.video, urlParsed); break; default: trace('Unknown streaming protocol:', urlParsed.protocol) return; } client.addEventListener(ClientEvent.NETSTREAM_CREATED, onNetStreamCreated); client.addEventListener(ClientEvent.STOPPED, onStopped); client.addEventListener(ClientEvent.START_PLAY, onStartPlay); client.start(); } public function pause():void { client.pause(); this.callAPI('streamPaused'); this.currentState = "Paused"; } public function resume():void { client.resume(); this.callAPI('streamResumed'); } public function stop():void { urlParsed = null; ns = null; client.stop(); this.callAPI('streamStopped'); this.currentState = "Stopped"; this.streamHasAudio = false; this.streamHasVideo = false; } public function seek(timestamp:String):void { trace('seek, timestamp->' + timestamp); } public function playbackSpeed(speed:Number):void { trace('playbackSpeed, speed->' + speed); } public function streamStatus():Object { if (this.currentState === 'Playing') { this.streamHasAudio = (this.streamHasAudio || this.ns.info.audioBufferByteLength); this.streamHasVideo = (this.streamHasVideo || this.ns.info.videoBufferByteLength); } var status:Object = { 'fps': (this.ns) ? Math.floor(this.ns.currentFPS + 0.5) : null, 'resolution': (this.ns) ? (meta.width + 'x' + meta.height) : null, 'playbackSpeed': (this.ns) ? 1.0 : null, 'protocol': (this.urlParsed) ? this.urlParsed.protocol: null, 'audio': (this.ns) ? this.streamHasAudio : null, 'video': (this.ns) ? this.streamHasVideo : null, 'state': this.currentState, 'isSeekable': false, 'isPlaybackSpeedChangeable': false, 'streamURL': (this.urlParsed) ? this.urlParsed.full : null }; return status; } public function playerStatus():Object { var mic:Microphone = Microphone.getMicrophone(); var status:Object = { 'microphoneVolume': audioTransmit.microphoneVolume, 'speakerVolume': this.savedSpeakerVolume, 'microphoneMuted': (mic.gain === 0), 'speakerMuted': (flash.media.SoundMixer.soundTransform.volume === 0), 'fullscreen': (StageDisplayState.FULL_SCREEN === stage.displayState) }; return status; } public function speakerVolume(volume:Number):void { this.savedSpeakerVolume = volume; var transform:SoundTransform = new SoundTransform(volume / 100.0); flash.media.SoundMixer.soundTransform = transform; } public function muteSpeaker():void { var transform:SoundTransform = new SoundTransform(0); flash.media.SoundMixer.soundTransform = transform; } public function unmuteSpeaker():void { if (flash.media.SoundMixer.soundTransform.volume !== 0) return; var transform:SoundTransform = new SoundTransform(this.savedSpeakerVolume / 100.0); flash.media.SoundMixer.soundTransform = transform; } public function microphoneVolume(volume:Number):void { audioTransmit.microphoneVolume = volume; } public function muteMicrophone():void { audioTransmit.muteMicrophone(); } public function unmuteMicrophone():void { audioTransmit.unmuteMicrophone(); } public function startAudioTransmit(url:String = null, type:String = 'axis'):void { if (type === 'axis') { audioTransmit.start(url); } else { trace("unsupported type"); } } public function stopAudioTransmit():void { audioTransmit.stop(); } public function allowFullscreen(state:Boolean):void { this.fullscreenAllowed = state; if (!state) this.stage.displayState = StageDisplayState.NORMAL; } private function onStageAdded(e:Event):void { trace('stage added'); } public function onMetaData(item:Object):void { this.meta = item; this.videoResize(); } public function onNetStreamCreated(ev:ClientEvent):void { this.ns = ev.data.ns; ev.data.ns.bufferTime = config.buffer; ev.data.ns.client = this; } private function onStopped(ev:ClientEvent):void { video.clear(); client = null; if (urlParsed) { start(); } } private function onStartPlay(ev:ClientEvent):void { this.currentState = "Playing"; } public function onPlayStatus(ev:Object):void { this.currentState = "Stopped"; } private function callAPI(eventName:String, data:Object = null):void { if (!ExternalInterface.available) { trace("ExternalInterface is not available!"); return; } var functionName:String = "Locomote('" + ExternalInterface.objectID + "').__playerEvent"; if (data) { ExternalInterface.call(functionName, eventName, data); } else { ExternalInterface.call(functionName, eventName); } } } }
Reset audio and video status
Reset audio and video status Added reset of stream audio and video status in case play is run without stopping a previously running stream first.
ActionScript
bsd-3-clause
AxisCommunications/locomote-video-player,gaetancollaud/locomote-video-player
fe8f3611f7930d3a6cd6c2e21a41e97b3fad98eb
source/fairygui/GMovieClip.as
source/fairygui/GMovieClip.as
package fairygui { import fairygui.display.MovieClip; import fairygui.utils.ByteBuffer; import laya.maths.Rectangle; import laya.utils.Handler; import fairygui.gears.IAnimationGear; import fairygui.gears.IColorGear; public class GMovieClip extends GObject implements IAnimationGear, IColorGear { private var _movieClip: MovieClip; public function GMovieClip() { super(); this._sizeImplType = 1; } public function get color(): String { return "#FFFFFF"; } public function set color(value: String):void { } override protected function createDisplayObject(): void { this._displayObject = _movieClip = new MovieClip(); _movieClip.mouseEnabled = false; this._displayObject["$owner"] = this; } public function get playing(): Boolean { return _movieClip.playing; } public function set playing(value: Boolean):void { if (_movieClip.playing != value) { _movieClip.playing = value; this.updateGear(5); } } public function get frame(): Number { return _movieClip.frame; } public function set frame(value: Number):void { if (_movieClip.frame != value) { _movieClip.frame = value; this.updateGear(5); } } final public function get timeScale():Number { return _movieClip.timeScale; } public function set timeScale(value:Number):void { _movieClip.timeScale = value; } public function rewind():void { _movieClip.rewind(); } public function syncStatus(anotherMc:GMovieClip):void { _movieClip.syncStatus(anotherMc._movieClip); } public function advance(timeInMiniseconds:int):void { _movieClip.advance(timeInMiniseconds); } //从start帧开始,播放到end帧(-1表示结尾),重复times次(0表示无限循环),循环结束后,停止在endAt帧(-1表示参数end) public function setPlaySettings(start: Number = 0,end: Number = -1, times: Number = 0,endAt: Number = -1, endHandler: Handler = null): void { _movieClip.setPlaySettings(start, end, times, endAt, endHandler); } override public function constructFromResource(): void { this.sourceWidth = this.packageItem.width; this.sourceHeight = this.packageItem.height; this.initWidth = this.sourceWidth; this.initHeight = this.sourceHeight; this.setSize(this.sourceWidth, this.sourceHeight); this.packageItem.load(); _movieClip.interval = this.packageItem.interval; _movieClip.swing = this.packageItem.swing; _movieClip.repeatDelay = this.packageItem.repeatDelay; _movieClip.frames = this.packageItem.frames; _movieClip.boundsRect = new Rectangle(0, 0, this.sourceWidth, this.sourceHeight); } override public function setup_beforeAdd(buffer:ByteBuffer, beginPos:int): void { super.setup_beforeAdd(buffer, beginPos); buffer.seek(beginPos, 5); if (buffer.readBool()) this.color = buffer.readColorS(); buffer.readByte(); //flip _movieClip.frame = buffer.getInt32(); _movieClip.playing = buffer.readBool(); } } }
package fairygui { import fairygui.display.MovieClip; import fairygui.utils.ByteBuffer; import laya.maths.Rectangle; import laya.utils.Handler; import fairygui.gears.IAnimationGear; import fairygui.gears.IColorGear; public class GMovieClip extends GObject implements IAnimationGear, IColorGear { private var _movieClip: MovieClip; public function GMovieClip() { super(); } public function get color(): String { return "#FFFFFF"; } public function set color(value: String):void { } override protected function createDisplayObject(): void { this._displayObject = _movieClip = new MovieClip(); _movieClip.mouseEnabled = false; this._displayObject["$owner"] = this; } public function get playing(): Boolean { return _movieClip.playing; } public function set playing(value: Boolean):void { if (_movieClip.playing != value) { _movieClip.playing = value; this.updateGear(5); } } public function get frame(): Number { return _movieClip.frame; } public function set frame(value: Number):void { if (_movieClip.frame != value) { _movieClip.frame = value; this.updateGear(5); } } final public function get timeScale():Number { return _movieClip.timeScale; } public function set timeScale(value:Number):void { _movieClip.timeScale = value; } public function rewind():void { _movieClip.rewind(); } public function syncStatus(anotherMc:GMovieClip):void { _movieClip.syncStatus(anotherMc._movieClip); } public function advance(timeInMiniseconds:int):void { _movieClip.advance(timeInMiniseconds); } //从start帧开始,播放到end帧(-1表示结尾),重复times次(0表示无限循环),循环结束后,停止在endAt帧(-1表示参数end) public function setPlaySettings(start: Number = 0,end: Number = -1, times: Number = 0,endAt: Number = -1, endHandler: Handler = null): void { _movieClip.setPlaySettings(start, end, times, endAt, endHandler); } override public function constructFromResource(): void { this.sourceWidth = this.packageItem.width; this.sourceHeight = this.packageItem.height; this.initWidth = this.sourceWidth; this.initHeight = this.sourceHeight; this.setSize(this.sourceWidth, this.sourceHeight); this.packageItem.load(); _movieClip.interval = this.packageItem.interval; _movieClip.swing = this.packageItem.swing; _movieClip.repeatDelay = this.packageItem.repeatDelay; _movieClip.frames = this.packageItem.frames; } override public function setup_beforeAdd(buffer:ByteBuffer, beginPos:int): void { super.setup_beforeAdd(buffer, beginPos); buffer.seek(beginPos, 5); if (buffer.readBool()) this.color = buffer.readColorS(); buffer.readByte(); //flip _movieClip.frame = buffer.getInt32(); _movieClip.playing = buffer.readBool(); } } }
remove unused code.
remove unused code.
ActionScript
mit
fairygui/FairyGUI-layabox,fairygui/FairyGUI-layabox
a5be4f1c9c3b5feb503dbff53a851ffbc40a9854
src/goplayer/Player.as
src/goplayer/Player.as
package goplayer { import flash.utils.getTimer public class Player implements FlashNetConnectionListener, FlashNetStreamListener { private const DEFAULT_VOLUME : Number = .8 private const START_BUFFER : Duration = Duration.seconds(3) private const SMALL_BUFFER : Duration = Duration.seconds(5) private const LARGE_BUFFER : Duration = Duration.seconds(60) private const SEEK_GRACE_TIME : Duration = Duration.seconds(2) private const finishingListeners : Array = [] private var connection : FlashNetConnection private var _movie : Movie private var bitratePolicy : BitratePolicy private var enableRTMP : Boolean private var reporter : MovieEventReporter private var sharedVolumeVariable : SharedVariable private var _started : Boolean = false private var _finished : Boolean = false private var triedStandardRTMP : Boolean = false private var _usingRTMP : Boolean = false private var measuredBandwidth : Bitrate = null private var measuredLatency : Duration = null private var stream : FlashNetStream = null private var metadata : Object = null private var _volume : Number = NaN private var savedVolume : Number = 0 private var _paused : Boolean = false private var _buffering : Boolean = false private var seekStopwatch : Stopwatch = new Stopwatch public function Player (connection : FlashNetConnection, movie : Movie, bitratePolicy : BitratePolicy, enableRTMP : Boolean, reporter : MovieEventReporter, sharedVolumeVariable : SharedVariable) { this.connection = connection _movie = movie this.bitratePolicy = bitratePolicy this.enableRTMP = enableRTMP this.reporter = reporter this.sharedVolumeVariable = sharedVolumeVariable connection.listener = this reporter.reportMovieViewed(movie.id) if (sharedVolumeVariable.hasValue) volume = sharedVolumeVariable.value else volume = DEFAULT_VOLUME } public function get movie() : Movie { return _movie } public function addFinishingListener (value : PlayerFinishingListener) : void { finishingListeners.push(value) } public function get started() : Boolean { return _started } public function get running() : Boolean { return started && !finished } public function get finished() : Boolean { return _finished } // ----------------------------------------------------- public function destroy() : void { if (stream != null) stream.destroy() } public function start() : void { _started = true if (enableRTMP && movie.rtmpURL != null) connectUsingRTMP() else connectUsingHTTP() reporter.reportMoviePlayed(movie.id) } public function handleConnectionFailed() : void { if (movie.rtmpURL.hasPort && !triedStandardRTMP) handleCustomRTMPUnavailable() else handleRTMPUnavailable() } private function handleCustomRTMPUnavailable() : void { debug("Trying to connect using default RTMP ports.") connectUsingStandardRTMP() } private function handleRTMPUnavailable() : void { debug("Could not connect using RTMP; trying plain HTTP.") connectUsingHTTP() } public function get usingRTMP() : Boolean { return _usingRTMP } private function connectUsingRTMP() : void { connection.connect(movie.rtmpURL) } private function connectUsingStandardRTMP() : void { triedStandardRTMP = true connection.connect(movie.rtmpURL.withoutPort) } private function connectUsingHTTP() : void { _usingRTMP = false connection.dontConnect() startPlaying() } public function handleConnectionClosed() : void {} // ----------------------------------------------------- public function handleConnectionEstablished() : void { _usingRTMP = true if (bandwidthDeterminationNeeded) connection.determineBandwidth() else startPlaying() } private function get bandwidthDeterminationNeeded() : Boolean { return bitratePolicy == BitratePolicy.BEST } public function handleBandwidthDetermined (bandwidth : Bitrate, latency : Duration) : void { measuredBandwidth = bandwidth measuredLatency = latency startPlaying() } private function get bandwidthDetermined() : Boolean { return measuredBandwidth != null } private function startPlaying() : void { stream = connection.getNetStream() stream.listener = this stream.volume = volume useStartBuffer() if (usingRTMP) playRTMPStream() else playHTTPStream() if (paused) stream.paused = true } private function playRTMPStream() : void { stream.playRTMP(streamPicker.first, streamPicker.all) } private function playHTTPStream() : void { stream.playHTTP(movie.httpURL) } private function get streamPicker() : RTMPStreamPicker { return new RTMPStreamPicker (movie.rtmpStreams, bitratePolicy, measuredBandwidth) } // ----------------------------------------------------- public function handleNetStreamMetadata(data : Object) : void { metadata = data if (!usingRTMP) debug("Video file size: " + stream.httpFileSize) } public function handleStreamingStarted() : void { useStartBuffer() _buffering = true _finished = false } public function handleBufferFilled() : void { handleBufferingFinished() } private function handleBufferingFinished() : void { _buffering = false // Give the backend a chance to resume playback before we go // ahead and raise the buffer size further. later($handleBufferingFinished) } private function $handleBufferingFinished() : void { // Make sure playback was not interrupted. if (!buffering && !finished) useLargeBuffer() } public function handleBufferEmptied() : void { if (finishedPlaying) handleFinishedPlaying() else handleBufferingStarted() } private function handleBufferingStarted() : void { useSmallBuffer() _buffering = true _finished = false } private function useStartBuffer() : void { stream.bufferTime = START_BUFFER } private function useSmallBuffer() : void { stream.bufferTime = SMALL_BUFFER } private function useLargeBuffer() : void { stream.bufferTime = LARGE_BUFFER } public function get buffering() : Boolean { return _buffering } public function get bufferingUnexpectedly() : Boolean { return buffering && !justSeeked } private function get justSeeked() : Boolean { return seekStopwatch.within(SEEK_GRACE_TIME) } public function handleStreamingStopped() : void { _buffering = false if (finishedPlaying) handleFinishedPlaying() } private function handleFinishedPlaying() : void { debug("Finished playing.") _finished = true for each (var listener : PlayerFinishingListener in finishingListeners) listener.handleMovieFinishedPlaying() } public function stop() : void { debug("Stopping.") stream.close() _started = false stream = null metadata = null } private function get finishedPlaying() : Boolean { return timeRemaining.seconds < 1 } private function get timeRemaining() : Duration { return duration.minus(currentTime) } // ----------------------------------------------------- public function get paused() : Boolean { return _paused } public function set paused(value : Boolean) : void { if (stream != null) _paused = value, stream.paused = value } public function togglePaused() : void { if (stream != null) paused = !paused } // ----------------------------------------------------- public function get currentTime() : Duration { return stream != null && stream.currentTime != null ? stream.currentTime : Duration.ZERO } public function get playheadRatio() : Number { return getRatio(currentTime.seconds, duration.seconds) } public function get bufferRatio() : Number { return getRatio(bufferPosition.seconds, duration.seconds) } private function getRatio (numerator : Number, denominator : Number) : Number { return Math.min(1, numerator / denominator) } private function get bufferPosition() : Duration { return currentTime.plus(bufferLength) } public function set currentTime(value : Duration) : void { if (stream != null) $currentTime = value } private function set $currentTime(value : Duration) : void { _finished = false seekStopwatch.start() useStartBuffer() stream.currentTime = value } public function set playheadRatio(value : Number) : void { currentTime = duration.scaledBy(value) } public function seekBy(delta : Duration) : void { currentTime = currentTime.plus(delta) } public function rewind() : void { currentTime = Duration.ZERO } public function get playing() : Boolean { return started && stream != null && !paused && !finished } // ----------------------------------------------------- public function get volume() : Number { return _volume } public function set volume(value : Number) : void { _volume = Math.round(clamp(value, 0, 1) * 100) / 100 if (sharedVolumeVariable.available) sharedVolumeVariable.value = volume if (stream) stream.volume = volume } public function changeVolumeBy(delta : Number) : void { volume = volume + delta } public function mute() : void { savedVolume = volume volume = 0 } public function unmute() : void { volume = savedVolume == 0 ? DEFAULT_VOLUME : savedVolume } public function get muted() : Boolean { return volume == 0 } // ----------------------------------------------------- public function get aspectRatio() : Number { return movie.aspectRatio } public function get bufferTime() : Duration { return stream != null && stream.bufferTime != null ? stream.bufferTime : START_BUFFER } public function get bufferLength() : Duration { return stream != null && stream.bufferLength != null ? stream.bufferLength : Duration.ZERO } public function get bufferFillRatio() : Number { return getRatio(bufferLength.seconds, bufferTime.seconds) } public function get duration() : Duration { return metadata != null ? Duration.seconds(metadata.duration) : movie.duration } public function get currentBitrate() : Bitrate { return stream != null && stream.bitrate != null ? stream.bitrate : Bitrate.ZERO } public function get currentBandwidth() : Bitrate { return stream != null && stream.bandwidth != null ? stream.bandwidth : Bitrate.ZERO } public function get highQualityDimensions() : Dimensions { var result : Dimensions = Dimensions.ZERO for each (var stream : RTMPStream in movie.rtmpStreams) if (stream.dimensions.isGreaterThan(result)) result = stream.dimensions return result } } }
package goplayer { import flash.utils.getTimer public class Player implements FlashNetConnectionListener, FlashNetStreamListener { private const DEFAULT_VOLUME : Number = .8 private const START_BUFFER : Duration = Duration.seconds(3) private const SMALL_BUFFER : Duration = Duration.seconds(5) private const LARGE_BUFFER : Duration = Duration.seconds(60) private const SEEK_GRACE_TIME : Duration = Duration.seconds(2) private const finishingListeners : Array = [] private var connection : FlashNetConnection private var _movie : Movie private var bitratePolicy : BitratePolicy private var enableRTMP : Boolean private var reporter : MovieEventReporter private var sharedVolumeVariable : SharedVariable private var _started : Boolean = false private var _finished : Boolean = false private var triedStandardRTMP : Boolean = false private var _usingRTMP : Boolean = false private var measuredBandwidth : Bitrate = null private var measuredLatency : Duration = null private var stream : FlashNetStream = null private var metadata : Object = null private var _volume : Number = NaN private var savedVolume : Number = 0 private var _paused : Boolean = false private var _buffering : Boolean = false private var seekStopwatch : Stopwatch = new Stopwatch public function Player (connection : FlashNetConnection, movie : Movie, bitratePolicy : BitratePolicy, enableRTMP : Boolean, reporter : MovieEventReporter, sharedVolumeVariable : SharedVariable) { this.connection = connection _movie = movie this.bitratePolicy = bitratePolicy this.enableRTMP = enableRTMP this.reporter = reporter this.sharedVolumeVariable = sharedVolumeVariable connection.listener = this reporter.reportMovieViewed(movie.id) if (sharedVolumeVariable.hasValue) volume = sharedVolumeVariable.value else volume = DEFAULT_VOLUME } public function get movie() : Movie { return _movie } public function addFinishingListener (value : PlayerFinishingListener) : void { finishingListeners.push(value) } public function get started() : Boolean { return _started } public function get running() : Boolean { return started && !finished } public function get finished() : Boolean { return _finished } // ----------------------------------------------------- public function destroy() : void { if (stream != null) stream.destroy() } public function start() : void { _started = true if (enableRTMP && movie.rtmpURL != null) connectUsingRTMP() else connectUsingHTTP() reporter.reportMoviePlayed(movie.id) } public function handleConnectionFailed() : void { if (movie.rtmpURL.hasPort && !triedStandardRTMP) handleCustomRTMPUnavailable() else handleRTMPUnavailable() } private function handleCustomRTMPUnavailable() : void { debug("Trying to connect using default RTMP ports.") connectUsingStandardRTMP() } private function handleRTMPUnavailable() : void { debug("Could not connect using RTMP; trying plain HTTP.") connectUsingHTTP() } public function get usingRTMP() : Boolean { return _usingRTMP } private function connectUsingRTMP() : void { connection.connect(movie.rtmpURL) } private function connectUsingStandardRTMP() : void { triedStandardRTMP = true connection.connect(movie.rtmpURL.withoutPort) } private function connectUsingHTTP() : void { _usingRTMP = false connection.dontConnect() startPlaying() } public function handleConnectionClosed() : void {} // ----------------------------------------------------- public function handleConnectionEstablished() : void { _usingRTMP = true if (bandwidthDeterminationNeeded) connection.determineBandwidth() else startPlaying() } private function get bandwidthDeterminationNeeded() : Boolean { return bitratePolicy == BitratePolicy.BEST } public function handleBandwidthDetermined (bandwidth : Bitrate, latency : Duration) : void { measuredBandwidth = bandwidth measuredLatency = latency startPlaying() } private function get bandwidthDetermined() : Boolean { return measuredBandwidth != null } private function startPlaying() : void { stream = connection.getNetStream() stream.listener = this stream.volume = volume useStartBuffer() if (usingRTMP) playRTMPStream() else playHTTPStream() if (paused) stream.paused = true } private function playRTMPStream() : void { stream.playRTMP(streamPicker.first, streamPicker.all) } private function playHTTPStream() : void { stream.playHTTP(movie.httpURL) } private function get streamPicker() : RTMPStreamPicker { return new RTMPStreamPicker (movie.rtmpStreams, bitratePolicy, measuredBandwidth) } // ----------------------------------------------------- public function handleNetStreamMetadata(data : Object) : void { metadata = data if (!usingRTMP) debug("Video file size: " + stream.httpFileSize) } public function handleStreamingStarted() : void { useStartBuffer() _buffering = true _finished = false } public function handleBufferFilled() : void { handleBufferingFinished() } private function handleBufferingFinished() : void { _buffering = false // Give the backend a chance to resume playback before we go // ahead and raise the buffer size further. later($handleBufferingFinished) } private function $handleBufferingFinished() : void { // Make sure playback was not interrupted. if (!buffering && !finished) useLargeBuffer() } public function handleBufferEmptied() : void { if (finishedPlaying) handleFinishedPlaying() else handleBufferingStarted() } private function handleBufferingStarted() : void { useSmallBuffer() _buffering = true _finished = false } private function useStartBuffer() : void { stream.bufferTime = START_BUFFER } private function useSmallBuffer() : void { stream.bufferTime = SMALL_BUFFER } private function useLargeBuffer() : void { stream.bufferTime = LARGE_BUFFER } public function get buffering() : Boolean { return _buffering } public function get bufferingUnexpectedly() : Boolean { return buffering && !justSeeked } private function get justSeeked() : Boolean { return seekStopwatch.within(SEEK_GRACE_TIME) } public function handleStreamingStopped() : void { _buffering = false if (finishedPlaying) handleFinishedPlaying() } private function handleFinishedPlaying() : void { debug("Finished playing.") _finished = true for each (var listener : PlayerFinishingListener in finishingListeners) listener.handleMovieFinishedPlaying() } public function stop() : void { debug("Stopping.") stream.close() _started = false stream = null metadata = null } private function get finishedPlaying() : Boolean { return timeRemaining.seconds < 1 } private function get timeRemaining() : Duration { return duration.minus(currentTime) } // ----------------------------------------------------- public function get paused() : Boolean { return _paused } public function set paused(value : Boolean) : void { if (stream != null && _paused != value) _paused = value, stream.paused = value } public function togglePaused() : void { if (stream != null) paused = !paused } // ----------------------------------------------------- public function get currentTime() : Duration { return stream != null && stream.currentTime != null ? stream.currentTime : Duration.ZERO } public function get playheadRatio() : Number { return getRatio(currentTime.seconds, duration.seconds) } public function get bufferRatio() : Number { return getRatio(bufferPosition.seconds, duration.seconds) } private function getRatio (numerator : Number, denominator : Number) : Number { return Math.min(1, numerator / denominator) } private function get bufferPosition() : Duration { return currentTime.plus(bufferLength) } public function set currentTime(value : Duration) : void { if (stream != null) $currentTime = value } private function set $currentTime(value : Duration) : void { _finished = false seekStopwatch.start() useStartBuffer() stream.currentTime = value } public function set playheadRatio(value : Number) : void { currentTime = duration.scaledBy(value) } public function seekBy(delta : Duration) : void { currentTime = currentTime.plus(delta) } public function rewind() : void { currentTime = Duration.ZERO } public function get playing() : Boolean { return started && stream != null && !paused && !finished } // ----------------------------------------------------- public function get volume() : Number { return _volume } public function set volume(value : Number) : void { _volume = Math.round(clamp(value, 0, 1) * 100) / 100 if (sharedVolumeVariable.available) sharedVolumeVariable.value = volume if (stream) stream.volume = volume } public function changeVolumeBy(delta : Number) : void { volume = volume + delta } public function mute() : void { savedVolume = volume volume = 0 } public function unmute() : void { volume = savedVolume == 0 ? DEFAULT_VOLUME : savedVolume } public function get muted() : Boolean { return volume == 0 } // ----------------------------------------------------- public function get aspectRatio() : Number { return movie.aspectRatio } public function get bufferTime() : Duration { return stream != null && stream.bufferTime != null ? stream.bufferTime : START_BUFFER } public function get bufferLength() : Duration { return stream != null && stream.bufferLength != null ? stream.bufferLength : Duration.ZERO } public function get bufferFillRatio() : Number { return getRatio(bufferLength.seconds, bufferTime.seconds) } public function get duration() : Duration { return metadata != null ? Duration.seconds(metadata.duration) : movie.duration } public function get currentBitrate() : Bitrate { return stream != null && stream.bitrate != null ? stream.bitrate : Bitrate.ZERO } public function get currentBandwidth() : Bitrate { return stream != null && stream.bandwidth != null ? stream.bandwidth : Bitrate.ZERO } public function get highQualityDimensions() : Dimensions { var result : Dimensions = Dimensions.ZERO for each (var stream : RTMPStream in movie.rtmpStreams) if (stream.dimensions.isGreaterThan(result)) result = stream.dimensions return result } } }
Make setting Player.pause idempotent.
Make setting Player.pause idempotent.
ActionScript
mit
dbrock/goplayer,dbrock/goplayer
aa85b28c08b49f20c2d4611b70cf5b9804ea0f15
src/battlecode/client/viewer/render/DrawRobot.as
src/battlecode/client/viewer/render/DrawRobot.as
package battlecode.client.viewer.render { import battlecode.common.ActionType; import battlecode.common.Direction; import battlecode.common.GameConstants; import battlecode.common.MapLocation; import battlecode.common.RobotType; import battlecode.common.Team; import battlecode.events.RobotEvent; import mx.containers.Canvas; import mx.controls.Image; import mx.core.UIComponent; [Event(name="indicatorStringChange", type="battlecode.events.RobotEvent")] public class DrawRobot extends Canvas implements DrawObject { private var actions:Vector.<DrawAction>; private var broadcastAnimation:BroadcastAnimation; private var explosionAnimation:ExplosionAnimation; private var overlayCanvas:UIComponent; private var imageCanvas:UIComponent; private var hatCanvas:UIComponent; private var image:Image; // size private var overrideSize:Number; // indicator strings private var indicatorStrings:Vector.<String> = new Vector.<String>(3, true); // movement animation private var drawX:Number, drawY:Number; private var movementDelay:uint; // attack animation private var targetLocation:MapLocation; private var selected:Boolean = false; private var robotID:uint; private var type:String; private var team:String; private var location:MapLocation; private var direction:String; private var energon:Number = 0; private var maxEnergon:Number = 0; private var alive:Boolean = true; private var hats:Array; private var hatImages:Array; public function DrawRobot(robotID:uint, type:String, team:String, overrideSize:Number = 0) { this.robotID = robotID; this.type = type; this.team = team; this.maxEnergon = RobotType.maxEnergon(type); this.movementDelay = 0; this.hats = new Array(); this.hatImages = new Array(); this.actions = new Vector.<DrawAction>(); this.overrideSize = overrideSize; // set the unit avatar image var avatarClass:Class = ImageAssets.getRobotAvatar(type, team); this.imageCanvas = new UIComponent(); this.image = new Image(); this.image.source = avatarClass; this.image.width = getImageSize(true); this.image.height = getImageSize(true); this.image.x = -this.image.width / 2; this.image.y = -this.image.height / 2; this.imageCanvas.addChild(image); this.addChild(imageCanvas); this.width = this.image.width; this.height = this.image.height; this.overlayCanvas = new UIComponent(); this.addChild(overlayCanvas); this.hatCanvas = new UIComponent(); this.addChild(hatCanvas); // set the hit area for click selection this.hitArea = imageCanvas; // animations this.broadcastAnimation = new BroadcastAnimation(0, team); this.addChild(broadcastAnimation); this.explosionAnimation = new ExplosionAnimation(); this.addChild(explosionAnimation); } public function clone():DrawObject { var d:DrawRobot = new DrawRobot(robotID, type, team, overrideSize); d.location = location; d.energon = energon; d.movementDelay = movementDelay; d.targetLocation = targetLocation; d.alive = alive; d.hats = hats.concat(); d.hatImages = new Array(); d.actions = new Vector.<DrawAction>(actions.length); for each (var o:DrawAction in actions) { d.actions.push(o.clone()); } d.removeChild(d.broadcastAnimation); d.removeChild(d.explosionAnimation); d.broadcastAnimation = broadcastAnimation.clone() as BroadcastAnimation; d.explosionAnimation = explosionAnimation.clone() as ExplosionAnimation; d.addChild(d.broadcastAnimation); d.addChild(d.explosionAnimation); return d; } private function addAction(d:DrawAction):void { actions.push(d); } public function getRobotID():uint { return robotID; } public function getType():String { return type; } public function getTeam():String { return team; } public function getLocation():MapLocation { return location; } public function getSelected():Boolean { return selected; } public function getIndicatorString(index:uint):String { return indicatorStrings[index]; } public function setLocation(location:MapLocation):void { this.location = location; } public function setEnergon(amt:Number):void { this.energon = Math.min(Math.max(0, amt), maxEnergon); } public function setSelected(val:Boolean):void { this.selected = val; } public function setIndicatorString(str:String, index:uint):void { indicatorStrings[index] = str; dispatchEvent(new RobotEvent(RobotEvent.INDICATOR_STRING_CHANGE, false, false, this)); } public function setOverrideSize(overrideSize:Number):void { this.overrideSize = overrideSize; this.draw(true); } public function capture():void { this.addAction(new DrawAction(ActionType.CAPTURING, GameConstants.CAPTURE_DELAY)); } public function layMine():void { this.addAction(new DrawAction(ActionType.MINING, GameConstants.MINE_LAY_DELAY)); } public function stopLayingMine():void { this.addAction(new DrawAction(ActionType.MINING_STOPPING, GameConstants.MINE_LAY_STOP_DELAY)); } public function diffuseMine(hasUpgrade:Boolean):void { this.addAction(new DrawAction(ActionType.DEFUSING, hasUpgrade ? GameConstants.MINE_DIFFUSE_UPGRADE_DELAY: GameConstants.MINE_DIFFUSE_DELAY)) } public function attack(targetLocation:MapLocation):void { this.targetLocation = targetLocation; this.addAction(new DrawAction(ActionType.ATTACKING, RobotType.attackDelay(type))); } public function broadcast():void { this.broadcastAnimation.broadcast(); } public function destroyUnit():void { this.explosionAnimation.explode(); this.alive = false; } public function moveToLocation(location:MapLocation):void { this.direction = this.location.directionTo(location); this.movementDelay = Direction.isDiagonal(direction) ? RobotType.movementDelayDiagonal(type) : RobotType.movementDelay(type); this.location = location; this.addAction(new DrawAction(ActionType.MOVING, movementDelay)); } public function wearHat(hat:int):void { hats.push(hat); } public function isAlive():Boolean { return alive || explosionAnimation.isAlive(); } public function updateRound():void { // update actions for (var i:uint = 0; i < actions.length; i++) { var o:DrawAction = actions[i]; o.decreaseRound(); if (o.getRounds() <= 0) { actions.splice(i, 1); i--; } } // update animations broadcastAnimation.updateRound(); explosionAnimation.updateRound(); // update tooltip this.toolTip = "Robot " + getRobotID() + " " + getType() + " Energon: " + energon + " Loc: " + getLocation().toString(); } public function draw(force:Boolean = false):void { if (explosionAnimation.isExploding()) { this.imageCanvas.visible = false; this.overlayCanvas.visible = false; this.graphics.clear(); explosionAnimation.draw(force); return; } // draw direction if (type != RobotType.SOLDIER) { this.imageCanvas.rotation = directionToRotation(direction); } else { // TODO soldier sprite } if (force) { this.image.width = getImageSize(true); this.image.height = getImageSize(true); this.image.x = -this.image.width / 2; this.image.y = -this.image.height / 2; } // clear the graphics object once this.graphics.clear(); this.overlayCanvas.graphics.clear(); var o:DrawAction; var movementRounds:uint = 0; for each (o in actions) { if (o.getType() == ActionType.MOVING) { movementRounds = o.getRounds(); break; } } drawX = calculateDrawX(movementRounds); drawY = calculateDrawY(movementRounds); for each (o in actions) { switch (o.getType()) { case ActionType.ATTACKING: drawAttack(); break; case ActionType.MOVING: drawMovement(); break; case ActionType.CAPTURING: case ActionType.MINING: case ActionType.MINING_STOPPING: case ActionType.DEFUSING: drawActionBar(o); break; } } drawEnergonBar(); drawSelected(); drawHats(); // draw animations broadcastAnimation.draw(force); } /////////////////////////////////////////////////////// ////////////// DRAWING HELPER FUNCTIONS /////////////// /////////////////////////////////////////////////////// private function drawEnergonBar():void { if (!RenderConfiguration.showEnergon() && getType() != RobotType.HQ) return; var ratio:Number = energon / maxEnergon; var size:Number = getImageSize(true); this.graphics.lineStyle(); this.graphics.beginFill(0x00FF00, 0.8); this.graphics.drawRect(-size / 2, size / 2, ratio * size, 5 * getImageScale()); this.graphics.endFill(); this.graphics.beginFill(0x000000, 0.8); this.graphics.drawRect(-size / 2 + ratio * size, size / 2, (1 - ratio) * size, 5 * getImageScale()); this.graphics.endFill(); } private function drawActionBar(action:DrawAction):void { var yOffset:Number = RenderConfiguration.showEnergon() ? 5 * getImageScale() : 0; var color:uint; switch (action.getType()) { case ActionType.CAPTURING: color = 0x4C4CFF; break; case ActionType.MINING: color = 0xFF00CC; break; case ActionType.MINING_STOPPING: color = 0xFF0000; break; case ActionType.DEFUSING: color = 0x00FFFF; break; default: color = 0x000000; break; } var ratio:Number; switch (action.getType()) { case ActionType.MINING_STOPPING: ratio = action.getRounds() / action.getMaxRounds(); break; default: ratio = (action.getMaxRounds() - action.getRounds()) / action.getMaxRounds(); break; } var size:Number = getImageSize(true); this.graphics.lineStyle(); this.graphics.beginFill(color, 0.8); this.graphics.drawRect(-size / 2, size / 2 + yOffset, ratio * size, 5 * getImageScale()); this.graphics.endFill(); this.graphics.beginFill(0x000000, 0.8); this.graphics.drawRect(-size / 2 + ratio * size, size / 2 + yOffset, (1 - ratio) * size, 5 * getImageScale()); this.graphics.endFill(); } private function drawAttack():void { var targetOffsetX:Number = (targetLocation.getX() - location.getX()) * getImageSize(); var targetOffsetY:Number = (targetLocation.getY() - location.getY()) * getImageSize(); this.graphics.lineStyle(2, team == Team.A ? 0xFF0000 : 0x0000FF); this.graphics.moveTo(0, 0); this.graphics.lineTo(targetOffsetX - drawX, targetOffsetY - drawY); this.graphics.drawCircle(targetOffsetX - drawX, targetOffsetY - drawY, getImageSize() / 2 * .6); } private function drawMovement():void { if (RenderConfiguration.showDiscrete()) return; this.x += drawX; this.y += drawY; } private function drawSelected():void { var size:Number = getImageSize(true); if (selected) { this.graphics.lineStyle(2, 0xFFFFFF); this.graphics.moveTo(-size / 2, -size / 4); this.graphics.lineTo(-size / 2, -size / 2); this.graphics.lineTo(-size / 4, -size / 2); this.graphics.moveTo(size / 2, -size / 4); this.graphics.lineTo(size / 2, -size / 2); this.graphics.lineTo(size / 4, -size / 2); this.graphics.moveTo(size / 2, size / 4); this.graphics.lineTo(size / 2, size / 2); this.graphics.lineTo(size / 4, size / 2); this.graphics.moveTo(-size / 2, size / 4); this.graphics.lineTo(-size / 2, size / 2); this.graphics.lineTo(-size / 4, size / 2); } } private function drawHats():void { if (!RenderConfiguration.showHats()) { hatCanvas.visible = false; return; } hatCanvas.visible = true; while (hatImages.length < hats.length) { var hatImage:Image = new Image(); var hatSource:Class = ImageAssets.getHatAvatar(hats[hatImages.length]); hatImage.source = new hatSource(); hatImage.width = RenderConfiguration.getGridSize(); hatImage.height = RenderConfiguration.getGridSize(); hatImage.x = -RenderConfiguration.getGridSize() / 2; hatImage.y = -RenderConfiguration.getGridSize() - hatImage.height * hatImages.length; hatCanvas.addChild(hatImage); hatImages.push(hatImage); } } /////////////////////////////////////////////////////// ////////////// PRIVATE HELPER FUNCTIONS /////////////// /////////////////////////////////////////////////////// private function getImageSize(scale:Boolean = false):Number { if (overrideSize) return overrideSize; return RenderConfiguration.getGridSize() * (scale ? getUnitScale(type) : 1.0); } private function getImageScale():Number { if (overrideSize) return 1.0; return RenderConfiguration.getScalingFactor(); } private function getUnitScale(type:String):Number { switch (type) { case RobotType.HQ: return 2.0; default: return 1.0; } } private function getUnitOffset(type:String):Number { return 0; } private function directionToRotation(dir:String):int { switch (dir) { case Direction.NORTH: return -90; case Direction.NORTH_EAST: return -45; case Direction.EAST: return 0; case Direction.SOUTH_EAST: return 45; case Direction.SOUTH: return 90; case Direction.SOUTH_WEST: return 135; case Direction.WEST: return 180; case Direction.NORTH_WEST: return -135; default: return 0; } } private function directionOffsetX(dir:String):int { switch (dir) { case Direction.NORTH_EAST: return +1; case Direction.NORTH_WEST: return -1; case Direction.SOUTH_EAST: return +1; case Direction.SOUTH_WEST: return -1; case Direction.NORTH: return 0; case Direction.SOUTH: return 0; case Direction.EAST: return +1; case Direction.WEST: return -1; default: return 0; } } private function directionOffsetY(dir:String):int { switch (dir) { case Direction.NORTH_EAST: return -1; case Direction.NORTH_WEST: return -1; case Direction.SOUTH_EAST: return +1; case Direction.SOUTH_WEST: return +1; case Direction.NORTH: return -1; case Direction.SOUTH: return +1; case Direction.EAST: return 0; case Direction.WEST: return 0; default: return 0; } } private function calculateDrawX(rounds:uint):Number { return 0; } private function calculateDrawY(rounds:uint):Number { return 0; } } }
package battlecode.client.viewer.render { import battlecode.common.ActionType; import battlecode.common.Direction; import battlecode.common.GameConstants; import battlecode.common.MapLocation; import battlecode.common.RobotType; import battlecode.common.Team; import battlecode.events.RobotEvent; import mx.containers.Canvas; import mx.controls.Image; import mx.core.UIComponent; [Event(name="indicatorStringChange", type="battlecode.events.RobotEvent")] public class DrawRobot extends Canvas implements DrawObject { private var actions:Vector.<DrawAction>; private var broadcastAnimation:BroadcastAnimation; private var explosionAnimation:ExplosionAnimation; private var overlayCanvas:UIComponent; private var imageCanvas:UIComponent; private var hatCanvas:UIComponent; private var image:Image; // size private var overrideSize:Number; // indicator strings private var indicatorStrings:Vector.<String> = new Vector.<String>(3, true); // movement animation private var drawX:Number, drawY:Number; private var movementDelay:uint; // attack animation private var targetLocation:MapLocation; private var selected:Boolean = false; private var robotID:uint; private var type:String; private var team:String; private var location:MapLocation; private var direction:String; private var energon:Number = 0; private var maxEnergon:Number = 0; private var alive:Boolean = true; private var hats:Array; private var hatImages:Array; public function DrawRobot(robotID:uint, type:String, team:String, overrideSize:Number = 0) { this.robotID = robotID; this.type = type; this.team = team; this.maxEnergon = RobotType.maxEnergon(type); this.movementDelay = 0; this.hats = new Array(); this.hatImages = new Array(); this.actions = new Vector.<DrawAction>(); this.overrideSize = overrideSize; // set the unit avatar image var avatarClass:Class = ImageAssets.getRobotAvatar(type, team); this.imageCanvas = new UIComponent(); this.image = new Image(); this.image.source = avatarClass; this.image.width = getImageSize(true); this.image.height = getImageSize(true); this.image.x = -this.image.width / 2; this.image.y = -this.image.height / 2; this.imageCanvas.addChild(image); this.addChild(imageCanvas); this.width = this.image.width; this.height = this.image.height; this.overlayCanvas = new UIComponent(); this.addChild(overlayCanvas); this.hatCanvas = new UIComponent(); this.addChild(hatCanvas); // set the hit area for click selection this.hitArea = imageCanvas; // animations this.broadcastAnimation = new BroadcastAnimation(0, team); this.addChild(broadcastAnimation); this.explosionAnimation = new ExplosionAnimation(); this.addChild(explosionAnimation); } public function clone():DrawObject { var d:DrawRobot = new DrawRobot(robotID, type, team, overrideSize); d.location = location; d.energon = energon; d.movementDelay = movementDelay; d.targetLocation = targetLocation; d.alive = alive; d.hats = hats.concat(); d.hatImages = new Array(); d.actions = new Vector.<DrawAction>(actions.length); for each (var o:DrawAction in actions) { d.actions.push(o.clone()); } d.removeChild(d.broadcastAnimation); d.removeChild(d.explosionAnimation); d.broadcastAnimation = broadcastAnimation.clone() as BroadcastAnimation; d.explosionAnimation = explosionAnimation.clone() as ExplosionAnimation; d.addChild(d.broadcastAnimation); d.addChild(d.explosionAnimation); return d; } private function addAction(d:DrawAction):void { actions.push(d); } public function getRobotID():uint { return robotID; } public function getType():String { return type; } public function getTeam():String { return team; } public function getLocation():MapLocation { return location; } public function getSelected():Boolean { return selected; } public function getIndicatorString(index:uint):String { return indicatorStrings[index]; } public function setLocation(location:MapLocation):void { this.location = location; } public function setEnergon(amt:Number):void { this.energon = Math.min(Math.max(0, amt), maxEnergon); } public function setSelected(val:Boolean):void { this.selected = val; } public function setIndicatorString(str:String, index:uint):void { indicatorStrings[index] = str; dispatchEvent(new RobotEvent(RobotEvent.INDICATOR_STRING_CHANGE, false, false, this)); } public function setOverrideSize(overrideSize:Number):void { this.overrideSize = overrideSize; this.draw(true); } public function capture():void { this.addAction(new DrawAction(ActionType.CAPTURING, GameConstants.CAPTURE_DELAY)); } public function layMine():void { this.addAction(new DrawAction(ActionType.MINING, GameConstants.MINE_LAY_DELAY)); } public function stopLayingMine():void { this.addAction(new DrawAction(ActionType.MINING_STOPPING, GameConstants.MINE_LAY_STOP_DELAY)); } public function diffuseMine(hasUpgrade:Boolean):void { this.addAction(new DrawAction(ActionType.DEFUSING, hasUpgrade ? GameConstants.MINE_DIFFUSE_UPGRADE_DELAY: GameConstants.MINE_DIFFUSE_DELAY)) } public function attack(targetLocation:MapLocation):void { this.targetLocation = targetLocation; this.addAction(new DrawAction(ActionType.ATTACKING, RobotType.attackDelay(type))); } public function broadcast():void { this.broadcastAnimation.broadcast(); } public function destroyUnit():void { this.explosionAnimation.explode(); this.alive = false; } public function moveToLocation(location:MapLocation):void { this.direction = this.location.directionTo(location); this.movementDelay = Direction.isDiagonal(direction) ? RobotType.movementDelayDiagonal(type) : RobotType.movementDelay(type); this.location = location; this.addAction(new DrawAction(ActionType.MOVING, movementDelay)); } public function wearHat(hat:int):void { hats.push(hat); } public function isAlive():Boolean { return alive || explosionAnimation.isAlive(); } public function updateRound():void { // update actions for (var i:uint = 0; i < actions.length; i++) { var o:DrawAction = actions[i]; o.decreaseRound(); if (o.getRounds() <= 0) { actions.splice(i, 1); i--; } } // update animations broadcastAnimation.updateRound(); explosionAnimation.updateRound(); // update tooltip this.toolTip = "Robot " + getRobotID() + " " + getType() + " Energon: " + energon + " Loc: " + getLocation().toString(); } public function draw(force:Boolean = false):void { if (explosionAnimation.isExploding()) { this.imageCanvas.visible = false; this.overlayCanvas.visible = false; this.graphics.clear(); explosionAnimation.draw(force); return; } // draw direction this.imageCanvas.rotation = directionToRotation(direction); if (force) { this.image.width = getImageSize(true); this.image.height = getImageSize(true); this.image.x = -this.image.width / 2; this.image.y = -this.image.height / 2; } // clear the graphics object once this.graphics.clear(); this.overlayCanvas.graphics.clear(); var o:DrawAction; var movementRounds:uint = 0; for each (o in actions) { if (o.getType() == ActionType.MOVING) { movementRounds = o.getRounds(); break; } } drawX = calculateDrawX(movementRounds); drawY = calculateDrawY(movementRounds); for each (o in actions) { switch (o.getType()) { case ActionType.ATTACKING: drawAttack(); break; case ActionType.MOVING: drawMovement(); break; case ActionType.CAPTURING: case ActionType.MINING: case ActionType.MINING_STOPPING: case ActionType.DEFUSING: drawActionBar(o); break; } } drawEnergonBar(); drawSelected(); drawHats(); // draw animations broadcastAnimation.draw(force); } /////////////////////////////////////////////////////// ////////////// DRAWING HELPER FUNCTIONS /////////////// /////////////////////////////////////////////////////// private function drawEnergonBar():void { if (!RenderConfiguration.showEnergon() && getType() != RobotType.HQ) return; var ratio:Number = energon / maxEnergon; var size:Number = getImageSize(true); this.graphics.lineStyle(); this.graphics.beginFill(0x00FF00, 0.8); this.graphics.drawRect(-size / 2, size / 2, ratio * size, 5 * getImageScale()); this.graphics.endFill(); this.graphics.beginFill(0x000000, 0.8); this.graphics.drawRect(-size / 2 + ratio * size, size / 2, (1 - ratio) * size, 5 * getImageScale()); this.graphics.endFill(); } private function drawActionBar(action:DrawAction):void { var yOffset:Number = RenderConfiguration.showEnergon() ? 5 * getImageScale() : 0; var color:uint; switch (action.getType()) { case ActionType.CAPTURING: color = 0x4C4CFF; break; case ActionType.MINING: color = 0xFF00CC; break; case ActionType.MINING_STOPPING: color = 0xFF0000; break; case ActionType.DEFUSING: color = 0x00FFFF; break; default: color = 0x000000; break; } var ratio:Number; switch (action.getType()) { case ActionType.MINING_STOPPING: ratio = action.getRounds() / action.getMaxRounds(); break; default: ratio = (action.getMaxRounds() - action.getRounds()) / action.getMaxRounds(); break; } var size:Number = getImageSize(true); this.graphics.lineStyle(); this.graphics.beginFill(color, 0.8); this.graphics.drawRect(-size / 2, size / 2 + yOffset, ratio * size, 5 * getImageScale()); this.graphics.endFill(); this.graphics.beginFill(0x000000, 0.8); this.graphics.drawRect(-size / 2 + ratio * size, size / 2 + yOffset, (1 - ratio) * size, 5 * getImageScale()); this.graphics.endFill(); } private function drawAttack():void { var targetOffsetX:Number = (targetLocation.getX() - location.getX()) * getImageSize(); var targetOffsetY:Number = (targetLocation.getY() - location.getY()) * getImageSize(); this.graphics.lineStyle(2, team == Team.A ? 0xFF0000 : 0x0000FF); this.graphics.moveTo(0, 0); this.graphics.lineTo(targetOffsetX - drawX, targetOffsetY - drawY); this.graphics.drawCircle(targetOffsetX - drawX, targetOffsetY - drawY, getImageSize() / 2 * .6); } private function drawMovement():void { if (RenderConfiguration.showDiscrete()) return; this.x += drawX; this.y += drawY; } private function drawSelected():void { var size:Number = getImageSize(true); if (selected) { this.graphics.lineStyle(2, 0xFFFFFF); this.graphics.moveTo(-size / 2, -size / 4); this.graphics.lineTo(-size / 2, -size / 2); this.graphics.lineTo(-size / 4, -size / 2); this.graphics.moveTo(size / 2, -size / 4); this.graphics.lineTo(size / 2, -size / 2); this.graphics.lineTo(size / 4, -size / 2); this.graphics.moveTo(size / 2, size / 4); this.graphics.lineTo(size / 2, size / 2); this.graphics.lineTo(size / 4, size / 2); this.graphics.moveTo(-size / 2, size / 4); this.graphics.lineTo(-size / 2, size / 2); this.graphics.lineTo(-size / 4, size / 2); } } private function drawHats():void { if (!RenderConfiguration.showHats()) { hatCanvas.visible = false; return; } hatCanvas.visible = true; while (hatImages.length < hats.length) { var hatImage:Image = new Image(); var hatSource:Class = ImageAssets.getHatAvatar(hats[hatImages.length]); hatImage.source = new hatSource(); hatImage.width = RenderConfiguration.getGridSize(); hatImage.height = RenderConfiguration.getGridSize(); hatImage.x = -RenderConfiguration.getGridSize() / 2; hatImage.y = -RenderConfiguration.getGridSize() - hatImage.height * hatImages.length; hatCanvas.addChild(hatImage); hatImages.push(hatImage); } } /////////////////////////////////////////////////////// ////////////// PRIVATE HELPER FUNCTIONS /////////////// /////////////////////////////////////////////////////// private function getImageSize(scale:Boolean = false):Number { if (overrideSize) return overrideSize; return RenderConfiguration.getGridSize() * (scale ? getUnitScale(type) : 1.0); } private function getImageScale():Number { if (overrideSize) return 1.0; return RenderConfiguration.getScalingFactor(); } private function getUnitScale(type:String):Number { switch (type) { case RobotType.HQ: return 2.0; default: return 1.0; } } private function getUnitOffset(type:String):Number { return 0; } private function directionToRotation(dir:String):int { switch (dir) { case Direction.NORTH: return -90; case Direction.NORTH_EAST: return -45; case Direction.EAST: return 0; case Direction.SOUTH_EAST: return 45; case Direction.SOUTH: return 90; case Direction.SOUTH_WEST: return 135; case Direction.WEST: return 180; case Direction.NORTH_WEST: return -135; default: return 0; } } private function directionOffsetX(dir:String):int { switch (dir) { case Direction.NORTH_EAST: return +1; case Direction.NORTH_WEST: return -1; case Direction.SOUTH_EAST: return +1; case Direction.SOUTH_WEST: return -1; case Direction.NORTH: return 0; case Direction.SOUTH: return 0; case Direction.EAST: return +1; case Direction.WEST: return -1; default: return 0; } } private function directionOffsetY(dir:String):int { switch (dir) { case Direction.NORTH_EAST: return -1; case Direction.NORTH_WEST: return -1; case Direction.SOUTH_EAST: return +1; case Direction.SOUTH_WEST: return +1; case Direction.NORTH: return -1; case Direction.SOUTH: return +1; case Direction.EAST: return 0; case Direction.WEST: return 0; default: return 0; } } private function calculateDrawX(rounds:uint):Number { return 0; } private function calculateDrawY(rounds:uint):Number { return 0; } } }
fix solider rotation
fix solider rotation
ActionScript
mit
trun/battlecode-webclient
730be88d871e6c94ea6170689c8cc582be37e8f2
src/fr/manashield/flex/thex/Game.as
src/fr/manashield/flex/thex/Game.as
package fr.manashield.flex.thex { import fr.manashield.flex.thex.blocks.Block; import fr.manashield.flex.thex.blocks.BlockGenerator; import fr.manashield.flex.thex.blocks.HexagonalGrid; import fr.manashield.flex.thex.events.BlockLandingEvent; import fr.manashield.flex.thex.utils.Color; import flash.display.Stage; import flash.geom.Point; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; /** * @author Morgan Peyre ([email protected]) * @author Paul Bonnet */ public class Game { private static const CELL_RADIUS:uint = 25; protected var _stage:Stage; protected var _origin:Point; protected var _score:uint; protected var _scoreField:TextField; public function Game(stage:Stage):void { // Game board _stage = stage; HexagonalGrid.init(_stage, CELL_RADIUS); _origin = _origin = HexagonalGrid.instance.hexToCartesian(new Point(0,0)); // Score field _score = 0; _scoreField = new TextField(); _scoreField.name = "_scoreField"; // TODO : repositionner le texte en fonction du ratio d'aspect _scoreField.autoSize = TextFieldAutoSize.LEFT; stage.addChild(_scoreField); var format:TextFormat = new TextFormat(); format.size = 100; format.font = "score"; format.color = 0x555555; format.letterSpacing = 4; _scoreField.defaultTextFormat = format; _scoreField.embedFonts = true; _scoreField.text = _score.toString(); // central hexagon var centralBlock:Block = new Block(HexagonalGrid.instance.cell(new Point(0,0)), new Color(0x5c5c5c)); $(centralBlock); // Get rid of the annoying "not used" warning. // reate the initial blocks this.fillGrid(); // initialze and launch the animation of the falling blocks Animation.initialize(this); Animation.instance.addEventListener(BlockLandingEvent.LANDING, this.blockLanded); // create first falling block BlockGenerator.instance.spawnBlock(); } public function get stage():Stage { return _stage; } public function blockLanded(e:BlockLandingEvent):void { if(e.block.sameColorNeighbors() >= 3) { _score += e.block.sameColorNeighbors() - 2; _scoreField.text = _score.toString(); e.block.destroyIf(e.block.color); } } protected function fillGrid(radius:uint = 3):void { for(var i:uint=1; i<=radius; ++i) { for(var j:uint=0; j<6*i; ++j) { BlockGenerator.instance.spawnBlock(i, j, false); } } } //useless function used to get rid of a warning private function $(o:Object):void{} } }
package fr.manashield.flex.thex { import fr.manashield.flex.thex.blocks.Block; import fr.manashield.flex.thex.blocks.BlockGenerator; import fr.manashield.flex.thex.blocks.HexagonalGrid; import fr.manashield.flex.thex.events.BlockLandingEvent; import fr.manashield.flex.thex.utils.Color; import flash.display.Stage; import flash.geom.Point; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; /** * @author Morgan Peyre ([email protected]) * @author Paul Bonnet */ public class Game { private static const CELL_RADIUS:uint = 25; protected var _stage:Stage; protected var _origin:Point; protected var _score:uint; protected var _scoreField:TextField; public function Game(stage:Stage):void { // Game board _stage = stage; HexagonalGrid.init(_stage, CELL_RADIUS); _origin = _origin = HexagonalGrid.instance.hexToCartesian(new Point(0,0)); // Score field _score = 0; _scoreField = new TextField(); _scoreField.name = "_scoreField"; // TODO : repositionner le texte en fonction du ratio d'aspect _scoreField.autoSize = TextFieldAutoSize.LEFT; stage.addChild(_scoreField); var format:TextFormat = new TextFormat(); format.size = 100; format.font = "score"; format.color = 0x555555; format.letterSpacing = 4; _scoreField.defaultTextFormat = format; _scoreField.embedFonts = true; _scoreField.text = _score.toString(); // central hexagon var centralBlock:Block = new Block(HexagonalGrid.instance.cell(new Point(0,0)), new Color(0x5c5c5c)); $(centralBlock); // Get rid of the annoying "not used" warning. // create the initial blocks this.fillGrid(); // initialze and launch the animation of the falling blocks Animation.initialize(this); Animation.instance.addEventListener(BlockLandingEvent.LANDING, this.blockLanded); // create first falling block BlockGenerator.instance.spawnBlock(); } public function get stage():Stage { return _stage; } public function blockLanded(e:BlockLandingEvent):void { if(e.block.sameColorNeighbors() >= 3) { _score += e.block.sameColorNeighbors() - 2; _scoreField.text = _score.toString(); e.block.destroyIf(e.block.color); } } protected function fillGrid(radius:uint = 3):void { for(var i:uint=1; i<=radius; ++i) { for(var j:uint=0; j<6*i; ++j) { BlockGenerator.instance.spawnBlock(i, j, false); } } } //useless function used to get rid of a warning private function $(o:Object):void{} } }
comment fix
comment fix
ActionScript
apache-2.0
peyremorgan/thex
02d24ecce4c5978999ba2f3b2498047dfe218bd0
kdp3Lib/src/com/kaltura/kdpfl/ApplicationFacade.as
kdp3Lib/src/com/kaltura/kdpfl/ApplicationFacade.as
package com.kaltura.kdpfl { import com.kaltura.kdpfl.controller.InitMacroCommand; import com.kaltura.kdpfl.controller.LayoutReadyCommand; import com.kaltura.kdpfl.controller.PlaybackCompleteCommand; import com.kaltura.kdpfl.controller.SequenceItemPlayEndCommand; import com.kaltura.kdpfl.controller.SequenceSkipNextCommand; import com.kaltura.kdpfl.controller.StartupCommand; import com.kaltura.kdpfl.controller.media.InitChangeMediaMacroCommand; import com.kaltura.kdpfl.controller.media.LiveStreamCommand; import com.kaltura.kdpfl.controller.media.MediaReadyCommand; import com.kaltura.kdpfl.events.DynamicEvent; import com.kaltura.kdpfl.model.ExternalInterfaceProxy; import com.kaltura.kdpfl.model.type.DebugLevel; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.view.controls.KTrace; import com.kaltura.kdpfl.view.media.KMediaPlayerMediator; import com.kaltura.puremvc.as3.core.KView; import flash.display.DisplayObject; import mx.utils.ObjectProxy; import org.osmf.media.MediaPlayerState; import org.puremvc.as3.interfaces.IFacade; import org.puremvc.as3.interfaces.IMediator; import org.puremvc.as3.interfaces.IProxy; import org.puremvc.as3.patterns.facade.Facade; public class ApplicationFacade extends Facade implements IFacade { /** * The current version of the KDP. */ public var kdpVersion : String = "v3.9.3"; /** * save any mediator name that is registered to this array in order to delete at any time * (the pure mvc don't support it as built-in function) */ private var _mediatorNameArray : Array = new Array(); /** * save any proxy name that is registered to this array in order to delete at any time * (the pure mvc don't support it as built-in function) */ private var _proxyNameArray : Array = new Array(); /** * save any notification that create a command name that is registered to this array in order to delete at any time * (the pure mvc don't support it as built-in function) */ private var _commandNameArray : Array = new Array(); /** * The bindObject create dynamicly all attributes that need to be binded on it */ public var bindObject:ObjectProxy = new ObjectProxy(); /** * a reference to KDP3 main application */ private var _app : DisplayObject; /** * the url of the kdp */ public var appFolder : String; public var debugMode : Boolean = false; /** * * will affect the traces that will be sent. See DebugLevel enum */ public var debugLevel:int; private var externalInterface : ExternalInterfaceProxy; /** * return the one and only instance of the ApplicationFacade, * if not exist it will be created. * @return * */ public static function getInstance() : ApplicationFacade { if (instance == null) instance = new ApplicationFacade(); return instance as ApplicationFacade; } /** * All this simply does is fire a notification which is routed to * "StartupCommand" via the "registerCommand" handlers * @param app * */ public function start(app:DisplayObject):void { CONFIG::isSDK46 { kdpVersion += ".sdk46"; } _app = app; appFolder = app.root.loaderInfo.url; appFolder = appFolder.substr(0, appFolder.lastIndexOf('/') + 1); sendNotification(NotificationType.STARTUP, app); externalInterface = retrieveProxy(ExternalInterfaceProxy.NAME) as ExternalInterfaceProxy; } /** * Created to trace all notifications for debug * @param notificationName * @param body * @param type * */ override public function sendNotification(notificationName:String, body:Object = null, type:String = null):void { if (debugMode) { var s:String; if ((notificationName == NotificationType.BYTES_DOWNLOADED_CHANGE && debugLevel == DebugLevel.HIGH) || (notificationName == NotificationType.PLAYER_UPDATE_PLAYHEAD && (debugLevel == DebugLevel.HIGH || debugLevel == DebugLevel.MEDIUM)) || (notificationName != NotificationType.PLAYER_UPDATE_PLAYHEAD && notificationName != NotificationType.BYTES_DOWNLOADED_CHANGE)) { if (notificationName == NotificationType.PLAYER_STATE_CHANGE) s = 'Sent ' + notificationName + ' ==> ' + body.toString(); else { s = 'Sent ' + notificationName; if (body) { var found:Boolean = false; for (var o:* in body) { s += ", " + o + ":" + body[o]; found = true; } if (!found) { s += ", " + body.toString(); } } } } if (s && s != "null") { var curTime:Number = 0; var kmediaPlayerMediator:KMediaPlayerMediator = retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator; if (kmediaPlayerMediator && kmediaPlayerMediator.player && kmediaPlayerMediator.player.state!=MediaPlayerState.LOADING && kmediaPlayerMediator.player.state!=MediaPlayerState.UNINITIALIZED && kmediaPlayerMediator.player.state!=MediaPlayerState.PLAYBACK_ERROR) { curTime = kmediaPlayerMediator.getCurrentTime(); } var date:Date = new Date(); KTrace.getInstance().log(date.toTimeString(), ":", s, ", playhead position:", curTime); } } super.sendNotification(notificationName, body, type); //For external Flash/Flex application application listening to the KDP events _app.dispatchEvent(new DynamicEvent(notificationName, body)); //For external Javascript application listening to the KDP events if (externalInterface) externalInterface.notifyJs(notificationName, body); } /** * controls the routing of notifications to our controllers, * we all know them as commands * */ override protected function initializeController():void { super.initializeController(); registerCommand(NotificationType.STARTUP, StartupCommand); // we do both init start KDP life cycle, and start to load the entry simultaneously registerCommand(NotificationType.INITIATE_APP, InitMacroCommand); //There are several things that need to be done as soon as the layout of the kdp is ready. registerCommand(NotificationType.LAYOUT_READY, LayoutReadyCommand ); //when one call change media we fire the load media command again registerCommand(NotificationType.CHANGE_MEDIA, InitChangeMediaMacroCommand); registerCommand (NotificationType.LIVE_ENTRY, LiveStreamCommand ); registerCommand (NotificationType.MEDIA_LOADED, MediaReadyCommand ); registerCommand (NotificationType.PLAYBACK_COMPLETE, PlaybackCompleteCommand); registerCommand(NotificationType.SEQUENCE_ITEM_PLAY_END, SequenceItemPlayEndCommand); registerCommand(NotificationType.SEQUENCE_SKIP_NEXT, SequenceSkipNextCommand); } override protected function initializeView():void { if ( view != null ) return; view = KView.getInstance(); } override protected function initializeFacade():void { initializeView(); initializeModel(); initializeController(); } /** * Help to remove all commands, mediator, proxies from the facade * */ public function dispose() : void { var i:int =0; for(i=0; i<_commandNameArray.length; i++) this.removeCommand( _commandNameArray[i] ); for(i=0; i<_mediatorNameArray.length; i++) this.removeMediator( _mediatorNameArray[i] ); for(i=0; i<_proxyNameArray.length; i++) this.removeProxy( _proxyNameArray[i] ); _commandNameArray = new Array(); _mediatorNameArray = new Array(); _proxyNameArray = new Array(); } /** * after registartion add the notification name to a * @param notificationName * @param commandClassRef * */ override public function registerCommand(notificationName:String, commandClassRef:Class):void { super.registerCommand(notificationName, commandClassRef); //save the notification name so we can delete it later _commandNameArray.push( notificationName ); } override public function registerMediator(mediator:IMediator):void { super.registerMediator(mediator); //save the mediator name so we can delete it later _mediatorNameArray.push( mediator.getMediatorName() ); } override public function registerProxy(proxy:IProxy):void { bindObject[proxy.getProxyName()] = proxy.getData(); super.registerProxy(proxy); //save the proxy name so we can delete it later _proxyNameArray.push( proxy.getProxyName() ); } /** * add notification observer for a given mediator * @param notification the notification to listen for * @param notificationHandler handler to be called * @param mediator * */ public function addNotificationInterest(notification:String, notificationHandler:Function, mediator:IMediator):void { (view as KView).addNotificationInterest(notification, notificationHandler, mediator); } public function get app () : DisplayObject { return _app; } public function set app (disObj : DisplayObject) : void { _app = disObj; } } }
package com.kaltura.kdpfl { import com.kaltura.kdpfl.controller.InitMacroCommand; import com.kaltura.kdpfl.controller.LayoutReadyCommand; import com.kaltura.kdpfl.controller.PlaybackCompleteCommand; import com.kaltura.kdpfl.controller.SequenceItemPlayEndCommand; import com.kaltura.kdpfl.controller.SequenceSkipNextCommand; import com.kaltura.kdpfl.controller.StartupCommand; import com.kaltura.kdpfl.controller.media.InitChangeMediaMacroCommand; import com.kaltura.kdpfl.controller.media.LiveStreamCommand; import com.kaltura.kdpfl.controller.media.MediaReadyCommand; import com.kaltura.kdpfl.events.DynamicEvent; import com.kaltura.kdpfl.model.ExternalInterfaceProxy; import com.kaltura.kdpfl.model.type.DebugLevel; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.view.controls.KTrace; import com.kaltura.kdpfl.view.media.KMediaPlayerMediator; import com.kaltura.puremvc.as3.core.KView; import flash.display.DisplayObject; import mx.utils.ObjectProxy; import org.osmf.media.MediaPlayerState; import org.puremvc.as3.interfaces.IFacade; import org.puremvc.as3.interfaces.IMediator; import org.puremvc.as3.interfaces.IProxy; import org.puremvc.as3.patterns.facade.Facade; public class ApplicationFacade extends Facade implements IFacade { /** * The current version of the KDP. */ public var kdpVersion : String = "v3.9.4"; /** * save any mediator name that is registered to this array in order to delete at any time * (the pure mvc don't support it as built-in function) */ private var _mediatorNameArray : Array = new Array(); /** * save any proxy name that is registered to this array in order to delete at any time * (the pure mvc don't support it as built-in function) */ private var _proxyNameArray : Array = new Array(); /** * save any notification that create a command name that is registered to this array in order to delete at any time * (the pure mvc don't support it as built-in function) */ private var _commandNameArray : Array = new Array(); /** * The bindObject create dynamicly all attributes that need to be binded on it */ public var bindObject:ObjectProxy = new ObjectProxy(); /** * a reference to KDP3 main application */ private var _app : DisplayObject; /** * the url of the kdp */ public var appFolder : String; public var debugMode : Boolean = false; /** * * will affect the traces that will be sent. See DebugLevel enum */ public var debugLevel:int; private var externalInterface : ExternalInterfaceProxy; /** * return the one and only instance of the ApplicationFacade, * if not exist it will be created. * @return * */ public static function getInstance() : ApplicationFacade { if (instance == null) instance = new ApplicationFacade(); return instance as ApplicationFacade; } /** * All this simply does is fire a notification which is routed to * "StartupCommand" via the "registerCommand" handlers * @param app * */ public function start(app:DisplayObject):void { CONFIG::isSDK46 { kdpVersion += ".sdk46"; } _app = app; appFolder = app.root.loaderInfo.url; appFolder = appFolder.substr(0, appFolder.lastIndexOf('/') + 1); sendNotification(NotificationType.STARTUP, app); externalInterface = retrieveProxy(ExternalInterfaceProxy.NAME) as ExternalInterfaceProxy; } /** * Created to trace all notifications for debug * @param notificationName * @param body * @param type * */ override public function sendNotification(notificationName:String, body:Object = null, type:String = null):void { if (debugMode) { var s:String; if ((notificationName == NotificationType.BYTES_DOWNLOADED_CHANGE && debugLevel == DebugLevel.HIGH) || (notificationName == NotificationType.PLAYER_UPDATE_PLAYHEAD && (debugLevel == DebugLevel.HIGH || debugLevel == DebugLevel.MEDIUM)) || (notificationName != NotificationType.PLAYER_UPDATE_PLAYHEAD && notificationName != NotificationType.BYTES_DOWNLOADED_CHANGE)) { if (notificationName == NotificationType.PLAYER_STATE_CHANGE) s = 'Sent ' + notificationName + ' ==> ' + body.toString(); else { s = 'Sent ' + notificationName; if (body) { var found:Boolean = false; for (var o:* in body) { s += ", " + o + ":" + body[o]; found = true; } if (!found) { s += ", " + body.toString(); } } } } if (s && s != "null") { var curTime:Number = 0; var kmediaPlayerMediator:KMediaPlayerMediator = retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator; if (kmediaPlayerMediator && kmediaPlayerMediator.player && kmediaPlayerMediator.player.state!=MediaPlayerState.LOADING && kmediaPlayerMediator.player.state!=MediaPlayerState.UNINITIALIZED && kmediaPlayerMediator.player.state!=MediaPlayerState.PLAYBACK_ERROR) { curTime = kmediaPlayerMediator.getCurrentTime(); } var date:Date = new Date(); KTrace.getInstance().log(date.toTimeString(), ":", s, ", playhead position:", curTime); } } super.sendNotification(notificationName, body, type); //For external Flash/Flex application application listening to the KDP events _app.dispatchEvent(new DynamicEvent(notificationName, body)); //For external Javascript application listening to the KDP events if (externalInterface) externalInterface.notifyJs(notificationName, body); } /** * controls the routing of notifications to our controllers, * we all know them as commands * */ override protected function initializeController():void { super.initializeController(); registerCommand(NotificationType.STARTUP, StartupCommand); // we do both init start KDP life cycle, and start to load the entry simultaneously registerCommand(NotificationType.INITIATE_APP, InitMacroCommand); //There are several things that need to be done as soon as the layout of the kdp is ready. registerCommand(NotificationType.LAYOUT_READY, LayoutReadyCommand ); //when one call change media we fire the load media command again registerCommand(NotificationType.CHANGE_MEDIA, InitChangeMediaMacroCommand); registerCommand (NotificationType.LIVE_ENTRY, LiveStreamCommand ); registerCommand (NotificationType.MEDIA_LOADED, MediaReadyCommand ); registerCommand (NotificationType.PLAYBACK_COMPLETE, PlaybackCompleteCommand); registerCommand(NotificationType.SEQUENCE_ITEM_PLAY_END, SequenceItemPlayEndCommand); registerCommand(NotificationType.SEQUENCE_SKIP_NEXT, SequenceSkipNextCommand); } override protected function initializeView():void { if ( view != null ) return; view = KView.getInstance(); } override protected function initializeFacade():void { initializeView(); initializeModel(); initializeController(); } /** * Help to remove all commands, mediator, proxies from the facade * */ public function dispose() : void { var i:int =0; for(i=0; i<_commandNameArray.length; i++) this.removeCommand( _commandNameArray[i] ); for(i=0; i<_mediatorNameArray.length; i++) this.removeMediator( _mediatorNameArray[i] ); for(i=0; i<_proxyNameArray.length; i++) this.removeProxy( _proxyNameArray[i] ); _commandNameArray = new Array(); _mediatorNameArray = new Array(); _proxyNameArray = new Array(); } /** * after registartion add the notification name to a * @param notificationName * @param commandClassRef * */ override public function registerCommand(notificationName:String, commandClassRef:Class):void { super.registerCommand(notificationName, commandClassRef); //save the notification name so we can delete it later _commandNameArray.push( notificationName ); } override public function registerMediator(mediator:IMediator):void { super.registerMediator(mediator); //save the mediator name so we can delete it later _mediatorNameArray.push( mediator.getMediatorName() ); } override public function registerProxy(proxy:IProxy):void { bindObject[proxy.getProxyName()] = proxy.getData(); super.registerProxy(proxy); //save the proxy name so we can delete it later _proxyNameArray.push( proxy.getProxyName() ); } /** * add notification observer for a given mediator * @param notification the notification to listen for * @param notificationHandler handler to be called * @param mediator * */ public function addNotificationInterest(notification:String, notificationHandler:Function, mediator:IMediator):void { (view as KView).addNotificationInterest(notification, notificationHandler, mediator); } public function get app () : DisplayObject { return _app; } public function set app (disObj : DisplayObject) : void { _app = disObj; } } }
update version to 3.9.4
update version to 3.9.4
ActionScript
agpl-3.0
shvyrev/kdp,kaltura/kdp,shvyrev/kdp,kaltura/kdp,shvyrev/kdp,kaltura/kdp
4ba97a19f2b85948838df7b918afe3ddd8f3fcdb
examples/LanguageTests/src/LanguageTests.as
examples/LanguageTests/src/LanguageTests.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package { import flash.display.Sprite; import classes.B; import interfaces.IA; import interfaces.IB; import interfaces.IC; import interfaces.ID; import interfaces.IE; import interfaces.IF; public class LanguageTests extends Sprite implements IA, IE { public function LanguageTests() { var testResult:Boolean; var testObject:Object; var b:B = new B(); testResult = this instanceof Sprite; trace('this instanceof Sprite - true: ' + testResult.toString()); testResult = this instanceof B; trace('this instanceof classes.B - false: ' + testResult.toString()); testResult = b instanceof classes.B; trace('b instanceof classes.B - true: ' + testResult.toString()); testResult = b instanceof classes.C; trace('b instanceof classes.C - true: ' + testResult.toString()); testResult = b instanceof interfaces.IC; trace('b instanceof interfaces.IC - false: ' + testResult.toString()); testResult = b instanceof interfaces.IF; trace('b instanceof interfaces.IF - false: ' + testResult.toString()); testResult = this instanceof IA; trace('this instanceof interfaces.IA - false: ' + testResult.toString()); testResult = this instanceof IB; trace('this instanceof interfaces.IB - false: ' + testResult.toString()); testResult = this instanceof IC; trace('this instanceof interfaces.IC - false: ' + testResult.toString()); testResult = this instanceof ID; trace('this instanceof interfaces.ID - false: ' + testResult.toString()); testResult = this instanceof IE; trace('this instanceof interfaces.IE - false: ' + testResult.toString()); trace(); testResult = this is Sprite; trace('this is Sprite - true: ' + testResult.toString()); testResult = this is B; trace('this is classes.B - false: ' + testResult.toString()); testResult = b is classes.B; trace('b is classes.B - true: ' + testResult.toString()); testResult = b is classes.C; trace('b is classes.C - true: ' + testResult.toString()); testResult = b is interfaces.IC; trace('b is interfaces.IC - false: ' + testResult.toString()); testResult = b is interfaces.IF; trace('b is interfaces.IF - true: ' + testResult.toString()); testResult = this is IA; trace('this is interfaces.IA - true: ' + testResult.toString()); testResult = this is IB; trace('this is interfaces.IB - false: ' + testResult.toString()); testResult = this is IC; trace('this is interfaces.IC - true: ' + testResult.toString()); testResult = this is ID; trace('this is interfaces.ID - true: ' + testResult.toString()); testResult = this is IE; trace('this is interfaces.IE - true: ' + testResult.toString()); trace(); testObject = (this as Sprite) ? this as Sprite : 'null'; trace('this as Sprite - [object ...]: ' + testObject.toString()); testObject = (this as B) ? this as B : 'null'; trace('this as classes.B - null: ' + testObject.toString()); testObject = (b as classes.B) ? b as classes.B : 'null'; trace('b as classes.B - [object ...]: ' + testObject.toString()); testObject = (b as classes.C) ? b as classes.C : 'null'; trace('b as classes.C - [object ...]: ' + testObject.toString()); testObject = (b as interfaces.IC) ? b as interfaces.IC : 'null'; trace('b as interfaces.IC - null: ' + testObject.toString()); testObject = (b as interfaces.IF) ? b as interfaces.IF : 'null'; trace('b as interfaces.IF - [object ...]: ' + testObject.toString()); testObject = (this as IA) ? this as IA : 'null'; trace('this as interfaces.IA - [object ...]: ' + testObject.toString()); testObject = (this as IB) ? this as IB : 'null'; trace('this as interfaces.IB - null: ' + testObject.toString()); testObject = (this as IC) ? this as IC : 'null'; trace('this as interfaces.IC - [object ...]: ' + testObject.toString()); testObject = (this as ID) ? this as ID : 'null'; trace('this as interfaces.ID - [object ...]: ' + testObject.toString()); testObject = (this as IE) ? this as IE : 'null'; trace('this as interfaces.IE - [object ...]: ' + testObject.toString()); trace(); try { testObject = Sprite(this); trace('Sprite(this) - [object ...]: ' + testObject.toString()); } catch (e:Error) { trace("This shouldn't show!"); } try { testObject = B(this); trace("This shouldn't show!"); } catch (e:Error) { trace('B(this) - exception expected: ' + e.message); } try { testObject = interfaces.IC(b); trace("This shouldn't show!"); } catch (e:Error) { trace('IC(b) - exception expected: ' + e.message); } try { testObject = interfaces.IF(b); trace('IF(b) - [object ...]: ' + testObject.toString()); } catch (e:Error) { trace("This shouldn't show!"); } } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package { import org.apache.flex.core.SimpleApplication; import org.apache.flex.events.Event; import classes.B; import interfaces.IA; import interfaces.IB; import interfaces.IC; import interfaces.ID; import interfaces.IE; import interfaces.IF; public class LanguageTests extends SimpleApplication implements IA, IE { public function LanguageTests() { var testResult:Boolean; var testObject:Object; var b:B = new B(); testResult = this instanceof SimpleApplication; trace('this instanceof SimpleApplication - true: ' + testResult.toString()); testResult = this instanceof B; trace('this instanceof classes.B - false: ' + testResult.toString()); testResult = b instanceof classes.B; trace('b instanceof classes.B - true: ' + testResult.toString()); testResult = b instanceof classes.C; trace('b instanceof classes.C - true: ' + testResult.toString()); testResult = b instanceof interfaces.IC; trace('b instanceof interfaces.IC - false: ' + testResult.toString()); testResult = b instanceof interfaces.IF; trace('b instanceof interfaces.IF - false: ' + testResult.toString()); testResult = this instanceof IA; trace('this instanceof interfaces.IA - false: ' + testResult.toString()); testResult = this instanceof IB; trace('this instanceof interfaces.IB - false: ' + testResult.toString()); testResult = this instanceof IC; trace('this instanceof interfaces.IC - false: ' + testResult.toString()); testResult = this instanceof ID; trace('this instanceof interfaces.ID - false: ' + testResult.toString()); testResult = this instanceof IE; trace('this instanceof interfaces.IE - false: ' + testResult.toString()); trace(); testResult = this is SimpleApplication; trace('this is SimpleApplication - true: ' + testResult.toString()); testResult = this is B; trace('this is classes.B - false: ' + testResult.toString()); testResult = b is classes.B; trace('b is classes.B - true: ' + testResult.toString()); testResult = b is classes.C; trace('b is classes.C - true: ' + testResult.toString()); testResult = b is interfaces.IC; trace('b is interfaces.IC - false: ' + testResult.toString()); testResult = b is interfaces.IF; trace('b is interfaces.IF - true: ' + testResult.toString()); testResult = this is IA; trace('this is interfaces.IA - true: ' + testResult.toString()); testResult = this is IB; trace('this is interfaces.IB - false: ' + testResult.toString()); testResult = this is IC; trace('this is interfaces.IC - true: ' + testResult.toString()); testResult = this is ID; trace('this is interfaces.ID - true: ' + testResult.toString()); testResult = this is IE; trace('this is interfaces.IE - true: ' + testResult.toString()); trace(); testObject = (this as SimpleApplication) ? this as SimpleApplication : 'null'; trace('this as SimpleApplication - [object ...]: ' + testObject.toString()); testObject = (this as B) ? this as B : 'null'; trace('this as classes.B - null: ' + testObject.toString()); testObject = (b as classes.B) ? b as classes.B : 'null'; trace('b as classes.B - [object ...]: ' + testObject.toString()); testObject = (b as classes.C) ? b as classes.C : 'null'; trace('b as classes.C - [object ...]: ' + testObject.toString()); testObject = (b as interfaces.IC) ? b as interfaces.IC : 'null'; trace('b as interfaces.IC - null: ' + testObject.toString()); testObject = (b as interfaces.IF) ? b as interfaces.IF : 'null'; trace('b as interfaces.IF - [object ...]: ' + testObject.toString()); testObject = (this as IA) ? this as IA : 'null'; trace('this as interfaces.IA - [object ...]: ' + testObject.toString()); testObject = (this as IB) ? this as IB : 'null'; trace('this as interfaces.IB - null: ' + testObject.toString()); testObject = (this as IC) ? this as IC : 'null'; trace('this as interfaces.IC - [object ...]: ' + testObject.toString()); testObject = (this as ID) ? this as ID : 'null'; trace('this as interfaces.ID - [object ...]: ' + testObject.toString()); testObject = (this as IE) ? this as IE : 'null'; trace('this as interfaces.IE - [object ...]: ' + testObject.toString()); trace(); try { testObject = SimpleApplication(this); trace('SimpleApplication(this) - [object ...]: ' + testObject.toString()); } catch (e:Error) { trace("This shouldn't show!"); } try { testObject = B(this); trace("This shouldn't show!"); } catch (e:Error) { trace('B(this) - exception expected: ' + e.message); } try { testObject = interfaces.IC(b); trace("This shouldn't show!"); } catch (e:Error) { trace('IC(b) - exception expected: ' + e.message); } try { testObject = interfaces.IF(b); trace('IF(b) - [object ...]: ' + testObject.toString()); } catch (e:Error) { trace("This shouldn't show!"); } addEventListener("foo", eventHandler); if (hasEventListener("foo")) trace("addEventListener worked"); else trace("This shouldn't show!"); removeEventListener("foo", eventHandler); if (!hasEventListener("foo")) trace("removeEventListener worked"); else trace("This shouldn't show!"); } public function eventHandler(e:Event):void { } } }
switch language tests to use SimpleApp and add event listener tests
switch language tests to use SimpleApp and add event listener tests
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
88287404645bf300425fccef3e976fe9dc4c5cfe
bin/Data/Scripts/Editor/EditorViewPaintSelection.as
bin/Data/Scripts/Editor/EditorViewPaintSelection.as
const int PAINT_STEP_UPDATE = 16; const int PAINT_SELECTION_KEY = KEY_C; bool EditorPaintSelectionShow = false; int EditorPaintSelectionUITimeToUpdate = 0; UIElement@ EditorPaintSelectionUIContainer = null; BorderImage@ paintSelectionImage = null; IntVector2 paintSelectionBrushDefaultSize(96,96); IntVector2 paintSelectionBrushCurrentSize = paintSelectionBrushDefaultSize; IntVector2 paintSelectionBrushMinSize(64,64); IntVector2 paintSelectionBrushMaxSize(512,512); IntVector2 paintSelectionBrushStepSizeChange(16,16); void CreatePaintSelectionContainer() { if (editorScene is null) return; EditorPaintSelectionUIContainer = UIElement(); EditorPaintSelectionUIContainer.position = IntVector2(0,0); EditorPaintSelectionUIContainer.size = IntVector2(graphics.width,graphics.height); EditorPaintSelectionUIContainer.priority = -5; EditorPaintSelectionUIContainer.focusMode = FM_NOTFOCUSABLE; EditorPaintSelectionUIContainer.bringToBack = true; EditorPaintSelectionUIContainer.name ="DebugPaintSelectionContainer"; EditorPaintSelectionUIContainer.temporary = true; ui.root.AddChild(EditorPaintSelectionUIContainer); } void CreatePaintSelectionTool() { paintSelectionImage = BorderImage("Icon"); paintSelectionImage.temporary = true; paintSelectionImage.SetFixedSize(paintSelectionBrushDefaultSize.x,paintSelectionBrushDefaultSize.y); paintSelectionImage.texture = cache.GetResource("Texture2D", "Textures/Editor/SelectionCircle.png"); paintSelectionImage.imageRect = IntRect(0,0,512,512); paintSelectionImage.priority = -5; paintSelectionImage.color = Color(1,1,1); paintSelectionImage.bringToBack = true; paintSelectionImage.enabled = false; paintSelectionImage.selected = false; paintSelectionImage.visible = true; EditorPaintSelectionUIContainer.AddChild(paintSelectionImage); } void UpdatePaintSelection() { PaintSelectionCheckKeyboard(); // Early out if disabled if (!EditorPaintSelectionShow) return; if (editorScene is null || EditorPaintSelectionUITimeToUpdate > time.systemTime) return; EditorPaintSelectionUIContainer = ui.root.GetChild("DebugPaintSelectionContainer"); if (EditorPaintSelectionUIContainer is null) { CreatePaintSelectionContainer(); CreatePaintSelectionTool(); } if (EditorPaintSelectionUIContainer !is null) { // Set visibility for all origins EditorPaintSelectionUIContainer.visible = EditorPaintSelectionShow; if (viewportMode!=VIEWPORT_SINGLE) EditorPaintSelectionUIContainer.visible = false; if (EditorPaintSelectionShow) { IntVector2 mp = input.mousePosition; paintSelectionImage.position = IntVector2(mp.x - (paintSelectionBrushCurrentSize.x * 0.5f), mp.y - (paintSelectionBrushCurrentSize.y * 0.5f)); } } EditorPaintSelectionUITimeToUpdate = time.systemTime + PAINT_STEP_UPDATE; } void PaintSelectionCheckKeyboard() { bool key = input.keyPress[PAINT_SELECTION_KEY]; if (key && ui.focusElement is null) { EditorPaintSelectionShow = !EditorPaintSelectionShow; if (EditorPaintSelectionUIContainer !is null) EditorPaintSelectionUIContainer.visible = EditorPaintSelectionShow; if (EditorPaintSelectionShow) { // When we start paint selection we change editmode to select editMode = EDIT_SELECT; //selectedNodes.Clear(); // and also we show origins for proper origins update ShowOrigins(true); toolBarDirty = true; } } else if (EditorPaintSelectionShow && ui.focusElement is null) { if (editMode != EDIT_SELECT) { EditorPaintSelectionShow = false; EditorPaintSelectionUIContainer.visible = false; } } if (input.mouseButtonDown[MOUSEB_RIGHT]) { EditorPaintSelectionShow = false; if (EditorPaintSelectionUIContainer !is null) EditorPaintSelectionUIContainer.visible = false; } } void SelectOriginsByPaintSelection(IntVector2 curPos, float brushRadius, bool isOperationAddToSelection = true) { if (!EditorPaintSelectionShow || EditorPaintSelectionUIContainer is null) return; for (int i=0; i < originsNodes.length; i++) { Vector3 v1(originsIcons[i].position.x, originsIcons[i].position.y, 0); Vector3 v2(curPos.x - ORIGINOFFSETICON.x, curPos.y - ORIGINOFFSETICON.y, 0); float distance = (v1 - v2).length; bool isThisOriginInCircle = distance < brushRadius ? true : false; int nodeID = originsIcons[i].vars[ORIGIN_NODEID_VAR].GetInt(); if (isThisOriginInCircle) { WeakHandle handle = editorScene.GetNode(nodeID); if (handle.Get() !is null) { Node@ node = handle.Get(); if (isOperationAddToSelection) { if (node !is null && isThisNodeOneOfSelected(node) == false) SelectNode(node, true); } else // Deselect origins operation { if (node !is null && isThisNodeOneOfSelected(node) == true) DeselectNode(node); } } } } } void HandlePaintSelectionMouseMove(StringHash eventType, VariantMap& eventData) { if (!EditorPaintSelectionShow || EditorPaintSelectionUIContainer is null) return; int x = eventData["X"].GetInt(); int y = eventData["Y"].GetInt(); float r = (paintSelectionBrushCurrentSize.x * 0.5); IntVector2 mousePos(x,y); // Select by mouse if (input.mouseButtonDown[MOUSEB_LEFT] && input.qualifierDown[QUAL_ALT] != true) { SelectOriginsByPaintSelection(mousePos, r, true); } // Deselect by mouse else if (input.mouseButtonDown[MOUSEB_LEFT] && input.qualifierDown[QUAL_ALT] == true) { SelectOriginsByPaintSelection(mousePos, r, false); } } void HandlePaintSelectionWheel(StringHash eventType, VariantMap& eventData) { if (!EditorPaintSelectionShow || EditorPaintSelectionUIContainer is null) return; int wheelValue = eventData["Wheel"].GetInt(); if (wheelValue != 0) { if (wheelValue > 0) { paintSelectionBrushCurrentSize = paintSelectionBrushCurrentSize - paintSelectionBrushStepSizeChange; paintSelectionBrushCurrentSize = IntVector2(Max(paintSelectionBrushCurrentSize.x, paintSelectionBrushMinSize.x), Max(paintSelectionBrushCurrentSize.y, paintSelectionBrushMinSize.y)); } else if (wheelValue < 0) { paintSelectionBrushCurrentSize = paintSelectionBrushCurrentSize + paintSelectionBrushStepSizeChange; paintSelectionBrushCurrentSize = IntVector2(Min(paintSelectionBrushCurrentSize.x, paintSelectionBrushMaxSize.x), Min(paintSelectionBrushCurrentSize.y, paintSelectionBrushMaxSize.y)); } paintSelectionImage.SetFixedSize(paintSelectionBrushCurrentSize.x, paintSelectionBrushCurrentSize.y); } }
const int PAINT_STEP_UPDATE = 16; const int PAINT_SELECTION_KEY = KEY_C; bool EditorPaintSelectionShow = false; int EditorPaintSelectionUITimeToUpdate = 0; UIElement@ EditorPaintSelectionUIContainer = null; BorderImage@ paintSelectionImage = null; IntVector2 paintSelectionBrushDefaultSize(96,96); IntVector2 paintSelectionBrushCurrentSize = paintSelectionBrushDefaultSize; IntVector2 paintSelectionBrushMinSize(64,64); IntVector2 paintSelectionBrushMaxSize(512,512); IntVector2 paintSelectionBrushStepSizeChange(16,16); void CreatePaintSelectionContainer() { if (editorScene is null) return; EditorPaintSelectionUIContainer = UIElement(); EditorPaintSelectionUIContainer.position = IntVector2(0,0); EditorPaintSelectionUIContainer.size = IntVector2(graphics.width,graphics.height); EditorPaintSelectionUIContainer.priority = -5; EditorPaintSelectionUIContainer.focusMode = FM_NOTFOCUSABLE; EditorPaintSelectionUIContainer.bringToBack = true; EditorPaintSelectionUIContainer.name ="DebugPaintSelectionContainer"; EditorPaintSelectionUIContainer.temporary = true; ui.root.AddChild(EditorPaintSelectionUIContainer); } void CreatePaintSelectionTool() { paintSelectionImage = BorderImage("Icon"); paintSelectionImage.temporary = true; paintSelectionImage.SetFixedSize(paintSelectionBrushDefaultSize.x,paintSelectionBrushDefaultSize.y); paintSelectionImage.texture = cache.GetResource("Texture2D", "Textures/Editor/SelectionCircle.png"); paintSelectionImage.imageRect = IntRect(0,0,512,512); paintSelectionImage.priority = -5; paintSelectionImage.color = Color(1,1,1); paintSelectionImage.bringToBack = true; paintSelectionImage.enabled = false; paintSelectionImage.selected = false; paintSelectionImage.visible = true; EditorPaintSelectionUIContainer.AddChild(paintSelectionImage); } void UpdatePaintSelection() { PaintSelectionCheckKeyboard(); // Early out if disabled if (!EditorPaintSelectionShow) return; if (editorScene is null || EditorPaintSelectionUITimeToUpdate > time.systemTime) return; EditorPaintSelectionUIContainer = ui.root.GetChild("DebugPaintSelectionContainer"); if (EditorPaintSelectionUIContainer is null) { CreatePaintSelectionContainer(); CreatePaintSelectionTool(); } if (EditorPaintSelectionUIContainer !is null) { // Set visibility for all origins EditorPaintSelectionUIContainer.visible = EditorPaintSelectionShow; if (viewportMode!=VIEWPORT_SINGLE) EditorPaintSelectionUIContainer.visible = false; if (EditorPaintSelectionShow) { IntVector2 mp = input.mousePosition; paintSelectionImage.position = IntVector2(mp.x - (paintSelectionBrushCurrentSize.x * 0.5f), mp.y - (paintSelectionBrushCurrentSize.y * 0.5f)); } } EditorPaintSelectionUITimeToUpdate = time.systemTime + PAINT_STEP_UPDATE; } void PaintSelectionCheckKeyboard() { bool key = input.keyPress[PAINT_SELECTION_KEY]; if (key && ui.focusElement is null) { EditorPaintSelectionShow = !EditorPaintSelectionShow; if (EditorPaintSelectionUIContainer !is null) EditorPaintSelectionUIContainer.visible = EditorPaintSelectionShow; if (EditorPaintSelectionShow) { // When we start paint selection we change editmode to select editMode = EDIT_SELECT; //selectedNodes.Clear(); // and also we show origins for proper origins update ShowOrigins(true); toolBarDirty = true; } } else if (EditorPaintSelectionShow && ui.focusElement is null) { if (editMode != EDIT_SELECT) { EditorPaintSelectionShow = false; EditorPaintSelectionUIContainer.visible = false; } } if (input.mouseButtonDown[MOUSEB_RIGHT]) { EditorPaintSelectionShow = false; if (EditorPaintSelectionUIContainer !is null) EditorPaintSelectionUIContainer.visible = false; } } void SelectOriginsByPaintSelection(IntVector2 curPos, float brushRadius, bool isOperationAddToSelection = true) { if (!EditorPaintSelectionShow || EditorPaintSelectionUIContainer is null) return; for (int i=0; i < originsNodes.length; i++) { Vector3 v1(originsIcons[i].position.x, originsIcons[i].position.y, 0); Vector3 v2(curPos.x - ORIGINOFFSETICON.x, curPos.y - ORIGINOFFSETICON.y, 0); float distance = (v1 - v2).length; bool isThisOriginInCircle = distance < brushRadius ? true : false; int nodeID = originsIcons[i].vars[ORIGIN_NODEID_VAR].GetInt(); if (isThisOriginInCircle) { WeakHandle handle = editorScene.GetNode(nodeID); if (handle.Get() !is null) { Node@ node = handle.Get(); if (isOperationAddToSelection) { if (node !is null && isThisNodeOneOfSelected(node) == false) SelectNode(node, true); } else // Deselect origins operation { if (node !is null && isThisNodeOneOfSelected(node) == true) DeselectNode(node); } } } } } void HandlePaintSelectionMouseMove(StringHash eventType, VariantMap& eventData) { if (!EditorPaintSelectionShow || EditorPaintSelectionUIContainer is null) return; int x = eventData["X"].GetInt(); int y = eventData["Y"].GetInt(); float r = (paintSelectionBrushCurrentSize.x * 0.5); IntVector2 mousePos(x,y); // Select by mouse if (input.mouseButtonDown[MOUSEB_LEFT] && input.qualifierDown[QUAL_CTRL] != true) { SelectOriginsByPaintSelection(mousePos, r, true); } // Deselect by mouse else if (input.mouseButtonDown[MOUSEB_LEFT] && input.qualifierDown[QUAL_CTRL] == true) { SelectOriginsByPaintSelection(mousePos, r, false); } } void HandlePaintSelectionWheel(StringHash eventType, VariantMap& eventData) { if (!EditorPaintSelectionShow || EditorPaintSelectionUIContainer is null) return; int wheelValue = eventData["Wheel"].GetInt(); if (wheelValue != 0) { if (wheelValue > 0) { paintSelectionBrushCurrentSize = paintSelectionBrushCurrentSize - paintSelectionBrushStepSizeChange; paintSelectionBrushCurrentSize = IntVector2(Max(paintSelectionBrushCurrentSize.x, paintSelectionBrushMinSize.x), Max(paintSelectionBrushCurrentSize.y, paintSelectionBrushMinSize.y)); } else if (wheelValue < 0) { paintSelectionBrushCurrentSize = paintSelectionBrushCurrentSize + paintSelectionBrushStepSizeChange; paintSelectionBrushCurrentSize = IntVector2(Min(paintSelectionBrushCurrentSize.x, paintSelectionBrushMaxSize.x), Min(paintSelectionBrushCurrentSize.y, paintSelectionBrushMaxSize.y)); } paintSelectionImage.SetFixedSize(paintSelectionBrushCurrentSize.x, paintSelectionBrushCurrentSize.y); } }
Use Ctrl instead Alt for deselecting with PaintSelection
Use Ctrl instead Alt for deselecting with PaintSelection
ActionScript
mit
MonkeyFirst/Urho3D,MeshGeometry/Urho3D,weitjong/Urho3D,iainmerrick/Urho3D,weitjong/Urho3D,weitjong/Urho3D,SirNate0/Urho3D,codemon66/Urho3D,iainmerrick/Urho3D,299299/Urho3D,tommy3/Urho3D,c4augustus/Urho3D,rokups/Urho3D,SuperWangKai/Urho3D,rokups/Urho3D,cosmy1/Urho3D,urho3d/Urho3D,MeshGeometry/Urho3D,urho3d/Urho3D,MeshGeometry/Urho3D,c4augustus/Urho3D,kostik1337/Urho3D,SirNate0/Urho3D,henu/Urho3D,fire/Urho3D-1,victorholt/Urho3D,rokups/Urho3D,PredatorMF/Urho3D,MonkeyFirst/Urho3D,c4augustus/Urho3D,fire/Urho3D-1,cosmy1/Urho3D,iainmerrick/Urho3D,carnalis/Urho3D,tommy3/Urho3D,iainmerrick/Urho3D,SirNate0/Urho3D,fire/Urho3D-1,codedash64/Urho3D,victorholt/Urho3D,urho3d/Urho3D,SuperWangKai/Urho3D,weitjong/Urho3D,xiliu98/Urho3D,299299/Urho3D,bacsmar/Urho3D,xiliu98/Urho3D,victorholt/Urho3D,carnalis/Urho3D,cosmy1/Urho3D,c4augustus/Urho3D,SirNate0/Urho3D,MeshGeometry/Urho3D,eugeneko/Urho3D,c4augustus/Urho3D,MonkeyFirst/Urho3D,codedash64/Urho3D,carnalis/Urho3D,codedash64/Urho3D,kostik1337/Urho3D,codemon66/Urho3D,eugeneko/Urho3D,bacsmar/Urho3D,SuperWangKai/Urho3D,urho3d/Urho3D,codemon66/Urho3D,cosmy1/Urho3D,weitjong/Urho3D,eugeneko/Urho3D,rokups/Urho3D,299299/Urho3D,MonkeyFirst/Urho3D,299299/Urho3D,orefkov/Urho3D,henu/Urho3D,orefkov/Urho3D,victorholt/Urho3D,MeshGeometry/Urho3D,PredatorMF/Urho3D,rokups/Urho3D,bacsmar/Urho3D,SuperWangKai/Urho3D,xiliu98/Urho3D,orefkov/Urho3D,fire/Urho3D-1,carnalis/Urho3D,PredatorMF/Urho3D,bacsmar/Urho3D,kostik1337/Urho3D,codemon66/Urho3D,SirNate0/Urho3D,henu/Urho3D,SuperWangKai/Urho3D,rokups/Urho3D,kostik1337/Urho3D,tommy3/Urho3D,henu/Urho3D,299299/Urho3D,orefkov/Urho3D,PredatorMF/Urho3D,299299/Urho3D,henu/Urho3D,codedash64/Urho3D,codemon66/Urho3D,victorholt/Urho3D,carnalis/Urho3D,tommy3/Urho3D,eugeneko/Urho3D,kostik1337/Urho3D,xiliu98/Urho3D,fire/Urho3D-1,iainmerrick/Urho3D,MonkeyFirst/Urho3D,tommy3/Urho3D,cosmy1/Urho3D,xiliu98/Urho3D,codedash64/Urho3D