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
75f47c24089895b93c31e38169c7db550b9e9f3e
plugins/wvPlugin/src/com/widevine/WvNetConnection.as
plugins/wvPlugin/src/com/widevine/WvNetConnection.as
/** WvNetConnection version 1.1 03/08/2010 Widevine extension to the NetConnection class. Required to stream encrypted content. **/ package com.widevine { import flash.events.*; import flash.external.ExternalInterface; import flash.net.NetConnection; import flash.net.Responder; public class WvNetConnection extends NetConnection { // URL passed in by swf private var myOrigURL:String; // URL used during connect() call. private var myNewURL:String; private var myMovie:String; private var myErrorText:String; private var myIsConnected:Boolean; private var myMediaTime:Number; private var myPlayScale:Number; // bypass Widevine client private var myIsBypassMode:Boolean; // progressive download private var myIsPdl:Boolean; public static const DO_CONNECT_FAILED:String = "doConnectFailed"; public function WvNetConnection():void { this.objectEncoding = flash.net.ObjectEncoding.AMF0; myIsConnected = false; myIsBypassMode = false; myIsPdl = true; myMediaTime = 0; myPlayScale = 1; } /////////////////////////////////////////////////////////////////////////// public override function connect(command:String, ... arguments):void { // handle RTMP streaming, not supported in Widevine yet if (command.substr(0, 4) == "rtmp") { myIsPdl = false; } if (IsBypassMode()) { try { if (IsPdl()) { //trace("(bypass) Handling HTTP stream:" + command); super.connect(null); myNewURL = command; } else { // RTMP streaming //trace("(bypass) Handling RTMP stream:" + command); myNewURL = command.substring(0, command.lastIndexOf("/")+1); super.connect(myNewURL); } } catch (e:Error) { //dispatchEvent(new NetStatusEvent("onNetStatus", obj)); //trace("WvNetStream.connect() error:" + e.message); throw new Error("connect() failed"); } return; } // Widevine encrypted stream only if (IsPdl()) { //trace("(Handling Wv HTTP stream:" + command); } else { command = command.substring(0, command.lastIndexOf("/")+1); //trace("(Handling Wv RTMP stream:" + command); } if (doConnect(command) != 0) { //dispatchEvent(new NetStatusEvent("netStatus", obj)); //throw new Error("doConnect() failed"); dispatchEvent(new Event(DO_CONNECT_FAILED)); } } /////////////////////////////////////////////////////////////////////////// private function doConnect(theURL:String):Number { myOrigURL = theURL; if (myOrigURL == null) { myErrorText = "url passed in connect() is null"; return 1; } try { myMovie = theURL.substr(myOrigURL.lastIndexOf("/")+1); myNewURL = String(ExternalInterface.call("WVGetURL", myOrigURL)); if (myNewURL.toLowerCase().indexOf("error:") != -1) { myErrorText = myNewURL; return 2; } } catch (errObject:Error) { myErrorText = "WVGetURL() failed. " + errObject.message; } try { //trace("Calling super.connect()"); super.connect(myNewURL); } catch (errObject:Error) { myErrorText = "super.connect() failed. " + errObject.message; } myIsConnected = true; return 0; } /////////////////////////////////////////////////////////////////////////// public override function close():void { trace("WvNetConnection.close()"); myIsConnected = false; super.close(); } /////////////////////////////////////////////////////////////////////////// public function getErrorText():String { return myErrorText; } /////////////////////////////////////////////////////////////////////////// public function getNewURL():String { return myNewURL; } /////////////////////////////////////////////////////////////////////////// public function isConnected():Boolean { return myIsConnected; } /////////////////////////////////////////////////////////////////////////// public function setBypassMode(flag:Boolean):void { myIsBypassMode = flag; } /////////////////////////////////////////////////////////////////////////// public function IsBypassMode():Boolean { return myIsBypassMode; } /////////////////////////////////////////////////////////////////////////// public function IsPdl():Boolean { return myIsPdl; } } // class } // package
/** WvNetConnection version 1.1 03/08/2010 Widevine extension to the NetConnection class. Required to stream encrypted content. **/ package com.widevine { import flash.events.*; import flash.external.ExternalInterface; import flash.net.NetConnection; import flash.net.Responder; import flash.utils.setTimeout; public class WvNetConnection extends NetConnection { // URL passed in by swf private var myOrigURL:String; // URL used during connect() call. private var myNewURL:String; private var myMovie:String; private var myErrorText:String; private var myIsConnected:Boolean; private var myMediaTime:Number; private var myPlayScale:Number; // bypass Widevine client private var myIsBypassMode:Boolean; // progressive download private var myIsPdl:Boolean; public static const DO_CONNECT_FAILED:String = "doConnectFailed"; public function WvNetConnection():void { this.objectEncoding = flash.net.ObjectEncoding.AMF0; myIsConnected = false; myIsBypassMode = false; myIsPdl = true; myMediaTime = 0; myPlayScale = 1; } /////////////////////////////////////////////////////////////////////////// public override function connect(command:String, ... arguments):void { // handle RTMP streaming, not supported in Widevine yet if (command.substr(0, 4) == "rtmp") { myIsPdl = false; } if (IsBypassMode()) { try { if (IsPdl()) { //trace("(bypass) Handling HTTP stream:" + command); super.connect(null); myNewURL = command; } else { // RTMP streaming //trace("(bypass) Handling RTMP stream:" + command); myNewURL = command.substring(0, command.lastIndexOf("/")+1); super.connect(myNewURL); } } catch (e:Error) { //dispatchEvent(new NetStatusEvent("onNetStatus", obj)); //trace("WvNetStream.connect() error:" + e.message); throw new Error("connect() failed"); } return; } // Widevine encrypted stream only if (IsPdl()) { //trace("(Handling Wv HTTP stream:" + command); } else { command = command.substring(0, command.lastIndexOf("/")+1); //trace("(Handling Wv RTMP stream:" + command); } if (doConnect(command) != 0) { setTimeout(function():void{ if (doConnect(command) != 0) { //dispatchEvent(new NetStatusEvent("netStatus", obj)); //throw new Error("doConnect() failed"); dispatchEvent(new Event(DO_CONNECT_FAILED)); } },1500); } } /////////////////////////////////////////////////////////////////////////// private function doConnect(theURL:String):Number { myOrigURL = theURL; if (myOrigURL == null) { myErrorText = "url passed in connect() is null"; return 1; } try { myMovie = theURL.substr(myOrigURL.lastIndexOf("/")+1); myNewURL = String(ExternalInterface.call("WVGetURL", myOrigURL)); if (myNewURL.toLowerCase().indexOf("error:") != -1) { myErrorText = myNewURL; return 2; } } catch (errObject:Error) { myErrorText = "WVGetURL() failed. " + errObject.message; } try { //trace("Calling super.connect()"); super.connect(myNewURL); } catch (errObject:Error) { myErrorText = "super.connect() failed. " + errObject.message; } myIsConnected = true; return 0; } /////////////////////////////////////////////////////////////////////////// public override function close():void { trace("WvNetConnection.close()"); myIsConnected = false; super.close(); } /////////////////////////////////////////////////////////////////////////// public function getErrorText():String { return myErrorText; } /////////////////////////////////////////////////////////////////////////// public function getNewURL():String { return myNewURL; } /////////////////////////////////////////////////////////////////////////// public function isConnected():Boolean { return myIsConnected; } /////////////////////////////////////////////////////////////////////////// public function setBypassMode(flag:Boolean):void { myIsBypassMode = flag; } /////////////////////////////////////////////////////////////////////////// public function IsBypassMode():Boolean { return myIsBypassMode; } /////////////////////////////////////////////////////////////////////////// public function IsPdl():Boolean { return myIsPdl; } } // class } // package
fix widevine issue on MAC
fix widevine issue on MAC
ActionScript
agpl-3.0
kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp
0adc9abba02a497d4d345653508e6c44b1a50b17
dolly-framework/src/main/actionscript/dolly/Cloner.as
dolly-framework/src/main/actionscript/dolly/Cloner.as
package dolly { public class Cloner { public function Cloner() { } } }
package dolly { public class Cloner { public static function clone(source:*):* { return null; } } }
Add empty "clone" method to Cloner class.
Add empty "clone" method to Cloner class.
ActionScript
mit
Yarovoy/dolly
7dc50f23d6bd0ae9ae2565184ce5cf96e96d0a42
src/main/as/com/threerings/io/Streamer.as
src/main/as/com/threerings/io/Streamer.as
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2011 Three Rings Design, Inc., All Rights Reserved // http://code.google.com/p/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.io { import flash.utils.ByteArray; import flash.utils.Dictionary; import com.threerings.util.ByteEnum; import com.threerings.util.ClassUtil; import com.threerings.util.Enum; import com.threerings.io.streamers.ArrayStreamer; import com.threerings.io.streamers.ByteArrayStreamer; import com.threerings.io.streamers.ByteEnumStreamer; import com.threerings.io.streamers.EnumStreamer; import com.threerings.io.streamers.MapStreamer; import com.threerings.io.streamers.NumberStreamer; import com.threerings.io.streamers.SetStreamer; import com.threerings.io.streamers.StringStreamer; public class Streamer { public static function getStreamer (obj :Object) :Streamer { var jname :String; if (obj is TypedArray) { jname = TypedArray(obj).getJavaType(); } else { jname = Translations.getToServer(ClassUtil.getClassName(obj)); } return getStreamerByJavaName(jname); } public static function getStreamerByJavaName (jname :String) :Streamer { initStreamers(); // see if we have a streamer for it var streamer :Streamer = _byJName[jname] as Streamer; if (streamer != null) { return streamer; } // see if it's an array that we unstream using an ArrayStreamer if (jname.charAt(0) === "[") { streamer = new ArrayStreamer(jname); } else { // otherwise see if it represents a Streamable // usually this is called from ObjectInputStream, but when it's called from // ObjectOutputStream it's a bit annoying, because we started with a class/object. // But: the code is smaller, so that wins var clazz :Class = ClassUtil.getClassByName(Translations.getFromServer(jname)); if (ClassUtil.isAssignableAs(Enum, clazz)) { streamer = ClassUtil.isAssignableAs(ByteEnum, clazz) ? new ByteEnumStreamer(clazz, jname) : new EnumStreamer(clazz, jname); } else if (ClassUtil.isAssignableAs(Streamable, clazz)) { streamer = new Streamer(clazz, jname); } else { return null; } } // add the good new streamer registerStreamer(streamer); return streamer; } /** This should be a protected constructor. */ public function Streamer (targ :Class, jname :String = null) //throws IOError { _target = targ; _jname = (jname != null) ? jname : Translations.getToServer(ClassUtil.getClassName(targ)); } /** * Return the String to use to identify the class that we're streaming. */ public function getJavaClassName () :String { return _jname; } public function writeObject (obj :Object, out :ObjectOutputStream) :void //throws IOError { (obj as Streamable).writeObject(out); } public function createObject (ins :ObjectInputStream) :Object //throws IOError { // actionscript is so fucked up return new _target(); } public function readObject (obj :Object, ins :ObjectInputStream) :void //throws IOError { (obj as Streamable).readObject(ins); } public function toString () :String { return "[Streamer(" + _jname + ")]"; } protected static function registerStreamer (st :Streamer, ... extraJavaNames) :void { _byJName[st.getJavaClassName()] = st; for each (var name :String in extraJavaNames) { _byJName[name] = st; } } /** * Initialize our streamers. This cannot simply be done statically * because we cannot instantiate a subclass when this class is still * being created. Fucking actionscript. */ private static function initStreamers () :void { if (_byJName != null) { return; } _byJName = new Dictionary(); for each (var c :Class in [ StringStreamer, NumberStreamer, ByteArrayStreamer ]) { registerStreamer(Streamer(new c())); } registerStreamer(ArrayStreamer.INSTANCE, "java.util.List", "java.util.ArrayList", "java.util.Collection"); registerStreamer(SetStreamer.INSTANCE, "java.util.Set"); registerStreamer(MapStreamer.INSTANCE, "java.util.Map"); } protected var _target :Class; protected var _jname :String; protected static var _byJName :Dictionary; } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2011 Three Rings Design, Inc., All Rights Reserved // http://code.google.com/p/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.io { import com.threerings.io.streamers.ArrayStreamer; import com.threerings.io.streamers.ByteArrayStreamer; import com.threerings.io.streamers.ByteEnumStreamer; import com.threerings.io.streamers.EnumStreamer; import com.threerings.io.streamers.MapStreamer; import com.threerings.io.streamers.NumberStreamer; import com.threerings.io.streamers.SetStreamer; import com.threerings.io.streamers.StringStreamer; import com.threerings.util.ByteEnum; import com.threerings.util.ClassUtil; import com.threerings.util.Enum; import com.threerings.util.Log; import flash.utils.ByteArray; import flash.utils.Dictionary; public class Streamer { public static function registerStreamer (st :Streamer, ... extraJavaNames) :void { initStreamers(); extraJavaNames.unshift(st.getJavaClassName()); for each (var name :String in extraJavaNames) { if (name in _byJName) { log.warning("Existing Streamer replaced", "name", name, "cur", _byJName[name], "replacement", st); } _byJName[name] = st; } } public static function getStreamer (obj :Object) :Streamer { var jname :String; if (obj is TypedArray) { jname = TypedArray(obj).getJavaType(); } else { jname = Translations.getToServer(ClassUtil.getClassName(obj)); } return getStreamerByJavaName(jname); } public static function getStreamerByJavaName (jname :String) :Streamer { initStreamers(); // see if we have a streamer for it var streamer :Streamer = _byJName[jname] as Streamer; if (streamer != null) { return streamer; } // see if it's an array that we unstream using an ArrayStreamer if (jname.charAt(0) === "[") { streamer = new ArrayStreamer(jname); } else { // otherwise see if it represents a Streamable // usually this is called from ObjectInputStream, but when it's called from // ObjectOutputStream it's a bit annoying, because we started with a class/object. // But: the code is smaller, so that wins var clazz :Class = ClassUtil.getClassByName(Translations.getFromServer(jname)); if (ClassUtil.isAssignableAs(Enum, clazz)) { streamer = ClassUtil.isAssignableAs(ByteEnum, clazz) ? new ByteEnumStreamer(clazz, jname) : new EnumStreamer(clazz, jname); } else if (ClassUtil.isAssignableAs(Streamable, clazz)) { streamer = new Streamer(clazz, jname); } else { return null; } } // add the good new streamer registerStreamer(streamer); return streamer; } /** This should be a protected constructor. */ public function Streamer (targ :Class, jname :String = null) //throws IOError { _target = targ; _jname = (jname != null) ? jname : Translations.getToServer(ClassUtil.getClassName(targ)); } /** * Return the String to use to identify the class that we're streaming. */ public function getJavaClassName () :String { return _jname; } public function writeObject (obj :Object, out :ObjectOutputStream) :void //throws IOError { (obj as Streamable).writeObject(out); } public function createObject (ins :ObjectInputStream) :Object //throws IOError { // actionscript is so fucked up return new _target(); } public function readObject (obj :Object, ins :ObjectInputStream) :void //throws IOError { (obj as Streamable).readObject(ins); } public function toString () :String { return "[Streamer(" + _jname + ")]"; } /** * Initialize our streamers. This cannot simply be done statically * because we cannot instantiate a subclass when this class is still * being created. Fucking actionscript. */ private static function initStreamers () :void { if (_byJName != null) { return; } _byJName = new Dictionary(); for each (var c :Class in [ StringStreamer, NumberStreamer, ByteArrayStreamer ]) { registerStreamer(Streamer(new c())); } registerStreamer(ArrayStreamer.INSTANCE, "java.util.List", "java.util.ArrayList", "java.util.Collection"); registerStreamer(SetStreamer.INSTANCE, "java.util.Set"); registerStreamer(MapStreamer.INSTANCE, "java.util.Map"); } protected var _target :Class; protected var _jname :String; protected static var _byJName :Dictionary; protected static const log :Log = Log.getLog(Streamer); } }
Make Streamer.registerStreamer public, and add a warning if an existing Streamer is replaced.
Make Streamer.registerStreamer public, and add a warning if an existing Streamer is replaced. (In Who, we need to stream com.threerings.geom.Vector2, so we need a custom Streamer for it) git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@6487 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
f0381024f8a3f740b8b442149bae2946e7869ccb
HLSPlugin/src/com/kaltura/hls/m2ts/M2TSFileHandler.as
HLSPlugin/src/com/kaltura/hls/m2ts/M2TSFileHandler.as
package com.kaltura.hls.m2ts { import com.kaltura.hls.HLSStreamingResource; import com.kaltura.hls.SubtitleTrait; import com.kaltura.hls.manifest.HLSManifestEncryptionKey; import com.kaltura.hls.muxing.AACParser; import com.kaltura.hls.subtitles.SubTitleParser; import com.kaltura.hls.subtitles.TextTrackCue; import com.kaltura.hls.HLSIndexHandler; import flash.utils.ByteArray; import flash.utils.IDataInput; import flash.utils.getTimer; import org.osmf.events.HTTPStreamingEvent; import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase; import org.osmf.net.httpstreaming.flv.FLVTagAudio; /** * Process M2TS data into FLV data and return it for rendering via OSMF video system. */ public class M2TSFileHandler extends HTTPStreamingFileHandlerBase { public var subtitleTrait:SubtitleTrait; public var key:HLSManifestEncryptionKey; public var segmentId:uint = 0; public var resource:HLSStreamingResource; public var segmentUri:String; public var isBestEffort:Boolean = false; private var _parser:TSPacketParser; private var _curTimeOffset:uint; private var _buffer:ByteArray; private var _fragReadBuffer:ByteArray; private var _encryptedDataBuffer:ByteArray; private var _timeOrigin:uint; private var _timeOriginNeeded:Boolean; private var _segmentBeginSeconds:Number; private var _segmentLastSeconds:Number; private var _firstSeekTime:Number; private var _lastContinuityToken:String; private var _extendedIndexHandler:IExtraIndexHandlerState; private var _lastFLVMessageTime:Number; private var _injectingSubtitles:Boolean = false; private var _lastInjectedSubtitleTime:Number = 0; private var _decryptionIV:ByteArray; public function M2TSFileHandler() { super(); _encryptedDataBuffer = new ByteArray(); _parser = new TSPacketParser(); _parser.callback = handleFLVMessage; _timeOrigin = 0; _timeOriginNeeded = true; _segmentBeginSeconds = -1; _segmentLastSeconds = -1; _firstSeekTime = 0; _extendedIndexHandler = null; _lastContinuityToken = null; } public function get duration():Number { if(_segmentLastSeconds > _segmentBeginSeconds) return _segmentLastSeconds - _segmentBeginSeconds; return -1; } public function set extendedIndexHandler(handler:IExtraIndexHandlerState):void { _extendedIndexHandler = handler; } public function get extendedIndexHandler():IExtraIndexHandlerState { return _extendedIndexHandler; } public override function beginProcessFile(seek:Boolean, seekTime:Number):void { // Decryption reset if ( key ) { if ( key.iv ) _decryptionIV = key.retrieveStoredIV(); else _decryptionIV = HLSManifestEncryptionKey.createIVFromID( segmentId ); } var discontinuity:Boolean = false; if(_extendedIndexHandler) { var currentContinuityToken:String = _extendedIndexHandler.getCurrentContinuityToken(); if(_lastContinuityToken != currentContinuityToken) discontinuity = true; _lastContinuityToken = currentContinuityToken; } if(seek) { _parser.clear(); _timeOriginNeeded = true; if(_extendedIndexHandler) _firstSeekTime = _extendedIndexHandler.calculateFileOffsetForTime(seekTime) * 1000.0; } else if(discontinuity) { // Kick the converter state, but try to avoid upsetting the audio stream. _parser.clear(false); if(_segmentLastSeconds >= 0.0) { _timeOriginNeeded = true; if(_extendedIndexHandler) _firstSeekTime = _extendedIndexHandler.getCurrentSegmentOffset() * 1000.0; else _firstSeekTime = _segmentLastSeconds * 1000.0 + 30; } } else if(_extendedIndexHandler && _segmentLastSeconds >= 0.0) { var currentFileOffset:Number = _extendedIndexHandler.getCurrentSegmentOffset(); var delta:Number = currentFileOffset - _segmentLastSeconds; // If it's a big jump, handle it. if(delta > 5.0) { _timeOriginNeeded = true; _firstSeekTime = currentFileOffset * 1000.0; } } _segmentBeginSeconds = -1; _segmentLastSeconds = -1; _lastInjectedSubtitleTime = -1; } public override function get inputBytesNeeded():Number { // We can always survive no bytes. return 0; } public static var tmpBuffer:ByteArray = new ByteArray(); private function basicProcessFileSegment(input:IDataInput, flush:Boolean):ByteArray { if ( key && !key.isLoaded ) { input.readBytes( _encryptedDataBuffer, _encryptedDataBuffer.length ); return null; } tmpBuffer.position = 0; tmpBuffer.length = 0; if ( _encryptedDataBuffer.length > 0 ) { _encryptedDataBuffer.position = 0; _encryptedDataBuffer.readBytes( tmpBuffer ); _encryptedDataBuffer.clear(); } input.readBytes( tmpBuffer, tmpBuffer.length ); if ( key ) { var bytesToRead:uint = tmpBuffer.length; var leftoverBytes:uint = bytesToRead % 16; bytesToRead -= leftoverBytes; key.usePadding = false; if ( leftoverBytes > 0 ) { // Place any bytes left over (not divisible by 16) into our encrypted buffer // to decrypt later, when we have more bytes tmpBuffer.position = bytesToRead; tmpBuffer.readBytes( _encryptedDataBuffer ); tmpBuffer.length = bytesToRead; } else { // Attempt to unpad if our buffer is equally divisible by 16. // It could mean that we've reached the end of the file segment. key.usePadding = true; } // Store our current IV so we can use it do decrypt var currentIV:ByteArray = _decryptionIV; // Set up the IV for our next set of bytes _decryptionIV = new ByteArray(); tmpBuffer.position = bytesToRead - 16; tmpBuffer.readBytes( _decryptionIV ); // Aaaaand...decrypt! key.decrypt( tmpBuffer, currentIV ); } // If it's AAC, process it. if(AACParser.probe(tmpBuffer)) { //trace("GOT AAC " + tmpBuffer.bytesAvailable); var aac:AACParser = new AACParser(); aac.parse(tmpBuffer, _fragReadHandler); //trace(" - returned " + _fragReadBuffer.length + " bytes!"); _fragReadBuffer.position = 0; if(isBestEffort && _fragReadBuffer.length > 0) { trace("Discarding AAC data from best effort."); _fragReadBuffer.length = 0; } return _fragReadBuffer; } var buffer:ByteArray = new ByteArray(); _buffer = buffer; _parser.appendBytes(tmpBuffer); if ( flush ) _parser.flush(); _buffer = null; buffer.position = 0; if(isBestEffort && buffer.length > 0) { trace("Discarding normal data from best effort."); buffer.length = 0; } return buffer; } private function _fragReadHandler(audioTags:Vector.<FLVTagAudio>, adif:ByteArray):void { _fragReadBuffer = new ByteArray(); var audioTag:FLVTagAudio = new FLVTagAudio(); audioTag.soundFormat = FLVTagAudio.SOUND_FORMAT_AAC; audioTag.data = adif; audioTag.isAACSequenceHeader = true; audioTag.write(_fragReadBuffer); for(var i:int=0; i<audioTags.length; i++) audioTags[i].write(_fragReadBuffer); } public override function processFileSegment(input:IDataInput):ByteArray { return basicProcessFileSegment(input, false); } public override function endProcessFile(input:IDataInput):ByteArray { if ( key ) key.usePadding = true; var rv:ByteArray = basicProcessFileSegment(input, false); var elapsed:Number = _segmentLastSeconds - _segmentBeginSeconds; if(elapsed <= 0.0 && _extendedIndexHandler) { elapsed = _extendedIndexHandler.getTargetSegmentDuration(); // XXX fudge hack! } dispatchEvent(new HTTPStreamingEvent(HTTPStreamingEvent.FRAGMENT_DURATION, false, false, elapsed)); return rv; } public override function flushFileSegment(input:IDataInput):ByteArray { return basicProcessFileSegment(input || new ByteArray(), true); } private function handleFLVMessage(timestamp:uint, message:ByteArray):void { var timestampSeconds:Number = timestamp / 1000.0; if(_segmentBeginSeconds < 0) { _segmentBeginSeconds = timestampSeconds; trace("Noting segment start time for " + segmentUri + " of " + timestampSeconds); HLSIndexHandler.startTimeWitnesses[segmentUri] = timestampSeconds; } if(timestampSeconds > _segmentLastSeconds) _segmentLastSeconds = timestampSeconds; if(isBestEffort) return; //trace("Got " + message.length + " bytes at " + timestampSeconds + " seconds"); if(_timeOriginNeeded) { _timeOrigin = timestamp; _timeOriginNeeded = false; } if(timestamp < _timeOrigin) _timeOrigin = timestamp; // Encode the timestamp. message[6] = (timestamp ) & 0xff; message[5] = (timestamp >> 8) & 0xff; message[4] = (timestamp >> 16) & 0xff; message[7] = (timestamp >> 24) & 0xff; var lastMsgTime:Number = _lastFLVMessageTime; _lastFLVMessageTime = timestampSeconds; // If timer was reset due to seek, reset last subtitle time if(timestampSeconds < _lastInjectedSubtitleTime) { trace("Bumping back on subtitle threshold.") _lastInjectedSubtitleTime = timestampSeconds; } // Inject any subtitle tags between messages injectSubtitles( _lastInjectedSubtitleTime + 0.001, timestampSeconds ); //trace( "MESSAGE RECEIVED " + timestampSeconds ); _buffer.writeBytes(message); } protected var _lastCue:TextTrackCue = null; private function injectSubtitles( startTime:Number, endTime:Number ):void { //if(startTime > endTime) trace("***** BAD BEHAVIOR " + startTime + " " + endTime); //trace("Inject subtitles " + startTime + " " + endTime); // Early out if no subtitles, no time has elapsed or we are already injecting subtitles if ( !subtitleTrait || endTime - startTime <= 0 || _injectingSubtitles ) return; var subtitles:Vector.<SubTitleParser> = subtitleTrait.activeSubtitles; if ( !subtitles ) return; _injectingSubtitles = true; var subtitleCount:int = subtitles.length; for ( var i:int = 0; i < subtitleCount; i++ ) { var subtitle:SubTitleParser = subtitles[ i ]; if ( subtitle.startTime > endTime ) break; var cues:Vector.<TextTrackCue> = subtitle.textTrackCues; var cueCount:int = cues.length; var potentials:Vector.<TextTrackCue> = new Vector.<TextTrackCue>(); for ( var j:int = 0; j < cueCount; j++ ) { var cue:TextTrackCue = cues[ j ]; if ( cue.startTime > endTime ) break; else if ( cue.startTime >= startTime ) { potentials.push(cue); } } if(potentials.length > 0) { // TODO: Add support for trackid cue = potentials[potentials.length - 1]; if(cue != _lastCue) { _parser.createAndSendCaptionMessage( cue.startTime, cue.buffer, subtitleTrait.language ); _lastInjectedSubtitleTime = cue.startTime; _lastCue = cue; } } } _injectingSubtitles = false; } } }
package com.kaltura.hls.m2ts { import com.kaltura.hls.HLSStreamingResource; import com.kaltura.hls.SubtitleTrait; import com.kaltura.hls.manifest.HLSManifestEncryptionKey; import com.kaltura.hls.muxing.AACParser; import com.kaltura.hls.subtitles.SubTitleParser; import com.kaltura.hls.subtitles.TextTrackCue; import com.kaltura.hls.HLSIndexHandler; import flash.utils.ByteArray; import flash.utils.IDataInput; import flash.utils.getTimer; import org.osmf.events.HTTPStreamingEvent; import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase; import org.osmf.net.httpstreaming.flv.FLVTagAudio; /** * Process M2TS data into FLV data and return it for rendering via OSMF video system. */ public class M2TSFileHandler extends HTTPStreamingFileHandlerBase { public var subtitleTrait:SubtitleTrait; public var key:HLSManifestEncryptionKey; public var segmentId:uint = 0; public var resource:HLSStreamingResource; public var segmentUri:String; public var isBestEffort:Boolean = false; private var _parser:TSPacketParser; private var _curTimeOffset:uint; private var _buffer:ByteArray; private var _fragReadBuffer:ByteArray; private var _encryptedDataBuffer:ByteArray; private var _timeOrigin:uint; private var _timeOriginNeeded:Boolean; private var _segmentBeginSeconds:Number; private var _segmentLastSeconds:Number; private var _firstSeekTime:Number; private var _lastContinuityToken:String; private var _extendedIndexHandler:IExtraIndexHandlerState; private var _lastFLVMessageTime:Number; private var _injectingSubtitles:Boolean = false; private var _lastInjectedSubtitleTime:Number = 0; private var _decryptionIV:ByteArray; public function M2TSFileHandler() { super(); _encryptedDataBuffer = new ByteArray(); _parser = new TSPacketParser(); _parser.callback = handleFLVMessage; _timeOrigin = 0; _timeOriginNeeded = true; _segmentBeginSeconds = -1; _segmentLastSeconds = -1; _firstSeekTime = 0; _extendedIndexHandler = null; _lastContinuityToken = null; } public function get duration():Number { if(_segmentLastSeconds > _segmentBeginSeconds) return _segmentLastSeconds - _segmentBeginSeconds; return -1; } public function set extendedIndexHandler(handler:IExtraIndexHandlerState):void { _extendedIndexHandler = handler; } public function get extendedIndexHandler():IExtraIndexHandlerState { return _extendedIndexHandler; } public override function beginProcessFile(seek:Boolean, seekTime:Number):void { if(isBestEffort) { trace("Doing extra flush for best effort file handler"); _parser.flush(); _parser.clear(); } // Decryption reset if ( key ) { if ( key.iv ) _decryptionIV = key.retrieveStoredIV(); else _decryptionIV = HLSManifestEncryptionKey.createIVFromID( segmentId ); } var discontinuity:Boolean = false; if(_extendedIndexHandler) { var currentContinuityToken:String = _extendedIndexHandler.getCurrentContinuityToken(); if(_lastContinuityToken != currentContinuityToken) discontinuity = true; _lastContinuityToken = currentContinuityToken; } if(seek) { _parser.clear(); _timeOriginNeeded = true; if(_extendedIndexHandler) _firstSeekTime = _extendedIndexHandler.calculateFileOffsetForTime(seekTime) * 1000.0; } else if(discontinuity) { // Kick the converter state, but try to avoid upsetting the audio stream. _parser.clear(false); if(_segmentLastSeconds >= 0.0) { _timeOriginNeeded = true; if(_extendedIndexHandler) _firstSeekTime = _extendedIndexHandler.getCurrentSegmentOffset() * 1000.0; else _firstSeekTime = _segmentLastSeconds * 1000.0 + 30; } } else if(_extendedIndexHandler && _segmentLastSeconds >= 0.0) { var currentFileOffset:Number = _extendedIndexHandler.getCurrentSegmentOffset(); var delta:Number = currentFileOffset - _segmentLastSeconds; // If it's a big jump, handle it. if(delta > 5.0) { _timeOriginNeeded = true; _firstSeekTime = currentFileOffset * 1000.0; } } _segmentBeginSeconds = -1; _segmentLastSeconds = -1; _lastInjectedSubtitleTime = -1; } public override function get inputBytesNeeded():Number { // We can always survive no bytes. return 0; } public static var tmpBuffer:ByteArray = new ByteArray(); private function basicProcessFileSegment(input:IDataInput, flush:Boolean):ByteArray { if ( key && !key.isLoaded ) { input.readBytes( _encryptedDataBuffer, _encryptedDataBuffer.length ); return null; } tmpBuffer.position = 0; tmpBuffer.length = 0; if ( _encryptedDataBuffer.length > 0 ) { _encryptedDataBuffer.position = 0; _encryptedDataBuffer.readBytes( tmpBuffer ); _encryptedDataBuffer.clear(); } input.readBytes( tmpBuffer, tmpBuffer.length ); if ( key ) { var bytesToRead:uint = tmpBuffer.length; var leftoverBytes:uint = bytesToRead % 16; bytesToRead -= leftoverBytes; key.usePadding = false; if ( leftoverBytes > 0 ) { // Place any bytes left over (not divisible by 16) into our encrypted buffer // to decrypt later, when we have more bytes tmpBuffer.position = bytesToRead; tmpBuffer.readBytes( _encryptedDataBuffer ); tmpBuffer.length = bytesToRead; } else { // Attempt to unpad if our buffer is equally divisible by 16. // It could mean that we've reached the end of the file segment. key.usePadding = true; } // Store our current IV so we can use it do decrypt var currentIV:ByteArray = _decryptionIV; // Set up the IV for our next set of bytes _decryptionIV = new ByteArray(); tmpBuffer.position = bytesToRead - 16; tmpBuffer.readBytes( _decryptionIV ); // Aaaaand...decrypt! key.decrypt( tmpBuffer, currentIV ); } // If it's AAC, process it. if(AACParser.probe(tmpBuffer)) { //trace("GOT AAC " + tmpBuffer.bytesAvailable); var aac:AACParser = new AACParser(); aac.parse(tmpBuffer, _fragReadHandler); //trace(" - returned " + _fragReadBuffer.length + " bytes!"); _fragReadBuffer.position = 0; if(isBestEffort && _fragReadBuffer.length > 0) { trace("Discarding AAC data from best effort."); _fragReadBuffer.length = 0; } return _fragReadBuffer; } var buffer:ByteArray = new ByteArray(); _buffer = buffer; _parser.appendBytes(tmpBuffer); if ( flush ) _parser.flush(); _buffer = null; buffer.position = 0; if(isBestEffort && buffer.length > 0) { trace("Discarding normal data from best effort."); buffer.length = 0; } return buffer; } private function _fragReadHandler(audioTags:Vector.<FLVTagAudio>, adif:ByteArray):void { _fragReadBuffer = new ByteArray(); var audioTag:FLVTagAudio = new FLVTagAudio(); audioTag.soundFormat = FLVTagAudio.SOUND_FORMAT_AAC; audioTag.data = adif; audioTag.isAACSequenceHeader = true; audioTag.write(_fragReadBuffer); for(var i:int=0; i<audioTags.length; i++) audioTags[i].write(_fragReadBuffer); } public override function processFileSegment(input:IDataInput):ByteArray { return basicProcessFileSegment(input, false); } public override function endProcessFile(input:IDataInput):ByteArray { if ( key ) key.usePadding = true; var rv:ByteArray = basicProcessFileSegment(input, false); var elapsed:Number = _segmentLastSeconds - _segmentBeginSeconds; if(elapsed <= 0.0 && _extendedIndexHandler) { elapsed = _extendedIndexHandler.getTargetSegmentDuration(); // XXX fudge hack! } dispatchEvent(new HTTPStreamingEvent(HTTPStreamingEvent.FRAGMENT_DURATION, false, false, elapsed)); return rv; } public override function flushFileSegment(input:IDataInput):ByteArray { return basicProcessFileSegment(input || new ByteArray(), true); } private function handleFLVMessage(timestamp:uint, message:ByteArray):void { var timestampSeconds:Number = timestamp / 1000.0; if(_segmentBeginSeconds < 0) { _segmentBeginSeconds = timestampSeconds; trace("Noting segment start time for " + segmentUri + " of " + timestampSeconds); HLSIndexHandler.startTimeWitnesses[segmentUri] = timestampSeconds; } if(timestampSeconds > _segmentLastSeconds) _segmentLastSeconds = timestampSeconds; if(isBestEffort) return; //trace("Got " + message.length + " bytes at " + timestampSeconds + " seconds"); if(_timeOriginNeeded) { _timeOrigin = timestamp; _timeOriginNeeded = false; } if(timestamp < _timeOrigin) _timeOrigin = timestamp; // Encode the timestamp. message[6] = (timestamp ) & 0xff; message[5] = (timestamp >> 8) & 0xff; message[4] = (timestamp >> 16) & 0xff; message[7] = (timestamp >> 24) & 0xff; var lastMsgTime:Number = _lastFLVMessageTime; _lastFLVMessageTime = timestampSeconds; // If timer was reset due to seek, reset last subtitle time if(timestampSeconds < _lastInjectedSubtitleTime) { trace("Bumping back on subtitle threshold.") _lastInjectedSubtitleTime = timestampSeconds; } // Inject any subtitle tags between messages injectSubtitles( _lastInjectedSubtitleTime + 0.001, timestampSeconds ); //trace( "MESSAGE RECEIVED " + timestampSeconds ); _buffer.writeBytes(message); } protected var _lastCue:TextTrackCue = null; private function injectSubtitles( startTime:Number, endTime:Number ):void { //if(startTime > endTime) trace("***** BAD BEHAVIOR " + startTime + " " + endTime); //trace("Inject subtitles " + startTime + " " + endTime); // Early out if no subtitles, no time has elapsed or we are already injecting subtitles if ( !subtitleTrait || endTime - startTime <= 0 || _injectingSubtitles ) return; var subtitles:Vector.<SubTitleParser> = subtitleTrait.activeSubtitles; if ( !subtitles ) return; _injectingSubtitles = true; var subtitleCount:int = subtitles.length; for ( var i:int = 0; i < subtitleCount; i++ ) { var subtitle:SubTitleParser = subtitles[ i ]; if ( subtitle.startTime > endTime ) break; var cues:Vector.<TextTrackCue> = subtitle.textTrackCues; var cueCount:int = cues.length; var potentials:Vector.<TextTrackCue> = new Vector.<TextTrackCue>(); for ( var j:int = 0; j < cueCount; j++ ) { var cue:TextTrackCue = cues[ j ]; if ( cue.startTime > endTime ) break; else if ( cue.startTime >= startTime ) { potentials.push(cue); } } if(potentials.length > 0) { // TODO: Add support for trackid cue = potentials[potentials.length - 1]; if(cue != _lastCue) { _parser.createAndSendCaptionMessage( cue.startTime, cue.buffer, subtitleTrait.language ); _lastInjectedSubtitleTime = cue.startTime; _lastCue = cue; } } } _injectingSubtitles = false; } } }
Address issue where failing to flush could result in inaccurate best effort results.
Address issue where failing to flush could result in inaccurate best effort results.
ActionScript
agpl-3.0
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
d0c32da40dc2f494618f6d7e98e3b0aecd998c7f
Arguments/src/Controller/TextController.as
Arguments/src/Controller/TextController.as
package Controller { import components.DynamicTextArea; public class TextController { private static var instance:TextController; public function TextController(singletonEnforcer:SingletonEnforcer) { //Event Listeners } public static function getInstance() :TextController{ if(instance == null){ instance = new TextController(new SingletonEnforcer); } return instance; } //---------------- Text Changed ------------------// public function updateModelText(dta:DynamicTextArea):void{ dta.model.text = dta.text; } } } class SingletonEnforcer{}
package Controller { import components.DynamicTextArea; public class TextController { private static var instance:TextController; public function TextController(singletonEnforcer:SingletonEnforcer) { //Event Listeners } public static function getInstance() :TextController{ if(instance == null){ instance = new TextController(new SingletonEnforcer); } return instance; } //---------------- Text Changed ------------------// public function updateModelText(dta:DynamicTextArea):void{ dta.model.text = dta.text; } public function escapeText(s:String):String{ s.replace(/&/g, "&amp"); s.replace(/\"/g, "&quot"); //s.replace(/'/g, "&apos;"); //This does not appear to be necessary s.replace(/</g, "&lt;"); s.replace(/>/g, "&gt;"); s.replace(/&/, "%26"); return s; } } } class SingletonEnforcer{}
Add escapeText to TextController. This should handle client-side text escaping.
Add escapeText to TextController. This should handle client-side text escaping.
ActionScript
agpl-3.0
mbjornas3/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA
9cccceda7beccbae14957d1ffc4f702ce3f80136
src/aerys/minko/render/shader/DynamicShader.as
src/aerys/minko/render/shader/DynamicShader.as
package aerys.minko.render.shader { import aerys.minko.ns.minko; import aerys.minko.render.ressource.TextureRessource; import aerys.minko.render.shader.compiler.DebugCompiler; import aerys.minko.render.shader.compiler.allocator.ParameterAllocation; import aerys.minko.render.shader.node.INode; import aerys.minko.render.shader.node.leaf.AbstractParameter; import aerys.minko.render.shader.node.leaf.StyleParameter; import aerys.minko.render.shader.node.leaf.TransformParameter; import aerys.minko.render.shader.node.leaf.WorldParameter; import aerys.minko.render.renderer.state.RenderState; import aerys.minko.scene.visitor.data.LocalData; import aerys.minko.scene.visitor.data.StyleStack; import aerys.minko.scene.visitor.data.LocalData; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import aerys.minko.type.vertex.format.VertexComponent; import flash.utils.ByteArray; import flash.utils.Dictionary; public class DynamicShader extends Shader { use namespace minko; protected var _vsConstData : Vector.<Number>; protected var _fsConstData : Vector.<Number>; protected var _vsParams : Vector.<ParameterAllocation>; protected var _fsParams : Vector.<ParameterAllocation>; protected var _samplers : Vector.<String>; public static function create(clipspacePosition : INode, color : INode) : DynamicShader { var compiler : DebugCompiler = new DebugCompiler(); compiler.load(clipspacePosition, color); return compiler.compileShader(); } public function DynamicShader(vertexShader : ByteArray, fragmentShader : ByteArray, vertexInput : Vector.<VertexComponent>, vertexShaderConstantData : Vector.<Number>, fragmentShaderConstantData : Vector.<Number>, vertexShaderParameters : Vector.<ParameterAllocation>, fragmentShaderParameters : Vector.<ParameterAllocation>, samplers : Vector.<String>) { _vsConstData = vertexShaderConstantData; _fsConstData = fragmentShaderConstantData; _vsParams = vertexShaderParameters; _fsParams = fragmentShaderParameters; _samplers = samplers; super(vertexShader, fragmentShader, vertexInput); } public function fillRenderState(state : RenderState, style : StyleStack, local : LocalData, world : Dictionary) : Boolean { setTextures(state, style, local, world); setConstants(state, style, local, world); state.shader = this; return true; } protected function setTextures(state : RenderState, styleStack : StyleStack, localData : LocalData, worldData : Object) : void { var texture : TextureRessource = null; var samplerStyleName : String = null; var samplerCount : uint = _samplers.length; for (var i : int = 0; i < samplerCount; ++i) { samplerStyleName = _samplers[i]; texture = styleStack.get(samplerStyleName) as TextureRessource; state.setTextureAt(i, texture); } } protected function setConstants(state : RenderState, styleStack : StyleStack, local : LocalData, world : Dictionary) : void { updateConstData(_vsConstData, _vsParams, styleStack, local, world); updateConstData(_fsConstData, _fsParams, styleStack, local, world); state.setVertexConstants(0, _vsConstData); state.setFragmentConstants(0, _fsConstData); } protected function updateConstData(constData : Vector.<Number>, paramsAllocs : Vector.<ParameterAllocation>, styleStack : StyleStack, local : LocalData, world : Dictionary) : void { var paramLength : int = paramsAllocs.length; for (var i : int = 0; i < paramLength; ++i) { var paramAlloc : ParameterAllocation = paramsAllocs[i]; var param : AbstractParameter = paramAlloc._parameter; var data : Object = getParameterData(param, styleStack, local, world); loadParameterData(paramAlloc, constData, data); } } private function getParameterData(param : AbstractParameter, styleStack : StyleStack, local : LocalData, world : Dictionary) : Object { if (param is StyleParameter) { if (param._index != -1) { return styleStack.get(param._key).getItem(param._index)[param._field]; } else if (param._field != null) { return styleStack.get(param._key)[param._field]; } else { return styleStack.get(param._key, null); } } else if (param is WorldParameter) { var paramClass : Class = WorldParameter(param)._class; if (param._index != -1) { return world[paramClass].getItem(param._index)[param._field]; } else if (param._field != null) { return world[paramClass][param._field]; } else { return world[paramClass]; } } else if (param is TransformParameter) { return local[param._key]; } else throw new Error('Unknown parameter type'); } private function loadParameterData(paramAlloc : ParameterAllocation, constData : Vector.<Number>, data : Object) : void { var offset : uint = paramAlloc._offset; var size : uint = paramAlloc._parameter._size; if (data is int || data is uint) { var intData : int = data as int; if (size == 1) { constData[offset] = intData; } else if (size == 2) { constData[offset] = ((intData & 0xFFFF0000) >>> 16) / Number(0xffff); constData[int(offset + 2)] = (intData & 0x0000FFFF) / Number(0xffff); } else if (size == 3) { constData[offset] = ((intData & 0xFF0000) >>> 16) / 255.; constData[int(offset + 1)] = ((intData & 0x00FF00) >>> 8) / 255.; constData[int(offset + 2)] = (intData & 0x0000FF) / 255.; } else if (size == 4) { constData[offset] = ((intData & 0xFF000000) >>> 24) / 255.; constData[int(offset + 1)] = ((intData & 0x00FF0000) >>> 16) / 255.; constData[int(offset + 2)] = ((intData & 0x0000FF00) >>> 8) / 255.; constData[int(offset + 3)] = ((intData & 0x000000FF)) / 255.; } } else if (data is Number) { if (size != 1) throw new Error('Parameter ' + paramAlloc.toString() + ' is ' + 'defined as size=' + size + ' but only a Number was found'); constData[offset] = data as Number; } else if (data is Vector4) { var vectorData : Vector4; vectorData = data as Vector4; constData[offset] = vectorData.x; size >= 2 && (constData[int(offset + 1)] = vectorData.y); size >= 3 && (constData[int(offset + 2)] = vectorData.z); size >= 4 && (constData[int(offset + 3)] = vectorData.w); } else if (data is Matrix4x4) { (data as Matrix4x4).getRawData(constData, offset, true); } else if (data == null) { throw new Error('Parameter ' + paramAlloc.toString() + ' is ' + 'null and required by automatic shader'); } else { throw new Error('Parameter ' + paramAlloc.toString() + ' is ' + 'neither a int, a Number, a Vector4 or a Matrix4x4. Unable to ' + 'map it to a shader constant.'); } } } }
package aerys.minko.render.shader { import aerys.minko.ns.minko; import aerys.minko.render.renderer.state.RenderState; import aerys.minko.render.ressource.TextureRessource; import aerys.minko.render.shader.compiler.DebugCompiler; import aerys.minko.render.shader.compiler.allocator.ParameterAllocation; import aerys.minko.render.shader.node.INode; import aerys.minko.render.shader.node.leaf.AbstractParameter; import aerys.minko.render.shader.node.leaf.StyleParameter; import aerys.minko.render.shader.node.leaf.TransformParameter; import aerys.minko.render.shader.node.leaf.WorldParameter; import aerys.minko.scene.visitor.data.LocalData; import aerys.minko.scene.visitor.data.StyleStack; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import aerys.minko.type.vertex.format.VertexComponent; import flash.utils.ByteArray; import flash.utils.Dictionary; public class DynamicShader extends Shader { use namespace minko; protected var _vsConstData : Vector.<Number>; protected var _fsConstData : Vector.<Number>; protected var _vsParams : Vector.<ParameterAllocation>; protected var _fsParams : Vector.<ParameterAllocation>; protected var _samplers : Vector.<String>; public static function create(clipspacePosition : INode, color : INode) : DynamicShader { var compiler : DebugCompiler = new DebugCompiler(); compiler.load(clipspacePosition, color); return compiler.compileShader(); } public function DynamicShader(vertexShader : ByteArray, fragmentShader : ByteArray, vertexInput : Vector.<VertexComponent>, vertexShaderConstantData : Vector.<Number>, fragmentShaderConstantData : Vector.<Number>, vertexShaderParameters : Vector.<ParameterAllocation>, fragmentShaderParameters : Vector.<ParameterAllocation>, samplers : Vector.<String>) { _vsConstData = vertexShaderConstantData; _fsConstData = fragmentShaderConstantData; _vsParams = vertexShaderParameters; _fsParams = fragmentShaderParameters; _samplers = samplers; super(vertexShader, fragmentShader, vertexInput); } public function fillRenderState(state : RenderState, style : StyleStack, local : LocalData, world : Dictionary) : Boolean { setTextures(state, style, local, world); setConstants(state, style, local, world); state.shader = this; return true; } protected function setTextures(state : RenderState, styleStack : StyleStack, localData : LocalData, worldData : Object) : void { var texture : TextureRessource = null; var samplerStyleName : String = null; var samplerCount : uint = _samplers.length; for (var i : int = 0; i < samplerCount; ++i) { samplerStyleName = _samplers[i]; texture = styleStack.get(samplerStyleName) as TextureRessource; state.setTextureAt(i, texture); } } protected function setConstants(state : RenderState, styleStack : StyleStack, local : LocalData, world : Dictionary) : void { updateConstData(_vsConstData, _vsParams, styleStack, local, world); updateConstData(_fsConstData, _fsParams, styleStack, local, world); state.setVertexConstants(0, _vsConstData); state.setFragmentConstants(0, _fsConstData); } protected function updateConstData(constData : Vector.<Number>, paramsAllocs : Vector.<ParameterAllocation>, styleStack : StyleStack, local : LocalData, world : Dictionary) : void { var paramLength : int = paramsAllocs.length; for (var i : int = 0; i < paramLength; ++i) { var paramAlloc : ParameterAllocation = paramsAllocs[i]; var param : AbstractParameter = paramAlloc._parameter; var data : Object = getParameterData(param, styleStack, local, world); loadParameterData(paramAlloc, constData, data); } } private function getParameterData(param : AbstractParameter, styleStack : StyleStack, local : LocalData, world : Dictionary) : Object { if (param is StyleParameter) { if (param._index != -1) { return styleStack.get(param._key).getItem(param._index)[param._field]; } else if (param._field != null) { return styleStack.get(param._key)[param._field]; } else { return styleStack.get(param._key, null); } } else if (param is WorldParameter) { var paramClass : Class = WorldParameter(param)._class; if (param._index != -1) { return world[paramClass].getItem(param._index)[param._field]; } else if (param._field != null) { return world[paramClass][param._field]; } else { return world[paramClass]; } } else if (param is TransformParameter) { return local[param._key]; } else throw new Error('Unknown parameter type'); } private function loadParameterData(paramAlloc : ParameterAllocation, constData : Vector.<Number>, data : Object) : void { var offset : uint = paramAlloc._offset; var size : uint = paramAlloc._parameter._size; if (data is int) { var intData : int = data as int; if (size == 1) { constData[offset] = intData; } else if (size == 2) { constData[offset] = ((intData & 0xFFFF0000) >>> 16) / Number(0xffff); constData[int(offset + 2)] = (intData & 0x0000FFFF) / Number(0xffff); } else if (size == 3) { constData[offset] = ((intData & 0xFF0000) >>> 16) / 255.; constData[int(offset + 1)] = ((intData & 0x00FF00) >>> 8) / 255.; constData[int(offset + 2)] = (intData & 0x0000FF) / 255.; } else if (size == 4) { constData[offset] = ((intData & 0xFF000000) >>> 24) / 255.; constData[int(offset + 1)] = ((intData & 0x00FF0000) >>> 16) / 255.; constData[int(offset + 2)] = ((intData & 0x0000FF00) >>> 8) / 255.; constData[int(offset + 3)] = ((intData & 0x000000FF)) / 255.; } } else if (data is uint) { var uintData : uint = data as uint; if (size == 1) { constData[offset] = uintData; } else if (size == 2) { constData[offset] = ((uintData & 0xFFFF0000) >>> 16) / Number(0xffff); constData[int(offset + 2)] = (uintData & 0x0000FFFF) / Number(0xffff); } else if (size == 3) { constData[offset] = ((uintData & 0xFF0000) >>> 16) / 255.; constData[int(offset + 1)] = ((uintData & 0x00FF00) >>> 8) / 255.; constData[int(offset + 2)] = (uintData & 0x0000FF) / 255.; } else if (size == 4) { constData[offset] = ((uintData & 0xFF000000) >>> 24) / 255.; constData[int(offset + 1)] = ((uintData & 0x00FF0000) >>> 16) / 255.; constData[int(offset + 2)] = ((uintData & 0x0000FF00) >>> 8) / 255.; constData[int(offset + 3)] = ((uintData & 0x000000FF)) / 255.; } } else if (data is Number) { if (size != 1) throw new Error('Parameter ' + paramAlloc.toString() + ' is ' + 'defined as size=' + size + ' but only a Number was found'); constData[offset] = data as Number; } else if (data is Vector4) { var vectorData : Vector4; vectorData = data as Vector4; constData[offset] = vectorData.x; size >= 2 && (constData[int(offset + 1)] = vectorData.y); size >= 3 && (constData[int(offset + 2)] = vectorData.z); size >= 4 && (constData[int(offset + 3)] = vectorData.w); } else if (data is Matrix4x4) { (data as Matrix4x4).getRawData(constData, offset, true); } else if (data == null) { throw new Error('Parameter ' + paramAlloc.toString() + ' is ' + 'null and required by automatic shader'); } else { throw new Error('Parameter ' + paramAlloc.toString() + ' is ' + 'neither a int, a Number, a Vector4 or a Matrix4x4. Unable to ' + 'map it to a shader constant.'); } } } }
Fix bug when using uints in style to represent RGBA color
Fix bug when using uints in style to represent RGBA color
ActionScript
mit
aerys/minko-as3
9cef26ef6bd916d02c57b35859f08d585bce2716
src/aerys/minko/scene/node/mesh/SkinnedMesh.as
src/aerys/minko/scene/node/mesh/SkinnedMesh.as
package aerys.minko.scene.node.mesh { import aerys.minko.ns.minko_stream; import aerys.minko.scene.action.mesh.MeshAction; import aerys.minko.scene.action.mesh.PopMeshSkinAction; import aerys.minko.scene.action.mesh.PushMeshSkinAction; import aerys.minko.scene.node.AbstractScene; import aerys.minko.scene.node.group.IGroup; import aerys.minko.type.math.Matrix3D; import aerys.minko.type.stream.IVertexStream; import aerys.minko.type.stream.IndexStream; import aerys.minko.type.stream.format.VertexComponent; import aerys.minko.type.stream.format.VertexFormat; use namespace minko_stream; public class SkinnedMesh extends AbstractScene implements IMesh { private var _name : String; private var _mesh : IMesh; private var _skeletonRootName : String; private var _skeletonReference : IGroup; private var _bindShapeMatrix : Matrix3D; private var _jointNames : Vector.<String>; private var _inverseBindMatrices : Vector.<Matrix3D>; private var _maxInfluences : uint; public function set skeletonReference(v : IGroup) : void { _skeletonReference = v; } /** * IMesh implementation */ public function get version() : uint { return _mesh.version; } public function get vertexStream() : IVertexStream { return _mesh.vertexStream; } public function get indexStream() : IndexStream { return _mesh.indexStream; } public function get maxInfluences() : uint { return _maxInfluences; } public function get mesh() : IMesh { return _mesh; } public function get skeletonRootName() : String { return _skeletonRootName; } public function get skeletonReference() : IGroup { return _skeletonReference; } public function get bindShapeMatrix() : Matrix3D { return _bindShapeMatrix; } public function get jointNames() : Vector.<String> { return _jointNames; } public function get inverseBindMatrices() : Vector.<Matrix3D> { return _inverseBindMatrices; } public function SkinnedMesh(mesh : Mesh, skeletonReference : IGroup, skeletonRootName : String, bindShapeMatrix : Matrix3D, jointNames : Vector.<String>, inverseBindMatrices : Vector.<Matrix3D>) { super(); _name = 'SkinnedMesh'; _skeletonReference = skeletonReference; _skeletonRootName = skeletonRootName; _mesh = mesh; _bindShapeMatrix = bindShapeMatrix; _jointNames = jointNames; _inverseBindMatrices = inverseBindMatrices; _maxInfluences = getMaxInfluencesFromVertexFormat(_mesh.vertexStream.format); actions.push(PushMeshSkinAction.pushMeshSkinAction, MeshAction.meshAction, PopMeshSkinAction.popMeshSkinAction); } private function getMaxInfluencesFromVertexFormat(vertexFormat : VertexFormat) : uint { var maxInfluences : uint = VertexComponent.BONES.length; for (var i : uint = 0; i < maxInfluences; ++i) if (!vertexFormat.hasComponent(VertexComponent.BONES[i])) break; return i; } } }
package aerys.minko.scene.node.mesh { import aerys.minko.ns.minko_stream; import aerys.minko.scene.action.mesh.MeshAction; import aerys.minko.scene.action.mesh.PopMeshSkinAction; import aerys.minko.scene.action.mesh.PushMeshSkinAction; import aerys.minko.scene.node.AbstractScene; import aerys.minko.scene.node.group.IGroup; import aerys.minko.type.math.Matrix3D; import aerys.minko.type.stream.IVertexStream; import aerys.minko.type.stream.IndexStream; import aerys.minko.type.stream.format.VertexComponent; import aerys.minko.type.stream.format.VertexFormat; use namespace minko_stream; public class SkinnedMesh extends AbstractScene implements IMesh { private var _name : String; private var _mesh : IMesh; private var _skeletonRootName : String; private var _skeletonReference : IGroup; private var _bindShapeMatrix : Matrix3D; private var _jointNames : Vector.<String>; private var _inverseBindMatrices : Vector.<Matrix3D>; private var _maxInfluences : uint; public function set skeletonReference(v : IGroup) : void { _skeletonReference = v; } /** * IMesh implementation */ public function get version() : uint { return _mesh.version; } public function get vertexStream() : IVertexStream { return _mesh.vertexStream; } public function get indexStream() : IndexStream { return _mesh.indexStream; } public function get maxInfluences() : uint { return _maxInfluences; } public function get mesh() : IMesh { return _mesh; } public function get skeletonRootName() : String { return _skeletonRootName; } public function get skeletonReference() : IGroup { return _skeletonReference; } public function get bindShapeMatrix() : Matrix3D { return _bindShapeMatrix; } public function get jointNames() : Vector.<String> { return _jointNames; } public function get inverseBindMatrices() : Vector.<Matrix3D> { return _inverseBindMatrices; } public function SkinnedMesh(mesh : IMesh, skeletonReference : IGroup, skeletonRootName : String, bindShapeMatrix : Matrix3D, jointNames : Vector.<String>, inverseBindMatrices : Vector.<Matrix3D>) { super(); _name = 'SkinnedMesh'; _skeletonReference = skeletonReference; _skeletonRootName = skeletonRootName; _mesh = mesh; _bindShapeMatrix = bindShapeMatrix; _jointNames = jointNames; _inverseBindMatrices = inverseBindMatrices; _maxInfluences = getMaxInfluencesFromVertexFormat(_mesh.vertexStream.format); actions.push(PushMeshSkinAction.pushMeshSkinAction, MeshAction.meshAction, PopMeshSkinAction.popMeshSkinAction); } private function getMaxInfluencesFromVertexFormat(vertexFormat : VertexFormat) : uint { var maxInfluences : uint = VertexComponent.BONES.length; for (var i : uint = 0; i < maxInfluences; ++i) if (!vertexFormat.hasComponent(VertexComponent.BONES[i])) break; return i; } } }
Change constructor of SkinnedMesh to allow skinning keyframedmesh
Change constructor of SkinnedMesh to allow skinning keyframedmesh
ActionScript
mit
aerys/minko-as3
3a4a4f19ea351a078d8469ff2630ee47038fa7e6
src/org/flintparticles/threeD/particles/Particle3D.as
src/org/flintparticles/threeD/particles/Particle3D.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.threeD.particles { import org.flintparticles.common.particles.Particle; import org.flintparticles.common.particles.ParticleFactory; import org.flintparticles.threeD.geom.Quaternion; import org.flintparticles.threeD.geom.Vector3DUtils; import flash.geom.Vector3D; /** * The Particle3D class extends the Particle class to include state properties * that are relevant to particles in 3D space. */ public class Particle3D extends Particle { /** * The position of the particle (in the renderer's units). */ public var position:Vector3D; /** * The velocity of the particle (in the renderer's units per second). */ public var velocity:Vector3D; /** * The rotation of the particle, represented as a unit quaternion. */ public var rotation:Quaternion; /** * The rate of rotation of the particle, represented as a vector in the direction of * the axis of rotation and whose magnitude indicates the number of rotations per second. */ public var angVelocity:Vector3D; /** * The axis in the particle's own coordinate space that * indicates the direction that the particle is facing. */ public var faceAxis:Vector3D; private var _previousMass:Number; private var _previousRadius:Number; private var _inertia:Number; /** * The moment of inertia of the particle about its center point */ public function get inertia():Number { if( mass != _previousMass || collisionRadius != _previousRadius ) { _inertia = mass * collisionRadius * collisionRadius * 0.4; _previousMass = mass; _previousRadius = collisionRadius; } return _inertia; } /** * The position of the particle in the emitter's x-axis spacial sorted array */ public var sortID:int = -1; /** * Position vector projected into screen space. Used by renderers. */ public var projectedPosition:Vector3D; /** * z depth of particle in renderer's camera space */ public var zDepth:Number = 0; /** * Creates a Particle3D. Alternatively particles can be reused by using an * instance of the Particle3DCreator class to create them. Usually the * emitter will create the particles and the user doesn't need to create * them. */ public function Particle3D() { super(); position = Vector3DUtils.getPoint( 0, 0, 0 ); projectedPosition = Vector3DUtils.getPoint( 0, 0, 0 ); faceAxis = Vector3DUtils.getVector( 1, 0, 0 ); velocity = Vector3DUtils.getVector( 0, 0, 0 ); rotation = new Quaternion( 1, 0, 0, 0 ); angVelocity = Vector3DUtils.getVector( 0, 0, 0 ); } /** * Sets the particles properties to their default values. */ override public function initialize():void { super.initialize(); Vector3DUtils.resetPoint( position, 0, 0, 0 ); Vector3DUtils.resetPoint( projectedPosition, 0, 0, 0 ); Vector3DUtils.resetVector( faceAxis, 1, 0, 0 ); Vector3DUtils.resetVector( velocity, 0, 0, 0 ); rotation.reset( 1, 0, 0, 0 ); Vector3DUtils.resetVector( angVelocity, 0, 0, 0 ); sortID = -1; zDepth = 0; } /** * @inheritDoc */ override public function clone( factory:ParticleFactory = null ):Particle { var p:Particle3D; if( factory ) { p = factory.createParticle() as Particle3D; } else { p = new Particle3D(); } cloneInto( p ); p.position = position.clone(); p.projectedPosition = projectedPosition.clone(); p.faceAxis = faceAxis.clone(); p.velocity = velocity.clone(); p.rotation = rotation.clone(); p.angVelocity = angVelocity.clone(); p.zDepth = zDepth; return p; } } }
/* * 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.threeD.particles { import org.flintparticles.common.particles.Particle; import org.flintparticles.common.particles.ParticleFactory; import org.flintparticles.threeD.geom.Quaternion; import flash.geom.Vector3D; /** * The Particle3D class extends the Particle class to include state properties * that are relevant to particles in 3D space. */ public class Particle3D extends Particle { /** * The position of the particle (in the renderer's units). */ public var position:Vector3D; /** * The velocity of the particle (in the renderer's units per second). */ public var velocity:Vector3D; /** * The rotation of the particle, represented as a unit quaternion. */ public var rotation:Quaternion; /** * The rate of rotation of the particle, represented as a vector in the direction of * the axis of rotation and whose magnitude indicates the number of rotations per second. */ public var angVelocity:Vector3D; /** * The axis in the particle's own coordinate space that * indicates the direction that the particle is facing. */ public var faceAxis:Vector3D; private var _previousMass:Number; private var _previousRadius:Number; private var _inertia:Number; /** * The moment of inertia of the particle about its center point */ public function get inertia():Number { if( mass != _previousMass || collisionRadius != _previousRadius ) { _inertia = mass * collisionRadius * collisionRadius * 0.4; _previousMass = mass; _previousRadius = collisionRadius; } return _inertia; } /** * The position of the particle in the emitter's x-axis spacial sorted array */ public var sortID:int = -1; /** * Position vector projected into screen space. Used by renderers. */ public var projectedPosition:Vector3D; /** * z depth of particle in renderer's camera space */ public var zDepth:Number = 0; /** * Creates a Particle3D. Alternatively particles can be reused by using an * instance of the Particle3DCreator class to create them. Usually the * emitter will create the particles and the user doesn't need to create * them. */ public function Particle3D() { super(); position = new Vector3D( 0, 0, 0, 1 ); projectedPosition = new Vector3D( 0, 0, 0, 1 ); faceAxis = new Vector3D( 1, 0, 0, 0 ); velocity = new Vector3D( 0, 0, 0, 0 ); rotation = new Quaternion( 1, 0, 0, 0 ); angVelocity = new Vector3D( 0, 0, 0, 0 ); } /** * Sets the particles properties to their default values. */ override public function initialize():void { super.initialize(); position.x = 0; position.y = 0; position.z = 0; projectedPosition.x = 0; projectedPosition.y = 0; projectedPosition.z = 0; faceAxis.x = 1; faceAxis.y = 0; faceAxis.z = 0; velocity.x = 0; velocity.y = 0; velocity.z = 0; rotation.w = 1; rotation.x = 0; rotation.y = 0; rotation.z = 0; angVelocity.x = 0; angVelocity.y = 0; angVelocity.z = 0; sortID = -1; zDepth = 0; } /** * @inheritDoc */ override public function clone( factory:ParticleFactory = null ):Particle { var p:Particle3D; if( factory ) { p = factory.createParticle() as Particle3D; } else { p = new Particle3D(); } cloneInto( p ); p.position = position.clone(); p.projectedPosition = projectedPosition.clone(); p.faceAxis = faceAxis.clone(); p.velocity = velocity.clone(); p.rotation = rotation.clone(); p.angVelocity = angVelocity.clone(); p.zDepth = zDepth; return p; } } }
Optimise the initialise method of the particle class
Optimise the initialise method of the particle class
ActionScript
mit
richardlord/Flint
87e9247128065ceca41bd61812af5d288cf0730e
asx/src/asx/string/camelize.as
asx/src/asx/string/camelize.as
package asx.string { import asx.array.map; import flash.display.JointStyle; /** * Converts a String with a word or phrase to a CamelCaseString. * * Words can be separated by spaces, underscores and hyphens. * * @param value String to camelize. * @param lowerCaseFirstWord Indicates if the first word should be lowercase or camel cased. * * @example * <listing version="3.0"> * trace(camelize("I can has camel-cases")); * // ICanHasCamelCases * * trace(camelize("all your camel cases", true)); * // allYourCamelCases * * trace(camelize("all_the_hyphens_are_goners")); * // allTheHyphensAreGoners * </listing> * * @author drewbourne */ public function camelize(value:String, lowerCaseFirstWord:Boolean=false):String { const underscoresHyphensAndWhitespace:RegExp = /[_-\s]+/g; var camelized:String = map( value.split(underscoresHyphensAndWhitespace), capitalize) .join(""); return lowerCaseFirstWord ? camelized.slice(0, 1).toLowerCase() + camelized.slice(1) : camelized; } }
package asx.string { import asx.array.map; /** * Converts a String with a word or phrase to a CamelCaseString. * * Words can be separated by spaces, underscores and hyphens. * * @param value String to camelize. * @param lowerCaseFirstWord Indicates if the first word should be lowercase or camel cased. * * @example * <listing version="3.0"> * trace(camelize("I can has camel-cases")); * // ICanHasCamelCases * * trace(camelize("all your camel cases", true)); * // allYourCamelCases * * trace(camelize("all_the_hyphens_are_goners")); * // allTheHyphensAreGoners * </listing> * * @author drewbourne */ public function camelize(value:String, lowerCaseFirstWord:Boolean=false):String { const underscoresHyphensAndWhitespace:RegExp = /[_-\s]+/g; var camelized:String = map( value.split(underscoresHyphensAndWhitespace), capitalize) .join(""); return lowerCaseFirstWord ? camelized.slice(0, 1).toLowerCase() + camelized.slice(1) : camelized; } }
remove unused import
remove unused import
ActionScript
mit
drewbourne/asx,drewbourne/asx
5570e265c210b44c539707aae7398f75630d5388
com/rtmfpcat/rtmfpcat.as
com/rtmfpcat/rtmfpcat.as
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.events.NetStatusEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; import flash.utils.setTimeout; import rtmfp.RTMFPSocket; import rtmfp.events.RTMFPSocketEvent; import Utils; public class rtmfpcat extends Sprite { /* Nate's facilitator -- also serving a crossdomain policy */ private const DEFAULT_FAC_ADDR:Object = { host: "128.12.179.80", port: 9002 }; private const DEFAULT_TOR_CLIENT_ADDR:Object = { host: "127.0.0.1", port: 3333 }; /* David's bridge (nickname eRYaZuvY02FpExln) that also serves a crossdomain policy. */ private const DEFAULT_TOR_PROXY_ADDR:Object = { host: "69.164.193.231", port: 9001 }; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; private var output_text:TextField; private var s_f:Socket; private var s_r:RTMFPSocket; private var s_t:Socket; private var fac_addr:Object; private var tor_addr:Object; private var proxy_mode:Boolean; public function rtmfpcat() { output_text = new TextField(); output_text.width = 400; output_text.height = 300; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; addChild(output_text); puts("Starting."); this.loaderInfo.addEventListener(Event.COMPLETE, onLoaderInfoComplete); } private function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } private function onLoaderInfoComplete(e:Event):void { var fac_spec:String; var tor_spec:String; puts("Parameters loaded."); proxy_mode = (this.loaderInfo.parameters["proxy"] != null); fac_spec = this.loaderInfo.parameters["facilitator"]; if (!fac_spec) { puts("No \"facilitator\" specification provided...using default."); fac_addr = DEFAULT_FAC_ADDR; } else { puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = Utils.parseAddrSpec(fac_spec); } if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } tor_spec = this.loaderInfo.parameters["tor"]; if (!tor_spec) { puts("No Tor specification provided...using default."); if (proxy_mode) tor_addr = DEFAULT_TOR_PROXY_ADDR; else tor_addr = DEFAULT_TOR_CLIENT_ADDR; } else { puts("Tor spec: \"" + tor_spec + "\"") tor_addr = Utils.parseAddrSpec(tor_spec); } if (!tor_addr) { puts("Error: Tor spec must be in the form \"host:port\"."); return; } establishRTMFPConnection(); } private function establishRTMFPConnection():void { s_r = new RTMFPSocket(); s_r.addEventListener(RTMFPSocketEvent.CONNECT_SUCCESS, function (e:Event):void { puts("Cirrus: connected with id " + s_r.id + "."); establishFacilitatorConnection(); }); s_r.addEventListener(RTMFPSocketEvent.CONNECT_FAIL, function (e:Event):void { puts("Error: failed to connect to Cirrus."); }); s_r.addEventListener(RTMFPSocketEvent.PUBLISH_START, function(e:RTMFPSocketEvent):void { puts("Publishing started."); }); s_r.addEventListener(RTMFPSocketEvent.PEER_CONNECTED, function(e:RTMFPSocketEvent):void { puts("Peer connected."); }); s_r.addEventListener(RTMFPSocketEvent.PEER_DISCONNECTED, function(e:RTMFPSocketEvent):void { puts("Peer disconnected."); }); s_r.addEventListener(RTMFPSocketEvent.PEERING_SUCCESS, function(e:RTMFPSocketEvent):void { puts("Peering success."); establishTorConnection(); }); s_r.addEventListener(RTMFPSocketEvent.PEERING_FAIL, function(e:RTMFPSocketEvent):void { puts("Peering fail."); }); s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_r.readBytes(bytes); puts("RTMFP: read " + bytes.length + " bytes."); s_t.writeBytes(bytes); }); s_r.connect(); } private function establishTorConnection():void { s_t = new Socket(); s_t.addEventListener(Event.CONNECT, function (e:Event):void { puts("Tor: connected to " + tor_addr.host + ":" + tor_addr.port + "."); }); s_t.addEventListener(Event.CLOSE, function (e:Event):void { puts("Tor: closed connection."); }); s_t.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Tor: I/O error: " + e.text + "."); }); s_t.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_t.readBytes(bytes, 0, e.bytesLoaded); puts("Tor: read " + bytes.length + " bytes."); s_r.writeBytes(bytes); }); s_t.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Tor: security error: " + e.text + "."); }); s_t.connect(tor_addr.host, tor_addr.port); } private function establishFacilitatorConnection():void { s_f = new Socket(); s_f.addEventListener(Event.CONNECT, function (e:Event):void { puts("Facilitator: connected to " + fac_addr.host + ":" + fac_addr.port + "."); if (proxy_mode) s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n"); else s_f.writeUTFBytes("POST / HTTP/1.0\r\n\r\nclient=" + s_r.id + "\r\n"); }); s_f.addEventListener(Event.CLOSE, function (e:Event):void { puts("Facilitator: connection closed."); if (proxy_mode) { setTimeout(establishFacilitatorConnection, FACILITATOR_POLL_INTERVAL); } }); s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); }); s_f.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var clientID:String = s_f.readMultiByte(e.bytesLoaded, "utf-8"); puts("Facilitator: got \"" + clientID + "\""); if (clientID != "Registration list empty") { puts("Connecting to " + clientID + "."); s_r.peer = clientID; } }); s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); }); s_f.connect(fac_addr.host, fac_addr.port); } } }
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.events.NetStatusEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; import flash.utils.setTimeout; import rtmfp.RTMFPSocket; import rtmfp.events.RTMFPSocketEvent; import Utils; public class rtmfpcat extends Sprite { /* Nate's facilitator -- also serving a crossdomain policy */ private const DEFAULT_FAC_ADDR:Object = { host: "128.12.179.80", port: 9002 }; private const DEFAULT_TOR_CLIENT_ADDR:Object = { host: "127.0.0.1", port: 3333 }; /* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a crossdomain policy. */ private const DEFAULT_TOR_PROXY_ADDR:Object = { host: "173.255.221.44", port: 9001 }; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; private var output_text:TextField; private var s_f:Socket; private var s_r:RTMFPSocket; private var s_t:Socket; private var fac_addr:Object; private var tor_addr:Object; private var proxy_mode:Boolean; public function rtmfpcat() { output_text = new TextField(); output_text.width = 400; output_text.height = 300; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; addChild(output_text); puts("Starting."); this.loaderInfo.addEventListener(Event.COMPLETE, onLoaderInfoComplete); } private function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } private function onLoaderInfoComplete(e:Event):void { var fac_spec:String; var tor_spec:String; puts("Parameters loaded."); proxy_mode = (this.loaderInfo.parameters["proxy"] != null); fac_spec = this.loaderInfo.parameters["facilitator"]; if (!fac_spec) { puts("No \"facilitator\" specification provided...using default."); fac_addr = DEFAULT_FAC_ADDR; } else { puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = Utils.parseAddrSpec(fac_spec); } if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } tor_spec = this.loaderInfo.parameters["tor"]; if (!tor_spec) { puts("No Tor specification provided...using default."); if (proxy_mode) tor_addr = DEFAULT_TOR_PROXY_ADDR; else tor_addr = DEFAULT_TOR_CLIENT_ADDR; } else { puts("Tor spec: \"" + tor_spec + "\"") tor_addr = Utils.parseAddrSpec(tor_spec); } if (!tor_addr) { puts("Error: Tor spec must be in the form \"host:port\"."); return; } establishRTMFPConnection(); } private function establishRTMFPConnection():void { s_r = new RTMFPSocket(); s_r.addEventListener(RTMFPSocketEvent.CONNECT_SUCCESS, function (e:Event):void { puts("Cirrus: connected with id " + s_r.id + "."); establishFacilitatorConnection(); }); s_r.addEventListener(RTMFPSocketEvent.CONNECT_FAIL, function (e:Event):void { puts("Error: failed to connect to Cirrus."); }); s_r.addEventListener(RTMFPSocketEvent.PUBLISH_START, function(e:RTMFPSocketEvent):void { puts("Publishing started."); }); s_r.addEventListener(RTMFPSocketEvent.PEER_CONNECTED, function(e:RTMFPSocketEvent):void { puts("Peer connected."); }); s_r.addEventListener(RTMFPSocketEvent.PEER_DISCONNECTED, function(e:RTMFPSocketEvent):void { puts("Peer disconnected."); }); s_r.addEventListener(RTMFPSocketEvent.PEERING_SUCCESS, function(e:RTMFPSocketEvent):void { puts("Peering success."); establishTorConnection(); }); s_r.addEventListener(RTMFPSocketEvent.PEERING_FAIL, function(e:RTMFPSocketEvent):void { puts("Peering fail."); }); s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_r.readBytes(bytes); puts("RTMFP: read " + bytes.length + " bytes."); s_t.writeBytes(bytes); }); s_r.connect(); } private function establishTorConnection():void { s_t = new Socket(); s_t.addEventListener(Event.CONNECT, function (e:Event):void { puts("Tor: connected to " + tor_addr.host + ":" + tor_addr.port + "."); }); s_t.addEventListener(Event.CLOSE, function (e:Event):void { puts("Tor: closed connection."); }); s_t.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Tor: I/O error: " + e.text + "."); }); s_t.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_t.readBytes(bytes, 0, e.bytesLoaded); puts("Tor: read " + bytes.length + " bytes."); s_r.writeBytes(bytes); }); s_t.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Tor: security error: " + e.text + "."); }); s_t.connect(tor_addr.host, tor_addr.port); } private function establishFacilitatorConnection():void { s_f = new Socket(); s_f.addEventListener(Event.CONNECT, function (e:Event):void { puts("Facilitator: connected to " + fac_addr.host + ":" + fac_addr.port + "."); if (proxy_mode) s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n"); else s_f.writeUTFBytes("POST / HTTP/1.0\r\n\r\nclient=" + s_r.id + "\r\n"); }); s_f.addEventListener(Event.CLOSE, function (e:Event):void { puts("Facilitator: connection closed."); if (proxy_mode) { setTimeout(establishFacilitatorConnection, FACILITATOR_POLL_INTERVAL); } }); s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); }); s_f.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var clientID:String = s_f.readMultiByte(e.bytesLoaded, "utf-8"); puts("Facilitator: got \"" + clientID + "\""); if (clientID != "Registration list empty") { puts("Connecting to " + clientID + "."); s_r.peer = clientID; } }); s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); }); s_f.connect(fac_addr.host, fac_addr.port); } } }
Switch back to the public relay.
Switch back to the public relay.
ActionScript
mit
arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy
87ce3ca95632a9107ff9a0ad25ae18bb4f4b9e12
src/org/mangui/hls/HLS.as
src/org/mangui/hls/HLS.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.mangui.hls { import flash.display.Stage; import flash.events.Event; import flash.events.EventDispatcher; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.URLLoader; import flash.net.URLStream; import org.mangui.hls.controller.AudioTrackController; import org.mangui.hls.controller.LevelController; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.handler.StatsHandler; import org.mangui.hls.loader.AltAudioLevelLoader; import org.mangui.hls.loader.LevelLoader; import org.mangui.hls.model.AudioTrack; import org.mangui.hls.model.Level; import org.mangui.hls.model.Stats; import org.mangui.hls.playlist.AltAudioTrack; import org.mangui.hls.stream.HLSNetStream; import org.mangui.hls.stream.StreamBuffer; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that manages the streaming process. **/ public class HLS extends EventDispatcher { private var _levelLoader : LevelLoader; private var _altAudioLevelLoader : AltAudioLevelLoader; private var _audioTrackController : AudioTrackController; private var _levelController : LevelController; private var _streamBuffer : StreamBuffer; private var _statsHandler : StatsHandler; /** HLS NetStream **/ private var _hlsNetStream : HLSNetStream; /** HLS URLStream/URLLoader **/ private var _hlsURLStream : Class; private var _hlsURLLoader : Class; private var _client : Object = {}; private var _stage : Stage; /* level handling */ private var _level : int; /* overrided quality_manual_level level */ private var _manual_level : int = -1; /** Create and connect all components. **/ public function HLS() { _levelLoader = new LevelLoader(this); _altAudioLevelLoader = new AltAudioLevelLoader(this); _audioTrackController = new AudioTrackController(this); _levelController = new LevelController(this); _statsHandler = new StatsHandler(this); _streamBuffer = new StreamBuffer(this, _audioTrackController, _levelController); _hlsURLStream = URLStream as Class; _hlsURLLoader = URLLoader as Class; // default loader var connection : NetConnection = new NetConnection(); connection.connect(null); _hlsNetStream = new HLSNetStream(connection, this, _streamBuffer); this.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); }; /** Forward internal errors. **/ override public function dispatchEvent(event : Event) : Boolean { if (event.type == HLSEvent.ERROR) { CONFIG::LOGGING { Log.error((event as HLSEvent).error); } _hlsNetStream.close(); } return super.dispatchEvent(event); }; private function _levelSwitchHandler(event : HLSEvent) : void { _level = event.level; }; public function dispose() : void { this.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); _levelLoader.dispose(); _altAudioLevelLoader.dispose(); _audioTrackController.dispose(); _levelController.dispose(); _hlsNetStream.dispose_(); _statsHandler.dispose(); _streamBuffer.dispose(); _levelLoader = null; _altAudioLevelLoader = null; _audioTrackController = null; _levelController = null; _hlsNetStream = null; _client = null; _stage = null; _hlsNetStream = null; } /** Return index of first quality level referenced in Manifest **/ public function get firstLevel() : int { return _levelController.firstLevel; }; /** Return the quality level used when starting a fresh playback **/ public function get startLevel() : int { return _levelController.startLevel; }; /* set the quality level used when starting a fresh playback */ public function set startLevel(level : int) : void { _levelController.startLevel = level; }; /** Return the quality level used after a seek operation **/ public function get seekLevel() : int { return _levelController.seekLevel; }; /** Return the quality level of the currently played fragment **/ public function get currentLevel() : int { return _hlsNetStream.currentLevel; }; /** Return the quality level of the next played fragment **/ public function get nextLevel() : int { return _streamBuffer.nextLevel; }; /** Return the quality level of last loaded fragment **/ public function get loadLevel() : int { return _level; }; /* instant quality level switch (-1 for automatic level selection) */ public function set currentLevel(level : int) : void { _manual_level = level; _streamBuffer.flushBuffer(); _hlsNetStream.seek(position); }; /* set quality level for next loaded fragment (-1 for automatic level selection) */ public function set nextLevel(level : int) : void { _manual_level = level; _streamBuffer.nextLevel = level; }; /* set quality level for last loaded fragment (-1 for automatic level selection) */ public function set loadLevel(level : int) : void { _manual_level = level; }; /* check if we are in automatic level selection mode */ public function get autoLevel() : Boolean { return (_manual_level == -1); }; /* return manual level */ public function get manualLevel() : int { return _manual_level; }; /** Return the capping/max level value that could be used by automatic level selection algorithm **/ public function get autoLevelCapping() : int { return _levelController.autoLevelCapping; } /** set the capping/max level value that could be used by automatic level selection algorithm **/ public function set autoLevelCapping(newLevel : int) : void { _levelController.autoLevelCapping = newLevel; } /** Return a Vector of quality level **/ public function get levels() : Vector.<Level> { return _levelLoader.levels; }; /** Return the current playback position. **/ public function get position() : Number { return _streamBuffer.position; }; /** Return the current playback state. **/ public function get playbackState() : String { return _hlsNetStream.playbackState; }; /** Return the current seek state. **/ public function get seekState() : String { return _hlsNetStream.seekState; }; /** Return the type of stream (VOD/LIVE). **/ public function get type() : String { return _levelLoader.type; }; /** Load and parse a new HLS URL **/ public function load(url : String) : void { _level = 0; _hlsNetStream.close(); _levelLoader.load(url); }; /** return HLS NetStream **/ public function get stream() : NetStream { return _hlsNetStream; } public function get client() : Object { return _client; } public function set client(value : Object) : void { _client = value; } /** get audio tracks list**/ public function get audioTracks() : Vector.<AudioTrack> { return _audioTrackController.audioTracks; }; /** get alternate audio tracks list from playlist **/ public function get altAudioTracks() : Vector.<AltAudioTrack> { return _levelLoader.altAudioTracks; }; /** get index of the selected audio track (index in audio track lists) **/ public function get audioTrack() : int { return _audioTrackController.audioTrack; }; /** select an audio track, based on its index in audio track lists**/ public function set audioTrack(val : int) : void { _audioTrackController.audioTrack = val; } /* set stage */ public function set stage(stage : Stage) : void { _stage = stage; this.dispatchEvent(new HLSEvent(HLSEvent.STAGE_SET)); } /* get stage */ public function get stage() : Stage { return _stage; } /* set URL stream loader */ public function set URLstream(urlstream : Class) : void { _hlsURLStream = urlstream; } /* retrieve URL stream loader */ public function get URLstream() : Class { return _hlsURLStream; } /* set URL stream loader */ public function set URLloader(urlloader : Class) : void { _hlsURLLoader = urlloader; } /* retrieve URL stream loader */ public function get URLloader() : Class { return _hlsURLLoader; } /* retrieve playback session stats */ public function get stats() : Stats { return _statsHandler.stats; } /* start/restart playlist/fragment loading. this is only effective if MANIFEST_PARSED event has been triggered already */ public function startLoad() : void { if(levels && levels.length) { this.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_SWITCH, startLevel)); } } } }
/* 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.mangui.hls { import flash.display.Stage; import flash.events.Event; import flash.events.EventDispatcher; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.URLLoader; import flash.net.URLStream; import org.mangui.hls.constant.HLSSeekStates; import org.mangui.hls.controller.AudioTrackController; import org.mangui.hls.controller.LevelController; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.handler.StatsHandler; import org.mangui.hls.loader.AltAudioLevelLoader; import org.mangui.hls.loader.LevelLoader; import org.mangui.hls.model.AudioTrack; import org.mangui.hls.model.Level; import org.mangui.hls.model.Stats; import org.mangui.hls.playlist.AltAudioTrack; import org.mangui.hls.stream.HLSNetStream; import org.mangui.hls.stream.StreamBuffer; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that manages the streaming process. **/ public class HLS extends EventDispatcher { private var _levelLoader : LevelLoader; private var _altAudioLevelLoader : AltAudioLevelLoader; private var _audioTrackController : AudioTrackController; private var _levelController : LevelController; private var _streamBuffer : StreamBuffer; private var _statsHandler : StatsHandler; /** HLS NetStream **/ private var _hlsNetStream : HLSNetStream; /** HLS URLStream/URLLoader **/ private var _hlsURLStream : Class; private var _hlsURLLoader : Class; private var _client : Object = {}; private var _stage : Stage; /* level handling */ private var _level : int; /* overrided quality_manual_level level */ private var _manual_level : int = -1; /** Create and connect all components. **/ public function HLS() { _levelLoader = new LevelLoader(this); _altAudioLevelLoader = new AltAudioLevelLoader(this); _audioTrackController = new AudioTrackController(this); _levelController = new LevelController(this); _statsHandler = new StatsHandler(this); _streamBuffer = new StreamBuffer(this, _audioTrackController, _levelController); _hlsURLStream = URLStream as Class; _hlsURLLoader = URLLoader as Class; // default loader var connection : NetConnection = new NetConnection(); connection.connect(null); _hlsNetStream = new HLSNetStream(connection, this, _streamBuffer); this.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); }; /** Forward internal errors. **/ override public function dispatchEvent(event : Event) : Boolean { if (event.type == HLSEvent.ERROR) { CONFIG::LOGGING { Log.error((event as HLSEvent).error); } _hlsNetStream.close(); } return super.dispatchEvent(event); }; private function _levelSwitchHandler(event : HLSEvent) : void { _level = event.level; }; public function dispose() : void { this.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); _levelLoader.dispose(); _altAudioLevelLoader.dispose(); _audioTrackController.dispose(); _levelController.dispose(); _hlsNetStream.dispose_(); _statsHandler.dispose(); _streamBuffer.dispose(); _levelLoader = null; _altAudioLevelLoader = null; _audioTrackController = null; _levelController = null; _hlsNetStream = null; _client = null; _stage = null; _hlsNetStream = null; } /** Return index of first quality level referenced in Manifest **/ public function get firstLevel() : int { return _levelController.firstLevel; }; /** Return the quality level used when starting a fresh playback **/ public function get startLevel() : int { return _levelController.startLevel; }; /* set the quality level used when starting a fresh playback */ public function set startLevel(level : int) : void { _levelController.startLevel = level; }; /** Return the quality level used after a seek operation **/ public function get seekLevel() : int { return _levelController.seekLevel; }; /** Return the quality level of the currently played fragment **/ public function get currentLevel() : int { return _hlsNetStream.currentLevel; }; /** Return the quality level of the next played fragment **/ public function get nextLevel() : int { return _streamBuffer.nextLevel; }; /** Return the quality level of last loaded fragment **/ public function get loadLevel() : int { return _level; }; /* instant quality level switch (-1 for automatic level selection) */ public function set currentLevel(level : int) : void { _manual_level = level; // don't flush and seek if never seeked or if end of stream if(seekState != HLSSeekStates.IDLE) { _streamBuffer.flushBuffer(); _hlsNetStream.seek(position); } }; /* set quality level for next loaded fragment (-1 for automatic level selection) */ public function set nextLevel(level : int) : void { _manual_level = level; _streamBuffer.nextLevel = level; }; /* set quality level for last loaded fragment (-1 for automatic level selection) */ public function set loadLevel(level : int) : void { _manual_level = level; }; /* check if we are in automatic level selection mode */ public function get autoLevel() : Boolean { return (_manual_level == -1); }; /* return manual level */ public function get manualLevel() : int { return _manual_level; }; /** Return the capping/max level value that could be used by automatic level selection algorithm **/ public function get autoLevelCapping() : int { return _levelController.autoLevelCapping; } /** set the capping/max level value that could be used by automatic level selection algorithm **/ public function set autoLevelCapping(newLevel : int) : void { _levelController.autoLevelCapping = newLevel; } /** Return a Vector of quality level **/ public function get levels() : Vector.<Level> { return _levelLoader.levels; }; /** Return the current playback position. **/ public function get position() : Number { return _streamBuffer.position; }; /** Return the current playback state. **/ public function get playbackState() : String { return _hlsNetStream.playbackState; }; /** Return the current seek state. **/ public function get seekState() : String { return _hlsNetStream.seekState; }; /** Return the type of stream (VOD/LIVE). **/ public function get type() : String { return _levelLoader.type; }; /** Load and parse a new HLS URL **/ public function load(url : String) : void { _level = 0; _hlsNetStream.close(); _levelLoader.load(url); }; /** return HLS NetStream **/ public function get stream() : NetStream { return _hlsNetStream; } public function get client() : Object { return _client; } public function set client(value : Object) : void { _client = value; } /** get audio tracks list**/ public function get audioTracks() : Vector.<AudioTrack> { return _audioTrackController.audioTracks; }; /** get alternate audio tracks list from playlist **/ public function get altAudioTracks() : Vector.<AltAudioTrack> { return _levelLoader.altAudioTracks; }; /** get index of the selected audio track (index in audio track lists) **/ public function get audioTrack() : int { return _audioTrackController.audioTrack; }; /** select an audio track, based on its index in audio track lists**/ public function set audioTrack(val : int) : void { _audioTrackController.audioTrack = val; } /* set stage */ public function set stage(stage : Stage) : void { _stage = stage; this.dispatchEvent(new HLSEvent(HLSEvent.STAGE_SET)); } /* get stage */ public function get stage() : Stage { return _stage; } /* set URL stream loader */ public function set URLstream(urlstream : Class) : void { _hlsURLStream = urlstream; } /* retrieve URL stream loader */ public function get URLstream() : Class { return _hlsURLStream; } /* set URL stream loader */ public function set URLloader(urlloader : Class) : void { _hlsURLLoader = urlloader; } /* retrieve URL stream loader */ public function get URLloader() : Class { return _hlsURLLoader; } /* retrieve playback session stats */ public function get stats() : Stats { return _statsHandler.stats; } /* start/restart playlist/fragment loading. this is only effective if MANIFEST_PARSED event has been triggered already */ public function startLoad() : void { if(levels && levels.length) { this.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_SWITCH, startLevel)); } } } }
set currentLevel : don't flush and seek if seeking state is IDLE
set currentLevel : don't flush and seek if seeking state is IDLE
ActionScript
mpl-2.0
vidible/vdb-flashls,tedconf/flashls,hola/flashls,codex-corp/flashls,neilrackett/flashls,neilrackett/flashls,clappr/flashls,codex-corp/flashls,thdtjsdn/flashls,hola/flashls,jlacivita/flashls,NicolasSiver/flashls,vidible/vdb-flashls,jlacivita/flashls,mangui/flashls,loungelogic/flashls,thdtjsdn/flashls,Corey600/flashls,tedconf/flashls,loungelogic/flashls,mangui/flashls,clappr/flashls,NicolasSiver/flashls,fixedmachine/flashls,Corey600/flashls,fixedmachine/flashls
71eb5a0dd2242952c65a76ac64364249a835b05e
src/com/axis/rtspclient/RTSPClient.as
src/com/axis/rtspclient/RTSPClient.as
package com.axis.rtspclient { import flash.events.EventDispatcher; import flash.events.Event; import flash.utils.ByteArray; import flash.net.Socket; import flash.net.NetConnection; import flash.net.NetStream; import flash.media.Video; import mx.utils.StringUtil; import com.axis.rtspclient.FLVMux; import com.axis.rtspclient.RTP; import com.axis.rtspclient.SDP; import com.axis.http.url; import com.axis.http.request; import com.axis.http.auth; import com.axis.IClient; import com.axis.ClientEvent; public class RTSPClient extends EventDispatcher implements IClient { [Embed(source = "../../../../VERSION", mimeType = "application/octet-stream")] private var Version:Class; private var userAgent:String; private static var STATE_INITIAL:uint = 1 << 0; private static var STATE_OPTIONS:uint = 1 << 1; private static var STATE_DESCRIBE:uint = 1 << 2; private static var STATE_SETUP:uint = 1 << 3; private static var STATE_PLAY:uint = 1 << 4; private static var STATE_PLAYING:uint = 1 << 5; private static var STATE_PAUSE:uint = 1 << 6; private static var STATE_PAUSED:uint = 1 << 7; private static var STATE_TEARDOWN:uint = 1 << 8; private var state:int = STATE_INITIAL; private var handle:IRTSPHandle; private var ns:NetStream; private var video:Video; private var sdp:SDP = new SDP(); private var flvmux:FLVMux; private var urlParsed:Object; private var cSeq:uint = 1; private var session:String; private var contentBase:String; private var interleaveChannelIndex:uint = 0; private var methods:Array = []; private var data:ByteArray = new ByteArray(); private var rtpLength:int = -1; private var rtpChannel:int = -1; private var tracks:Array; private var authState:String = "none"; private var authOpts:Object = {}; private var digestNC:uint = 1; public function RTSPClient(video:Video, urlParsed:Object, handle:IRTSPHandle) { this.userAgent = "Slush " + StringUtil.trim(new Version().toString()); this.state = STATE_INITIAL; this.handle = handle; this.video = video; this.urlParsed = urlParsed; handle.addEventListener('data', this.onData); } public function start():Boolean { var self:RTSPClient = this; handle.addEventListener('connected', function():void { if (state !== STATE_INITIAL) { trace('Cannot start unless in initial state.'); return; } /* If the handle closes, take care of it */ handle.addEventListener('closed', self.onClose); if (0 === self.methods.length) { /* We don't know the options yet. Start with that. */ sendOptionsReq(); } else { /* Already queried the options (and perhaps got unauthorized on describe) */ sendDescribeReq(); } }); var nc:NetConnection = new NetConnection(); nc.connect(null); this.ns = new NetStream(nc); dispatchEvent(new ClientEvent(ClientEvent.NETSTREAM_CREATED, { ns : this.ns })); video.attachNetStream(this.ns); handle.connect(); return true; } public function pause():Boolean { if (state !== STATE_PLAYING) { trace('Unable to pause a stream if not playing.'); return false; } try { sendPauseReq(); } catch (err:Error) { trace("Unable to pause: " + err.message); return false; } return true; } public function resume():Boolean { if (state !== STATE_PAUSED) { trace('Unable to resume a stream if not paused.'); return false; } sendPlayReq(); return true; } public function stop():Boolean { if (state < STATE_PLAY) { trace('Unable to stop if we never reached play.'); return false; } sendTeardownReq(); return true; } private function onClose(event:Event):void { if (state === STATE_TEARDOWN) { this.ns.dispose(); dispatchEvent(new ClientEvent(ClientEvent.STOPPED)); } else { trace('RTSPClient: Handle unexpectedly closed.'); } } private function onData(event:Event):void { if (0 < data.bytesAvailable) { /* Determining byte have already been read. This is a continuation */ } else { /* Read the determining byte */ handle.readBytes(data, 0, 1); } switch(data[0]) { case 0x52: /* ascii 'R', start of RTSP */ onRTSPCommand(); break; case 0x24: /* ascii '$', start of interleaved packet */ onInterleavedData(); break; default: trace('Unknown determining byte:', '0x' + data[0].toString(16), '. Stopping stream.'); stop(); break; } } private function requestReset():void { var copy:ByteArray = new ByteArray(); data.readBytes(copy); data.clear(); copy.readBytes(data); rtpLength = -1; rtpChannel = -1; } private function readRequest(oBody:ByteArray):* { var parsed:* = request.readHeaders(handle, data); if (false === parsed) { return false; } 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('GET: Exhausted all authentication methods.'); trace('GET: Unable to authorize to ' + urlParsed.host); return false; } trace('RTSPClient: switching http-authorization from ' + authState + ' to ' + newAuthState); authState = newAuthState; state = STATE_INITIAL; data = new ByteArray(); handle.reconnect(); return false; } if (data.bytesAvailable < parsed.headers['content-length']) { return false; } /* RTSP commands contain no heavy body, so it's safe to read everything */ data.readBytes(oBody, 0, parsed.headers['content-length']); requestReset(); return parsed; } private function onRTSPCommand():void { var parsed:*, body:ByteArray = new ByteArray(); if (false === (parsed = readRequest(body))) { return; } if (200 !== parsed.code) { trace('RTSPClient: Invalid RTSP response - ', parsed.code, parsed.message); return; } switch (state) { case STATE_INITIAL: trace("RTSPClient: STATE_INITIAL"); case STATE_OPTIONS: trace("RTSPClient: STATE_OPTIONS"); this.methods = parsed.headers.public.split(/[ ]*,[ ]*/); sendDescribeReq(); break; case STATE_DESCRIBE: trace("RTSPClient: STATE_DESCRIBE"); if (!sdp.parse(body)) { trace("RTSPClient:Failed to parse SDP file"); return; } if (!parsed.headers['content-base']) { trace('RTSPClient: no content-base in describe reply'); return; } contentBase = parsed.headers['content-base']; tracks = sdp.getMediaBlockList(); trace('SDP contained ' + tracks.length + ' track(s). Calling SETUP for each.'); if (0 === tracks.length) { trace('No tracks in SDP file.'); return; } /* Fall through, it's time for setup */ case STATE_SETUP: trace("RTSPClient: STATE_SETUP"); if (parsed.headers['session']) { session = parsed.headers['session']; } if (0 !== tracks.length) { /* More tracks we must setup before playing */ var block:Object = tracks.shift(); sendSetupReq(block); return; } /* All tracks setup and ready to go! */ sendPlayReq(); break; case STATE_PLAY: trace("RTSPClient: STATE_PLAY"); state = STATE_PLAYING; if (this.flvmux) { /* If the flvmux have been initialized don't do it again. this is probably a resume after pause */ break; } this.flvmux = new FLVMux(this.ns, this.sdp); var analu:ANALU = new ANALU(); var aaac:AAAC = new AAAC(sdp); this.addEventListener("VIDEO_PACKET", analu.onRTPPacket); this.addEventListener("AUDIO_PACKET", aaac.onRTPPacket); analu.addEventListener(NALU.NEW_NALU, flvmux.onNALU); aaac.addEventListener(AACFrame.NEW_FRAME, flvmux.onAACFrame); break; case STATE_PLAYING: trace("RTSPClient: STATE_PLAYING"); break; case STATE_PAUSE: trace("RTSPClient: STATE_PAUSE"); state = STATE_PAUSED; break; case STATE_TEARDOWN: trace('RTSPClient: STATE_TEARDOWN'); this.handle.disconnect(); break; } if (0 < data.bytesAvailable) { onData(null); } } private function onInterleavedData():void { handle.readBytes(data, data.length); if (-1 == rtpLength && 0x24 === data[0]) { /* This is the beginning of a new RTP package */ data.readByte(); rtpChannel = data.readByte(); rtpLength = data.readShort(); } if (data.bytesAvailable < rtpLength) { /* The complete RTP package is not here yet, wait for more data */ return; } var pkgData:ByteArray = new ByteArray(); data.readBytes(pkgData, 0, rtpLength); if (rtpChannel === 0 || rtpChannel === 2) { /* We're discarding the RTCP counter parts for now */ var rtppkt:RTP = new RTP(pkgData, sdp); dispatchEvent(rtppkt); } requestReset(); if (0 < data.bytesAvailable) { onData(null); } } private function supportCommand(command:String):Boolean { return (-1 !== this.methods.indexOf(command)); } private function sendOptionsReq():void { state = STATE_OPTIONS; var req:String = "OPTIONS * RTSP/1.0\r\n" + "CSeq: " + (++cSeq) + "\r\n" + "User-Agent: " + userAgent + "\r\n" + "\r\n"; handle.writeUTFBytes(req); } private function sendDescribeReq():void { state = STATE_DESCRIBE; var u:String = 'rtsp://' + urlParsed.host + ":" + urlParsed.port + urlParsed.urlpath; var req:String = "DESCRIBE " + u + " RTSP/1.0\r\n" + "CSeq: " + (++cSeq) + "\r\n" + "User-Agent: " + userAgent + "\r\n" + "Accept: application/sdp\r\n" + auth.authorizationHeader("DESCRIBE", authState, authOpts, urlParsed, digestNC++) + "\r\n"; handle.writeUTFBytes(req); } private function sendSetupReq(block:Object):void { state = STATE_SETUP; var interleavedChannels:String = interleaveChannelIndex++ + "-" + interleaveChannelIndex++; var p:String = url.isAbsolute(block.control) ? block.control : contentBase + block.control; trace('Setting up track: ' + p); var req:String = "SETUP " + p + " RTSP/1.0\r\n" + "CSeq: " + (++cSeq) + "\r\n" + "User-Agent: " + userAgent + "\r\n" + (session ? ("Session: " + session + "\r\n") : "") + "Transport: RTP/AVP/TCP;unicast;interleaved=" + interleavedChannels + "\r\n" + auth.authorizationHeader("SETUP", authState, authOpts, urlParsed, digestNC++) + "Date: " + new Date().toUTCString() + "\r\n" + "\r\n"; handle.writeUTFBytes(req); } private function sendPlayReq():void { /* Put the NetStream in 'Data Generation Mode'. Data is generated by FLVMux */ this.ns.play(null); state = STATE_PLAY; var req:String = "PLAY " + contentBase + " RTSP/1.0\r\n" + "CSeq: " + (++cSeq) + "\r\n" + "User-Agent: " + userAgent + "\r\n" + "Session: " + session + "\r\n" + auth.authorizationHeader("PLAY", authState, authOpts, urlParsed, digestNC++) + "\r\n"; handle.writeUTFBytes(req); } private function sendPauseReq():void { if (-1 === this.supportCommand("PAUSE")) { throw new Error('Pause is not supported by server.'); } state = STATE_PAUSE; /* NetStream must be closed here, otherwise it will think of this rtsp pause as a very bad connection and buffer a lot before playing again. Not excellent for live data. */ this.ns.close(); var req:String = "PAUSE " + contentBase + " RTSP/1.0\r\n" + "CSeq: " + (++cSeq) + "\r\n" + "User-Agent: " + userAgent + "\r\n" + "Session: " + session + "\r\n" + auth.authorizationHeader("PAUSE", authState, authOpts, urlParsed, digestNC++) + "\r\n"; handle.writeUTFBytes(req); } private function sendTeardownReq():void { state = STATE_TEARDOWN; var req:String = "TEARDOWN " + contentBase + " RTSP/1.0\r\n" + "CSeq: " + (++cSeq) + "\r\n" + "User-Agent: " + userAgent + "\r\n" + "Session: " + session + "\r\n" + auth.authorizationHeader("TEARDOWN", authState, authOpts, urlParsed, digestNC++) + "\r\n"; handle.writeUTFBytes(req); } } }
package com.axis.rtspclient { import flash.events.EventDispatcher; import flash.events.Event; import flash.utils.ByteArray; import flash.net.Socket; import flash.net.NetConnection; import flash.net.NetStream; import flash.media.Video; import mx.utils.StringUtil; import com.axis.rtspclient.FLVMux; import com.axis.rtspclient.RTP; import com.axis.rtspclient.SDP; import com.axis.http.url; import com.axis.http.request; import com.axis.http.auth; import com.axis.IClient; import com.axis.ClientEvent; public class RTSPClient extends EventDispatcher implements IClient { [Embed(source = "../../../../VERSION", mimeType = "application/octet-stream")] private var Version:Class; private var userAgent:String; private static const STATE_INITIAL:uint = 1 << 0; private static const STATE_OPTIONS:uint = 1 << 1; private static const STATE_DESCRIBE:uint = 1 << 2; private static const STATE_SETUP:uint = 1 << 3; private static const STATE_PLAY:uint = 1 << 4; private static const STATE_PLAYING:uint = 1 << 5; private static const STATE_PAUSE:uint = 1 << 6; private static const STATE_PAUSED:uint = 1 << 7; private static const STATE_TEARDOWN:uint = 1 << 8; private var state:int = STATE_INITIAL; private var handle:IRTSPHandle; private var ns:NetStream; private var video:Video; private var sdp:SDP = new SDP(); private var flvmux:FLVMux; private var urlParsed:Object; private var cSeq:uint = 1; private var session:String; private var contentBase:String; private var interleaveChannelIndex:uint = 0; private var methods:Array = []; private var data:ByteArray = new ByteArray(); private var rtpLength:int = -1; private var rtpChannel:int = -1; private var tracks:Array; private var authState:String = "none"; private var authOpts:Object = {}; private var digestNC:uint = 1; public function RTSPClient(video:Video, urlParsed:Object, handle:IRTSPHandle) { this.userAgent = "Slush " + StringUtil.trim(new Version().toString()); this.state = STATE_INITIAL; this.handle = handle; this.video = video; this.urlParsed = urlParsed; handle.addEventListener('data', this.onData); } public function start():Boolean { var self:RTSPClient = this; handle.addEventListener('connected', function():void { if (state !== STATE_INITIAL) { trace('Cannot start unless in initial state.'); return; } /* If the handle closes, take care of it */ handle.addEventListener('closed', self.onClose); if (0 === self.methods.length) { /* We don't know the options yet. Start with that. */ sendOptionsReq(); } else { /* Already queried the options (and perhaps got unauthorized on describe) */ sendDescribeReq(); } }); var nc:NetConnection = new NetConnection(); nc.connect(null); this.ns = new NetStream(nc); dispatchEvent(new ClientEvent(ClientEvent.NETSTREAM_CREATED, { ns : this.ns })); video.attachNetStream(this.ns); handle.connect(); return true; } public function pause():Boolean { if (state !== STATE_PLAYING) { trace('Unable to pause a stream if not playing.'); return false; } try { sendPauseReq(); } catch (err:Error) { trace("Unable to pause: " + err.message); return false; } return true; } public function resume():Boolean { if (state !== STATE_PAUSED) { trace('Unable to resume a stream if not paused.'); return false; } sendPlayReq(); return true; } public function stop():Boolean { if (state < STATE_PLAY) { trace('Unable to stop if we never reached play.'); return false; } sendTeardownReq(); return true; } private function onClose(event:Event):void { if (state === STATE_TEARDOWN) { this.ns.dispose(); dispatchEvent(new ClientEvent(ClientEvent.STOPPED)); } else { trace('RTSPClient: Handle unexpectedly closed.'); } } private function onData(event:Event):void { if (0 < data.bytesAvailable) { /* Determining byte have already been read. This is a continuation */ } else { /* Read the determining byte */ handle.readBytes(data, 0, 1); } switch(data[0]) { case 0x52: /* ascii 'R', start of RTSP */ onRTSPCommand(); break; case 0x24: /* ascii '$', start of interleaved packet */ onInterleavedData(); break; default: trace('Unknown determining byte:', '0x' + data[0].toString(16), '. Stopping stream.'); stop(); break; } } private function requestReset():void { var copy:ByteArray = new ByteArray(); data.readBytes(copy); data.clear(); copy.readBytes(data); rtpLength = -1; rtpChannel = -1; } private function readRequest(oBody:ByteArray):* { var parsed:* = request.readHeaders(handle, data); if (false === parsed) { return false; } 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('GET: Exhausted all authentication methods.'); trace('GET: Unable to authorize to ' + urlParsed.host); return false; } trace('RTSPClient: switching http-authorization from ' + authState + ' to ' + newAuthState); authState = newAuthState; state = STATE_INITIAL; data = new ByteArray(); handle.reconnect(); return false; } if (data.bytesAvailable < parsed.headers['content-length']) { return false; } /* RTSP commands contain no heavy body, so it's safe to read everything */ data.readBytes(oBody, 0, parsed.headers['content-length']); requestReset(); return parsed; } private function onRTSPCommand():void { var parsed:*, body:ByteArray = new ByteArray(); if (false === (parsed = readRequest(body))) { return; } if (200 !== parsed.code) { trace('RTSPClient: Invalid RTSP response - ', parsed.code, parsed.message); return; } switch (state) { case STATE_INITIAL: trace("RTSPClient: STATE_INITIAL"); case STATE_OPTIONS: trace("RTSPClient: STATE_OPTIONS"); this.methods = parsed.headers.public.split(/[ ]*,[ ]*/); sendDescribeReq(); break; case STATE_DESCRIBE: trace("RTSPClient: STATE_DESCRIBE"); if (!sdp.parse(body)) { trace("RTSPClient:Failed to parse SDP file"); return; } if (!parsed.headers['content-base']) { trace('RTSPClient: no content-base in describe reply'); return; } contentBase = parsed.headers['content-base']; tracks = sdp.getMediaBlockList(); trace('SDP contained ' + tracks.length + ' track(s). Calling SETUP for each.'); if (0 === tracks.length) { trace('No tracks in SDP file.'); return; } /* Fall through, it's time for setup */ case STATE_SETUP: trace("RTSPClient: STATE_SETUP"); if (parsed.headers['session']) { session = parsed.headers['session']; } if (0 !== tracks.length) { /* More tracks we must setup before playing */ var block:Object = tracks.shift(); sendSetupReq(block); return; } /* All tracks setup and ready to go! */ sendPlayReq(); break; case STATE_PLAY: trace("RTSPClient: STATE_PLAY"); state = STATE_PLAYING; if (this.flvmux) { /* If the flvmux have been initialized don't do it again. this is probably a resume after pause */ break; } this.flvmux = new FLVMux(this.ns, this.sdp); var analu:ANALU = new ANALU(); var aaac:AAAC = new AAAC(sdp); this.addEventListener("VIDEO_PACKET", analu.onRTPPacket); this.addEventListener("AUDIO_PACKET", aaac.onRTPPacket); analu.addEventListener(NALU.NEW_NALU, flvmux.onNALU); aaac.addEventListener(AACFrame.NEW_FRAME, flvmux.onAACFrame); break; case STATE_PLAYING: trace("RTSPClient: STATE_PLAYING"); break; case STATE_PAUSE: trace("RTSPClient: STATE_PAUSE"); state = STATE_PAUSED; break; case STATE_TEARDOWN: trace('RTSPClient: STATE_TEARDOWN'); this.handle.disconnect(); break; } if (0 < data.bytesAvailable) { onData(null); } } private function onInterleavedData():void { handle.readBytes(data, data.length); if (-1 == rtpLength && 0x24 === data[0]) { /* This is the beginning of a new RTP package */ data.readByte(); rtpChannel = data.readByte(); rtpLength = data.readShort(); } if (data.bytesAvailable < rtpLength) { /* The complete RTP package is not here yet, wait for more data */ return; } var pkgData:ByteArray = new ByteArray(); data.readBytes(pkgData, 0, rtpLength); if (rtpChannel === 0 || rtpChannel === 2) { /* We're discarding the RTCP counter parts for now */ var rtppkt:RTP = new RTP(pkgData, sdp); dispatchEvent(rtppkt); } requestReset(); if (0 < data.bytesAvailable) { onData(null); } } private function supportCommand(command:String):Boolean { return (-1 !== this.methods.indexOf(command)); } private function sendOptionsReq():void { state = STATE_OPTIONS; var req:String = "OPTIONS * RTSP/1.0\r\n" + "CSeq: " + (++cSeq) + "\r\n" + "User-Agent: " + userAgent + "\r\n" + "\r\n"; handle.writeUTFBytes(req); } private function sendDescribeReq():void { state = STATE_DESCRIBE; var u:String = 'rtsp://' + urlParsed.host + ":" + urlParsed.port + urlParsed.urlpath; var req:String = "DESCRIBE " + u + " RTSP/1.0\r\n" + "CSeq: " + (++cSeq) + "\r\n" + "User-Agent: " + userAgent + "\r\n" + "Accept: application/sdp\r\n" + auth.authorizationHeader("DESCRIBE", authState, authOpts, urlParsed, digestNC++) + "\r\n"; handle.writeUTFBytes(req); } private function sendSetupReq(block:Object):void { state = STATE_SETUP; var interleavedChannels:String = interleaveChannelIndex++ + "-" + interleaveChannelIndex++; var p:String = url.isAbsolute(block.control) ? block.control : contentBase + block.control; trace('Setting up track: ' + p); var req:String = "SETUP " + p + " RTSP/1.0\r\n" + "CSeq: " + (++cSeq) + "\r\n" + "User-Agent: " + userAgent + "\r\n" + (session ? ("Session: " + session + "\r\n") : "") + "Transport: RTP/AVP/TCP;unicast;interleaved=" + interleavedChannels + "\r\n" + auth.authorizationHeader("SETUP", authState, authOpts, urlParsed, digestNC++) + "Date: " + new Date().toUTCString() + "\r\n" + "\r\n"; handle.writeUTFBytes(req); } private function sendPlayReq():void { /* Put the NetStream in 'Data Generation Mode'. Data is generated by FLVMux */ this.ns.play(null); state = STATE_PLAY; var req:String = "PLAY " + contentBase + " RTSP/1.0\r\n" + "CSeq: " + (++cSeq) + "\r\n" + "User-Agent: " + userAgent + "\r\n" + "Session: " + session + "\r\n" + auth.authorizationHeader("PLAY", authState, authOpts, urlParsed, digestNC++) + "\r\n"; handle.writeUTFBytes(req); } private function sendPauseReq():void { if (-1 === this.supportCommand("PAUSE")) { throw new Error('Pause is not supported by server.'); } state = STATE_PAUSE; /* NetStream must be closed here, otherwise it will think of this rtsp pause as a very bad connection and buffer a lot before playing again. Not excellent for live data. */ this.ns.close(); var req:String = "PAUSE " + contentBase + " RTSP/1.0\r\n" + "CSeq: " + (++cSeq) + "\r\n" + "User-Agent: " + userAgent + "\r\n" + "Session: " + session + "\r\n" + auth.authorizationHeader("PAUSE", authState, authOpts, urlParsed, digestNC++) + "\r\n"; handle.writeUTFBytes(req); } private function sendTeardownReq():void { state = STATE_TEARDOWN; var req:String = "TEARDOWN " + contentBase + " RTSP/1.0\r\n" + "CSeq: " + (++cSeq) + "\r\n" + "User-Agent: " + userAgent + "\r\n" + "Session: " + session + "\r\n" + auth.authorizationHeader("TEARDOWN", authState, authOpts, urlParsed, digestNC++) + "\r\n"; handle.writeUTFBytes(req); } } }
Set state vars as const
RTSPClient: Set state vars as const
ActionScript
bsd-3-clause
AxisCommunications/locomote-video-player,gaetancollaud/locomote-video-player
b78667d37a4a55c9812ad8b461ed69c0f64354fb
src/control/ExportDataCommand.as
src/control/ExportDataCommand.as
package control { import com.adobe.serialization.json.JSON; import dragonBones.objects.DataParser; import dragonBones.utils.ConstValues; import flash.display.BitmapData; import flash.display.MovieClip; import flash.events.Event; import flash.events.IOErrorEvent; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.net.FileReference; import flash.utils.ByteArray; import message.Message; import message.MessageDispatcher; import model.ImportDataProxy; import model.JSFLProxy; import model.XMLDataProxy; import utils.BitmapDataUtil; import utils.GlobalConstValues; import utils.PNGEncoder; import utils.xmlToObject; import zero.zip.Zip; public class ExportDataCommand { public static const instance:ExportDataCommand = new ExportDataCommand(); private var _fileREF:FileReference; private var _isExporting:Boolean; private var _scale:Number; private var _exportType:uint; private var _backgroundColor:uint; private var _importDataProxy:ImportDataProxy; private var _xmlDataProxy:XMLDataProxy; private var _bitmapData:BitmapData; public function ExportDataCommand() { _fileREF = new FileReference(); _importDataProxy = ImportDataProxy.getInstance(); } public function export(exportType:uint, scale:Number, backgroundColor:uint = 0):void { if(_isExporting) { return; } _isExporting = true; _exportType = exportType; _scale = scale; switch(_exportType) { case 0: case 2: case 5: _scale = 1; break; } _backgroundColor = backgroundColor; exportStart(); } private function exportStart():void { var dataBytes:ByteArray; var zip:Zip; var date:Date; _xmlDataProxy = _importDataProxy.xmlDataProxy; _bitmapData = _importDataProxy.textureAtlas.bitmapData; if(_scale != 1) { _xmlDataProxy = _xmlDataProxy.clone(); var subBitmapDataDic:Object; var movieClip:MovieClip = _importDataProxy.textureAtlas.movieClip; if(movieClip && movieClip.totalFrames >= 3) { subBitmapDataDic = {}; for each (var displayName:String in _xmlDataProxy.getSubTextureListFromDisplayList()) { movieClip.gotoAndStop(movieClip.totalFrames); movieClip.gotoAndStop(displayName); subBitmapDataDic[displayName] = movieClip.getChildAt(0); } } else { subBitmapDataDic = BitmapDataUtil.getSubBitmapDataDic( _bitmapData, _xmlDataProxy.getSubTextureRectMap() ); } _xmlDataProxy.scaleData(_scale); _bitmapData = BitmapDataUtil.getMergeBitmapData( subBitmapDataDic, _xmlDataProxy.getSubTextureRectMap(), _xmlDataProxy.textureAtlasWidth, _xmlDataProxy.textureAtlasHeight, _scale ); } var isSWF:Boolean = _exportType == 0 || _exportType == 2 || _exportType == 5; var isXML:Boolean = _exportType == 2 || _exportType == 3 || _exportType == 4; switch(_exportType) { case 0: try { dataBytes = getSWFBytes(); if(dataBytes) { exportSave( DataParser.compressData( xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES), xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES), dataBytes ), _importDataProxy.data.name + GlobalConstValues.SWF_SUFFIX ); return; } break; } catch(_e:Error) { break; } case 1: try { dataBytes = getPNGBytes(_backgroundColor); if(dataBytes) { exportSave( DataParser.compressData( xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES), xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES), dataBytes ), _importDataProxy.data.name + GlobalConstValues.PNG_SUFFIX ); return; } break; } catch(_e:Error) { break; } case 2: case 3: case 5: case 6: try { if(isSWF) { dataBytes = getSWFBytes(); } else { dataBytes = getPNGBytes(_backgroundColor); } if(dataBytes) { date = new Date(); zip = new Zip(); zip.add( dataBytes, GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + (isSWF?GlobalConstValues.SWF_SUFFIX:GlobalConstValues.PNG_SUFFIX), date ); _xmlDataProxy.setImagePath(GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.PNG_SUFFIX); if(isXML) { zip.add( _xmlDataProxy.xml.toXMLString(), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); zip.add( _xmlDataProxy.textureAtlasXML.toXMLString(), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); } else { zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); } exportSave( zip.encode(), _importDataProxy.data.name + GlobalConstValues.ZIP_SUFFIX ); zip.clear(); return; } break; } catch(_e:Error) { break; } case 4: case 7: try { date = new Date(); zip = new Zip(); if(_xmlDataProxy == _importDataProxy.xmlDataProxy) { _xmlDataProxy = _xmlDataProxy.clone(); } _xmlDataProxy.changePath(); subBitmapDataDic = BitmapDataUtil.getSubBitmapDataDic( _bitmapData, _xmlDataProxy.getSubTextureRectMap() ); for(var subTextureName:String in subBitmapDataDic) { var subBitmapData:BitmapData = subBitmapDataDic[subTextureName]; zip.add( PNGEncoder.encode(subBitmapData), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + "/" + subTextureName + GlobalConstValues.PNG_SUFFIX, date ); subBitmapData.dispose(); } if(isXML) { zip.add( _xmlDataProxy.xml.toXMLString(), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); zip.add( _xmlDataProxy.textureAtlasXML.toXMLString(), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); } else { zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); } exportSave( zip.encode(), _importDataProxy.data.name + GlobalConstValues.ZIP_SUFFIX ); zip.clear(); return; } catch(_e:Error) { break; } default: break; } _isExporting = false; MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_ERROR); } private function getSWFBytes():ByteArray { if(_importDataProxy.textureAtlas.movieClip) { return _importDataProxy.textureBytes; } return null; } private function getPNGBytes(color:uint = 0):ByteArray { if(color) { var bitmapData:BitmapData = new BitmapData(_bitmapData.width, _bitmapData.height, true, color); bitmapData.draw(_bitmapData); var byteArray:ByteArray = PNGEncoder.encode(bitmapData); bitmapData.dispose(); return byteArray; } else if(_importDataProxy.textureAtlas.movieClip) { return PNGEncoder.encode(_bitmapData); } else { if(_bitmapData && _bitmapData != _importDataProxy.textureAtlas.bitmapData) { return PNGEncoder.encode(_bitmapData); } return _importDataProxy.textureBytes; } return null; } private function exportSave(fileData:ByteArray, fileName:String):void { MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT, fileName); _fileREF.addEventListener(Event.CANCEL, onFileSaveHandler); _fileREF.addEventListener(Event.COMPLETE, onFileSaveHandler); _fileREF.addEventListener(IOErrorEvent.IO_ERROR, onFileSaveHandler); _fileREF.save(fileData, fileName); } private function onFileSaveHandler(e:Event):void { _fileREF.removeEventListener(Event.CANCEL, onFileSaveHandler); _fileREF.removeEventListener(Event.COMPLETE, onFileSaveHandler); _fileREF.removeEventListener(IOErrorEvent.IO_ERROR, onFileSaveHandler); _isExporting = false; switch(e.type) { case Event.CANCEL: MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_CANCEL); break; case IOErrorEvent.IO_ERROR: MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_ERROR); break; case Event.COMPLETE: if(_bitmapData && _bitmapData != _importDataProxy.textureAtlas.bitmapData) { _bitmapData.dispose(); _bitmapData = null; } MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_COMPLETE); break; } } } }
package control { import com.adobe.serialization.json.JSON; import dragonBones.objects.DataParser; import dragonBones.utils.ConstValues; import flash.display.BitmapData; import flash.display.MovieClip; import flash.events.Event; import flash.events.IOErrorEvent; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.net.FileReference; import flash.utils.ByteArray; import message.Message; import message.MessageDispatcher; import model.ImportDataProxy; import model.JSFLProxy; import model.XMLDataProxy; import utils.BitmapDataUtil; import utils.GlobalConstValues; import utils.PNGEncoder; import utils.xmlToObject; import zero.zip.Zip; public class ExportDataCommand { public static const instance:ExportDataCommand = new ExportDataCommand(); private var _fileREF:FileReference; private var _isExporting:Boolean; private var _scale:Number; private var _exportType:uint; private var _backgroundColor:uint; private var _importDataProxy:ImportDataProxy; private var _xmlDataProxy:XMLDataProxy; private var _bitmapData:BitmapData; public function ExportDataCommand() { _fileREF = new FileReference(); _importDataProxy = ImportDataProxy.getInstance(); } public function export(exportType:uint, scale:Number, backgroundColor:uint = 0):void { if(_isExporting) { return; } _isExporting = true; _exportType = exportType; _scale = scale; switch(_exportType) { case 0: case 2: case 5: _scale = 1; break; } _backgroundColor = backgroundColor; exportStart(); } private function exportStart():void { var dataBytes:ByteArray; var zip:Zip; var date:Date; _xmlDataProxy = _importDataProxy.xmlDataProxy; _bitmapData = _importDataProxy.textureAtlas.bitmapData; if(_scale != 1) { _xmlDataProxy = _xmlDataProxy.clone(); var subBitmapDataDic:Object; var movieClip:MovieClip = _importDataProxy.textureAtlas.movieClip; if(movieClip && movieClip.totalFrames >= 3) { subBitmapDataDic = {}; for each (var displayName:String in _xmlDataProxy.getSubTextureListFromDisplayList()) { movieClip.gotoAndStop(movieClip.totalFrames); movieClip.gotoAndStop(displayName); subBitmapDataDic[displayName] = movieClip.getChildAt(0); } } else { subBitmapDataDic = BitmapDataUtil.getSubBitmapDataDic( _bitmapData, _xmlDataProxy.getSubTextureRectMap() ); } _xmlDataProxy.scaleData(_scale); _bitmapData = BitmapDataUtil.getMergeBitmapData( subBitmapDataDic, _xmlDataProxy.getSubTextureRectMap(), _xmlDataProxy.textureAtlasWidth, _xmlDataProxy.textureAtlasHeight, _scale ); } var isSWF:Boolean = _exportType == 0 || _exportType == 2 || _exportType == 5; var isXML:Boolean = _exportType == 2 || _exportType == 3 || _exportType == 4; switch(_exportType) { case 0: try { dataBytes = getSWFBytes(); if(dataBytes) { exportSave( DataParser.compressData( xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES), xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES), dataBytes ), _importDataProxy.data.name + GlobalConstValues.SWF_SUFFIX ); return; } break; } catch(_e:Error) { break; } case 1: try { dataBytes = getPNGBytes(_backgroundColor); if(dataBytes) { exportSave( DataParser.compressData( xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES), xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES), dataBytes ), _importDataProxy.data.name + GlobalConstValues.PNG_SUFFIX ); return; } break; } catch(_e:Error) { break; } case 2: case 3: case 5: case 6: try { if(isSWF) { dataBytes = getSWFBytes(); } else { dataBytes = getPNGBytes(_backgroundColor); } if(dataBytes) { date = new Date(); zip = new Zip(); zip.add( dataBytes, GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + (isSWF?GlobalConstValues.SWF_SUFFIX:GlobalConstValues.PNG_SUFFIX), date ); _xmlDataProxy.setImagePath(GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.PNG_SUFFIX); if(isXML) { zip.add( _xmlDataProxy.xml.toXMLString(), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); zip.add( _xmlDataProxy.textureAtlasXML.toXMLString(), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); } else { zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); } exportSave( zip.encode(), _importDataProxy.data.name + GlobalConstValues.ZIP_SUFFIX ); zip.clear(); return; } break; } catch(_e:Error) { break; } case 4: case 7: try { date = new Date(); zip = new Zip(); if(_xmlDataProxy == _importDataProxy.xmlDataProxy) { _xmlDataProxy = _xmlDataProxy.clone(); } //do not need to change changePath for TexturePacker //_xmlDataProxy.changePath(); subBitmapDataDic = BitmapDataUtil.getSubBitmapDataDic( _bitmapData, _xmlDataProxy.getSubTextureRectMap() ); for(var subTextureName:String in subBitmapDataDic) { var subBitmapData:BitmapData = subBitmapDataDic[subTextureName]; zip.add( PNGEncoder.encode(subBitmapData), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + "/" + subTextureName + GlobalConstValues.PNG_SUFFIX, date ); subBitmapData.dispose(); } if(isXML) { zip.add( _xmlDataProxy.xml.toXMLString(), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); zip.add( _xmlDataProxy.textureAtlasXML.toXMLString(), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); } else { zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); } exportSave( zip.encode(), _importDataProxy.data.name + GlobalConstValues.ZIP_SUFFIX ); zip.clear(); return; } catch(_e:Error) { break; } default: break; } _isExporting = false; MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_ERROR); } private function getSWFBytes():ByteArray { if(_importDataProxy.textureAtlas.movieClip) { return _importDataProxy.textureBytes; } return null; } private function getPNGBytes(color:uint = 0):ByteArray { if(color) { var bitmapData:BitmapData = new BitmapData(_bitmapData.width, _bitmapData.height, true, color); bitmapData.draw(_bitmapData); var byteArray:ByteArray = PNGEncoder.encode(bitmapData); bitmapData.dispose(); return byteArray; } else if(_importDataProxy.textureAtlas.movieClip) { return PNGEncoder.encode(_bitmapData); } else { if(_bitmapData && _bitmapData != _importDataProxy.textureAtlas.bitmapData) { return PNGEncoder.encode(_bitmapData); } return _importDataProxy.textureBytes; } return null; } private function exportSave(fileData:ByteArray, fileName:String):void { MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT, fileName); _fileREF.addEventListener(Event.CANCEL, onFileSaveHandler); _fileREF.addEventListener(Event.COMPLETE, onFileSaveHandler); _fileREF.addEventListener(IOErrorEvent.IO_ERROR, onFileSaveHandler); _fileREF.save(fileData, fileName); } private function onFileSaveHandler(e:Event):void { _fileREF.removeEventListener(Event.CANCEL, onFileSaveHandler); _fileREF.removeEventListener(Event.COMPLETE, onFileSaveHandler); _fileREF.removeEventListener(IOErrorEvent.IO_ERROR, onFileSaveHandler); _isExporting = false; switch(e.type) { case Event.CANCEL: MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_CANCEL); break; case IOErrorEvent.IO_ERROR: MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_ERROR); break; case Event.COMPLETE: if(_bitmapData && _bitmapData != _importDataProxy.textureAtlas.bitmapData) { _bitmapData.dispose(); _bitmapData = null; } MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_COMPLETE); break; } } } }
remove _xmlDataProxy.changePath
remove _xmlDataProxy.changePath
ActionScript
mit
DragonBones/DesignPanel
daaf88d330b574a906968f0d79e3b75837b95484
exporter/src/main/as/flump/export/Atlas.as
exporter/src/main/as/flump/export/Atlas.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.Sprite; import flash.filesystem.File; import flash.geom.Rectangle; import flump.SwfTexture; import com.threerings.util.Map; import com.threerings.util.Maps; public class Atlas { public var name :String; public var w :int, h :int, id :int; public var bins :Vector.<Rectangle> = new Vector.<Rectangle>(); public const textures :Vector.<SwfTexture> = new Vector.<SwfTexture>(); public function Atlas(name :String, w :int, h :int) { this.name = name; this.w = w; this.h = h; bins.push(new Rectangle(0, 0, w, h)); } public function place (tex :SwfTexture, target :Rectangle, rotated :Boolean) :void { _locs.put(tex, {x: target.x, y: target.y, rotated: rotated}); textures.push(tex); trace("Packer " + tex); var used :Rectangle = new Rectangle(target.x, target.y, rotated ? tex.h : tex.w, rotated ? tex.w : tex.h); const newBins :Vector.<Rectangle> = new Vector.<Rectangle>(); for each (var bin :Rectangle in bins) { for each (var newBin :Rectangle in subtract(bin, used)) { newBins.push(newBin); } } bins = newBins; } public function subtract (space :Rectangle, area :Rectangle) :Vector.<Rectangle> { const left :Vector.<Rectangle> = new Vector.<Rectangle>(); if (space.x < area.x) { left.push(new Rectangle(space.x, space.y, area.left - space.x, space.height)); } if (space.right > area.right) { left.push(new Rectangle(area.right, space.y, space.right - area.right, space.height)); } if (space.y < area.y) { left.push(new Rectangle(space.x, space.y, space.width, area.top - space.y)); } if (space.bottom > area.bottom) { left.push(new Rectangle(space.x, area.bottom, space.width, space.bottom - area.bottom)); } return left; } public function publish (dir :File) :void { var constructed :Sprite = new Sprite(); for each (var tex :SwfTexture in textures) { constructed.addChild(tex.holder); var loc :Object = _locs.get(tex); tex.holder.x = loc.x; tex.holder.y = loc.y; } PngPublisher.publish(dir.resolvePath(name + ".png"), w, h, constructed); } public function toXml () :String { var xml :String = "<atlas name='" + name + "' filename='" + name + ".png'>\n"; for each (var tex :SwfTexture in textures) { var loc :Object = _locs.get(tex); xml += " <texture name='" + tex.name + "' xOffset='" + tex.offset.x + "' yOffset='" + tex.offset.y + "' md5='" + tex.md5 + "' xAtlas='" + loc.x + "' yAtlas='" + loc.y + "' wAtlas='" + tex.w + "' hAtlas='" + tex.h + "'/>\n"; } return xml + "</atlas>\n"; } protected const _locs :Map = Maps.newMapOf(SwfTexture);//{x :int, y :int, rotated :Boolean} } }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.Sprite; import flash.filesystem.File; import flash.geom.Rectangle; import flump.SwfTexture; import com.threerings.util.Map; import com.threerings.util.Maps; public class Atlas { public var name :String; public var w :int, h :int, id :int; public var bins :Vector.<Rectangle> = new Vector.<Rectangle>(); public const textures :Vector.<SwfTexture> = new Vector.<SwfTexture>(); public function Atlas(name :String, w :int, h :int) { this.name = name; this.w = w; this.h = h; bins.push(new Rectangle(0, 0, w, h)); } public function place (tex :SwfTexture, target :Rectangle, rotated :Boolean) :void { _locs.put(tex, {x: target.x, y: target.y, rotated: rotated}); textures.push(tex); trace("Packer " + tex); var used :Rectangle = new Rectangle(target.x, target.y, rotated ? tex.h : tex.w, rotated ? tex.w : tex.h); const newBins :Vector.<Rectangle> = new Vector.<Rectangle>(); for each (var bin :Rectangle in bins) { for each (var newBin :Rectangle in subtract(bin, used)) { newBins.push(newBin); } } bins = newBins; } public function subtract (space :Rectangle, area :Rectangle) :Vector.<Rectangle> { const left :Vector.<Rectangle> = new Vector.<Rectangle>(); if (space.x < area.x) { left.push(new Rectangle(space.x, space.y, area.left - space.x, space.height)); } if (space.right > area.right) { left.push(new Rectangle(area.right, space.y, space.right - area.right, space.height)); } if (space.y < area.y) { left.push(new Rectangle(space.x, space.y, space.width, area.top - space.y)); } if (space.bottom > area.bottom) { left.push(new Rectangle(space.x, area.bottom, space.width, space.bottom - area.bottom)); } return left; } public function publish (dir :File) :void { var constructed :Sprite = new Sprite(); for each (var tex :SwfTexture in textures) { constructed.addChild(tex.holder); var loc :Object = _locs.get(tex); tex.holder.x = loc.x; tex.holder.y = loc.y; } PngPublisher.publish(dir.resolvePath(name + ".png"), w, h, constructed); } public function toXml () :String { var xml :String = '<atlas name="' + name + '" filename="' + name + '.png">\n'; for each (var tex :SwfTexture in textures) { var loc :Object = _locs.get(tex); xml += ' <texture name="' + tex.name + '" xOffset="' + tex.offset.x + '" yOffset="' + tex.offset.y + '" md5="' + tex.md5 + '" xAtlas="' + loc.x + '" yAtlas="' + loc.y + '" wAtlas="' + tex.w + '" hAtlas="' + tex.h + '"/>\n'; } return xml + '</atlas>\n'; } protected const _locs :Map = Maps.newMapOf(SwfTexture);//{x :int, y :int, rotated :Boolean} } }
Use double quotes around XML attributes for consistency.
Use double quotes around XML attributes for consistency.
ActionScript
mit
tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump,mathieuanthoine/flump
4c9a6087d17cce108e379e354ce715a2adca124b
actionscript/src/com/freshplanet/ane/AirBackgroundFetch/AirBackgroundFetch.as
actionscript/src/com/freshplanet/ane/AirBackgroundFetch/AirBackgroundFetch.as
////////////////////////////////////////////////////////////////////////////////////// // // Copyright 2012 Freshplanet (http://freshplanet.com | [email protected]) // // 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.AirBackgroundFetch { import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class AirBackgroundFetch extends EventDispatcher { // --------------------------------------------------------------------------------------// // // // PUBLIC API // // // // --------------------------------------------------------------------------------------// /** AirBackgroundFetch is supported on iOS and Android devices. */ public static function get isSupported() : Boolean { var isIOS:Boolean = (Capabilities.manufacturer.indexOf("iOS") != -1); var isAndroid:Boolean = (Capabilities.manufacturer.indexOf("Android") != -1) return isIOS || isAndroid; } public function AirBackgroundFetch() { if (!_instance) { _context = ExtensionContext.createExtensionContext(EXTENSION_ID, null); if (!_context) { log("ERROR - Extension context is null. Please check if extension.xml is setup correctly."); return; } _context.addEventListener(StatusEvent.STATUS, onStatus); _instance = this; } else { throw Error("This is a singleton, use getInstance(), do not call the constructor directly."); } } public static function getInstance() : AirBackgroundFetch { return _instance ? _instance : new AirBackgroundFetch(); } public var logEnabled : Boolean = true; // --------------------------------------------------------------------------------------// // // // FUNCTIONS // // // // --------------------------------------------------------------------------------------// /** * Load a music stream url * @param url:String */ public function loadUrl(url:String, data:String):void { _context.call("loadUrl", url, data); } // --------------------------------------------------------------------------------------// // // // PRIVATE API // // // // --------------------------------------------------------------------------------------// private static const EXTENSION_ID : String = "com.freshplanet.AirBackgroundFetch"; private static var _instance : AirBackgroundFetch; private var _context : ExtensionContext; private function onStatus( event : StatusEvent ) : void { if (event.code == "LOGGING") // Simple log message { log(event.level); } } private function log( message : String ) : void { if (logEnabled) trace("[AirBackgroundFetch] " + message); } } }
////////////////////////////////////////////////////////////////////////////////////// // // Copyright 2012 Freshplanet (http://freshplanet.com | [email protected]) // // 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.AirBackgroundFetch { import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class AirBackgroundFetch extends EventDispatcher { // --------------------------------------------------------------------------------------// // // // PUBLIC API // // // // --------------------------------------------------------------------------------------// /** AirBackgroundFetch is supported on iOS and Android devices. */ public static function get isSupported() : Boolean { var isIOS:Boolean = (Capabilities.manufacturer.indexOf("iOS") != -1); var isAndroid:Boolean = (Capabilities.manufacturer.indexOf("Android") != -1) return isIOS || isAndroid; } public function AirBackgroundFetch() { if (!_instance) { _context = ExtensionContext.createExtensionContext(EXTENSION_ID, null); if (!_context) { log("ERROR - Extension context is null. Please check if extension.xml is setup correctly."); return; } _context.addEventListener(StatusEvent.STATUS, onStatus); _instance = this; } else { throw Error("This is a singleton, use getInstance(), do not call the constructor directly."); } } public static function getInstance() : AirBackgroundFetch { return _instance ? _instance : new AirBackgroundFetch(); } public var logEnabled : Boolean = true; // --------------------------------------------------------------------------------------// // // // FUNCTIONS // // // // --------------------------------------------------------------------------------------// /** * Load get-create-mega url/data * @param url:String * @param data:jsonString */ public function loadUrl(url:String, data:String):void { _context.call("loadUrl", url, data); } /** * Load a music stream url */ public function getUserData():String { return _context.call("getUserData") as String; } /** * Load a music stream url */ public function flushUserData():void { _context.call("flushUserData"); } // --------------------------------------------------------------------------------------// // // // PRIVATE API // // // // --------------------------------------------------------------------------------------// private static const EXTENSION_ID : String = "com.freshplanet.AirBackgroundFetch"; private static var _instance : AirBackgroundFetch; private var _context : ExtensionContext; private function onStatus( event : StatusEvent ) : void { if (event.code == "LOGGING") // Simple log message { log(event.level); } } private function log( message : String ) : void { if (logEnabled) trace("[AirBackgroundFetch] " + message); } } }
Add flush user data
Add flush user data
ActionScript
apache-2.0
freshplanet/ANE-BackgroundFetch,freshplanet/ANE-BackgroundFetch
12ebf4673fb4af2447265b7939161d1a0b8b594e
activities/module-2/series-measuring/Probe.as
activities/module-2/series-measuring/Probe.as
package { //test change// import flash.display.MovieClip; import flash.events.MouseEvent; import flash.geom.Point; import org.concord.sparks.JavaScript; import org.concord.sparks.util.Display; public class Probe extends MovieClip { private var circuit:Circuit; private var connection:Object = null; private var id:String; private var _dragging:Boolean = false; private var _down:Boolean = false; public function Probe() { //trace('ENTER Probe#Probe'); super(); id = this.name; trace('Probe id=' + id); this.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown); this.addEventListener(MouseEvent.MOUSE_UP, onMouseUp); this.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove); stage.addEventListener(MouseEvent.MOUSE_OUT, onMouseUp); } public function getId() { return id; } public function getConnection():Object { return connection; } public function setConnection(connection:Object):void { this.connection = connection; } public function setCircuit(circuit:Circuit) { //trace('ENTER Probe#setCircuit'); this.circuit = circuit; } public function getTipPos():Point { return Display.localToStage(this.parent, new Point(this.x, this.y)); } public function onMouseDown(event:MouseEvent):void { _down = true; circuit.putProbeOnTop(this); } public function onMouseUp(event:MouseEvent):void { trace('ENTER Probe#onMouseUp'); this.stopDrag(); _down = false; if (_dragging) { _dragging = false; circuit.updateProbeConnection(this); } } public function onMouseMove(event:MouseEvent):void { //trace('ENTER Probe#onMouseMove'); if (! _down) { return; } if (_dragging) { circuit.updateResistorEndColors(this); } else { _dragging = true; this.startDrag(); if (connection) { disConnect(); } } } private function disConnect():void { JavaScript.instance().sendEvent('disconnect', 'probe', getId(), connection.getId()); connection = null; } } }
package { import flash.display.MovieClip; import flash.events.MouseEvent; import flash.geom.Point; import org.concord.sparks.JavaScript; import org.concord.sparks.util.Display; public class Probe extends MovieClip { private var circuit:Circuit; private var connection:Object = null; private var id:String; private var _dragging:Boolean = false; private var _down:Boolean = false; public function Probe() { //trace('ENTER Probe#Probe'); super(); id = this.name; trace('Probe id=' + id); this.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown); this.addEventListener(MouseEvent.MOUSE_UP, onMouseUp); this.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove); stage.addEventListener(MouseEvent.MOUSE_OUT, onMouseUp); } public function getId() { return id; } public function getConnection():Object { return connection; } public function setConnection(connection:Object):void { this.connection = connection; } public function setCircuit(circuit:Circuit) { //trace('ENTER Probe#setCircuit'); this.circuit = circuit; } public function getTipPos():Point { return Display.localToStage(this.parent, new Point(this.x, this.y)); } public function onMouseDown(event:MouseEvent):void { _down = true; circuit.putProbeOnTop(this); } public function onMouseUp(event:MouseEvent):void { trace('ENTER Probe#onMouseUp'); this.stopDrag(); _down = false; if (_dragging) { _dragging = false; circuit.updateProbeConnection(this); } } public function onMouseMove(event:MouseEvent):void { //trace('ENTER Probe#onMouseMove'); if (! _down) { return; } if (_dragging) { circuit.updateResistorEndColors(this); } else { _dragging = true; this.startDrag(); if (connection) { disConnect(); } } } private function disConnect():void { JavaScript.instance().sendEvent('disconnect', 'probe', getId(), connection.getId()); connection = null; } } }
test change 2
test change 2
ActionScript
apache-2.0
concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks
9fbd02591142f5457ccaf260715ee7acc495c503
src/org/mangui/hls/demux/Nalu.as
src/org/mangui/hls/demux/Nalu.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.mangui.hls.demux { import flash.utils.ByteArray; CONFIG::LOGGING { import org.mangui.hls.HLSSettings; import org.mangui.hls.utils.Log; } /** Constants and utilities for the H264 video format. **/ public class Nalu { private static var _audNalu : ByteArray; // static initializer { _audNalu = new ByteArray(); _audNalu.length = 2; _audNalu.writeByte(0x09); _audNalu.writeByte(0xF0); }; /** Return an array with NAL delimiter indexes. **/ public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> { var units : Vector.<VideoFrame> = new Vector.<VideoFrame>(); var unit_start : int; var unit_type : int; var unit_header : int; var aud_found : Boolean = false; // Loop through data to find NAL startcodes. var window : uint = 0; nalu.position = position; while (nalu.bytesAvailable > 4) { window = nalu.readUnsignedInt(); // Match four-byte startcodes if ((window & 0xFFFFFFFF) == 0x01) { // push previous NAL unit if new start delimiter found, dont push unit with type = 0 if (unit_start && unit_type) { units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type)); } unit_header = 4; unit_start = nalu.position; unit_type = nalu.readByte() & 0x1F; if(unit_type ==9) { aud_found = true; } /* if AUD already found and newly found unit is NDR or IDR, stop parsing here and consider that this IDR/NDR is the last NAL unit breaking the loop here is done for optimization purpose, as NAL parsing is time consuming ... */ if (aud_found && (unit_type == 1 || unit_type == 5)) { break; } // Match three-byte startcodes } else if ((window & 0xFFFFFF00) == 0x100) { // push previous NAL unit if new start delimiter found, dont push unit with type = 0 if (unit_start && unit_type) { units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type)); } nalu.position--; unit_header = 3; unit_start = nalu.position; unit_type = nalu.readByte() & 0x1F; if(unit_type ==9) { aud_found = true; } /* if AUD already found and newly found unit is NDR or IDR, stop parsing here and consider that this IDR/NDR is the last NAL unit breaking the loop here is done for optimization purpose, as NAL parsing is time consuming ... */ if (aud_found && (unit_type == 1 || unit_type == 5)) { break; } } else { nalu.position -= 3; } } // Append the last NAL to the array. if (unit_start) { units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type)); } // Reset position and return results. CONFIG::LOGGING { if (HLSSettings.logDebug2) { /** H264 NAL unit names. **/ const NAMES : Array = ['Unspecified',// 0 'NDR', // 1 'Partition A', // 2 'Partition B', // 3 'Partition C', // 4 'IDR', // 5 'SEI', // 6 'SPS', // 7 'PPS', // 8 'AUD', // 9 'End of Sequence', // 10 'End of Stream', // 11 'Filler Data'// 12 ]; if (units.length) { var txt : String = "AVC: "; for (var i : int = 0; i < units.length; i++) { txt += NAMES[units[i].type] + ","; //+ ":" + units[i].length } Log.debug2(txt.substr(0,txt.length-1) + " slices"); } else { Log.debug2('AVC: no NALU slices found'); } } } nalu.position = position; return units; }; public static function get AUD():ByteArray { return _audNalu; } } }
/* 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.mangui.hls.demux { import flash.utils.ByteArray; CONFIG::LOGGING { import org.mangui.hls.HLSSettings; import org.mangui.hls.utils.Log; } /** Constants and utilities for the H264 video format. **/ public class Nalu { private static var _audNalu : ByteArray; // static initializer { _audNalu = new ByteArray(); _audNalu.length = 2; _audNalu.writeByte(0x09); _audNalu.writeByte(0xF0); }; /** Return an array with NAL delimiter indexes. **/ public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> { var len : uint = nalu.length,i : uint = position; var unitHeader : int,lastUnitHeader : int = 0; var unitStart : int,lastUnitStart : int = 0; var unitType : int,lastUnitType : int = 0; var audFound : Boolean = false; var value : uint,state : uint = 0; var units : Vector.<VideoFrame> = new Vector.<VideoFrame>(); // Loop through data to find NAL startcodes. while (i < len) { // finding 3 or 4-byte start codes (00 00 01 OR 00 00 00 01) value = nalu[i++]; switch(state) { case 0: if(!value) { state = 1; // unitHeader is NAL header offset unitHeader=i-1; } break; case 1: if(value) { state = 0; } else { state = 2; } break; case 2: case 3: if(value) { if(value === 1) { unitType = nalu[i] & 0x1f; if(unitType == 9) { audFound = true; } if(lastUnitStart) { // use Math.min(4,...) as max header size is 4. // in case there are any leading zeros // such as 00 00 00 00 00 00 01 // ^^ // we need to ignore them as they are part of previous NAL unit units.push(new VideoFrame(Math.min(4,lastUnitStart-lastUnitHeader), i-state-1-lastUnitStart, lastUnitStart, lastUnitType)); } lastUnitStart = i; lastUnitType = unitType; lastUnitHeader = unitHeader; if(audFound == true && (unitType === 1 || unitType === 5)) { // OPTI !!! if AUD unit already parsed and if IDR/NDR unit, consider it is last NALu i = len; } } state = 0; } else { state = 3; } break; default: break; } } //push last unit if(lastUnitStart) { units.push(new VideoFrame(Math.min(4,lastUnitStart-lastUnitHeader), len-lastUnitStart, lastUnitStart, lastUnitType)); } // Reset position and return results. CONFIG::LOGGING { if (HLSSettings.logDebug2) { /** H264 NAL unit names. **/ const NAMES : Array = ['Unspecified',// 0 'NDR', // 1 'Partition A', // 2 'Partition B', // 3 'Partition C', // 4 'IDR', // 5 'SEI', // 6 'SPS', // 7 'PPS', // 8 'AUD', // 9 'End of Sequence', // 10 'End of Stream', // 11 'Filler Data'// 12 ]; if (units.length) { var txt : String = "AVC: "; for (i = 0; i < units.length; i++) { txt += NAMES[units[i].type] + ","; //+ ":" + units[i].length } Log.debug2(txt.substr(0,txt.length-1) + " slices"); } else { Log.debug2('AVC: no NALU slices found'); } } } nalu.position = position; return units; }; public static function get AUD():ByteArray { return _audNalu; } } }
optimize NAL unit parsing use a state machine and byte read instead of word read and jump backwards in the array in case start code not found related to #162
optimize NAL unit parsing use a state machine and byte read instead of word read and jump backwards in the array in case start code not found related to #162
ActionScript
mpl-2.0
Corey600/flashls,JulianPena/flashls,mangui/flashls,dighan/flashls,neilrackett/flashls,codex-corp/flashls,thdtjsdn/flashls,jlacivita/flashls,Boxie5/flashls,jlacivita/flashls,tedconf/flashls,fixedmachine/flashls,clappr/flashls,hola/flashls,thdtjsdn/flashls,NicolasSiver/flashls,loungelogic/flashls,codex-corp/flashls,clappr/flashls,Boxie5/flashls,NicolasSiver/flashls,JulianPena/flashls,Corey600/flashls,hola/flashls,loungelogic/flashls,vidible/vdb-flashls,neilrackett/flashls,fixedmachine/flashls,mangui/flashls,vidible/vdb-flashls,dighan/flashls,tedconf/flashls
c0483e8259485e379e8250b6325a8b2163336943
test/acceptance/e4x/Types/e9_2_1_2.as
test/acceptance/e4x/Types/e9_2_1_2.as
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** 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 Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Ethan Hugg * Milen Nankov * * 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 ***** */ START("9.2.1.2 - XMLList [[Put]]"); // element var x1 = new XMLList("<alpha>one</alpha><bravo>two</bravo>"); TEST(1, "<alpha>one</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); x1[0] = <charlie>three</charlie>; TEST(2, "<charlie>three</charlie>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); x1[0] = <delta>four</delta> + <echo>five</echo>; TEST(3, "<delta>four</delta>" + NL() + "<echo>five</echo>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); var y1 = new XMLList("<alpha>one</alpha><bravo>two</bravo>"); y1[0] = "five"; TEST(4, "<alpha>five</alpha>" + NL() + "<bravo>two</bravo>", y1.toXMLString()); // attribute var x1 = new XMLList("<alpha attr=\"50\">one</alpha><bravo>two</bravo>"); x1[0].@attr = "fifty"; TEST(5, "<alpha attr=\"fifty\">one</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); var x1 = new XMLList("<alpha attr=\"50\">one</alpha><bravo>two</bravo>"); x1[0].@attr = new XMLList("<att>sixty</att>"); TEST(6, "<alpha attr=\"sixty\">one</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); var x1 = new XMLList("<alpha attr=\"50\">one</alpha><bravo>two</bravo>"); x1[0].@attr = "<att>sixty</att>"; TEST(7, "<alpha attr=\"&lt;att>sixty&lt;/att>\">one</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); // text node var x1 = new XMLList("alpha<bravo>two</bravo>"); x1[0] = "beta"; TEST(8, "<alpha>beta</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); var x1 = new XMLList("<alpha>one</alpha><bravo>two</bravo>"); x1[0] = new XML("beta"); TEST(9, "<alpha>beta</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); var x1 = new XMLList("<alpha>one</alpha><bravo>two</bravo>"); x1[0] = new XMLList("beta"); TEST(10, "<alpha>beta</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); var x1 = new XMLList("alpha<bravo>two</bravo>"); x1[0] = new XML("<two>beta</two>"); TEST(11, "<two>beta</two>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); // comment var x1 = new XMLList("<alpha><beta><!-- hello, comment --></beta></alpha>"); x1.beta = new XMLList("<comment>hello</comment>"); TEST(12, new XMLList("<alpha><comment>hello</comment></alpha>"), x1); var x1 = new XMLList("<alpha><beta><!-- hello, comment --></beta></alpha>"); x1.beta = new XML("<comment>hello</comment>"); TEST(13, new XMLList("<alpha><comment>hello</comment></alpha>"), x1); var x1 = new XMLList("<alpha><beta><!-- hello, comment --></beta></alpha>"); x1.beta = "hello"; TEST(14, new XMLList("<alpha><beta>hello</beta></alpha>"), x1); var x1 = new XMLList("<alpha><beta><!-- hello, comment --></beta></alpha>"); x1.beta = new XML("hello"); TEST(15, new XMLList("<alpha><beta>hello</beta></alpha>"), x1); // PI XML.ignoreProcessingInstructions = false; var x1 = new XML("<alpha><beta><?xm-xsl-param name=\"sponsor\" value=\"dw\"?></beta></alpha>"); x1.beta = new XML("<pi element=\"yes\">instructions</pi>"); TEST(16, new XMLList("<alpha><pi element=\"yes\">instructions</pi></alpha>"), x1); XML.ignoreProcessingInstructions = false; var x1 = new XML("<alpha><beta><?xm-xsl-param name=\"sponsor\" value=\"dw\"?></beta></alpha>"); x1.beta = new XMLList("<pi element=\"yes\">instructions</pi>"); TEST(17, new XMLList("<alpha><pi element=\"yes\">instructions</pi></alpha>"), x1); var x1 = new XML("<alpha><beta><?xm-xsl-param name=\"sponsor\" value=\"dw\"?></beta></alpha>"); x1.beta = "processing instructions"; TEST(18, new XMLList("<alpha><beta>processing instructions</beta></alpha>"), x1); END();
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** 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 Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Ethan Hugg * Milen Nankov * * 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 ***** */ START("9.2.1.2 - XMLList [[Put]]"); // element var x1 = new XMLList("<alpha>one</alpha><bravo>two</bravo>"); TEST(1, "<alpha>one</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); x1[0] = <charlie>three</charlie>; TEST(2, "<charlie>three</charlie>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); x1[0] = <delta>four</delta> + <echo>five</echo>; TEST(3, "<delta>four</delta>" + NL() + "<echo>five</echo>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); var y1 = new XMLList("<alpha>one</alpha><bravo>two</bravo>"); y1[0] = "five"; TEST(4, "<alpha>five</alpha>" + NL() + "<bravo>two</bravo>", y1.toXMLString()); // attribute var x1 = new XMLList("<alpha attr=\"50\">one</alpha><bravo>two</bravo>"); x1[0].@attr = "fifty"; TEST(5, "<alpha attr=\"fifty\">one</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); var x1 = new XMLList("<alpha attr=\"50\">one</alpha><bravo>two</bravo>"); x1[0].@attr = new XMLList("<att>sixty</att>"); TEST(6, "<alpha attr=\"sixty\">one</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); var x1 = new XMLList("<alpha attr=\"50\">one</alpha><bravo>two</bravo>"); x1[0].@attr = "<att>sixty</att>"; TEST(7, "<alpha attr=\"&lt;att>sixty&lt;/att>\">one</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); // text node var x1 = new XMLList("alpha<bravo>two</bravo>"); x1[0] = "beta"; TEST(8, "beta" + NL() + "<bravo>two</bravo>", x1.toXMLString()); var x1 = new XMLList("<alpha>one</alpha><bravo>two</bravo>"); x1[0] = new XML("beta"); TEST(9, "<alpha>beta</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); var x1 = new XMLList("<alpha>one</alpha><bravo>two</bravo>"); x1[0] = new XMLList("beta"); TEST(10, "<alpha>beta</alpha>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); var x1 = new XMLList("alpha<bravo>two</bravo>"); x1[0] = new XML("<two>beta</two>"); TEST(11, "<two>beta</two>" + NL() + "<bravo>two</bravo>", x1.toXMLString()); // comment var x1 = new XMLList("<alpha><beta><!-- hello, comment --></beta></alpha>"); x1.beta = new XMLList("<comment>hello</comment>"); TEST(12, new XMLList("<alpha><comment>hello</comment></alpha>"), x1); var x1 = new XMLList("<alpha><beta><!-- hello, comment --></beta></alpha>"); x1.beta = new XML("<comment>hello</comment>"); TEST(13, new XMLList("<alpha><comment>hello</comment></alpha>"), x1); var x1 = new XMLList("<alpha><beta><!-- hello, comment --></beta></alpha>"); x1.beta = "hello"; TEST(14, new XMLList("<alpha><beta>hello</beta></alpha>"), x1); var x1 = new XMLList("<alpha><beta><!-- hello, comment --></beta></alpha>"); x1.beta = new XML("hello"); TEST(15, new XMLList("<alpha><beta>hello</beta></alpha>"), x1); // PI XML.ignoreProcessingInstructions = false; var x1 = new XML("<alpha><beta><?xm-xsl-param name=\"sponsor\" value=\"dw\"?></beta></alpha>"); x1.beta = new XML("<pi element=\"yes\">instructions</pi>"); TEST(16, new XMLList("<alpha><pi element=\"yes\">instructions</pi></alpha>"), x1); XML.ignoreProcessingInstructions = false; var x1 = new XML("<alpha><beta><?xm-xsl-param name=\"sponsor\" value=\"dw\"?></beta></alpha>"); x1.beta = new XMLList("<pi element=\"yes\">instructions</pi>"); TEST(17, new XMLList("<alpha><pi element=\"yes\">instructions</pi></alpha>"), x1); var x1 = new XML("<alpha><beta><?xm-xsl-param name=\"sponsor\" value=\"dw\"?></beta></alpha>"); x1.beta = "processing instructions"; TEST(18, new XMLList("<alpha><beta>processing instructions</beta></alpha>"), x1); END();
revert e4x change that was not implemented
revert e4x change that was not implemented
ActionScript
mpl-2.0
pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux
a855fa8340becde00d4c48224b59df85cd5e58b7
src/as/com/threerings/flash/MediaContainer.as
src/as/com/threerings/flash/MediaContainer.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.flash { //import flash.display.Bitmap; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Shape; import flash.display.Sprite; import flash.errors.IOError; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import flash.events.IOErrorEvent; import flash.events.MouseEvent; import flash.events.NetStatusEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.events.StatusEvent; import flash.events.TextEvent; import flash.geom.Point; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.system.ApplicationDomain; import flash.system.LoaderContext; import flash.system.SecurityDomain; import flash.net.URLRequest; import com.threerings.util.StringUtil; import com.threerings.util.ValueEvent; import com.threerings.util.Util; /** * Dispatched when the size of the media being loaded is known. * * @eventType com.threerings.flash.MediaContainer.SIZE_KNOWN */ [Event(name="mediaSizeKnown", type="com.threerings.util.ValueEvent")] /** * A wrapper class for all media that will be placed on the screen. * Subject to change. */ public class MediaContainer extends Sprite { /** A ValueEvent we dispatch when our size is known. * Value: [ width, height ]. * * @eventType mediaSizeKnown */ public static const SIZE_KNOWN :String = "mediaSizeKnown"; /** A log instance that can be shared by sprites. */ protected static const log :Log = Log.getLog(MediaContainer); /** * Constructor. */ public function MediaContainer (url :String = null) { if (url != null) { setMedia(url); } mouseEnabled = false; mouseChildren = true; } /** * Return true if the content has been initialized. * For most content, this is true if the media is non-null, but * for anything loaded with a Loader, it is only true after the INIT event is dispatched. */ public function isContentInitialized () :Boolean { return (_media != null) && (_initialized || !(_media is Loader)); } /** * Get the media. If the media was loaded using a URL, this will * likely be the Loader object holding the real media. */ public function getMedia () :DisplayObject { return _media; } /** * Configure the media to display. */ public function setMedia (url :String) :void { if (Util.equals(_url, url)) { return; // no change } _url = url; // shutdown any previous media if (_media != null) { shutdown(false); } // set up the new media willShowNewMedia(); if (StringUtil.endsWith(url.toLowerCase(), ".flv")) { setupVideo(url); } else { setupSwfOrImage(url); } } /** * Configure our media as an instance of the specified class. */ public function setMediaClass (clazz :Class) :void { setMediaObject(new clazz() as DisplayObject); } /** * Configure an already-instantiated DisplayObject as our media. */ public function setMediaObject (disp :DisplayObject) :void { _url = null; if (_media != null) { shutdown(false); } willShowNewMedia(); addChild(disp); _media = disp; updateContentDimensions(disp.width, disp.height); } /** * A place where subclasses can initialize things prior to showing * new media. */ protected function willShowNewMedia () :void { _initialized = false; } /** * Configure this sprite to show a video. */ protected function setupVideo (url :String) :void { var vid :VideoDisplayer = new VideoDisplayer(); vid.addEventListener(VideoDisplayer.SIZE_KNOWN, handleVideoSizeKnown); vid.addEventListener(VideoDisplayer.VIDEO_ERROR, handleVideoError); _media = vid; addChild(vid); vid.setup(url); } /** * Configure this sprite to show an image or flash movie. */ protected function setupSwfOrImage (url :String) :void { startedLoading(); // create our loader and set up some event listeners var loader :Loader = new Loader(); _media = loader; var info :LoaderInfo = loader.contentLoaderInfo; info.addEventListener(Event.COMPLETE, loadingComplete); info.addEventListener(Event.INIT, handleInit); info.addEventListener(IOErrorEvent.IO_ERROR, loadError); info.addEventListener(ProgressEvent.PROGRESS, loadProgress); // create a mask to prevent the media from drawing out of bounds if (getMaxContentWidth() < int.MAX_VALUE && getMaxContentHeight() < int.MAX_VALUE) { configureMask(getMaxContentWidth(), getMaxContentHeight()); } // start it loading, add it as a child loader.load(new URLRequest(url), getContext(url)); addChild(loader); try { updateContentDimensions(info.width, info.height); } catch (err :Error) { // an error is thrown trying to access these props before they're // ready } } /** * Display a 'broken image' to indicate there were troubles with * loading the media. */ protected function setupBrokenImage (w :int = -1, h :int = -1) :void { if (w == -1) { w = 100; } if (h == -1) { h = 100; } setMediaObject(ImageUtil.createErrorImage(w, h)); } /** * Get the application domain being used by this media, or null if * none or not applicable. */ public function getApplicationDomain () :ApplicationDomain { return (_media is Loader) ? (_media as Loader).contentLoaderInfo.applicationDomain : null; } /** * Unload the media we're displaying, clean up any resources. * * @param completely if true, we're going away and should stop * everything. Otherwise, we're just loading up new media. */ public function shutdown (completely :Boolean = true) :void { try { // remove the mask (but only if we added it) if (_media != null && _media.mask != null) { try { removeChild(_media.mask); _media.mask = null; } catch (argErr :ArgumentError) { // If we catch this error, it was thrown in removeChild // and means that we did not add the media's mask, // and so shouldn't remove it either. The action we // take here is NOT setting _media.mask = null. // Then, we continue happily... } } if (_media is Loader) { var loader :Loader = (_media as Loader); var url :String = loader.contentLoaderInfo.url; // remove any listeners removeListeners(loader.contentLoaderInfo); // dispose of media try { loader.close(); } catch (ioe :IOError) { // ignore } loader.unload(); removeChild(loader); log.info("Unloaded media [url=" + url + "]."); } else if (_media is VideoDisplayer) { var vid :VideoDisplayer = (_media as VideoDisplayer); vid.removeEventListener(VideoDisplayer.SIZE_KNOWN, handleVideoSizeKnown); vid.removeEventListener(VideoDisplayer.VIDEO_ERROR, handleVideoError); vid.shutdown(); removeChild(vid); } else if (_media != null) { removeChild(_media); } } catch (ioe :IOError) { log.warning("Error shutting down media: " + ioe); log.logStackTrace(ioe); } // clean everything up _w = 0; _h = 0; _media = null; } /** * Get the width of the content, bounded by the maximum. */ public function getContentWidth () :int { return Math.min(Math.abs(_w * getMediaScaleX()), getMaxContentWidth()); } /** * Get the height of the content, bounded by the maximum. */ public function getContentHeight () :int { return Math.min(Math.abs(_h * getMediaScaleY()), getMaxContentHeight()); } /** * Get the maximum allowable width for our content. */ public function getMaxContentWidth () :int { return int.MAX_VALUE; } /** * Get the maximum allowable height for our content. */ public function getMaxContentHeight () :int { return int.MAX_VALUE; } /** * Get the X scaling factor to use on the actual media. */ public function getMediaScaleX () :Number { return 1; } /** * Get the Y scaling factor to use on the actual media. */ public function getMediaScaleY () :Number { return 1; } /** * Called by MediaWrapper as notification that its size has changed. */ public function containerDimensionsUpdated (newWidth :Number, newHeight :Number) :void { // do nothing in base MediaContainer } override public function toString () :String { return "MediaContainer[url=" + _url + "]"; } /** * Return the LoaderContext that should be used to load the media * at the specified url. */ protected function getContext (url :String) :LoaderContext { if (isImage(url)) { // load images into our domain so that we can view their pixels return new LoaderContext(true, new ApplicationDomain(ApplicationDomain.currentDomain), SecurityDomain.currentDomain); } else { // share nothing, trust nothing return new LoaderContext(false, new ApplicationDomain(null), null); } } /** * Does the specified url represent an image? */ protected function isImage (url :String) :Boolean { // look at the last 4 characters in the lowercased url switch (url.toLowerCase().slice(-4)) { case ".png": case ".jpg": case ".gif": return true; default: return false; } } /** * Remove our listeners from the LoaderInfo object. */ protected function removeListeners (info :LoaderInfo) :void { info.removeEventListener(Event.COMPLETE, loadingComplete); info.removeEventListener(Event.INIT, handleInit); info.removeEventListener(IOErrorEvent.IO_ERROR, loadError); info.removeEventListener(ProgressEvent.PROGRESS, loadProgress); } /** * A callback to receive IO_ERROR events. */ protected function loadError (event :IOErrorEvent) :void { stoppedLoading(); setupBrokenImage(-1, -1); } /** * A callback to receive PROGRESS events. */ protected function loadProgress (event :ProgressEvent) :void { updateLoadingProgress(event.bytesLoaded, event.bytesTotal); var info :LoaderInfo = (event.target as LoaderInfo); try { updateContentDimensions(info.width, info.height); } catch (err :Error) { // an error is thrown trying to access these props before they're // ready } } /** * Handles video size known. */ protected function handleVideoSizeKnown (event :ValueEvent) :void { var args :Array = (event.value as Array); updateContentDimensions(int(args[0]), int(args[1])); } /** * Handles an error loading a video. */ protected function handleVideoError (event :ValueEvent) :void { log.warning("Error loading video [cause=" + event.value + "]."); stoppedLoading(); setupBrokenImage(-1, -1); } /** * Handles the INIT event for content loaded with a Loader. */ protected function handleInit (event :Event) :void { _initialized = true; } /** * Callback function to receive COMPLETE events for swfs or images. */ protected function loadingComplete (event :Event) :void { var info :LoaderInfo = (event.target as LoaderInfo); removeListeners(info); // trace("Loading complete: " + info.url + // ", childAllowsParent=" + info.childAllowsParent + // ", parentAllowsChild=" + info.parentAllowsChild + // ", sameDomain=" + info.sameDomain); updateContentDimensions(info.width, info.height); updateLoadingProgress(1, 1); stoppedLoading(); } /** * Configure the mask for this object. */ protected function configureMask (ww :int, hh :int) :void { var mask :Shape; if (_media.mask != null) { // see if the mask was added by us try { getChildIndex(_media.mask); } catch (argErr :ArgumentError) { // oy! We are not the controllers of this mask, it must // have been added by someone else. This probably means // that the _media is not a Loader, and so we should just // leave it alone with its custom mask. return; } // otherwise, it's a mask we previously configured mask = (_media.mask as Shape); } else { mask = new Shape(); // the mask must be added to the display list (which is wacky) addChild(mask); _media.mask = mask; } mask.graphics.clear(); mask.graphics.beginFill(0xFFFFFF); mask.graphics.drawRect(0, 0, ww, hh); mask.graphics.endFill(); } /** * Called during loading as we figure out how big the content we're * loading is. */ protected function updateContentDimensions (ww :int, hh :int) :void { // update our saved size, and possibly notify our container if (_w != ww || _h != hh) { _w = ww; _h = hh; contentDimensionsUpdated(); // dispatch an event to any listeners dispatchEvent(new ValueEvent(SIZE_KNOWN, [ ww, hh ])); } } /** * Called when we know the true size of the content. */ protected function contentDimensionsUpdated () :void { // nada, by default } /** * Update the graphics to indicate how much is loaded. */ protected function updateLoadingProgress ( soFar :Number, total :Number) :void { // nada, by default } /** * Called when we've started loading new media. Will not be called * for new media that does not require loading. */ protected function startedLoading () :void { // nada } /** * Called when we've stopped loading, which may be as a result of * completion, an error while loading, or early termination. */ protected function stoppedLoading () :void { // nada } /** The unaltered URL of the content we're displaying. */ protected var _url :String; /** The unscaled width of our content. */ protected var _w :int; /** The unscaled height of our content. */ protected var _h :int; /** Either a Loader or a VideoDisplay. */ protected var _media :DisplayObject; /** If we're using a Loader, true once the INIT property has been dispatched. */ protected var _initialized :Boolean; } }
// // $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.flash { //import flash.display.Bitmap; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Shape; import flash.display.Sprite; import flash.errors.IOError; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import flash.events.IOErrorEvent; import flash.events.MouseEvent; import flash.events.NetStatusEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.events.StatusEvent; import flash.events.TextEvent; import flash.geom.Point; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.system.ApplicationDomain; import flash.system.LoaderContext; import flash.system.SecurityDomain; import flash.net.URLRequest; import com.threerings.util.StringUtil; import com.threerings.util.ValueEvent; import com.threerings.util.Util; /** * Dispatched when the size of the media being loaded is known. * * @eventType com.threerings.flash.MediaContainer.SIZE_KNOWN */ [Event(name="mediaSizeKnown", type="com.threerings.util.ValueEvent")] /** * A wrapper class for all media that will be placed on the screen. * Subject to change. */ public class MediaContainer extends Sprite { /** A ValueEvent we dispatch when our size is known. * Value: [ width, height ]. * * @eventType mediaSizeKnown */ public static const SIZE_KNOWN :String = "mediaSizeKnown"; /** A log instance that can be shared by sprites. */ protected static const log :Log = Log.getLog(MediaContainer); /** * Constructor. */ public function MediaContainer (url :String = null) { if (url != null) { setMedia(url); } mouseEnabled = false; mouseChildren = true; } /** * Return true if the content has been initialized. * For most content, this is true if the media is non-null, but * for anything loaded with a Loader, it is only true after the INIT event is dispatched. */ public function isContentInitialized () :Boolean { return (_media != null) && (_initialized || !(_media is Loader)); } /** * Get the media. If the media was loaded using a URL, this will * likely be the Loader object holding the real media. */ public function getMedia () :DisplayObject { return _media; } /** * Configure the media to display. */ public function setMedia (url :String) :void { if (Util.equals(_url, url)) { return; // no change } _url = url; // shutdown any previous media if (_media != null) { shutdown(false); } // set up the new media willShowNewMedia(); if (StringUtil.endsWith(url.toLowerCase(), ".flv")) { setupVideo(url); } else { setupSwfOrImage(url); } } /** * Configure our media as an instance of the specified class. */ public function setMediaClass (clazz :Class) :void { setMediaObject(new clazz() as DisplayObject); } /** * Configure an already-instantiated DisplayObject as our media. */ public function setMediaObject (disp :DisplayObject) :void { _url = null; if (_media != null) { shutdown(false); } willShowNewMedia(); addChild(disp); _media = disp; updateContentDimensions(disp.width, disp.height); } /** * A place where subclasses can initialize things prior to showing * new media. */ protected function willShowNewMedia () :void { _initialized = false; } /** * Configure this sprite to show a video. */ protected function setupVideo (url :String) :void { var vid :VideoDisplayer = new VideoDisplayer(); vid.addEventListener(VideoDisplayer.SIZE_KNOWN, handleVideoSizeKnown); vid.addEventListener(VideoDisplayer.VIDEO_ERROR, handleVideoError); _media = vid; addChild(vid); vid.setup(url); } /** * Configure this sprite to show an image or flash movie. */ protected function setupSwfOrImage (url :String) :void { startedLoading(); // create our loader and set up some event listeners var loader :Loader = new Loader(); _media = loader; var info :LoaderInfo = loader.contentLoaderInfo; info.addEventListener(Event.COMPLETE, loadingComplete); info.addEventListener(Event.INIT, handleInit); info.addEventListener(IOErrorEvent.IO_ERROR, loadError); info.addEventListener(ProgressEvent.PROGRESS, loadProgress); // create a mask to prevent the media from drawing out of bounds if (getMaxContentWidth() < int.MAX_VALUE && getMaxContentHeight() < int.MAX_VALUE) { configureMask(getMaxContentWidth(), getMaxContentHeight()); } // start it loading, add it as a child loader.load(new URLRequest(url), getContext(url)); addChild(loader); try { updateContentDimensions(info.width, info.height); } catch (err :Error) { // an error is thrown trying to access these props before they're // ready } } /** * Display a 'broken image' to indicate there were troubles with * loading the media. */ protected function setupBrokenImage (w :int = -1, h :int = -1) :void { if (w == -1) { w = 100; } if (h == -1) { h = 100; } setMediaObject(ImageUtil.createErrorImage(w, h)); } /** * Get the application domain being used by this media, or null if * none or not applicable. */ public function getApplicationDomain () :ApplicationDomain { return (_media is Loader) ? (_media as Loader).contentLoaderInfo.applicationDomain : null; } /** * Unload the media we're displaying, clean up any resources. * * @param completely if true, we're going away and should stop * everything. Otherwise, we're just loading up new media. */ public function shutdown (completely :Boolean = true) :void { try { // remove the mask (but only if we added it) if (_media != null && _media.mask != null) { try { removeChild(_media.mask); _media.mask = null; } catch (argErr :ArgumentError) { // If we catch this error, it was thrown in removeChild // and means that we did not add the media's mask, // and so shouldn't remove it either. The action we // take here is NOT setting _media.mask = null. // Then, we continue happily... } } if (_media is Loader) { var loader :Loader = (_media as Loader); var url :String = loader.contentLoaderInfo.url; // remove any listeners removeListeners(loader.contentLoaderInfo); // dispose of media try { loader.close(); } catch (ioe :IOError) { // ignore } loader.unload(); removeChild(loader); log.info("Unloaded media [url=" + url + "]."); } else if (_media is VideoDisplayer) { var vid :VideoDisplayer = (_media as VideoDisplayer); vid.removeEventListener(VideoDisplayer.SIZE_KNOWN, handleVideoSizeKnown); vid.removeEventListener(VideoDisplayer.VIDEO_ERROR, handleVideoError); vid.shutdown(); removeChild(vid); } else if (_media != null) { removeChild(_media); } } catch (ioe :IOError) { log.warning("Error shutting down media: " + ioe); log.logStackTrace(ioe); } // clean everything up _w = 0; _h = 0; _media = null; } /** * Get the width of the content, bounded by the maximum. */ public function getContentWidth () :int { return Math.min(Math.abs(_w * getMediaScaleX()), getMaxContentWidth()); } /** * Get the height of the content, bounded by the maximum. */ public function getContentHeight () :int { return Math.min(Math.abs(_h * getMediaScaleY()), getMaxContentHeight()); } /** * Get the maximum allowable width for our content. */ public function getMaxContentWidth () :int { return int.MAX_VALUE; } /** * Get the maximum allowable height for our content. */ public function getMaxContentHeight () :int { return int.MAX_VALUE; } /** * Get the X scaling factor to use on the actual media. */ public function getMediaScaleX () :Number { return 1; } /** * Get the Y scaling factor to use on the actual media. */ public function getMediaScaleY () :Number { return 1; } /** * Called by MediaWrapper as notification that its size has changed. */ public function containerDimensionsUpdated (newWidth :Number, newHeight :Number) :void { // do nothing in base MediaContainer } override public function toString () :String { return "MediaContainer[url=" + _url + "]"; } /** * Return the LoaderContext that should be used to load the media * at the specified url. */ protected function getContext (url :String) :LoaderContext { if (isImage(url)) { // load images into our domain so that we can view their pixels return new LoaderContext(true, new ApplicationDomain(ApplicationDomain.currentDomain), SecurityDomain.currentDomain); } else { // share nothing, trust nothing return new LoaderContext(false, new ApplicationDomain(null), null); } } /** * Does the specified url represent an image? */ protected function isImage (url :String) :Boolean { // look at the last 4 characters in the lowercased url switch (url.toLowerCase().slice(-4)) { case ".png": case ".jpg": case ".gif": return true; default: return false; } } /** * Remove our listeners from the LoaderInfo object. */ protected function removeListeners (info :LoaderInfo) :void { info.removeEventListener(Event.COMPLETE, loadingComplete); info.removeEventListener(Event.INIT, handleInit); info.removeEventListener(IOErrorEvent.IO_ERROR, loadError); info.removeEventListener(ProgressEvent.PROGRESS, loadProgress); } /** * A callback to receive IO_ERROR events. */ protected function loadError (event :IOErrorEvent) :void { stoppedLoading(); setupBrokenImage(-1, -1); } /** * A callback to receive PROGRESS events. */ protected function loadProgress (event :ProgressEvent) :void { updateLoadingProgress(event.bytesLoaded, event.bytesTotal); var info :LoaderInfo = (event.target as LoaderInfo); try { updateContentDimensions(info.width, info.height); } catch (err :Error) { // an error is thrown trying to access these props before they're // ready } } /** * Handles video size known. */ protected function handleVideoSizeKnown (event :ValueEvent) :void { var args :Array = (event.value as Array); updateContentDimensions(int(args[0]), int(args[1])); } /** * Handles an error loading a video. */ protected function handleVideoError (event :ValueEvent) :void { log.warning("Error loading video [cause=" + event.value + "]."); stoppedLoading(); setupBrokenImage(-1, -1); } /** * Handles the INIT event for content loaded with a Loader. */ protected function handleInit (event :Event) :void { _initialized = true; } /** * Callback function to receive COMPLETE events for swfs or images. */ protected function loadingComplete (event :Event) :void { var info :LoaderInfo = (event.target as LoaderInfo); removeListeners(info); // trace("Loading complete: " + info.url + // ", childAllowsParent=" + info.childAllowsParent + // ", parentAllowsChild=" + info.parentAllowsChild + // ", sameDomain=" + info.sameDomain); updateContentDimensions(info.width, info.height); updateLoadingProgress(1, 1); stoppedLoading(); } /** * Configure the mask for this object. */ protected function configureMask (ww :int, hh :int) :void { var mask :Shape; if (_media.mask != null) { // see if the mask was added by us try { getChildIndex(_media.mask); } catch (argErr :ArgumentError) { // oy! We are not the controllers of this mask, it must // have been added by someone else. This probably means // that the _media is not a Loader, and so we should just // leave it alone with its custom mask. return; } // otherwise, it's a mask we previously configured mask = (_media.mask as Shape); } else { mask = new Shape(); // the mask must be added to the display list (which is wacky) addChild(mask); _media.mask = mask; } mask.graphics.clear(); mask.graphics.beginFill(0xFFFFFF); mask.graphics.drawRect(0, 0, ww, hh); mask.graphics.endFill(); } /** * Called during loading as we figure out how big the content we're * loading is. */ protected function updateContentDimensions (ww :int, hh :int) :void { // update our saved size, and possibly notify our container if (_w != ww || _h != hh) { _w = ww; _h = hh; contentDimensionsUpdated(); // dispatch an event to any listeners dispatchEvent(new ValueEvent(SIZE_KNOWN, [ ww, hh ])); } } /** * Called when we know the true size of the content. */ protected function contentDimensionsUpdated () :void { // nada, by default } /** * Update the graphics to indicate how much is loaded. */ protected function updateLoadingProgress ( soFar :Number, total :Number) :void { // nada, by default } /** * Called when we've started loading new media. Will not be called * for new media that does not require loading. */ protected function startedLoading () :void { // nada } /** * Called when we've stopped loading, which may be as a result of * completion, an error while loading, or early termination. */ protected function stoppedLoading () :void { // nada } /** The unaltered URL of the content we're displaying. */ protected var _url :String; /** The unscaled width of our content. */ protected var _w :int; /** The unscaled height of our content. */ protected var _h :int; /** Either a Loader or a VideoDisplay. */ protected var _media :DisplayObject; /** If we're using a Loader, true once the INIT event has been dispatched. */ protected var _initialized :Boolean; } }
Comment fixup.
Comment fixup. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@220 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
31b23137d829ac47a6a72783045164107116a621
src/justpinegames/Logi/Console.as
src/justpinegames/Logi/Console.as
package justpinegames.Logi { import com.gskinner.motion.GTweener; import flash.events.Event; import flash.desktop.Clipboard; import flash.desktop.ClipboardFormats; import flash.utils.getQualifiedClassName; import feathers.display.Sprite; import feathers.controls.Button; import feathers.controls.List; import feathers.controls.Scroller; import feathers.controls.renderers.IListItemRenderer; import feathers.controls.ScrollContainer; import feathers.controls.text.BitmapFontTextRenderer; import feathers.core.FeathersControl; import feathers.data.ListCollection; import feathers.layout.VerticalLayout; import feathers.text.BitmapFontTextFormat; import starling.core.Starling; import starling.display.Quad; import starling.events.Event; import starling.text.BitmapFont; import starling.textures.TextureSmoothing; /** * Main class, used to display console and handle its events. */ public class Console extends Sprite { private static var _console:Console; private static var _archiveOfUndisplayedLogs:Array = []; private var _consoleSettings:ConsoleSettings; private var _defaultFont:BitmapFont; private var _format:BitmapFontTextFormat; private var _formatBackground:BitmapFontTextFormat; private var _consoleContainer:Sprite; private var _hudContainer:ScrollContainer; private var _consoleHeight:Number; private var _isShown:Boolean; private var _copyButton:Button; private var _data:Array; private var _quad:Quad; private var _list:List; private const VERTICAL_PADDING: Number = 5; private const HORIZONTAL_PADDING: Number = 5; /** * You need to create the instance of this class and add it to the stage in order to use this library. * * @param consoleSettings Optional parameter which can specify the look and behaviour of the console. */ public function Console(consoleSettings:ConsoleSettings = null) { _consoleSettings = consoleSettings ? consoleSettings : new ConsoleSettings(); _console = _console ? _console : this; _data = []; _defaultFont = new BitmapFont(); _format = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.textColor); _format.letterSpacing = 2; _formatBackground = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.textBackgroundColor); _formatBackground.letterSpacing = 2; this.addEventListener(starling.events.Event.ADDED_TO_STAGE, addedToStageHandler); } public function get isShown():Boolean { return _isShown; } public function set isShown(value:Boolean):void { if (_isShown == value) { return; } _isShown = value; if (_isShown) { show(); } else { hide(); } } private function addedToStageHandler(e:starling.events.Event):void { _consoleHeight = this.stage.stageHeight * _consoleSettings.consoleSize; _isShown = false; _consoleContainer = new FeathersControl(); _consoleContainer.alpha = 0; _consoleContainer.y = -_consoleHeight; this.addChild(_consoleContainer); _quad = new Quad(this.stage.stageWidth, _consoleHeight, _consoleSettings.consoleBackground); _quad.alpha = _consoleSettings.consoleTransparency; _consoleContainer.addChild(_quad); // TODO Make the list selection work correctly. _list = new List(); _list.x = HORIZONTAL_PADDING; _list.y = VERTICAL_PADDING; _list.dataProvider = new ListCollection(_data); _list.itemRendererFactory = function():IListItemRenderer { var consoleItemRenderer:ConsoleItemRenderer = new ConsoleItemRenderer(_consoleSettings.textColor, _consoleSettings.highlightColor); consoleItemRenderer.width = _list.width; consoleItemRenderer.height = 20; return consoleItemRenderer; }; _list.onChange.add(copyLine); _consoleContainer.addChild(_list); _copyButton = new Button(); _copyButton.label = "Copy All"; _copyButton.addEventListener(starling.events.Event.ADDED, function(e:starling.events.Event):void { _copyButton.defaultLabelProperties.smoothing = TextureSmoothing.NONE; _copyButton.downLabelProperties.smoothing = TextureSmoothing.NONE; _copyButton.defaultLabelProperties.textFormat = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.textColor); _copyButton.downLabelProperties.textFormat = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.highlightColor); _copyButton.stateToSkinFunction = function(target:Object, state:Object, oldValue:Object = null):Object { return null; }; _copyButton.width = 150; _copyButton.height = 40; }); _copyButton.onPress.add(copy); _consoleContainer.addChild(_copyButton); _hudContainer = new ScrollContainer(); // TODO This should be changed to prevent the hud from even creating, not just making it invisible. if (!_consoleSettings.hudEnabled) { _hudContainer.visible = false; } _hudContainer.x = HORIZONTAL_PADDING; _hudContainer.y = VERTICAL_PADDING; _hudContainer.touchable = false; _hudContainer.layout = new VerticalLayout(); _hudContainer.scrollerProperties.verticalScrollPolicy = Scroller.SCROLL_POLICY_OFF; this.addChild(_hudContainer); this.setScreenSize(Starling.current.nativeStage.stageWidth, Starling.current.nativeStage.stageHeight); for each (var undisplayedMessage:* in _archiveOfUndisplayedLogs) { this.logMessage(undisplayedMessage); } _archiveOfUndisplayedLogs = []; Starling.current.nativeStage.addEventListener(flash.events.Event.RESIZE, function(e:flash.events.Event):void { setScreenSize(Starling.current.nativeStage.stageWidth, Starling.current.nativeStage.stageHeight); }); } private function setScreenSize(width:Number, height:Number):void { _consoleContainer.width = width; _consoleContainer.height = height; _consoleHeight = height * _consoleSettings.consoleSize; _quad.width = width; _quad.height = _consoleHeight; _copyButton.x = width - 110 - HORIZONTAL_PADDING; _copyButton.y = _consoleHeight - 33 - VERTICAL_PADDING; _list.width = this.stage.stageWidth - HORIZONTAL_PADDING * 2; _list.height = _consoleHeight - VERTICAL_PADDING * 2; if (!_isShown) { _consoleContainer.y = -_consoleHeight; } } private function show():void { _consoleContainer.visible = true; GTweener.to(_consoleContainer, _consoleSettings.animationTime, { y: 0, alpha: 1 } ); GTweener.to(_hudContainer, _consoleSettings.animationTime, { alpha: 0 } ); _isShown = true; } private function hide():void { GTweener.to(_consoleContainer, _consoleSettings.animationTime, { y: -_consoleHeight, alpha: 0 }).onComplete = function():void { _consoleContainer.visible = false; }; GTweener.to(_hudContainer, _consoleSettings.animationTime, { alpha: 1 } ); _isShown = false; } private function copyLine(list:List):void { //log(list.selectedItem.data); } /** * You can use this data to save a log to the file. * * @return Log messages joined into a String with new lines. */ public function getLogData():String { var text:String = ""; for each (var object:Object in _data) { text += object.data + "\n"; } return text; } private function copy(button:Button):void { var text:String = this.getLogData(); Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, text); } /** * Displays the message string in the console, or on the HUD if the console is hidden. * * @param message String to display */ public function logMessage(message:String):void { if (_consoleSettings.traceEnabled) { trace(message); } var labelDisplay: String = (new Date()).toLocaleTimeString() + ": " + message; _list.dataProvider.push({label: labelDisplay, data: message}); var createLabel:Function = function(text:String, format:BitmapFontTextFormat):BitmapFontTextRenderer { var label:BitmapFontTextRenderer = new BitmapFontTextRenderer(); label.addEventListener(starling.events.Event.ADDED, function(e:starling.events.Event):void { label.textFormat = format; }); label.smoothing = TextureSmoothing.NONE; label.text = text; label.validate(); return label; }; var hudLabelContainer:FeathersControl = new FeathersControl(); hudLabelContainer.width = 640; hudLabelContainer.height = 20; var addBackground:Function = function(offsetX:int, offsetY: int):void { var hudLabelBackground:BitmapFontTextRenderer = createLabel(message, _formatBackground); hudLabelBackground.x = offsetX; hudLabelBackground.y = offsetY; hudLabelContainer.addChild(hudLabelBackground); }; addBackground(0, 0); addBackground(2, 0); addBackground(0, 2); addBackground(2, 2); var hudLabel:BitmapFontTextRenderer = createLabel(message, _format); hudLabel.x += 1; hudLabel.y += 1; hudLabelContainer.addChild(hudLabel); _hudContainer.addChildAt(hudLabelContainer, 0); GTweener.to(hudLabelContainer, _consoleSettings.hudMessageFadeOutTime, { alpha: 0 }, { delay: _consoleSettings.hudMessageDisplayTime } ).onComplete = function():void { _hudContainer.removeChild(hudLabelContainer); }; // TODO use the correct API, currently there is a problem with List max vertical position. A bug in foxhole? _list.verticalScrollPosition = Math.max(_list.dataProvider.length * 20 - _list.height, 0); } /** * Returns the fist created Console instance. * * @return Console instance */ public static function getMainConsoleInstance():Console { return _console; } /** * Main log function. Usage is the same as for the trace statement. * * For data sent to the log function to be displayed, you need to first create a LogConsole instance, and add it to the Starling stage. * * @param ... arguments Variable number of arguments, which will be displayed in the log */ public static function staticLogMessage(... arguments):void { var message:String = ""; var firstTime:Boolean = true; for each (var argument:* in arguments) { var description:String; if (argument == null) { description = "[null]" } else if (!("toString" in argument)) { description = "[object " + getQualifiedClassName(argument) + "]"; } else { description = argument; } if (firstTime) { message = description; firstTime = false; } else { message += ", " + description; } } if (Console.getMainConsoleInstance() == null) { _archiveOfUndisplayedLogs.push(message); } else { Console.getMainConsoleInstance().logMessage(message); } } } }
package justpinegames.Logi { import flash.events.Event; import flash.desktop.Clipboard; import flash.desktop.ClipboardFormats; import flash.utils.getQualifiedClassName; import feathers.display.Sprite; import feathers.controls.Button; import feathers.controls.List; import feathers.controls.Scroller; import feathers.controls.renderers.IListItemRenderer; import feathers.controls.ScrollContainer; import feathers.controls.text.BitmapFontTextRenderer; import feathers.core.FeathersControl; import feathers.data.ListCollection; import feathers.layout.VerticalLayout; import feathers.text.BitmapFontTextFormat; import starling.animation.Tween; import starling.core.Starling; import starling.display.Quad; import starling.events.Event; import starling.text.BitmapFont; import starling.textures.TextureSmoothing; /** * Main class, used to display console and handle its events. */ public class Console extends Sprite { private static var _console:Console; private static var _archiveOfUndisplayedLogs:Array = []; private var _consoleSettings:ConsoleSettings; private var _defaultFont:BitmapFont; private var _format:BitmapFontTextFormat; private var _formatBackground:BitmapFontTextFormat; private var _consoleContainer:Sprite; private var _hudContainer:ScrollContainer; private var _consoleHeight:Number; private var _isShown:Boolean; private var _copyButton:Button; private var _data:Array; private var _quad:Quad; private var _list:List; private const VERTICAL_PADDING: Number = 5; private const HORIZONTAL_PADDING: Number = 5; /** * You need to create the instance of this class and add it to the stage in order to use this library. * * @param consoleSettings Optional parameter which can specify the look and behaviour of the console. */ public function Console(consoleSettings:ConsoleSettings = null) { _consoleSettings = consoleSettings ? consoleSettings : new ConsoleSettings(); _console = _console ? _console : this; _data = []; _defaultFont = new BitmapFont(); _format = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.textColor); _format.letterSpacing = 2; _formatBackground = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.textBackgroundColor); _formatBackground.letterSpacing = 2; this.addEventListener(starling.events.Event.ADDED_TO_STAGE, addedToStageHandler); } public function get isShown():Boolean { return _isShown; } public function set isShown(value:Boolean):void { if (_isShown == value) { return; } _isShown = value; if (_isShown) { show(); } else { hide(); } } private function addedToStageHandler(e:starling.events.Event):void { _consoleHeight = this.stage.stageHeight * _consoleSettings.consoleSize; _isShown = false; _consoleContainer = new FeathersControl(); _consoleContainer.alpha = 0; _consoleContainer.y = -_consoleHeight; this.addChild(_consoleContainer); _quad = new Quad(this.stage.stageWidth, _consoleHeight, _consoleSettings.consoleBackground); _quad.alpha = _consoleSettings.consoleTransparency; _consoleContainer.addChild(_quad); // TODO Make the list selection work correctly. _list = new List(); _list.x = HORIZONTAL_PADDING; _list.y = VERTICAL_PADDING; _list.dataProvider = new ListCollection(_data); _list.itemRendererFactory = function():IListItemRenderer { var consoleItemRenderer:ConsoleItemRenderer = new ConsoleItemRenderer(_consoleSettings.textColor, _consoleSettings.highlightColor); consoleItemRenderer.width = _list.width; consoleItemRenderer.height = 20; return consoleItemRenderer; }; _list.addEventListener(starling.events.Event.CHANGE, copyLine); _consoleContainer.addChild(_list); _copyButton = new Button(); _copyButton.label = "Copy All"; _copyButton.addEventListener(starling.events.Event.ADDED, function(e:starling.events.Event):void { _copyButton.defaultLabelProperties.smoothing = TextureSmoothing.NONE; _copyButton.downLabelProperties.smoothing = TextureSmoothing.NONE; _copyButton.defaultLabelProperties.textFormat = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.textColor); _copyButton.downLabelProperties.textFormat = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.highlightColor); _copyButton.stateToSkinFunction = function(target:Object, state:Object, oldValue:Object = null):Object { return null; }; _copyButton.width = 150; _copyButton.height = 40; }); _copyButton.addEventListener(starling.events.Event.SELECT, copy); _consoleContainer.addChild(_copyButton); _hudContainer = new ScrollContainer(); // TODO This should be changed to prevent the hud from even creating, not just making it invisible. if (!_consoleSettings.hudEnabled) { _hudContainer.visible = false; } _hudContainer.x = HORIZONTAL_PADDING; _hudContainer.y = VERTICAL_PADDING; _hudContainer.touchable = false; _hudContainer.layout = new VerticalLayout(); _hudContainer.scrollerProperties.verticalScrollPolicy = Scroller.SCROLL_POLICY_OFF; this.addChild(_hudContainer); this.setScreenSize(Starling.current.nativeStage.stageWidth, Starling.current.nativeStage.stageHeight); for each (var undisplayedMessage:* in _archiveOfUndisplayedLogs) { this.logMessage(undisplayedMessage); } _archiveOfUndisplayedLogs = []; Starling.current.nativeStage.addEventListener(flash.events.Event.RESIZE, function(e:flash.events.Event):void { setScreenSize(Starling.current.nativeStage.stageWidth, Starling.current.nativeStage.stageHeight); }); } private function setScreenSize(width:Number, height:Number):void { _consoleContainer.width = width; _consoleContainer.height = height; _consoleHeight = height * _consoleSettings.consoleSize; _quad.width = width; _quad.height = _consoleHeight; _copyButton.x = width - 110 - HORIZONTAL_PADDING; _copyButton.y = _consoleHeight - 33 - VERTICAL_PADDING; _list.width = this.stage.stageWidth - HORIZONTAL_PADDING * 2; _list.height = _consoleHeight - VERTICAL_PADDING * 2; if (!_isShown) { _consoleContainer.y = -_consoleHeight; } } private function show():void { _consoleContainer.visible = true; var __tween1:Tween = new Tween(_consoleContainer, _consoleSettings.animationTime); __tween1.animate("y", 0); __tween1.fadeTo(1); Starling.juggler.add(__tween1); var __tween2:Tween = new Tween(_hudContainer, _consoleSettings.animationTime); __tween2.fadeTo(0); Starling.juggler.add(__tween2); _isShown = true; } private function hide():void { var __tween1:Tween = new Tween(_consoleContainer, _consoleSettings.animationTime); __tween1.animate("y", -_consoleHeight); __tween1.fadeTo(0); __tween1.onComplete = function():void { _consoleContainer.visible = false; }; Starling.juggler.add(__tween1); var __tween2:Tween = new Tween(_hudContainer, _consoleSettings.animationTime); __tween2.fadeTo(1); Starling.juggler.add(__tween2); _isShown = false; } private function copyLine(list:List):void { //log(list.selectedItem.data); } /** * You can use this data to save a log to the file. * * @return Log messages joined into a String with new lines. */ public function getLogData():String { var text:String = ""; for each (var object:Object in _data) { text += object.data + "\n"; } return text; } private function copy(button:Button):void { var text:String = this.getLogData(); Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, text); } /** * Displays the message string in the console, or on the HUD if the console is hidden. * * @param message String to display */ public function logMessage(message:String):void { if (_consoleSettings.traceEnabled) { trace(message); } var labelDisplay: String = (new Date()).toLocaleTimeString() + ": " + message; _list.dataProvider.push({label: labelDisplay, data: message}); var createLabel:Function = function(text:String, format:BitmapFontTextFormat):BitmapFontTextRenderer { var label:BitmapFontTextRenderer = new BitmapFontTextRenderer(); label.addEventListener(starling.events.Event.ADDED, function(e:starling.events.Event):void { label.textFormat = format; }); label.smoothing = TextureSmoothing.NONE; label.text = text; label.validate(); return label; }; var hudLabelContainer:FeathersControl = new FeathersControl(); hudLabelContainer.width = 640; hudLabelContainer.height = 20; var addBackground:Function = function(offsetX:int, offsetY: int):void { var hudLabelBackground:BitmapFontTextRenderer = createLabel(message, _formatBackground); hudLabelBackground.x = offsetX; hudLabelBackground.y = offsetY; hudLabelContainer.addChild(hudLabelBackground); }; addBackground(0, 0); addBackground(2, 0); addBackground(0, 2); addBackground(2, 2); var hudLabel:BitmapFontTextRenderer = createLabel(message, _format); hudLabel.x += 1; hudLabel.y += 1; hudLabelContainer.addChild(hudLabel); _hudContainer.addChildAt(hudLabelContainer, 0); var __tween1:Tween = new Tween(hudLabelContainer, _consoleSettings.hudMessageFadeOutTime); __tween1.delay = _consoleSettings.hudMessageDisplayTime __tween1.fadeTo(0); __tween1.onComplete = function():void { _hudContainer.removeChild(hudLabelContainer); }; Starling.juggler.add(__tween1); // TODO use the correct API, currently there is a problem with List max vertical position. A bug in foxhole? _list.verticalScrollPosition = Math.max(_list.dataProvider.length * 20 - _list.height, 0); } /** * Returns the fist created Console instance. * * @return Console instance */ public static function getMainConsoleInstance():Console { return _console; } /** * Main log function. Usage is the same as for the trace statement. * * For data sent to the log function to be displayed, you need to first create a LogConsole instance, and add it to the Starling stage. * * @param ... arguments Variable number of arguments, which will be displayed in the log */ public static function staticLogMessage(... arguments):void { var message:String = ""; var firstTime:Boolean = true; for each (var argument:* in arguments) { var description:String; if (argument == null) { description = "[null]" } else if (!("toString" in argument)) { description = "[object " + getQualifiedClassName(argument) + "]"; } else { description = argument; } if (firstTime) { message = description; firstTime = false; } else { message += ", " + description; } } if (Console.getMainConsoleInstance() == null) { _archiveOfUndisplayedLogs.push(message); } else { Console.getMainConsoleInstance().logMessage(message); } } } }
Update src/justpinegames/Logi/Console.as
Update src/justpinegames/Logi/Console.as Removed GTween dependency bringing this library in line with Feathers
ActionScript
mit
justpinegames/Logi,justpinegames/Logi
d4df4dbe6c9499a826846d275d6fa05902b0ffd6
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.6.18_osmf2.0"; /** * 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.7"; /** * 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 v3.7
update version to v3.7
ActionScript
agpl-3.0
kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp
3ebd32c3450efe0724456b2950441e865a66fa25
src/com/google/analytics/core/Organic.as
src/com/google/analytics/core/Organic.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.core { import com.google.analytics.utils.Variables; /** * The Organic class. */ public class Organic { public static var throwErrors:Boolean = false; /* note: about the different objects cache it's a little crude but it allow us to search engines/referrals/keywords in O(1) instead of O(n) */ private var _sources:Array; private var _sourcesCache:Array; private var _sourcesEngine:Array; private var _ignoredReferrals:Array; private var _ignoredReferralsCache:Object; private var _ignoredKeywords:Array; private var _ignoredKeywordsCache:Object; /** * Creates a new Organic instance. */ public function Organic() { _sources = []; _sourcesCache = []; _sourcesEngine = []; _ignoredReferrals = []; _ignoredReferralsCache = {}; _ignoredKeywords = []; _ignoredKeywordsCache = {}; } /** * Indicates the count value. */ public function get count():int { return _sources.length; } /** * Indicates the Array collection of all sources. */ public function get sources():Array { return _sources; } public function get ignoredReferralsCount():int { return _ignoredReferrals.length; } public function get ignoredKeywordsCount():int { return _ignoredKeywords.length; } /** * Adds a source in the organic. */ public function addSource( engine:String, keyword:String ):void { var orgref:OrganicReferrer = new OrganicReferrer(engine, keyword); if( _sourcesCache[ orgref.toString() ] == undefined ) { _sources.push( orgref ); _sourcesCache[ orgref.toString() ] = _sources.length-1; if( _sourcesEngine[ orgref.engine ] == undefined ) { _sourcesEngine[ orgref.engine ] = [ _sources.length-1 ]; } else { _sourcesEngine[ orgref.engine ].push( _sources.length-1 ); } } else if( throwErrors ) { throw new Error( orgref.toString() + " already exists, we don't add it." ); } } public function addIgnoredReferral( referrer:String ):void { if( _ignoredReferralsCache[ referrer ] == undefined ) { _ignoredReferrals.push( referrer ); _ignoredReferralsCache[ referrer ] = _ignoredReferrals.length-1; } else if( throwErrors ) { throw new Error( "\"" + referrer + "\" already exists, we don't add it." ); } } public function addIgnoredKeyword( keyword:String ):void { if( _ignoredKeywordsCache[ keyword ] == undefined ) { _ignoredKeywords.push( keyword ); _ignoredKeywordsCache[ keyword ] = _ignoredKeywords.length-1; } else if( throwErrors ) { throw new Error( "\"" + keyword + "\" already exists, we don't add it." ); } } /** * Clear all the engines / ignored referrals / ignored keywords. */ public function clear():void { clearEngines(); clearIgnoredReferrals(); clearIgnoredKeywords(); } /** * Clear the orgnaic engines. */ public function clearEngines():void { _sources = []; _sourcesCache = []; _sourcesEngine = []; } /** * Clear the ignored referrals. */ public function clearIgnoredReferrals():void { _ignoredReferrals = []; _ignoredReferralsCache = {}; } /** * Clear the ignored keywords. */ public function clearIgnoredKeywords():void { _ignoredKeywords = []; _ignoredKeywordsCache = {}; } /** * Returns the keyword value of the organic referrer. * @return the keyword value of the organic referrer. */ public function getKeywordValue( or:OrganicReferrer, path:String ):String { var keyword:String = or.keyword; return getKeywordValueFromPath( keyword, path ); } /** * Returns a keyword value from the specified path. * @return a keyword value from the specified path. */ public static function getKeywordValueFromPath( keyword:String, path:String ):String { var value:String; if( path.indexOf( keyword+"=" ) > -1 ) { if( path.charAt(0) == "?" ) { path = path.substr(1); } path = path.split( "+" ).join( "%20" ); var vars:Variables = new Variables( path ); value = vars[keyword]; } return value; } /** * Returns the OrganicReferrer by name. * @return the OrganicReferrer by name. */ public function getReferrerByName( name:String ):OrganicReferrer { if( match( name ) ) { //by default return the first referrer found var index:int = _sourcesEngine[ name ][0]; return _sources[ index ]; } return null; } /** * Indicates if the passed referrer is in the list * of ignored referrals. */ public function isIgnoredReferral( referrer:String ):Boolean { if( _ignoredReferralsCache.hasOwnProperty( referrer ) ) { return true; } return false; } /** * Indicates if the passed keyword is in the list * of ignored keywords. */ public function isIgnoredKeyword( keyword:String ):Boolean { if( _ignoredKeywordsCache.hasOwnProperty( keyword ) ) { return true; } return false; } /** * Match the specified value. */ public function match( name:String ):Boolean { if( name == "" ) { return false; } name = name.toLowerCase(); if( _sourcesEngine[ name ] != undefined ) { return true; } return false; } } }
/* * 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.core { import com.google.analytics.utils.Variables; /** * The Organic class. */ public class Organic { public static var throwErrors:Boolean = false; /* note: about the different objects cache it's a little crude but it allow us to search engines/referrals/keywords in O(1) instead of O(n) */ private var _sources:Array; private var _sourcesCache:Array; private var _sourcesEngine:Array; private var _ignoredReferrals:Array; private var _ignoredReferralsCache:Object; private var _ignoredKeywords:Array; private var _ignoredKeywordsCache:Object; /** * Creates a new Organic instance. */ public function Organic() { _sources = []; _sourcesCache = []; _sourcesEngine = []; _ignoredReferrals = []; _ignoredReferralsCache = {}; _ignoredKeywords = []; _ignoredKeywordsCache = {}; } /** * Indicates the count value. */ public function get count():int { return _sources.length; } /** * Indicates the Array collection of all sources. */ public function get sources():Array { return _sources; } public function get ignoredReferralsCount():int { return _ignoredReferrals.length; } public function get ignoredKeywordsCount():int { return _ignoredKeywords.length; } /** * Adds a source in the organic. */ public function addSource( engine:String, keyword:String ):void { var orgref:OrganicReferrer = new OrganicReferrer(engine, keyword); if( _sourcesCache[ orgref.toString() ] == undefined ) { _sources.push( orgref ); _sourcesCache[ orgref.toString() ] = _sources.length-1; if( _sourcesEngine[ orgref.engine ] == undefined ) { _sourcesEngine[ orgref.engine ] = [ _sources.length-1 ]; } else { _sourcesEngine[ orgref.engine ].push( _sources.length-1 ); } } else if( throwErrors ) { throw new Error( orgref.toString() + " already exists, we don't add it." ); } } public function addIgnoredReferral( referrer:String ):void { if( _ignoredReferralsCache[ referrer ] == undefined ) { _ignoredReferrals.push( referrer ); _ignoredReferralsCache[ referrer ] = _ignoredReferrals.length-1; } else if( throwErrors ) { throw new Error( "\"" + referrer + "\" already exists, we don't add it." ); } } public function addIgnoredKeyword( keyword:String ):void { if( _ignoredKeywordsCache[ keyword ] == undefined ) { _ignoredKeywords.push( keyword ); _ignoredKeywordsCache[ keyword ] = _ignoredKeywords.length-1; } else if( throwErrors ) { throw new Error( "\"" + keyword + "\" already exists, we don't add it." ); } } /** * Clear all the engines / ignored referrals / ignored keywords. */ public function clear():void { clearEngines(); clearIgnoredReferrals(); clearIgnoredKeywords(); } /** * Clear the orgnaic engines. */ public function clearEngines():void { _sources = []; _sourcesCache = []; _sourcesEngine = []; } /** * Clear the ignored referrals. */ public function clearIgnoredReferrals():void { _ignoredReferrals = []; _ignoredReferralsCache = {}; } /** * Clear the ignored keywords. */ public function clearIgnoredKeywords():void { _ignoredKeywords = []; _ignoredKeywordsCache = {}; } /** * Returns the keyword value of the organic referrer. * @return the keyword value of the organic referrer. */ public function getKeywordValue( or:OrganicReferrer, path:String ):String { var keyword:String = or.keyword; return getKeywordValueFromPath( keyword, path ); } /** * Returns a keyword value from the specified path. * @return a keyword value from the specified path. */ public static function getKeywordValueFromPath( keyword:String, path:String ):String { var value:String; if( path.indexOf( keyword+"=" ) > -1 ) { if( path.charAt(0) == "?" ) { path = path.substr(1); } path = path.split( "+" ).join( "%20" ); var vars:Variables = new Variables( path ); value = vars[keyword]; } return value; } /** * Returns the OrganicReferrer by name. * @return the OrganicReferrer by name. */ public function getReferrerByName( name:String ):OrganicReferrer { if( match( name ) ) { //by default return the first referrer found var index:int = _sourcesEngine[ name ][0]; return _sources[ index ]; } return null; } /** * Indicates if the passed referrer is in the list * of ignored referrals. */ public function isIgnoredReferral( referrer:String ):Boolean { if( _ignoredReferralsCache.hasOwnProperty( referrer ) ) { return true; } return false; } /** * Indicates if the passed keyword is in the list * of ignored keywords. */ public function isIgnoredKeyword( keyword:String ):Boolean { if( _ignoredKeywordsCache.hasOwnProperty( keyword ) ) { return true; } return false; } /** * Match the specified value. */ public function match( name:String ):Boolean { if( !name ) { return false; } name = name.toLowerCase(); if( _sourcesEngine[ name ] != undefined ) { return true; } return false; } } }
fix https://code.google.com/p/gaforflash/issues/detail?id=104
fix https://code.google.com/p/gaforflash/issues/detail?id=104
ActionScript
apache-2.0
diver-in-sky/gaforflash
2817021c560a131631cf4409e1627e2372d26906
src/as/com/threerings/flex/CommandComboBox.as
src/as/com/threerings/flex/CommandComboBox.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.events.Event; import mx.controls.ComboBox; import mx.events.ListEvent; import com.threerings.util.CommandEvent; import com.threerings.util.Util; /** * A combo box that dispatches a command (or calls a function) when it is toggled. NOTE: Unlike the * other Command* controls, CommandComboBox does not guarantee that the CommandEvent is dispatched * after notifying all other listeners. */ public class CommandComboBox extends ComboBox { /** * The field of the selectedItem object used as the argument to the * command or function. If null, the entire selectedItem is passed as the argument. */ public var dataField :String = "data"; /** * Create a command combobox. * * @param cmdOrFn either a String, which will be the CommandEvent command to dispatch, * or a function, which will be called when changed. */ public function CommandComboBox (cmdOrFn :* = null) { CommandButton.validateCmd(cmdOrFn); _cmdOrFn = cmdOrFn; addEventListener(ListEvent.CHANGE, handleChange, false, int.MIN_VALUE); } /** * Set the command and argument to be issued when this button is pressed. */ public function setCommand (cmd :String) :void { _cmdOrFn = cmd; } /** * Set a callback function to call when the button is pressed. */ public function setCallback (fn :Function) :void { _cmdOrFn = fn; } /** * Set the selectedItem based on the data field. */ public function set selectedData (data :Object) :void { for (var ii :int = 0; ii < dataProvider.length; ++ii) { if (Util.equals(data, itemToData(dataProvider[ii]))) { this.selectedIndex = ii; return; } } // not found, clear the selection this.selectedIndex = -1; } /** * The value that will be passed to the command or function based on dataField and the * current selected item. */ public function get selectedData () :Object { return itemToData(this.selectedItem); } /** * Extract the data from the specified item. This can be expanded in the future * if we provide a 'dataFunction'. */ protected function itemToData (item :Object) :Object { return (dataField == null) ? item : ((item == null) ? null : item[dataField]); } protected function handleChange (event :ListEvent) :void { if (this.selectedIndex != -1) { CommandEvent.dispatch(this, _cmdOrFn, selectedData); } } /** The command (String) to submit, or the function (Function) to call * when changed, */ protected var _cmdOrFn :Object; } }
// // $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.events.Event; import mx.controls.ComboBox; import mx.events.ListEvent; import com.threerings.util.CommandEvent; import com.threerings.util.Util; /** * A combo box that dispatches a command (or calls a callback) when an item is selected. * The argument will be the 'data' value of the selected item. * NOTE: Unlike the other Command* controls, CommandComboBox allows a null cmd/callback * to be specified. */ public class CommandComboBox extends ComboBox { /** The field of the selectedItem object used as the 'data'. If this property is null, * then the item is the data. */ public var dataField :String = "data"; /** * Create a command combobox. * * @param cmdOrFn either a String, which will be the CommandEvent command to dispatch, * or a function, which will be called when changed. */ public function CommandComboBox (cmdOrFn :* = null) { CommandButton.validateCmd(cmdOrFn); _cmdOrFn = cmdOrFn; addEventListener(ListEvent.CHANGE, handleChange, false, int.MIN_VALUE); } /** * Set the command and argument to be issued when this button is pressed. */ public function setCommand (cmd :String) :void { _cmdOrFn = cmd; } /** * Set a callback function to call when the button is pressed. */ public function setCallback (fn :Function) :void { _cmdOrFn = fn; } /** * Set the selectedItem based on the data field. */ public function set selectedData (data :Object) :void { for (var ii :int = 0; ii < dataProvider.length; ++ii) { if (Util.equals(data, itemToData(dataProvider[ii]))) { this.selectedIndex = ii; return; } } // not found, clear the selection this.selectedIndex = -1; } /** * The value that will be passed to the command or function based on dataField and the * current selected item. */ public function get selectedData () :Object { return itemToData(this.selectedItem); } /** * Extract the data from the specified item. This can be expanded in the future * if we provide a 'dataFunction'. */ protected function itemToData (item :Object) :Object { return (item == null || dataField == null) ? item : item[dataField]; } protected function handleChange (event :ListEvent) :void { if (_cmdOrFn != null && this.selectedIndex != -1) { CommandEvent.dispatch(this, _cmdOrFn, selectedData); } } /** The command (String) to submit, or the function (Function) to call * when changed, */ protected var _cmdOrFn :Object; } }
Allow to be used without a command. Alternatively, I could create a DataComboBox that just does the cool 'data' stuff, and have CommandComboBox extend that. Comment cleanups.
Allow to be used without a command. Alternatively, I could create a DataComboBox that just does the cool 'data' stuff, and have CommandComboBox extend that. Comment cleanups. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@746 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
09190478063ccef00e6cf398e29e0ae13cb00db0
src/battlecode/client/viewer/render/DrawHUD.as
src/battlecode/client/viewer/render/DrawHUD.as
package battlecode.client.viewer.render { import battlecode.client.viewer.MatchController; import battlecode.common.RobotType; import battlecode.common.Team; import battlecode.events.MatchEvent; import battlecode.serial.Match; import flash.filters.DropShadowFilter; import mx.containers.Canvas; import mx.containers.VBox; import mx.controls.Label; import mx.events.ResizeEvent; public class DrawHUD extends VBox { private var controller:MatchController; private var team:String; private var pointLabel:Label; private var hqBox:DrawHUDHQ; private var researchBoxes:Array; private var unitBoxes:Array; private var winMarkerCanvas:Canvas; private var lastRound:uint = 0; public function DrawHUD(controller:MatchController, team:String) { this.controller = controller; this.team = team; controller.addEventListener(MatchEvent.ROUND_CHANGE, onRoundChange); controller.addEventListener(MatchEvent.MATCH_CHANGE, onMatchChange); addEventListener(ResizeEvent.RESIZE, onResize); width = 180; percentHeight = 100; autoLayout = false; pointLabel = new Label(); pointLabel.width = width; pointLabel.height = 30; pointLabel.x = 0; pointLabel.y = 10; pointLabel.filters = [ new DropShadowFilter(3, 45, 0x333333, 1, 2, 2) ]; pointLabel.setStyle("color", team == Team.A ? 0xFF6666 : 0x9999FF); pointLabel.setStyle("fontSize", 24); pointLabel.setStyle("fontWeight", "bold"); pointLabel.setStyle("textAlign", "center"); pointLabel.setStyle("fontFamily", "Courier New"); winMarkerCanvas = new Canvas(); winMarkerCanvas.width = width; winMarkerCanvas.height = 40; addChild(pointLabel); hqBox = new DrawHUDHQ(); addChild(hqBox); unitBoxes = new Array(); for each (var unit:String in RobotType.ground()) { var unitBox:DrawHUDUnit = new DrawHUDUnit(unit, team); unitBoxes.push(unitBox); addChild(unitBox); } addChild(winMarkerCanvas); repositionWinMarkers(); resizeHQBox(); drawResearchBoxes(); drawUnitCounts(); } private function onRoundChange(e:MatchEvent):void { pointLabel.text = String(controller.currentState.getPoints(team)); if (e.currentRound <= lastRound) { hqBox.removeRobot(); drawWinMarkers(); } lastRound = e.currentRound; var hq:DrawRobot = controller.currentState.getHQ(team); if (hq && hq.isAlive()) { hqBox.setRobot(hq); hq.draw(); } for each (var unitBox:DrawHUDUnit in unitBoxes) { unitBox.setCount(controller.currentState.getUnitCount(unitBox.getType(), team)); } drawUnitCounts(); if (controller.currentRound == controller.match.getRounds()) { drawWinMarkers(); } } private function onMatchChange(e:MatchEvent):void { pointLabel.text = "0"; hqBox.removeRobot(); drawWinMarkers(); drawResearchBoxes(); } private function resizeHQBox():void { var boxSize:Number = Math.min(100, (height - 70 - pointLabel.height - winMarkerCanvas.height) - 20); hqBox.resize(boxSize); hqBox.x = (180 - boxSize) / 2; hqBox.y = 50; } private function drawResearchBoxes():void { var i:uint = 0; var bottomUnitBox:DrawHUDUnit = unitBoxes[unitBoxes.length - 1]; var top:Number = bottomUnitBox.y + bottomUnitBox.height + 10; } private function drawUnitCounts():void { var top:Number = hqBox.height + hqBox.y + 10; var i:uint = 0; for each (var unitBox:DrawHUDUnit in unitBoxes) { unitBox.x = (180 - unitBox.width * 3) / 2 + (i % 3) * unitBox.width; unitBox.y = ((unitBox.height + 10) * Math.floor(i / 3)) + top; i++; } } private function drawWinMarkers():void { var matches:Vector.<Match> = controller.getMatches(); winMarkerCanvas.graphics.clear(); var i:uint, wins:uint = 0; var numMatches:int = (controller.currentRound == controller.match.getRounds()) ? controller.currentMatch : controller.currentMatch - 1; for (i = 0; i <= numMatches; i++) { if (matches[i].getWinner() == team) { var x:Number = (winMarkerCanvas.height - 5) / 2 + wins * winMarkerCanvas.height + 30; var y:Number = (winMarkerCanvas.height - 5) / 2; var r:Number = (winMarkerCanvas.height - 5) / 2; winMarkerCanvas.graphics.lineStyle(2, 0x000000); winMarkerCanvas.graphics.beginFill((team == Team.A) ? 0xFF6666 : 0x9999FF); winMarkerCanvas.graphics.drawCircle(x, y, r); winMarkerCanvas.graphics.endFill(); wins++; } } } private function repositionWinMarkers():void { winMarkerCanvas.y = height - winMarkerCanvas.height - 20; } private function onResize(e:ResizeEvent):void { repositionWinMarkers(); resizeHQBox(); drawResearchBoxes(); drawUnitCounts(); } } }
package battlecode.client.viewer.render { import battlecode.client.viewer.MatchController; import battlecode.common.RobotType; import battlecode.common.Team; import battlecode.events.MatchEvent; import battlecode.serial.Match; import flash.filters.DropShadowFilter; import mx.containers.Canvas; import mx.containers.VBox; import mx.controls.Label; import mx.events.ResizeEvent; import mx.formatters.NumberFormatter; public class DrawHUD extends VBox { private var controller:MatchController; private var team:String; private var pointLabel:Label; private var hqBox:DrawHUDHQ; private var researchBoxes:Array; private var unitBoxes:Array; private var winMarkerCanvas:Canvas; private var lastRound:uint = 0; private var formatter:NumberFormatter; public function DrawHUD(controller:MatchController, team:String) { this.controller = controller; this.team = team; controller.addEventListener(MatchEvent.ROUND_CHANGE, onRoundChange); controller.addEventListener(MatchEvent.MATCH_CHANGE, onMatchChange); addEventListener(ResizeEvent.RESIZE, onResize); width = 180; percentHeight = 100; autoLayout = false; pointLabel = new Label(); pointLabel.width = width; pointLabel.height = 30; pointLabel.x = 0; pointLabel.y = 10; pointLabel.filters = [ new DropShadowFilter(3, 45, 0x333333, 1, 2, 2) ]; pointLabel.setStyle("color", team == Team.A ? 0xFF6666 : 0x9999FF); pointLabel.setStyle("fontSize", 24); pointLabel.setStyle("fontWeight", "bold"); pointLabel.setStyle("textAlign", "center"); pointLabel.setStyle("fontFamily", "Courier New"); winMarkerCanvas = new Canvas(); winMarkerCanvas.width = width; winMarkerCanvas.height = 40; addChild(pointLabel); hqBox = new DrawHUDHQ(); addChild(hqBox); unitBoxes = new Array(); for each (var unit:String in RobotType.ground()) { var unitBox:DrawHUDUnit = new DrawHUDUnit(unit, team); unitBoxes.push(unitBox); addChild(unitBox); } formatter = new NumberFormatter(); formatter.rounding = "down"; formatter.precision = 2; addChild(winMarkerCanvas); repositionWinMarkers(); resizeHQBox(); drawUnitCounts(); } private function onRoundChange(e:MatchEvent):void { var points:Number = controller.currentState.getPoints(team); pointLabel.text = formatter.format(points / 1000000) + "GG"; if (e.currentRound <= lastRound) { hqBox.removeRobot(); drawWinMarkers(); } lastRound = e.currentRound; var hq:DrawRobot = controller.currentState.getHQ(team); if (hq && hq.isAlive()) { hqBox.setRobot(hq); hq.draw(); } for each (var unitBox:DrawHUDUnit in unitBoxes) { unitBox.setCount(controller.currentState.getUnitCount(unitBox.getType(), team)); } drawUnitCounts(); if (controller.currentRound == controller.match.getRounds()) { drawWinMarkers(); } } private function onMatchChange(e:MatchEvent):void { pointLabel.text = "0GG"; hqBox.removeRobot(); drawWinMarkers(); } private function resizeHQBox():void { var boxSize:Number = Math.min(100, (height - 70 - pointLabel.height - winMarkerCanvas.height) - 20); hqBox.resize(boxSize); hqBox.x = (180 - boxSize) / 2; hqBox.y = 50; } private function drawUnitCounts():void { var top:Number = hqBox.height + hqBox.y + 10; var i:uint = 0; for each (var unitBox:DrawHUDUnit in unitBoxes) { unitBox.x = (180 - unitBox.width * 3) / 2 + (i % 3) * unitBox.width; unitBox.y = ((unitBox.height + 10) * Math.floor(i / 3)) + top; i++; } } private function drawWinMarkers():void { var matches:Vector.<Match> = controller.getMatches(); winMarkerCanvas.graphics.clear(); var i:uint, wins:uint = 0; var numMatches:int = (controller.currentRound == controller.match.getRounds()) ? controller.currentMatch : controller.currentMatch - 1; for (i = 0; i <= numMatches; i++) { if (matches[i].getWinner() == team) { var x:Number = (winMarkerCanvas.height - 5) / 2 + wins * winMarkerCanvas.height + 30; var y:Number = (winMarkerCanvas.height - 5) / 2; var r:Number = (winMarkerCanvas.height - 5) / 2; winMarkerCanvas.graphics.lineStyle(2, 0x000000); winMarkerCanvas.graphics.beginFill((team == Team.A) ? 0xFF6666 : 0x9999FF); winMarkerCanvas.graphics.drawCircle(x, y, r); winMarkerCanvas.graphics.endFill(); wins++; } } } private function repositionWinMarkers():void { winMarkerCanvas.y = height - winMarkerCanvas.height - 20; } private function onResize(e:ResizeEvent):void { repositionWinMarkers(); resizeHQBox(); drawUnitCounts(); } } }
format points as "GG"
format points as "GG"
ActionScript
mit
trun/battlecode-webclient
f7a828e0c4e6bc603c012e34bd880c3089eaadf1
src/as/com/threerings/presents/data/ClientObject.as
src/as/com/threerings/presents/data/ClientObject.as
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2010 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.presents.data { import com.threerings.util.Name; import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.DSet; import com.threerings.presents.dobj.DSet_Entry; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; /** * Every client in the system has an associated client object to which * only they subscribe. The client object can be used to deliver messages * solely to a particular client as well as to publish client-specific * data. */ public class ClientObject extends DObject { // AUTO-GENERATED: FIELDS START /** The field name of the <code>receivers</code> field. */ public static const RECEIVERS :String = "receivers"; // AUTO-GENERATED: FIELDS END /** The name of a message event delivered to the client when they * switch usernames (and therefore user objects). */ public static const CLOBJ_CHANGED :String = "!clobj_changed!"; /** The authenticated user name of this client. */ public var username :Name; /** Used to publish all invocation service receivers registered on * this client. */ public var receivers :DSet; /** * Returns a short string identifying this client. */ public function who () :String { return "(" + username + ":" + getOid() + ")"; } /** * Checks whether or not this client has the specified permission. * * @return null if the user has access, a fully-qualified translatable message string * indicating the reason for denial of access. * * @see PermissionPolicy */ public function checkAccess (perm :Permission, context :Object = null) :String { return _permPolicy.checkAccess(this, perm, context); } // AUTO-GENERATED: METHODS START public function addToReceivers (elem :DSet_Entry) :void { requestEntryAdd(RECEIVERS, elem); } public function removeFromReceivers (key :Object) :void { requestEntryRemove(RECEIVERS, key); } public function updateReceivers (elem :DSet_Entry) :void { requestEntryUpdate(RECEIVERS, elem); } public function setReceivers (value :DSet) :void { requestAttributeChange(RECEIVERS, value, this.receivers); this.receivers = (value == null) ? null : (value.clone() as DSet); } // AUTO-GENERATED: METHODS END // override public function writeObject (out :ObjectOutputStream) :void // { // super.writeObject(out); // out.writeObject(receivers); // } override public function readObject (ins :ObjectInputStream) :void { super.readObject(ins); username = Name(ins.readObject()); receivers = DSet(ins.readObject()); _permPolicy = PermissionPolicy(ins.readObject()); } protected var _permPolicy :PermissionPolicy; } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2010 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.presents.data { import com.threerings.util.Name; import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.DSet; import com.threerings.presents.dobj.DSet_Entry; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; /** * Every client in the system has an associated client object to which * only they subscribe. The client object can be used to deliver messages * solely to a particular client as well as to publish client-specific * data. */ public class ClientObject extends DObject { // AUTO-GENERATED: FIELDS START /** The field name of the <code>receivers</code> field. */ public static const RECEIVERS :String = "receivers"; // AUTO-GENERATED: FIELDS END /** The name of a message event delivered to the client when they * switch usernames (and therefore user objects). */ public static const CLOBJ_CHANGED :String = "!clobj_changed!"; /** The authenticated user name of this client. */ public var username :Name; /** Used to publish all invocation service receivers registered on * this client. */ public var receivers :DSet; /** * Returns a short string identifying this client. */ public function who () :String { return "(" + username + ":" + getOid() + ")"; } /** * Convenience wrapper around {@link #checkAccess(Permission)} that simply returns a boolean * indicating whether or not this client has the permission rather than an explanation. */ public function hasAccess (perm :Permission) :Boolean { return checkAccess(perm) == null; } /** * Checks whether or not this client has the specified permission. * * @return null if the user has access, a fully-qualified translatable message string * indicating the reason for denial of access. * * @see PermissionPolicy */ public function checkAccess (perm :Permission, context :Object = null) :String { return _permPolicy.checkAccess(this, perm, context); } // AUTO-GENERATED: METHODS START public function addToReceivers (elem :DSet_Entry) :void { requestEntryAdd(RECEIVERS, elem); } public function removeFromReceivers (key :Object) :void { requestEntryRemove(RECEIVERS, key); } public function updateReceivers (elem :DSet_Entry) :void { requestEntryUpdate(RECEIVERS, elem); } public function setReceivers (value :DSet) :void { requestAttributeChange(RECEIVERS, value, this.receivers); this.receivers = (value == null) ? null : (value.clone() as DSet); } // AUTO-GENERATED: METHODS END // override public function writeObject (out :ObjectOutputStream) :void // { // super.writeObject(out); // out.writeObject(receivers); // } override public function readObject (ins :ObjectInputStream) :void { super.readObject(ins); username = Name(ins.readObject()); receivers = DSet(ins.readObject()); _permPolicy = PermissionPolicy(ins.readObject()); } protected var _permPolicy :PermissionPolicy; } }
Move this convenience method up here to the ClientObject because it's... well... convenient.
Move this convenience method up here to the ClientObject because it's... well... convenient. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@6068 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
eab36f4f890b68cb195c299f354f07e9b7f2c80d
WEB-INF/lps/lfc/kernel/swf/LzInputTextSprite.as
WEB-INF/lps/lfc/kernel/swf/LzInputTextSprite.as
/** * LzInputTextSprite.as * * @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ /** * @shortdesc Used for input text. * */ var LzInputTextSprite = function(newowner, args) { this.__LZdepth = newowner.immediateparent.sprite.__LZsvdepth++; this.__LZsvdepth = 0; this.owner = newowner; this._accProps = {}; // Copied (eep!) from LzTextSprite //inherited attributes, documented in view this.fontname = args.font; this.fontsize = args.fontsize; this.fontstyle = args.fontstyle; this.sizeToHeight = false; this.yscroll = 0; this.xscroll = 0; //@field Boolean resize: text width automatically resizes when text is set. // default: false // this.resize = (args.resize == true); //////////////////////////////////////////////////////////////// this.masked = true; this.makeContainerResource(); var mc = this.__LZmovieClipRef; // create the textfield on container movieclip - give it a unique name var txtname = '$LzText'; mc.createTextField( txtname, 1, 0, 0, 100, 12 ); var textclip = mc[txtname]; //Debug.write('created', textclip, 'in', mc, txtname); this.__LZtextclip = textclip; this.__LZtextclip._accProps = this._accProps; // set a pointer back to this view from the TextField object textclip.__owner = this; textclip.__lzview = this.owner; textclip._visible = true; this.password = args.password ? true : false; textclip.password = this.password; } LzInputTextSprite.prototype = new LzTextSprite(null); /** * @access private */ LzInputTextSprite.prototype.construct = function ( parent , args ){ } LzInputTextSprite.prototype.focusable = true; LzInputTextSprite.prototype.__initTextProperties = function (args) { var textclip = this.__LZtextclip; // conditionalize this; set to false for inputtext for back compatibility with lps 2.1 textclip.html = true; textclip.selectable = args.selectable; textclip.autoSize = false; this.setMultiline( args.multiline ); //inherited attributes, documented in view this.fontname = args.font; this.fontsize = args.fontsize; this.fontstyle = args.fontstyle; this.__setFormat(); this.text = ((args['text'] != null) ? String(args.text) : ''); textclip.htmlText = this.text; textclip.background = false; // To compute our width: // + if text is multiline: // if no width is supplied, use parent width // + if text is single line: // if no width was supplied and there's no constraint, measure the text width: // if empty text content was supplied, use DEFAULT_WIDTH // (! this.owner.hassetwidth) // To compute our height: // + If height is supplied, use it. // + if no height supplied: // if single line, use font line height // else get height from flash textobject.textHeight // // FIXME [2008-11-24 ptw] (LPP-7391) kernel sprites should not be // using LzNode args directly if (! this.owner.hassetheight) { this.sizeToHeight = true; // set autoSize to get text measured textclip.autoSize = true; textclip.htmlText = "__ypgSAMPLE__"; this.height = textclip._height; textclip.htmlText = this.text; if (!this.multiline) { // But turn off autosizing for single line text, now that // we got a correct line height from flash. textclip.autoSize = false; } } else if (args['height'] != null) { textclip._height = args.height; //this.setHeight(args.height); } // Default the scrollheight to the visible height. this.scrollheight = this.height; //@field Number maxlength: maximum number of characters allowed in this field // default: null // if (args.maxlength != null) { this.setMaxLength(args.maxlength); } //@field String pattern: regexp describing set of characters allowed in this field // Restrict the characters that can be entered to a pattern // specified by a regular expression. // // Currently only the expression [ ]* enclosing a set of // characters or character ranges, preceded by an optional "^", is // supported. // // examples: [0-9]* , [a-zA-Z0-9]*, [^0-9]* // default: null // if (args.pattern != null) { this.setPattern(args.pattern); } // We do not support html in input fields. if ('enabled' in this && this.enabled) { textclip.type = 'input'; } else { textclip.type = 'dynamic'; } this.__LZtextclip.__cacheSelection = TextField.prototype.__cacheSelection; textclip.onSetFocus = TextField.prototype.__gotFocus; textclip.onKillFocus = TextField.prototype.__lostFocus; textclip.onChanged = TextField.prototype.__onChanged; this.hasFocus = false; textclip.onScroller = this.__updatefieldsize; } /** * Called from LzInputText#_gotFocusEvent() after focus was set by lz.Focus * @access private */ LzInputTextSprite.prototype.gotFocus = function () { if ( this.hasFocus ) { return; } this.select(); this.hasFocus = true; } /** * Called from LzInputText#_gotBlurEvent() after focus was cleared by lz.Focus * @access private */ LzInputTextSprite.prototype.gotBlur = function () { this.hasFocus = false; this.deselect(); } LzInputTextSprite.prototype.select = function () { var sf = targetPath(this.__LZtextclip); // calling setFocus() bashes the scroll and hscroll values, so save them var myscroll = this.__LZtextclip.scroll; var myhscroll = this.__LZtextclip.hscroll; if( Selection.getFocus() != sf ) { Selection.setFocus( sf ); } // restore the scroll and hscroll values this.__LZtextclip.scroll = myscroll; this.__LZtextclip.hscroll = myhscroll; this.__LZtextclip.background = false; } LzInputTextSprite.prototype.deselect = function () { var sf = targetPath(this.__LZtextclip); if( Selection.getFocus() == sf ) { Selection.setFocus( null ); } } /** * Register for update on every frame when the text field gets the focus. * Set the behavior of the enter key depending on whether the field is * multiline or not. * * @access private */ TextField.prototype.__gotFocus = function (oldfocus) { // scroll text fields horizontally back to start if (this.__lzview) this.__lzview.inputtextevent('onfocus'); } /** * @access private */ TextField.prototype.__lostFocus = function () { if (this['__handlelostFocusdel'] == null) this.__handlelostFocusdel = new LzDelegate(this, "__handlelostFocus"); lz.Idle.callOnIdle(this.__handlelostFocusdel); } /** * must be called after an idle event to prevent the selection from being * cleared prematurely, e.g. before a button click. If the selection is * cleared, the button doesn't send mouse events. * @access private */ TextField.prototype.__handlelostFocus = function (ignore) { if (this.__lzview) this.__lzview.inputtextevent('onblur'); } /** * Register to be called when the text field is modified. Convert this * into a LFC ontext event. * @access private */ TextField.prototype.__onChanged = function () { if (this.__lzview) { this.__owner.text = this.__owner.getText(); this.__lzview.inputtextevent('onchange', this.__owner.text); } } /** * Sets whether user can modify input text field * @param Boolean enabled: true if the text field can be edited */ LzInputTextSprite.prototype.setEnabled = function (enabled){ var mc = this.__LZtextclip; this.enabled = enabled; if (enabled) { mc.type = 'input'; } else { mc.type = 'dynamic'; } } /** * Set the html flag on this text view */ LzInputTextSprite.prototype.setHTML = function (htmlp) { this.__LZtextclip.html = htmlp; } // This is the text without any formatting LzInputTextSprite.prototype.getText = function ( ){ // We normalize swf's \r to \n return this.__LZtextclip.text.split('\r').join('\n'); } /** * If a mouse event occurs in an input text field, find the focused view */ LzInputTextSprite.findSelection = function ( ){ var ss = Selection.getFocus(); if ( ss != null ){ var focusview = eval(ss + '.__lzview'); //Debug.warn("Selection.getFocus: %w, %w, %w", focusview, ss); if ( focusview != undefined ) return focusview; } }
/** * LzInputTextSprite.as * * @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ /** * @shortdesc Used for input text. * */ var LzInputTextSprite = function(newowner, args) { this.__LZdepth = newowner.immediateparent.sprite.__LZsvdepth++; this.__LZsvdepth = 0; this.owner = newowner; this._accProps = {}; // Copied (eep!) from LzTextSprite //inherited attributes, documented in view this.fontname = args.font; this.fontsize = args.fontsize; this.fontstyle = args.fontstyle; this.sizeToHeight = false; this.yscroll = 0; this.xscroll = 0; //@field Boolean resize: text width automatically resizes when text is set. // default: false // this.resize = (args.resize == true); //////////////////////////////////////////////////////////////// this.masked = true; this.makeContainerResource(); var mc = this.__LZmovieClipRef; // create the textfield on container movieclip - give it a unique name var txtname = '$LzText'; mc.createTextField( txtname, 1, 0, 0, 100, 12 ); var textclip = mc[txtname]; //Debug.write('created', textclip, 'in', mc, txtname); this.__LZtextclip = textclip; this.__LZtextclip._accProps = this._accProps; // set a pointer back to this view from the TextField object textclip.__owner = this; textclip.__lzview = this.owner; textclip._visible = true; this.password = args.password ? true : false; textclip.password = this.password; } LzInputTextSprite.prototype = new LzTextSprite(null); /** * @access private */ LzInputTextSprite.prototype.construct = function ( parent , args ){ } LzInputTextSprite.prototype.focusable = true; LzInputTextSprite.prototype.__initTextProperties = function (args) { var textclip = this.__LZtextclip; // NOTE [2009-03-05 ptw] Input text is NOT html by default. We // used to set this to true to fudge in the font styles as markup, // but now we use the clip textFormat to do that directly. Note // that by setting this to false, the uses of htmlText below are // equivalent to using text; whereas if you enable html with // setHTML, then this should all magically work. :) textclip.html = false; textclip.selectable = args.selectable; textclip.autoSize = false; this.setMultiline( args.multiline ); //inherited attributes, documented in view this.fontname = args.font; this.fontsize = args.fontsize; this.fontstyle = args.fontstyle; this.__setFormat(); this.text = ((args['text'] != null) ? String(args.text) : ''); textclip.htmlText = this.text; textclip.background = false; // To compute our width: // + if text is multiline: // if no width is supplied, use parent width // + if text is single line: // if no width was supplied and there's no constraint, measure the text width: // if empty text content was supplied, use DEFAULT_WIDTH // (! this.owner.hassetwidth) // To compute our height: // + If height is supplied, use it. // + if no height supplied: // if single line, use font line height // else get height from flash textobject.textHeight // // FIXME [2008-11-24 ptw] (LPP-7391) kernel sprites should not be // using LzNode args directly if (! this.owner.hassetheight) { this.sizeToHeight = true; // set autoSize to get text measured textclip.autoSize = true; textclip.htmlText = "__ypgSAMPLE__"; this.height = textclip._height; textclip.htmlText = this.text; if (!this.multiline) { // But turn off autosizing for single line text, now that // we got a correct line height from flash. textclip.autoSize = false; } } else if (args['height'] != null) { textclip._height = args.height; //this.setHeight(args.height); } // Default the scrollheight to the visible height. this.scrollheight = this.height; //@field Number maxlength: maximum number of characters allowed in this field // default: null // if (args.maxlength != null) { this.setMaxLength(args.maxlength); } //@field String pattern: regexp describing set of characters allowed in this field // Restrict the characters that can be entered to a pattern // specified by a regular expression. // // Currently only the expression [ ]* enclosing a set of // characters or character ranges, preceded by an optional "^", is // supported. // // examples: [0-9]* , [a-zA-Z0-9]*, [^0-9]* // default: null // if (args.pattern != null) { this.setPattern(args.pattern); } // We do not support html in input fields. if ('enabled' in this && this.enabled) { textclip.type = 'input'; } else { textclip.type = 'dynamic'; } this.__LZtextclip.__cacheSelection = TextField.prototype.__cacheSelection; textclip.onSetFocus = TextField.prototype.__gotFocus; textclip.onKillFocus = TextField.prototype.__lostFocus; textclip.onChanged = TextField.prototype.__onChanged; this.hasFocus = false; textclip.onScroller = this.__updatefieldsize; } /** * Called from LzInputText#_gotFocusEvent() after focus was set by lz.Focus * @access private */ LzInputTextSprite.prototype.gotFocus = function () { if ( this.hasFocus ) { return; } this.select(); this.hasFocus = true; } /** * Called from LzInputText#_gotBlurEvent() after focus was cleared by lz.Focus * @access private */ LzInputTextSprite.prototype.gotBlur = function () { this.hasFocus = false; this.deselect(); } LzInputTextSprite.prototype.select = function () { var sf = targetPath(this.__LZtextclip); // calling setFocus() bashes the scroll and hscroll values, so save them var myscroll = this.__LZtextclip.scroll; var myhscroll = this.__LZtextclip.hscroll; if( Selection.getFocus() != sf ) { Selection.setFocus( sf ); } // restore the scroll and hscroll values this.__LZtextclip.scroll = myscroll; this.__LZtextclip.hscroll = myhscroll; this.__LZtextclip.background = false; } LzInputTextSprite.prototype.deselect = function () { var sf = targetPath(this.__LZtextclip); if( Selection.getFocus() == sf ) { Selection.setFocus( null ); } } /** * Register for update on every frame when the text field gets the focus. * Set the behavior of the enter key depending on whether the field is * multiline or not. * * @access private */ TextField.prototype.__gotFocus = function (oldfocus) { // scroll text fields horizontally back to start if (this.__lzview) this.__lzview.inputtextevent('onfocus'); } /** * @access private */ TextField.prototype.__lostFocus = function () { if (this['__handlelostFocusdel'] == null) this.__handlelostFocusdel = new LzDelegate(this, "__handlelostFocus"); lz.Idle.callOnIdle(this.__handlelostFocusdel); } /** * must be called after an idle event to prevent the selection from being * cleared prematurely, e.g. before a button click. If the selection is * cleared, the button doesn't send mouse events. * @access private */ TextField.prototype.__handlelostFocus = function (ignore) { if (this.__lzview) this.__lzview.inputtextevent('onblur'); } /** * Register to be called when the text field is modified. Convert this * into a LFC ontext event. * @access private */ TextField.prototype.__onChanged = function () { if (this.__lzview) { this.__owner.text = this.__owner.getText(); this.__lzview.inputtextevent('onchange', this.__owner.text); } } /** * Sets whether user can modify input text field * @param Boolean enabled: true if the text field can be edited */ LzInputTextSprite.prototype.setEnabled = function (enabled){ var mc = this.__LZtextclip; this.enabled = enabled; if (enabled) { mc.type = 'input'; } else { mc.type = 'dynamic'; } } /** * Set the html flag on this text view */ LzInputTextSprite.prototype.setHTML = function (htmlp) { this.__LZtextclip.html = htmlp; } // This is the text without any formatting // NOTE [2009-03-05 ptw] Which is presumably what you want. If you // enable html with setHTML, you still will get the text without // formatting. But, how would you enter formatting in an input field // anyways? This is not a rich-edit-text doo-dad. LzInputTextSprite.prototype.getText = function ( ){ // We normalize swf's \r to \n return this.__LZtextclip.text.split('\r').join('\n'); } /** * If a mouse event occurs in an input text field, find the focused view */ LzInputTextSprite.findSelection = function ( ){ var ss = Selection.getFocus(); if ( ss != null ){ var focusview = eval(ss + '.__lzview'); //Debug.warn("Selection.getFocus: %w, %w, %w", focusview, ss); if ( focusview != undefined ) return focusview; } }
Change 20090305-ptw-u by [email protected] on 2009-03-05 17:21:04 EST in /Users/ptw/OpenLaszlo/trunk-3 for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20090305-ptw-u by [email protected] on 2009-03-05 17:21:04 EST in /Users/ptw/OpenLaszlo/trunk-3 for http://svn.openlaszlo.org/openlaszlo/trunk Summary: Fix regression in input text: should not interpret HTML markup Bugs Fixed: LPP-7857 html tags not showing in inputtext Technical Reviewer: hminsky, [email protected] (Message-ID: <[email protected]>, pending) QA Reviewer: aalappat (pending) Details: html should be off by default in input text Tests: Text case from bug git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@13195 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
ec2f68e15a55b57f8a7c8f04dc703c63eaca21dd
src/aerys/minko/render/material/phong/PhongShader.as
src/aerys/minko/render/material/phong/PhongShader.as
package aerys.minko.render.material.phong { import aerys.minko.render.RenderTarget; import aerys.minko.render.material.basic.BasicShader; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.part.phong.LightAwareDiffuseShaderPart; import aerys.minko.render.shader.part.phong.PhongShaderPart; public class PhongShader extends BasicShader { private var _diffuse : LightAwareDiffuseShaderPart; private var _phong : PhongShaderPart; public function PhongShader(renderTarget : RenderTarget = null, priority : Number = 0.) { super(renderTarget, priority); // init shader parts _diffuse = new LightAwareDiffuseShaderPart(this); _phong = new PhongShaderPart(this); } override protected function getPixelColor() : SFloat { var color : SFloat = _diffuse.getDiffuseColor(); var lighting : SFloat = _phong.getLightingColor(); color = float4(multiply(lighting, color.rgb), color.a); return color; } } }
package aerys.minko.render.material.phong { import aerys.minko.render.RenderTarget; import aerys.minko.render.material.basic.BasicShader; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.part.phong.LightAwareDiffuseShaderPart; import aerys.minko.render.shader.part.phong.PhongShaderPart; public class PhongShader extends BasicShader { private var _diffuse : LightAwareDiffuseShaderPart; private var _phong : PhongShaderPart; public function PhongShader(renderTarget : RenderTarget = null, priority : Number = 0.) { super(renderTarget, priority); // init shader parts _diffuse = new LightAwareDiffuseShaderPart(this); _phong = new PhongShaderPart(this); } override protected function getPixelColor() : SFloat { var color : SFloat = _diffuse.getDiffuseColor(); var lighting : SFloat = _phong.getLightingColor(); color = float4(multiply(lighting, color.rgb), color.a); return color; } } }
remove useless imports
remove useless imports
ActionScript
mit
aerys/minko-as3
ce3d3474f920b77550ecba6cd8e68243f7866f7f
src/as/com/threerings/util/Name.as
src/as/com/threerings/util/Name.as
package com.threerings.util { import com.threerings.util.Equalable; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Streamable; public class Name extends Object implements Hashable, Streamable { public function Name (name :String = "") { _name = name; } public function getNormal () :String { if (_normal == null) { _normal = normalize(_name); } return _normal; } public function isValid () :Boolean { return !isBlank(); } public function isBlank () :Boolean { return Name.isBlank(this); } public function toString () :String { return _name; } // documentation inherited from interface Hashable public function equals (other :Object) :Boolean { return (other is Name) && (getNormal() === (other as Name).getNormal()); } // documentation inherited from interface Hashable public function hashCode () :int { var norm :String = getNormal(); var hash :int = 0; for (var ii :int = 0; ii < norm.length; ii++) { hash = (hash << 1) ^ int(norm.charCodeAt(ii)); } return hash; } // documentation inherited from interface Streamable public function writeObject (out :ObjectOutputStream) :void //throws IOError { out.writeField(_name); } // documentation inherited from interface Streamable public function readObject (ins :ObjectInputStream) :void //throws IOError { _name = (ins.readField(String) as String); } protected function normalize (txt :String) :String { return txt.toLowerCase(); } public static function isBlank (name :Name) :Boolean { return (name == null || "" === name.toString()); } /** The raw name text. */ protected var _name :String; /** The normalized name text. */ protected var _normal :String; } }
package com.threerings.util { import com.threerings.util.Equalable; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Streamable; public class Name extends Object implements Comparable, Hashable, Streamable { public function Name (name :String = "") { _name = name; } public function getNormal () :String { if (_normal == null) { _normal = normalize(_name); } return _normal; } public function isValid () :Boolean { return !isBlank(); } public function isBlank () :Boolean { return Name.isBlank(this); } public function toString () :String { return _name; } // from interface Hashable public function equals (other :Object) :Boolean { return (other is Name) && (getNormal() === (other as Name).getNormal()); } // from interface Hashable public function hashCode () :int { var norm :String = getNormal(); var hash :int = 0; for (var ii :int = 0; ii < norm.length; ii++) { hash = (hash << 1) ^ int(norm.charCodeAt(ii)); } return hash; } // from interface Comparable public function compareTo (other :Object) :int { var thisNormal :String = getNormal(); var thatNormal :String = (other as Name).getNormal(); if (thisNormal == thatNormal) { return 0; } if (thisNormal < thatNormal) { return -1; } else { return 1; } } // from interface Streamable public function writeObject (out :ObjectOutputStream) :void //throws IOError { out.writeField(_name); } // from interface Streamable public function readObject (ins :ObjectInputStream) :void //throws IOError { _name = (ins.readField(String) as String); } protected function normalize (txt :String) :String { return txt.toLowerCase(); } public static function isBlank (name :Name) :Boolean { return (name == null || "" === name.toString()); } /** The raw name text. */ protected var _name :String; /** The normalized name text. */ protected var _normal :String; } }
implement Comparable.
implement Comparable. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4270 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
3eeb88abba05290e74085ddec5d0d98af13b10f8
src/org/mangui/hls/constant/HLSLoaderTypes.as
src/org/mangui/hls/constant/HLSLoaderTypes.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.mangui.hls.constant { /** Identifiers for the different stream types. **/ public class HLSLoaderTypes { // playlist / level loader public static const LEVEL_MAIN : int = 0; // playlist / level loader public static const LEVEL_ALTAUDIO : int = 1; // main fragment loader public static const FRAGMENT_MAIN : int = 2; // alt audio fragment loader public static const FRAGMENT_ALTAUDIO : int = 3; } }
/* 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.mangui.hls.constant { /** Identifiers for the different stream types. **/ public class HLSLoaderTypes { // manifest loader public static const MANIFEST : int = 0; // playlist / level loader public static const LEVEL_MAIN : int = 1; // playlist / level loader public static const LEVEL_ALTAUDIO : int = 2; // main fragment loader public static const FRAGMENT_MAIN : int = 3; // alt audio fragment loader public static const FRAGMENT_ALTAUDIO : int = 4; } }
introduce MANIFEST loader type
introduce MANIFEST loader type
ActionScript
mpl-2.0
suuhas/flashls,mangui/flashls,aevange/flashls,Peer5/flashls,Corey600/flashls,Corey600/flashls,neilrackett/flashls,Peer5/flashls,fixedmachine/flashls,clappr/flashls,suuhas/flashls,aevange/flashls,vidible/vdb-flashls,JulianPena/flashls,mangui/flashls,jlacivita/flashls,tedconf/flashls,dighan/flashls,thdtjsdn/flashls,NicolasSiver/flashls,suuhas/flashls,tedconf/flashls,Peer5/flashls,suuhas/flashls,fixedmachine/flashls,codex-corp/flashls,NicolasSiver/flashls,hola/flashls,neilrackett/flashls,thdtjsdn/flashls,aevange/flashls,loungelogic/flashls,JulianPena/flashls,Boxie5/flashls,Boxie5/flashls,hola/flashls,loungelogic/flashls,Peer5/flashls,jlacivita/flashls,dighan/flashls,aevange/flashls,codex-corp/flashls,clappr/flashls,vidible/vdb-flashls
e09093e3f7c752c5b511907ba6a97fc71be38751
dolly-framework/src/main/actionscript/dolly/utils/CopyUtil.as
dolly-framework/src/main/actionscript/dolly/utils/CopyUtil.as
package dolly.utils { import mx.collections.ArrayCollection; public class CopyUtil { private static function copyArray(targetObj:*, propertyName:String, sourceProperty:*):void { targetObj[propertyName] = (sourceProperty as Array).slice(); } private static function copyArrayCollection(targetObj:*, propertyName:String, sourceProperty:*):void { const arrayCollection:ArrayCollection = (sourceProperty as ArrayCollection); targetObj[propertyName] = arrayCollection.source ? new ArrayCollection(arrayCollection.source.slice()) : new ArrayCollection(); } private static function copyObject(targetObj:*, propertyName:String, sourceProperty:*):void { targetObj[propertyName] = sourceProperty; } public static function copyProperty(sourceObj:*, targetObj:*, propertyName:String):void { const sourceProperty:* = sourceObj[propertyName]; if (sourceProperty is Array) { copyArray(targetObj, propertyName, sourceProperty); return; } if (sourceProperty is ArrayCollection) { copyArrayCollection(targetObj, propertyName, sourceProperty); return; } copyObject(targetObj, propertyName, sourceProperty); } public static function cloneProperty(sourceObj:*, targetObj:*, propertyName:String):void { const sourceProperty:* = sourceObj[propertyName]; if (sourceProperty is Array) { copyArray(targetObj, propertyName, sourceProperty); return; } if (sourceProperty is ArrayCollection) { copyArrayCollection(targetObj, propertyName, sourceProperty); return; } copyObject(targetObj, propertyName, sourceProperty); } } }
package dolly.utils { import mx.collections.ArrayCollection; import mx.collections.ArrayList; public class CopyUtil { private static function copyArray(targetObj:*, propertyName:String, sourceProperty:*):void { targetObj[propertyName] = (sourceProperty as Array).slice(); } private static function copyArrayList(targetObj:*, propertyName:String, arrayList:ArrayList):void { targetObj[propertyName] = arrayList.source ? new ArrayList(arrayList.source) : new ArrayList(); } private static function copyArrayCollection(targetObj:*, propertyName:String, sourceProperty:*):void { const arrayCollection:ArrayCollection = (sourceProperty as ArrayCollection); targetObj[propertyName] = arrayCollection.source ? new ArrayCollection(arrayCollection.source.slice()) : new ArrayCollection(); } private static function copyObject(targetObj:*, propertyName:String, sourceProperty:*):void { targetObj[propertyName] = sourceProperty; } public static function copyProperty(sourceObj:*, targetObj:*, propertyName:String):void { const sourceProperty:* = sourceObj[propertyName]; if (sourceProperty is Array) { copyArray(targetObj, propertyName, sourceProperty); return; } if (sourceProperty is ArrayList) { copyArrayList(targetObj, propertyName, sourceObj); return; } if (sourceProperty is ArrayCollection) { copyArrayCollection(targetObj, propertyName, sourceProperty); return; } copyObject(targetObj, propertyName, sourceProperty); } public static function cloneProperty(sourceObj:*, targetObj:*, propertyName:String):void { const sourceProperty:* = sourceObj[propertyName]; if (sourceProperty is Array) { copyArray(targetObj, propertyName, sourceProperty); return; } if (sourceProperty is ArrayList) { copyArrayList(targetObj, propertyName, sourceProperty); return; } if (sourceProperty is ArrayCollection) { copyArrayCollection(targetObj, propertyName, sourceProperty); return; } copyObject(targetObj, propertyName, sourceProperty); } } }
Add support for ArrayList type in CopyUtil.
Add support for ArrayList type in CopyUtil.
ActionScript
mit
Yarovoy/dolly
0b6d1c7cd5e702c97e7a54669389e659a174a7df
kdp3Lib/src/com/kaltura/kdpfl/view/controls/ToolTipManager.as
kdp3Lib/src/com/kaltura/kdpfl/view/controls/ToolTipManager.as
package com.kaltura.kdpfl.view.controls { import com.hybrid.ui.ToolTip; import com.kaltura.kdpfl.style.TextFormatManager; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Sprite; import flash.geom.Point; import flash.text.TextField; import flash.utils.Timer; public class ToolTipManager extends Sprite { private static var _instance:ToolTipManager; private var _labelText:TextField; private var _foregroundLayer:DisplayObjectContainer; private var _timerLapse:int=1000 private var _timer:Timer=new Timer(_timerLapse,1) private var _dataTip:ToolTip; private var _zeroPoint : Point = new Point(0,0); private var _edgeTolerance:Number = .1; private var _showHook:Boolean = false; private var _hookSize:Number = 5; private var _autoSize:Boolean = true; private var _cornerRadius:Number = 0; private var _hookAlignment:String; private var _textBuffer:Number = 10; private var _follow:Boolean = false; protected var _offsetX : Number = 0; protected var _offsetY : Number = 30; protected var _tooltipWidth : Number = 100; protected var _tooltipHeight : Number; //Tooltip delay in milliseconds protected var _delay : Number; protected var _paddingX : Number = 0; public function ToolTipManager(enforcer:Enforcer){} public static function getInstance():ToolTipManager { if(_instance == null) _instance = new ToolTipManager(new Enforcer()); return _instance; } public function set foregroundLayer(value:DisplayObjectContainer):void { _foregroundLayer = value; } public function showToolTip(message:String,target:DisplayObject):void { //Set tooltip parameters _dataTip= new ToolTip(); _dataTip.autoSize = _autoSize; _dataTip.follow = false; _dataTip.hook = _showHook; _dataTip.cornerRadius = _cornerRadius; _dataTip.hookSize = _hookSize; _dataTip.follow = _follow; if (_tooltipHeight) _dataTip.tipHeight = _tooltipHeight; if (_delay) _dataTip.delay = _delay; _dataTip.buffer = _textBuffer; //getting the possition of the stage var positionX : int = target.stage.mouseX; var targetPoint:Point=new Point(target.x,target.y); var rightLimitX : Number = target.root.parent.localToGlobal(new Point(target.root.parent.x, target.root.parent.y) ).x + target.root.parent.width; var leftLimitX : Number = target.root.parent.x; //find left rail var totalTolerancePixels:Number = target.stage.width * _edgeTolerance; if(positionX < totalTolerancePixels) _dataTip.align = "right"; else if(positionX > (target.stage.width - totalTolerancePixels)) _dataTip.align = "left"; else _dataTip.align = "center"; //override all settings it set if(!_hookAlignment) _dataTip.align = _hookAlignment; if (target.parent.localToGlobal(targetPoint).x + _tooltipWidth + offsetX > rightLimitX) { positionX = rightLimitX - tooltipWidth + offsetX + paddingX; } else if (target.parent.localToGlobal(targetPoint).x + offsetX < leftLimitX) { //In case of negative offsetX positionX = - target.parent.localToGlobal(targetPoint).x - offsetX + paddingX; } else { positionX = target.parent.localToGlobal(targetPoint).x + offsetX + paddingX; } var positionY : int = target.stage.mouseY if(target.localToGlobal(targetPoint).y - _offsetY >0) { positionY=(target.localToGlobal(targetPoint).y-_offsetY); } else { positionY=(target.localToGlobal(targetPoint).y+_offsetY); } _dataTip.titleFormat = TextFormatManager.getInstance().getTextFormat( "toolTip_label" ); //usage of new tooltip class //http://blog.hy-brid.com/flash/25/simple-as3-tooltip/ if(message!=""){ //_dataTip.show(_foregroundLayer,message,positionX,positionY,target.stage.width,target.stage.height,null) _dataTip.show(_foregroundLayer,message,null, positionX, positionY); } } public function updateTitle(value:String):void{ if(_dataTip) _dataTip.updateTitle(value); } //tooltips that fall within this percentile to side edges will receive a different hook point. //hook values "left, right, center". value in decimals public function set edgeTolerance(value : Number):void{ _edgeTolerance = value; } public function get edgeTolerance():Number{ return _edgeTolerance; } public function set textBuffer(value : Number):void{ _textBuffer = value; } public function get textBuffer():Number{ return _textBuffer; } //left, right, center. public function set hookAlignment(value : String):void{ _hookAlignment = value; } public function get hookAlignment():String{ return _hookAlignment; } public function set hookSize(value : Number):void{ _hookSize = value; } public function get hookSize():Number{ return _hookSize; } public function set showHook(value:Boolean):void{ _showHook = value; } public function get showHook():Boolean{ return _showHook; } public function set cornerRadius(value:Number):void{ _cornerRadius = value; } public function get cornerRadius():Number{ return _cornerRadius; } public function set autoSize(value:Boolean):void{ _autoSize = value; } public function get autoSize():Boolean{ return _autoSize; } public function destroyToolTip():void { if (_dataTip) _dataTip.hide() } public function get offsetX():Number { return _offsetX; } public function set offsetX(value:Number):void { _offsetX = value; } public function get follow():Boolean { return _follow; } public function set follow(value:Boolean):void { _follow = value; } public function get offsetY():Number { return _offsetY; } public function set offsetY(value:Number):void { _offsetY = value; } public function get tooltipWidth():Number { return _tooltipWidth; } public function set tooltipWidth(value:Number):void { _tooltipWidth = value; } public function get tooltipHeight():Number { return _tooltipHeight; } public function set tooltipHeight(value:Number):void { _tooltipHeight = value; } public function get delay():Number { return _delay; } public function set delay(value:Number):void { _delay = value; } public function get paddingX():Number { return _paddingX; } public function set paddingX(value:Number):void { _paddingX = value; } } } class Enforcer{}
package com.kaltura.kdpfl.view.controls { import com.hybrid.ui.ToolTip; import com.kaltura.kdpfl.style.TextFormatManager; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Sprite; import flash.geom.Point; import flash.text.TextField; import flash.utils.Timer; public class ToolTipManager extends Sprite { private static var _instance:ToolTipManager; private var _labelText:TextField; private var _foregroundLayer:DisplayObjectContainer; private var _timerLapse:int=1000 private var _timer:Timer=new Timer(_timerLapse,1) private var _dataTip:ToolTip; private var _zeroPoint : Point = new Point(0,0); private var _edgeTolerance:Number = .1; private var _showHook:Boolean = false; private var _hookSize:Number = 5; private var _autoSize:Boolean = true; private var _cornerRadius:Number = 0; private var _hookAlignment:String; private var _textBuffer:Number = 10; private var _follow:Boolean = false; protected var _offsetX : Number = 0; protected var _offsetY : Number = 30; protected var _tooltipWidth : Number = 100; protected var _tooltipHeight : Number; //Tooltip delay in milliseconds protected var _delay : Number; protected var _paddingX : Number = 0; public function ToolTipManager(enforcer:Enforcer){} public static function getInstance():ToolTipManager { if(_instance == null) _instance = new ToolTipManager(new Enforcer()); return _instance; } public function set foregroundLayer(value:DisplayObjectContainer):void { _foregroundLayer = value; } public function showToolTip(message:String,target:DisplayObject):void { //Set tooltip parameters _dataTip= new ToolTip(); _dataTip.autoSize = _autoSize; _dataTip.follow = false; _dataTip.hook = _showHook; _dataTip.cornerRadius = _cornerRadius; _dataTip.hookSize = _hookSize; _dataTip.follow = _follow; if (_tooltipHeight) _dataTip.tipHeight = _tooltipHeight; if (_delay) _dataTip.delay = _delay; _dataTip.buffer = _textBuffer; //getting the possition of the stage var positionX : int = target.stage.mouseX; var targetPoint:Point=new Point(target.x,target.y); var rightLimitX : Number = target.root.parent.localToGlobal(new Point(target.root.parent.x, target.root.parent.y) ).x + target.root.parent.width; var leftLimitX : Number = target.root.parent.x; //find left rail var totalTolerancePixels:Number = target.stage.width * _edgeTolerance; if(positionX < totalTolerancePixels) _dataTip.align = "right"; else if(positionX > (target.stage.width - totalTolerancePixels)) _dataTip.align = "left"; else _dataTip.align = "center"; //override all settings it set if(_hookAlignment) _dataTip.align = _hookAlignment; if (target.parent.localToGlobal(targetPoint).x + _tooltipWidth + offsetX > rightLimitX) { positionX = rightLimitX - tooltipWidth + offsetX + paddingX; } else if (target.parent.localToGlobal(targetPoint).x + offsetX < leftLimitX) { //In case of negative offsetX positionX = - target.parent.localToGlobal(targetPoint).x - offsetX + paddingX; } else { positionX = target.parent.localToGlobal(targetPoint).x + offsetX + paddingX; } var positionY : int = target.stage.mouseY if(target.localToGlobal(targetPoint).y - _offsetY >0) { positionY=(target.localToGlobal(targetPoint).y-_offsetY); } else { positionY=(target.localToGlobal(targetPoint).y+_offsetY); } _dataTip.titleFormat = TextFormatManager.getInstance().getTextFormat( "toolTip_label" ); //usage of new tooltip class //http://blog.hy-brid.com/flash/25/simple-as3-tooltip/ if(message!=""){ //_dataTip.show(_foregroundLayer,message,positionX,positionY,target.stage.width,target.stage.height,null) _dataTip.show(_foregroundLayer,message,null, positionX, positionY); } } public function updateTitle(value:String):void{ if(_dataTip) _dataTip.updateTitle(value); } //tooltips that fall within this percentile to side edges will receive a different hook point. //hook values "left, right, center". value in decimals public function set edgeTolerance(value : Number):void{ _edgeTolerance = value; } public function get edgeTolerance():Number{ return _edgeTolerance; } public function set textBuffer(value : Number):void{ _textBuffer = value; } public function get textBuffer():Number{ return _textBuffer; } //left, right, center. public function set hookAlignment(value : String):void{ _hookAlignment = value; } public function get hookAlignment():String{ return _hookAlignment; } public function set hookSize(value : Number):void{ _hookSize = value; } public function get hookSize():Number{ return _hookSize; } public function set showHook(value:Boolean):void{ _showHook = value; } public function get showHook():Boolean{ return _showHook; } public function set cornerRadius(value:Number):void{ _cornerRadius = value; } public function get cornerRadius():Number{ return _cornerRadius; } public function set autoSize(value:Boolean):void{ _autoSize = value; } public function get autoSize():Boolean{ return _autoSize; } public function destroyToolTip():void { if (_dataTip) _dataTip.hide() } public function get offsetX():Number { return _offsetX; } public function set offsetX(value:Number):void { _offsetX = value; } public function get follow():Boolean { return _follow; } public function set follow(value:Boolean):void { _follow = value; } public function get offsetY():Number { return _offsetY; } public function set offsetY(value:Number):void { _offsetY = value; } public function get tooltipWidth():Number { return _tooltipWidth; } public function set tooltipWidth(value:Number):void { _tooltipWidth = value; } public function get tooltipHeight():Number { return _tooltipHeight; } public function set tooltipHeight(value:Number):void { _tooltipHeight = value; } public function get delay():Number { return _delay; } public function set delay(value:Number):void { _delay = value; } public function get paddingX():Number { return _paddingX; } public function set paddingX(value:Number):void { _paddingX = value; } } } class Enforcer{}
Update kdp3Lib/src/com/kaltura/kdpfl/view/controls/ToolTipManager.as
Update kdp3Lib/src/com/kaltura/kdpfl/view/controls/ToolTipManager.as Fixed wrong logic when checking if there is a _hookAlignment
ActionScript
agpl-3.0
shvyrev/kdp,kaltura/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp
ced4dda2484d4d8dda95342385f7fec6b3d467b4
src/org/mangui/hls/stream/TagBuffer.as
src/org/mangui/hls/stream/TagBuffer.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.mangui.hls.stream { import flash.events.TimerEvent; import flash.events.Event; import flash.utils.Timer; import flash.utils.Dictionary; import org.mangui.hls.event.HLSMediatime; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.constant.HLSSeekStates; import org.mangui.hls.constant.HLSSeekMode; import org.mangui.hls.utils.Log; import org.mangui.hls.flv.FLVTag; import org.mangui.hls.HLS; import org.mangui.hls.HLSSettings; /* * intermediate FLV Tag Buffer * input : FLV tags retrieved from different fragment loaders (video/alt-audio...) * output : provide muxed FLV tags to HLSNetStream */ public class TagBuffer { private var _hls : HLS; /** Timer used to process FLV tags. **/ private var _timer : Timer; private var _audioTags : Vector.<FLVData>; private var _videoTags : Vector.<FLVData>; private var _metaTags : Vector.<FLVData>; /** playlist duration **/ private var _playlist_duration : Number = 0; /** requested start position **/ private var _seek_position_requested : Number; /** real start position , retrieved from first fragment **/ private var _seek_position_real : Number; /** start position of first injected tag **/ private var _first_start_position : Number; private var _seek_pos_reached : Boolean; /** playlist sliding (non null for live playlist) **/ private var _playlist_sliding_duration : Number; /** buffer PTS (indexed by continuity counter) */ private var _buffer_pts : Dictionary; public function TagBuffer(hls : HLS) { _hls = hls; flushAll(); _timer = new Timer(100, 0); _timer.addEventListener(TimerEvent.TIMER, _checkBuffer); _hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED, _playlistDurationUpdated); } public function dispose() : void { flushAll(); _hls.removeEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED, _playlistDurationUpdated); _timer.stop(); _hls = null; _timer = null; } public function stop() : void { flushAll(); } public function seek(position : Number) : void { _seek_position_requested = position; flushAll(); _timer.start(); } public function flushAll() : void { _audioTags = new Vector.<FLVData>(); _videoTags = new Vector.<FLVData>(); _metaTags = new Vector.<FLVData>(); _buffer_pts = new Dictionary(); _seek_pos_reached = false; _playlist_sliding_duration = 0; _first_start_position = -1; } public function flushAudio() : void { _audioTags = new Vector.<FLVData>(); } public function appendTags(tags : Vector.<FLVTag>, min_pts : Number, max_pts : Number, continuity : int, start_position : Number) : void { for each (var tag : FLVTag in tags) { var position : Number = start_position + (tag.pts - min_pts) / 1000; var tagData : FLVData = new FLVData(tag, position, continuity); switch(tag.type) { case FLVTag.AAC_HEADER: case FLVTag.AAC_RAW: case FLVTag.MP3_RAW: _audioTags.push(tagData); break; case FLVTag.AVC_HEADER: case FLVTag.AVC_NALU: _videoTags.push(tagData); break; case FLVTag.DISCONTINUITY: case FLVTag.METADATA: _metaTags.push(tagData); break; default: } } /* check live playlist sliding here : _seek_position_real + getTotalBufferedDuration() should be the start_position * /of the new fragment if the playlist was not sliding => live playlist sliding is the difference between the new start position and this previous value */ if (_hls.seekState == HLSSeekStates.SEEKED) { // Log.info("seek pos/getTotalBufferedDuration/start pos:" + _seek_position_requested + "/" + getTotalBufferedDuration() + "/" + start_position); _playlist_sliding_duration = (_first_start_position + getTotalBufferedDuration()) - start_position; } else { if (_first_start_position == -1) { // remember position of first tag injected after seek. it will be used for playlist sliding computation _first_start_position = start_position; } } // update buffer min/max table indexed with continuity counter if (_buffer_pts[continuity] == undefined) { _buffer_pts[continuity] = new BufferPTS(min_pts, max_pts); } else { (_buffer_pts[continuity] as BufferPTS).max = max_pts; } _timer.start(); } /** Return current media position **/ public function get position() : Number { switch(_hls.seekState) { case HLSSeekStates.SEEKING: return _seek_position_requested; case HLSSeekStates.SEEKED: /** Relative playback position = (Absolute Position(seek position + play time) - playlist sliding, non null for Live Playlist) **/ return _seek_position_real + _hls.stream.time - _playlist_sliding_duration; case HLSSeekStates.IDLE: default: return 0; } }; public function get audioBufferLength() : Number { return getbuflen(_audioTags); } public function get videoBufferLength() : Number { return getbuflen(_videoTags); } public function get bufferLength() : Number { return Math.max(audioBufferLength, videoBufferLength); } /** Timer **/ private function _checkBuffer(e : Event) : void { // dispatch media time event _hls.dispatchEvent(new HLSEvent(HLSEvent.MEDIA_TIME, new HLSMediatime(position, _playlist_duration, _hls.stream.bufferLength, _playlist_sliding_duration))); /* only append tags if seek position has been reached, otherwise wait for more tags to come * this is to ensure that accurate seeking will work appropriately */ if (_seek_pos_reached || max_pos >= _seek_position_requested) { var flvdata : FLVData; var data : Vector.<FLVData> = new Vector.<FLVData>(); while ((flvdata = shift()) != null) { data.push(flvdata); } if (!_seek_pos_reached) { data = seekFilterTags(data); _seek_pos_reached = true; } var tags : Vector.<FLVTag> = new Vector.<FLVTag>(); for each (flvdata in data) { tags.push(flvdata.tag); } if (tags.length) { (_hls.stream as HLSNetStream).appendTags(tags); Log.debug("appending " + tags.length + " tags"); } } } /* filter/tweak tags to seek accurately into the stream */ private function seekFilterTags(tags : Vector.<FLVData>) : Vector.<FLVData> { var filteredTags : Vector.<FLVData>= new Vector.<FLVData>(); /* PTS of first tag that will be pushed into FLV tag buffer */ var first_pts : Number; /* PTS of last video keyframe before requested seek position */ var keyframe_pts : Number; /* */ var min_offset : Number = tags[0].position; var min_pts : Number = tags[0].tag.pts; /* * * real seek requested seek Frag * position position End * *------------------*------------------------- * <------------------> * seek_offset * * real seek position is the start offset of the first received fragment after seek command. (= fragment start offset). * seek offset is the diff between the requested seek position and the real seek position */ /* if requested seek position is out of this segment bounds * all the segments will be pushed, first pts should be thus be min_pts */ if (_seek_position_requested < min_offset) { _seek_position_real = min_offset; first_pts = min_pts; } else { /* if requested position is within segment bounds, determine real seek position depending on seek mode setting */ if (HLSSettings.seekMode == HLSSeekMode.SEGMENT_SEEK) { _seek_position_real = min_offset; first_pts = min_pts; } else { /* accurate or keyframe seeking */ /* seek_pts is the requested PTS seek position */ var seek_pts : Number = min_pts + 1000 * (_seek_position_requested - min_offset); /* analyze fragment tags and look for PTS of last keyframe before seek position.*/ keyframe_pts = min_pts; for each (var flvData : FLVData in tags) { var tag : FLVTag = flvData.tag; // look for last keyframe with pts <= seek_pts if (tag.keyframe == true && tag.pts <= seek_pts && (tag.type == FLVTag.AVC_HEADER || tag.type == FLVTag.AVC_NALU)) { keyframe_pts = tag.pts; } } if (HLSSettings.seekMode == HLSSeekMode.KEYFRAME_SEEK) { _seek_position_real = min_offset + (keyframe_pts - min_pts) / 1000; first_pts = keyframe_pts; } else { // accurate seek, to exact requested position _seek_position_real = _seek_position_requested; first_pts = seek_pts; } } } /* if in segment seeking mode : push all FLV tags */ if (HLSSettings.seekMode == HLSSeekMode.SEGMENT_SEEK) { filteredTags = tags; } else { /* keyframe / accurate seeking, we need to filter out some FLV tags */ for each (flvData in tags) { tag = flvData.tag; if (tag.pts >= first_pts) { filteredTags.push(flvData); } else { switch(tag.type) { case FLVTag.AAC_HEADER: case FLVTag.AVC_HEADER: case FLVTag.METADATA: case FLVTag.DISCONTINUITY: tag.pts = tag.dts = first_pts; filteredTags.push(flvData); break; case FLVTag.AVC_NALU: /* only append video tags starting from last keyframe before seek position to avoid playback artifacts * rationale of this is that there can be multiple keyframes per segment. if we append all keyframes * in NetStream, all of them will be displayed in a row and this will introduce some playback artifacts * */ if (tag.pts >= keyframe_pts) { tag.pts = tag.dts = first_pts; filteredTags.push(flvData); } break; default: break; } } } } return filteredTags; } private function _playlistDurationUpdated(event : HLSEvent) : void { _playlist_duration = event.duration; } private function getbuflen(tags : Vector.<FLVData>) : Number { var min_pts : Number = 0; var max_pts : Number = 0; var continuity : int = -1; var len : Number = 0; for each (var data : FLVData in tags) { if (data.continuity != continuity) { len += (max_pts - min_pts); min_pts = data.tag.pts; continuity = data.continuity; } else { max_pts = data.tag.pts; } } len += (max_pts - min_pts); return len / 1000; } /** return total buffered duration since seek() call, needed to compute live playlist sliding */ private function getTotalBufferedDuration() : Number { var len : Number = 0; for each (var entry : BufferPTS in _buffer_pts) { len += (entry.max - entry.min); } return len / 1000; } /* * * return next tag from queue, using the following priority : * smallest continuity * then smallest pts * then metadata then video then audio tags */ private function shift() : FLVData { if (_videoTags.length == 0 && _audioTags.length == 0 && _metaTags.length == 0) return null; var continuity : int = int.MAX_VALUE; // find smallest continuity counter if (_metaTags.length) continuity = Math.min(continuity, _metaTags[0].continuity); if (_videoTags.length) continuity = Math.min(continuity, _videoTags[0].continuity); if (_audioTags.length) continuity = Math.min(continuity, _audioTags[0].continuity); var pts : Number = Number.MAX_VALUE; // for this continuity counter, find smallest PTS if (_metaTags.length && _metaTags[0].continuity == continuity) pts = Math.min(pts, _metaTags[0].tag.pts); if (_videoTags.length && _videoTags[0].continuity == continuity) pts = Math.min(pts, _videoTags[0].tag.pts); if (_audioTags.length && _audioTags[0].continuity == continuity) pts = Math.min(pts, _audioTags[0].tag.pts); // for this continuity counter, this PTS, prioritize tags with the following order : metadata/video/audio if (_metaTags.length && _metaTags[0].continuity == continuity && _metaTags[0].tag.pts == pts) return _metaTags.shift(); if (_videoTags.length && _videoTags[0].continuity == continuity && _videoTags[0].tag.pts == pts) return _videoTags.shift(); else return _audioTags.shift(); } /* private function get min_pos() : Number { var min_pos_ : Number = Number.POSITIVE_INFINITY; if (_metaTags.length) min_pos_ = Math.min(min_pos_, _metaTags[0].position); if (_videoTags.length) min_pos_ = Math.min(min_pos_, _videoTags[0].position); if (_audioTags.length) min_pos_ = Math.min(min_pos_, _audioTags[0].position); return min_pos_; } */ private function get max_pos() : Number { var max_pos_ : Number = Number.NEGATIVE_INFINITY; if (_metaTags.length) max_pos_ = Math.max(max_pos_, _metaTags[_metaTags.length - 1].position); if (_videoTags.length) max_pos_ = Math.max(max_pos_, _videoTags[_videoTags.length - 1].position); if (_audioTags.length) max_pos_ = Math.max(max_pos_, _audioTags[_audioTags.length - 1].position); return max_pos_; } } } import org.mangui.hls.flv.FLVTag; class FLVData { public var tag : FLVTag; public var position : Number; public var continuity : int; public function FLVData(tag : FLVTag, position : Number, continuity : int) { this.tag = tag; this.position = position; this.continuity = continuity; } } class BufferPTS { public var min : Number; public var max : Number; public function BufferPTS(min : Number, max : Number) { this.min = min; this.max = max; } }
/* 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.mangui.hls.stream { import flash.events.TimerEvent; import flash.events.Event; import flash.utils.Timer; import flash.utils.Dictionary; import org.mangui.hls.event.HLSMediatime; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.constant.HLSSeekStates; import org.mangui.hls.constant.HLSSeekMode; import org.mangui.hls.flv.FLVTag; import org.mangui.hls.HLS; import org.mangui.hls.HLSSettings; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /* * intermediate FLV Tag Buffer * input : FLV tags retrieved from different fragment loaders (video/alt-audio...) * output : provide muxed FLV tags to HLSNetStream */ public class TagBuffer { private var _hls : HLS; /** Timer used to process FLV tags. **/ private var _timer : Timer; private var _audioTags : Vector.<FLVData>; private var _videoTags : Vector.<FLVData>; private var _metaTags : Vector.<FLVData>; /** playlist duration **/ private var _playlist_duration : Number = 0; /** requested start position **/ private var _seek_position_requested : Number; /** real start position , retrieved from first fragment **/ private var _seek_position_real : Number; /** start position of first injected tag **/ private var _first_start_position : Number; private var _seek_pos_reached : Boolean; /** playlist sliding (non null for live playlist) **/ private var _playlist_sliding_duration : Number; /** buffer PTS (indexed by continuity counter) */ private var _buffer_pts : Dictionary; public function TagBuffer(hls : HLS) { _hls = hls; flushAll(); _timer = new Timer(100, 0); _timer.addEventListener(TimerEvent.TIMER, _checkBuffer); _hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED, _playlistDurationUpdated); } public function dispose() : void { flushAll(); _hls.removeEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED, _playlistDurationUpdated); _timer.stop(); _hls = null; _timer = null; } public function stop() : void { flushAll(); } public function seek(position : Number) : void { _seek_position_requested = position; flushAll(); _timer.start(); } public function flushAll() : void { _audioTags = new Vector.<FLVData>(); _videoTags = new Vector.<FLVData>(); _metaTags = new Vector.<FLVData>(); _buffer_pts = new Dictionary(); _seek_pos_reached = false; _playlist_sliding_duration = 0; _first_start_position = -1; } public function flushAudio() : void { _audioTags = new Vector.<FLVData>(); } public function appendTags(tags : Vector.<FLVTag>, min_pts : Number, max_pts : Number, continuity : int, start_position : Number) : void { for each (var tag : FLVTag in tags) { var position : Number = start_position + (tag.pts - min_pts) / 1000; var tagData : FLVData = new FLVData(tag, position, continuity); switch(tag.type) { case FLVTag.AAC_HEADER: case FLVTag.AAC_RAW: case FLVTag.MP3_RAW: _audioTags.push(tagData); break; case FLVTag.AVC_HEADER: case FLVTag.AVC_NALU: _videoTags.push(tagData); break; case FLVTag.DISCONTINUITY: case FLVTag.METADATA: _metaTags.push(tagData); break; default: } } /* check live playlist sliding here : _seek_position_real + getTotalBufferedDuration() should be the start_position * /of the new fragment if the playlist was not sliding => live playlist sliding is the difference between the new start position and this previous value */ if (_hls.seekState == HLSSeekStates.SEEKED) { // Log.info("seek pos/getTotalBufferedDuration/start pos:" + _seek_position_requested + "/" + getTotalBufferedDuration() + "/" + start_position); _playlist_sliding_duration = (_first_start_position + getTotalBufferedDuration()) - start_position; } else { if (_first_start_position == -1) { // remember position of first tag injected after seek. it will be used for playlist sliding computation _first_start_position = start_position; } } // update buffer min/max table indexed with continuity counter if (_buffer_pts[continuity] == undefined) { _buffer_pts[continuity] = new BufferPTS(min_pts, max_pts); } else { (_buffer_pts[continuity] as BufferPTS).max = max_pts; } _timer.start(); } /** Return current media position **/ public function get position() : Number { switch(_hls.seekState) { case HLSSeekStates.SEEKING: return _seek_position_requested; case HLSSeekStates.SEEKED: /** Relative playback position = (Absolute Position(seek position + play time) - playlist sliding, non null for Live Playlist) **/ return _seek_position_real + _hls.stream.time - _playlist_sliding_duration; case HLSSeekStates.IDLE: default: return 0; } }; public function get audioBufferLength() : Number { return getbuflen(_audioTags); } public function get videoBufferLength() : Number { return getbuflen(_videoTags); } public function get bufferLength() : Number { return Math.max(audioBufferLength, videoBufferLength); } /** Timer **/ private function _checkBuffer(e : Event) : void { // dispatch media time event _hls.dispatchEvent(new HLSEvent(HLSEvent.MEDIA_TIME, new HLSMediatime(position, _playlist_duration, _hls.stream.bufferLength, _playlist_sliding_duration))); /* only append tags if seek position has been reached, otherwise wait for more tags to come * this is to ensure that accurate seeking will work appropriately */ if (_seek_pos_reached || max_pos >= _seek_position_requested) { var flvdata : FLVData; var data : Vector.<FLVData> = new Vector.<FLVData>(); while ((flvdata = shift()) != null) { data.push(flvdata); } if (!_seek_pos_reached) { data = seekFilterTags(data); _seek_pos_reached = true; } var tags : Vector.<FLVTag> = new Vector.<FLVTag>(); for each (flvdata in data) { tags.push(flvdata.tag); } if (tags.length) { (_hls.stream as HLSNetStream).appendTags(tags); CONFIG::LOGGING { Log.debug2("appending " + tags.length + " tags"); } } } } /* filter/tweak tags to seek accurately into the stream */ private function seekFilterTags(tags : Vector.<FLVData>) : Vector.<FLVData> { var filteredTags : Vector.<FLVData>= new Vector.<FLVData>(); /* PTS of first tag that will be pushed into FLV tag buffer */ var first_pts : Number; /* PTS of last video keyframe before requested seek position */ var keyframe_pts : Number; /* */ var min_offset : Number = tags[0].position; var min_pts : Number = tags[0].tag.pts; /* * * real seek requested seek Frag * position position End * *------------------*------------------------- * <------------------> * seek_offset * * real seek position is the start offset of the first received fragment after seek command. (= fragment start offset). * seek offset is the diff between the requested seek position and the real seek position */ /* if requested seek position is out of this segment bounds * all the segments will be pushed, first pts should be thus be min_pts */ if (_seek_position_requested < min_offset) { _seek_position_real = min_offset; first_pts = min_pts; } else { /* if requested position is within segment bounds, determine real seek position depending on seek mode setting */ if (HLSSettings.seekMode == HLSSeekMode.SEGMENT_SEEK) { _seek_position_real = min_offset; first_pts = min_pts; } else { /* accurate or keyframe seeking */ /* seek_pts is the requested PTS seek position */ var seek_pts : Number = min_pts + 1000 * (_seek_position_requested - min_offset); /* analyze fragment tags and look for PTS of last keyframe before seek position.*/ keyframe_pts = min_pts; for each (var flvData : FLVData in tags) { var tag : FLVTag = flvData.tag; // look for last keyframe with pts <= seek_pts if (tag.keyframe == true && tag.pts <= seek_pts && (tag.type == FLVTag.AVC_HEADER || tag.type == FLVTag.AVC_NALU)) { keyframe_pts = tag.pts; } } if (HLSSettings.seekMode == HLSSeekMode.KEYFRAME_SEEK) { _seek_position_real = min_offset + (keyframe_pts - min_pts) / 1000; first_pts = keyframe_pts; } else { // accurate seek, to exact requested position _seek_position_real = _seek_position_requested; first_pts = seek_pts; } } } /* if in segment seeking mode : push all FLV tags */ if (HLSSettings.seekMode == HLSSeekMode.SEGMENT_SEEK) { filteredTags = tags; } else { /* keyframe / accurate seeking, we need to filter out some FLV tags */ for each (flvData in tags) { tag = flvData.tag; if (tag.pts >= first_pts) { filteredTags.push(flvData); } else { switch(tag.type) { case FLVTag.AAC_HEADER: case FLVTag.AVC_HEADER: case FLVTag.METADATA: case FLVTag.DISCONTINUITY: tag.pts = tag.dts = first_pts; filteredTags.push(flvData); break; case FLVTag.AVC_NALU: /* only append video tags starting from last keyframe before seek position to avoid playback artifacts * rationale of this is that there can be multiple keyframes per segment. if we append all keyframes * in NetStream, all of them will be displayed in a row and this will introduce some playback artifacts * */ if (tag.pts >= keyframe_pts) { tag.pts = tag.dts = first_pts; filteredTags.push(flvData); } break; default: break; } } } } return filteredTags; } private function _playlistDurationUpdated(event : HLSEvent) : void { _playlist_duration = event.duration; } private function getbuflen(tags : Vector.<FLVData>) : Number { var min_pts : Number = 0; var max_pts : Number = 0; var continuity : int = -1; var len : Number = 0; for each (var data : FLVData in tags) { if (data.continuity != continuity) { len += (max_pts - min_pts); min_pts = data.tag.pts; continuity = data.continuity; } else { max_pts = data.tag.pts; } } len += (max_pts - min_pts); return len / 1000; } /** return total buffered duration since seek() call, needed to compute live playlist sliding */ private function getTotalBufferedDuration() : Number { var len : Number = 0; for each (var entry : BufferPTS in _buffer_pts) { len += (entry.max - entry.min); } return len / 1000; } /* * * return next tag from queue, using the following priority : * smallest continuity * then smallest pts * then metadata then video then audio tags */ private function shift() : FLVData { if (_videoTags.length == 0 && _audioTags.length == 0 && _metaTags.length == 0) return null; var continuity : int = int.MAX_VALUE; // find smallest continuity counter if (_metaTags.length) continuity = Math.min(continuity, _metaTags[0].continuity); if (_videoTags.length) continuity = Math.min(continuity, _videoTags[0].continuity); if (_audioTags.length) continuity = Math.min(continuity, _audioTags[0].continuity); var pts : Number = Number.MAX_VALUE; // for this continuity counter, find smallest PTS if (_metaTags.length && _metaTags[0].continuity == continuity) pts = Math.min(pts, _metaTags[0].tag.pts); if (_videoTags.length && _videoTags[0].continuity == continuity) pts = Math.min(pts, _videoTags[0].tag.pts); if (_audioTags.length && _audioTags[0].continuity == continuity) pts = Math.min(pts, _audioTags[0].tag.pts); // for this continuity counter, this PTS, prioritize tags with the following order : metadata/video/audio if (_metaTags.length && _metaTags[0].continuity == continuity && _metaTags[0].tag.pts == pts) return _metaTags.shift(); if (_videoTags.length && _videoTags[0].continuity == continuity && _videoTags[0].tag.pts == pts) return _videoTags.shift(); else return _audioTags.shift(); } /* private function get min_pos() : Number { var min_pos_ : Number = Number.POSITIVE_INFINITY; if (_metaTags.length) min_pos_ = Math.min(min_pos_, _metaTags[0].position); if (_videoTags.length) min_pos_ = Math.min(min_pos_, _videoTags[0].position); if (_audioTags.length) min_pos_ = Math.min(min_pos_, _audioTags[0].position); return min_pos_; } */ private function get max_pos() : Number { var max_pos_ : Number = Number.NEGATIVE_INFINITY; if (_metaTags.length) max_pos_ = Math.max(max_pos_, _metaTags[_metaTags.length - 1].position); if (_videoTags.length) max_pos_ = Math.max(max_pos_, _videoTags[_videoTags.length - 1].position); if (_audioTags.length) max_pos_ = Math.max(max_pos_, _audioTags[_audioTags.length - 1].position); return max_pos_; } } } import org.mangui.hls.flv.FLVTag; class FLVData { public var tag : FLVTag; public var position : Number; public var continuity : int; public function FLVData(tag : FLVTag, position : Number, continuity : int) { this.tag = tag; this.position = position; this.continuity = continuity; } } class BufferPTS { public var min : Number; public var max : Number; public function BufferPTS(min : Number, max : Number) { this.min = min; this.max = max; } }
reduce log verbosity
reduce log verbosity
ActionScript
mpl-2.0
hola/flashls,aevange/flashls,suuhas/flashls,Corey600/flashls,fixedmachine/flashls,fixedmachine/flashls,jlacivita/flashls,vidible/vdb-flashls,Boxie5/flashls,Peer5/flashls,hola/flashls,aevange/flashls,dighan/flashls,aevange/flashls,neilrackett/flashls,vidible/vdb-flashls,Peer5/flashls,dighan/flashls,codex-corp/flashls,School-Improvement-Network/flashls,codex-corp/flashls,Peer5/flashls,viktorot/flashls,suuhas/flashls,thdtjsdn/flashls,tedconf/flashls,clappr/flashls,Boxie5/flashls,School-Improvement-Network/flashls,School-Improvement-Network/flashls,viktorot/flashls,jlacivita/flashls,Corey600/flashls,neilrackett/flashls,Peer5/flashls,viktorot/flashls,thdtjsdn/flashls,NicolasSiver/flashls,tedconf/flashls,suuhas/flashls,clappr/flashls,mangui/flashls,suuhas/flashls,NicolasSiver/flashls,JulianPena/flashls,loungelogic/flashls,aevange/flashls,loungelogic/flashls,mangui/flashls,JulianPena/flashls
0deb74d201a5169aff6df3b8f4ba29070660bed9
Bin/Data/Scripts/Editor/EditorSettings.as
Bin/Data/Scripts/Editor/EditorSettings.as
// Urho3D editor settings dialog bool subscribedToEditorSettings = false; Window@ settingsDialog; void CreateEditorSettingsDialog() { if (settingsDialog !is null) return; settingsDialog = ui.LoadLayout(cache.GetResource("XMLFile", "UI/EditorSettingsDialog.xml")); ui.root.AddChild(settingsDialog); settingsDialog.opacity = uiMaxOpacity; settingsDialog.height = 440; CenterDialog(settingsDialog); UpdateEditorSettingsDialog(); HideEditorSettingsDialog(); } void UpdateEditorSettingsDialog() { if (settingsDialog is null) return; LineEdit@ nearClipEdit = settingsDialog.GetChild("NearClipEdit", true); nearClipEdit.text = String(viewNearClip); LineEdit@ farClipEdit = settingsDialog.GetChild("FarClipEdit", true); farClipEdit.text = String(viewFarClip); LineEdit@ fovEdit = settingsDialog.GetChild("FOVEdit", true); fovEdit.text = String(viewFov); LineEdit@ speedEdit = settingsDialog.GetChild("SpeedEdit", true); speedEdit.text = String(cameraBaseSpeed); CheckBox@ limitRotationToggle = settingsDialog.GetChild("LimitRotationToggle", true); limitRotationToggle.checked = limitRotation; CheckBox@ mouseWheelCameraPositionToggle = settingsDialog.GetChild("MouseWheelCameraPositionToggle", true); mouseWheelCameraPositionToggle.checked = mouseWheelCameraPosition; DropDownList@ MouseOrbitEdit = settingsDialog.GetChild("MouseOrbitEdit", true); MouseOrbitEdit.selection = mouseOrbitMode; LineEdit@ distanceEdit = settingsDialog.GetChild("DistanceEdit", true); distanceEdit.text = String(newNodeDistance); LineEdit@ moveStepEdit = settingsDialog.GetChild("MoveStepEdit", true); moveStepEdit.text = String(moveStep); CheckBox@ moveSnapToggle = settingsDialog.GetChild("MoveSnapToggle", true); moveSnapToggle.checked = moveSnap; LineEdit@ rotateStepEdit = settingsDialog.GetChild("RotateStepEdit", true); rotateStepEdit.text = String(rotateStep); CheckBox@ rotateSnapToggle = settingsDialog.GetChild("RotateSnapToggle", true); rotateSnapToggle.checked = rotateSnap; LineEdit@ scaleStepEdit = settingsDialog.GetChild("ScaleStepEdit", true); scaleStepEdit.text = String(scaleStep); CheckBox@ scaleSnapToggle = settingsDialog.GetChild("ScaleSnapToggle", true); scaleSnapToggle.checked = scaleSnap; CheckBox@ applyMaterialListToggle = settingsDialog.GetChild("ApplyMaterialListToggle", true); applyMaterialListToggle.checked = applyMaterialList; CheckBox@ rememberResourcePathToggle = settingsDialog.GetChild("RememberResourcePathToggle", true); rememberResourcePathToggle.checked = rememberResourcePath; LineEdit@ importOptionsEdit = settingsDialog.GetChild("ImportOptionsEdit", true); importOptionsEdit.text = importOptions; DropDownList@ pickModeEdit = settingsDialog.GetChild("PickModeEdit", true); pickModeEdit.selection = pickMode; DropDownList@ textureQualityEdit = settingsDialog.GetChild("TextureQualityEdit", true); textureQualityEdit.selection = renderer.textureQuality; DropDownList@ materialQualityEdit = settingsDialog.GetChild("MaterialQualityEdit", true); materialQualityEdit.selection = renderer.materialQuality; DropDownList@ shadowResolutionEdit = settingsDialog.GetChild("ShadowResolutionEdit", true); shadowResolutionEdit.selection = GetShadowResolution(); DropDownList@ shadowQualityEdit = settingsDialog.GetChild("ShadowQualityEdit", true); shadowQualityEdit.selection = renderer.shadowQuality; LineEdit@ maxOccluderTrianglesEdit = settingsDialog.GetChild("MaxOccluderTrianglesEdit", true); maxOccluderTrianglesEdit.text = String(renderer.maxOccluderTriangles); CheckBox@ specularLightingToggle = settingsDialog.GetChild("SpecularLightingToggle", true); specularLightingToggle.checked = renderer.specularLighting; CheckBox@ dynamicInstancingToggle = settingsDialog.GetChild("DynamicInstancingToggle", true); dynamicInstancingToggle.checked = renderer.dynamicInstancing; CheckBox@ frameLimiterToggle = settingsDialog.GetChild("FrameLimiterToggle", true); frameLimiterToggle.checked = engine.maxFps > 0; if (!subscribedToEditorSettings) { SubscribeToEvent(nearClipEdit, "TextChanged", "EditCameraNearClip"); SubscribeToEvent(nearClipEdit, "TextFinished", "EditCameraNearClip"); SubscribeToEvent(farClipEdit, "TextChanged", "EditCameraFarClip"); SubscribeToEvent(farClipEdit, "TextFinished", "EditCameraFarClip"); SubscribeToEvent(fovEdit, "TextChanged", "EditCameraFOV"); SubscribeToEvent(fovEdit, "TextFinished", "EditCameraFOV"); SubscribeToEvent(speedEdit, "TextChanged", "EditCameraSpeed"); SubscribeToEvent(speedEdit, "TextFinished", "EditCameraSpeed"); SubscribeToEvent(limitRotationToggle, "Toggled", "EditLimitRotation"); SubscribeToEvent(mouseWheelCameraPositionToggle, "Toggled", "EditMouseWheelCameraPosition"); SubscribeToEvent(MouseOrbitEdit, "ItemSelected", "EditMouseOrbitMode"); SubscribeToEvent(distanceEdit, "TextChanged", "EditNewNodeDistance"); SubscribeToEvent(distanceEdit, "TextFinished", "EditNewNodeDistance"); SubscribeToEvent(moveStepEdit, "TextChanged", "EditMoveStep"); SubscribeToEvent(moveStepEdit, "TextFinished", "EditMoveStep"); SubscribeToEvent(rotateStepEdit, "TextChanged", "EditRotateStep"); SubscribeToEvent(rotateStepEdit, "TextFinished", "EditRotateStep"); SubscribeToEvent(scaleStepEdit, "TextChanged", "EditScaleStep"); SubscribeToEvent(scaleStepEdit, "TextFinished", "EditScaleStep"); SubscribeToEvent(moveSnapToggle, "Toggled", "EditMoveSnap"); SubscribeToEvent(rotateSnapToggle, "Toggled", "EditRotateSnap"); SubscribeToEvent(scaleSnapToggle, "Toggled", "EditScaleSnap"); SubscribeToEvent(rememberResourcePathToggle, "Toggled", "EditRememberResourcePath"); SubscribeToEvent(applyMaterialListToggle, "Toggled", "EditApplyMaterialList"); SubscribeToEvent(importOptionsEdit, "TextChanged", "EditImportOptions"); SubscribeToEvent(importOptionsEdit, "TextFinished", "EditImportOptions"); SubscribeToEvent(pickModeEdit, "ItemSelected", "EditPickMode"); SubscribeToEvent(textureQualityEdit, "ItemSelected", "EditTextureQuality"); SubscribeToEvent(materialQualityEdit, "ItemSelected", "EditMaterialQuality"); SubscribeToEvent(shadowResolutionEdit, "ItemSelected", "EditShadowResolution"); SubscribeToEvent(shadowQualityEdit, "ItemSelected", "EditShadowQuality"); SubscribeToEvent(maxOccluderTrianglesEdit, "TextChanged", "EditMaxOccluderTriangles"); SubscribeToEvent(maxOccluderTrianglesEdit, "TextFinished", "EditMaxOccluderTriangles"); SubscribeToEvent(specularLightingToggle, "Toggled", "EditSpecularLighting"); SubscribeToEvent(dynamicInstancingToggle, "Toggled", "EditDynamicInstancing"); SubscribeToEvent(frameLimiterToggle, "Toggled", "EditFrameLimiter"); SubscribeToEvent(settingsDialog.GetChild("CloseButton", true), "Released", "HideEditorSettingsDialog"); subscribedToEditorSettings = true; } } bool ShowEditorSettingsDialog() { UpdateEditorSettingsDialog(); settingsDialog.visible = true; settingsDialog.BringToFront(); return true; } void HideEditorSettingsDialog() { settingsDialog.visible = false; } void EditCameraNearClip(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); viewNearClip = edit.text.ToFloat(); UpdateViewParameters(); if (eventType == StringHash("TextFinished")) edit.text = String(camera.nearClip); } void EditCameraFarClip(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); viewFarClip = edit.text.ToFloat(); UpdateViewParameters(); if (eventType == StringHash("TextFinished")) edit.text = String(camera.farClip); } void EditCameraFOV(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); viewFov = edit.text.ToFloat(); UpdateViewParameters(); if (eventType == StringHash("TextFinished")) edit.text = String(camera.fov); } void EditCameraSpeed(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); cameraBaseSpeed = Max(edit.text.ToFloat(), 1.0); if (eventType == StringHash("TextFinished")) edit.text = String(cameraBaseSpeed); } void EditLimitRotation(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); limitRotation = edit.checked; } void EditMouseWheelCameraPosition(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); mouseWheelCameraPosition = edit.checked; } void EditMouseOrbitMode(StringHash eventType, VariantMap& eventData) { DropDownList@ edit = eventData["Element"].GetPtr(); mouseOrbitMode = edit.selection; } void EditNewNodeDistance(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); newNodeDistance = Max(edit.text.ToFloat(), 0.0); if (eventType == StringHash("TextFinished")) edit.text = String(newNodeDistance); } void EditMoveStep(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); moveStep = Max(edit.text.ToFloat(), 0.0); if (eventType == StringHash("TextFinished")) edit.text = String(moveStep); } void EditRotateStep(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); rotateStep = Max(edit.text.ToFloat(), 0.0); if (eventType == StringHash("TextFinished")) edit.text = String(rotateStep); } void EditScaleStep(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); scaleStep = Max(edit.text.ToFloat(), 0.0); if (eventType == StringHash("TextFinished")) edit.text = String(scaleStep); } void EditMoveSnap(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); moveSnap = edit.checked; toolBarDirty = true; } void EditRotateSnap(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); rotateSnap = edit.checked; toolBarDirty = true; } void EditScaleSnap(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); scaleSnap = edit.checked; toolBarDirty = true; } void EditRememberResourcePath(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); rememberResourcePath = edit.checked; } void EditApplyMaterialList(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); applyMaterialList = edit.checked; } void EditImportOptions(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); importOptions = edit.text.Trimmed(); } void EditPickMode(StringHash eventType, VariantMap& eventData) { DropDownList@ edit = eventData["Element"].GetPtr(); pickMode = edit.selection; } void EditTextureQuality(StringHash eventType, VariantMap& eventData) { DropDownList@ edit = eventData["Element"].GetPtr(); renderer.textureQuality = edit.selection; } void EditMaterialQuality(StringHash eventType, VariantMap& eventData) { DropDownList@ edit = eventData["Element"].GetPtr(); renderer.materialQuality = edit.selection; } void EditShadowResolution(StringHash eventType, VariantMap& eventData) { DropDownList@ edit = eventData["Element"].GetPtr(); SetShadowResolution(edit.selection); } void EditShadowQuality(StringHash eventType, VariantMap& eventData) { DropDownList@ edit = eventData["Element"].GetPtr(); renderer.shadowQuality = edit.selection; } void EditMaxOccluderTriangles(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); renderer.maxOccluderTriangles = edit.text.ToInt(); if (eventType == StringHash("TextFinished")) edit.text = String(renderer.maxOccluderTriangles); } void EditSpecularLighting(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); renderer.specularLighting = edit.checked; } void EditDynamicInstancing(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); renderer.dynamicInstancing = edit.checked; } void EditFrameLimiter(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); engine.maxFps = edit.checked ? 200 : 0; }
// Urho3D editor settings dialog bool subscribedToEditorSettings = false; Window@ settingsDialog; void CreateEditorSettingsDialog() { if (settingsDialog !is null) return; settingsDialog = ui.LoadLayout(cache.GetResource("XMLFile", "UI/EditorSettingsDialog.xml")); ui.root.AddChild(settingsDialog); settingsDialog.opacity = uiMaxOpacity; settingsDialog.height = 440; CenterDialog(settingsDialog); UpdateEditorSettingsDialog(); HideEditorSettingsDialog(); } void UpdateEditorSettingsDialog() { if (settingsDialog is null) return; LineEdit@ nearClipEdit = settingsDialog.GetChild("NearClipEdit", true); nearClipEdit.text = String(viewNearClip); LineEdit@ farClipEdit = settingsDialog.GetChild("FarClipEdit", true); farClipEdit.text = String(viewFarClip); LineEdit@ fovEdit = settingsDialog.GetChild("FOVEdit", true); fovEdit.text = String(viewFov); LineEdit@ speedEdit = settingsDialog.GetChild("SpeedEdit", true); speedEdit.text = String(cameraBaseSpeed); CheckBox@ limitRotationToggle = settingsDialog.GetChild("LimitRotationToggle", true); limitRotationToggle.checked = limitRotation; CheckBox@ mouseWheelCameraPositionToggle = settingsDialog.GetChild("MouseWheelCameraPositionToggle", true); mouseWheelCameraPositionToggle.checked = mouseWheelCameraPosition; DropDownList@ mouseOrbitEdit = settingsDialog.GetChild("MouseOrbitEdit", true); mouseOrbitEdit.selection = mouseOrbitMode; LineEdit@ distanceEdit = settingsDialog.GetChild("DistanceEdit", true); distanceEdit.text = String(newNodeDistance); LineEdit@ moveStepEdit = settingsDialog.GetChild("MoveStepEdit", true); moveStepEdit.text = String(moveStep); CheckBox@ moveSnapToggle = settingsDialog.GetChild("MoveSnapToggle", true); moveSnapToggle.checked = moveSnap; LineEdit@ rotateStepEdit = settingsDialog.GetChild("RotateStepEdit", true); rotateStepEdit.text = String(rotateStep); CheckBox@ rotateSnapToggle = settingsDialog.GetChild("RotateSnapToggle", true); rotateSnapToggle.checked = rotateSnap; LineEdit@ scaleStepEdit = settingsDialog.GetChild("ScaleStepEdit", true); scaleStepEdit.text = String(scaleStep); CheckBox@ scaleSnapToggle = settingsDialog.GetChild("ScaleSnapToggle", true); scaleSnapToggle.checked = scaleSnap; CheckBox@ applyMaterialListToggle = settingsDialog.GetChild("ApplyMaterialListToggle", true); applyMaterialListToggle.checked = applyMaterialList; CheckBox@ rememberResourcePathToggle = settingsDialog.GetChild("RememberResourcePathToggle", true); rememberResourcePathToggle.checked = rememberResourcePath; LineEdit@ importOptionsEdit = settingsDialog.GetChild("ImportOptionsEdit", true); importOptionsEdit.text = importOptions; DropDownList@ pickModeEdit = settingsDialog.GetChild("PickModeEdit", true); pickModeEdit.selection = pickMode; DropDownList@ textureQualityEdit = settingsDialog.GetChild("TextureQualityEdit", true); textureQualityEdit.selection = renderer.textureQuality; DropDownList@ materialQualityEdit = settingsDialog.GetChild("MaterialQualityEdit", true); materialQualityEdit.selection = renderer.materialQuality; DropDownList@ shadowResolutionEdit = settingsDialog.GetChild("ShadowResolutionEdit", true); shadowResolutionEdit.selection = GetShadowResolution(); DropDownList@ shadowQualityEdit = settingsDialog.GetChild("ShadowQualityEdit", true); shadowQualityEdit.selection = renderer.shadowQuality; LineEdit@ maxOccluderTrianglesEdit = settingsDialog.GetChild("MaxOccluderTrianglesEdit", true); maxOccluderTrianglesEdit.text = String(renderer.maxOccluderTriangles); CheckBox@ specularLightingToggle = settingsDialog.GetChild("SpecularLightingToggle", true); specularLightingToggle.checked = renderer.specularLighting; CheckBox@ dynamicInstancingToggle = settingsDialog.GetChild("DynamicInstancingToggle", true); dynamicInstancingToggle.checked = renderer.dynamicInstancing; CheckBox@ frameLimiterToggle = settingsDialog.GetChild("FrameLimiterToggle", true); frameLimiterToggle.checked = engine.maxFps > 0; if (!subscribedToEditorSettings) { SubscribeToEvent(nearClipEdit, "TextChanged", "EditCameraNearClip"); SubscribeToEvent(nearClipEdit, "TextFinished", "EditCameraNearClip"); SubscribeToEvent(farClipEdit, "TextChanged", "EditCameraFarClip"); SubscribeToEvent(farClipEdit, "TextFinished", "EditCameraFarClip"); SubscribeToEvent(fovEdit, "TextChanged", "EditCameraFOV"); SubscribeToEvent(fovEdit, "TextFinished", "EditCameraFOV"); SubscribeToEvent(speedEdit, "TextChanged", "EditCameraSpeed"); SubscribeToEvent(speedEdit, "TextFinished", "EditCameraSpeed"); SubscribeToEvent(limitRotationToggle, "Toggled", "EditLimitRotation"); SubscribeToEvent(mouseWheelCameraPositionToggle, "Toggled", "EditMouseWheelCameraPosition"); SubscribeToEvent(mouseOrbitEdit, "ItemSelected", "EditMouseOrbitMode"); SubscribeToEvent(distanceEdit, "TextChanged", "EditNewNodeDistance"); SubscribeToEvent(distanceEdit, "TextFinished", "EditNewNodeDistance"); SubscribeToEvent(moveStepEdit, "TextChanged", "EditMoveStep"); SubscribeToEvent(moveStepEdit, "TextFinished", "EditMoveStep"); SubscribeToEvent(rotateStepEdit, "TextChanged", "EditRotateStep"); SubscribeToEvent(rotateStepEdit, "TextFinished", "EditRotateStep"); SubscribeToEvent(scaleStepEdit, "TextChanged", "EditScaleStep"); SubscribeToEvent(scaleStepEdit, "TextFinished", "EditScaleStep"); SubscribeToEvent(moveSnapToggle, "Toggled", "EditMoveSnap"); SubscribeToEvent(rotateSnapToggle, "Toggled", "EditRotateSnap"); SubscribeToEvent(scaleSnapToggle, "Toggled", "EditScaleSnap"); SubscribeToEvent(rememberResourcePathToggle, "Toggled", "EditRememberResourcePath"); SubscribeToEvent(applyMaterialListToggle, "Toggled", "EditApplyMaterialList"); SubscribeToEvent(importOptionsEdit, "TextChanged", "EditImportOptions"); SubscribeToEvent(importOptionsEdit, "TextFinished", "EditImportOptions"); SubscribeToEvent(pickModeEdit, "ItemSelected", "EditPickMode"); SubscribeToEvent(textureQualityEdit, "ItemSelected", "EditTextureQuality"); SubscribeToEvent(materialQualityEdit, "ItemSelected", "EditMaterialQuality"); SubscribeToEvent(shadowResolutionEdit, "ItemSelected", "EditShadowResolution"); SubscribeToEvent(shadowQualityEdit, "ItemSelected", "EditShadowQuality"); SubscribeToEvent(maxOccluderTrianglesEdit, "TextChanged", "EditMaxOccluderTriangles"); SubscribeToEvent(maxOccluderTrianglesEdit, "TextFinished", "EditMaxOccluderTriangles"); SubscribeToEvent(specularLightingToggle, "Toggled", "EditSpecularLighting"); SubscribeToEvent(dynamicInstancingToggle, "Toggled", "EditDynamicInstancing"); SubscribeToEvent(frameLimiterToggle, "Toggled", "EditFrameLimiter"); SubscribeToEvent(settingsDialog.GetChild("CloseButton", true), "Released", "HideEditorSettingsDialog"); subscribedToEditorSettings = true; } } bool ShowEditorSettingsDialog() { UpdateEditorSettingsDialog(); settingsDialog.visible = true; settingsDialog.BringToFront(); return true; } void HideEditorSettingsDialog() { settingsDialog.visible = false; } void EditCameraNearClip(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); viewNearClip = edit.text.ToFloat(); UpdateViewParameters(); if (eventType == StringHash("TextFinished")) edit.text = String(camera.nearClip); } void EditCameraFarClip(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); viewFarClip = edit.text.ToFloat(); UpdateViewParameters(); if (eventType == StringHash("TextFinished")) edit.text = String(camera.farClip); } void EditCameraFOV(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); viewFov = edit.text.ToFloat(); UpdateViewParameters(); if (eventType == StringHash("TextFinished")) edit.text = String(camera.fov); } void EditCameraSpeed(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); cameraBaseSpeed = Max(edit.text.ToFloat(), 1.0); if (eventType == StringHash("TextFinished")) edit.text = String(cameraBaseSpeed); } void EditLimitRotation(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); limitRotation = edit.checked; } void EditMouseWheelCameraPosition(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); mouseWheelCameraPosition = edit.checked; } void EditMouseOrbitMode(StringHash eventType, VariantMap& eventData) { DropDownList@ edit = eventData["Element"].GetPtr(); mouseOrbitMode = edit.selection; } void EditNewNodeDistance(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); newNodeDistance = Max(edit.text.ToFloat(), 0.0); if (eventType == StringHash("TextFinished")) edit.text = String(newNodeDistance); } void EditMoveStep(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); moveStep = Max(edit.text.ToFloat(), 0.0); if (eventType == StringHash("TextFinished")) edit.text = String(moveStep); } void EditRotateStep(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); rotateStep = Max(edit.text.ToFloat(), 0.0); if (eventType == StringHash("TextFinished")) edit.text = String(rotateStep); } void EditScaleStep(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); scaleStep = Max(edit.text.ToFloat(), 0.0); if (eventType == StringHash("TextFinished")) edit.text = String(scaleStep); } void EditMoveSnap(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); moveSnap = edit.checked; toolBarDirty = true; } void EditRotateSnap(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); rotateSnap = edit.checked; toolBarDirty = true; } void EditScaleSnap(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); scaleSnap = edit.checked; toolBarDirty = true; } void EditRememberResourcePath(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); rememberResourcePath = edit.checked; } void EditApplyMaterialList(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); applyMaterialList = edit.checked; } void EditImportOptions(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); importOptions = edit.text.Trimmed(); } void EditPickMode(StringHash eventType, VariantMap& eventData) { DropDownList@ edit = eventData["Element"].GetPtr(); pickMode = edit.selection; } void EditTextureQuality(StringHash eventType, VariantMap& eventData) { DropDownList@ edit = eventData["Element"].GetPtr(); renderer.textureQuality = edit.selection; } void EditMaterialQuality(StringHash eventType, VariantMap& eventData) { DropDownList@ edit = eventData["Element"].GetPtr(); renderer.materialQuality = edit.selection; } void EditShadowResolution(StringHash eventType, VariantMap& eventData) { DropDownList@ edit = eventData["Element"].GetPtr(); SetShadowResolution(edit.selection); } void EditShadowQuality(StringHash eventType, VariantMap& eventData) { DropDownList@ edit = eventData["Element"].GetPtr(); renderer.shadowQuality = edit.selection; } void EditMaxOccluderTriangles(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); renderer.maxOccluderTriangles = edit.text.ToInt(); if (eventType == StringHash("TextFinished")) edit.text = String(renderer.maxOccluderTriangles); } void EditSpecularLighting(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); renderer.specularLighting = edit.checked; } void EditDynamicInstancing(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); renderer.dynamicInstancing = edit.checked; } void EditFrameLimiter(StringHash eventType, VariantMap& eventData) { CheckBox@ edit = eventData["Element"].GetPtr(); engine.maxFps = edit.checked ? 200 : 0; }
Change variable name to start with lowercase.
Change variable name to start with lowercase.
ActionScript
mit
tommy3/Urho3D,urho3d/Urho3D,MonkeyFirst/Urho3D,codedash64/Urho3D,codedash64/Urho3D,MonkeyFirst/Urho3D,MeshGeometry/Urho3D,xiliu98/Urho3D,helingping/Urho3D,weitjong/Urho3D,henu/Urho3D,tommy3/Urho3D,xiliu98/Urho3D,carnalis/Urho3D,bacsmar/Urho3D,abdllhbyrktr/Urho3D,fire/Urho3D-1,MeshGeometry/Urho3D,c4augustus/Urho3D,tommy3/Urho3D,iainmerrick/Urho3D,PredatorMF/Urho3D,fire/Urho3D-1,299299/Urho3D,bacsmar/Urho3D,helingping/Urho3D,helingping/Urho3D,kostik1337/Urho3D,rokups/Urho3D,urho3d/Urho3D,weitjong/Urho3D,orefkov/Urho3D,kostik1337/Urho3D,cosmy1/Urho3D,codemon66/Urho3D,helingping/Urho3D,luveti/Urho3D,eugeneko/Urho3D,codemon66/Urho3D,henu/Urho3D,bacsmar/Urho3D,PredatorMF/Urho3D,victorholt/Urho3D,codemon66/Urho3D,eugeneko/Urho3D,299299/Urho3D,henu/Urho3D,luveti/Urho3D,abdllhbyrktr/Urho3D,codemon66/Urho3D,MonkeyFirst/Urho3D,luveti/Urho3D,cosmy1/Urho3D,PredatorMF/Urho3D,rokups/Urho3D,cosmy1/Urho3D,victorholt/Urho3D,SirNate0/Urho3D,cosmy1/Urho3D,iainmerrick/Urho3D,MonkeyFirst/Urho3D,carnalis/Urho3D,fire/Urho3D-1,eugeneko/Urho3D,299299/Urho3D,bacsmar/Urho3D,codedash64/Urho3D,fire/Urho3D-1,kostik1337/Urho3D,299299/Urho3D,xiliu98/Urho3D,c4augustus/Urho3D,rokups/Urho3D,abdllhbyrktr/Urho3D,rokups/Urho3D,299299/Urho3D,MeshGeometry/Urho3D,kostik1337/Urho3D,weitjong/Urho3D,rokups/Urho3D,SuperWangKai/Urho3D,iainmerrick/Urho3D,SirNate0/Urho3D,weitjong/Urho3D,abdllhbyrktr/Urho3D,codedash64/Urho3D,c4augustus/Urho3D,SirNate0/Urho3D,SuperWangKai/Urho3D,henu/Urho3D,helingping/Urho3D,victorholt/Urho3D,codedash64/Urho3D,PredatorMF/Urho3D,kostik1337/Urho3D,henu/Urho3D,MeshGeometry/Urho3D,carnalis/Urho3D,urho3d/Urho3D,299299/Urho3D,carnalis/Urho3D,tommy3/Urho3D,orefkov/Urho3D,SuperWangKai/Urho3D,fire/Urho3D-1,weitjong/Urho3D,orefkov/Urho3D,abdllhbyrktr/Urho3D,cosmy1/Urho3D,xiliu98/Urho3D,c4augustus/Urho3D,SuperWangKai/Urho3D,iainmerrick/Urho3D,c4augustus/Urho3D,luveti/Urho3D,rokups/Urho3D,luveti/Urho3D,eugeneko/Urho3D,carnalis/Urho3D,SirNate0/Urho3D,MeshGeometry/Urho3D,MonkeyFirst/Urho3D,tommy3/Urho3D,SirNate0/Urho3D,victorholt/Urho3D,orefkov/Urho3D,iainmerrick/Urho3D,SuperWangKai/Urho3D,victorholt/Urho3D,codemon66/Urho3D,xiliu98/Urho3D,urho3d/Urho3D
bb65af3083b876480802dfac3d35c26fb59de232
frameworks/projects/framework/src/mx/core/RuntimeDPIProvider.as
frameworks/projects/framework/src/mx/core/RuntimeDPIProvider.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.core { import flash.system.Capabilities; import mx.core.mx_internal; use namespace mx_internal; /** * The RuntimeDPIProvider class provides the default mapping of * similar device DPI values into predefined DPI classes. * An Application may have its runtimeDPIProvider property set to a * subclass of RuntimeDPIProvider to override Flex's default mappings. * Overriding Flex's default mappings will cause changes in the Application's * automatic scaling behavior. * * <p>Overriding Flex's default mappings is usually only necessary for devices * that incorrectly report their screenDPI and for devices that may scale better * in a different DPI class.</p> * * <p>Flex's default mappings are: * <table class="innertable"> * <tr><td>160 DPI</td><td>&lt;140 DPI</td></tr> * <tr><td>160 DPI</td><td>&gt;=140 DPI and &lt;=200 DPI</td></tr> * <tr><td>240 DPI</td><td>&gt;=200 DPI and &lt;=280 DPI</td></tr> * <tr><td>320 DPI</td><td>&gt;=280 DPI and &lt;=400 DPI</td></tr> * <tr><td>480 DPI</td><td>&gt;=400 DPI and &lt;=560 DPI</td></tr> * <tr><td>640 DPI</td><td>&gt;=640 DPI</td></tr> * </table> * </p> * * <p>Subclasses of RuntimeDPIProvider should only depend on runtime APIs * and should not depend on any classes specific to the Flex framework except * <code>mx.core.DPIClassification</code>.</p> * * @includeExample examples/RuntimeDPIProviderApp.mxml -noswf * @includeExample examples/RuntimeDPIProviderExample.as -noswf * @includeExample examples/views/RuntimeDPIProviderAppView.mxml -noswf * * @see mx.core.DPIClassification * @see spark.components.Application#applicationDPI * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class RuntimeDPIProvider { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function RuntimeDPIProvider() { } /** * Returns the runtime DPI of the current device by mapping its * <code>flash.system.Capabilities.screenDPI</code> to one of several DPI * values in <code>mx.core.DPIClassification</code>. * * A number of devices can have slightly different DPI values and Flex maps these * into the several DPI classes. * * Flex uses this method to calculate the current DPI value when an Application * authored for a specific DPI is adapted to the current one through scaling. * * @param dpi The DPI value. * @return The corresponding <code>DPIClassification</code> value. * * @see flash.system.Capabilities * @see mx.core.DPIClassification * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get runtimeDPI():Number { return classifyDPI(Capabilities.screenDPI); } /** * @private * Matches the specified DPI to a <code>DPIClassification</code> value. * A number of devices can have slightly different DPI values and classifyDPI * maps these into the several DPI classes. * * This method is specifically kept for Design View. Flex uses RuntimeDPIProvider * to calculate DPI classes. * * @param dpi The DPI value. * @return The corresponding <code>DPIClassification</code> value. */ mx_internal static function classifyDPI(dpi:Number):Number { if (dpi <= 140) return DPIClassification.DPI_120; if (dpi <= 200) return DPIClassification.DPI_160; if (dpi <= 280) return DPIClassification.DPI_240; if (dpi <= 400) return DPIClassification.DPI_320; if (dpi <= 560) return DPIClassification.DPI_480; return DPIClassification.DPI_640; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.core { import flash.display.DisplayObject; import flash.display.Stage; import flash.system.Capabilities; import mx.core.mx_internal; import mx.managers.SystemManager; use namespace mx_internal; /** * The RuntimeDPIProvider class provides the default mapping of * similar device DPI values into predefined DPI classes. * An Application may have its runtimeDPIProvider property set to a * subclass of RuntimeDPIProvider to override Flex's default mappings. * Overriding Flex's default mappings will cause changes in the Application's * automatic scaling behavior. * * <p>Overriding Flex's default mappings is usually only necessary for devices * that incorrectly report their screenDPI and for devices that may scale better * in a different DPI class.</p> * * <p>Flex's default mappings are: * <table class="innertable"> * <tr><td>160 DPI</td><td>&lt;140 DPI</td></tr> * <tr><td>160 DPI</td><td>&gt;=140 DPI and &lt;=200 DPI</td></tr> * <tr><td>240 DPI</td><td>&gt;=200 DPI and &lt;=280 DPI</td></tr> * <tr><td>320 DPI</td><td>&gt;=280 DPI and &lt;=400 DPI</td></tr> * <tr><td>480 DPI</td><td>&gt;=400 DPI and &lt;=560 DPI</td></tr> * <tr><td>640 DPI</td><td>&gt;=640 DPI</td></tr> * </table> * </p> * * * * <p>Subclasses of RuntimeDPIProvider should only depend on runtime APIs * and should not depend on any classes specific to the Flex framework except * <code>mx.core.DPIClassification</code>.</p> * * @includeExample examples/RuntimeDPIProviderApp.mxml -noswf * @includeExample examples/RuntimeDPIProviderExample.as -noswf * @includeExample examples/views/RuntimeDPIProviderAppView.mxml -noswf * * @see mx.core.DPIClassification * @see spark.components.Application#applicationDPI * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class RuntimeDPIProvider { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function RuntimeDPIProvider() { } /** * Returns the runtime DPI of the current device by mapping its * <code>flash.system.Capabilities.screenDPI</code> to one of several DPI * values in <code>mx.core.DPIClassification</code>. * * A number of devices can have slightly different DPI values and Flex maps these * into the several DPI classes. * * Flex uses this method to calculate the current DPI value when an Application * authored for a specific DPI is adapted to the current one through scaling. * * <p> Exceptions: </p> * <ul> * <li>All non-retina iPads receive 160 DPI </li> * <li>All retina iPads receive 320 DPI </li> * </ul> * * @param dpi The DPI value. * @return The corresponding <code>DPIClassification</code> value. * isI * @see flash.system.Capabilities * @see mx.core.DPIClassification * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get runtimeDPI():Number { var isIOS:Boolean = Capabilities.version.indexOf("IOS") == 0; var screenDPI : Number= Capabilities.screenDPI; if (isIOS) { var root:DisplayObject = SystemManager.getSWFRoot(this); if (root != null ) { var stage:Stage = root.stage; if (stage != null){ var scX:Number = stage.fullScreenWidth; var scY:Number = stage.fullScreenHeight; /* as of Dec 2013, iPad (resp. iPad retina) are the only iOS devices to have 1024 (resp. 2048) screen width or height cf http://en.wikipedia.org/wiki/List_of_displays_by_pixel_density#Apple * */ if ((scX == 2048 || scY == 2048)) return DPIClassification.DPI_320; else if (scX == 1024 || scY == 1024) return DPIClassification.DPI_160; } } } return classifyDPI(screenDPI); } /** * @private * Matches the specified DPI to a <code>DPIClassification</code> value. * A number of devices can have slightly different DPI values and classifyDPI * maps these into the several DPI classes. * * This method is specifically kept for Design View. Flex uses RuntimeDPIProvider * to calculate DPI classes. * * @param dpi The DPI value. * @return The corresponding <code>DPIClassification</code> value. */ mx_internal static function classifyDPI(dpi:Number):Number { if (dpi <= 140) return DPIClassification.DPI_120; if (dpi <= 200) return DPIClassification.DPI_160; if (dpi <= 280) return DPIClassification.DPI_240; if (dpi <= 400) return DPIClassification.DPI_320; if (dpi <= 560) return DPIClassification.DPI_480; return DPIClassification.DPI_640; } } }
FIX FLEX-33861 Flex Incorrectly Scaling Down Application mutella test pass: tests/mobile/*
FIX FLEX-33861 Flex Incorrectly Scaling Down Application mutella test pass: tests/mobile/*
ActionScript
apache-2.0
shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk
9f6272f818c78d31f628709f9b769fe00f2c03e9
src/Player.as
src/Player.as
package { import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.display.StageDisplayState; import flash.events.Event; import flash.events.ErrorEvent; import flash.events.NetStatusEvent; import flash.events.ActivityEvent; import flash.events.ProgressEvent; import flash.events.StatusEvent; import flash.events.SampleDataEvent; import flash.events.MouseEvent; import flash.external.ExternalInterface; import flash.media.Video; import flash.net.NetStream; import flash.net.NetConnection; import flash.net.Socket; import flash.system.Security; import flash.utils.getTimer; import com.axis.rtspclient.*; import com.axis.audioclient.AxisTransmit; import com.axis.http.url; [SWF(frameRate="60")] [SWF(backgroundColor="#efefef")] public class Player extends Sprite { private var vid:Video; private var audioTransmit:AxisTransmit = new AxisTransmit(); private var meta:Object = {}; private var client:RTSPClient; private static var ns:NetStream; public function Player() { 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); /* Audio Transmission API */ ExternalInterface.addCallback("startAudioTransmit", audioTransmitStartInterface); ExternalInterface.addCallback("stopAudioTransmit", audioTransmitStopInterface); this.stage.align = StageAlign.TOP_LEFT; this.stage.scaleMode = StageScaleMode.NO_SCALE; addEventListener(Event.ADDED_TO_STAGE, onStageAdded); var nc:NetConnection = new NetConnection(); nc.connect(null); vid = new Video(stage.stageWidth, stage.stageHeight); ns = new NetStream(nc); ns.bufferTime = 1; ns.client = new Object(); var self:Player = this; ns.client.onMetaData = function(item:Object):void { self.meta = item; videoResize(); }; this.stage.doubleClickEnabled = true; this.stage.addEventListener(MouseEvent.DOUBLE_CLICK, fullscreen); this.stage.addEventListener(Event.FULLSCREEN, function(event:Event):void { videoResize(); }); ns.play(null); vid.attachNetStream(ns); addChild(vid); } public function fullscreen(event:MouseEvent):void { 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; vid.width = Math.min(meta.width, stagewidth); vid.height = Math.min(meta.height, stageheight); vid.x = 0; vid.y = 0; if (meta.width < stagewidth || meta.height < stageheight) { vid.x = (stagewidth - meta.width) / 2; vid.y = (stageheight - meta.height) / 2; } } public function play(iurl:String = null):void { var urlParsed:Object = url.parse(iurl); var rtspHandle:IRTSPHandle = null; switch (urlParsed.protocol) { case 'rtsph': /* RTSP over HTTP */ rtspHandle = new RTSPoverHTTPHandle(urlParsed); break; case 'rtsp': /* RTSP over TCP */ rtspHandle = new RTSPoverTCPHandle(urlParsed); } client = new RTSPClient(rtspHandle, urlParsed); rtspHandle.addEventListener('connected', function():void { client.start(); }); rtspHandle.connect(); } public function pause():void { client.pause(); } public function resume():void { client.resume(); } public function stop():void { client.stop(); } public function audioTransmitStopInterface():void { audioTransmit.stop(); } public function audioTransmitStartInterface(url:String = null):void { audioTransmit.start(url); } private function onStageAdded(e:Event):void { trace('stage added'); } public static function getNetStream():NetStream { return ns; } } }
package { import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.display.StageDisplayState; import flash.events.Event; import flash.events.ErrorEvent; import flash.events.NetStatusEvent; import flash.events.ActivityEvent; import flash.events.ProgressEvent; import flash.events.StatusEvent; import flash.events.SampleDataEvent; import flash.events.MouseEvent; import flash.external.ExternalInterface; import flash.media.Video; import flash.net.NetStream; import flash.net.NetConnection; import flash.net.Socket; import flash.system.Security; import flash.utils.getTimer; import com.axis.rtspclient.*; import com.axis.audioclient.AxisTransmit; import com.axis.http.url; [SWF(frameRate="60")] [SWF(backgroundColor="#efefef")] public class Player extends Sprite { private var config:Object = { 'scaleUp' : false }; private var vid:Video; private var audioTransmit:AxisTransmit = new AxisTransmit(); private var meta:Object = {}; private var client:RTSPClient; private static var ns:NetStream; public function Player() { 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); /* Audio Transmission API */ ExternalInterface.addCallback("startAudioTransmit", audioTransmitStartInterface); ExternalInterface.addCallback("stopAudioTransmit", audioTransmitStopInterface); this.stage.align = StageAlign.TOP_LEFT; this.stage.scaleMode = StageScaleMode.NO_SCALE; addEventListener(Event.ADDED_TO_STAGE, onStageAdded); var nc:NetConnection = new NetConnection(); nc.connect(null); vid = new Video(stage.stageWidth, stage.stageHeight); ns = new NetStream(nc); ns.bufferTime = 1; ns.client = new Object(); var self:Player = this; ns.client.onMetaData = function(item:Object):void { self.meta = item; videoResize(); }; this.stage.doubleClickEnabled = true; this.stage.addEventListener(MouseEvent.DOUBLE_CLICK, fullscreen); this.stage.addEventListener(Event.FULLSCREEN, function(event:Event):void { videoResize(); }); ns.play(null); vid.attachNetStream(ns); addChild(vid); } public function fullscreen(event:MouseEvent):void { 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); vid.width = meta.width; vid.height = meta.height; if ((scale < 1.0) || (scale > 1.0 && true === config.scaleUp)) { trace('scaling video, scale:', scale.toFixed(2), ' (aspect ratio: ' + (vid.width / vid.height).toFixed(2) + ')'); vid.width = meta.width * scale; vid.height = meta.height * scale; } vid.x = (stagewidth - vid.width) / 2; vid.y = (stageheight - vid.height) / 2; } public function play(iurl:String = null):void { var urlParsed:Object = url.parse(iurl); var rtspHandle:IRTSPHandle = null; switch (urlParsed.protocol) { case 'rtsph': /* RTSP over HTTP */ rtspHandle = new RTSPoverHTTPHandle(urlParsed); break; case 'rtsp': /* RTSP over TCP */ rtspHandle = new RTSPoverTCPHandle(urlParsed); } client = new RTSPClient(rtspHandle, urlParsed); rtspHandle.addEventListener('connected', function():void { client.start(); }); rtspHandle.connect(); } public function pause():void { client.pause(); } public function resume():void { client.resume(); } public function stop():void { client.stop(); } public function audioTransmitStopInterface():void { audioTransmit.stop(); } public function audioTransmitStartInterface(url:String = null):void { audioTransmit.start(url); } private function onStageAdded(e:Event):void { trace('stage added'); } public static function getNetStream():NetStream { return ns; } } }
scale sensibly
Player: scale sensibly If the stage is smaller than the video, scale down the video. If the stage is large, let a config decide if upscale should occur. If the stage fits the video precisly do no scaling. Afterwards, center the movie on the stage.
ActionScript
bsd-3-clause
AxisCommunications/locomote-video-player,gaetancollaud/locomote-video-player
546c44c600a0974eb427276f0ea280db1ed3734e
src/as/com/threerings/presents/client/Communicator.as
src/as/com/threerings/presents/client/Communicator.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.presents.client { import flash.errors.IOError; import flash.events.Event; import flash.events.IOErrorEvent; import flash.net.Socket; import flash.utils.ByteArray; import flash.utils.Endian; import com.threerings.util.StringUtil; import com.threerings.io.FrameAvailableEvent; import com.threerings.io.FrameReader; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Translations; import com.threerings.presents.data.AuthCodes; import com.threerings.presents.net.AuthRequest; import com.threerings.presents.net.AuthResponse; import com.threerings.presents.net.AuthResponseData; import com.threerings.presents.net.DownstreamMessage; import com.threerings.presents.net.LogoffRequest; import com.threerings.presents.net.UpstreamMessage; public class Communicator { public function Communicator (client :Client) { _client = client; } public function logon () :void { // create our input/output business _outBuffer = new ByteArray(); _outBuffer.endian = Endian.BIG_ENDIAN; _outStream = new ObjectOutputStream(_outBuffer); _inStream = new ObjectInputStream(); _portIdx = 0; logonToPort(); } /** * This method is strangely named, and it does two things which is * bad style. Either log on to the next port, or save that the port * we just logged on to was a good one. */ protected function logonToPort (logonWasSuccessful :Boolean = false) :Boolean { var ports :Array = _client.getPorts(); if (!logonWasSuccessful) { if (_portIdx >= ports.length) { return false; } if (_portIdx != 0) { _client.reportLogonTribulations( new LogonError(AuthCodes.TRYING_NEXT_PORT, true)); removeListeners(); } // create the socket and set up listeners _socket = new Socket(); _socket.endian = Endian.BIG_ENDIAN; _socket.addEventListener(Event.CONNECT, socketOpened); _socket.addEventListener(IOErrorEvent.IO_ERROR, socketError); _socket.addEventListener(Event.CLOSE, socketClosed); _frameReader = new FrameReader(_socket); _frameReader.addEventListener(FrameAvailableEvent.FRAME_AVAILABLE, inputFrameReceived); } var host :String = _client.getHostname(); var pportKey :String = host + ".preferred_port"; var pport :int = (PresentsPrefs.config.getValue(pportKey, ports[0]) as int); var ppidx :int = Math.max(0, ports.indexOf(pport)); var port :int = (ports[(_portIdx + ppidx) % ports.length] as int); if (logonWasSuccessful) { _portIdx = -1; // indicate that we're no longer trying new ports PresentsPrefs.config.setValue(pportKey, port); } else { Log.getLog(this).info( "Connecting [host=" + host + ", port=" + port + "]."); _socket.connect(host, port); } return true; } protected function removeListeners () :void { _socket.removeEventListener(Event.CONNECT, socketOpened); _socket.removeEventListener(IOErrorEvent.IO_ERROR, socketError); _socket.removeEventListener(Event.CLOSE, socketClosed); _frameReader.removeEventListener(FrameAvailableEvent.FRAME_AVAILABLE, inputFrameReceived); } public function logoff () :void { if (_socket == null) { return; } sendMessage(new LogoffRequest()); shutdown(null); } public function postMessage (msg :UpstreamMessage) :void { sendMessage(msg); // send it now: we have no out queue } protected function shutdown (logonError :Error) :void { _client.notifyObservers(ClientEvent.CLIENT_DID_LOGOFF, null); if (_socket != null) { try { _socket.close(); } catch (err :Error) { Log.getLog(this).warning( "Error closing failed socket [error=" + err + "]."); } removeListeners(); _socket = null; _outStream = null; _inStream = null; _frameReader = null; _outBuffer = null; } _client.cleanup(logonError); } protected function sendMessage (msg :UpstreamMessage) :void { if (_outStream == null) { Log.getLog(this).warning( "No socket, dropping msg [msg=" + msg + "]."); return; } // write the message (ends up in _outBuffer) _outStream.writeObject(msg); // Log.debug("outBuffer: " + StringUtil.unhexlate(_outBuffer)); // Frame it by writing the length, then the bytes. // We add 4 to the length, because the length is of the entire frame // including the 4 bytes used to encode the length! _socket.writeInt(_outBuffer.length + 4); _socket.writeBytes(_outBuffer); _socket.flush(); // clean up the output buffer _outBuffer.length = 0; _outBuffer.position = 0; // make a note of our most recent write time updateWriteStamp(); } /** * Returns the time at which we last sent a packet to the server. */ internal function getLastWrite () :uint { return _lastWrite; } /** * Makes a note of the time at which we last communicated with the server. */ internal function updateWriteStamp () :void { _lastWrite = flash.utils.getTimer(); } /** * Called when a frame of data from the server is ready to be * decoded into a DownstreamMessage. */ protected function inputFrameReceived (event :FrameAvailableEvent) :void { // convert the frame data into a message from the server var frameData :ByteArray = event.getFrameData(); //Log.debug("length of in frame: " + frameData.length); //Log.debug("inBuffer: " + StringUtil.unhexlate(frameData)); _inStream.setSource(frameData); var msg :DownstreamMessage; try { msg = (_inStream.readObject() as DownstreamMessage); } catch (e :Error) { var log :Log = Log.getLog(this); log.warning("Error processing downstream message: " + e); log.logStackTrace(e); return; } if (frameData.bytesAvailable > 0) { Log.getLog(this).warning( "Beans! We didn't fully read a frame, surely there's " + "a bug in some streaming code. " + "[bytesLeftOver=" + frameData.bytesAvailable + "]."); } if (_omgr != null) { // if we're logged on, then just do the normal thing _omgr.processMessage(msg); return; } // Otherwise, this would be the AuthResponse to our logon attempt. var rsp :AuthResponse = (msg as AuthResponse); var data :AuthResponseData = rsp.getData(); if (data.code !== AuthResponseData.SUCCESS) { shutdown(new Error(data.code)); return; } // logon success _omgr = new ClientDObjectMgr(this, _client); _client.setAuthResponseData(data); } /** * Called when the connection to the server was successfully opened. */ protected function socketOpened (event :Event) :void { logonToPort(true); // well that's great! let's logon var req :AuthRequest = new AuthRequest( _client.getCredentials(), _client.getVersion(), _client.getBootGroups()); sendMessage(req); } /** * Called when there is an io error with the socket. */ protected function socketError (event :IOErrorEvent) :void { // if we're trying ports, try the next one. if (_portIdx != -1) { _portIdx++; if (logonToPort()) { return; } } // total failure Log.getLog(this).warning("socket error: " + event); Log.dumpStack(); if (_socket.connected) { Log.getLog(this).info("Things seem ok. Ignoring."); } else { shutdown(new Error("socket closed unexpectedly.")); } } /** * Called when the connection to the server was closed. */ protected function socketClosed (event :Event) :void { Log.getLog(this).warning("socket was closed: " + event); _client.notifyObservers(ClientEvent.CLIENT_CONNECTION_FAILED); logoff(); } protected var _client :Client; protected var _omgr :ClientDObjectMgr; protected var _outBuffer :ByteArray; protected var _outStream :ObjectOutputStream; protected var _inStream :ObjectInputStream; protected var _frameReader :FrameReader; protected var _socket :Socket; protected var _lastWrite :uint; /** The current port we'll try to connect to. */ protected var _portIdx :int = -1; } }
// // $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.presents.client { import flash.errors.IOError; import flash.events.Event; import flash.events.IOErrorEvent; import flash.net.Socket; import flash.utils.ByteArray; import flash.utils.Endian; import com.threerings.util.StringUtil; import com.threerings.io.FrameAvailableEvent; import com.threerings.io.FrameReader; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Translations; import com.threerings.presents.data.AuthCodes; import com.threerings.presents.net.AuthRequest; import com.threerings.presents.net.AuthResponse; import com.threerings.presents.net.AuthResponseData; import com.threerings.presents.net.DownstreamMessage; import com.threerings.presents.net.LogoffRequest; import com.threerings.presents.net.UpstreamMessage; public class Communicator { public function Communicator (client :Client) { _client = client; } public function logon () :void { // create our input/output business _outBuffer = new ByteArray(); _outBuffer.endian = Endian.BIG_ENDIAN; _outStream = new ObjectOutputStream(_outBuffer); _inStream = new ObjectInputStream(); _portIdx = 0; logonToPort(); } /** * This method is strangely named, and it does two things which is * bad style. Either log on to the next port, or save that the port * we just logged on to was a good one. */ protected function logonToPort (logonWasSuccessful :Boolean = false) :Boolean { var ports :Array = _client.getPorts(); if (!logonWasSuccessful) { if (_portIdx >= ports.length) { return false; } if (_portIdx != 0) { _client.reportLogonTribulations( new LogonError(AuthCodes.TRYING_NEXT_PORT, true)); removeListeners(); } // create the socket and set up listeners _socket = new Socket(); _socket.endian = Endian.BIG_ENDIAN; _socket.addEventListener(Event.CONNECT, socketOpened); _socket.addEventListener(IOErrorEvent.IO_ERROR, socketError); _socket.addEventListener(Event.CLOSE, socketClosed); _frameReader = new FrameReader(_socket); _frameReader.addEventListener(FrameAvailableEvent.FRAME_AVAILABLE, inputFrameReceived); } var host :String = _client.getHostname(); var pportKey :String = host + ".preferred_port"; var pport :int = (PresentsPrefs.config.getValue(pportKey, ports[0]) as int); var ppidx :int = Math.max(0, ports.indexOf(pport)); var port :int = (ports[(_portIdx + ppidx) % ports.length] as int); if (logonWasSuccessful) { _portIdx = -1; // indicate that we're no longer trying new ports PresentsPrefs.config.setValue(pportKey, port); } else { Log.getLog(this).info( "Connecting [host=" + host + ", port=" + port + "]."); _socket.connect(host, port); } return true; } protected function removeListeners () :void { _socket.removeEventListener(Event.CONNECT, socketOpened); _socket.removeEventListener(IOErrorEvent.IO_ERROR, socketError); _socket.removeEventListener(Event.CLOSE, socketClosed); _frameReader.removeEventListener(FrameAvailableEvent.FRAME_AVAILABLE, inputFrameReceived); } public function logoff () :void { if (_socket == null) { return; } sendMessage(new LogoffRequest()); shutdown(null); } public function postMessage (msg :UpstreamMessage) :void { sendMessage(msg); // send it now: we have no out queue } protected function shutdown (logonError :Error) :void { _client.notifyObservers(ClientEvent.CLIENT_DID_LOGOFF, null); if (_socket != null) { try { _socket.close(); } catch (err :Error) { Log.getLog(this).warning( "Error closing failed socket [error=" + err + "]."); } removeListeners(); _socket = null; _outStream = null; _inStream = null; _frameReader = null; _outBuffer = null; } _client.cleanup(logonError); } protected function sendMessage (msg :UpstreamMessage) :void { if (_outStream == null) { Log.getLog(this).warning( "No socket, dropping msg [msg=" + msg + "]."); return; } // write the message (ends up in _outBuffer) _outStream.writeObject(msg); // Log.debug("outBuffer: " + StringUtil.unhexlate(_outBuffer)); // Frame it by writing the length, then the bytes. // We add 4 to the length, because the length is of the entire frame // including the 4 bytes used to encode the length! _socket.writeInt(_outBuffer.length + 4); _socket.writeBytes(_outBuffer); _socket.flush(); // clean up the output buffer _outBuffer.length = 0; _outBuffer.position = 0; // make a note of our most recent write time updateWriteStamp(); } /** * Returns the time at which we last sent a packet to the server. */ internal function getLastWrite () :uint { return _lastWrite; } /** * Makes a note of the time at which we last communicated with the server. */ internal function updateWriteStamp () :void { _lastWrite = flash.utils.getTimer(); } /** * Called when a frame of data from the server is ready to be * decoded into a DownstreamMessage. */ protected function inputFrameReceived (event :FrameAvailableEvent) :void { // convert the frame data into a message from the server var frameData :ByteArray = event.getFrameData(); //Log.debug("length of in frame: " + frameData.length); //Log.debug("inBuffer: " + StringUtil.unhexlate(frameData)); _inStream.setSource(frameData); var msg :DownstreamMessage; try { msg = (_inStream.readObject() as DownstreamMessage); } catch (e :Error) { var log :Log = Log.getLog(this); log.warning("Error processing downstream message: " + e); log.logStackTrace(e); return; } if (frameData.bytesAvailable > 0) { Log.getLog(this).warning( "Beans! We didn't fully read a frame, surely there's " + "a bug in some streaming code. " + "[bytesLeftOver=" + frameData.bytesAvailable + "]."); } if (_omgr != null) { // if we're logged on, then just do the normal thing _omgr.processMessage(msg); return; } // Otherwise, this would be the AuthResponse to our logon attempt. var rsp :AuthResponse = (msg as AuthResponse); var data :AuthResponseData = rsp.getData(); if (data.code !== AuthResponseData.SUCCESS) { shutdown(new Error(data.code)); return; } // logon success _omgr = new ClientDObjectMgr(this, _client); _client.setAuthResponseData(data); } /** * Called when the connection to the server was successfully opened. */ protected function socketOpened (event :Event) :void { logonToPort(true); // well that's great! let's logon var req :AuthRequest = new AuthRequest( _client.getCredentials(), _client.getVersion(), _client.getBootGroups()); sendMessage(req); } /** * Called when there is an io error with the socket. */ protected function socketError (event :IOErrorEvent) :void { // if we're trying ports, try the next one. if (_portIdx != -1) { _portIdx++; if (logonToPort()) { return; } } // total failure Log.getLog(this).warning("socket error: " + event + ", target=" + event.target); Log.dumpStack(); shutdown(new Error("socket closed unexpectedly.")); } /** * Called when the connection to the server was closed. */ protected function socketClosed (event :Event) :void { Log.getLog(this).warning("socket was closed: " + event); _client.notifyObservers(ClientEvent.CLIENT_CONNECTION_FAILED); logoff(); } protected var _client :Client; protected var _omgr :ClientDObjectMgr; protected var _outBuffer :ByteArray; protected var _outStream :ObjectOutputStream; protected var _inStream :ObjectInputStream; protected var _frameReader :FrameReader; protected var _socket :Socket; protected var _lastWrite :uint; /** The current port we'll try to connect to. */ protected var _portIdx :int = -1; } }
Stop trying to recover from this error (it doesn't work), but try logging the event target.
Stop trying to recover from this error (it doesn't work), but try logging the event target. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4644 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
c32de2476fa33d6e59a98d9b770c0f08cf941f13
frameworks/as/projects/FlexJSUI/src/FlexJSUIClasses.as
frameworks/as/projects/FlexJSUI/src/FlexJSUIClasses.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 { /** * @private * This class is used to link additional classes into rpc.swc * beyond those that are found by dependecy analysis starting * from the classes specified in manifest.xml. */ internal class FlexJSUIClasses { import org.apache.cordova.camera.Camera; Camera; import org.apache.cordova.Application; Application; import org.apache.cordova.Weinre; Weinre; import org.apache.flex.charts.core.CartesianChart; CartesianChart; import org.apache.flex.charts.core.ChartBase; ChartBase; import org.apache.flex.charts.core.IChart; IChart; import org.apache.flex.charts.core.ICartesianChartLayout; ICartesianChartLayout; import org.apache.flex.charts.core.IChartSeries; IChartSeries; import org.apache.flex.charts.core.IHorizontalAxisBead; IHorizontalAxisBead; import org.apache.flex.charts.core.IVerticalAxisBead; IVerticalAxisBead; import org.apache.flex.charts.core.IChartItemRenderer; IChartItemRenderer; import org.apache.flex.charts.core.IConnectedItemRenderer; IConnectedItemRenderer; import org.apache.flex.charts.core.PolarChart; PolarChart; import org.apache.flex.charts.ChartDataGroup; ChartDataGroup; import org.apache.flex.charts.supportClasses.BoxItemRenderer; BoxItemRenderer; import org.apache.flex.charts.supportClasses.LineSegmentItemRenderer; LineSegmentItemRenderer; import org.apache.flex.charts.supportClasses.WedgeItemRenderer; WedgeItemRenderer; import org.apache.flex.maps.google.Map; Map; import org.apache.flex.html.accessories.NumericOnlyTextInputBead; NumericOnlyTextInputBead; import org.apache.flex.html.accessories.PasswordInputBead; PasswordInputBead; import org.apache.flex.html.accessories.TextPromptBead; TextPromptBead; import org.apache.flex.html.beads.AlertView; AlertView; import org.apache.flex.html.beads.ButtonBarView; ButtonBarView; import org.apache.flex.html.beads.CheckBoxView; CheckBoxView; import org.apache.flex.html.beads.ComboBoxView; ComboBoxView; import org.apache.flex.html.beads.ContainerView; ContainerView; import org.apache.flex.html.beads.ControlBarMeasurementBead; ControlBarMeasurementBead; import org.apache.flex.html.beads.CSSButtonView; CSSButtonView; import org.apache.flex.html.beads.CSSTextButtonView; CSSTextButtonView; import org.apache.flex.html.beads.DropDownListView; DropDownListView; import org.apache.flex.html.beads.ImageButtonView; ImageButtonView; import org.apache.flex.html.beads.ImageView; ImageView; import org.apache.flex.html.beads.ListView; ListView; import org.apache.flex.html.beads.NumericStepperView; NumericStepperView; import org.apache.flex.html.beads.PanelView; PanelView; import org.apache.flex.html.beads.RadioButtonView; RadioButtonView; import org.apache.flex.html.beads.ScrollBarView; ScrollBarView; import org.apache.flex.html.beads.SimpleAlertView; SimpleAlertView; import org.apache.flex.html.beads.SingleLineBorderBead; SingleLineBorderBead; import org.apache.flex.html.beads.SliderView; SliderView; import org.apache.flex.html.beads.SliderThumbView; SliderThumbView; import org.apache.flex.html.beads.SliderTrackView; SliderTrackView; import org.apache.flex.html.beads.SolidBackgroundBead; SolidBackgroundBead; import org.apache.flex.html.beads.SpinnerView; SpinnerView; import org.apache.flex.html.beads.TextButtonMeasurementBead; TextButtonMeasurementBead; import org.apache.flex.html.beads.TextFieldLabelMeasurementBead; TextFieldLabelMeasurementBead; import org.apache.flex.html.beads.TextAreaView; TextAreaView; import org.apache.flex.html.beads.TextButtonView; TextButtonView; import org.apache.flex.html.beads.TextFieldView; TextFieldView; import org.apache.flex.html.beads.TextInputView; TextInputView; import org.apache.flex.html.beads.TextInputWithBorderView; TextInputWithBorderView; import org.apache.flex.html.beads.TitleBarMeasurementBead; TitleBarMeasurementBead; import org.apache.flex.html.beads.TitleBarView; TitleBarView; import org.apache.flex.html.beads.models.AlertModel; AlertModel; import org.apache.flex.html.beads.models.ArraySelectionModel; ArraySelectionModel; import org.apache.flex.html.beads.models.ComboBoxModel; ComboBoxModel; import org.apache.flex.html.beads.models.ImageModel; ImageModel; import org.apache.flex.html.beads.models.PanelModel; PanelModel; import org.apache.flex.html.beads.models.SingleLineBorderModel; SingleLineBorderModel; import org.apache.flex.html.beads.models.TextModel; TextModel; import org.apache.flex.html.beads.models.TitleBarModel; TitleBarModel; import org.apache.flex.html.beads.models.ToggleButtonModel; ToggleButtonModel; import org.apache.flex.html.beads.models.ValueToggleButtonModel; ValueToggleButtonModel; import org.apache.flex.html.beads.controllers.AlertController; AlertController; import org.apache.flex.html.beads.controllers.ComboBoxController; ComboBoxController; import org.apache.flex.html.beads.controllers.DropDownListController; DropDownListController; import org.apache.flex.html.beads.controllers.EditableTextKeyboardController; EditableTextKeyboardController; import org.apache.flex.html.beads.controllers.ItemRendererMouseController; ItemRendererMouseController; import org.apache.flex.html.beads.controllers.ListSingleSelectionMouseController; ListSingleSelectionMouseController; import org.apache.flex.html.beads.controllers.SliderMouseController; SliderMouseController; import org.apache.flex.html.beads.controllers.SpinnerMouseController; SpinnerMouseController; import org.apache.flex.html.beads.controllers.VScrollBarMouseController; VScrollBarMouseController; import org.apache.flex.html.beads.layouts.ButtonBarLayout; ButtonBarLayout; import org.apache.flex.html.beads.layouts.NonVirtualVerticalScrollingLayout; NonVirtualVerticalScrollingLayout; import org.apache.flex.html.beads.layouts.NonVirtualHorizontalScrollingLayout; NonVirtualHorizontalScrollingLayout; import org.apache.flex.html.beads.layouts.VScrollBarLayout; VScrollBarLayout; import org.apache.flex.html.beads.layouts.TileLayout; TileLayout; import org.apache.flex.html.beads.TextItemRendererFactoryForArrayData; TextItemRendererFactoryForArrayData; import org.apache.flex.html.beads.DataItemRendererFactoryForArrayData; DataItemRendererFactoryForArrayData; import org.apache.flex.html.supportClasses.NonVirtualDataGroup; NonVirtualDataGroup; import org.apache.flex.core.ItemRendererClassFactory; ItemRendererClassFactory; import org.apache.flex.core.FilledRectangle; FilledRectangle; import org.apache.flex.core.FormatBase; FormatBase; import org.apache.flex.events.CustomEvent; CustomEvent; import org.apache.flex.events.Event; Event; import org.apache.flex.events.ValueEvent; ValueEvent; import org.apache.flex.utils.EffectTimer; EffectTimer; import org.apache.flex.utils.Timer; Timer; import org.apache.flex.utils.UIUtils; UIUtils; import org.apache.flex.core.SimpleStatesImpl; SimpleStatesImpl; import org.apache.flex.core.graphics.GraphicShape; GraphicShape; import org.apache.flex.core.graphics.Rect; Rect; import org.apache.flex.core.graphics.SolidColor; SolidColor; import org.apache.flex.core.graphics.SolidColorStroke; SolidColorStroke; import mx.core.ClassFactory; ClassFactory; import mx.states.AddItems; AddItems; import mx.states.SetProperty; SetProperty; import mx.states.State; State; } }
//////////////////////////////////////////////////////////////////////////////// // // 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 { /** * @private * This class is used to link additional classes into rpc.swc * beyond those that are found by dependecy analysis starting * from the classes specified in manifest.xml. */ internal class FlexJSUIClasses { import org.apache.cordova.camera.Camera; Camera; import org.apache.cordova.Application; Application; import org.apache.cordova.Weinre; Weinre; import org.apache.flex.charts.core.CartesianChart; CartesianChart; import org.apache.flex.charts.core.ChartBase; ChartBase; import org.apache.flex.charts.core.IChart; IChart; import org.apache.flex.charts.core.ICartesianChartLayout; ICartesianChartLayout; import org.apache.flex.charts.core.IChartSeries; IChartSeries; import org.apache.flex.charts.core.IHorizontalAxisBead; IHorizontalAxisBead; import org.apache.flex.charts.core.IVerticalAxisBead; IVerticalAxisBead; import org.apache.flex.charts.core.IChartItemRenderer; IChartItemRenderer; import org.apache.flex.charts.core.IConnectedItemRenderer; IConnectedItemRenderer; import org.apache.flex.charts.core.PolarChart; PolarChart; import org.apache.flex.charts.ChartDataGroup; ChartDataGroup; import org.apache.flex.charts.supportClasses.BoxItemRenderer; BoxItemRenderer; import org.apache.flex.charts.supportClasses.LineSegmentItemRenderer; LineSegmentItemRenderer; import org.apache.flex.charts.supportClasses.WedgeItemRenderer; WedgeItemRenderer; import org.apache.flex.maps.google.Map; Map; import org.apache.flex.html.accessories.NumericOnlyTextInputBead; NumericOnlyTextInputBead; import org.apache.flex.html.accessories.PasswordInputBead; PasswordInputBead; import org.apache.flex.html.accessories.TextPromptBead; TextPromptBead; import org.apache.flex.html.beads.AlertView; AlertView; import org.apache.flex.html.beads.ButtonBarView; ButtonBarView; import org.apache.flex.html.beads.CheckBoxView; CheckBoxView; import org.apache.flex.html.beads.ComboBoxView; ComboBoxView; import org.apache.flex.html.beads.ContainerView; ContainerView; import org.apache.flex.html.beads.ControlBarMeasurementBead; ControlBarMeasurementBead; import org.apache.flex.html.beads.CSSButtonView; CSSButtonView; import org.apache.flex.html.beads.CSSTextButtonView; CSSTextButtonView; import org.apache.flex.html.beads.DropDownListView; DropDownListView; import org.apache.flex.html.beads.ImageButtonView; ImageButtonView; import org.apache.flex.html.beads.ImageView; ImageView; import org.apache.flex.html.beads.ListView; ListView; import org.apache.flex.html.beads.NumericStepperView; NumericStepperView; import org.apache.flex.html.beads.PanelView; PanelView; import org.apache.flex.html.beads.RadioButtonView; RadioButtonView; import org.apache.flex.html.beads.ScrollBarView; ScrollBarView; import org.apache.flex.html.beads.SimpleAlertView; SimpleAlertView; import org.apache.flex.html.beads.SingleLineBorderBead; SingleLineBorderBead; import org.apache.flex.html.beads.SliderView; SliderView; import org.apache.flex.html.beads.SliderThumbView; SliderThumbView; import org.apache.flex.html.beads.SliderTrackView; SliderTrackView; import org.apache.flex.html.beads.SolidBackgroundBead; SolidBackgroundBead; import org.apache.flex.html.beads.SpinnerView; SpinnerView; import org.apache.flex.html.beads.TextButtonMeasurementBead; TextButtonMeasurementBead; import org.apache.flex.html.beads.TextFieldLabelMeasurementBead; TextFieldLabelMeasurementBead; import org.apache.flex.html.beads.TextAreaView; TextAreaView; import org.apache.flex.html.beads.TextButtonView; TextButtonView; import org.apache.flex.html.beads.TextFieldView; TextFieldView; import org.apache.flex.html.beads.TextInputView; TextInputView; import org.apache.flex.html.beads.TextInputWithBorderView; TextInputWithBorderView; import org.apache.flex.html.beads.TitleBarMeasurementBead; TitleBarMeasurementBead; import org.apache.flex.html.beads.TitleBarView; TitleBarView; import org.apache.flex.html.beads.models.AlertModel; AlertModel; import org.apache.flex.html.beads.models.ArraySelectionModel; ArraySelectionModel; import org.apache.flex.html.beads.models.ComboBoxModel; ComboBoxModel; import org.apache.flex.html.beads.models.ImageModel; ImageModel; import org.apache.flex.html.beads.models.PanelModel; PanelModel; import org.apache.flex.html.beads.models.SingleLineBorderModel; SingleLineBorderModel; import org.apache.flex.html.beads.models.TextModel; TextModel; import org.apache.flex.html.beads.models.TitleBarModel; TitleBarModel; import org.apache.flex.html.beads.models.ToggleButtonModel; ToggleButtonModel; import org.apache.flex.html.beads.models.ValueToggleButtonModel; ValueToggleButtonModel; import org.apache.flex.html.beads.controllers.AlertController; AlertController; import org.apache.flex.html.beads.controllers.ComboBoxController; ComboBoxController; import org.apache.flex.html.beads.controllers.DropDownListController; DropDownListController; import org.apache.flex.html.beads.controllers.EditableTextKeyboardController; EditableTextKeyboardController; import org.apache.flex.html.beads.controllers.ItemRendererMouseController; ItemRendererMouseController; import org.apache.flex.html.beads.controllers.ListSingleSelectionMouseController; ListSingleSelectionMouseController; import org.apache.flex.html.beads.controllers.SliderMouseController; SliderMouseController; import org.apache.flex.html.beads.controllers.SpinnerMouseController; SpinnerMouseController; import org.apache.flex.html.beads.controllers.VScrollBarMouseController; VScrollBarMouseController; import org.apache.flex.html.beads.layouts.ButtonBarLayout; ButtonBarLayout; import org.apache.flex.html.beads.layouts.NonVirtualVerticalScrollingLayout; NonVirtualVerticalScrollingLayout; import org.apache.flex.html.beads.layouts.NonVirtualHorizontalScrollingLayout; NonVirtualHorizontalScrollingLayout; import org.apache.flex.html.beads.layouts.VScrollBarLayout; VScrollBarLayout; import org.apache.flex.html.beads.layouts.TileLayout; TileLayout; import org.apache.flex.html.beads.TextItemRendererFactoryForArrayData; TextItemRendererFactoryForArrayData; import org.apache.flex.html.beads.DataItemRendererFactoryForArrayData; DataItemRendererFactoryForArrayData; import org.apache.flex.html.supportClasses.NonVirtualDataGroup; NonVirtualDataGroup; import org.apache.flex.core.ItemRendererClassFactory; ItemRendererClassFactory; import org.apache.flex.core.FilledRectangle; FilledRectangle; import org.apache.flex.core.FormatBase; FormatBase; import org.apache.flex.events.CustomEvent; CustomEvent; import org.apache.flex.events.Event; Event; import org.apache.flex.events.ValueEvent; ValueEvent; import org.apache.flex.utils.EffectTimer; EffectTimer; import org.apache.flex.utils.Timer; Timer; import org.apache.flex.utils.UIUtils; UIUtils; import org.apache.flex.core.SimpleStatesImpl; SimpleStatesImpl; import org.apache.flex.core.graphics.GraphicShape; GraphicShape; import org.apache.flex.core.graphics.Rect; Rect; import org.apache.flex.core.graphics.Ellipse; Ellipse; import org.apache.flex.core.graphics.SolidColor; SolidColor; import org.apache.flex.core.graphics.SolidColorStroke; SolidColorStroke; import mx.core.ClassFactory; ClassFactory; import mx.states.AddItems; AddItems; import mx.states.SetProperty; SetProperty; import mx.states.State; State; } }
Include Ellipse in FlexJSUIClasses.as
Include Ellipse in FlexJSUIClasses.as
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
b7594a11356db83a60bd5e04545cfa4b2c6f8d79
src/main/actionscript/com/castlabs/dash/DashNetStream.as
src/main/actionscript/com/castlabs/dash/DashNetStream.as
/* * Copyright (c) 2014 castLabs GmbH * * 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 com.castlabs.dash { import com.castlabs.dash.events.FragmentEvent; import com.castlabs.dash.events.ManifestEvent; import com.castlabs.dash.events.SegmentEvent; import com.castlabs.dash.events.StreamEvent; import com.castlabs.dash.handlers.ManifestHandler; import com.castlabs.dash.loaders.FragmentLoader; import com.castlabs.dash.loaders.ManifestLoader; import flash.events.NetStatusEvent; import flash.events.TimerEvent; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.NetStreamAppendBytesAction; import flash.utils.ByteArray; import flash.utils.Timer; import com.castlabs.dash.utils.NetStreamCodes; public class DashNetStream extends NetStream { private const MIN_BUFFER_TIME:Number = 5; private const MAX_BUFFER_TIME:Number = 30; // actions private const PLAY:uint = 1; private const PAUSE:uint = 2; private const RESUME:uint = 3; private const STOP:uint = 4; private const SEEK:uint = 5; private const BUFFER:uint = 6; // states private const INITIALIZING:uint = 0; private const PLAYING:uint = 1; private const BUFFERING:uint = 2; private const SEEKING:uint = 3; private const PAUSED:uint = 4; private const STOPPED:uint = 5; protected var _context:DashContext; private var _state:uint = INITIALIZING; private var _loader:FragmentLoader; private var _loaded:Boolean = false; private var _offset:Number = 0; private var _loadedTimestamp:Number = 0; private var _duration:Number = 0; private var _live:Boolean; private var _bufferTimer:Timer; private var _fragmentTimer:Timer; public function DashNetStream(context:DashContext, connection:NetConnection) { super(connection); _context = context; addEventListener(NetStatusEvent.NET_STATUS, onNetStatus); _bufferTimer = new Timer(250); // 250 ms _bufferTimer.addEventListener(TimerEvent.TIMER, onBufferTimer); _fragmentTimer = new Timer(250); // 250 ms _fragmentTimer.addEventListener(TimerEvent.TIMER, onFragmentTimer); inBufferSeek = false; bufferTime = 0; bufferTimeMax = 0; maxPauseBufferTime = 0; useHardwareDecoder = true; } override public function play(...rest):void { if (typeof(rest[0]) == 'string' && rest[0] != '') { loadManifest(rest[0]); updateState(PLAY); return; } super.play(null); appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN); appendFileHeader(); notifyPlayStart(); _bufferTimer.start(); jump(); updateState(PLAY); } private function onBufferTimer(timerEvent:TimerEvent):void { var bufferTime:Number = _loadedTimestamp - time; switch(_state) { case PLAYING: if (!_loaded && bufferTime < MIN_BUFFER_TIME) { pause(); notifyBufferEmpty(); updateState(BUFFER); return; } break; case BUFFERING: if (bufferTime > MIN_BUFFER_TIME) { resume(); notifyBufferFull(); return; } break; } } override public function pause():void { super.pause(); updateState(PAUSE); } override public function resume():void { switch (_state) { case PAUSED: case BUFFERING: super.resume(); break; case STOPPED: play(); break; case SEEKING: jump(); break; } updateState(RESUME); } override public function seek(offset:Number):void { switch (_state) { case PAUSED: case SEEKING: case STOPPED: _fragmentTimer.stop(); _loader.close(); _offset = offset; super.seek(_offset); break; case PLAYING: case BUFFERING: _fragmentTimer.stop(); _loader.close(); _offset = offset; super.seek(_offset); jump(); break; } updateState(SEEK); } override public function get time():Number { return super.time + _offset; } override public function close():void { super.close(); appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE); appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK); _bufferTimer.stop(); notifyPlayStop(); reset(); updateState(STOP); } override public function get bytesLoaded():uint { if (_live) { return 1; } else { if (_loadedTimestamp == 0) { //WORKAROUND ScrubBar:531 ignores zero value return 1; } // seconds return _loadedTimestamp; } } override public function get bytesTotal():uint { if (_live) { return 1; } else { if (_loadedTimestamp == 0) { //WORKAROUND ScrubBar:531 ignore zero value; generate smallest possible fraction return uint.MAX_VALUE; } // seconds return _duration; } } public function loadManifest(url:String):void { var thisStream:DashNetStream = this; var loader:ManifestLoader = _context.buildManifestLoader(url); loader.addEventListener(ManifestEvent.LOADED, onLoad); loader.addEventListener(ManifestEvent.ERROR, onError); function onLoad(event:ManifestEvent):void { _context.console.info("Creating manifest..."); var manifest:ManifestHandler = _context.createManifestHandler(event.url, event.xml); _context.console.info("Created manifest, " + manifest.toString()); thisStream.init(); } function onError(event:ManifestEvent):void { /*loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(MediaErrorCodes.MEDIA_LOAD_FAILED)));*/ } loader.load(); } public function init():void { _live = _context.manifestHandler.live; _duration = _context.manifestHandler.duration; if (client && client.hasOwnProperty('onMetaData')) { client.onMetaData({ canSeekToEnd : !_live, videocodecid : 0, framerate : 24, videodatarate : 0, height : 0, width : 0, duration : _duration, dash: true }); } _loader = _context.fragmentLoader; _loader.addEventListener(StreamEvent.READY, onReady); _loader.addEventListener(FragmentEvent.LOADED, onLoaded); _loader.addEventListener(StreamEvent.END, onEnd); _loader.addEventListener(SegmentEvent.ERROR, onError); _loader.init(); } protected function appendFileHeader():void { var output:ByteArray = new ByteArray(); output.writeByte(0x46); // 'F' output.writeByte(0x4c); // 'L' output.writeByte(0x56); // 'V' output.writeByte(0x01); // version 0x01 var flags:uint = 0; flags |= 0x01; output.writeByte(flags); var offsetToWrite:uint = 9; // minimum file header byte count output.writeUnsignedInt(offsetToWrite); var previousTagSize0:uint = 0; output.writeUnsignedInt(previousTagSize0); appendBytes(output); } private function updateState(action:Number):void { switch (action) { case PLAY: _context.console.debug("Received PLAY action and changed to PLAYING state"); _state = PLAYING; break; case PAUSE: _context.console.debug("Received PAUSE action and changed to PAUSED state"); _state = PAUSED; break; case RESUME: _context.console.debug("Received RESUME action and changed to PLAYING state"); _state = PLAYING; break; case STOP: _context.console.debug("Received STOP action and changed to STOPPED state"); _state = STOPPED; break; case SEEK: switch (_state) { case PAUSED: _context.console.debug("Received SEEK action and changed to SEEKING state"); _state = SEEKING; break; case PLAYING: case BUFFERING: _context.console.debug("Received SEEK action and changed to PLAYING state"); _state = PLAYING; break; } break; case BUFFER: _context.console.debug("Received BUFFER action and changed to BUFFERING state"); _state = BUFFERING; break; } } private function jump():void { _offset = _loader.seek(_offset); _loadedTimestamp = 0; super.seek(_offset); appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK); _loader.loadFirstFragment(); } private function notifyPlayStart():void { dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, { code: NetStreamCodes.NETSTREAM_PLAY_START, level: "status" })); } private function notifyPlayStop():void { dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, { code: NetStreamCodes.NETSTREAM_PLAY_STOP, level: "status" })); } private function notifyPlayUnpublish():void { dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, { code: NetStreamCodes.NETSTREAM_PLAY_UNPUBLISH_NOTIFY, level: "status" })); } private function notifyBufferFull():void { dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, { code: NetStreamCodes.NETSTREAM_BUFFER_FULL, level: "status" })); } private function notifyBufferEmpty():void { dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, { code: NetStreamCodes.NETSTREAM_BUFFER_EMPTY, level: "status" })); } private function reset():void { _offset = 0; _loadedTimestamp = 0; _loaded = false; } private function onReady(event:StreamEvent):void { if (_state == PLAYING) { play(); } else { _state = STOPPED; } dispatchEvent(event); } private function onLoaded(event:FragmentEvent):void { _loadedTimestamp = event.endTimestamp; appendBytes(event.bytes); onFragmentTimer(); } private function onError(event:SegmentEvent):void { if (_state == INITIALIZING) { dispatchEvent(_context.buildStreamEvent(StreamEvent.ERROR)); } else { dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, { code: NetStreamCodes.NETSTREAM_FAILED, level: "status" })); } } private function onFragmentTimer(timerEvent:TimerEvent = null):void { _fragmentTimer.stop(); if ((_loadedTimestamp - time) < MAX_BUFFER_TIME) { _loader.loadNextFragment(); } else { _fragmentTimer.start(); } } private function onNetStatus(event:NetStatusEvent):void { switch(event.info.code) { case NetStreamCodes.NETSTREAM_BUFFER_EMPTY: if (_loaded) { close(); notifyPlayUnpublish(); } break; case NetStreamCodes.NETSTREAM_PLAY_STREAMNOTFOUND: close(); break; } } private function onEnd(event:StreamEvent):void { _loaded = true; _loadedTimestamp = _duration; } } }
/* * Copyright (c) 2014 castLabs GmbH * * 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 com.castlabs.dash { import com.castlabs.dash.events.FragmentEvent; import com.castlabs.dash.events.ManifestEvent; import com.castlabs.dash.events.SegmentEvent; import com.castlabs.dash.events.StreamEvent; import com.castlabs.dash.handlers.ManifestHandler; import com.castlabs.dash.loaders.FragmentLoader; import com.castlabs.dash.loaders.ManifestLoader; import flash.events.NetStatusEvent; import flash.events.TimerEvent; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.NetStreamAppendBytesAction; import flash.utils.ByteArray; import flash.utils.Timer; import com.castlabs.dash.utils.NetStreamCodes; public class DashNetStream extends NetStream { private const MIN_BUFFER_TIME:Number = 5; private const MAX_BUFFER_TIME:Number = 30; // actions private const PLAY:uint = 1; private const PAUSE:uint = 2; private const RESUME:uint = 3; private const STOP:uint = 4; private const SEEK:uint = 5; private const BUFFER:uint = 6; // states private const INITIALIZING:uint = 0; private const PLAYING:uint = 1; private const BUFFERING:uint = 2; private const SEEKING:uint = 3; private const PAUSED:uint = 4; private const STOPPED:uint = 5; protected var _context:DashContext; private var _state:uint = INITIALIZING; private var _loader:FragmentLoader; private var _loaded:Boolean = false; private var _offset:Number = 0; private var _loadedTimestamp:Number = 0; private var _duration:Number = 0; private var _live:Boolean; private var _bufferTimer:Timer; private var _fragmentTimer:Timer; public function DashNetStream(context:DashContext, connection:NetConnection) { super(connection); _context = context; addEventListener(NetStatusEvent.NET_STATUS, onNetStatus); _bufferTimer = new Timer(250); // 250 ms _bufferTimer.addEventListener(TimerEvent.TIMER, onBufferTimer); _fragmentTimer = new Timer(250); // 250 ms _fragmentTimer.addEventListener(TimerEvent.TIMER, onFragmentTimer); inBufferSeek = false; bufferTime = 0; bufferTimeMax = 0; maxPauseBufferTime = 0; useHardwareDecoder = true; } override public function play(...rest):void { if (typeof(rest[0]) == 'string' && rest[0] != '') { loadManifest(rest[0]); updateState(PLAY); return; } super.play(null); appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN); appendFileHeader(); notifyPlayStart(); _bufferTimer.start(); jump(); updateState(PLAY); } private function onBufferTimer(timerEvent:TimerEvent):void { var bufferTime:Number = _loadedTimestamp - time; switch(_state) { case PLAYING: if (!_loaded && bufferTime < MIN_BUFFER_TIME) { pause(); notifyBufferEmpty(); updateState(BUFFER); return; } break; case BUFFERING: if (bufferTime > MIN_BUFFER_TIME) { resume(); notifyBufferFull(); return; } break; } } override public function togglePause(): void { if (time >= _duration) return; if (_state == PLAYING) pause(); else resume(); } override public function pause():void { super.pause(); updateState(PAUSE); } override public function resume():void { switch (_state) { case PAUSED: case BUFFERING: super.resume(); break; case STOPPED: play(); break; case SEEKING: jump(); break; } updateState(RESUME); } override public function seek(offset:Number):void { if (offset >= MIN_BUFFER_TIME) offset = offset - MIN_BUFFER_TIME - 1; switch (_state) { case PAUSED: case SEEKING: case STOPPED: _fragmentTimer.stop(); _loader.close(); _offset = offset; super.seek(_offset); break; case PLAYING: case BUFFERING: _fragmentTimer.stop(); _loader.close(); _offset = offset; super.seek(_offset); jump(); break; } updateState(SEEK); } override public function get time():Number { return super.time + _offset; } override public function close():void { super.close(); appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE); appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK); _bufferTimer.stop(); notifyPlayStop(); reset(); updateState(STOP); } override public function get bytesLoaded():uint { if (_live) { return 1; } else { if (_loadedTimestamp == 0) { //WORKAROUND ScrubBar:531 ignores zero value return 1; } // seconds return _loadedTimestamp; } } override public function get bytesTotal():uint { if (_live) { return 1; } else { if (_loadedTimestamp == 0) { //WORKAROUND ScrubBar:531 ignore zero value; generate smallest possible fraction return uint.MAX_VALUE; } // seconds return _duration; } } public function loadManifest(url:String):void { var thisStream:DashNetStream = this; var loader:ManifestLoader = _context.buildManifestLoader(url); loader.addEventListener(ManifestEvent.LOADED, onLoad); loader.addEventListener(ManifestEvent.ERROR, onError); function onLoad(event:ManifestEvent):void { _context.console.info("Creating manifest..."); var manifest:ManifestHandler = _context.createManifestHandler(event.url, event.xml); _context.console.info("Created manifest, " + manifest.toString()); thisStream.init(); } function onError(event:ManifestEvent):void { /*loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(MediaErrorCodes.MEDIA_LOAD_FAILED)));*/ } loader.load(); } public function init():void { _live = _context.manifestHandler.live; _duration = _context.manifestHandler.duration; if (client && client.hasOwnProperty('onMetaData')) { client.onMetaData({ canSeekToEnd : !_live, videocodecid : 0, framerate : 24, videodatarate : 0, height : 0, width : 0, duration : _duration, dash: true }); } _loader = _context.fragmentLoader; _loader.addEventListener(StreamEvent.READY, onReady); _loader.addEventListener(FragmentEvent.LOADED, onLoaded); _loader.addEventListener(StreamEvent.END, onEnd); _loader.addEventListener(SegmentEvent.ERROR, onError); _loader.init(); } protected function appendFileHeader():void { var output:ByteArray = new ByteArray(); output.writeByte(0x46); // 'F' output.writeByte(0x4c); // 'L' output.writeByte(0x56); // 'V' output.writeByte(0x01); // version 0x01 var flags:uint = 0; flags |= 0x01; output.writeByte(flags); var offsetToWrite:uint = 9; // minimum file header byte count output.writeUnsignedInt(offsetToWrite); var previousTagSize0:uint = 0; output.writeUnsignedInt(previousTagSize0); appendBytes(output); } private function updateState(action:Number):void { switch (action) { case PLAY: _context.console.debug("Received PLAY action and changed to PLAYING state"); _state = PLAYING; break; case PAUSE: _context.console.debug("Received PAUSE action and changed to PAUSED state"); _state = PAUSED; break; case RESUME: _context.console.debug("Received RESUME action and changed to PLAYING state"); _state = PLAYING; break; case STOP: _context.console.debug("Received STOP action and changed to STOPPED state"); _state = STOPPED; break; case SEEK: switch (_state) { case PAUSED: _context.console.debug("Received SEEK action and changed to SEEKING state"); _state = SEEKING; break; case PLAYING: case BUFFERING: _context.console.debug("Received SEEK action and changed to PLAYING state"); _state = PLAYING; break; } break; case BUFFER: _context.console.debug("Received BUFFER action and changed to BUFFERING state"); _state = BUFFERING; break; } } private function jump():void { _offset = _loader.seek(_offset); _loadedTimestamp = 0; super.seek(_offset); appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK); _loader.loadFirstFragment(); } private function notifyPlayStart():void { dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, { code: NetStreamCodes.NETSTREAM_PLAY_START, level: "status" })); } private function notifyPlayStop():void { dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, { code: NetStreamCodes.NETSTREAM_PLAY_STOP, level: "status" })); } private function notifyPlayUnpublish():void { dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, { code: NetStreamCodes.NETSTREAM_PLAY_UNPUBLISH_NOTIFY, level: "status" })); } private function notifyBufferFull():void { dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, { code: NetStreamCodes.NETSTREAM_BUFFER_FULL, level: "status" })); } private function notifyBufferEmpty():void { dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, { code: NetStreamCodes.NETSTREAM_BUFFER_EMPTY, level: "status" })); } private function reset():void { _offset = 0; _loadedTimestamp = 0; _loaded = false; } private function onReady(event:StreamEvent):void { if (_state == PLAYING) { play(); } else { _state = STOPPED; } dispatchEvent(event); } private function onLoaded(event:FragmentEvent):void { _loadedTimestamp = event.endTimestamp; appendBytes(event.bytes); onFragmentTimer(); } private function onError(event:SegmentEvent):void { if (_state == INITIALIZING) { dispatchEvent(_context.buildStreamEvent(StreamEvent.ERROR)); } else { dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, { code: NetStreamCodes.NETSTREAM_FAILED, level: "status" })); } } private function onFragmentTimer(timerEvent:TimerEvent = null):void { _fragmentTimer.stop(); if ((_loadedTimestamp - time) < MAX_BUFFER_TIME) { _loader.loadNextFragment(); } else { _fragmentTimer.start(); } } private function onNetStatus(event:NetStatusEvent):void { switch(event.info.code) { case NetStreamCodes.NETSTREAM_BUFFER_EMPTY: if (_loaded) { close(); notifyPlayUnpublish(); } break; case NetStreamCodes.NETSTREAM_PLAY_STREAMNOTFOUND: close(); break; } } private function onEnd(event:StreamEvent):void { _loaded = true; _loadedTimestamp = _duration; } } }
Add togglePause function and temporary fix function seek on end range
Add togglePause function and temporary fix function seek on end range
ActionScript
mpl-2.0
XamanSoft/dashas,XamanSoft/dashas,XamanSoft/dashas
66d16e892691ebb10395dcd233a96f1bf348898d
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/ContainerView.as
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/ContainerView.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.beads { import org.apache.flex.core.BeadViewBase; import org.apache.flex.core.ContainerBase; import org.apache.flex.core.IBead; import org.apache.flex.core.IBeadLayout; import org.apache.flex.core.IBeadView; import org.apache.flex.core.ILayoutParent; import org.apache.flex.core.IParentIUIBase; import org.apache.flex.core.IStrand; import org.apache.flex.core.IUIBase; import org.apache.flex.core.UIBase; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.html.supportClasses.Border; import org.apache.flex.html.supportClasses.ContainerContentArea; import org.apache.flex.html.supportClasses.ScrollBar; /** * The ContainerView class is the default view for * the org.apache.flex.core.ContainerBase classes. * It lets you use some CSS styles to manage the border, background * and padding around the content area. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class ContainerView extends BeadViewBase implements IBeadView, ILayoutParent { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function ContainerView() { } /** * The actual parent that parents the children. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var actualParent:UIBase; /** * The layout. The layout may actually layout * the children of the internal content area * and not the pieces of the "chrome" like titlebars * and borders. The ContainerView or its subclass will have some * baked-in logic for handling the chrome. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var layout:IBeadLayout; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set strand(value:IStrand):void { super.strand = value; var host:UIBase = value as UIBase; if (host.isWidthSizedToContent() && host.isHeightSizedToContent()) { // if both dimensions are sized to content, then only draw the // borders, etc, after a child is added. The children in an MXML // document don't send this event until the last child is added. host.addEventListener("childrenAdded", changeHandler); host.addEventListener("layoutNeeded", changeHandler); // listen for width and height changes as well in case the app // switches away from content sizing via binding or other code host.addEventListener("widthChanged", changeHandler); host.addEventListener("heightChanged", changeHandler); } else { // otherwise, listen for size changes before drawing // borders and laying out children. host.addEventListener("widthChanged", changeHandler); host.addEventListener("heightChanged", changeHandler); host.addEventListener("sizeChanged", sizeChangeHandler); // if we have fixed size in both dimensions, wait for children // to be added then run a layout pass right then as the // parent won't kick off any other event in the child if (!isNaN(host.explicitWidth) && !isNaN(host.explicitHeight)) host.addEventListener("childrenAdded", changeHandler); } checkActualParent(); } private function checkActualParent():Boolean { var host:UIBase = UIBase(_strand); if (contentAreaNeeded()) { if (actualParent == null || actualParent == host) { actualParent = new ContainerContentArea(); actualParent.className = "ActualParent"; host.addElement(actualParent, false); ContainerBase(host).setActualParent(actualParent); } return true; } else { actualParent = host; } return false; } private function sizeChangeHandler(event:Event):void { var host:UIBase = UIBase(_strand); host.addEventListener("childrenAdded", changeHandler); host.addEventListener("layoutNeeded", changeHandler); host.addEventListener("itemsCreated", changeHandler); changeHandler(event); } private var inChangeHandler:Boolean; /** * React if the size changed or content changed * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function changeHandler(event:Event):void { if (inChangeHandler) return; inChangeHandler = true; var host:UIBase = UIBase(_strand); if (layout == null) { layout = _strand.getBeadByType(IBeadLayout) as IBeadLayout; if (layout == null) { var c:Class = ValuesManager.valuesImpl.getValue(host, "iBeadLayout"); if (c) { layout = new c() as IBeadLayout; _strand.addBead(layout); } } } var padding:Object = determinePadding(); if (checkActualParent()) { actualParent.x = padding.paddingLeft; actualParent.y = padding.paddingTop; } var pb:Number = padding.paddingBottom; if (isNaN(pb)) pb = 0; var pr:Number = padding.paddingRight; if (isNaN(pr)) pr = 0; // if the width is dictated by the parent if (!host.isWidthSizedToContent()) { if (actualParent != host) { // force the width of the internal content area as desired. actualParent.setWidth(host.width - padding.paddingLeft - pr); } // run the layout layout.layout(); } else { // if the height is dictated by the parent if (!host.isHeightSizedToContent()) { if (actualParent != host) { // force the height actualParent.setHeight(host.height - padding.paddingTop - pb); } } layout.layout(); if (actualParent != host) { // actualParent.width should be the new width after layout. // set the host's width. This should send a widthChanged event and // have it blocked at the beginning of this method host.setWidth(padding.paddingLeft + pr + actualParent.width); } } // and if the height is sized to content, set the height now as well. if (host != actualParent) { if (host.isHeightSizedToContent()) host.setHeight(padding.paddingTop + pb + actualParent.height); else actualParent.setHeight(host.height - padding.paddingTop - pb); } var backgroundColor:Object = ValuesManager.valuesImpl.getValue(host, "background-color"); var backgroundImage:Object = ValuesManager.valuesImpl.getValue(host, "background-image"); if (backgroundColor != null || backgroundImage != null) { if (host.getBeadByType(IBackgroundBead) == null) host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBackgroundBead")) as IBead); } var borderStyle:String; var borderStyles:Object = ValuesManager.valuesImpl.getValue(host, "border"); if (borderStyles is Array) { borderStyle = borderStyles[1]; } if (borderStyle == null) { borderStyle = ValuesManager.valuesImpl.getValue(host, "border-style") as String; } if (borderStyle != null && borderStyle != "none") { if (host.getBeadByType(IBorderBead) == null) host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBorderBead")) as IBead); } inChangeHandler = false; } /** * Determines the top and left padding values, if any, as set by * padding style values. This includes "padding" for all padding values * as well as "padding-left" and "padding-top". * * Returns an object with paddingLeft and paddingTop properties. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function determinePadding():Object { var paddingLeft:Object; var paddingTop:Object; var paddingRight:Object; var paddingBottom:Object; var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding"); if (padding is Array) { if (padding.length == 1) paddingLeft = paddingTop = padding[0]; else if (padding.length <= 3) { paddingLeft = padding[1]; paddingTop = padding[0]; } else if (padding.length == 4) { paddingLeft = padding[3]; paddingTop = padding[0]; } } else if (padding == null) { paddingLeft = ValuesManager.valuesImpl.getValue(_strand, "padding-left"); paddingTop = ValuesManager.valuesImpl.getValue(_strand, "padding-top"); paddingRight = ValuesManager.valuesImpl.getValue(_strand, "padding-right"); paddingBottom = ValuesManager.valuesImpl.getValue(_strand, "padding-bottom"); } else { paddingLeft = paddingTop = padding; paddingRight = paddingBottom = padding; } var pl:Number = Number(paddingLeft); var pt:Number = Number(paddingTop); var pr:Number = Number(paddingRight); var pb:Number = Number(paddingBottom); return {paddingLeft:pl, paddingTop:pt, paddingRight:pr, paddingBottom:pb}; } /** * Returns true if container to create a separate ContainerContentArea. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function contentAreaNeeded():Boolean { var padding:Object = determinePadding(); return (!isNaN(padding.paddingLeft) && padding.paddingLeft > 0 || !isNaN(padding.paddingTop) && padding.paddingTop > 0); } /** * The parent of the children. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get contentView():IParentIUIBase { return actualParent; } /** * The host component, which can resize to different slots. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get resizableView():IUIBase { return _strand as IUIBase; } private var inGetViewHeight:Boolean; /** * @copy org.apache.flex.core.IBeadView#viewHeight * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function get viewHeight():Number { if (inGetViewHeight) { trace("ContainerView: no height set for " + host); return host["$height"]; } inGetViewHeight = true; var vh:Number = contentView.height; inGetViewHeight = false; return vh; } private var inGetViewWidth:Boolean; /** * @copy org.apache.flex.core.IBeadView#viewWidth * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function get viewWidth():Number { if (inGetViewWidth) { trace("ContainerView: no width set for " + host); return host["$width"]; } inGetViewWidth = true; var vw:Number = contentView.width; inGetViewWidth = false; return vw; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.beads { import org.apache.flex.core.BeadViewBase; import org.apache.flex.core.ContainerBase; import org.apache.flex.core.IBead; import org.apache.flex.core.IBeadLayout; import org.apache.flex.core.IBeadView; import org.apache.flex.core.ILayoutParent; import org.apache.flex.core.IParentIUIBase; import org.apache.flex.core.IStrand; import org.apache.flex.core.IUIBase; import org.apache.flex.core.UIBase; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.html.supportClasses.Border; import org.apache.flex.html.supportClasses.ContainerContentArea; import org.apache.flex.html.supportClasses.ScrollBar; /** * The ContainerView class is the default view for * the org.apache.flex.core.ContainerBase classes. * It lets you use some CSS styles to manage the border, background * and padding around the content area. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class ContainerView extends BeadViewBase implements IBeadView, ILayoutParent { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function ContainerView() { } /** * The actual parent that parents the children. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var actualParent:UIBase; /** * The layout. The layout may actually layout * the children of the internal content area * and not the pieces of the "chrome" like titlebars * and borders. The ContainerView or its subclass will have some * baked-in logic for handling the chrome. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var layout:IBeadLayout; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set strand(value:IStrand):void { super.strand = value; var host:UIBase = value as UIBase; if (host.isWidthSizedToContent() && host.isHeightSizedToContent()) { // if both dimensions are sized to content, then only draw the // borders, etc, after a child is added. The children in an MXML // document don't send this event until the last child is added. host.addEventListener("childrenAdded", changeHandler); host.addEventListener("layoutNeeded", changeHandler); // listen for width and height changes as well in case the app // switches away from content sizing via binding or other code host.addEventListener("widthChanged", changeHandler); host.addEventListener("heightChanged", changeHandler); } else { // otherwise, listen for size changes before drawing // borders and laying out children. host.addEventListener("widthChanged", changeHandler); host.addEventListener("heightChanged", changeHandler); host.addEventListener("sizeChanged", sizeChangeHandler); // if we have fixed size in both dimensions, wait for children // to be added then run a layout pass right then as the // parent won't kick off any other event in the child if (!isNaN(host.explicitWidth) && !isNaN(host.explicitHeight)) host.addEventListener("childrenAdded", changeHandler); } checkActualParent(); } private function checkActualParent():Boolean { var host:UIBase = UIBase(_strand); if (contentAreaNeeded()) { if (actualParent == null || actualParent == host) { actualParent = new ContainerContentArea(); actualParent.className = "ActualParent"; host.addElement(actualParent, false); ContainerBase(host).setActualParent(actualParent); } return true; } else { actualParent = host; } return false; } private function sizeChangeHandler(event:Event):void { var host:UIBase = UIBase(_strand); host.addEventListener("childrenAdded", changeHandler); host.addEventListener("layoutNeeded", changeHandler); host.addEventListener("itemsCreated", changeHandler); changeHandler(event); } private var inChangeHandler:Boolean; /** * React if the size changed or content changed * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function changeHandler(event:Event):void { if (inChangeHandler) return; inChangeHandler = true; var host:UIBase = UIBase(_strand); if (layout == null) { layout = _strand.getBeadByType(IBeadLayout) as IBeadLayout; if (layout == null) { var c:Class = ValuesManager.valuesImpl.getValue(host, "iBeadLayout"); if (c) { layout = new c() as IBeadLayout; _strand.addBead(layout); } } } var padding:Object = determinePadding(); if (checkActualParent()) { actualParent.x = padding.paddingLeft; actualParent.y = padding.paddingTop; } var pb:Number = padding.paddingBottom; if (isNaN(pb)) pb = 0; var pr:Number = padding.paddingRight; if (isNaN(pr)) pr = 0; // if the width is dictated by the parent if (!host.isWidthSizedToContent()) { if (actualParent != host) { // force the width of the internal content area as desired. actualParent.setWidth(host.width - padding.paddingLeft - pr); } // run the layout layout.layout(); } else { // if the height is dictated by the parent if (!host.isHeightSizedToContent()) { if (actualParent != host) { // force the height actualParent.setHeight(host.height - padding.paddingTop - pb); } } layout.layout(); if (actualParent != host) { // actualParent.width should be the new width after layout. // set the host's width. This should send a widthChanged event and // have it blocked at the beginning of this method host.setWidth(padding.paddingLeft + pr + actualParent.width); } } // and if the height is sized to content, set the height now as well. if (host != actualParent) { if (host.isHeightSizedToContent()) host.setHeight(padding.paddingTop + pb + actualParent.height); else actualParent.setHeight(host.height - padding.paddingTop - pb); } var backgroundColor:Object = ValuesManager.valuesImpl.getValue(host, "background-color"); var backgroundImage:Object = ValuesManager.valuesImpl.getValue(host, "background-image"); if (backgroundColor != null || backgroundImage != null) { if (host.getBeadByType(IBackgroundBead) == null) host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBackgroundBead")) as IBead); } var borderStyle:String; var borderStyles:Object = ValuesManager.valuesImpl.getValue(host, "border"); if (borderStyles is Array) { borderStyle = borderStyles[1]; } if (borderStyle == null) { borderStyle = ValuesManager.valuesImpl.getValue(host, "border-style") as String; } if (borderStyle != null && borderStyle != "none") { if (host.getBeadByType(IBorderBead) == null) host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBorderBead")) as IBead); } inChangeHandler = false; } /** * Determines the top and left padding values, if any, as set by * padding style values. This includes "padding" for all padding values * as well as "padding-left" and "padding-top". * * Returns an object with paddingLeft and paddingTop properties. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function determinePadding():Object { var paddingLeft:Object; var paddingTop:Object; var paddingRight:Object; var paddingBottom:Object; var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding"); if (padding is Array) { if (padding.length == 1) paddingLeft = paddingTop = padding[0]; else if (padding.length <= 3) { paddingLeft = padding[1]; paddingTop = padding[0]; } else if (padding.length == 4) { paddingLeft = padding[3]; paddingTop = padding[0]; } } else if (padding == null) { paddingLeft = ValuesManager.valuesImpl.getValue(_strand, "padding-left"); paddingTop = ValuesManager.valuesImpl.getValue(_strand, "padding-top"); paddingRight = ValuesManager.valuesImpl.getValue(_strand, "padding-right"); paddingBottom = ValuesManager.valuesImpl.getValue(_strand, "padding-bottom"); } else { paddingLeft = paddingTop = padding; paddingRight = paddingBottom = padding; } var pl:Number = Number(paddingLeft); var pt:Number = Number(paddingTop); var pr:Number = Number(paddingRight); var pb:Number = Number(paddingBottom); return {paddingLeft:pl, paddingTop:pt, paddingRight:pr, paddingBottom:pb}; } /** * Returns true if container to create a separate ContainerContentArea. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function contentAreaNeeded():Boolean { var padding:Object = determinePadding(); return (!isNaN(padding.paddingLeft) && padding.paddingLeft > 0 || !isNaN(padding.paddingTop) && padding.paddingTop > 0); } /** * The parent of the children. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get contentView():IParentIUIBase { return actualParent; } /** * The host component, which can resize to different slots. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get resizableView():IUIBase { return _strand as IUIBase; } private var inGetViewHeight:Boolean; /** * @copy org.apache.flex.core.IBeadView#viewHeight * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function get viewHeight():Number { if (inGetViewHeight) { //trace("ContainerView: no height set for " + host); return host["$height"]; } inGetViewHeight = true; var vh:Number = contentView.height; inGetViewHeight = false; return vh; } private var inGetViewWidth:Boolean; /** * @copy org.apache.flex.core.IBeadView#viewWidth * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function get viewWidth():Number { if (inGetViewWidth) { //trace("ContainerView: no width set for " + host); return host["$width"]; } inGetViewWidth = true; var vw:Number = contentView.width; inGetViewWidth = false; return vw; } } }
remove trace
remove trace
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
24faad97c80881965c913ca50c65d82e783be9c5
frameworks/as/projects/FlexJSJX/src/org/apache/flex/effects/Wipe.as
frameworks/as/projects/FlexJSJX/src/org/apache/flex/effects/Wipe.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.effects { import flash.geom.Rectangle; import org.apache.flex.core.IDocument; import org.apache.flex.core.IUIBase; /** * The Fade effect animates a UI component's alpha or opacity. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class Wipe extends Tween implements IDocument { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param target Object ID or reference to an object that will * have its x and/or y property animated. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function Wipe(target:IUIBase = null) { super(); this.actualTarget = target; listener = this; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * The document. */ private var document:Object; /** * @private * The target. */ private var actualTarget:IUIBase; /** * The target as the String id * of a widget in an MXML Document. */ public var target:String; /** * The direction of the Wipe. "up" means the top will be the last * part to disappear. "down" will reveal from the top down. */ public var direction:String; private var wiper:PlatformWiper; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- public function setDocument(document:Object, id:String = null):void { this.document = document; } /** * @private */ override public function play():void { if (target != null) actualTarget = document[target]; wiper.target = actualTarget; if (direction == "up") { startValue = actualTarget.height; endValue = 0; } else { startValue = 0; endValue = actualTarget.height; wiper.visibleRect = new Rectangle(0, 0, actualTarget.width, 0); } super.play(); } public function onTweenUpdate(value:Number):void { wiper.visibleRect = new Rectangle(0, 0, actualTarget.width, value); } public function onTweenEnd(value:Number):void { wiper.target = null; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.effects { import flash.geom.Rectangle; import org.apache.flex.core.IDocument; import org.apache.flex.core.IUIBase; /** * The Fade effect animates a UI component's alpha or opacity. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class Wipe extends Tween implements IDocument { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param target Object ID or reference to an object that will * have its x and/or y property animated. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function Wipe(target:IUIBase = null) { super(); this.actualTarget = target; listener = this; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * The document. */ private var document:Object; /** * @private * The target. */ private var actualTarget:IUIBase; /** * The target as the String id * of a widget in an MXML Document. */ public var target:String; /** * The direction of the Wipe. "up" means the top will be the last * part to disappear. "down" will reveal from the top down. */ public var direction:String; private var wiper:PlatformWiper = new PlatformWiper(); //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- public function setDocument(document:Object, id:String = null):void { this.document = document; } /** * @private */ override public function play():void { if (target != null) actualTarget = document[target]; wiper.target = actualTarget; if (direction == "up") { startValue = actualTarget.height; endValue = 0; } else { startValue = 0; endValue = actualTarget.height; // WipeDown makes something appear actualTarget.visible = true; wiper.visibleRect = new Rectangle(0, 0, actualTarget.width, 0); } super.play(); } public function onTweenUpdate(value:Number):void { trace(actualTarget, value); wiper.visibleRect = new Rectangle(0, 0, actualTarget.width, value); } public function onTweenEnd(value:Number):void { // WipeUp makes something disappear if (direction == "up") actualTarget.visible = false; wiper.target = null; } } }
fix wipe effect
fix wipe effect
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
d7aa53de193c30b4478fc8dfb963d0b9df062429
src/aerys/minko/scene/node/AbstractSceneNode.as
src/aerys/minko/scene/node/AbstractSceneNode.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.shader.part.phong.attenuation.MatrixShadowMapAttenuationShaderPart; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.IRebindableController; import aerys.minko.scene.controller.TransformController; import aerys.minko.type.Signal; import aerys.minko.type.clone.CloneOptions; import aerys.minko.type.clone.ControllerCloneAction; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; use namespace minko_scene; /** * The base class to extend in order to create new scene node types. * * @author Jean-Marc Le Roux * */ public class AbstractSceneNode implements ISceneNode { private static var _id : uint; private var _name : String; private var _root : ISceneNode; private var _parent : Group; private var _visible : Boolean; private var _computedVisibility : Boolean; private var _transform : Matrix4x4; private var _controllers : Vector.<AbstractController>; private var _added : Signal; private var _removed : Signal; private var _addedToScene : Signal; private var _removedFromScene : Signal; private var _controllerAdded : Signal; private var _controllerRemoved : Signal; private var _visibilityChanged : Signal; private var _computedVisibilityChanged : Signal; private var _localToWorldChanged : Signal; final public function get x() : Number { return _transform.translationX; } final public function set x(value : Number) : void { _transform.translationX = value; } final public function get y() : Number { return _transform.translationX; } final public function set y(value : Number) : void { _transform.translationY = value; } final public function get z() : Number { return _transform.translationX; } final public function set z(value : Number) : void { _transform.translationZ = value; } final public function get rotationX() : Number { return _transform.rotationX; } final public function set rotationX(value : Number) : void { _transform.rotationX = value; } final public function get rotationY() : Number { return _transform.rotationY; } final public function set rotationY(value : Number) : void { _transform.rotationY = value; } final public function get rotationZ() : Number { return _transform.rotationZ; } final public function set rotationZ(value : Number) : void { _transform.rotationZ = value; } final public function get scaleX() : Number { return _transform.scaleX; } final public function set scaleX(value : Number) : void { _transform.scaleX = value; } final public function get scaleY() : Number { return _transform.scaleY; } final public function set scaleY(value : Number) : void { _transform.scaleY = value; } final public function get scaleZ() : Number { return _transform.scaleZ; } final public function set scaleZ(value : Number) : void { _transform.scaleZ = value; } public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } final public function get parent() : Group { return _parent; } final public function set parent(value : Group) : void { if (value == _parent) return ; // remove child if (_parent) { var oldParent : Group = _parent; oldParent._children.splice(oldParent.getChildIndex(this), 1); parent._numChildren--; _parent = null; _removed.execute(this, oldParent); oldParent.descendantRemoved.execute(oldParent, this); } // set parent _parent = value; // add child if (_parent) { _parent._children[_parent.numChildren] = this; _parent._numChildren++; _added.execute(this, _parent); _parent.descendantAdded.execute(_parent, this); } } final public function get scene() : Scene { return _root as Scene; } final public function get root() : ISceneNode { return _root; } final public function get transform() : Matrix4x4 { return _transform; } final public function get added() : Signal { return _added; } final public function get removed() : Signal { return _removed; } final public function get addedToScene() : Signal { return _addedToScene; } final public function get removedFromScene() : Signal { return _removedFromScene; } public function get numControllers() : uint { return _controllers.length; } public function get controllerAdded() : Signal { return _controllerAdded; } public function get controllerRemoved() : Signal { return _controllerRemoved; } public function get localToWorldTransformChanged() : Signal { return _localToWorldChanged; } public function AbstractSceneNode() { initialize(); } private function initialize() : void { _name = getDefaultSceneName(this); _visible = true; _computedVisibility = true; _transform = new Matrix4x4(); _controllers = new <AbstractController>[]; _added = new Signal('AbstractSceneNode.added'); _removed = new Signal('AbstractSceneNode.removed'); _addedToScene = new Signal('AbstractSceneNode.addedToScene'); _removedFromScene = new Signal('AbstractSceneNode.removedFromScene'); _controllerAdded = new Signal('AbstractSceneNode.controllerAdded'); _controllerRemoved = new Signal('AbstractSceneNode.controllerRemoved'); _visibilityChanged = new Signal('AbstractSceneNode.visibilityChanged'); _computedVisibilityChanged = new Signal('AbstractSceneNode.computedVisibilityChanged'); _localToWorldChanged = new Signal('AbstractSceneNode.localToWorldChanged'); updateRoot(); _added.add(addedHandler); _removed.add(removedHandler); _addedToScene.add(addedToSceneHandler); _removedFromScene.add(removedFromSceneHandler); addController(new TransformController()); } protected function addedHandler(child : ISceneNode, ancestor : Group) : void { updateRoot(); } protected function removedHandler(child : ISceneNode, ancestor : Group) : void { updateRoot(); } private function updateRoot() : void { var newRoot : ISceneNode = _parent ? _parent.root : this; var oldRoot : ISceneNode = _root; if (newRoot != oldRoot) { _root = newRoot; if (oldRoot is Scene) _removedFromScene.execute(this, oldRoot); if (newRoot is Scene) _addedToScene.execute(this, newRoot); } } protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } public function addController(controller : AbstractController) : ISceneNode { _controllers.push(controller); controller.addTarget(this); _controllerAdded.execute(this, controller); return this; } public function removeController(controller : AbstractController) : ISceneNode { var numControllers : uint = _controllers.length - 1; var controllerId : int = _controllers.indexOf(controller); if (controllerId < 0) throw new Error('The controller is not on the node.'); _controllers[controllerId] = _controllers[numControllers]; _controllers.length = numControllers; controller.removeTarget(this); _controllerRemoved.execute(this, controller); return this; } public function getController(index : uint) : AbstractController { return _controllers[index]; } public function getControllersByType(type : Class, controllers : Vector.<AbstractController> = null) : Vector.<AbstractController> { controllers ||= new Vector.<AbstractController>(); var nbControllers : uint = numControllers; for (var i : int = 0; i < nbControllers; ++i) { var ctrl : AbstractController = getController(i); if (ctrl is type) controllers.push(ctrl); } return controllers; } public static function getDefaultSceneName(scene : ISceneNode) : String { var className : String = getQualifiedClassName(scene); return className.substr(className.lastIndexOf(':') + 1) + '_' + (++_id); } minko_scene function cloneNode() : AbstractSceneNode { throw new Error('Must be overriden'); } public final function clone(cloneOptions : CloneOptions = null) : ISceneNode { cloneOptions ||= CloneOptions.defaultOptions; // fill up 2 dics with all nodes and controllers var nodeMap : Dictionary = new Dictionary(); var controllerMap : Dictionary = new Dictionary(); listItems(cloneNode(), nodeMap, controllerMap); // clone controllers with respect with instructions cloneControllers(controllerMap, cloneOptions); // rebind all controller dependencies. rebindControllerDependencies(controllerMap, nodeMap, cloneOptions); // add cloned/rebinded/original controllers to clones for (var objNode : Object in nodeMap) { var node : AbstractSceneNode = AbstractSceneNode(objNode); var numControllers : uint = node.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controller : AbstractController = controllerMap[node.getController(controllerId)]; if (controller != null) nodeMap[node].addController(controller); } } return nodeMap[this]; } minko_scene function getLocalToWorldTransformUnsafe() : Matrix4x4 { var transformController : TransformController = root.getControllersByType( TransformController )[0] as TransformController; return transformController.getLocalToWorldTransform(this); } public function getLocalToWorldTransform(output : Matrix4x4 = null) : Matrix4x4 { output ||= new Matrix4x4(); output.copyFrom(getLocalToWorldTransformUnsafe()); return output; } public function getWorldToLocalTransform(output : Matrix4x4 = null) : Matrix4x4 { return getLocalToWorldTransform(output).invert(); } public function localToWorld(vector : Vector4, output : Vector4 = null) : Vector4 { var localToWorld : Matrix4x4 = getLocalToWorldTransformUnsafe(); return localToWorld.transformVector(vector, output); } public function deltaLocalToWorld(vector : Vector4, output : Vector4 = null) : Vector4 { var localToWorld : Matrix4x4 = getLocalToWorldTransformUnsafe(); return localToWorld.deltaTransformVector(vector, output); } private function listItems(clonedRoot : ISceneNode, nodes : Dictionary, controllers : Dictionary) : void { var numControllers : uint = this.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) controllers[getController(controllerId)] = true; nodes[this] = clonedRoot; if (this is Group) { var group : Group = Group(this); var clonedGroup : Group = Group(clonedRoot); var numChildren : uint = group.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(group.getChildAt(childId)); var clonedChild : AbstractSceneNode = AbstractSceneNode(clonedGroup.getChildAt(childId)); child.listItems(clonedChild, nodes, controllers); } } } private function cloneControllers(controllerMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (action == ControllerCloneAction.CLONE) controllerMap[controller] = controller.clone(); else if (action == ControllerCloneAction.REASSIGN) controllerMap[controller] = controller; else if (action == ControllerCloneAction.IGNORE) controllerMap[controller] = null; else throw new Error(); } } private function rebindControllerDependencies(controllerMap : Dictionary, nodeMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (controller is IRebindableController && action == ControllerCloneAction.CLONE) IRebindableController(controllerMap[controller]).rebindDependencies(nodeMap, controllerMap); } } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.shader.part.phong.attenuation.MatrixShadowMapAttenuationShaderPart; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.IRebindableController; import aerys.minko.scene.controller.TransformController; import aerys.minko.type.Signal; import aerys.minko.type.clone.CloneOptions; import aerys.minko.type.clone.ControllerCloneAction; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; import flash.utils.setTimeout; use namespace minko_scene; /** * The base class to extend in order to create new scene node types. * * @author Jean-Marc Le Roux * */ public class AbstractSceneNode implements ISceneNode { private static var _id : uint; private var _name : String; private var _root : ISceneNode; private var _parent : Group; private var _visible : Boolean; private var _computedVisibility : Boolean; private var _transform : Matrix4x4; private var _controllers : Vector.<AbstractController>; private var _added : Signal; private var _removed : Signal; private var _addedToScene : Signal; private var _removedFromScene : Signal; private var _controllerAdded : Signal; private var _controllerRemoved : Signal; private var _visibilityChanged : Signal; private var _computedVisibilityChanged : Signal; private var _localToWorldChanged : Signal; final public function get x() : Number { return _transform.translationX; } final public function set x(value : Number) : void { _transform.translationX = value; } final public function get y() : Number { return _transform.translationX; } final public function set y(value : Number) : void { _transform.translationY = value; } final public function get z() : Number { return _transform.translationX; } final public function set z(value : Number) : void { _transform.translationZ = value; } final public function get rotationX() : Number { return _transform.rotationX; } final public function set rotationX(value : Number) : void { _transform.rotationX = value; } final public function get rotationY() : Number { return _transform.rotationY; } final public function set rotationY(value : Number) : void { _transform.rotationY = value; } final public function get rotationZ() : Number { return _transform.rotationZ; } final public function set rotationZ(value : Number) : void { _transform.rotationZ = value; } final public function get scaleX() : Number { return _transform.scaleX; } final public function set scaleX(value : Number) : void { _transform.scaleX = value; } final public function get scaleY() : Number { return _transform.scaleY; } final public function set scaleY(value : Number) : void { _transform.scaleY = value; } final public function get scaleZ() : Number { return _transform.scaleZ; } final public function set scaleZ(value : Number) : void { _transform.scaleZ = value; } public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } final public function get parent() : Group { return _parent; } final public function set parent(value : Group) : void { if (value == _parent) return ; // remove child if (_parent) { var oldParent : Group = _parent; oldParent._children.splice(oldParent.getChildIndex(this), 1); parent._numChildren--; _parent = null; _removed.execute(this, oldParent); oldParent.descendantRemoved.execute(oldParent, this); } // set parent _parent = value; // add child if (_parent) { _parent._children[_parent.numChildren] = this; _parent._numChildren++; _added.execute(this, _parent); _parent.descendantAdded.execute(_parent, this); } } final public function get scene() : Scene { return _root as Scene; } final public function get root() : ISceneNode { return _root; } final public function get transform() : Matrix4x4 { return _transform; } final public function get added() : Signal { return _added; } final public function get removed() : Signal { return _removed; } final public function get addedToScene() : Signal { return _addedToScene; } final public function get removedFromScene() : Signal { return _removedFromScene; } public function get numControllers() : uint { return _controllers.length; } public function get controllerAdded() : Signal { return _controllerAdded; } public function get controllerRemoved() : Signal { return _controllerRemoved; } public function get localToWorldTransformChanged() : Signal { return _localToWorldChanged; } public function AbstractSceneNode() { initialize(); } private function initialize() : void { _name = getDefaultSceneName(this); _visible = true; _computedVisibility = true; _transform = new Matrix4x4(); _controllers = new <AbstractController>[]; _added = new Signal('AbstractSceneNode.added'); _removed = new Signal('AbstractSceneNode.removed'); _addedToScene = new Signal('AbstractSceneNode.addedToScene'); _removedFromScene = new Signal('AbstractSceneNode.removedFromScene'); _controllerAdded = new Signal('AbstractSceneNode.controllerAdded'); _controllerRemoved = new Signal('AbstractSceneNode.controllerRemoved'); _visibilityChanged = new Signal('AbstractSceneNode.visibilityChanged'); _computedVisibilityChanged = new Signal('AbstractSceneNode.computedVisibilityChanged'); _localToWorldChanged = new Signal('AbstractSceneNode.localToWorldChanged'); updateRoot(); _added.add(addedHandler); _removed.add(removedHandler); _addedToScene.add(addedToSceneHandler); _removedFromScene.add(removedFromSceneHandler); addController(new TransformController()); } protected function addedHandler(child : ISceneNode, ancestor : Group) : void { setTimeout(updateRoot, 0); } protected function removedHandler(child : ISceneNode, ancestor : Group) : void { setTimeout(updateRoot, 0); } private function updateRoot() : void { var newRoot : ISceneNode = _parent ? _parent.root : this; var oldRoot : ISceneNode = _root; if (newRoot != oldRoot) { _root = newRoot; if (oldRoot is Scene) _removedFromScene.execute(this, oldRoot); if (newRoot is Scene) _addedToScene.execute(this, newRoot); } } protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } public function addController(controller : AbstractController) : ISceneNode { _controllers.push(controller); controller.addTarget(this); _controllerAdded.execute(this, controller); return this; } public function removeController(controller : AbstractController) : ISceneNode { var numControllers : uint = _controllers.length - 1; var controllerId : int = _controllers.indexOf(controller); if (controllerId < 0) throw new Error('The controller is not on the node.'); _controllers[controllerId] = _controllers[numControllers]; _controllers.length = numControllers; controller.removeTarget(this); _controllerRemoved.execute(this, controller); return this; } public function getController(index : uint) : AbstractController { return _controllers[index]; } public function getControllersByType(type : Class, controllers : Vector.<AbstractController> = null) : Vector.<AbstractController> { controllers ||= new Vector.<AbstractController>(); var nbControllers : uint = numControllers; for (var i : int = 0; i < nbControllers; ++i) { var ctrl : AbstractController = getController(i); if (ctrl is type) controllers.push(ctrl); } return controllers; } public static function getDefaultSceneName(scene : ISceneNode) : String { var className : String = getQualifiedClassName(scene); return className.substr(className.lastIndexOf(':') + 1) + '_' + (++_id); } minko_scene function cloneNode() : AbstractSceneNode { throw new Error('Must be overriden'); } public final function clone(cloneOptions : CloneOptions = null) : ISceneNode { cloneOptions ||= CloneOptions.defaultOptions; // fill up 2 dics with all nodes and controllers var nodeMap : Dictionary = new Dictionary(); var controllerMap : Dictionary = new Dictionary(); listItems(cloneNode(), nodeMap, controllerMap); // clone controllers with respect with instructions cloneControllers(controllerMap, cloneOptions); // rebind all controller dependencies. rebindControllerDependencies(controllerMap, nodeMap, cloneOptions); // add cloned/rebinded/original controllers to clones for (var objNode : Object in nodeMap) { var node : AbstractSceneNode = AbstractSceneNode(objNode); var numControllers : uint = node.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controller : AbstractController = controllerMap[node.getController(controllerId)]; if (controller != null) nodeMap[node].addController(controller); } } return nodeMap[this]; } minko_scene function getLocalToWorldTransformUnsafe() : Matrix4x4 { var transformController : TransformController = root.getControllersByType( TransformController )[0] as TransformController; return transformController.getLocalToWorldTransform(this); } public function getLocalToWorldTransform(output : Matrix4x4 = null) : Matrix4x4 { output ||= new Matrix4x4(); output.copyFrom(getLocalToWorldTransformUnsafe()); return output; } public function getWorldToLocalTransform(output : Matrix4x4 = null) : Matrix4x4 { return getLocalToWorldTransform(output).invert(); } public function localToWorld(vector : Vector4, output : Vector4 = null) : Vector4 { var localToWorld : Matrix4x4 = getLocalToWorldTransformUnsafe(); return localToWorld.transformVector(vector, output); } public function deltaLocalToWorld(vector : Vector4, output : Vector4 = null) : Vector4 { var localToWorld : Matrix4x4 = getLocalToWorldTransformUnsafe(); return localToWorld.deltaTransformVector(vector, output); } private function listItems(clonedRoot : ISceneNode, nodes : Dictionary, controllers : Dictionary) : void { var numControllers : uint = this.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) controllers[getController(controllerId)] = true; nodes[this] = clonedRoot; if (this is Group) { var group : Group = Group(this); var clonedGroup : Group = Group(clonedRoot); var numChildren : uint = group.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(group.getChildAt(childId)); var clonedChild : AbstractSceneNode = AbstractSceneNode(clonedGroup.getChildAt(childId)); child.listItems(clonedChild, nodes, controllers); } } } private function cloneControllers(controllerMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (action == ControllerCloneAction.CLONE) controllerMap[controller] = controller.clone(); else if (action == ControllerCloneAction.REASSIGN) controllerMap[controller] = controller; else if (action == ControllerCloneAction.IGNORE) controllerMap[controller] = null; else throw new Error(); } } private function rebindControllerDependencies(controllerMap : Dictionary, nodeMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (controller is IRebindableController && action == ControllerCloneAction.CLONE) IRebindableController(controllerMap[controller]).rebindDependencies(nodeMap, controllerMap); } } } }
fix AbstractSceneNode.updateRoot() to be called "after" using setTimeout in order to make sure the addedToScene/removedFromScene signals are not called inside the added/removed signals
fix AbstractSceneNode.updateRoot() to be called "after" using setTimeout in order to make sure the addedToScene/removedFromScene signals are not called inside the added/removed signals
ActionScript
mit
aerys/minko-as3
0a545ce12abc40f565311643dcef955ef88200d5
src/battlecode/common/RobotType.as
src/battlecode/common/RobotType.as
package battlecode.common { public class RobotType { public static const HQ:String = "HQ"; public static const TOWER:String = "TOWER"; public static const SUPPLYDEPOT:String = "SUPPLYDEPOT"; public static const TECHNOLOGYINSTITUTE:String = "TECHNOLOGYINSTITUTE"; public static const BARRACKS:String = "BARRACKS"; public static const HELIPAD:String = "HELIPAD"; public static const TRAININGFIELD:String = "TRAININGFIELD"; public static const TANKFACTORY:String = "TANKFACTORY"; public static const HANDWASHSTATION:String = "HANDWASHSTATION"; public static const AEROSPACELAB:String = "AEROSPACELAB"; public static const BEAVER:String = "BEAVER"; public static const COMPUTER:String = "COMPUTER"; public static const SOLDIER:String = "SOLDIER"; public static const BASHER:String = "BASHER"; public static const MINER:String = "MINER"; public static const DRONE:String = "DRONE"; public static const TANK:String = "TANK"; public static const COMMANDER:String = "COMMANDER"; public static const LAUNCHER:String = "LAUNCHER"; public static const MISSLE:String = "MISSLE"; public function RobotType() { } public static function values():Array { return [ HQ, TOWER, SUPPLYDEPOT, TECHNOLOGYINSTITUTE, BARRACKS, HELIPAD, TRAININGFIELD, TANKFACTORY, HANDWASHSTATION, AEROSPACELAB, BEAVER, COMPUTER, SOLDIER, BASHER, MINER, DRONE, TANK, COMMANDER, LAUNCHER, MISSLE ]; } public static function buildings():Array { return [ HQ, TOWER, SUPPLYDEPOT, TECHNOLOGYINSTITUTE, BARRACKS, HELIPAD, TRAININGFIELD, TANKFACTORY, HANDWASHSTATION, AEROSPACELAB ]; } public static function ground():Array { return [ BEAVER, COMPUTER, SOLDIER, BASHER, MINER, TANK, COMMANDER, LAUNCHER, MISSLE ]; } public static function air():Array { return []; // TODO air types } // TODO fix values public static function maxEnergon(type:String):Number { switch (type) { case HQ: return int.MAX_VALUE; case SOLDIER: return 100.0; } throw new ArgumentError("Unknown type: " + type); } public static function movementDelay(type:String):uint { return 1; } public static function movementDelayDiagonal(type:String):uint { return 1; } public static function attackDelay(type:String):uint { return 0; } } }
package battlecode.common { public class RobotType { public static const HQ:String = "HQ"; public static const TOWER:String = "TOWER"; public static const SUPPLYDEPOT:String = "SUPPLYDEPOT"; public static const TECHNOLOGYINSTITUTE:String = "TECHNOLOGYINSTITUTE"; public static const BARRACKS:String = "BARRACKS"; public static const HELIPAD:String = "HELIPAD"; public static const TRAININGFIELD:String = "TRAININGFIELD"; public static const TANKFACTORY:String = "TANKFACTORY"; public static const HANDWASHSTATION:String = "HANDWASHSTATION"; public static const AEROSPACELAB:String = "AEROSPACELAB"; public static const BEAVER:String = "BEAVER"; public static const COMPUTER:String = "COMPUTER"; public static const SOLDIER:String = "SOLDIER"; public static const BASHER:String = "BASHER"; public static const MINER:String = "MINER"; public static const DRONE:String = "DRONE"; public static const TANK:String = "TANK"; public static const COMMANDER:String = "COMMANDER"; public static const LAUNCHER:String = "LAUNCHER"; public static const MISSILE:String = "MISSILE"; public function RobotType() { } public static function values():Array { return [ HQ, TOWER, SUPPLYDEPOT, TECHNOLOGYINSTITUTE, BARRACKS, HELIPAD, TRAININGFIELD, TANKFACTORY, HANDWASHSTATION, AEROSPACELAB, BEAVER, COMPUTER, SOLDIER, BASHER, MINER, DRONE, TANK, COMMANDER, LAUNCHER, MISSILE ]; } public static function buildings():Array { return [ HQ, TOWER, SUPPLYDEPOT, TECHNOLOGYINSTITUTE, BARRACKS, HELIPAD, TRAININGFIELD, TANKFACTORY, HANDWASHSTATION, AEROSPACELAB ]; } public static function ground():Array { return [ BEAVER, COMPUTER, SOLDIER, BASHER, MINER, TANK, COMMANDER, LAUNCHER, MISSILE ]; } public static function air():Array { return []; // TODO air types } // TODO fix values public static function maxEnergon(type:String):Number { switch (type) { case HQ: return 2000; case TOWER: return 1000; case SUPPLYDEPOT: case TECHNOLOGYINSTITUTE: case BARRACKS: case HELIPAD: case TRAININGFIELD: case TANKFACTORY: case HANDWASHSTATION: case AEROSPACELAB: return 100; case BEAVER: return 30; case MINER: return 50; case COMPUTER: return 1; case SOLDIER: return 40; case BASHER: return 50; case DRONE: return 70; case TANK: return 160; case COMMANDER: return 120; case LAUNCHER: return 400; case MISSILE: return 3; } throw new ArgumentError("Unknown type: " + type); } public static function movementDelay(type:String):uint { return 1; } public static function movementDelayDiagonal(type:String):uint { return 1; } public static function attackDelay(type:String):uint { return 0; } } }
add HP for robot types
add HP for robot types
ActionScript
mit
trun/battlecode-webclient
19831db930af438f28bcf190fdeb6f69a85ad998
src/as/com/threerings/presents/client/ClientDObjectMgr.as
src/as/com/threerings/presents/client/ClientDObjectMgr.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.presents.client { import flash.events.Event; import flash.events.TimerEvent; import flash.utils.Timer; import flash.utils.getTimer; // function import import com.threerings.util.ClassUtil; import com.threerings.util.HashMap; import com.threerings.util.Log; import com.threerings.presents.dobj.CompoundEvent; import com.threerings.presents.dobj.DEvent; import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.DObjectManager; import com.threerings.presents.dobj.ObjectAccessError; import com.threerings.presents.dobj.ObjectDestroyedEvent; import com.threerings.presents.dobj.Subscriber; import com.threerings.presents.net.BootstrapNotification; import com.threerings.presents.net.EventNotification; import com.threerings.presents.net.DownstreamMessage; import com.threerings.presents.net.FailureResponse; import com.threerings.presents.net.ForwardEventRequest; import com.threerings.presents.net.ObjectResponse; import com.threerings.presents.net.PongResponse; import com.threerings.presents.net.SubscribeRequest; import com.threerings.presents.net.UnsubscribeRequest; import com.threerings.presents.net.UnsubscribeResponse; /** * The client distributed object manager manages a set of proxy objects * which mirror the distributed objects maintained on the server. * Requests for modifications, etc. are forwarded to the server and events * are dispatched from the server to this client for objects to which this * client is subscribed. */ public class ClientDObjectMgr implements DObjectManager { private static const log :Log = Log.getLog(ClientDObjectMgr); /** * Constructs a client distributed object manager. * * @param comm a communicator instance by which it can communicate * with the server. * @param client a reference to the client that is managing this whole * communications and event dispatch business. */ public function ClientDObjectMgr (comm :Communicator, client :Client) { _comm = comm; _client = client; // register a flush interval _flushInterval = new Timer(FLUSH_INTERVAL); _flushInterval.addEventListener(TimerEvent.TIMER, flushObjects); _flushInterval.start(); client.getStage().addEventListener( Event.ENTER_FRAME, processNextAction); } // documentation inherited from interface DObjectManager public function isManager (object :DObject) :Boolean { // we are never authoritative in the present implementation return false; } // inherit documentation from the interface DObjectManager public function subscribeToObject (oid :int, target :Subscriber) :void { if (oid <= 0) { target.requestFailed(oid, new ObjectAccessError("Invalid oid " + oid + ".")); } else { queueAction(oid, target, true); } } // inherit documentation from the interface DObjectManager public function unsubscribeFromObject (oid :int, target :Subscriber) :void { queueAction(oid, target, false); } protected function queueAction ( oid :int, target :Subscriber, subscribe :Boolean) :void { // queue up an action _actions.push(new ObjectAction(oid, target, subscribe)); } // inherit documentation from the interface public function postEvent (event :DEvent) :void { // send a forward event request to the server _comm.postMessage(new ForwardEventRequest(event)); } // inherit documentation from the interface public function removedLastSubscriber ( obj :DObject, deathWish :Boolean) :void { // if this object has a registered flush delay, don't can it just // yet, just slip it onto the flush queue for each (var dclass :Class in _delays.keys()) { if (obj is dclass) { var expire :Number = getTimer() + Number(_delays.get(dclass)); _flushes.put(obj.getOid(), new FlushRecord(obj, expire)); // log.info("Flushing " + obj.getOid() + " at " + // new java.util.Date(expire)); return; } } // if we didn't find a delay registration, flush immediately flushObject(obj); } /** * Registers an object flush delay. * * @see Client#registerFlushDelay */ public function registerFlushDelay (objclass :Class, delay :Number) :void { _delays.put(objclass, delay); } /** * Called by the communicator when a downstream message arrives from * the network layer. We queue it up for processing and request some * processing time on the main thread. */ public function processMessage (msg :DownstreamMessage) :void { // append it to our queue _actions.push(msg); } /** * Invoked on the main client thread to process any newly arrived * messages that we have waiting in our queue. */ public function processNextAction (event :Event) :void { while (_actions.length > 0) { doNextAction(); } } protected function doNextAction () :void { // process the next event on our queue if (_actions.length == 0) { return; } var obj :Object = _actions.shift(); // do the proper thing depending on the object if (obj is EventNotification) { var evt :DEvent = (obj as EventNotification).getEvent(); // log.info("Dispatch event: " + evt); dispatchEvent(evt); } else if (obj is BootstrapNotification) { _client.gotBootstrap((obj as BootstrapNotification).getData(), this); } else if (obj is ObjectResponse) { registerObjectAndNotify((obj as ObjectResponse).getObject()); } else if (obj is UnsubscribeResponse) { var oid :int = (obj as UnsubscribeResponse).getOid(); if (_dead.remove(oid) == null) { log.warning("Received unsub ACK from unknown object [oid=" + oid + "]."); } } else if (obj is FailureResponse) { notifyFailure((obj as FailureResponse).getOid(), (obj as FailureResponse).getMessage()); } else if (obj is PongResponse) { _client.gotPong(obj as PongResponse); } else if (obj is ObjectAction) { var act :ObjectAction = (obj as ObjectAction); if (act.subscribe) { doSubscribe(act.oid, act.target); } else { doUnsubscribe(act.oid, act.target); } } } /** * Called when a new event arrives from the server that should be * dispatched to subscribers here on the client. */ protected function dispatchEvent (event :DEvent) :void { // if this is a compound event, we need to process its contained // events in order if (event is CompoundEvent) { var events :Array = (event as CompoundEvent).getEvents(); var ecount :int = events.length; for (var ii :int = 0; ii < ecount; ii++) { dispatchEvent(events[ii] as DEvent); } return; } // look up the object on which we're dispatching this event var toid :int = event.getTargetOid(); var target :DObject = (_ocache.get(toid) as DObject); if (target == null) { if (_dead.get(toid) == null) { log.warning("Unable to dispatch event on non-proxied " + "object [event=" + event + "]."); } return; } try { // apply the event to the object var notify :Boolean = event.applyToObject(target); // if this is an object destroyed event, we need to remove the // object from our object table if (event is ObjectDestroyedEvent) { // log.info("Pitching destroyed object " + // "[oid=" + toid + ", class=" + // StringUtil.shortClassName(target) + "]."); _ocache.remove(toid); } // have the object pass this event on to its listeners if (notify) { target.notifyListeners(event); } } catch (e :Error) { log.warning("Failure processing event [event=" + event + ", target=" + target + "]."); log.logStackTrace(e); } } /** * Registers this object in our proxy cache and notifies the * subscribers that were waiting for subscription to this object. */ protected function registerObjectAndNotify (obj :DObject) :void { // let the object know that we'll be managing it obj.setManager(this); var oid :int = obj.getOid(); // stick the object into the proxy object table _ocache.put(oid, obj); // let the penders know that the object is available var req :PendingRequest = (_penders.remove(oid) as PendingRequest); if (req == null) { log.warning("Got object, but no one cares?! " + "[oid=" + oid + ", obj=" + obj + "]."); return; } // log.debug("Got object: pendReq=" + req); for (var ii :int = 0; ii < req.targets.length; ii++) { var target :Subscriber = (req.targets[ii] as Subscriber); // log.debug("Notifying subscriber: " + target); // add them as a subscriber obj.addSubscriber(target); // and let them know that the object is in target.objectAvailable(obj); } } /** * Notifies the subscribers that had requested this object (for subscription) that it is not * available. */ protected function notifyFailure (oid :int, message :String) :void { // let the penders know that the object is not available var req :PendingRequest = (_penders.remove(oid) as PendingRequest); if (req == null) { log.warning("Failed to get object, but no one cares?! [oid=" + oid + "]."); return; } for (var ii :int = 0; ii < req.targets.length; ii++) { var target :Subscriber = req.targets[ii]; // and let them know that the object is in target.requestFailed(oid, new ObjectAccessError(message)); } } /** * This is guaranteed to be invoked via the invoker and can safely do * main thread type things like call back to the subscriber. */ protected function doSubscribe (oid :int, target :Subscriber) :void { // log.info("doSubscribe: " + oid + ": " + target); // first see if we've already got the object in our table var obj :DObject = (_ocache.get(oid) as DObject); if (obj != null) { // clear the object out of the flush table if it's in there _flushes.remove(oid); // add the subscriber and call them back straight away obj.addSubscriber(target); target.objectAvailable(obj); return; } // see if we've already got an outstanding request for this object var req :PendingRequest = (_penders.get(oid) as PendingRequest); if (req != null) { // add this subscriber to the list of subscribers to be // notified when the request is satisfied req.addTarget(target); return; } // otherwise we need to create a new request req = new PendingRequest(oid); req.addTarget(target); _penders.put(oid, req); // log.info("Registering pending request [oid=" + oid + "]."); // and issue a request to get things rolling _comm.postMessage(new SubscribeRequest(oid)); } /** * This is guaranteed to be invoked via the invoker and can safely do * main thread type things like call back to the subscriber. */ protected function doUnsubscribe (oid :int, target :Subscriber) :void { var dobj :DObject = (_ocache.get(oid) as DObject); if (dobj != null) { dobj.removeSubscriber(target); } else { log.info("Requested to remove subscriber from " + "non-proxied object [oid=" + oid + ", sub=" + target + "]."); } } /** * Flushes a distributed object subscription, issuing an unsubscribe * request to the server. */ protected function flushObject (obj :DObject) :void { // move this object into the dead pool so that we don't claim to // have it around anymore; once our unsubscribe message is // processed, it'll be 86ed var ooid :int = obj.getOid(); _ocache.remove(ooid); _dead.put(ooid, obj); // ship off an unsubscribe message to the server; we'll remove the // object from our table when we get the unsub ack _comm.postMessage(new UnsubscribeRequest(ooid)); } /** * Called periodically to flush any objects that have been lingering * due to a previously enacted flush delay. */ protected function flushObjects (event :TimerEvent) :void { var now :Number = getTimer(); for each (var oid :int in _flushes.keys()) { var rec :FlushRecord = (_flushes.get(oid) as FlushRecord); if (rec.expire <= now) { _flushes.remove(oid); flushObject(rec.obj); } } } /** A reference to the communicator that sends and receives messages * for this client. */ protected var _comm :Communicator; /** A reference to our client instance. */ protected var _client :Client; /** Our primary dispatch queue. */ protected var _actions :Array = new Array(); /** All of the distributed objects that are active on this client. */ protected var _ocache :HashMap = new HashMap(); /** Objects that have been marked for death. */ protected var _dead :HashMap = new HashMap(); /** Pending object subscriptions. */ protected var _penders :HashMap = new HashMap(); /** A mapping from distributed object class to flush delay. */ protected var _delays :HashMap = new HashMap(); /** A set of objects waiting to be flushed. */ protected var _flushes :HashMap = new HashMap(); /** Flushes objects every now and again. */ protected var _flushInterval :Timer; /** Flush expired objects every 30 seconds. */ protected static const FLUSH_INTERVAL :Number = 30 * 1000; } } import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.Subscriber; /** * The object action is used to queue up a subscribe or unsubscribe * request. */ class ObjectAction { public var oid :int; public var target :Subscriber; public var subscribe :Boolean; public function ObjectAction ( oid :int, target :Subscriber, subscribe :Boolean) { this.oid = oid; this.target = target; this.subscribe = subscribe; } public function toString () :String { return "oid=" + oid + ", target=" + target + ", subscribe=" + subscribe; } } class PendingRequest { public var oid :int; public var targets :Array = new Array(); public function PendingRequest (oid :int) { this.oid = oid; } public function addTarget (target :Subscriber) :void { targets.push(target); } } /** Used to manage pending object flushes. */ class FlushRecord { /** The object to be flushed. */ public var obj :DObject; /** The time at which we flush it. */ public var expire :Number; public function FlushRecord (obj :DObject, expire :Number) { this.obj = obj; this.expire = expire; } }
// // $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.presents.client { import flash.events.Event; import flash.events.TimerEvent; import flash.utils.Timer; import flash.utils.getTimer; // function import import com.threerings.util.ClassUtil; import com.threerings.util.HashMap; import com.threerings.util.Log; import com.threerings.presents.dobj.CompoundEvent; import com.threerings.presents.dobj.DEvent; import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.DObjectManager; import com.threerings.presents.dobj.ObjectAccessError; import com.threerings.presents.dobj.ObjectDestroyedEvent; import com.threerings.presents.dobj.Subscriber; import com.threerings.presents.net.BootstrapNotification; import com.threerings.presents.net.EventNotification; import com.threerings.presents.net.DownstreamMessage; import com.threerings.presents.net.FailureResponse; import com.threerings.presents.net.ForwardEventRequest; import com.threerings.presents.net.ObjectResponse; import com.threerings.presents.net.PongResponse; import com.threerings.presents.net.SubscribeRequest; import com.threerings.presents.net.UnsubscribeRequest; import com.threerings.presents.net.UnsubscribeResponse; /** * The client distributed object manager manages a set of proxy objects * which mirror the distributed objects maintained on the server. * Requests for modifications, etc. are forwarded to the server and events * are dispatched from the server to this client for objects to which this * client is subscribed. */ public class ClientDObjectMgr implements DObjectManager { private static const log :Log = Log.getLog(ClientDObjectMgr); /** * Constructs a client distributed object manager. * * @param comm a communicator instance by which it can communicate * with the server. * @param client a reference to the client that is managing this whole * communications and event dispatch business. */ public function ClientDObjectMgr (comm :Communicator, client :Client) { _comm = comm; _client = client; // register a flush interval _flushInterval = new Timer(FLUSH_INTERVAL); _flushInterval.addEventListener(TimerEvent.TIMER, flushObjects); _flushInterval.start(); } // documentation inherited from interface DObjectManager public function isManager (object :DObject) :Boolean { // we are never authoritative in the present implementation return false; } // inherit documentation from the interface DObjectManager public function subscribeToObject (oid :int, target :Subscriber) :void { if (oid <= 0) { target.requestFailed(oid, new ObjectAccessError("Invalid oid " + oid + ".")); } else { doSubscribe(oid, target); } } // inherit documentation from the interface DObjectManager public function unsubscribeFromObject (oid :int, target :Subscriber) :void { doUnsubscribe(oid, target); } // inherit documentation from the interface public function postEvent (event :DEvent) :void { // send a forward event request to the server _comm.postMessage(new ForwardEventRequest(event)); } // inherit documentation from the interface public function removedLastSubscriber ( obj :DObject, deathWish :Boolean) :void { // if this object has a registered flush delay, don't can it just // yet, just slip it onto the flush queue for each (var dclass :Class in _delays.keys()) { if (obj is dclass) { var expire :Number = getTimer() + Number(_delays.get(dclass)); _flushes.put(obj.getOid(), new FlushRecord(obj, expire)); // log.info("Flushing " + obj.getOid() + " at " + // new java.util.Date(expire)); return; } } // if we didn't find a delay registration, flush immediately flushObject(obj); } /** * Registers an object flush delay. * * @see Client#registerFlushDelay */ public function registerFlushDelay (objclass :Class, delay :Number) :void { _delays.put(objclass, delay); } /** * Called by the communicator when a downstream message arrives from * the network layer. We queue it up for processing and request some * processing time on the main thread. */ public function processMessage (msg :DownstreamMessage) :void { // do the proper thing depending on the object if (msg is EventNotification) { var evt :DEvent = (msg as EventNotification).getEvent(); // log.info("Dispatch event: " + evt); dispatchEvent(evt); } else if (msg is BootstrapNotification) { _client.gotBootstrap((msg as BootstrapNotification).getData(), this); } else if (msg is ObjectResponse) { registerObjectAndNotify((msg as ObjectResponse).getObject()); } else if (msg is UnsubscribeResponse) { var oid :int = (msg as UnsubscribeResponse).getOid(); if (_dead.remove(oid) == null) { log.warning("Received unsub ACK from unknown object [oid=" + oid + "]."); } } else if (msg is FailureResponse) { notifyFailure((msg as FailureResponse).getOid(), (msg as FailureResponse).getMessage()); } else if (msg is PongResponse) { _client.gotPong(msg as PongResponse); } } /** * Called when a new event arrives from the server that should be * dispatched to subscribers here on the client. */ protected function dispatchEvent (event :DEvent) :void { // if this is a compound event, we need to process its contained // events in order if (event is CompoundEvent) { var events :Array = (event as CompoundEvent).getEvents(); var ecount :int = events.length; for (var ii :int = 0; ii < ecount; ii++) { dispatchEvent(events[ii] as DEvent); } return; } // look up the object on which we're dispatching this event var toid :int = event.getTargetOid(); var target :DObject = (_ocache.get(toid) as DObject); if (target == null) { if (_dead.get(toid) == null) { log.warning("Unable to dispatch event on non-proxied " + "object [event=" + event + "]."); } return; } try { // apply the event to the object var notify :Boolean = event.applyToObject(target); // if this is an object destroyed event, we need to remove the // object from our object table if (event is ObjectDestroyedEvent) { // log.info("Pitching destroyed object " + // "[oid=" + toid + ", class=" + // StringUtil.shortClassName(target) + "]."); _ocache.remove(toid); } // have the object pass this event on to its listeners if (notify) { target.notifyListeners(event); } } catch (e :Error) { log.warning("Failure processing event [event=" + event + ", target=" + target + "]."); log.logStackTrace(e); } } /** * Registers this object in our proxy cache and notifies the * subscribers that were waiting for subscription to this object. */ protected function registerObjectAndNotify (obj :DObject) :void { // let the object know that we'll be managing it obj.setManager(this); var oid :int = obj.getOid(); // stick the object into the proxy object table _ocache.put(oid, obj); // let the penders know that the object is available var req :PendingRequest = (_penders.remove(oid) as PendingRequest); if (req == null) { log.warning("Got object, but no one cares?! " + "[oid=" + oid + ", obj=" + obj + "]."); return; } // log.debug("Got object: pendReq=" + req); for (var ii :int = 0; ii < req.targets.length; ii++) { var target :Subscriber = (req.targets[ii] as Subscriber); // log.debug("Notifying subscriber: " + target); // add them as a subscriber obj.addSubscriber(target); // and let them know that the object is in target.objectAvailable(obj); } } /** * Notifies the subscribers that had requested this object (for subscription) that it is not * available. */ protected function notifyFailure (oid :int, message :String) :void { // let the penders know that the object is not available var req :PendingRequest = (_penders.remove(oid) as PendingRequest); if (req == null) { log.warning("Failed to get object, but no one cares?! [oid=" + oid + "]."); return; } for (var ii :int = 0; ii < req.targets.length; ii++) { var target :Subscriber = req.targets[ii]; // and let them know that the object is in target.requestFailed(oid, new ObjectAccessError(message)); } } /** * This is guaranteed to be invoked via the invoker and can safely do * main thread type things like call back to the subscriber. */ protected function doSubscribe (oid :int, target :Subscriber) :void { // log.info("doSubscribe: " + oid + ": " + target); // first see if we've already got the object in our table var obj :DObject = (_ocache.get(oid) as DObject); if (obj != null) { // clear the object out of the flush table if it's in there _flushes.remove(oid); // add the subscriber and call them back straight away obj.addSubscriber(target); target.objectAvailable(obj); return; } // see if we've already got an outstanding request for this object var req :PendingRequest = (_penders.get(oid) as PendingRequest); if (req != null) { // add this subscriber to the list of subscribers to be // notified when the request is satisfied req.addTarget(target); return; } // otherwise we need to create a new request req = new PendingRequest(oid); req.addTarget(target); _penders.put(oid, req); // log.info("Registering pending request [oid=" + oid + "]."); // and issue a request to get things rolling _comm.postMessage(new SubscribeRequest(oid)); } /** * This is guaranteed to be invoked via the invoker and can safely do * main thread type things like call back to the subscriber. */ protected function doUnsubscribe (oid :int, target :Subscriber) :void { var dobj :DObject = (_ocache.get(oid) as DObject); if (dobj != null) { dobj.removeSubscriber(target); } else { log.info("Requested to remove subscriber from " + "non-proxied object [oid=" + oid + ", sub=" + target + "]."); } } /** * Flushes a distributed object subscription, issuing an unsubscribe * request to the server. */ protected function flushObject (obj :DObject) :void { // move this object into the dead pool so that we don't claim to // have it around anymore; once our unsubscribe message is // processed, it'll be 86ed var ooid :int = obj.getOid(); _ocache.remove(ooid); _dead.put(ooid, obj); // ship off an unsubscribe message to the server; we'll remove the // object from our table when we get the unsub ack _comm.postMessage(new UnsubscribeRequest(ooid)); } /** * Called periodically to flush any objects that have been lingering * due to a previously enacted flush delay. */ protected function flushObjects (event :TimerEvent) :void { var now :Number = getTimer(); for each (var oid :int in _flushes.keys()) { var rec :FlushRecord = (_flushes.get(oid) as FlushRecord); if (rec.expire <= now) { _flushes.remove(oid); flushObject(rec.obj); } } } /** A reference to the communicator that sends and receives messages * for this client. */ protected var _comm :Communicator; /** A reference to our client instance. */ protected var _client :Client; /** Our primary dispatch queue. */ protected var _actions :Array = new Array(); /** All of the distributed objects that are active on this client. */ protected var _ocache :HashMap = new HashMap(); /** Objects that have been marked for death. */ protected var _dead :HashMap = new HashMap(); /** Pending object subscriptions. */ protected var _penders :HashMap = new HashMap(); /** A mapping from distributed object class to flush delay. */ protected var _delays :HashMap = new HashMap(); /** A set of objects waiting to be flushed. */ protected var _flushes :HashMap = new HashMap(); /** Flushes objects every now and again. */ protected var _flushInterval :Timer; /** Flush expired objects every 30 seconds. */ protected static const FLUSH_INTERVAL :Number = 30 * 1000; } } import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.Subscriber; class PendingRequest { public var oid :int; public var targets :Array = new Array(); public function PendingRequest (oid :int) { this.oid = oid; } public function addTarget (target :Subscriber) :void { targets.push(target); } } /** Used to manage pending object flushes. */ class FlushRecord { /** The object to be flushed. */ public var obj :DObject; /** The time at which we flush it. */ public var expire :Number; public function FlushRecord (obj :DObject, expire :Number) { this.obj = obj; this.expire = expire; } }
Stop waiting for ENTER_FRAME to process incoming messages. This was residual from the initial conversion from Java, but I don't think it's very necessary on the flash side, and Zell is working to decouple the presents layer from flash-player specific classes and events like ENTER_FRAME. So now we just process everything immediately. I did some tests, it seems that the flash player dispatches ENTER_FRAME, then it dispatches any network events, then the frame is rendered. So our old way of doing things was pointlessly
Stop waiting for ENTER_FRAME to process incoming messages. This was residual from the initial conversion from Java, but I don't think it's very necessary on the flash side, and Zell is working to decouple the presents layer from flash-player specific classes and events like ENTER_FRAME. So now we just process everything immediately. I did some tests, it seems that the flash player dispatches ENTER_FRAME, then it dispatches any network events, then the frame is rendered. So our old way of doing things was pointlessly git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5015 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
6b3aba02250223bde8b07375cfa024e1bda21dde
src/as/com/threerings/presents/dobj/ObjectRemovedEvent.as
src/as/com/threerings/presents/dobj/ObjectRemovedEvent.as
// // $Id: ObjectRemovedEvent.java 3099 2004-08-27 02:21:06Z mdb $ // // Narya library - tools for developing networked games // Copyright (C) 2002-2004 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.presents.dobj { import com.threerings.util.StringBuilder; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; /** * An object removed event is dispatched when an object is removed from an * <code>OidList</code> attribute of a distributed object. It can also be * constructed to request the removal of an oid from an * <code>OidList</code> attribute of an object and posted to the dobjmgr. * * @see DObjectManager#postEvent */ public class ObjectRemovedEvent extends NamedEvent { /** * Constructs a new object removed event on the specified target * object with the supplied oid list attribute name and object id to * remove. * * @param targetOid the object id of the object from whose oid list we * will remove an oid. * @param name the name of the attribute (data member) from which to * remove the specified oid. * @param oid the oid to remove from the oid list attribute. */ public function ObjectRemovedEvent (targetOid :int, name :String, oid :int) { super(targetOid, name); _oid = oid; } /** * Returns the oid that has been removed. */ public function getOid () :int { return _oid; } /** * Applies this event to the object. */ public override function applyToObject (target :DObject) :Boolean //throws ObjectAccessException { var list :OidList = (target[_name] as OidList); list.remove(_oid); return true; } // documentation inherited protected override function notifyListener (listener :Object) :void { if (listener is OidListListener) { listener.objectRemoved(this); } } public override function writeObject (out :ObjectOutputStream) :void { super.writeObject(out); out.writeInt(_oid); } public override function readObject (ins :ObjectInputStream) :void { super.readObject(ins); _oid = ins.readInt(); } // documentation inherited protected override function toStringBuf (buf :StringBuilder) :void { buf.append("OBJREM:"); super.toStringBuf(buf); buf.append(", oid=", _oid); } protected var _oid :int; } }
// // $Id: ObjectRemovedEvent.java 3099 2004-08-27 02:21:06Z mdb $ // // Narya library - tools for developing networked games // Copyright (C) 2002-2004 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.presents.dobj { import com.threerings.util.StringBuilder; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; /** * An object removed event is dispatched when an object is removed from an * <code>OidList</code> attribute of a distributed object. It can also be * constructed to request the removal of an oid from an * <code>OidList</code> attribute of an object and posted to the dobjmgr. * * @see DObjectManager#postEvent */ public class ObjectRemovedEvent extends NamedEvent { /** * Constructs a new object removed event on the specified target * object with the supplied oid list attribute name and object id to * remove. * * @param targetOid the object id of the object from whose oid list we * will remove an oid. * @param name the name of the attribute (data member) from which to * remove the specified oid. * @param oid the oid to remove from the oid list attribute. */ public function ObjectRemovedEvent ( targetOid :int = 0, name :String = null, oid :int = 0) { super(targetOid, name); _oid = oid; } /** * Returns the oid that has been removed. */ public function getOid () :int { return _oid; } /** * Applies this event to the object. */ public override function applyToObject (target :DObject) :Boolean //throws ObjectAccessException { var list :OidList = (target[_name] as OidList); list.remove(_oid); return true; } // documentation inherited protected override function notifyListener (listener :Object) :void { if (listener is OidListListener) { listener.objectRemoved(this); } } public override function writeObject (out :ObjectOutputStream) :void { super.writeObject(out); out.writeInt(_oid); } public override function readObject (ins :ObjectInputStream) :void { super.readObject(ins); _oid = ins.readInt(); } // documentation inherited protected override function toStringBuf (buf :StringBuilder) :void { buf.append("OBJREM:"); super.toStringBuf(buf); buf.append(", oid=", _oid); } protected var _oid :int; } }
Allow zero-arg construction (for unserialization).
Allow zero-arg construction (for unserialization). git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4154 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
1148dce19bb04407aac8dc1dcf6e97af4e64811a
actionscript-cafe/src/main/flex/org/servebox/cafe/core/util/DateUtils.as
actionscript-cafe/src/main/flex/org/servebox/cafe/core/util/DateUtils.as
/* * actionscript-cafe ClassUtils 18 avr. 2011 adesmarais * * Created by Servebox * Copyright 2010 Servebox (c) All rights reserved. You may not use, distribute * or modify this code under its source or binary form * without the express authorization of ServeBox. Contact : [email protected] */ package org.servebox.cafe.core.util { /** * DateUtils is a helper class with a lot of static methods to handle dates. */ public class DateUtils { /** * Returns the last day for a given month and year. * @param fullYear The year. * @param month The month. (0-11) * @return The last day in month. */ public static function getLastDayInMonth( fullYear : int , month : int) : int { var date : Date = new Date( fullYear , month , 28 ); var toReturn : int; do { toReturn = date.getDate(); date.setDate( date.getDate() + 1 ); }while( date.getMonth() == month ); return toReturn; } /** * Adds given values to a date, using a mask. The mask parameter can take the following values :<br> * - d : Days.<br> * - m : Months.<br> * - y : Years.<br> * @param date The date to add value to. * @param mask The mask to apply on addition. * @param addValue The value to add. Can be negative. * @return The new date. */ public static function dateAdd( date : Date , mask : String , addValue : int ) : Date { var newDate : Date = dateCopy( date ); switch( mask ) { case "d" : newDate.setDate( newDate.getDate() + addValue ); break; case "m" : newDate.setMonth( newDate.getMonth() + addValue ); break; case "y" : newDate.setFullYear( newDate.getFullYear() + addValue ); break; } return newDate; } /** * Creates a fresh new clone of the passed date. * @return A new Date, clone of an existing one. * @param date The date to copy. */ public static function dateCopy( date : Date ) : Date { var newDate : Date = new Date( date.getFullYear() , date.getMonth() , date.getDate() , date.getHours() , date.getMinutes() , date.getSeconds() , date.getMilliseconds() ); return newDate; } /** * Checks if a date is an open date (excluding saturday/sunday). * @param date The date to check. * @return A boolean indicating if the given date is an open one. */ public static function isOpenDate( date : Date ) : Boolean { if( date.getDay() == 0 || date.getDay() == 6 ) return false; return true; } /** * Adds days to a given date, including only open dates. * @param date The date. * @param daysToAdd The number of days to add. Can be negative. * @return The new date. */ public static function dateAddOpenDatesOnly( date : Date , daysToAdd : int ) : Date { var newDate : Date = dateCopy( date ); var direction : int = ( daysToAdd < 0 ? - 1 : 1 ); while( daysToAdd != 0 ) { newDate = dateAdd( newDate , "d" , direction ); if( isOpenDate( newDate ) ) { daysToAdd -= direction; } } return newDate; } /** * Returns the current date, with hh:mm:ss-ms set to 00:00:00-000. * @return The current date. */ public static function getCurrentDate() : Date { return getMidnightDateCopy( new Date() ); } /** * Returns the copy of a date, with the time set to 00:00:00-000. * @param date The date to copy. * @return The new date. */ public static function getMidnightDateCopy( date : Date ) : Date { return new Date( date.getFullYear() , date.getMonth() , date.getDate() , 0 , 0 , 0 , 0 ); } /** * Returns the difference between to dates, with the parameter mask as the unit. The mask parameter can take the following values :<br> * - d : Days.<br> * - m : Months.<br> * - y : Years.<br> * <b>The method do not consider hours, minutes, seconds and milliseconds.</b> * @return The difference ( date1 - date2). * @param date1 The first operand. * @param date2 The second operand. * @param mask The unit to use. */ public static function dateDiff( date1 : Date , date2 : Date , mask : String ) : Number { var first : Date = getMidnightDateCopy( date1 ); var second : Date = getMidnightDateCopy( date2 ); // difference expressed in ms var diffMs : Number = first.getTime() - second.getTime(); var conversionRate : int; switch( mask ) { case "d" : conversionRate = 86400000 ; break; case "m" : conversionRate = 86400000 * 30 ; break; case "y" : conversionRate = 86400000 * 365 ; break; } return Math.floor( diffMs / conversionRate ); } /** * Dates comparator function. * @return a negative value if obj1 &lt; obj2, zero is obj1 == obj2, a positive value is obj1 &gt; obj2. */ public static function dateComparator( obj1 : Date , obj2 : Date ) : Number { if ( obj1 == null ) { if ( obj2 == null ) return 0; else return - 1; }else { if ( obj2 == null ) return 1; else { var date1InMs : Number = obj1.getTime(); var date2InMs : Number = obj2.getTime(); if ( date1InMs > date2InMs ) return 1; else if ( date1InMs < date2InMs ) return - 1; else return 0; } } } /** * Used to return a date typed in without any separators */ public static function getSeparatorsOff ( value : String ) : String { value = StringUtils.stripChar( value, " "); value = StringUtils.stripChar( value, "/"); value = StringUtils.stripChar( value, "\""); value = StringUtils.stripChar( value, "-"); value = StringUtils.stripChar( value, "."); return value; } /** * Use this fucntion to validate a property using two dates */ public static function validateInterval( beginDate : Date, endDate : Date ) : Boolean { if ( beginDate == null || endDate == null) return false; else if( DateUtils.dateComparator(endDate, beginDate) >= 0 ) return true else return false; } /** * This function is used to validate an interval in a specified date range */ public static function validateIntervalInRange ( beginDate : Date, endDate : Date, range : Array ) : Boolean { if ( beginDate == null || endDate == null || range == null) return false; else if( validateInterval(beginDate, endDate) == true && DateUtils.dateComparator(range[0], beginDate) <=0 && DateUtils.dateComparator(range[1], endDate) >= 0) return true else return false; } /** * Sets the selectable date range for a date component */ public static function setRange ( beginDate : Date, endDate : Date ) : Object { var range : Object = new Object(); range.rangeStart = beginDate; range.rangeEnd = endDate; return range; } } }
/* * actionscript-cafe ClassUtils 18 avr. 2011 adesmarais * * Created by Servebox * Copyright 2010 Servebox (c) All rights reserved. You may not use, distribute * or modify this code under its source or binary form * without the express authorization of ServeBox. Contact : [email protected] */ package org.servebox.cafe.core.util { /** * DateUtils is a helper class with a lot of static methods to handle dates. */ public class DateUtils { /** * Returns the last day for a given month and year. * @param fullYear The year. * @param month The month. (0-11) * @return The last day in month. */ public static function getLastDayInMonth( fullYear : int , month : int) : int { var date : Date = new Date( fullYear , month , 28 ); var toReturn : int; do { toReturn = date.getDate(); date.setDate( date.getDate() + 1 ); }while( date.getMonth() == month ); return toReturn; } /** * Adds given values to a date, using a mask. The mask parameter can take the following values :<br> * - d : Days.<br> * - m : Months.<br> * - y : Years.<br> * @param date The date to add value to. * @param mask The mask to apply on addition. * @param addValue The value to add. Can be negative. * @return The new date. */ public static function dateAdd( date : Date , mask : String , addValue : int ) : Date { var newDate : Date = dateCopy( date ); switch( mask ) { case "d" : newDate.setDate( newDate.getDate() + addValue ); break; case "m" : newDate.setMonth( newDate.getMonth() + addValue ); break; case "y" : newDate.setFullYear( newDate.getFullYear() + addValue ); break; } return newDate; } /** * Creates a fresh new clone of the passed date. * @return A new Date, clone of an existing one. * @param date The date to copy. */ public static function dateCopy( date : Date ) : Date { var newDate : Date = new Date( date.getFullYear() , date.getMonth() , date.getDate() , date.getHours() , date.getMinutes() , date.getSeconds() , date.getMilliseconds() ); return newDate; } /** * Checks if a date is an open date (excluding saturday/sunday). * @param date The date to check. * @return A boolean indicating if the given date is an open one. */ public static function isOpenDate( date : Date ) : Boolean { if( date.getDay() == 0 || date.getDay() == 6 ) return false; return true; } /** * Adds days to a given date, including only open dates. * @param date The date. * @param daysToAdd The number of days to add. Can be negative. * @return The new date. */ public static function dateAddOpenDatesOnly( date : Date , daysToAdd : int ) : Date { var newDate : Date = dateCopy( date ); var direction : int = ( daysToAdd < 0 ? - 1 : 1 ); while( daysToAdd != 0 ) { newDate = dateAdd( newDate , "d" , direction ); if( isOpenDate( newDate ) ) { daysToAdd -= direction; } } return newDate; } /** * Returns the current date, with hh:mm:ss-ms set to 00:00:00-000. * @return The current date. */ public static function getCurrentDate() : Date { return getMidnightDateCopy( new Date() ); } /** * Returns the copy of a date, with the time set to 00:00:00-000. * @param date The date to copy. * @return The new date. */ public static function getMidnightDateCopy( date : Date ) : Date { return new Date( date.getFullYear() , date.getMonth() , date.getDate() , 0 , 0 , 0 , 0 ); } /** * Returns the difference between to dates, with the parameter mask as the unit. The mask parameter can take the following values :<br> * - d : Days.<br> * - m : Months.<br> * - y : Years.<br> * <b>The method do not consider hours, minutes, seconds and milliseconds.</b> * @return The difference ( date1 - date2). * @param date1 The first operand. * @param date2 The second operand. * @param mask The unit to use. */ public static function dateDiff( date1 : Date , date2 : Date , mask : String ) : Number { var first : Date = getMidnightDateCopy( date1 ); var second : Date = getMidnightDateCopy( date2 ); // difference expressed in ms var diffMs : Number = first.getTime() - second.getTime(); var conversionRate : int; switch( mask ) { case "d" : conversionRate = 86400000 ; break; case "m" : conversionRate = 86400000 * 30 ; break; case "y" : conversionRate = 86400000 * 365 ; break; } return Math.floor( diffMs / conversionRate ); } /** * Dates comparator function. * @return a negative value if obj1 &lt; obj2, zero is obj1 == obj2, a positive value is obj1 &gt; obj2. */ public static function dateComparator( obj1 : Date , obj2 : Date ) : Number { if ( obj1 == null ) { if ( obj2 == null ) return 0; else return - 1; }else { if ( obj2 == null ) return 1; else { var date1InMs : Number = obj1.getTime(); var date2InMs : Number = obj2.getTime(); if ( date1InMs > date2InMs ) return 1; else if ( date1InMs < date2InMs ) return - 1; else return 0; } } } /** * Used to return a date typed in without any separators */ public static function getSeparatorsOff ( value : String ) : String { value = StringUtils.stripChar( value, " "); value = StringUtils.stripChar( value, "/"); value = StringUtils.stripChar( value, "\""); value = StringUtils.stripChar( value, "-"); value = StringUtils.stripChar( value, "."); return value; } /** * Use this fucntion to validate a property using two dates */ public static function validateInterval( beginDate : Date, endDate : Date ) : Boolean { if ( beginDate == null || endDate == null) return false; else if( DateUtils.dateComparator(endDate, beginDate) >= 0 ) return true else return false; } /** * This function is used to validate an interval in a specified date range */ public static function validateIntervalInRange ( beginDate : Date, endDate : Date, range : Array ) : Boolean { if ( beginDate == null || endDate == null || range == null) return false; else if( validateInterval(beginDate, endDate) == true && DateUtils.dateComparator(range[0], beginDate) <=0 && DateUtils.dateComparator(range[1], endDate) >= 0) return true else return false; } /** * Sets the selectable date range for a date component */ public static function setRange ( beginDate : Date, endDate : Date ) : Object { var range : Object = new Object(); range.rangeStart = beginDate; range.rangeEnd = endDate; return range; } public static function getDayNumber( date : Date ) : int { if ( date.day == 0 ) { return 7; } else { return date.day; } } } }
Add method in date utils.
Add method in date utils.
ActionScript
mit
servebox/as-cafe
fb6af8672a49f4404a422b10a632a33a91a228d5
krew-framework/krewfw/builtin_actor/world/KrewWorldLayer.as
krew-framework/krewfw/builtin_actor/world/KrewWorldLayer.as
package krewfw.builtin_actor.world { import flash.geom.Rectangle; import starling.display.DisplayObject; import starling.display.Image; import starling.display.Sprite; import krewfw.core.KrewActor; //------------------------------------------------------------ public class KrewWorldLayer extends KrewActor { private var _halfScreenWidth:Number; private var _halfScreenHeight:Number; private var _screenOriginX:Number; private var _screenOriginY:Number; private var _label:String; private var _tree:QuadTreeSprite; private var _focusX:Number = 0; private var _focusY:Number = 0; private var _baseZoomScale:Number = 1.0; private var _zoomScale:Number = 1.0; private var _viewport:Rectangle; //----- debug stat public var debug_numObjectByDepth:Array; public var debug_countDrawActor:int; public var debug_countDrawActorPrev:int; public var debug_countDrawDObj:int; public var debug_countDrawDObjPrev:int; public var debug_countVisiblePrev:int; public var debug_countVisible:int; //------------------------------------------------------------ public function KrewWorldLayer(worldWidth:Number, worldHeight:Number, screenWidth:Number, screenHeight:Number, baseZoomScale:Number=1.0, maxQuadTreeDepth:int=6, subNodeMargin:Number=0.2, screenOriginX:Number=0, screenOriginY:Number=0, label:String="") { _halfScreenWidth = screenWidth / 2; _halfScreenHeight = screenHeight / 2; _screenOriginX = screenOriginX; _screenOriginY = screenOriginY; _baseZoomScale = baseZoomScale; _label = label; _tree = new QuadTreeSprite( worldWidth, worldHeight, 0, 0, 0, maxQuadTreeDepth, subNodeMargin, label ); super.addChild(_tree); _viewport = new Rectangle(); } //------------------------------------------------------------ // Actor's event handlers //------------------------------------------------------------ public override function init():void { listen(QuadTreeSprite.DEBUG_EVENT_ADD, _debug_onObjAdd); listen(QuadTreeSprite.DEBUG_EVENT_DRAW_ACTOR, _debug_onActorDraw); listen(QuadTreeSprite.DEBUG_EVENT_DRAW_DOBJ, _debug_onDObjDraw); listen(QuadTreeSprite.DEBUG_EVENT_ENABLE_NODE, _debug_onNodeEnabled); } protected override function onDispose():void { _tree.dispose(); _tree = null; _viewport = null; } public function updateWorld(passedTime:Number):void { _tree.updateActors(passedTime); } //------------------------------------------------------------ // accessors //------------------------------------------------------------ public function get treeRoot():QuadTreeSprite { return _tree; } public function get viewport():Rectangle { return _viewport; } //------------------------------------------------------------ // public //------------------------------------------------------------ /** width と height はアンカーが中心にあることを想定 */ public function putActor(actor:KrewActor, width:Number=NaN, height:Number=NaN):void { _tree.addActor(actor, width, height); if (!actor.hasInitialized) { actor.setUp(sharedObj, applyForNewActor, layer, layerName); } } /** width と height はアンカーが中心にあることを想定 */ public function putDisplayObj(child:DisplayObject, width:Number=NaN, height:Number=NaN, anchorX:Number=0.5, anchorY:Number=0.5):void { if (child is Image) { var image:Image = child as Image; image.pivotX = image.texture.width * anchorX; image.pivotY = image.texture.height * anchorY; } _tree.addDisplayObj(child, width, height); } public function setFocusPos(x:Number, y:Number):void { _focusX = x; _focusY = y; } public function setZoomScale(scale:Number):void { _zoomScale = scale; if (_zoomScale <= 0) { _zoomScale = 0.001; } } public function updateViewport():void { var zoomScale:Number = _zoomScale * _baseZoomScale; x = -(_focusX * zoomScale) + _screenOriginX + _halfScreenWidth; y = -(_focusY * zoomScale) + _screenOriginY + _halfScreenHeight; scaleX = zoomScale; scaleY = zoomScale; _viewport.setTo( _focusX - (_halfScreenWidth / zoomScale), _focusY - (_halfScreenHeight / zoomScale), _halfScreenWidth * 2 / zoomScale, _halfScreenHeight * 2 / zoomScale ); _tree.updateVisibility(_viewport); } public function updateScreenSize(screenWidth:Number, screenHeight:Number, screenOriginX:Number=0, screenOriginY:Number=0):void { _halfScreenWidth = screenWidth / 2; _halfScreenHeight = screenHeight / 2; _screenOriginX = screenOriginX; _screenOriginY = screenOriginY; } //------------------------------------------------------------ // debug //------------------------------------------------------------ public function startRecDebugStat():void { debug_countDrawActorPrev = debug_countDrawActor; debug_countDrawDObjPrev = debug_countDrawDObj; debug_countVisiblePrev = debug_countVisible; debug_countDrawActor = 0; debug_countDrawDObj = 0; debug_countVisible = 0; } private function _debug_onObjAdd(args:Object):void { if (args.label != _label) { return; } if (!debug_numObjectByDepth) { debug_numObjectByDepth = []; for (var i:int = 0; i <= _tree.maxDepth; ++i) { debug_numObjectByDepth[i] = 0; } } debug_numObjectByDepth[args.depth] += 1; } private function _debug_onActorDraw(args:Object):void { if (args.label != _label) { return; } debug_countDrawActor += args.num; } private function _debug_onDObjDraw(args:Object):void { if (args.label != _label) { return; } debug_countDrawDObj += args.num; } private function _debug_onNodeEnabled(args:Object):void { if (args.label != _label) { return; } debug_countVisible += 1; } } }
package krewfw.builtin_actor.world { import flash.geom.Rectangle; import starling.display.DisplayObject; import starling.display.Image; import starling.display.Sprite; import krewfw.core.KrewActor; //------------------------------------------------------------ public class KrewWorldLayer extends KrewActor { private var _halfScreenWidth:Number; private var _halfScreenHeight:Number; private var _screenOriginX:Number; private var _screenOriginY:Number; private var _label:String; private var _tree:QuadTreeSprite; private var _focusX:Number = 0; private var _focusY:Number = 0; private var _baseZoomScale:Number = 1.0; private var _zoomScale:Number = 1.0; private var _viewport:Rectangle; //----- debug stat public var debug_numObjectByDepth:Array; public var debug_countDrawActor:int; public var debug_countDrawActorPrev:int; public var debug_countDrawDObj:int; public var debug_countDrawDObjPrev:int; public var debug_countVisiblePrev:int; public var debug_countVisible:int; //------------------------------------------------------------ public function KrewWorldLayer(worldWidth:Number, worldHeight:Number, screenWidth:Number, screenHeight:Number, baseZoomScale:Number=1.0, maxQuadTreeDepth:int=6, subNodeMargin:Number=0.2, screenOriginX:Number=0, screenOriginY:Number=0, label:String="") { _halfScreenWidth = screenWidth / 2; _halfScreenHeight = screenHeight / 2; _screenOriginX = screenOriginX; _screenOriginY = screenOriginY; _baseZoomScale = baseZoomScale; _label = label; _tree = new QuadTreeSprite( worldWidth, worldHeight, 0, 0, 0, maxQuadTreeDepth, subNodeMargin, label ); super.addChild(_tree); _viewport = new Rectangle(); } //------------------------------------------------------------ // Actor's event handlers //------------------------------------------------------------ public override function init():void { listen(QuadTreeSprite.DEBUG_EVENT_ADD, _debug_onObjAdd); listen(QuadTreeSprite.DEBUG_EVENT_DRAW_ACTOR, _debug_onActorDraw); listen(QuadTreeSprite.DEBUG_EVENT_DRAW_DOBJ, _debug_onDObjDraw); listen(QuadTreeSprite.DEBUG_EVENT_ENABLE_NODE, _debug_onNodeEnabled); } protected override function onDispose():void { _tree.dispose(); _tree = null; _viewport = null; } public function updateWorld(passedTime:Number):void { _tree.updateActors(passedTime); } //------------------------------------------------------------ // accessors //------------------------------------------------------------ public function get treeRoot():QuadTreeSprite { return _tree; } public function get viewport():Rectangle { return _viewport; } public function get baseZoomScale():Number { return _baseZoomScale; } public function set baseZoomScale(scale:Number):void { _baseZoomScale = scale; } //------------------------------------------------------------ // public //------------------------------------------------------------ /** width と height はアンカーが中心にあることを想定 */ public function putActor(actor:KrewActor, width:Number=NaN, height:Number=NaN):void { _tree.addActor(actor, width, height); if (!actor.hasInitialized) { actor.setUp(sharedObj, applyForNewActor, layer, layerName); } } /** width と height はアンカーが中心にあることを想定 */ public function putDisplayObj(child:DisplayObject, width:Number=NaN, height:Number=NaN, anchorX:Number=0.5, anchorY:Number=0.5):void { if (child is Image) { var image:Image = child as Image; image.pivotX = image.texture.width * anchorX; image.pivotY = image.texture.height * anchorY; } _tree.addDisplayObj(child, width, height); } public function setFocusPos(x:Number, y:Number):void { _focusX = x; _focusY = y; } public function setZoomScale(scale:Number):void { _zoomScale = scale; if (_zoomScale <= 0) { _zoomScale = 0.001; } } public function updateViewport():void { var zoomScale:Number = _zoomScale * _baseZoomScale; x = -(_focusX * zoomScale) + _screenOriginX + _halfScreenWidth; y = -(_focusY * zoomScale) + _screenOriginY + _halfScreenHeight; scaleX = zoomScale; scaleY = zoomScale; _viewport.setTo( _focusX - (_halfScreenWidth / zoomScale), _focusY - (_halfScreenHeight / zoomScale), _halfScreenWidth * 2 / zoomScale, _halfScreenHeight * 2 / zoomScale ); _tree.updateVisibility(_viewport); } public function updateScreenSize(screenWidth:Number, screenHeight:Number, screenOriginX:Number=0, screenOriginY:Number=0):void { _halfScreenWidth = screenWidth / 2; _halfScreenHeight = screenHeight / 2; _screenOriginX = screenOriginX; _screenOriginY = screenOriginY; } //------------------------------------------------------------ // debug //------------------------------------------------------------ public function startRecDebugStat():void { debug_countDrawActorPrev = debug_countDrawActor; debug_countDrawDObjPrev = debug_countDrawDObj; debug_countVisiblePrev = debug_countVisible; debug_countDrawActor = 0; debug_countDrawDObj = 0; debug_countVisible = 0; } private function _debug_onObjAdd(args:Object):void { if (args.label != _label) { return; } if (!debug_numObjectByDepth) { debug_numObjectByDepth = []; for (var i:int = 0; i <= _tree.maxDepth; ++i) { debug_numObjectByDepth[i] = 0; } } debug_numObjectByDepth[args.depth] += 1; } private function _debug_onActorDraw(args:Object):void { if (args.label != _label) { return; } debug_countDrawActor += args.num; } private function _debug_onDObjDraw(args:Object):void { if (args.label != _label) { return; } debug_countDrawDObj += args.num; } private function _debug_onNodeEnabled(args:Object):void { if (args.label != _label) { return; } debug_countVisible += 1; } } }
Add baseZoomeScale accessor to KrewWorldLayer
Add baseZoomeScale accessor to KrewWorldLayer
ActionScript
mit
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
9ebd17829bbad41d84deb6b57be66d6e14e04674
src/goplayer/Player.as
src/goplayer/Player.as
package goplayer { public class Player implements FlashNetConnectionListener, FlashNetStreamListener { private const DEFAULT_VOLUME : Number = .8 private const DETERMINE_BANDWIDTH : Boolean = true private const START_BUFFER : Duration = Duration.seconds(.1) private const SMALL_BUFFER : Duration = Duration.seconds(10) private const LARGE_BUFFER : Duration = Duration.seconds(60) private const finishingListeners : Array = [] private var _movie : Movie private var connection : FlashNetConnection private var _started : Boolean = false private var _finished : Boolean = false private var triedStandardRTMP : Boolean = false private var rtmpAvailable : 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 = DEFAULT_VOLUME private var savedVolume : Number = 0 private var _paused : Boolean = false private var _buffering : Boolean = false public function Player (movie : Movie, connection : FlashNetConnection) { _movie = movie, this.connection = connection connection.listener = this } public function get movie() : Movie { return _movie } public function addFinishingListener (value : PlayerFinishingListener) : void { finishingListeners.push(value) } public function get finished() : Boolean { return _finished } // ----------------------------------------------------- public function get started() : Boolean { return _started } public function start() : void { _started = true if (movie.rtmpURL) connectUsingRTMP() else connectUsingHTTP() } 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() } private function connectUsingRTMP() : void { connection.connect(movie.rtmpURL) } private function connectUsingStandardRTMP() : void { triedStandardRTMP = true connection.connect(movie.rtmpURL.withoutPort) } private function connectUsingHTTP() : void { rtmpAvailable = false connection.dontConnect() startPlaying() } public function handleConnectionClosed() : void {} // ----------------------------------------------------- public function handleConnectionEstablished() : void { rtmpAvailable = true if (DETERMINE_BANDWIDTH) connection.determineBandwidth() else startPlaying() } 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 (rtmpAvailable) playRTMPStream() else playHTTPStream() if (paused) stream.paused = true } private function playRTMPStream() : void { stream.playRTMP(bestStream, streams) } private function playHTTPStream() : void { stream.playHTTP(movie.httpURL) } private function get bestStream() : RTMPStream { return new RTMPStreamPicker(streams, maxBitrate).bestStream } private function get streams() : Array { return movie.rtmpStreams } private function get maxBitrate() : Bitrate { return bandwidthDetermined ? measuredBandwidth.scaledBy(.8) : null } // ----------------------------------------------------- public function handleNetStreamMetadata(data : Object) : void { metadata = data } 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 handleStreamingStopped() : void { if (finishedPlaying) handleFinishedPlaying() } private function handleFinishedPlaying() : void { debug("Finished playing.") _finished = true for each (var listener : PlayerFinishingListener in finishingListeners) listener.handleMovieFinishedPlaying() } private function get finishedPlaying() : Boolean { return timeRemaining.seconds < 1 } private function get timeRemaining() : Duration { return streamLength.minus(playheadPosition) } // ----------------------------------------------------- public function get paused() : Boolean { return _paused } public function set paused(value : Boolean) : void { // Allow pausing before the stream has been created. _paused = value if (stream) stream.paused = value } public function togglePaused() : void { // Forbid pausing before the stream has been created. if (stream) paused = !paused } // ----------------------------------------------------- public function get playheadPosition() : Duration { return stream != null && stream.playheadPosition != null ? stream.playheadPosition : Duration.ZERO } public function get playheadRatio() : Number { return getRatio(playheadPosition.seconds, streamLength.seconds) } public function get bufferRatio() : Number { return getRatio(bufferPosition.seconds, streamLength.seconds) } private function getRatio (numerator : Number, denominator : Number) : Number { return Math.min(1, numerator / denominator) } private function get bufferPosition() : Duration { return playheadPosition.plus(bufferLength) } public function set playheadPosition(value : Duration) : void { if (!stream) return useStartBuffer() _finished = false stream.playheadPosition = value } public function set playheadRatio(value : Number) : void { playheadPosition = streamLength.scaledBy(value) } public function seekBy(delta : Duration) : void { playheadPosition = playheadPosition.plus(delta) } public function rewind() : void { playheadPosition = Duration.ZERO } public function get playing() : Boolean { return started && !paused && !finished } // ----------------------------------------------------- public function get volume() : Number { return _volume } public function set volume(value : Number) : void { _volume = value if (stream) stream.volume = value } 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 streamLength() : 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 { public class Player implements FlashNetConnectionListener, FlashNetStreamListener { private const DEFAULT_VOLUME : Number = .8 private const DETERMINE_BANDWIDTH : Boolean = true private const START_BUFFER : Duration = Duration.seconds(1) private const SMALL_BUFFER : Duration = Duration.seconds(5) private const LARGE_BUFFER : Duration = Duration.seconds(60) private const finishingListeners : Array = [] private var _movie : Movie private var connection : FlashNetConnection private var _started : Boolean = false private var _finished : Boolean = false private var triedStandardRTMP : Boolean = false private var rtmpAvailable : 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 = DEFAULT_VOLUME private var savedVolume : Number = 0 private var _paused : Boolean = false private var _buffering : Boolean = false public function Player (movie : Movie, connection : FlashNetConnection) { _movie = movie, this.connection = connection connection.listener = this } public function get movie() : Movie { return _movie } public function addFinishingListener (value : PlayerFinishingListener) : void { finishingListeners.push(value) } public function get finished() : Boolean { return _finished } // ----------------------------------------------------- public function get started() : Boolean { return _started } public function start() : void { _started = true if (movie.rtmpURL) connectUsingRTMP() else connectUsingHTTP() } 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() } private function connectUsingRTMP() : void { connection.connect(movie.rtmpURL) } private function connectUsingStandardRTMP() : void { triedStandardRTMP = true connection.connect(movie.rtmpURL.withoutPort) } private function connectUsingHTTP() : void { rtmpAvailable = false connection.dontConnect() startPlaying() } public function handleConnectionClosed() : void {} // ----------------------------------------------------- public function handleConnectionEstablished() : void { rtmpAvailable = true if (DETERMINE_BANDWIDTH) connection.determineBandwidth() else startPlaying() } 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 (rtmpAvailable) playRTMPStream() else playHTTPStream() if (paused) stream.paused = true } private function playRTMPStream() : void { stream.playRTMP(bestStream, streams) } private function playHTTPStream() : void { stream.playHTTP(movie.httpURL) } private function get bestStream() : RTMPStream { return new RTMPStreamPicker(streams, maxBitrate).bestStream } private function get streams() : Array { return movie.rtmpStreams } private function get maxBitrate() : Bitrate { return bandwidthDetermined ? measuredBandwidth.scaledBy(.8) : null } // ----------------------------------------------------- public function handleNetStreamMetadata(data : Object) : void { metadata = data } 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 handleStreamingStopped() : void { if (finishedPlaying) handleFinishedPlaying() } private function handleFinishedPlaying() : void { debug("Finished playing.") _finished = true for each (var listener : PlayerFinishingListener in finishingListeners) listener.handleMovieFinishedPlaying() } private function get finishedPlaying() : Boolean { return timeRemaining.seconds < 1 } private function get timeRemaining() : Duration { return streamLength.minus(playheadPosition) } // ----------------------------------------------------- public function get paused() : Boolean { return _paused } public function set paused(value : Boolean) : void { // Allow pausing before the stream has been created. _paused = value if (stream) stream.paused = value } public function togglePaused() : void { // Forbid pausing before the stream has been created. if (stream) paused = !paused } // ----------------------------------------------------- public function get playheadPosition() : Duration { return stream != null && stream.playheadPosition != null ? stream.playheadPosition : Duration.ZERO } public function get playheadRatio() : Number { return getRatio(playheadPosition.seconds, streamLength.seconds) } public function get bufferRatio() : Number { return getRatio(bufferPosition.seconds, streamLength.seconds) } private function getRatio (numerator : Number, denominator : Number) : Number { return Math.min(1, numerator / denominator) } private function get bufferPosition() : Duration { return playheadPosition.plus(bufferLength) } public function set playheadPosition(value : Duration) : void { if (!stream) return useStartBuffer() _finished = false stream.playheadPosition = value } public function set playheadRatio(value : Number) : void { playheadPosition = streamLength.scaledBy(value) } public function seekBy(delta : Duration) : void { playheadPosition = playheadPosition.plus(delta) } public function rewind() : void { playheadPosition = Duration.ZERO } public function get playing() : Boolean { return started && !paused && !finished } // ----------------------------------------------------- public function get volume() : Number { return _volume } public function set volume(value : Number) : void { _volume = value if (stream) stream.volume = value } 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 streamLength() : 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 } } }
Change buffer sizes from .1/10/60 to 1/5/60.
Change buffer sizes from .1/10/60 to 1/5/60.
ActionScript
mit
dbrock/goplayer,dbrock/goplayer
2a9d4e6b39c8f8d551215cab049d0fa373cf5dd6
src/aerys/minko/render/shader/compiler/graph/ShaderGraph.as
src/aerys/minko/render/shader/compiler/graph/ShaderGraph.as
package aerys.minko.render.shader.compiler.graph { import aerys.minko.Minko; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.Signature; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Extract; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Instruction; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Interpolate; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Overwriter; import aerys.minko.render.shader.compiler.graph.nodes.vertex.VariadicExtract; import aerys.minko.render.shader.compiler.graph.visitors.*; import aerys.minko.render.shader.compiler.register.Components; import aerys.minko.render.shader.compiler.sequence.AgalInstruction; import aerys.minko.type.log.DebugLevel; import aerys.minko.type.stream.format.VertexComponent; import flash.utils.ByteArray; import flash.utils.Dictionary; import flash.utils.Endian; /** * @private * @author Romain Gilliotte * */ public class ShaderGraph { private static const SPLITTER : SplitterVisitor = new SplitterVisitor(); private static const REMOVE_EXTRACT : RemoveExtractsVisitor = new RemoveExtractsVisitor(); private static const MERGER : MergeVisitor = new MergeVisitor(); private static const OVERWRITER_CLEANER : OverwriterCleanerVisitor = new OverwriterCleanerVisitor(); private static const RESOLVE_CONSTANT : ResolveConstantComputationVisitor = new ResolveConstantComputationVisitor(); private static const CONSTANT_PACKER : ConstantPackerVisitor = new ConstantPackerVisitor(); private static const CONSTANT_GROUPER : ConstantGrouperVisitor = new ConstantGrouperVisitor(); private static const RESOLVE_PARAMETRIZED : ResolveParametrizedComputationVisitor = new ResolveParametrizedComputationVisitor(); private static const REMOVE_USELESS : RemoveUselessComputation = new RemoveUselessComputation(); private static const COPY_INSERTER : CopyInserterVisitor = new CopyInserterVisitor(); private static const ALLOCATOR : AllocationVisitor = new AllocationVisitor(); private static const INTERPOLATE_FINDER : InterpolateFinder = new InterpolateFinder(); private static const WRITE_DOT : WriteDot = new WriteDot(); private static const MATRIX_TRANSFORMATION : MatrixTransformationGrouper = new MatrixTransformationGrouper(); private var _position : AbstractNode; private var _positionComponents : uint; private var _interpolates : Vector.<AbstractNode>; private var _color : AbstractNode; private var _colorComponents : uint; private var _kills : Vector.<AbstractNode>; private var _killComponents : Vector.<uint>; private var _computableConstants : Object; private var _isCompiled : Boolean; private var _vertexSequence : Vector.<AgalInstruction>; private var _fragmentSequence : Vector.<AgalInstruction>; private var _bindings : Object; private var _vertexComponents : Vector.<VertexComponent>; private var _vertexIndices : Vector.<uint>; private var _vsConstants : Vector.<Number>; private var _fsConstants : Vector.<Number>; private var _textures : Vector.<ITextureResource>; public function get position() : AbstractNode { return _position; } public function set position(v : AbstractNode) : void { _position = v; } public function get interpolates() : Vector.<AbstractNode> { return _interpolates; } public function get color() : AbstractNode { return _color; } public function set color(v : AbstractNode) : void { _color = v; } public function get kills() : Vector.<AbstractNode> { return _kills; } public function get positionComponents() : uint { return _positionComponents; } public function set positionComponents(v : uint) : void { _positionComponents = v; } public function get colorComponents() : uint { return _colorComponents; } public function set colorComponents(v : uint) : void { _colorComponents = v; } public function get killComponents() : Vector.<uint> { return _killComponents; } public function get computableConstants() : Object { return _computableConstants; } public function ShaderGraph(position : AbstractNode, color : AbstractNode, kills : Vector.<AbstractNode>) { _isCompiled = false; _position = position; _positionComponents = Components.createContinuous(0, 0, 4, position.size); _interpolates = new Vector.<AbstractNode>(); _color = color; _colorComponents = Components.createContinuous(0, 0, 4, color.size); _kills = kills; _killComponents = new Vector.<uint>(); _computableConstants = new Object(); var numKills : uint = kills.length; for (var killId : uint = 0; killId < numKills; ++killId) _killComponents[killId] = Components.createContinuous(0, 0, 1, 1); } public function generateProgram(name : String, signature : Signature) : Program3DResource { if (!_isCompiled) compile(); if (Minko.debugLevel & DebugLevel.SHADER_AGAL) Minko.log(DebugLevel.SHADER_AGAL, generateAGAL(name)); var vsProgram : ByteArray = computeBinaryProgram(_vertexSequence, true); var fsProgram : ByteArray = computeBinaryProgram(_fragmentSequence, false); var program : Program3DResource = new Program3DResource( name, signature, vsProgram, fsProgram, _vertexComponents, _vertexIndices, _vsConstants, _fsConstants, _textures, _bindings ); return program; } public function generateAGAL(name : String) : String { var instruction : AgalInstruction; var shader : String = name + "\n"; if (!_isCompiled) compile(); shader += "- vertex shader\n"; for each (instruction in _vertexSequence) shader += instruction.getAgal(true); shader += "- fragment shader\n"; for each (instruction in _fragmentSequence) shader += instruction.getAgal(false); return shader; } private function compile() : void { // execute consecutive visitors to optimize the shader graph. // Warning: the order matters, do not swap lines. MERGER .process(this); // merge duplicate nodes REMOVE_EXTRACT .process(this); // remove all extract nodes OVERWRITER_CLEANER .process(this); // remove nested overwriters RESOLVE_CONSTANT .process(this); // resolve constant computation CONSTANT_PACKER .process(this); // pack constants [0,0,0,1] => [0,1].xxxy REMOVE_USELESS .process(this); // remove some useless operations (add 0, mul 0, mul 1...) RESOLVE_PARAMETRIZED .process(this); // replace computations that depend on parameters by evalexp parameters // MATRIX_TRANSFORMATION .process(this); // replace ((vector * matrix1) * matrix2) by vector * (matrix1 * matrix2) to save registers on GPU COPY_INSERTER .process(this); // ensure there are no operations between constants SPLITTER .process(this); // clone nodes that are shared between vertex and fragment shader CONSTANT_GROUPER .process(this); // group constants [0,1] & [0,2] => [0, 1, 2] if (Minko.debugLevel & DebugLevel.SHADER_DOTTY) { WRITE_DOT.process(this); Minko.log(DebugLevel.SHADER_DOTTY, WRITE_DOT.result); WRITE_DOT.clear(); } // generate final program INTERPOLATE_FINDER .process(this); // find interpolate nodes. We may skip that in the future. ALLOCATOR .process(this); // allocate memory and generate final code. // retrieve program _vertexSequence = ALLOCATOR.vertexSequence; _fragmentSequence = ALLOCATOR.fragmentSequence; _bindings = ALLOCATOR.parameterBindings; _vertexComponents = ALLOCATOR.vertexComponents; _vertexIndices = ALLOCATOR.vertexIndices; _vsConstants = ALLOCATOR.vertexConstants; _fsConstants = ALLOCATOR.fragmentConstants; _textures = ALLOCATOR.textures; ALLOCATOR.clear(); _isCompiled = true; } private function computeBinaryProgram(sequence : Vector.<AgalInstruction>, isVertexShader : Boolean) : ByteArray { var program : ByteArray = new ByteArray(); program.endian = Endian.LITTLE_ENDIAN; program.writeByte(0xa0); // tag version program.writeUnsignedInt(1); // AGAL version, big endian, bit pattern will be 0x01000000 program.writeByte(0xa1); // tag program id program.writeByte(isVertexShader ? 0 : 1); // vertex or fragment for each (var instruction : AgalInstruction in sequence) instruction.getBytecode(program); return program; } } }
package aerys.minko.render.shader.compiler.graph { import aerys.minko.Minko; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.Signature; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Extract; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Instruction; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Interpolate; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Overwriter; import aerys.minko.render.shader.compiler.graph.nodes.vertex.VariadicExtract; import aerys.minko.render.shader.compiler.graph.visitors.*; import aerys.minko.render.shader.compiler.register.Components; import aerys.minko.render.shader.compiler.sequence.AgalInstruction; import aerys.minko.type.log.DebugLevel; import aerys.minko.type.stream.format.VertexComponent; import flash.utils.ByteArray; import flash.utils.Dictionary; import flash.utils.Endian; /** * @private * @author Romain Gilliotte * */ public class ShaderGraph { private static const SPLITTER : SplitterVisitor = new SplitterVisitor(); private static const REMOVE_EXTRACT : RemoveExtractsVisitor = new RemoveExtractsVisitor(); private static const MERGER : MergeVisitor = new MergeVisitor(); private static const OVERWRITER_CLEANER : OverwriterCleanerVisitor = new OverwriterCleanerVisitor(); private static const RESOLVE_CONSTANT : ResolveConstantComputationVisitor = new ResolveConstantComputationVisitor(); private static const CONSTANT_PACKER : ConstantPackerVisitor = new ConstantPackerVisitor(); private static const CONSTANT_GROUPER : ConstantGrouperVisitor = new ConstantGrouperVisitor(); private static const RESOLVE_PARAMETRIZED : ResolveParametrizedComputationVisitor = new ResolveParametrizedComputationVisitor(); private static const REMOVE_USELESS : RemoveUselessComputation = new RemoveUselessComputation(); private static const COPY_INSERTER : CopyInserterVisitor = new CopyInserterVisitor(); private static const ALLOCATOR : AllocationVisitor = new AllocationVisitor(); private static const INTERPOLATE_FINDER : InterpolateFinder = new InterpolateFinder(); private static const WRITE_DOT : WriteDot = new WriteDot(); private static const MATRIX_TRANSFORMATION : MatrixTransformationGrouper = new MatrixTransformationGrouper(); private var _position : AbstractNode; private var _positionComponents : uint; private var _interpolates : Vector.<AbstractNode>; private var _color : AbstractNode; private var _colorComponents : uint; private var _kills : Vector.<AbstractNode>; private var _killComponents : Vector.<uint>; private var _computableConstants : Object; private var _isCompiled : Boolean; private var _vertexSequence : Vector.<AgalInstruction>; private var _fragmentSequence : Vector.<AgalInstruction>; private var _bindings : Object; private var _vertexComponents : Vector.<VertexComponent>; private var _vertexIndices : Vector.<uint>; private var _vsConstants : Vector.<Number>; private var _fsConstants : Vector.<Number>; private var _textures : Vector.<ITextureResource>; public function get position() : AbstractNode { return _position; } public function set position(v : AbstractNode) : void { _position = v; } public function get interpolates() : Vector.<AbstractNode> { return _interpolates; } public function get color() : AbstractNode { return _color; } public function set color(v : AbstractNode) : void { _color = v; } public function get kills() : Vector.<AbstractNode> { return _kills; } public function get positionComponents() : uint { return _positionComponents; } public function set positionComponents(v : uint) : void { _positionComponents = v; } public function get colorComponents() : uint { return _colorComponents; } public function set colorComponents(v : uint) : void { _colorComponents = v; } public function get killComponents() : Vector.<uint> { return _killComponents; } public function get computableConstants() : Object { return _computableConstants; } public function ShaderGraph(position : AbstractNode, color : AbstractNode, kills : Vector.<AbstractNode>) { _isCompiled = false; _position = position; _positionComponents = Components.createContinuous(0, 0, 4, position.size); _interpolates = new Vector.<AbstractNode>(); _color = color; _colorComponents = Components.createContinuous(0, 0, 4, color.size); _kills = kills; _killComponents = new Vector.<uint>(); _computableConstants = new Object(); var numKills : uint = kills.length; for (var killId : uint = 0; killId < numKills; ++killId) _killComponents[killId] = Components.createContinuous(0, 0, 1, 1); } public function generateProgram(name : String, signature : Signature) : Program3DResource { if (!_isCompiled) compile(); if (Minko.debugLevel & DebugLevel.SHADER_AGAL) Minko.log(DebugLevel.SHADER_AGAL, generateAGAL(name)); var vsProgram : ByteArray = computeBinaryProgram(_vertexSequence, true); var fsProgram : ByteArray = computeBinaryProgram(_fragmentSequence, false); var program : Program3DResource = new Program3DResource( name, signature, vsProgram, fsProgram, _vertexComponents, _vertexIndices, _vsConstants, _fsConstants, _textures, _bindings ); return program; } public function generateAGAL(name : String) : String { var instruction : AgalInstruction; var shader : String = name + "\n"; if (!_isCompiled) compile(); shader += "- vertex shader\n"; for each (instruction in _vertexSequence) shader += instruction.getAgal(true); shader += "- fragment shader\n"; for each (instruction in _fragmentSequence) shader += instruction.getAgal(false); return shader; } private function compile() : void { // execute consecutive visitors to optimize the shader graph. // Warning: the order matters, do not swap lines. MERGER .process(this); // merge duplicate nodes REMOVE_EXTRACT .process(this); // remove all extract nodes OVERWRITER_CLEANER .process(this); // remove nested overwriters RESOLVE_CONSTANT .process(this); // resolve constant computation CONSTANT_PACKER .process(this); // pack constants [0,0,0,1] => [0,1].xxxy // REMOVE_USELESS .process(this); // remove some useless operations (add 0, mul 0, mul 1...) RESOLVE_PARAMETRIZED .process(this); // replace computations that depend on parameters by evalexp parameters // MATRIX_TRANSFORMATION .process(this); // replace ((vector * matrix1) * matrix2) by vector * (matrix1 * matrix2) to save registers on GPU COPY_INSERTER .process(this); // ensure there are no operations between constants SPLITTER .process(this); // clone nodes that are shared between vertex and fragment shader CONSTANT_GROUPER .process(this); // group constants [0,1] & [0,2] => [0, 1, 2] if (Minko.debugLevel & DebugLevel.SHADER_DOTTY) { WRITE_DOT.process(this); Minko.log(DebugLevel.SHADER_DOTTY, WRITE_DOT.result); WRITE_DOT.clear(); } // generate final program INTERPOLATE_FINDER .process(this); // find interpolate nodes. We may skip that in the future. ALLOCATOR .process(this); // allocate memory and generate final code. // retrieve program _vertexSequence = ALLOCATOR.vertexSequence; _fragmentSequence = ALLOCATOR.fragmentSequence; _bindings = ALLOCATOR.parameterBindings; _vertexComponents = ALLOCATOR.vertexComponents; _vertexIndices = ALLOCATOR.vertexIndices; _vsConstants = ALLOCATOR.vertexConstants; _fsConstants = ALLOCATOR.fragmentConstants; _textures = ALLOCATOR.textures; ALLOCATOR.clear(); _isCompiled = true; } private function computeBinaryProgram(sequence : Vector.<AgalInstruction>, isVertexShader : Boolean) : ByteArray { var program : ByteArray = new ByteArray(); program.endian = Endian.LITTLE_ENDIAN; program.writeByte(0xa0); // tag version program.writeUnsignedInt(1); // AGAL version, big endian, bit pattern will be 0x01000000 program.writeByte(0xa1); // tag program id program.writeByte(isVertexShader ? 0 : 1); // vertex or fragment for each (var instruction : AgalInstruction in sequence) instruction.getBytecode(program); return program; } } }
Comment shadergraph visitor
Comment shadergraph visitor M Remove_useless visitor creates errors inside the shader graph
ActionScript
mit
aerys/minko-as3
775908759ff9547892980080b2f126652452c573
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/ContainerView.as
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/ContainerView.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.beads { import org.apache.flex.core.BeadViewBase; import org.apache.flex.core.ContainerBase; import org.apache.flex.core.IBead; import org.apache.flex.core.IBeadLayout; import org.apache.flex.core.IBeadView; import org.apache.flex.core.ILayoutParent; import org.apache.flex.core.IParentIUIBase; import org.apache.flex.core.IStrand; import org.apache.flex.core.IUIBase; import org.apache.flex.core.UIBase; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.html.supportClasses.Border; import org.apache.flex.html.supportClasses.ContainerContentArea; import org.apache.flex.html.supportClasses.ScrollBar; /** * The ContainerView class is the default view for * the org.apache.flex.core.ContainerBase classes. * It lets you use some CSS styles to manage the border, background * and padding around the content area. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class ContainerView extends BeadViewBase implements IBeadView, ILayoutParent { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function ContainerView() { } /** * The actual parent that parents the children. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var actualParent:UIBase; /** * The layout. The layout may actually layout * the children of the internal content area * and not the pieces of the "chrome" like titlebars * and borders. The ContainerView or its subclass will have some * baked-in logic for handling the chrome. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var layout:IBeadLayout; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set strand(value:IStrand):void { super.strand = value; var host:UIBase = value as UIBase; if (host.isWidthSizedToContent() || host.isHeightSizedToContent()) { // if both dimensions are sized to content, then only draw the // borders, etc, after a child is added. The children in an MXML // document don't send this event until the last child is added. host.addEventListener("childrenAdded", changeHandler); host.addEventListener("layoutNeeded", changeHandler); // listen for width and height changes as well in case the app // switches away from content sizing via binding or other code host.addEventListener("widthChanged", changeHandler); host.addEventListener("heightChanged", changeHandler); } else { // otherwise, listen for size changes before drawing // borders and laying out children. host.addEventListener("widthChanged", changeHandler); host.addEventListener("heightChanged", changeHandler); host.addEventListener("sizeChanged", sizeChangeHandler); // if we have fixed size in both dimensions, listen for children // being added, but also force an initial display to get the // background, border, etc. if (!isNaN(host.explicitWidth) && !isNaN(host.explicitHeight)) { host.addEventListener("childrenAdded", changeHandler); displayBackgroundAndBorder(host); } } checkActualParent(); } private function checkActualParent():Boolean { var host:UIBase = UIBase(_strand); if (contentAreaNeeded()) { if (actualParent == null || actualParent == host) { actualParent = new ContainerContentArea(); actualParent.className = "ActualParent"; host.addElement(actualParent, false); ContainerBase(host).setActualParent(actualParent); } return true; } else { actualParent = host; } return false; } private function sizeChangeHandler(event:Event):void { var host:UIBase = UIBase(_strand); host.addEventListener("childrenAdded", changeHandler); host.addEventListener("layoutNeeded", changeHandler); host.addEventListener("itemsCreated", changeHandler); changeHandler(event); } private var inChangeHandler:Boolean; /** * React if the size changed or content changed * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function changeHandler(event:Event):void { if (inChangeHandler) return; inChangeHandler = true; var host:UIBase = UIBase(_strand); var originalHostWidth:Number = host.width; var originalHostHeight:Number = host.height; if (layout == null) { layout = _strand.getBeadByType(IBeadLayout) as IBeadLayout; if (layout == null) { var c:Class = ValuesManager.valuesImpl.getValue(host, "iBeadLayout"); if (c) { layout = new c() as IBeadLayout; _strand.addBead(layout); } } } var padding:Object = determinePadding(); if (checkActualParent()) { actualParent.x = padding.paddingLeft; actualParent.y = padding.paddingTop; } var pb:Number = padding.paddingBottom; if (isNaN(pb)) pb = 0; var pr:Number = padding.paddingRight; if (isNaN(pr)) pr = 0; var sizeChangedByLayout:Boolean; // if the width is dictated by the parent if (!host.isWidthSizedToContent()) { if (actualParent != host) { // force the width of the internal content area as desired. actualParent.setWidth(host.width - padding.paddingLeft - pr); } // run the layout sizeChangedByLayout = layout.layout(); } else { // if the height is dictated by the parent if (!host.isHeightSizedToContent()) { if (actualParent != host) { // force the height actualParent.setHeight(host.height - padding.paddingTop - pb); } } sizeChangedByLayout = layout.layout(); if (actualParent != host) { // actualParent.width should be the new width after layout. // set the host's width. This should send a widthChanged event and // have it blocked at the beginning of this method host.setWidth(padding.paddingLeft + pr + actualParent.width); } } // and if the height is sized to content, set the height now as well. if (host != actualParent) { if (host.isHeightSizedToContent()) { host.setHeight(padding.paddingTop + pb + actualParent.height); } else actualParent.setHeight(host.height - padding.paddingTop - pb); } // if host and actualParent are the same, determine if the layout changed // the size and if, dispatch events based on what changed else if (sizeChangedByLayout) { if (originalHostWidth != host.width) host.dispatchEvent(new Event("widthChanged")); if (originalHostHeight != host.height) host.dispatchEvent(new Event("heightChanged")); } displayBackgroundAndBorder(host); inChangeHandler = false; } protected function displayBackgroundAndBorder(host:UIBase) : void { var backgroundColor:Object = ValuesManager.valuesImpl.getValue(host, "background-color"); var backgroundImage:Object = ValuesManager.valuesImpl.getValue(host, "background-image"); if (backgroundColor != null || backgroundImage != null) { if (host.getBeadByType(IBackgroundBead) == null) host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBackgroundBead")) as IBead); } var borderStyle:String; var borderStyles:Object = ValuesManager.valuesImpl.getValue(host, "border"); if (borderStyles is Array) { borderStyle = borderStyles[1]; } if (borderStyle == null) { borderStyle = ValuesManager.valuesImpl.getValue(host, "border-style") as String; } if (borderStyle != null && borderStyle != "none") { if (host.getBeadByType(IBorderBead) == null) host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBorderBead")) as IBead); } } /** * Determines the top and left padding values, if any, as set by * padding style values. This includes "padding" for all padding values * as well as "padding-left" and "padding-top". * * Returns an object with paddingLeft and paddingTop properties. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function determinePadding():Object { var paddingLeft:Object; var paddingTop:Object; var paddingRight:Object; var paddingBottom:Object; var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding"); if (padding is Array) { if (padding.length == 1) paddingLeft = paddingTop = padding[0]; else if (padding.length <= 3) { paddingLeft = padding[1]; paddingTop = padding[0]; } else if (padding.length == 4) { paddingLeft = padding[3]; paddingTop = padding[0]; } } else if (padding == null) { paddingLeft = ValuesManager.valuesImpl.getValue(_strand, "padding-left"); paddingTop = ValuesManager.valuesImpl.getValue(_strand, "padding-top"); paddingRight = ValuesManager.valuesImpl.getValue(_strand, "padding-right"); paddingBottom = ValuesManager.valuesImpl.getValue(_strand, "padding-bottom"); } else { paddingLeft = paddingTop = padding; paddingRight = paddingBottom = padding; } var pl:Number = Number(paddingLeft); var pt:Number = Number(paddingTop); var pr:Number = Number(paddingRight); var pb:Number = Number(paddingBottom); return {paddingLeft:pl, paddingTop:pt, paddingRight:pr, paddingBottom:pb}; } /** * Returns true if container to create a separate ContainerContentArea. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function contentAreaNeeded():Boolean { var padding:Object = determinePadding(); return (!isNaN(padding.paddingLeft) && padding.paddingLeft > 0 || !isNaN(padding.paddingTop) && padding.paddingTop > 0); } /** * The parent of the children. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get contentView():IParentIUIBase { return actualParent; } /** * The host component, which can resize to different slots. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get resizableView():IUIBase { return _strand as IUIBase; } private var inGetViewHeight:Boolean; /** * @copy org.apache.flex.core.IBeadView#viewHeight * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function get viewHeight():Number { if (inGetViewHeight) { //trace("ContainerView: no height set for " + host); return host["$height"]; } inGetViewHeight = true; var vh:Number = contentView.height; inGetViewHeight = false; return vh; } private var inGetViewWidth:Boolean; /** * @copy org.apache.flex.core.IBeadView#viewWidth * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function get viewWidth():Number { if (inGetViewWidth) { //trace("ContainerView: no width set for " + host); return host["$width"]; } inGetViewWidth = true; var vw:Number = contentView.width; inGetViewWidth = false; return vw; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.beads { import org.apache.flex.core.BeadViewBase; import org.apache.flex.core.ContainerBase; import org.apache.flex.core.IBead; import org.apache.flex.core.IBeadLayout; import org.apache.flex.core.IBeadView; import org.apache.flex.core.ILayoutParent; import org.apache.flex.core.IParentIUIBase; import org.apache.flex.core.IStrand; import org.apache.flex.core.IUIBase; import org.apache.flex.core.UIBase; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.html.supportClasses.Border; import org.apache.flex.html.supportClasses.ContainerContentArea; import org.apache.flex.html.supportClasses.ScrollBar; /** * The ContainerView class is the default view for * the org.apache.flex.core.ContainerBase classes. * It lets you use some CSS styles to manage the border, background * and padding around the content area. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class ContainerView extends BeadViewBase implements IBeadView, ILayoutParent { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function ContainerView() { } /** * The actual parent that parents the children. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var actualParent:UIBase; /** * The layout. The layout may actually layout * the children of the internal content area * and not the pieces of the "chrome" like titlebars * and borders. The ContainerView or its subclass will have some * baked-in logic for handling the chrome. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var layout:IBeadLayout; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set strand(value:IStrand):void { super.strand = value; var host:UIBase = value as UIBase; if (host.isWidthSizedToContent() && host.isHeightSizedToContent()) { // if both dimensions are sized to content, then only draw the // borders, etc, after a child is added. The children in an MXML // document don't send this event until the last child is added. host.addEventListener("childrenAdded", changeHandler); host.addEventListener("layoutNeeded", changeHandler); // listen for width and height changes as well in case the app // switches away from content sizing via binding or other code host.addEventListener("widthChanged", changeHandler); host.addEventListener("heightChanged", changeHandler); } else { // otherwise, listen for size changes before drawing // borders and laying out children. host.addEventListener("widthChanged", changeHandler); host.addEventListener("heightChanged", changeHandler); host.addEventListener("sizeChanged", sizeChangeHandler); // if we have fixed size in both dimensions, listen for children // being added, but also force an initial display to get the // background, border, etc. if (!isNaN(host.explicitWidth) && !isNaN(host.explicitHeight)) { host.addEventListener("childrenAdded", changeHandler); displayBackgroundAndBorder(host); } } checkActualParent(); } private function checkActualParent():Boolean { var host:UIBase = UIBase(_strand); if (contentAreaNeeded()) { if (actualParent == null || actualParent == host) { actualParent = new ContainerContentArea(); actualParent.className = "ActualParent"; host.addElement(actualParent, false); ContainerBase(host).setActualParent(actualParent); } return true; } else { actualParent = host; } return false; } private function sizeChangeHandler(event:Event):void { var host:UIBase = UIBase(_strand); host.addEventListener("childrenAdded", changeHandler); host.addEventListener("layoutNeeded", changeHandler); host.addEventListener("itemsCreated", changeHandler); changeHandler(event); } private var inChangeHandler:Boolean; /** * React if the size changed or content changed * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function changeHandler(event:Event):void { if (inChangeHandler) return; inChangeHandler = true; var host:UIBase = UIBase(_strand); var originalHostWidth:Number = host.width; var originalHostHeight:Number = host.height; if (layout == null) { layout = _strand.getBeadByType(IBeadLayout) as IBeadLayout; if (layout == null) { var c:Class = ValuesManager.valuesImpl.getValue(host, "iBeadLayout"); if (c) { layout = new c() as IBeadLayout; _strand.addBead(layout); } } } var padding:Object = determinePadding(); if (checkActualParent()) { actualParent.x = padding.paddingLeft; actualParent.y = padding.paddingTop; } var pb:Number = padding.paddingBottom; if (isNaN(pb)) pb = 0; var pr:Number = padding.paddingRight; if (isNaN(pr)) pr = 0; var sizeChangedByLayout:Boolean; // if the width is dictated by the parent if (!host.isWidthSizedToContent()) { if (actualParent != host) { // force the width of the internal content area as desired. actualParent.setWidth(host.width - padding.paddingLeft - pr); } // run the layout sizeChangedByLayout = layout.layout(); } else { // if the height is dictated by the parent if (!host.isHeightSizedToContent()) { if (actualParent != host) { // force the height actualParent.setHeight(host.height - padding.paddingTop - pb); } } sizeChangedByLayout = layout.layout(); if (actualParent != host) { // actualParent.width should be the new width after layout. // set the host's width. This should send a widthChanged event and // have it blocked at the beginning of this method host.setWidth(padding.paddingLeft + pr + actualParent.width); } } // and if the height is sized to content, set the height now as well. if (host != actualParent) { if (host.isHeightSizedToContent()) { host.setHeight(padding.paddingTop + pb + actualParent.height); } else actualParent.setHeight(host.height - padding.paddingTop - pb); } // if host and actualParent are the same, determine if the layout changed // the size and if, dispatch events based on what changed else if (sizeChangedByLayout) { if (originalHostWidth != host.width) host.dispatchEvent(new Event("widthChanged")); if (originalHostHeight != host.height) host.dispatchEvent(new Event("heightChanged")); } displayBackgroundAndBorder(host); inChangeHandler = false; } protected function displayBackgroundAndBorder(host:UIBase) : void { var backgroundColor:Object = ValuesManager.valuesImpl.getValue(host, "background-color"); var backgroundImage:Object = ValuesManager.valuesImpl.getValue(host, "background-image"); if (backgroundColor != null || backgroundImage != null) { if (host.getBeadByType(IBackgroundBead) == null) host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBackgroundBead")) as IBead); } var borderStyle:String; var borderStyles:Object = ValuesManager.valuesImpl.getValue(host, "border"); if (borderStyles is Array) { borderStyle = borderStyles[1]; } if (borderStyle == null) { borderStyle = ValuesManager.valuesImpl.getValue(host, "border-style") as String; } if (borderStyle != null && borderStyle != "none") { if (host.getBeadByType(IBorderBead) == null) host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBorderBead")) as IBead); } } /** * Determines the top and left padding values, if any, as set by * padding style values. This includes "padding" for all padding values * as well as "padding-left" and "padding-top". * * Returns an object with paddingLeft and paddingTop properties. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function determinePadding():Object { var paddingLeft:Object; var paddingTop:Object; var paddingRight:Object; var paddingBottom:Object; var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding"); if (padding is Array) { if (padding.length == 1) paddingLeft = paddingTop = padding[0]; else if (padding.length <= 3) { paddingLeft = padding[1]; paddingTop = padding[0]; } else if (padding.length == 4) { paddingLeft = padding[3]; paddingTop = padding[0]; } } else if (padding == null) { paddingLeft = ValuesManager.valuesImpl.getValue(_strand, "padding-left"); paddingTop = ValuesManager.valuesImpl.getValue(_strand, "padding-top"); paddingRight = ValuesManager.valuesImpl.getValue(_strand, "padding-right"); paddingBottom = ValuesManager.valuesImpl.getValue(_strand, "padding-bottom"); } else { paddingLeft = paddingTop = padding; paddingRight = paddingBottom = padding; } var pl:Number = Number(paddingLeft); var pt:Number = Number(paddingTop); var pr:Number = Number(paddingRight); var pb:Number = Number(paddingBottom); return {paddingLeft:pl, paddingTop:pt, paddingRight:pr, paddingBottom:pb}; } /** * Returns true if container to create a separate ContainerContentArea. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function contentAreaNeeded():Boolean { var padding:Object = determinePadding(); return (!isNaN(padding.paddingLeft) && padding.paddingLeft > 0 || !isNaN(padding.paddingTop) && padding.paddingTop > 0); } /** * The parent of the children. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get contentView():IParentIUIBase { return actualParent; } /** * The host component, which can resize to different slots. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get resizableView():IUIBase { return _strand as IUIBase; } private var inGetViewHeight:Boolean; /** * @copy org.apache.flex.core.IBeadView#viewHeight * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function get viewHeight():Number { if (inGetViewHeight) { //trace("ContainerView: no height set for " + host); return host["$height"]; } inGetViewHeight = true; var vh:Number = contentView.height; inGetViewHeight = false; return vh; } private var inGetViewWidth:Boolean; /** * @copy org.apache.flex.core.IBeadView#viewWidth * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function get viewWidth():Number { if (inGetViewWidth) { //trace("ContainerView: no width set for " + host); return host["$width"]; } inGetViewWidth = true; var vw:Number = contentView.width; inGetViewWidth = false; return vw; } } }
switch this back to && so we only go down this path when sized to content
switch this back to && so we only go down this path when sized to content
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
05844f5519db9bb49f1e7284d1a0134b678d0261
src/stdio/Process.as
src/stdio/Process.as
package stdio { import flash.display.Sprite import flash.events.* import flash.net.* public class Process extends Sprite { public static var instance: Process = null private const stdin_buffer: StreamBuffer = new StreamBuffer private const stdin_socket: SocketStream = new SocketStream private const stdout_socket: SocketStream = new SocketStream private const stderr_socket: SocketStream = new SocketStream public function Process() { instance = this connect(function (): void { listen_for_uncaught_errors() main() }) } public function main(): void { warn("override public function main(): void {}") } public function exit(status: int = 0): void { post("exit", status.toString()) } private function get base_url(): String { // XXX: Not very robust. return loaderInfo.loaderURL.replace(/\?.*/, "") + "/" } private function post( path: String, content: String, callback: Function = null ): void { const request: URLRequest = new URLRequest(base_url + path) request.method = "POST" request.data = content const loader: URLLoader = new URLLoader if (callback !== null) { loader.addEventListener( Event.COMPLETE, function (event: Event): void { callback(loader.data) } ) } loader.load(request) } public function get argv(): Array { return get_parameter("argv").split(" ").map( function (argument: String, ...rest: Array): String { return decodeURIComponent(argument) } ) } private function get_parameter(name: String): String { return loaderInfo.parameters[name] } private function get_int_parameter(name: String): int { return parseInt(get_parameter(name)) } public function gets(callback: Function): void { stdin.read_line(callback) } public function puts(value: Object): void { stdout.write_line(value) } public function warn(value: Object): void { stderr.write_line(value) } public function get stdin(): InputStream { return stdin_buffer } public function get stdout(): OutputStream { return stdout_socket } public function get stderr(): OutputStream { return stderr_socket } private function listen_for_uncaught_errors(): void { loaderInfo.uncaughtErrorEvents.addEventListener( UncaughtErrorEvent.UNCAUGHT_ERROR, handle_uncaught_error_event ) } protected function handle_uncaught_error_event( event: UncaughtErrorEvent ): void { event.preventDefault() post( "error", event.error is Error ? (event.error as Error).getStackTrace() : event.error, function (response: String): void { exit(1) } ) } private function connect(callback: Function): void { stdin_socket.onopen = onopen stdout_socket.onopen = onopen stderr_socket.onopen = onopen stdin_socket.ondata = stdin_buffer.write stdin_socket.onclose = stdin_buffer.close stdin_socket.connect("localhost", get_int_parameter("stdin")) stdout_socket.connect("localhost", get_int_parameter("stdout")) stderr_socket.connect("localhost", get_int_parameter("stderr")) var n: int = 0 function onopen(): void { if (++n === 3) { callback() } } } } }
package stdio { import flash.display.Sprite import flash.events.* import flash.net.* public class Process extends Sprite { public static var instance: Process = null private const stdin_buffer: StreamBuffer = new StreamBuffer private const stdin_socket: SocketStream = new SocketStream private const stdout_socket: SocketStream = new SocketStream private const stderr_socket: SocketStream = new SocketStream public function Process() { instance = this if (get_parameter("stdin")) { connect(function (): void { listen_for_uncaught_errors() main() }) } else { main() } } public function main(): void { warn("override public function main(): void {}") } public function exit(status: int = 0): void { post("exit", status.toString()) } private function get base_url(): String { // XXX: Not very robust. return loaderInfo.loaderURL.replace(/\?.*/, "") + "/" } private function post( path: String, content: String, callback: Function = null ): void { const request: URLRequest = new URLRequest(base_url + path) request.method = "POST" request.data = content const loader: URLLoader = new URLLoader if (callback !== null) { loader.addEventListener( Event.COMPLETE, function (event: Event): void { callback(loader.data) } ) } loader.load(request) } public function get argv(): Array { return get_parameter("argv").split(" ").map( function (argument: String, ...rest: Array): String { return decodeURIComponent(argument) } ) } private function get_parameter(name: String): String { return loaderInfo.parameters[name] } private function get_int_parameter(name: String): int { return parseInt(get_parameter(name)) } public function gets(callback: Function): void { stdin.read_line(callback) } public function puts(value: Object): void { stdout.write_line(value) } public function warn(value: Object): void { stderr.write_line(value) } public function get stdin(): InputStream { return stdin_buffer } public function get stdout(): OutputStream { return stdout_socket } public function get stderr(): OutputStream { return stderr_socket } private function listen_for_uncaught_errors(): void { loaderInfo.uncaughtErrorEvents.addEventListener( UncaughtErrorEvent.UNCAUGHT_ERROR, handle_uncaught_error_event ) } protected function handle_uncaught_error_event( event: UncaughtErrorEvent ): void { event.preventDefault() post( "error", event.error is Error ? (event.error as Error).getStackTrace() : event.error, function (response: String): void { exit(1) } ) } private function connect(callback: Function): void { stdin_socket.onopen = onopen stdout_socket.onopen = onopen stderr_socket.onopen = onopen stdin_socket.ondata = stdin_buffer.write stdin_socket.onclose = stdin_buffer.close stdin_socket.connect("localhost", get_int_parameter("stdin")) stdout_socket.connect("localhost", get_int_parameter("stdout")) stderr_socket.connect("localhost", get_int_parameter("stderr")) var n: int = 0 function onopen(): void { if (++n === 3) { callback() } } } } }
Enable processes to run outside flashplayer-stdio envionment.
Enable processes to run outside flashplayer-stdio envionment.
ActionScript
mit
dbrock/stdio.as,dbrock/stdio.as,dbrock/stdio.as
322214f6386ff07a97a3f1eba65fa47d887984d1
DragonBonesDesignPanelLib/src/core/utils/OptimizeDataUtils.as
DragonBonesDesignPanelLib/src/core/utils/OptimizeDataUtils.as
package core.utils { import dragonBones.utils.ConstValues; public class OptimizeDataUtils { private static var animationPropertyArray:Array = [ConstValues.A_FADE_IN_TIME, ConstValues.A_SCALE, ConstValues.A_LOOP]; private static var animationValueArray:Array = [0,1,1]; private static var timelinePropertyArray:Array = [ConstValues.A_SCALE, ConstValues.A_OFFSET, ConstValues.A_PIVOT_X, ConstValues.A_PIVOT_Y]; private static var timelineValueArray:Array = [1,0,0,0]; private static var framePropertyArray:Array = [ConstValues.A_TWEEN_SCALE, ConstValues.A_TWEEN_ROTATE, ConstValues.A_HIDE, ConstValues.A_DISPLAY_INDEX, ConstValues.A_SCALE_X_OFFSET, ConstValues.A_SCALE_Y_OFFSET]; private static var frameValueArray:Array = [1,0,0,0,0,0]; private static var transformPropertyArray:Array = [ConstValues.A_X, ConstValues.A_Y, ConstValues.A_SKEW_X, ConstValues.A_SKEW_Y, ConstValues.A_SCALE_X, ConstValues.A_SCALE_Y, ConstValues.A_PIVOT_X, ConstValues.A_PIVOT_Y]; private static var transformValueArray:Array = [0,0,0,0,1,1,0,0]; private static var colorTransformPropertyArray:Array = [ConstValues.A_ALPHA_OFFSET, ConstValues.A_RED_OFFSET, ConstValues.A_GREEN_OFFSET, ConstValues.A_BLUE_OFFSET, ConstValues.A_ALPHA_MULTIPLIER, ConstValues.A_RED_MULTIPLIER, ConstValues.A_GREEN_MULTIPLIER, ConstValues.A_BLUE_MULTIPLIER]; private static var colorTransformValueArray:Array = [0,0,0,0,1,1,1,1]; public static function optimizeData(dragonBonesData:Object):void { for each(var armatureData:Object in dragonBonesData.armature) { var boneDataList:Array = armatureData.bone; for each(var boneData:Object in boneDataList) { optimizeTransform(boneData.transform); } var skinList:Array = armatureData.skin; var slotList:Array; var displayList:Array; for each(var skinData:Object in skinList) { slotList = skinData.slot; for each(var slotData:Object in slotList) { displayList = slotData.display; for each(var displayData:Object in displayList) { optimizeTransform(displayData.transform); } } } var animationList:Array = armatureData.animation; var timelineList:Array; var frameList:Array; for each(var animationData:Object in animationList) { optimizeAnimation(animationData); timelineList = animationData.timeline; for each(var timelineData:Object in timelineList) { optimizeTimeline(timelineData); frameList = timelineData.frame; for each(var frameData:Object in frameList) { optimizeFrame(frameData); optimizeTransform(frameData.transform); optimizeColorTransform(frameData.colorTransform); } } } } } private static function optimizeAnimation(animationData:Object):void { optimizeItem(animationData, animationPropertyArray, animationValueArray, 4); } private static function optimizeTimeline(timelineData:Object):void { optimizeItem(timelineData, timelinePropertyArray, timelineValueArray, 4); } private static function optimizeFrame(frameData:Object):void { optimizeItem(frameData, framePropertyArray, frameValueArray, 4); } private static function optimizeTransform(transform:Object):void { optimizeItem(transform, transformPropertyArray, transformValueArray, 4); } private static function optimizeColorTransform(colorTransform:Object):void { optimizeItem(colorTransform, transformPropertyArray, transformValueArray, 4); } private static function optimizeItem(item:Object, propertyArray:Array, valueArray:Array, prec:uint = 4):void { if(!item) { return; } var i:int = propertyArray.length; var property:String; var value:Number; while(i--) { property = propertyArray[i]; value = valueArray[i]; if(!item.hasOwnProperty(property)) { continue; } if(compareWith(item[property], value, prec)) { delete item[property]; } else { item[property] = Number(Number(item[property]).toFixed(prec)); } } } private static function compareWith(source:Number, target:Number, prec:uint):Boolean { var delta:Number = 1 / Math.pow(10, prec); if(source >= target - delta && source <= target + delta) { return true; } return false; } } }
package core.utils { import dragonBones.utils.ConstValues; public class OptimizeDataUtils { private static var animationPropertyArray:Array = [ConstValues.A_FADE_IN_TIME, ConstValues.A_SCALE, ConstValues.A_LOOP]; private static var animationValueArray:Array = [0,1,1]; private static var timelinePropertyArray:Array = [ConstValues.A_SCALE, ConstValues.A_OFFSET, ConstValues.A_PIVOT_X, ConstValues.A_PIVOT_Y]; private static var timelineValueArray:Array = [1,0,0,0]; private static var framePropertyArray:Array = [ConstValues.A_TWEEN_SCALE, ConstValues.A_TWEEN_ROTATE, ConstValues.A_HIDE, ConstValues.A_DISPLAY_INDEX, ConstValues.A_SCALE_X_OFFSET, ConstValues.A_SCALE_Y_OFFSET]; private static var frameValueArray:Array = [1,0,0,0,0,0]; private static var transformPropertyArray:Array = [ConstValues.A_X, ConstValues.A_Y, ConstValues.A_SKEW_X, ConstValues.A_SKEW_Y, ConstValues.A_SCALE_X, ConstValues.A_SCALE_Y, ConstValues.A_PIVOT_X, ConstValues.A_PIVOT_Y]; private static var transformValueArray:Array = [0,0,0,0,1,1,0,0]; private static var colorTransformPropertyArray:Array = [ConstValues.A_ALPHA_OFFSET, ConstValues.A_RED_OFFSET, ConstValues.A_GREEN_OFFSET, ConstValues.A_BLUE_OFFSET, ConstValues.A_ALPHA_MULTIPLIER, ConstValues.A_RED_MULTIPLIER, ConstValues.A_GREEN_MULTIPLIER, ConstValues.A_BLUE_MULTIPLIER]; private static var colorTransformValueArray:Array = [0,0,0,0,100,100,100,100]; public static function optimizeData(dragonBonesData:Object):void { for each(var armatureData:Object in dragonBonesData.armature) { var boneDataList:Array = armatureData.bone; for each(var boneData:Object in boneDataList) { optimizeTransform(boneData.transform); } var skinList:Array = armatureData.skin; var slotList:Array; var displayList:Array; for each(var skinData:Object in skinList) { slotList = skinData.slot; for each(var slotData:Object in slotList) { displayList = slotData.display; for each(var displayData:Object in displayList) { optimizeTransform(displayData.transform); } } } var animationList:Array = armatureData.animation; var timelineList:Array; var frameList:Array; for each(var animationData:Object in animationList) { optimizeAnimation(animationData); timelineList = animationData.timeline; for each(var timelineData:Object in timelineList) { optimizeTimeline(timelineData); frameList = timelineData.frame; for each(var frameData:Object in frameList) { optimizeFrame(frameData); optimizeTransform(frameData.transform); optimizeColorTransform(frameData.colorTransform); } } } } } private static function optimizeAnimation(animationData:Object):void { optimizeItem(animationData, animationPropertyArray, animationValueArray, 4); } private static function optimizeTimeline(timelineData:Object):void { optimizeItem(timelineData, timelinePropertyArray, timelineValueArray, 4); } private static function optimizeFrame(frameData:Object):void { optimizeItem(frameData, framePropertyArray, frameValueArray, 4); } private static function optimizeTransform(transform:Object):void { optimizeItem(transform, transformPropertyArray, transformValueArray, 4); } private static function optimizeColorTransform(colorTransform:Object):void { optimizeItem(colorTransform, transformPropertyArray, transformValueArray, 4); } private static function optimizeItem(item:Object, propertyArray:Array, valueArray:Array, prec:uint = 4):void { if(!item) { return; } var i:int = propertyArray.length; var property:String; var value:Number; while(i--) { property = propertyArray[i]; value = valueArray[i]; if(!item.hasOwnProperty(property)) { continue; } if(compareWith(item[property], value, prec)) { delete item[property]; } else { item[property] = Number(Number(item[property]).toFixed(prec)); } } } private static function compareWith(source:Number, target:Number, prec:uint):Boolean { var delta:Number = 1 / Math.pow(10, prec); if(source >= target - delta && source <= target + delta) { return true; } return false; } } }
fix a DesignPanel colorTransform default value bug
fix a DesignPanel colorTransform default value bug
ActionScript
mit
DragonBones/DesignPanel
30ace2a68be726795d58bd727eb0ead42a0c3fdb
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.Effect; 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 _dependencyLoaderClosure : Function = defaultDependencyLoaderClosure; 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 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 dependencyLoaderClosure():Function { return _dependencyLoaderClosure; } public function set dependencyLoaderClosure(value:Function):void { _dependencyLoaderClosure = value; } public function get loadDependencies():Boolean { return _loadDependencies; } public function set loadDependencies(value:Boolean):void { _loadDependencies = value; } public function clone(): ParserOptions { return new ParserOptions( _loadDependencies, _dependencyLoaderClosure, _mipmapTextures, _meshEffect, _vertexStreamUsage, _indexStreamUsage, _parser ); } public function ParserOptions(loadDependencies : Boolean = false, dependencyLoaderClosure : Function = null, mipmapTextures : Boolean = true, meshEffect : Effect = null, vertexStreamUsage : uint = 0, indexStreamUsage : uint = 0, parser : Class = null) { _loadDependencies = loadDependencies; _dependencyLoaderClosure = dependencyLoaderClosure || _dependencyLoaderClosure; _mipmapTextures = mipmapTextures; _meshEffect = meshEffect; _vertexStreamUsage = vertexStreamUsage; _indexStreamUsage = indexStreamUsage; _parser = parser; } private function defaultDependencyLoaderClosure(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.Effect; 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 _loadSkin : Boolean = false; private var _dependencyLoaderClosure : Function = defaultDependencyLoaderClosure; 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 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 dependencyLoaderClosure():Function { return _dependencyLoaderClosure; } public function set dependencyLoaderClosure(value:Function):void { _dependencyLoaderClosure = 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 { var parserOptions : ParserOptions = new ParserOptions( _loadDependencies, _dependencyLoaderClosure, _mipmapTextures, _meshEffect, _vertexStreamUsage, _indexStreamUsage, _parser ); parserOptions.loadSkin = _loadSkin; return parserOptions; } public function ParserOptions(loadDependencies : Boolean = false, dependencyLoaderClosure : Function = null, mipmapTextures : Boolean = true, meshEffect : Effect = null, vertexStreamUsage : uint = 0, indexStreamUsage : uint = 0, parser : Class = null) { _loadDependencies = loadDependencies; _dependencyLoaderClosure = dependencyLoaderClosure || _dependencyLoaderClosure; _mipmapTextures = mipmapTextures; _meshEffect = meshEffect; _vertexStreamUsage = vertexStreamUsage; _indexStreamUsage = indexStreamUsage; _parser = parser; } private function defaultDependencyLoaderClosure(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; } } }
Add loadSkin option in ParserOptions
Add loadSkin option in ParserOptions
ActionScript
mit
aerys/minko-as3
7cd7cc48cb2838ec1ce838b8ffc098706af2165a
src/as/com/threerings/util/MultiLoader.as
src/as/com/threerings/util/MultiLoader.as
// // $Id$ package com.threerings.util { import flash.display.Loader; import flash.display.LoaderInfo; import flash.events.AsyncErrorEvent; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IEventDispatcher; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.system.ApplicationDomain; import flash.system.LoaderContext; import flash.utils.ByteArray; import flash.utils.Dictionary; /** * Easy loader for many things, including managing multiple downloads. * More documentation coming. */ public class MultiLoader { /** * Load one or more sources and return DisplayObjects. * * @param sources an Array, Dictionary, or Object containing sources as values, or a single * source value. The sources may be Strings (representing urls), URLRequests, ByteArrays, * or a Class that can be instantiated to become a URLRequest or ByteArray. Note that * the format of your sources Object dictates the format of the return Object. * @param completeCallback the function to call when complete. The signature should be: * <code>function (value :Object) :void</code>. Note that the structure of the return Object * is dictated by the sources parameter. If you pass in an Array, you get your results * in an Array. If you use a Dictionary or Object, the results will be returned as the same, * with the same keys used in sources now pointing to the results. If your sources parameter * was just a single source (like a String) then the result will just be a single result, * like a DisplayObject. Each result will be a DisplayObject or an Error * describing the problem. * @param forEach if true, each value or error will be returned as soon as possible. The values * or errors will be returned directly to the completeCallback. Any keys are lost, so you * probably only want to use this with an Array sources. * @param appDom the ApplicationDomain in which to load the contents, or null to specify * that it should load in a child of the current ApplicationDomain. * * @example Load one embed, add it as a child. * <listing version="3.0"> * MultiLoader.getContents(EMBED_CONSTANT, addChild); * </listing> * * @example Load 3 embeds, add them as children. * <listing version="3.0"> * MultiLoader.getContents([EMBED1, EMBED2, EMBED3], addChild, true); * </listing> * * @example Load multiple URLs, have the contents returned to the result function one at * a time. * <listing version="3.0"> * function handleComplete (result :Object) :void { * // process a result here. Result may be a DisplayObject or an Error. * }; * * var obj :Object = { * key1: "http://somehost.com/someImage.gif", * key2: "http://somehost.com/someOtherImage.gif" * }; * * MultiLoader.getContents(obj, handleComplete, true); * </listing> * * @example Load 3 embeds, wait to handle them until they're all loaded. * <listing version="3.0"> * function handleComplete (results :Array) :void { * // process results here * }; * * MultiLoader.getContents([EMBED1, EMBED2, EMBED3], handleComplete); * </listing> */ public static function getContents ( sources :Object, completeCallback :Function, forEach :Boolean = false, appDom :ApplicationDomain = null) :void { var complete :Function = function (retval :Object) :void { completeCallback(processProperty(retval, Loader, "content")); }; getLoaders(sources, complete, forEach, appDom); } /** * Exactly like getContents() only it returns the Loader objects rather than their contents. * * @example Advanced usage: Loading classes. * <listing version="3.0"> * // A holder for new classes, created as a child of the system domain. * var appDom :ApplicationDomain = new ApplicationDomain(null); * <br/> * function handleComplete (results :Object) :void { * // now we can retrieve classes * var clazz :Class = appDom.getDefinition("com.package.SomeClass") as Class; * } * <br/> * // load all the classes contained in the specified sources * MultiLoader.getLoaders([EMBED, "http://site.com/pack.swf"], handleComplete, false, appDom); * <br/> * [Embed(source="resource.swf", mimeType="application/octet-stream")] * private static const EMBED :Class; * </listing> * * @see getContents() */ public static function getLoaders ( sources :Object, completeCallback :Function, forEach :Boolean = false, appDom :ApplicationDomain = null) :void { var generator :Function = function (source :*) :Object { // first transform common sources to their more useful nature if (source is String) { source = new URLRequest(String(source)); } else if (source is Class) { // it's probably a ByteArray from an Embed, but don't cast it source = new (source as Class)(); } var l :Loader = new Loader(); var lc :LoaderContext = new LoaderContext(false, appDom); // now we only need handle the two cases if (source is URLRequest) { l.load(URLRequest(source), lc); } else if (source is ByteArray) { l.loadBytes(ByteArray(source), lc); } else { return new Error("Unknown source: " + source); } return l.contentLoaderInfo; }; var complete :Function = function (retval :Object) :void { completeCallback(processProperty(retval, LoaderInfo, "loader")); }; new MultiLoader(sources, generator, complete, forEach); } /** * Coordinate loading some asynchronous objects. * * @param sources An Array, Dictionary, or Object of sources, or just a single source. * @param generatorFunciton a function to call to generate the loaders. * @param completeCallack the function to call when complete. * @param forEach whether to call the completeCallback for each source, or all-at-once at * the end. If forEach is used, keys will never be returned. * @param isCompleteCheckFn a function to attempt to call on the dispatcher to see if * it's already complete after generation. * @param errorTypes an Array of event types that will be dispatched by the loader. * If unspecifed, all the normal error event types are used. * @param completeType, the event complete type. If unspecifed @default Event.COMPLETE. */ public function MultiLoader ( sources :Object, generatorFn :Function, completeCallback :Function, forEach :Boolean = false, isCompleteCheckFn :String = null, errorTypes :Array = null, completeType :String = null) { if (errorTypes == null) { errorTypes = [ ErrorEvent.ERROR, AsyncErrorEvent.ASYNC_ERROR, IOErrorEvent.IO_ERROR, SecurityErrorEvent.SECURITY_ERROR ]; } if (completeType == null) { completeType = Event.COMPLETE; } _complete = completeCallback; _forEach = forEach; var endCheckKey :* = null; if (sources is Array) { _result = new Array(); } else if (sources is Dictionary) { _result = new Dictionary(); } else { _result = new Object(); if (!Util.isPlainObject(sources)) { // stash the singleton source sources = { singleton_key: sources }; endCheckKey = "singleton_key"; } } for (var key :* in sources) { var sourceVal :Object = sources[key]; var val :Object; try { val = (sourceVal is Array) ? generatorFn.apply(null, sourceVal as Array) : generatorFn(sourceVal); } catch (err :Error) { val = err; } _result[key] = val; if ((val is IEventDispatcher) && (isCompleteCheckFn == null || !val[isCompleteCheckFn]())) { var ed :IEventDispatcher = IEventDispatcher(val); _remaining++; _targetsToKeys[ed] = key; ed.addEventListener(completeType, handleComplete); for each (var type :String in errorTypes) { ed.addEventListener(type, handleError); } } else if (_forEach) { checkReport(key); } } if (!_forEach) { checkReport(endCheckKey); } // if we're not done at this point, keep a reference to this loader if (_remaining > 0) { _activeMultiLoaders[this] = true; } } protected function handleError (event :ErrorEvent) :void { _result[_targetsToKeys[event.target]] = new Error(event.text) // , event.errorID); ??? handleComplete(event); // the rest is the same as complete } protected function handleComplete (event :Event) :void { _remaining--; checkReport(_targetsToKeys[event.target]); } protected function checkReport (key :*) :void { if (!_forEach && _remaining > 0) { return; } var thisResult :Object = (_forEach || (key === "singleton_key")) ? _result[key] : _result; try { _complete(thisResult); } catch (err :Error) { trace("MultiLoader: Error calling completeCallback [result=" + thisResult + "]."); trace("Cause: " + err.getStackTrace()); } if (_forEach) { delete _result[key]; // free the loaded object to assist gc } // If we're all done, remove the static reference to this loader. // Note that this could be called in for-each mode if we haven't yet started to load // something asynchronously but have come across an Error or an already-completed load. // That's ok, as this will just end up deleting a reference that doesn't exist, and if // necessary the reference will still be added at the end of the constructor. if (_remaining == 0) { delete _activeMultiLoaders[this]; } } /** * Utility method used in this class. */ protected static function processProperty ( retval :Object, testClass :Class, prop :String) :Object { if (retval is testClass) { retval = retval[prop]; } else { for (var key :* in retval) { var o :Object = retval[key]; if (o is testClass) { retval[key] = o[prop]; } // else keep it the same } } return retval; } protected var _complete :Function; protected var _result :Object; protected var _targetsToKeys :Dictionary = new Dictionary(true); protected var _forEach :Boolean; protected var _remaining :int = 0; protected static const _activeMultiLoaders :Dictionary = new Dictionary(); } }
// // $Id$ package com.threerings.util { import flash.display.Loader; import flash.display.LoaderInfo; import flash.events.AsyncErrorEvent; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IEventDispatcher; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.system.ApplicationDomain; import flash.system.LoaderContext; import flash.utils.ByteArray; import flash.utils.Dictionary; /** * Easy loader for many things, including managing multiple downloads. * More documentation coming. */ public class MultiLoader { /** * Load one or more sources and return DisplayObjects. * * @param sources an Array, Dictionary, or Object containing sources as values, or a single * source value. The sources may be Strings (representing urls), URLRequests, ByteArrays, * or a Class that can be instantiated to become a URLRequest or ByteArray. Note that * the format of your sources Object dictates the format of the return Object. * @param completeCallback the function to call when complete. The signature should be: * <code>function (value :Object) :void</code>. Note that the structure of the return Object * is dictated by the sources parameter. If you pass in an Array, you get your results * in an Array. If you use a Dictionary or Object, the results will be returned as the same, * with the same keys used in sources now pointing to the results. If your sources parameter * was just a single source (like a String) then the result will just be a single result, * like a DisplayObject. Each result will be a DisplayObject or an Error * describing the problem. * @param forEach if true, each value or error will be returned as soon as possible. The values * or errors will be returned directly to the completeCallback. Any keys are lost, so you * probably only want to use this with an Array sources. * @param appDom the ApplicationDomain in which to load the contents, or null to specify * that it should load in a child of the current ApplicationDomain. * * @example Load one embed, add it as a child. * <listing version="3.0"> * MultiLoader.getContents(EMBED_CONSTANT, addChild); * </listing> * * @example Load 3 embeds, add them as children. * <listing version="3.0"> * MultiLoader.getContents([EMBED1, EMBED2, EMBED3], addChild, true); * </listing> * * @example Load multiple URLs, have the contents returned to the result function one at * a time. * <listing version="3.0"> * function handleComplete (result :Object) :void { * // process a result here. Result may be a DisplayObject or an Error. * }; * * var obj :Object = { * key1: "http://somehost.com/someImage.gif", * key2: "http://somehost.com/someOtherImage.gif" * }; * * MultiLoader.getContents(obj, handleComplete, true); * </listing> * * @example Load 3 embeds, wait to handle them until they're all loaded. * <listing version="3.0"> * function handleComplete (results :Array) :void { * // process results here * }; * * MultiLoader.getContents([EMBED1, EMBED2, EMBED3], handleComplete); * </listing> */ public static function getContents ( sources :Object, completeCallback :Function, forEach :Boolean = false, appDom :ApplicationDomain = null) :void { var complete :Function = function (retval :Object) :void { completeCallback(processProperty(retval, Loader, "content")); }; getLoaders(sources, complete, forEach, appDom); } /** * Exactly like getContents() only it returns the Loader objects rather than their contents. * * @example Advanced usage: Loading classes. * <listing version="3.0"> * // A holder for new classes, created as a child of the system domain. * var appDom :ApplicationDomain = new ApplicationDomain(null); * <br/> * function handleComplete (results :Object) :void { * // now we can retrieve classes * var clazz :Class = appDom.getDefinition("com.package.SomeClass") as Class; * } * <br/> * // load all the classes contained in the specified sources * MultiLoader.getLoaders([EMBED, "http://site.com/pack.swf"], handleComplete, false, appDom); * <br/> * [Embed(source="resource.swf", mimeType="application/octet-stream")] * private static const EMBED :Class; * </listing> * * @see getContents() */ public static function getLoaders ( sources :Object, completeCallback :Function, forEach :Boolean = false, appDom :ApplicationDomain = null) :void { var generator :Function = function (source :*) :Object { // first transform common sources to their more useful nature if (source is String) { source = new URLRequest(String(source)); } else if (source is Class) { // it's probably a ByteArray from an Embed, but don't cast it source = new (source as Class)(); } var l :Loader = new Loader(); var lc :LoaderContext = new LoaderContext(false, appDom); // now we only need handle the two cases if (source is URLRequest) { l.load(URLRequest(source), lc); } else if (source is ByteArray) { l.loadBytes(ByteArray(source), lc); } else { return new Error("Unknown source: " + source); } return l.contentLoaderInfo; }; var complete :Function = function (retval :Object) :void { completeCallback(processProperty(retval, LoaderInfo, "loader")); }; new MultiLoader(sources, complete, generator, forEach); } /** * Coordinate loading some asynchronous objects. * * @param sources An Array, Dictionary, or Object of sources, or just a single source. * @param completeCallack the function to call when complete. * @param generatorFunciton a function to call to generate the IEventDispatchers, or * null if the source values are already ready to go. * @param forEach whether to call the completeCallback for each source, or all-at-once at * the end. If forEach is used, keys will never be returned. * @param isCompleteCheckFn a function to attempt to call on the dispatcher to see if * it's already complete after generation. * @param errorTypes an Array of event types that will be dispatched by the loader. * If unspecifed, all the normal error event types are used. * @param completeType, the event complete type. If unspecifed @default Event.COMPLETE. */ public function MultiLoader ( sources :Object, completeCallback :Function, generatorFn :Function = null, forEach :Boolean = false, isCompleteCheckFn :String = null, errorTypes :Array = null, completeType :String = null) { if (errorTypes == null) { errorTypes = [ ErrorEvent.ERROR, AsyncErrorEvent.ASYNC_ERROR, IOErrorEvent.IO_ERROR, SecurityErrorEvent.SECURITY_ERROR ]; } if (completeType == null) { completeType = Event.COMPLETE; } _complete = completeCallback; _forEach = forEach; var endCheckKey :* = null; if (sources is Array) { _result = new Array(); } else if (sources is Dictionary) { _result = new Dictionary(); } else { _result = new Object(); if (!Util.isPlainObject(sources)) { // stash the singleton source sources = { singleton_key: sources }; endCheckKey = "singleton_key"; } } for (var key :* in sources) { var val :Object = sources[key]; if (generatorFn != null) { try { val = (val is Array) ? generatorFn.apply(null, val as Array) : generatorFn(val); } catch (err :Error) { val = err; } } _result[key] = val; if ((val is IEventDispatcher) && (isCompleteCheckFn == null || !val[isCompleteCheckFn]())) { var ed :IEventDispatcher = IEventDispatcher(val); _remaining++; _targetsToKeys[ed] = key; ed.addEventListener(completeType, handleComplete); for each (var type :String in errorTypes) { ed.addEventListener(type, handleError); } } else if (_forEach) { checkReport(key); } } if (!_forEach) { checkReport(endCheckKey); } // if we're not done at this point, keep a reference to this loader if (_remaining > 0) { _activeMultiLoaders[this] = true; } } protected function handleError (event :ErrorEvent) :void { _result[_targetsToKeys[event.target]] = new Error(event.text) // , event.errorID); ??? handleComplete(event); // the rest is the same as complete } protected function handleComplete (event :Event) :void { _remaining--; checkReport(_targetsToKeys[event.target]); } protected function checkReport (key :*) :void { if (!_forEach && _remaining > 0) { return; } var thisResult :Object = (_forEach || (key === "singleton_key")) ? _result[key] : _result; try { _complete(thisResult); } catch (err :Error) { trace("MultiLoader: Error calling completeCallback [result=" + thisResult + "]."); trace("Cause: " + err.getStackTrace()); } if (_forEach) { delete _result[key]; // free the loaded object to assist gc } // If we're all done, remove the static reference to this loader. // Note that this could be called in for-each mode if we haven't yet started to load // something asynchronously but have come across an Error or an already-completed load. // That's ok, as this will just end up deleting a reference that doesn't exist, and if // necessary the reference will still be added at the end of the constructor. if (_remaining == 0) { delete _activeMultiLoaders[this]; } } /** * Utility method used in this class. */ protected static function processProperty ( retval :Object, testClass :Class, prop :String) :Object { if (retval is testClass) { retval = retval[prop]; } else { for (var key :* in retval) { var o :Object = retval[key]; if (o is testClass) { retval[key] = o[prop]; } // else keep it the same } } return retval; } protected var _complete :Function; protected var _result :Object; protected var _targetsToKeys :Dictionary = new Dictionary(true); protected var _forEach :Boolean; protected var _remaining :int = 0; protected static const _activeMultiLoaders :Dictionary = new Dictionary(); } }
Swap the order of the generatorFn and callbackFn args. Made the generatorFn optional, in case the source values are already ready-to-go, although 99% of the time it's going to be better to use the generator function to get things ready to go because MultiLoader will take care of figuring out the sources structure.
Swap the order of the generatorFn and callbackFn args. Made the generatorFn optional, in case the source values are already ready-to-go, although 99% of the time it's going to be better to use the generator function to get things ready to go because MultiLoader will take care of figuring out the sources structure. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5022 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
f6b84b3e4fae4e8816b145e138f1556ae7e14dca
src/aerys/minko/scene/node/Scene.as
src/aerys/minko/scene/node/Scene.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.Effect; import aerys.minko.render.Viewport; import aerys.minko.scene.controller.scene.RenderingController; import aerys.minko.scene.node.camera.AbstractCamera; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import flash.display.BitmapData; import flash.utils.getTimer; /** * Scene objects are the root of any 3D scene. * * @author Jean-Marc Le Roux * */ public final class Scene extends Group { use namespace minko_scene; minko_scene var _camera : AbstractCamera; private var _renderingCtrl : RenderingController; private var _properties : DataProvider; private var _bindings : DataBindings; private var _enterFrame : Signal; private var _exitFrame : Signal; public function get activeCamera() : AbstractCamera { return _camera; } public function get numPasses() : uint { return _renderingCtrl.numPasses; } public function get numTriangles() : uint { return _renderingCtrl.numTriangles; } public function get postProcessingEffect() : Effect { return _renderingCtrl.postProcessingEffect; } public function set postProcessingEffect(value : Effect) : void { _renderingCtrl.postProcessingEffect = value; } public function get postProcessingProperties() : DataProvider { return _renderingCtrl.postProcessingProperties; } public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get bindings() : DataBindings { return _bindings; } /** * The signal executed when the viewport is about to start rendering a frame. * Callback functions for this signal should accept the following arguments: * <ul> * <li>viewport : Viewport, the viewport who starts rendering the frame</li> * </ul> * @return * */ public function get enterFrame() : Signal { return _enterFrame; } /** * The signal executed when the viewport is done rendering a frame. * Callback functions for this signal should accept the following arguments: * <ul> * <li>viewport : Viewport, the viewport who just finished rendering the frame</li> * </ul> * @return * */ public function get exitFrame() : Signal { return _exitFrame; } public function Scene(...children) { super(); } override protected function initialize() : void { _bindings = new DataBindings(this); this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE); super.initialize(); } override protected function initializeSignals() : void { super.initializeSignals(); _enterFrame = new Signal('Scene.enterFrame'); _exitFrame = new Signal('Scene.exitFrame'); } override protected function initializeSignalHandlers() : void { added.add(addedHandler); } override protected function initializeContollers() : void { super.initializeContollers(); _renderingCtrl = new RenderingController(); addController(_renderingCtrl); } public function render(viewport : Viewport, destination : BitmapData = null) : void { _enterFrame.execute(this, viewport, destination, getTimer()); _exitFrame.execute(this, viewport, destination, getTimer()); } private function addedHandler(child : ISceneNode, parent : Group) : void { throw new Error(); } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.Effect; import aerys.minko.render.Viewport; import aerys.minko.scene.controller.scene.RenderingController; import aerys.minko.scene.node.camera.AbstractCamera; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import flash.display.BitmapData; import flash.utils.getTimer; /** * Scene objects are the root of any 3D scene. * * @author Jean-Marc Le Roux * */ public final class Scene extends Group { use namespace minko_scene; minko_scene var _camera : AbstractCamera; private var _renderingCtrl : RenderingController; private var _properties : DataProvider; private var _bindings : DataBindings; private var _enterFrame : Signal; private var _exitFrame : Signal; public function get activeCamera() : AbstractCamera { return _camera; } public function get numPasses() : uint { return _renderingCtrl.numPasses; } public function get numTriangles() : uint { return _renderingCtrl.numTriangles; } public function get postProcessingEffect() : Effect { return _renderingCtrl.postProcessingEffect; } public function set postProcessingEffect(value : Effect) : void { _renderingCtrl.postProcessingEffect = value; } public function get postProcessingProperties() : DataProvider { return _renderingCtrl.postProcessingProperties; } public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get bindings() : DataBindings { return _bindings; } /** * The signal executed when the viewport is about to start rendering a frame. * Callback functions for this signal should accept the following arguments: * <ul> * <li>viewport : Viewport, the viewport who starts rendering the frame</li> * </ul> * @return * */ public function get enterFrame() : Signal { return _enterFrame; } /** * The signal executed when the viewport is done rendering a frame. * Callback functions for this signal should accept the following arguments: * <ul> * <li>viewport : Viewport, the viewport who just finished rendering the frame</li> * </ul> * @return * */ public function get exitFrame() : Signal { return _exitFrame; } public function Scene(...children) { super(); } override protected function initialize() : void { _bindings = new DataBindings(this); this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE); super.initialize(); } override protected function initializeSignals() : void { super.initializeSignals(); _enterFrame = new Signal('Scene.enterFrame'); _exitFrame = new Signal('Scene.exitFrame'); } override protected function initializeSignalHandlers() : void { super.initializeSignalHandlers(); added.add(addedHandler); } override protected function initializeContollers() : void { super.initializeContollers(); _renderingCtrl = new RenderingController(); addController(_renderingCtrl); } public function render(viewport : Viewport, destination : BitmapData = null) : void { _enterFrame.execute(this, viewport, destination, getTimer()); _exitFrame.execute(this, viewport, destination, getTimer()); } private function addedHandler(child : ISceneNode, parent : Group) : void { throw new Error(); } } }
fix missing call to super.initializeSignalHandlers()
fix missing call to super.initializeSignalHandlers()
ActionScript
mit
aerys/minko-as3
1fe7d00e4a737c12b1a7f2f80118a92d7708c2f6
src/aerys/minko/type/loader/SceneLoader.as
src/aerys/minko/type/loader/SceneLoader.as
package aerys.minko.type.loader { import flash.events.Event; import flash.events.ProgressEvent; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.setTimeout; import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.Signal; import aerys.minko.type.loader.parser.IParser; import aerys.minko.type.loader.parser.ParserOptions; public class SceneLoader implements ILoader { private static const REGISTERED_PARSERS : Vector.<Class> = new <Class>[]; private static const STATE_IDLE : uint = 0; private static const STATE_LOADING : uint = 1; private static const STATE_PARSING : uint = 2; private static const STATE_COMPLETE : uint = 3; private var _currentState : int; private var _progress : Signal; private var _complete : Signal; private var _error : Signal; private var _data : ISceneNode; private var _parser : IParser; private var _numDependencies : uint; private var _dependencies : Vector.<ILoader>; private var _parserOptions : ParserOptions; private var _currentProgress : Number; private var _currentProgressChanged : Boolean; private var _isComplete : Boolean; public function get error() : Signal { return _error; } public function get progress() : Signal { return _progress; } public function get complete() : Signal { return _complete; } public function get isComplete() : Boolean { return _isComplete; } public function get data() : ISceneNode { return _data; } public static function registerParser(parserClass : Class) : void { if (REGISTERED_PARSERS.indexOf(parserClass) != -1) return; if (!(new parserClass(new ParserOptions()) is IParser)) throw new Error('Parsers must implement the IParser interface.'); REGISTERED_PARSERS.push(parserClass); } public function SceneLoader(parserOptions : ParserOptions = null) { _currentState = STATE_IDLE; _error = new Signal('SceneLoader.error'); _progress = new Signal('SceneLoader.progress'); _complete = new Signal('SceneLoader.complete'); _data = null; _isComplete = false; _parserOptions = parserOptions || new ParserOptions(); } public function load(urlRequest : URLRequest) : void { if (_currentState != STATE_IDLE) throw new Error('This controller is already loading an asset.'); _currentState = STATE_LOADING; var urlLoader : URLLoader = new URLLoader(); urlLoader.dataFormat = URLLoaderDataFormat.BINARY; urlLoader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler); urlLoader.addEventListener(Event.COMPLETE, loadCompleteHandler); urlLoader.load(urlRequest); } private function loadProgressHandler(e : ProgressEvent) : void { _progress.execute(this, 0.5 * e.bytesLoaded / e.bytesTotal); } private function loadCompleteHandler(e : Event) : void { _currentState = STATE_IDLE; loadBytes(URLLoader(e.currentTarget).data); } public function loadClass(classObject : Class) : void { loadBytes(new classObject()); } public function loadBytes(byteArray : ByteArray) : void { var startPosition : uint = byteArray.position; if (_currentState != STATE_IDLE) throw new Error('This loader is already loading an asset.'); _currentState = STATE_PARSING; _progress.execute(this, 0.5); if (_parserOptions != null && _parserOptions.parser != null) { _parser = new (_parserOptions.parser)(_parserOptions); if (!_parser.isParsable(byteArray)) throw new Error('Invalid datatype for this parser.'); } else { // search a parser by testing registered parsers. var numRegisteredParser : uint = REGISTERED_PARSERS.length; for (var parserId : uint = 0; parserId < numRegisteredParser; ++parserId) { _parser = new REGISTERED_PARSERS[parserId](_parserOptions); byteArray.position = startPosition; if (_parser.isParsable(byteArray)) break; } if (parserId == numRegisteredParser) throw new Error('No parser could be found for this datatype.'); } byteArray.position = startPosition; _dependencies = _parser.getDependencies(byteArray); _numDependencies = 0; if (_dependencies != null) for each (var dependency : ILoader in _dependencies) if (!dependency.isComplete) { dependency.error.add(decrementDependencyCounter); dependency.complete.add(decrementDependencyCounter); _numDependencies++; } if (_numDependencies == 0) parse(); } private function decrementDependencyCounter(...args) : void { --_numDependencies; if (_numDependencies == 0) parse(); } private function parse() : void { _parser.error.add(parseErrorHandler); _parser.progress.add(parseProgressHandler); _parser.complete.add(parseCompleteHandler); _parser.parse(); } private function parseErrorHandler(parser : IParser) : void { _isComplete = true; } private function parseProgressHandler(parser : IParser, progress : Number) : void { _progress.execute(this, 0.5 * (1 + progress)); } private function parseCompleteHandler(parser : IParser, loadedData : ISceneNode) : void { _isComplete = true; _data = loadedData; // call later to make sure the loading is always seen as asynchronous setTimeout(callLaterComplete, 0, loadedData); } private function callLaterComplete(loadedData : ISceneNode) : void { _complete.execute(this, loadedData); } } }
package aerys.minko.type.loader { import flash.events.Event; import flash.events.ProgressEvent; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.setTimeout; import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.Signal; import aerys.minko.type.loader.parser.IParser; import aerys.minko.type.loader.parser.ParserOptions; public class SceneLoader implements ILoader { private static const REGISTERED_PARSERS : Vector.<Class> = new <Class>[]; private static const STATE_IDLE : uint = 0; private static const STATE_LOADING : uint = 1; private static const STATE_PARSING : uint = 2; private static const STATE_COMPLETE : uint = 3; private var _currentState : int; private var _progress : Signal; private var _complete : Signal; private var _error : Signal; private var _data : ISceneNode; private var _parser : IParser; private var _numDependencies : uint; private var _dependencies : Vector.<ILoader>; private var _parserOptions : ParserOptions; private var _currentProgress : Number; private var _currentProgressChanged : Boolean; private var _isComplete : Boolean; public function get error() : Signal { return _error; } public function get progress() : Signal { return _progress; } public function get complete() : Signal { return _complete; } public function get isComplete() : Boolean { return _isComplete; } public function get data() : ISceneNode { return _data; } public static function registerParser(parserClass : Class) : void { if (REGISTERED_PARSERS.indexOf(parserClass) != -1) return; if (!(new parserClass(new ParserOptions()) is IParser)) throw new Error('Parsers must implement the IParser interface.'); REGISTERED_PARSERS.push(parserClass); } public function SceneLoader(parserOptions : ParserOptions = null) { _currentState = STATE_IDLE; _error = new Signal('SceneLoader.error'); _progress = new Signal('SceneLoader.progress'); _complete = new Signal('SceneLoader.complete'); _data = null; _isComplete = false; _parserOptions = parserOptions || new ParserOptions(); } public function load(urlRequest : URLRequest) : void { if (_currentState != STATE_IDLE) throw new Error('This controller is already loading an asset.'); _currentState = STATE_LOADING; var urlLoader : URLLoader = new URLLoader(); urlLoader.dataFormat = URLLoaderDataFormat.BINARY; urlLoader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler); urlLoader.addEventListener(Event.COMPLETE, loadCompleteHandler); urlLoader.load(urlRequest); } private function loadProgressHandler(e : ProgressEvent) : void { _progress.execute(this, 0.5 * e.bytesLoaded / e.bytesTotal); } private function loadCompleteHandler(e : Event) : void { _currentState = STATE_IDLE; loadBytes(URLLoader(e.currentTarget).data); } public function loadClass(classObject : Class) : void { loadBytes(new classObject()); } public function loadBytes(byteArray : ByteArray) : void { var startPosition : uint = byteArray.position; if (_currentState != STATE_IDLE) throw new Error('This loader is already loading an asset.'); _currentState = STATE_PARSING; _progress.execute(this, 0.5); if (_parserOptions != null && _parserOptions.parser != null) { _parser = new (_parserOptions.parser)(_parserOptions); if (!_parser.isParsable(byteArray)) throw new Error('Invalid datatype for this parser.'); } else { // search a parser by testing registered parsers. var numRegisteredParser : uint = REGISTERED_PARSERS.length; for (var parserId : uint = 0; parserId < numRegisteredParser; ++parserId) { _parser = new REGISTERED_PARSERS[parserId](_parserOptions); byteArray.position = startPosition; if (_parser.isParsable(byteArray)) break; } if (parserId == numRegisteredParser) throw new Error('No parser could be found for this datatype.'); } byteArray.position = startPosition; _dependencies = _parser.getDependencies(byteArray); _numDependencies = 0; if (_dependencies != null) for each (var dependency : ILoader in _dependencies) if (!dependency.isComplete) { dependency.error.add(decrementDependencyCounter); dependency.complete.add(decrementDependencyCounter); _numDependencies++; } if (_numDependencies == 0) parse(); } private function decrementDependencyCounter(...args) : void { --_numDependencies; if (_numDependencies == 0) parse(); } private function parse() : void { _parser.error.add(parseErrorHandler); _parser.progress.add(parseProgressHandler); _parser.complete.add(parseCompleteHandler); _parser.parse(); } private function parseErrorHandler(parser : IParser) : void { _isComplete = true; _parser = null; } private function parseProgressHandler(parser : IParser, progress : Number) : void { _progress.execute(this, 0.5 * (1 + progress)); } private function parseCompleteHandler(parser : IParser, loadedData : ISceneNode) : void { _isComplete = true; _data = loadedData; _parser = null; // call later to make sure the loading is always seen as asynchronous setTimeout(callLaterComplete, 0, loadedData); } private function callLaterComplete(loadedData : ISceneNode) : void { _complete.execute(this, loadedData); } } }
set SceneLoader._parser = null when loading fails/completes
set SceneLoader._parser = null when loading fails/completes
ActionScript
mit
aerys/minko-as3
09936a9764430c02f0fc8438f8c957b81b37c8e9
exporter/src/main/as/flump/export/DisplayCreator.as
exporter/src/main/as/flump/export/DisplayCreator.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.BitmapData; import flash.utils.Dictionary; import flump.SwfTexture; import flump.display.Movie; import flump.mold.KeyframeMold; import flump.mold.LayerMold; import flump.mold.MovieMold; import flump.xfl.XflLibrary; import flump.xfl.XflTexture; import starling.display.DisplayObject; import starling.display.Image; import starling.display.Sprite; import starling.textures.Texture; public class DisplayCreator { public function DisplayCreator (lib :XflLibrary) { _lib = lib; } public function loadMovie (name :String) :Movie { return new Movie(_lib.getLibrary(name, MovieMold), _lib.frameRate, loadId); } public function getMemoryUsage (name :String, subtex :Dictionary = null) :int { if (name == null) return 0; if (FLIPBOOK_TEXTURE.exec(name) != null || _lib.getLibrary(name) is XflTexture) { const tex :Texture = getStarlingTexture(name); const usage :int = 4 * tex.width * tex.height; if (subtex != null && !subtex.hasOwnProperty(name)) { subtex[name] = usage; } return usage; } const xflMovie :MovieMold = _lib.getLibrary(name, MovieMold); if (subtex == null) subtex = new Dictionary(); for each (var layer :LayerMold in xflMovie.layers) { for each (var kf :KeyframeMold in layer.keyframes) { getMemoryUsage(kf.id, subtex); } } var subtexUsage :int = 0; for (var texName :String in subtex) subtexUsage += subtex[texName]; return subtexUsage; } /** Gets the maximum number of pixels drawn in a single frame by the given id. If it's * a texture, that's just the number of pixels in the texture. For a movie, it's the frame with * the largest set of textures present in its keyframe. For movies inside movies, the frame * drawn usage is the maximum that movie can draw. We're trying to get the worst case here. */ public function getMaxDrawn (name :String) :int { if (name == null) return 0; if (FLIPBOOK_TEXTURE.exec(name) != null || _lib.getLibrary(name) is XflTexture) { const tex :Texture = getStarlingTexture(name); return tex.width * tex.height; } const xflMovie :MovieMold = _lib.getLibrary(name, MovieMold); var maxDrawn :int = 0; for (var ii :int = 0; ii < xflMovie.frames; ii++) { var drawn :int = 0; for each (var layer :LayerMold in xflMovie.layers) { var kf :KeyframeMold = layer.keyframeForFrame(ii); if (kf.visible) drawn += getMaxDrawn(kf.id); } maxDrawn = Math.max(maxDrawn, drawn); } return maxDrawn; } private function getStarlingTexture (name :String) :Texture { if (!_textures.hasOwnProperty(name)) { const match :Object = FLIPBOOK_TEXTURE.exec(name); var packed :SwfTexture; if (match == null) { packed = SwfTexture.fromTexture(_lib.swf, _lib.getLibrary(name, XflTexture)); } else { const movieName :String = match[1]; const frame :int = int(match[2]); const movie :MovieMold = _lib.getLibrary(movieName, MovieMold); if (!movie.flipbook) { throw new Error("Got non-flipbook movie for flipbook texture '" + name + "'"); } packed = SwfTexture.fromFlipbook(_lib.swf, movie, frame); } _textures[name] = Texture.fromBitmapData(packed.toBitmapData()); _textureOffsets[name] = packed.offset; } return _textures[name]; } public function loadTexture (name :String) :DisplayObject { const image :Image = new Image(getStarlingTexture(name)); image.x = _textureOffsets[name].x; image.y = _textureOffsets[name].y; const holder :Sprite = new Sprite(); holder.addChild(image); return holder; } public function loadId (id :String) :DisplayObject { const match :Object = FLIPBOOK_TEXTURE.exec(id); if (match != null) return loadTexture(id); const libraryItem :* = _lib.getLibrary(id); if (libraryItem is XflTexture) return loadTexture(XflTexture(libraryItem).libraryItem); else return loadMovie(MovieMold(libraryItem).libraryItem); } protected const _textures :Dictionary = new Dictionary();// library name to Texture protected const _textureOffsets :Dictionary = new Dictionary();// library name to Point protected var _lib :XflLibrary; protected static const FLIPBOOK_TEXTURE :RegExp = /^(.*)_flipbook_(\d+)$/; } }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.utils.Dictionary; import flump.SwfTexture; import flump.display.Movie; import flump.mold.KeyframeMold; import flump.mold.LayerMold; import flump.mold.MovieMold; import flump.xfl.XflLibrary; import flump.xfl.XflTexture; import starling.display.DisplayObject; import starling.display.Image; import starling.display.Sprite; import starling.textures.Texture; import com.threerings.util.Map; import com.threerings.util.Maps; public class DisplayCreator { public function DisplayCreator (lib :XflLibrary) { _lib = lib; } public function loadMovie (name :String) :Movie { return new Movie(_lib.getLibrary(name, MovieMold), _lib.frameRate, loadId); } public function getMemoryUsage (name :String, subtex :Dictionary = null) :int { if (name == null) return 0; if (FLIPBOOK_TEXTURE.exec(name) != null || _lib.getLibrary(name) is XflTexture) { const tex :Texture = getStarlingTexture(name); const usage :int = 4 * tex.width * tex.height; if (subtex != null && !subtex.hasOwnProperty(name)) { subtex[name] = usage; } return usage; } const xflMovie :MovieMold = _lib.getLibrary(name, MovieMold); if (subtex == null) subtex = new Dictionary(); for each (var layer :LayerMold in xflMovie.layers) { for each (var kf :KeyframeMold in layer.keyframes) { getMemoryUsage(kf.id, subtex); } } var subtexUsage :int = 0; for (var texName :String in subtex) subtexUsage += subtex[texName]; return subtexUsage; } /** Gets the maximum number of pixels drawn in a single frame by the given id. If it's * a texture, that's just the number of pixels in the texture. For a movie, it's the frame with * the largest set of textures present in its keyframe. For movies inside movies, the frame * drawn usage is the maximum that movie can draw. We're trying to get the worst case here. */ public function getMaxDrawn (name :String) :int { if (name == null) return 0; if (FLIPBOOK_TEXTURE.exec(name) != null || _lib.getLibrary(name) is XflTexture) { const tex :Texture = getStarlingTexture(name); return tex.width * tex.height; } const xflMovie :MovieMold = _lib.getLibrary(name, MovieMold); var maxDrawn :int = 0; var calculatedKeyframes :Map = Maps.newMapOf(KeyframeMold); for (var ii :int = 0; ii < xflMovie.frames; ii++) { var drawn :int = 0; for each (var layer :LayerMold in xflMovie.layers) { var kf :KeyframeMold = layer.keyframeForFrame(ii); if (kf.visible) { if (!calculatedKeyframes.containsKey(kf)) { calculatedKeyframes.put(kf, getMaxDrawn(kf.id)); } drawn += calculatedKeyframes.get(kf); } } maxDrawn = Math.max(maxDrawn, drawn); } return maxDrawn; } private function getStarlingTexture (name :String) :Texture { if (!_textures.hasOwnProperty(name)) { const match :Object = FLIPBOOK_TEXTURE.exec(name); var packed :SwfTexture; if (match == null) { packed = SwfTexture.fromTexture(_lib.swf, _lib.getLibrary(name, XflTexture)); } else { const movieName :String = match[1]; const frame :int = int(match[2]); const movie :MovieMold = _lib.getLibrary(movieName, MovieMold); if (!movie.flipbook) { throw new Error("Got non-flipbook movie for flipbook texture '" + name + "'"); } packed = SwfTexture.fromFlipbook(_lib.swf, movie, frame); } _textures[name] = Texture.fromBitmapData(packed.toBitmapData()); _textureOffsets[name] = packed.offset; } return _textures[name]; } public function loadTexture (name :String) :DisplayObject { const image :Image = new Image(getStarlingTexture(name)); image.x = _textureOffsets[name].x; image.y = _textureOffsets[name].y; const holder :Sprite = new Sprite(); holder.addChild(image); return holder; } public function loadId (id :String) :DisplayObject { const match :Object = FLIPBOOK_TEXTURE.exec(id); if (match != null) return loadTexture(id); const libraryItem :* = _lib.getLibrary(id); if (libraryItem is XflTexture) return loadTexture(XflTexture(libraryItem).libraryItem); else return loadMovie(MovieMold(libraryItem).libraryItem); } protected const _textures :Dictionary = new Dictionary();// library name to Texture protected const _textureOffsets :Dictionary = new Dictionary();// library name to Point protected var _lib :XflLibrary; protected static const FLIPBOOK_TEXTURE :RegExp = /^(.*)_flipbook_(\d+)$/; } }
Speed up getMaxDrawn by caching keyframe computations
Speed up getMaxDrawn by caching keyframe computations A deeply nested movie in one of Jon's flas was causing a single keyframe calculation to run literally millions of times, which made Flash just hang forever.
ActionScript
mit
mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump
2eb10b30c86cb24d9b26f30f7a5570f9c7dd71d7
examples/FlexJSStore/src/ProductJSONItemConverter.as
examples/FlexJSStore/src/ProductJSONItemConverter.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 org.apache.flex.net.JSONItemConverter; import samples.flexstore.Product; public class ProductJSONItemConverter extends JSONItemConverter { public function ProductJSONItemConverter() { super(); } override public function convertItem(data:String):Object { var obj:Object = super.convertItem(data); var product:Product = new Product(); for (var p:String in obj) product[p] = obj[p]; return product; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.net.JSONItemConverter; import samples.flexstore.Product; public class ProductJSONItemConverter extends JSONItemConverter { public function ProductJSONItemConverter() { super(); } override public function convertItem(data:String):Object { var obj:Object = super.convertItem(data); var product:Product = new Product(); for (var p:String in obj) setProperty(product, p, obj[p]); return product; } } }
use setProperty (for now at least)
use setProperty (for now at least)
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
f031924f4df4caa8eaade76ef3a9693821f399dd
dolly-framework/src/main/actionscript/dolly/Copier.as
dolly-framework/src/main/actionscript/dolly/Copier.as
package dolly { import dolly.core.dolly_internal; import dolly.core.metadata.MetadataName; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.Field; import org.as3commons.reflect.IMetadataContainer; import org.as3commons.reflect.Type; import org.as3commons.reflect.Variable; use namespace dolly_internal; public class Copier { private static function isVariableCopyable(variable:Variable, skipMetadataChecking:Boolean = true):Boolean { return !variable.isStatic && (skipMetadataChecking || variable.hasMetadata(MetadataName.COPYABLE)); } private static function isAccessorCopyable(accessor:Accessor, skipMetadataChecking:Boolean = true):Boolean { return !accessor.isStatic && accessor.isReadable() && accessor.isWriteable() && (skipMetadataChecking || accessor.hasMetadata(MetadataName.COPYABLE)); } dolly_internal static function findCopyableFieldsForType(type:Type):Vector.<Field> { const result:Vector.<Field> = new Vector.<Field>(); var variable:Variable; var accessor:Accessor; const isClassCloneable:Boolean = type.hasMetadata(MetadataName.COPYABLE); if (isClassCloneable) { for each(variable in type.variables) { if (isVariableCopyable(variable)) { result.push(variable); } } for each(accessor in type.accessors) { if (isAccessorCopyable(accessor)) { result.push(accessor); } } } else { const metadataContainers:Array = type.getMetadataContainers(MetadataName.COPYABLE); for each(var metadataContainer:IMetadataContainer in metadataContainers) { if (metadataContainer is Variable) { variable = metadataContainer as Variable; if (isVariableCopyable(variable, false)) { result.push(variable); } } else if (metadataContainer is Accessor) { accessor = metadataContainer as Accessor; if (isAccessorCopyable(accessor, false)) { result.push(accessor); } } } } return result; } public static function copy(source:*):* { const type:Type = Type.forInstance(source); const copy:* = new (type.clazz)(); const fieldsToCopy:Vector.<Field> = findCopyableFieldsForType(type); var name:String; for each(var field:Field in fieldsToCopy) { name = field.name; copy[name] = source[name]; } return copy; } } }
package dolly { import dolly.core.dolly_internal; import dolly.core.metadata.MetadataName; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.Field; import org.as3commons.reflect.IMetadataContainer; import org.as3commons.reflect.Type; import org.as3commons.reflect.Variable; use namespace dolly_internal; public class Copier { private static function isVariableCopyable(variable:Variable, skipMetadataChecking:Boolean = true):Boolean { return !variable.isStatic && (skipMetadataChecking || variable.hasMetadata(MetadataName.COPYABLE)); } private static function isAccessorCopyable(accessor:Accessor, skipMetadataChecking:Boolean = true):Boolean { return !accessor.isStatic && accessor.isReadable() && accessor.isWriteable() && (skipMetadataChecking || accessor.hasMetadata(MetadataName.COPYABLE)); } dolly_internal static function findCopyableFieldsForType(type:Type):Vector.<Field> { const result:Vector.<Field> = new Vector.<Field>(); var variable:Variable; var accessor:Accessor; const isTypeCloneable:Boolean = type.hasMetadata(MetadataName.COPYABLE); if (isTypeCloneable) { for each(variable in type.variables) { if (isVariableCopyable(variable)) { result.push(variable); } } for each(accessor in type.accessors) { if (isAccessorCopyable(accessor)) { result.push(accessor); } } } else { const metadataContainers:Array = type.getMetadataContainers(MetadataName.COPYABLE); for each(var metadataContainer:IMetadataContainer in metadataContainers) { if (metadataContainer is Variable) { variable = metadataContainer as Variable; if (isVariableCopyable(variable, false)) { result.push(variable); } } else if (metadataContainer is Accessor) { accessor = metadataContainer as Accessor; if (isAccessorCopyable(accessor, false)) { result.push(accessor); } } } } return result; } public static function copy(source:*):* { const type:Type = Type.forInstance(source); const copy:* = new (type.clazz)(); const fieldsToCopy:Vector.<Field> = findCopyableFieldsForType(type); var name:String; for each(var field:Field in fieldsToCopy) { name = field.name; copy[name] = source[name]; } return copy; } } }
Rename local variable in method Copier.copy: isClassCloneable -> isTypeCloneable
Rename local variable in method Copier.copy: isClassCloneable -> isTypeCloneable
ActionScript
mit
Yarovoy/dolly
499abfcadef5ecb390811e4f475bbec7e96763d7
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
mrthuanvn/gaforflash,dli-iclinic/gaforflash,Vigmar/gaforflash,soumavachakraborty/gaforflash,drflash/gaforflash,jisobkim/gaforflash,Vigmar/gaforflash,Miyaru/gaforflash,jeremy-wischusen/gaforflash,Miyaru/gaforflash,jeremy-wischusen/gaforflash,drflash/gaforflash,mrthuanvn/gaforflash,dli-iclinic/gaforflash,DimaBaliakin/gaforflash,DimaBaliakin/gaforflash,soumavachakraborty/gaforflash,jisobkim/gaforflash
a030a137ba3e7fea31750924d737b4f208f1f482
src/com/merlinds/miracle_tool/models/ProjectModel.as
src/com/merlinds/miracle_tool/models/ProjectModel.as
/** * User: MerlinDS * Date: 13.07.2014 * Time: 1:51 */ package com.merlinds.miracle_tool.models { import com.merlinds.miracle_tool.events.EditorEvent; import com.merlinds.miracle_tool.models.vo.AnimationVO; import com.merlinds.miracle_tool.models.vo.ElementVO; import com.merlinds.miracle_tool.models.vo.SourceVO; import com.merlinds.unitls.Resolutions; import flash.filesystem.File; import flash.geom.Point; import org.robotlegs.mvcs.Actor; public class ProjectModel extends Actor { private var _name:String; /** * TODO: MF-29 Make normal comment for referenceSize * This size will be used for scaling of output texture. * It based of target screen resolution and resource screen resolution. * For example: IF reference size (width of screen of the fla. resource ) equals 2048 * and will be needed to publish project for 1024 screen width, than scale will be 0.5; **/ private var _referenceResolution:int; /** * Width of the target screen resolution */ private var _targetResolution:int; //TODO MF-28 Bound calculation for every polygon in texture private var _boundsOffset:int; private var _sources:Vector.<SourceVO>; private var _inProgress:int; private var _outputSize:int; private var _zoom:Number = 1; private var _sheetSize:Point; private var _saved:Boolean; //quick hack for animation saving public var tempFile:File; //storage for handling previous resolution sources private var _memorize:Object; //============================================================================== //{region PUBLIC METHODS public function ProjectModel(name:String, referenceResolution:int) { _name = name; _memorize = {}; _referenceResolution = referenceResolution; _targetResolution = referenceResolution; _sources = new <SourceVO>[]; _boundsOffset = 0; _sheetSize = new Point(); super(); } public function addSource(file:File):SourceVO { //revert to default sources and delete old backups this.revertBackupTo(_referenceResolution); _memorize = {}; //add new source var source:SourceVO; var n:int = _sources.length; for(var i:int = 0; i < n; i++){ source = _sources[i]; if(source.file.nativePath == file.nativePath)break; } if(i >= n){ source = new SourceVO(file); _sources.push(source); }else { //TODO MF-30 Update swf source if it already added } _inProgress = i; return source; } public function deleteAnimation(name:String):void { var source:SourceVO = this.selected; var animation:AnimationVO; var n:int = source.animations.length; for(var i:int = 0; i < n; i++){ animation = source.animations[i]; if(animation.name == name){ //delete founded animation source.animations.splice(i, 1); break; } animation = null; } //nulled object and add it back for future if(animation != null){ animation.added = false; source.animations.push(animation); } } //} endregion PUBLIC METHODS =================================================== //============================================================================== //{region PRIVATE\PROTECTED METHODS /** * Backup sources for current resolution */ private function prepareBackup():void { if(!_memorize.hasOwnProperty(_targetResolution.toString())){ _memorize[_targetResolution] = _sources.concat(); } } /** * get sources for resolution * @param resolution * @return True if backup was reverted. In other case returns false */ private function revertBackupTo(resolution:int):Boolean { var result:Boolean = _memorize.hasOwnProperty(resolution.toString()); if(result){ _sources = _memorize[resolution]; } return result; } /** * Scale sources for resolution */ private function scaleSources():void { //calculate scale var scale:Number = Resolutions.width(_targetResolution) / Resolutions.width(_referenceResolution); //clone default sources, that was first for the project and scale elements in it var defaultSources:Vector.<SourceVO> = _memorize[_referenceResolution.toString()]; var sources:Vector.<SourceVO> = new <SourceVO>[]; var n:int = sources.length = defaultSources.length; sources.fixed = true; for(var i:int = 0; i < n; i++){ //cloning //TODO do cloning of animation to publish command sources[i] = defaultSources[i].clone(scale); } //end sources.fixed = false; _sources = sources; } //} endregion PRIVATE\PROTECTED METHODS ======================================== //============================================================================== //{region EVENTS HANDLERS //} endregion EVENTS HANDLERS ================================================== //============================================================================== //{region GETTERS/SETTERS public function get name():String { return _name; } public function get sources():Vector.<SourceVO> { return _sources; } public function get sheetSize():Point { return _sheetSize; } public function get saved():Boolean { return _saved; } public function set saved(value:Boolean):void { _saved = value; } public function get selected():SourceVO { var source:SourceVO; var n:int = _sources.length; for(var i:int = 0; i < n; i++){ source = _sources[i]; if(source.selected)break; source = null; } return source; } public function get inProgress():SourceVO{ return _inProgress < 0 ? null : _sources[ _inProgress ]; } public function get boundsOffset():int { return _boundsOffset; } public function set boundsOffset(value:int):void { if(value != _boundsOffset){ _boundsOffset = value; if(_sources.length > 0){ this.dispatch(new EditorEvent(EditorEvent.UPDATE_PROJECT)); } } } public function get outputSize():int { return _outputSize; } public function set outputSize(value:int):void { _outputSize = value; _sheetSize.x = value; _sheetSize.y = value; } public function get zoom():Number { return _zoom; } public function set zoom(value:Number):void { _zoom = value; } //TODO MF-29 Make normal comment for referenceSize public function get referenceResolution():int { return _referenceResolution; } public function get targetResolution():int { return _targetResolution; } public function set targetResolution(value:int):void { if(value != _targetResolution){ this.prepareBackup(); _targetResolution = value; if(_sources.length > 0){ var reverted:Boolean = this.revertBackupTo(_targetResolution); if( !reverted ){ _outputSize = 1; this.scaleSources(); } this.dispatch(new EditorEvent(EditorEvent.UPDATE_PROJECT)); } } } //} endregion GETTERS/SETTERS ================================================== } }
/** * User: MerlinDS * Date: 13.07.2014 * Time: 1:51 */ package com.merlinds.miracle_tool.models { import com.merlinds.miracle_tool.events.EditorEvent; import com.merlinds.miracle_tool.models.vo.AnimationVO; import com.merlinds.miracle_tool.models.vo.ElementVO; import com.merlinds.miracle_tool.models.vo.SourceVO; import com.merlinds.unitls.Resolutions; import flash.filesystem.File; import flash.geom.Point; import org.robotlegs.mvcs.Actor; public class ProjectModel extends Actor { private var _name:String; /** * TODO: MF-29 Make normal comment for referenceSize * This size will be used for scaling of output texture. * It based of target screen resolution and resource screen resolution. * For example: IF reference size (width of screen of the fla. resource ) equals 2048 * and will be needed to publish project for 1024 screen width, than scale will be 0.5; **/ private var _referenceResolution:int; /** * Width of the target screen resolution */ private var _targetResolution:int; //TODO MF-28 Bound calculation for every polygon in texture private var _boundsOffset:int; private var _sources:Vector.<SourceVO>; private var _inProgress:int; private var _outputSize:int; private var _zoom:Number = 1; private var _sheetSize:Point; private var _saved:Boolean; //quick hack for animation saving public var tempFile:File; //storage for handling previous resolution sources private var _memorize:Object; //============================================================================== //{region PUBLIC METHODS public function ProjectModel(name:String, referenceResolution:int) { _name = name; _memorize = {}; _referenceResolution = referenceResolution; _targetResolution = referenceResolution; _sources = new <SourceVO>[]; _boundsOffset = 0; _sheetSize = new Point(); super(); } public function addSource(file:File):SourceVO { //revert to default sources and delete old backups this.revertBackupTo(_referenceResolution); _memorize = {}; //add new source var source:SourceVO; var n:int = _sources.length; for(var i:int = 0; i < n; i++){ source = _sources[i]; if(source.file.nativePath == file.nativePath)break; } if(i >= n){ source = new SourceVO(file); _sources.push(source); }else { //TODO MF-30 Update swf source if it already added } _inProgress = i; return source; } public function deleteAnimation(name:String):void { var source:SourceVO = this.selected; var animation:AnimationVO; var n:int = source.animations.length; for(var i:int = 0; i < n; i++){ animation = source.animations[i]; if(animation.name == name){ //delete founded animation source.animations.splice(i, 1); break; } animation = null; } //nulled object and add it back for future if(animation != null){ animation.added = false; source.animations.push(animation); } } //} endregion PUBLIC METHODS =================================================== //============================================================================== //{region PRIVATE\PROTECTED METHODS /** * Backup sources for current resolution */ private function prepareBackup():void { if(!_memorize.hasOwnProperty(_targetResolution.toString())){ _memorize[_targetResolution] = _sources.concat(); } } /** * get sources for resolution * @param resolution * @return True if backup was reverted. In other case returns false */ private function revertBackupTo(resolution:int):Boolean { var result:Boolean = _memorize.hasOwnProperty(resolution.toString()); if(result){ _sources = _memorize[resolution]; } return result; } /** * Scale sources for resolution */ private function scaleSources():void { //calculate scale var scale:Number = Resolutions.width(_targetResolution) / Resolutions.width(_referenceResolution); //clone default sources, that was first for the project and scale elements in it var defaultSources:Vector.<SourceVO> = _memorize[_referenceResolution.toString()]; var sources:Vector.<SourceVO> = new <SourceVO>[]; var n:int = sources.length = defaultSources.length; sources.fixed = true; for(var i:int = 0; i < n; i++){ //cloning sources[i] = defaultSources[i].clone(scale); } //end sources.fixed = false; _sources = sources; } //} endregion PRIVATE\PROTECTED METHODS ======================================== //============================================================================== //{region EVENTS HANDLERS //} endregion EVENTS HANDLERS ================================================== //============================================================================== //{region GETTERS/SETTERS public function get name():String { return _name; } public function get sources():Vector.<SourceVO> { return _sources; } public function get sheetSize():Point { return _sheetSize; } public function get saved():Boolean { return _saved; } public function set saved(value:Boolean):void { _saved = value; } public function get selected():SourceVO { var source:SourceVO; var n:int = _sources.length; for(var i:int = 0; i < n; i++){ source = _sources[i]; if(source.selected)break; source = null; } return source; } public function get inProgress():SourceVO{ return _inProgress < 0 ? null : _sources[ _inProgress ]; } public function get boundsOffset():int { return _boundsOffset; } public function set boundsOffset(value:int):void { if(value != _boundsOffset){ _boundsOffset = value; if(_sources.length > 0){ this.dispatch(new EditorEvent(EditorEvent.UPDATE_PROJECT)); } } } public function get outputSize():int { return _outputSize; } public function set outputSize(value:int):void { _outputSize = value; _sheetSize.x = value; _sheetSize.y = value; } public function get zoom():Number { return _zoom; } public function set zoom(value:Number):void { _zoom = value; } //TODO MF-29 Make normal comment for referenceSize public function get referenceResolution():int { return _referenceResolution; } public function get targetResolution():int { return _targetResolution; } public function set targetResolution(value:int):void { if(value != _targetResolution){ this.prepareBackup(); _targetResolution = value; if(_sources.length > 0){ var reverted:Boolean = this.revertBackupTo(_targetResolution); if( !reverted ){ _outputSize = 1; this.scaleSources(); } this.dispatch(new EditorEvent(EditorEvent.UPDATE_PROJECT)); } } } //} endregion GETTERS/SETTERS ================================================== } }
Remove fixed TODO
Remove fixed TODO
ActionScript
mit
MerlinDS/miracle_tool
aef7ea826a607c2d5ec3875cf54a0ee63888bbfa
src/com/esri/builder/controllers/LocaleController.as
src/com/esri/builder/controllers/LocaleController.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.controllers { import com.esri.builder.eventbus.AppEvent; import com.esri.builder.model.LocaleModel; import com.esri.builder.model.Model; import com.esri.builder.model.WidgetTypeRegistryModel; import com.esri.builder.supportClasses.LogUtil; import mx.core.FlexGlobals; import mx.logging.ILogger; import mx.logging.Log; import mx.resources.ResourceManager; import mx.styles.CSSStyleDeclaration; import mx.styles.IStyleManager2; import mx.styles.StyleManager; public class LocaleController { private static const LOG:ILogger = LogUtil.createLogger(LocaleController); public function LocaleController() { AppEvent.addListener(AppEvent.SETTINGS_SAVED, settingsChangeHandler, false, 500); //high priority to prevent app using outdated locale settings } private function settingsChangeHandler(event:AppEvent):void { updateApplicationLocale(); } private function updateApplicationLocale():void { var selectedLocale:String = Model.instance.locale; var localeChain:Array = ResourceManager.getInstance().localeChain; var selectedLocaleIndex:int = localeChain.indexOf(selectedLocale); localeChain.splice(selectedLocaleIndex, 1); localeChain.unshift(selectedLocale); if (Log.isDebug()) { LOG.debug("Updating application locale: {0}", selectedLocale); } ResourceManager.getInstance().update(); applyLocaleLayoutDirection(selectedLocale); setPreferredLocaleFonts(selectedLocale); setLocaleSpecificStyles(selectedLocale); } private function applyLocaleLayoutDirection(selectedLocale:String):void { var currentLayoutDirection:String = FlexGlobals.topLevelApplication.getStyle('layoutDirection'); var localeLayoutDirection:String = LocaleModel.getInstance().getLocaleLayoutDirection(selectedLocale); if (localeLayoutDirection != currentLayoutDirection) { FlexGlobals.topLevelApplication.setStyle('direction', localeLayoutDirection); FlexGlobals.topLevelApplication.setStyle('layoutDirection', localeLayoutDirection); } var currentLocale:String = FlexGlobals.topLevelApplication.getStyle('locale'); if (selectedLocale != currentLocale) { FlexGlobals.topLevelApplication.setStyle('locale', selectedLocale); WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.sort(); } } private function setPreferredLocaleFonts(selectedLocale:String):void { if (selectedLocale == 'ar') { FlexGlobals.topLevelApplication.setStyle('fontFamily', toFontFamily(LocaleModel.PREFERRED_ARABIC_FONTS)); } else if (selectedLocale == 'ja_JP') { FlexGlobals.topLevelApplication.setStyle('fontFamily', toFontFamily(LocaleModel.PREFERRED_JAPANESE_FONTS)); } else if (selectedLocale == 'ko_KR') { FlexGlobals.topLevelApplication.setStyle('fontFamily', toFontFamily(LocaleModel.PREFERRED_KOREAN_FONTS)); } else if (selectedLocale == 'zh_CN') { FlexGlobals.topLevelApplication.setStyle('fontFamily', toFontFamily(LocaleModel.PREFERRED_CHINESE_FONTS)); } else { FlexGlobals.topLevelApplication.setStyle('fontFamily', undefined); } } private function toFontFamily(fontNames:Array):String { return fontNames ? fontNames.join(',') : ""; } private function setLocaleSpecificStyles(locale:String):void { var topLevelStyleManager:IStyleManager2 = StyleManager.getStyleManager(null); var isItalicInappropriateLocale:Boolean = locale == 'ja_JP' || locale == 'ko_KR' || locale == 'zh_CN' || locale == 'ar' || locale == 'he_IL'; var emphasisStyle:CSSStyleDeclaration = topLevelStyleManager.getStyleDeclaration(".emphasisText"); var emphasisFontStyle:String = isItalicInappropriateLocale ? "normal" : "italic"; emphasisStyle.setStyle("fontStyle", emphasisFontStyle); var isBoldInappropriateLocale:Boolean = locale == 'ja_JP' || locale == 'ko_KR' || locale == 'zh_CN'; var boldStyle:CSSStyleDeclaration = topLevelStyleManager.getStyleDeclaration(".boldText"); var emphasisFontWeight:String = isBoldInappropriateLocale ? "normal" : "bold"; boldStyle.setStyle("fontWeight", emphasisFontWeight); } } }
//////////////////////////////////////////////////////////////////////////////// // 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.controllers { import com.esri.builder.eventbus.AppEvent; import com.esri.builder.model.LocaleModel; import com.esri.builder.model.Model; import com.esri.builder.model.WidgetTypeRegistryModel; import com.esri.builder.supportClasses.LogUtil; import mx.core.FlexGlobals; import mx.logging.ILogger; import mx.logging.Log; import mx.resources.ResourceManager; import mx.styles.CSSStyleDeclaration; import mx.styles.IStyleManager2; import mx.styles.StyleManager; public class LocaleController { private static const LOG:ILogger = LogUtil.createLogger(LocaleController); public function LocaleController() { AppEvent.addListener(AppEvent.SETTINGS_SAVED, settingsChangeHandler, false, 500); //high priority to prevent app using outdated locale settings } private function settingsChangeHandler(event:AppEvent):void { updateApplicationLocale(); } private function updateApplicationLocale():void { var selectedLocale:String = Model.instance.locale; var localeChain:Array = ResourceManager.getInstance().localeChain; var selectedLocaleIndex:int = localeChain.indexOf(selectedLocale); localeChain.splice(selectedLocaleIndex, 1); localeChain.unshift(selectedLocale); if (Log.isDebug()) { LOG.debug("Updating application locale: {0}", selectedLocale); } ResourceManager.getInstance().update(); applyLocaleLayoutDirection(selectedLocale); setPreferredLocaleFonts(selectedLocale); setLocaleSpecificStyles(selectedLocale); } private function applyLocaleLayoutDirection(selectedLocale:String):void { var currentLayoutDirection:String = FlexGlobals.topLevelApplication.getStyle('layoutDirection'); var localeLayoutDirection:String = LocaleModel.getInstance().getLocaleLayoutDirection(selectedLocale); if (localeLayoutDirection != currentLayoutDirection) { FlexGlobals.topLevelApplication.setStyle('direction', localeLayoutDirection); FlexGlobals.topLevelApplication.setStyle('layoutDirection', localeLayoutDirection); } var currentLocale:String = FlexGlobals.topLevelApplication.getStyle('locale'); if (selectedLocale != currentLocale) { FlexGlobals.topLevelApplication.setStyle('locale', selectedLocale); WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.sort(); } } private function setPreferredLocaleFonts(selectedLocale:String):void { if (selectedLocale == 'ar') { FlexGlobals.topLevelApplication.setStyle('fontFamily', toFontFamily(LocaleModel.PREFERRED_ARABIC_FONTS)); } else if (selectedLocale == 'ja_JP') { FlexGlobals.topLevelApplication.setStyle('fontFamily', toFontFamily(LocaleModel.PREFERRED_JAPANESE_FONTS)); } else if (selectedLocale == 'ko_KR') { FlexGlobals.topLevelApplication.setStyle('fontFamily', toFontFamily(LocaleModel.PREFERRED_KOREAN_FONTS)); } else if (selectedLocale == 'zh_CN') { FlexGlobals.topLevelApplication.setStyle('fontFamily', toFontFamily(LocaleModel.PREFERRED_CHINESE_FONTS)); } else { FlexGlobals.topLevelApplication.setStyle('fontFamily', undefined); } } private function toFontFamily(fontNames:Array):String { if (!fontNames) { return ""; } var fallbackFontName:String = "_sans"; fontNames.push(fallbackFontName); return fontNames.join(','); } private function setLocaleSpecificStyles(locale:String):void { var topLevelStyleManager:IStyleManager2 = StyleManager.getStyleManager(null); var isItalicInappropriateLocale:Boolean = locale == 'ja_JP' || locale == 'ko_KR' || locale == 'zh_CN' || locale == 'ar' || locale == 'he_IL'; var emphasisStyle:CSSStyleDeclaration = topLevelStyleManager.getStyleDeclaration(".emphasisText"); var emphasisFontStyle:String = isItalicInappropriateLocale ? "normal" : "italic"; emphasisStyle.setStyle("fontStyle", emphasisFontStyle); var isBoldInappropriateLocale:Boolean = locale == 'ja_JP' || locale == 'ko_KR' || locale == 'zh_CN'; var boldStyle:CSSStyleDeclaration = topLevelStyleManager.getStyleDeclaration(".boldText"); var emphasisFontWeight:String = isBoldInappropriateLocale ? "normal" : "bold"; boldStyle.setStyle("fontWeight", emphasisFontWeight); } } }
Add fallback font name for locale-specific font families.
Add fallback font name for locale-specific font families.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
9536687276ccbb6037d6fdbf756aa0853493cecd
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
package dolly { import dolly.core.dolly_internal; 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 ClonerTest { private var classMarkedAsCloneable:ClassLevelCloneable; private var classWithSomeCloneableFields:PropertyLevelCloneable; private var classMarkedAsCloneableType:Type; private var classWithSomeCloneableFieldsType:Type; [Before] public function before():void { classMarkedAsCloneable = new ClassLevelCloneable(); classMarkedAsCloneable.property1 = "value 1"; classMarkedAsCloneable.property2 = "value 2"; classMarkedAsCloneable.property3 = "value 3"; classMarkedAsCloneable.writableField = "value 4"; classWithSomeCloneableFields = new PropertyLevelCloneable(); classWithSomeCloneableFields.property1 = "value 1"; classWithSomeCloneableFields.property2 = "value 2"; classWithSomeCloneableFields.property3 = "value 3"; classWithSomeCloneableFields.writableField = "value 4"; classMarkedAsCloneableType = Type.forInstance(classMarkedAsCloneable); classWithSomeCloneableFieldsType = Type.forInstance(classWithSomeCloneableFields); } [After] public function after():void { classMarkedAsCloneable = null; classWithSomeCloneableFields = null; classMarkedAsCloneableType = null; classWithSomeCloneableFieldsType = null; } [Test] public function testGetCloneableFieldsForType():void { var cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classMarkedAsCloneableType); assertNotNull(cloneableFields); assertEquals(4, cloneableFields.length); cloneableFields = Cloner.getCloneableFieldsForType(classWithSomeCloneableFieldsType); assertNotNull(cloneableFields); assertEquals(3, cloneableFields.length); } [Test] public function testCloneWithClassLevelMetadata():void { const clone1:ClassLevelCloneable = Cloner.clone(classMarkedAsCloneable) as ClassLevelCloneable; assertNotNull(clone1); assertNotNull(clone1.property1); assertEquals(clone1.property1, classMarkedAsCloneable.property1); assertNotNull(clone1.property2); assertEquals(clone1.property2, classMarkedAsCloneable.property2); assertNotNull(clone1.property3); assertEquals(clone1.property3, classMarkedAsCloneable.property3); assertNotNull(clone1.writableField); assertEquals(clone1.writableField, classMarkedAsCloneable.writableField); } [Test] public function testCloneWithPropertyLevelMetadata():void { const clone2:PropertyLevelCloneable = Cloner.clone( classWithSomeCloneableFields ) as PropertyLevelCloneable; assertNotNull(clone2); assertNull(clone2.property1); assertNotNull(clone2.property2); assertEquals(clone2.property2, classWithSomeCloneableFields.property2); assertNotNull(clone2.property3); assertEquals(clone2.property3, classWithSomeCloneableFields.property3); assertNotNull(clone2.writableField); assertEquals(clone2.writableField, classWithSomeCloneableFields.writableField); } } }
package dolly { import dolly.core.dolly_internal; 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 ClonerTest { private var classMarkedAsCloneable:ClassLevelCloneable; private var classWithSomeCloneableFields:PropertyLevelCloneable; private var classMarkedAsCloneableType:Type; private var classWithSomeCloneableFieldsType:Type; [Before] public function before():void { classMarkedAsCloneable = new ClassLevelCloneable(); classMarkedAsCloneable.property1 = "value 1"; classMarkedAsCloneable.property2 = "value 2"; classMarkedAsCloneable.property3 = "value 3"; classMarkedAsCloneable.writableField = "value 4"; classWithSomeCloneableFields = new PropertyLevelCloneable(); classWithSomeCloneableFields.property1 = "value 1"; classWithSomeCloneableFields.property2 = "value 2"; classWithSomeCloneableFields.property3 = "value 3"; classWithSomeCloneableFields.writableField = "value 4"; classMarkedAsCloneableType = Type.forInstance(classMarkedAsCloneable); classWithSomeCloneableFieldsType = Type.forInstance(classWithSomeCloneableFields); } [After] public function after():void { classMarkedAsCloneable = null; classWithSomeCloneableFields = null; classMarkedAsCloneableType = null; classWithSomeCloneableFieldsType = null; } [Test] public function testGetCloneableFieldsForType():void { var cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classMarkedAsCloneableType); assertNotNull(cloneableFields); assertEquals(4, cloneableFields.length); cloneableFields = Cloner.getCloneableFieldsForType(classWithSomeCloneableFieldsType); assertNotNull(cloneableFields); assertEquals(3, cloneableFields.length); } [Test] public function testCloneWithClassLevelMetadata():void { const clone:ClassLevelCloneable = Cloner.clone(classMarkedAsCloneable) as ClassLevelCloneable; assertNotNull(clone); assertNotNull(clone.property1); assertEquals(clone.property1, classMarkedAsCloneable.property1); assertNotNull(clone.property2); assertEquals(clone.property2, classMarkedAsCloneable.property2); assertNotNull(clone.property3); assertEquals(clone.property3, classMarkedAsCloneable.property3); assertNotNull(clone.writableField); assertEquals(clone.writableField, classMarkedAsCloneable.writableField); } [Test] public function testCloneWithPropertyLevelMetadata():void { const clone:PropertyLevelCloneable = Cloner.clone( classWithSomeCloneableFields ) as PropertyLevelCloneable; assertNotNull(clone); assertNull(clone.property1); assertNotNull(clone.property2); assertEquals(clone.property2, classWithSomeCloneableFields.property2); assertNotNull(clone.property3); assertEquals(clone.property3, classWithSomeCloneableFields.property3); assertNotNull(clone.writableField); assertEquals(clone.writableField, classWithSomeCloneableFields.writableField); } } }
Rename local variables.
Rename local variables.
ActionScript
mit
Yarovoy/dolly
dee36289d2c6e3b114a56c43c7969e898ed6d5e6
src/aerys/minko/scene/node/Mesh.as
src/aerys/minko/scene/node/Mesh.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.material.Material; import aerys.minko.render.material.basic.BasicMaterial; import aerys.minko.scene.controller.mesh.MeshController; import aerys.minko.scene.controller.mesh.MeshVisibilityController; import aerys.minko.scene.data.TransformDataProvider; import aerys.minko.type.Signal; 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.Ray; use namespace minko_scene; /** * Mesh objects are a visible instance of a Geometry rendered using a specific * Effect with specific rendering properties. * * <p> * Those rendering properties are stored in a DataBindings object so they can * be directly used by the shaders in the rendering API. * </p> * * @author Jean-Marc Le Roux * */ public class Mesh extends AbstractVisibleSceneNode { public static const DEFAULT_MATERIAL : Material = new BasicMaterial(); private var _geometry : Geometry; private var _properties : DataProvider; private var _material : Material; private var _bindings : DataBindings; private var _visibility : MeshVisibilityController; private var _frame : uint; private var _cloned : Signal; private var _materialChanged : Signal; private var _frameChanged : Signal; private var _geometryChanged : Signal; /** * A DataProvider object already bound to the Mesh bindings. * * <pre> * // set the "diffuseColor" property to 0x0000ffff * mesh.properties.diffuseColor = 0x0000ffff; * * // animate the "diffuseColor" property * mesh.addController( * new AnimationController( * new &lt;ITimeline&gt;[new ColorTimeline( * "dataProvider.diffuseColor", * 5000, * new &lt;uint&gt;[0xffffffff, 0xffffff00, 0xffffffff] * )] * ) * ); * </pre> * * @return * */ public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get material() : Material { return _material; } public function set material(value : Material) : void { if (_material != value) { if (_material) _bindings.removeProvider(_material); var oldMaterial : Material = _material; _material = value; if (value) _bindings.addProvider(value); _materialChanged.execute(this, oldMaterial, value); } } /** * The rendering properties provided to the shaders to customize * how the mesh will appear on screen. * * @return * */ public function get bindings() : DataBindings { return _bindings; } /** * The Geometry of the mesh. * @return * */ public function get geometry() : Geometry { return _geometry; } public function set geometry(value : Geometry) : void { if (_geometry != value) { var oldGeometry : Geometry = _geometry; if (oldGeometry) oldGeometry.changed.remove(geometryChangedHandler); _geometry = value; if (value) _geometry.changed.add(geometryChangedHandler); _geometryChanged.execute(this, oldGeometry, value); } } /** * Whether the mesh in inside the camera frustum or not. * @return * */ public function get insideFrustum() : Boolean { return _visibility.insideFrustum; } override public function get computedVisibility() : Boolean { return scene ? super.computedVisibility && _visibility.computedVisibility : super.computedVisibility; } public function get frustumCulling() : uint { return _visibility.frustumCulling; } public function set frustumCulling(value : uint) : void { _visibility.frustumCulling = value; } public function get cloned() : Signal { return _cloned; } public function get materialChanged() : Signal { return _materialChanged; } public function get frameChanged() : Signal { return _frameChanged; } public function get geometryChanged() : Signal { return _geometryChanged; } public function get frame() : uint { return _frame; } public function set frame(value : uint) : void { if (_frame != value) { var oldFrame : uint = _frame; _frame = value; _frameChanged.execute(this, oldFrame, value); } } public function Mesh(geometry : Geometry = null, material : Material = null, name : String = null) { super(); initializeMesh(geometry, material, name); } override protected function initialize() : void { _bindings = new DataBindings(this); this.properties = new DataProvider( properties, 'meshProperties', DataProviderUsage.EXCLUSIVE ); super.initialize(); } override protected function initializeSignals():void { super.initializeSignals(); _cloned = new Signal('Mesh.cloned'); _materialChanged = new Signal('Mesh.materialChanged'); _frameChanged = new Signal('Mesh.frameChanged'); _geometryChanged = new Signal('Mesh.geometryChanged'); } override protected function initializeContollers():void { super.initializeContollers(); addController(new MeshController()); _visibility = new MeshVisibilityController(); _visibility.frustumCulling = FrustumCulling.ENABLED; addController(_visibility); } protected function initializeMesh(geometry : Geometry, material : Material, name : String) : void { if (name) this.name = name; this.geometry = geometry; this.material = material || DEFAULT_MATERIAL; } public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number { return _geometry.boundingBox.testRay( ray, getWorldToLocalTransform(), maxDistance ); } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Mesh = new Mesh(); clone.name = name; clone.geometry = _geometry; clone.properties = DataProvider(_properties.clone()); clone._bindings.copySharedProvidersFrom(_bindings); clone.transform.copyFrom(transform); clone.material = _material; this.cloned.execute(this, clone); return clone; } private function geometryChangedHandler(geometry : Geometry) : void { _geometryChanged.execute(this, _geometry, _geometry); } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.material.Material; import aerys.minko.render.material.basic.BasicMaterial; import aerys.minko.scene.controller.mesh.MeshController; import aerys.minko.scene.controller.mesh.MeshVisibilityController; import aerys.minko.scene.data.TransformDataProvider; import aerys.minko.type.Signal; 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.Ray; use namespace minko_scene; /** * Mesh objects are a visible instance of a Geometry rendered using a specific * Effect with specific rendering properties. * * <p> * Those rendering properties are stored in a DataBindings object so they can * be directly used by the shaders in the rendering API. * </p> * * @author Jean-Marc Le Roux * */ public class Mesh extends AbstractVisibleSceneNode { public static const DEFAULT_MATERIAL : Material = new BasicMaterial(); private var _geometry : Geometry; private var _properties : DataProvider; private var _material : Material; private var _bindings : DataBindings; private var _visibility : MeshVisibilityController; private var _frame : uint; private var _cloned : Signal; private var _materialChanged : Signal; private var _frameChanged : Signal; private var _geometryChanged : Signal; /** * A DataProvider object already bound to the Mesh bindings. * * <pre> * // set the "diffuseColor" property to 0x0000ffff * mesh.properties.diffuseColor = 0x0000ffff; * * // animate the "diffuseColor" property * mesh.addController( * new AnimationController( * new &lt;ITimeline&gt;[new ColorTimeline( * "dataProvider.diffuseColor", * 5000, * new &lt;uint&gt;[0xffffffff, 0xffffff00, 0xffffffff] * )] * ) * ); * </pre> * * @return * */ public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get material() : Material { return _material; } public function set material(value : Material) : void { if (_material != value) { if (_material) _bindings.removeProvider(_material); var oldMaterial : Material = _material; _material = value; if (value) _bindings.addProvider(value); _materialChanged.execute(this, oldMaterial, value); } } /** * The rendering properties provided to the shaders to customize * how the mesh will appear on screen. * * @return * */ public function get bindings() : DataBindings { return _bindings; } /** * The Geometry of the mesh. * @return * */ public function get geometry() : Geometry { return _geometry; } public function set geometry(value : Geometry) : void { if (_geometry != value) { var oldGeometry : Geometry = _geometry; if (oldGeometry) oldGeometry.changed.remove(geometryChangedHandler); _geometry = value; if (value) _geometry.changed.add(geometryChangedHandler); _geometryChanged.execute(this, oldGeometry, value); } } /** * Whether the mesh in inside the camera frustum or not. * @return * */ public function get insideFrustum() : Boolean { return _visibility.insideFrustum; } override public function get computedVisibility() : Boolean { var visibility : Boolean = super.computedVisibility && _material && _material.effect; return scene ? visibility && _visibility.computedVisibility : visibility; } public function get frustumCulling() : uint { return _visibility.frustumCulling; } public function set frustumCulling(value : uint) : void { _visibility.frustumCulling = value; } public function get cloned() : Signal { return _cloned; } public function get materialChanged() : Signal { return _materialChanged; } public function get frameChanged() : Signal { return _frameChanged; } public function get geometryChanged() : Signal { return _geometryChanged; } public function get frame() : uint { return _frame; } public function set frame(value : uint) : void { if (_frame != value) { var oldFrame : uint = _frame; _frame = value; _frameChanged.execute(this, oldFrame, value); } } public function Mesh(geometry : Geometry = null, material : Material = null, name : String = null) { super(); initializeMesh(geometry, material, name); } override protected function initialize() : void { _bindings = new DataBindings(this); this.properties = new DataProvider( properties, 'meshProperties', DataProviderUsage.EXCLUSIVE ); super.initialize(); } override protected function initializeSignals():void { super.initializeSignals(); _cloned = new Signal('Mesh.cloned'); _materialChanged = new Signal('Mesh.materialChanged'); _frameChanged = new Signal('Mesh.frameChanged'); _geometryChanged = new Signal('Mesh.geometryChanged'); } override protected function initializeContollers():void { super.initializeContollers(); addController(new MeshController()); _visibility = new MeshVisibilityController(); _visibility.frustumCulling = FrustumCulling.ENABLED; addController(_visibility); } protected function initializeMesh(geometry : Geometry, material : Material, name : String) : void { if (name) this.name = name; this.geometry = geometry; this.material = material || DEFAULT_MATERIAL; } public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number { return _geometry.boundingBox.testRay( ray, getWorldToLocalTransform(), maxDistance ); } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Mesh = new Mesh(); clone.name = name; clone.geometry = _geometry; clone.properties = DataProvider(_properties.clone()); clone._bindings.copySharedProvidersFrom(_bindings); clone.transform.copyFrom(transform); clone.material = _material; this.cloned.execute(this, clone); return clone; } private function geometryChangedHandler(geometry : Geometry) : void { _geometryChanged.execute(this, _geometry, _geometry); } } }
fix Mesh.computedVisibility to take material and material.effect availability into account: mesh without material/effect are now considered as hidden
fix Mesh.computedVisibility to take material and material.effect availability into account: mesh without material/effect are now considered as hidden
ActionScript
mit
aerys/minko-as3
d7b6ce6ced88163578a5fa0661bc7769fcedf396
dolly-framework/src/test/actionscript/dolly/utils/PropertyUtilTests.as
dolly-framework/src/test/actionscript/dolly/utils/PropertyUtilTests.as
package dolly.utils { import dolly.core.dolly_internal; import mx.collections.ArrayCollection; import mx.collections.ArrayList; import org.flexunit.assertThat; import org.flexunit.asserts.assertTrue; 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 PropertyUtilTests { private var sourceObj:Object; private var targetObj:Object; [Before] public function before():void { sourceObj = {}; sourceObj.array = [0, 1, 2, 3, 4]; sourceObj.arrayList = new ArrayList([0, 1, 2, 3, 4]); sourceObj.arrayCollection = new ArrayCollection([0, 1, 2, 3, 4]); targetObj = {}; } [After] public function after():void { sourceObj = targetObj = null; } [Test] public function copyingOfArray():void { PropertyUtil.copyArray(sourceObj, targetObj, "array"); assertThat(targetObj.array, arrayWithSize(5)); assertThat(targetObj.array, sourceObj.array); assertTrue(targetObj.array != sourceObj.array); assertThat(targetObj.array, everyItem(isA(Number))); assertThat(targetObj.array, array(equalTo(0), equalTo(1), equalTo(2), equalTo(3), equalTo(4))); } } }
package dolly.utils { import dolly.core.dolly_internal; import mx.collections.ArrayCollection; import mx.collections.ArrayList; import org.flexunit.assertThat; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertFalse; import org.flexunit.asserts.assertNotNull; import org.flexunit.asserts.assertTrue; 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 PropertyUtilTests { private var sourceObj:Object; private var targetObj:Object; [Before] public function before():void { sourceObj = {}; sourceObj.array = [0, 1, 2, 3, 4]; sourceObj.arrayList = new ArrayList([0, 1, 2, 3, 4]); sourceObj.arrayCollection = new ArrayCollection([0, 1, 2, 3, 4]); targetObj = {}; } [After] public function after():void { sourceObj = targetObj = null; } [Test] public function copyingOfArray():void { PropertyUtil.copyArray(sourceObj, targetObj, "array"); assertThat(targetObj.array, arrayWithSize(5)); assertThat(targetObj.array, sourceObj.array); assertTrue(targetObj.array != sourceObj.array); assertThat(targetObj.array, everyItem(isA(Number))); assertThat(targetObj.array, array(equalTo(0), equalTo(1), equalTo(2), equalTo(3), equalTo(4))); } [Test] public function copyingOfArrayList():void { PropertyUtil.copyArrayList(sourceObj, targetObj, "arrayList"); const targetArrayList:ArrayList = targetObj.arrayList; assertNotNull(targetArrayList); assertFalse(targetObj.arrayList == sourceObj.arrayList); assertEquals(targetArrayList.length, 5); assertEquals(targetArrayList.getItemAt(0), 0); assertEquals(targetArrayList.getItemAt(1), 1); assertEquals(targetArrayList.getItemAt(2), 2); assertEquals(targetArrayList.getItemAt(3), 3); assertEquals(targetArrayList.getItemAt(4), 4); } } }
Test for PropertyUtil.copyArrayList() method.
Test for PropertyUtil.copyArrayList() method.
ActionScript
mit
Yarovoy/dolly
32551f3abbf2e78bece6c3d08c63e81b6f21f2c4
src/org/hola/FlashFetchBin.as
src/org/hola/FlashFetchBin.as
package org.hola { import flash.events.*; import flash.net.URLStream; import flash.net.URLRequest; import flash.utils.setTimeout; import flash.utils.clearTimeout; import flash.external.ExternalInterface; import org.hola.ZExternalInterface; public class FlashFetchBin { public static var inited:Boolean = false; public static var free_id:Number = 0; public static var req_list:Object = {}; public static function init():Boolean{ if (inited) return inited; if (!ZExternalInterface.avail()) return false; ExternalInterface.addCallback('hola_fetchBin', hola_fetchBin); ExternalInterface.addCallback('hola_fetchBinRemove', hola_fetchBinRemove); ExternalInterface.addCallback('hola_fetchBinAbort', hola_fetchBinAbort); inited = true; return inited; } public static function hola_fetchBin(o:Object):Object{ var id:String = 'fetch_bin_'+free_id; free_id++; var url:String = o.url; var req:URLRequest = new URLRequest(url); var stream:URLStream = new URLStream(); stream.load(req); req_list[id] = {id: id, stream: stream, jsurlstream_req_id: o.jsurlstream_req_id}; stream.addEventListener(Event.OPEN, streamOpen); stream.addEventListener(ProgressEvent.PROGRESS, streamProgress); stream.addEventListener(HTTPStatusEvent.HTTP_STATUS, streamHttpStatus); stream.addEventListener(Event.COMPLETE, streamComplete); stream.addEventListener(IOErrorEvent.IO_ERROR, streamError); stream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, streamError); return {id: id, url: url}; } public static function hola_fetchBinRemove(id:String):void{ var req:Object = req_list[id]; if (!req) return; if (req.stream.connected) req.stream.close(); if (req.timer) clearTimeout(req.timer); delete req_list[id]; } public static function hola_fetchBinAbort(id:String):void{ var req:Object = req_list[id]; if (!req) return; if (req.stream.connected) req.stream.close(); } public static function getReqFromStream(stream:Object):Object{ // XXX arik/bahaa: implement without loop for (var n:String in req_list) { if (req_list[n].stream===stream) return req_list[n]; } return null; } // XXX arik/bahaa: mv to org.hola.util public static function jsPostMessage(id:String, data:Object):void{ if (!ZExternalInterface.avail()) return; ExternalInterface.call('window.postMessage', {id: id, ts: new Date().getTime(), data: data}, '*'); } public static function streamOpen(e:Event):void{ var req:Object = getReqFromStream(e.target); if (!req) return ZErr.log('req not found streamOpen'); jsPostMessage('holaflash.streamOpen', {id: req.id}); } public static function streamProgress(e:ProgressEvent):void{ var req:Object = getReqFromStream(e.target); if (!req) return ZErr.log('req not found streamProgress'); req.bytesTotal = e.bytesTotal; req.bytesLoaded = e.bytesLoaded; if (!req.prevJSProgress || req.bytesLoaded==req.bytesTotal || req.bytesLoaded-req.prevJSProgress > (req.bytesTotal/5)) { req.prevJSProgress = req.bytesLoaded; jsPostMessage('holaflash.streamProgress', {id: req.id, bytesLoaded: e.bytesLoaded, bytesTotal: e.bytesTotal}); } } public static function streamHttpStatus(e:HTTPStatusEvent):void{ var req:Object = getReqFromStream(e.target); if (!req) return ZErr.log('req not found streamHttpStatus'); jsPostMessage('holaflash.streamHttpStatus', {id: req.id, status: e.status}); } public static function streamComplete(e:Event):void{ var req:Object = getReqFromStream(e.target); if (!req) return ZErr.log('req not found streamComplete'); jsPostMessage('holaflash.streamComplete', {id: req.id, bytesTotal: req.bytesTotal}); } public static function streamError(e:ErrorEvent):void{ var req:Object = getReqFromStream(e.target); if (!req) return ZErr.log('req not found streamError'); jsPostMessage('holaflash.streamError', {id: req.id}); hola_fetchBinRemove(req.id); } public static function consumeDataTimeout(id:String, cb:Function, ms:Number, ctx:Object):void{ var req:Object = req_list[id]; if (!req) throw new Error('consumeDataTimeout failed find req '+id); if (req.timer) clearTimeout(req.timer); req.timer = setTimeout(cb, ms, ctx); } } }
package org.hola { import flash.events.*; import flash.net.URLStream; import flash.net.URLRequest; import flash.utils.setTimeout; import flash.utils.clearTimeout; import flash.external.ExternalInterface; import org.hola.ZExternalInterface; public class FlashFetchBin { private static var inited:Boolean = false; private static var free_id:Number = 0; public static var req_list:Object = {}; public static function init():Boolean{ if (inited) return inited; if (!ZExternalInterface.avail()) return false; ExternalInterface.addCallback('hola_fetchBin', hola_fetchBin); ExternalInterface.addCallback('hola_fetchBinRemove', hola_fetchBinRemove); ExternalInterface.addCallback('hola_fetchBinAbort', hola_fetchBinAbort); inited = true; return inited; } private static function hola_fetchBin(o:Object):Object{ var id:String = 'fetch_bin_'+free_id; free_id++; var url:String = o.url; var req:URLRequest = new URLRequest(url); var stream:URLStream = new URLStream(); stream.load(req); req_list[id] = {id: id, stream: stream, jsurlstream_req_id: o.jsurlstream_req_id}; stream.addEventListener(Event.OPEN, streamOpen); stream.addEventListener(ProgressEvent.PROGRESS, streamProgress); stream.addEventListener(HTTPStatusEvent.HTTP_STATUS, streamHttpStatus); stream.addEventListener(Event.COMPLETE, streamComplete); stream.addEventListener(IOErrorEvent.IO_ERROR, streamError); stream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, streamError); return {id: id, url: url}; } public static function hola_fetchBinRemove(id:String):void{ var req:Object = req_list[id]; if (!req) return; if (req.stream.connected) req.stream.close(); if (req.timer) clearTimeout(req.timer); delete req_list[id]; } private static function hola_fetchBinAbort(id:String):void{ var req:Object = req_list[id]; if (!req) return; if (req.stream.connected) req.stream.close(); } private static function getReqFromStream(stream:Object):Object{ // XXX arik/bahaa: implement without loop for (var n:String in req_list) { if (req_list[n].stream===stream) return req_list[n]; } return null; } // XXX arik/bahaa: mv to org.hola.util private static function jsPostMessage(id:String, data:Object):void{ if (!ZExternalInterface.avail()) return; ExternalInterface.call('window.postMessage', {id: id, ts: new Date().getTime(), data: data}, '*'); } private static function streamOpen(e:Event):void{ var req:Object = getReqFromStream(e.target); if (!req) return ZErr.log('req not found streamOpen'); jsPostMessage('holaflash.streamOpen', {id: req.id}); } private static function streamProgress(e:ProgressEvent):void{ var req:Object = getReqFromStream(e.target); if (!req) return ZErr.log('req not found streamProgress'); req.bytesTotal = e.bytesTotal; req.bytesLoaded = e.bytesLoaded; if (!req.prevJSProgress || req.bytesLoaded==req.bytesTotal || req.bytesLoaded-req.prevJSProgress > (req.bytesTotal/5)) { req.prevJSProgress = req.bytesLoaded; jsPostMessage('holaflash.streamProgress', {id: req.id, bytesLoaded: e.bytesLoaded, bytesTotal: e.bytesTotal}); } } private static function streamHttpStatus(e:HTTPStatusEvent):void{ var req:Object = getReqFromStream(e.target); if (!req) return ZErr.log('req not found streamHttpStatus'); jsPostMessage('holaflash.streamHttpStatus', {id: req.id, status: e.status}); } private static function streamComplete(e:Event):void{ var req:Object = getReqFromStream(e.target); if (!req) return ZErr.log('req not found streamComplete'); jsPostMessage('holaflash.streamComplete', {id: req.id, bytesTotal: req.bytesTotal}); } private static function streamError(e:ErrorEvent):void{ var req:Object = getReqFromStream(e.target); if (!req) return ZErr.log('req not found streamError'); jsPostMessage('holaflash.streamError', {id: req.id}); hola_fetchBinRemove(req.id); } public static function consumeDataTimeout(id:String, cb:Function, ms:Number, ctx:Object):void{ var req:Object = req_list[id]; if (!req) throw new Error('consumeDataTimeout failed find req '+id); if (req.timer) clearTimeout(req.timer); req.timer = setTimeout(cb, ms, ctx); } } }
make private members private
make private members private
ActionScript
mpl-2.0
hola/flashls,hola/flashls
7c6597e0d73ca2df643787003fc7fc4d5820b3c3
VectorCommon/src/org/jbei/components/sequenceClasses/FeatureRenderer.as
VectorCommon/src/org/jbei/components/sequenceClasses/FeatureRenderer.as
package org.jbei.components.sequenceClasses { import flash.display.Graphics; import flash.geom.Rectangle; import org.jbei.bio.sequence.common.StrandType; import org.jbei.bio.sequence.dna.Feature; import org.jbei.components.common.AnnotationRenderer; import org.jbei.components.common.IContentHolder; /** * @author Zinovii Dmytriv */ public class FeatureRenderer extends AnnotationRenderer { public static const DEFAULT_FEATURE_HEIGHT:int = 6; public static const DEFAULT_FEATURES_SEQUENCE_GAP:int = 3; public static const DEFAULT_FEATURES_GAP:int = 2; private var sequenceContentHolder:ContentHolder; // Contructor public function FeatureRenderer(contentHolder:IContentHolder, feature:Feature) { super(contentHolder, feature); sequenceContentHolder = contentHolder as ContentHolder; } // Properties public function get feature():Feature { return annotation as Feature; } // Public Methods public function update():void { needsMeasurement = true; invalidateDisplayList(); } // Protected Methods protected override function render():void { super.render(); var g:Graphics = graphics; g.clear(); var featureRows:Array = sequenceContentHolder.rowMapper.featureToRowMap[feature]; if(! featureRows) { return; } for(var i:int = 0; i < featureRows.length; i++) { var row:Row = sequenceContentHolder.rowMapper.rows[featureRows[i]] as Row; // find feature row index var alignmentRowIndex:int = -1; for(var r:int = 0; r < row.rowData.featuresAlignment.length; r++) { var rowFeatures:Array = row.rowData.featuresAlignment[r] as Array; for(var c:int = 0; c < rowFeatures.length; c++) { if((rowFeatures[c] as Feature) == feature) { alignmentRowIndex = r; break; } } if(alignmentRowIndex != -1) { break; } } g.lineStyle(1, 0x606060); g.beginFill(colorByType(feature.type.toLowerCase())); var startBP:int; var endBP:int; if(feature.start > feature.end) { // circular case /* |--------------------------------------------------------------------------------------| * FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF| */ if(feature.end >= row.rowData.start && feature.end <= row.rowData.end) { endBP = feature.end - 1; } /* |--------------------------------------------------------------------------------------| * FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ else if(row.rowData.end >= contentHolder.sequenceProvider.sequence.length) { endBP = contentHolder.sequenceProvider.sequence.length - 1; } else { endBP = row.rowData.end; } /* |--------------------------------------------------------------------------------------| * |FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ if(feature.start >= row.rowData.start && feature.start <= row.rowData.end) { startBP = feature.start; } /* |--------------------------------------------------------------------------------------| * FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ else { startBP = row.rowData.start; } } else { startBP = (feature.start < row.rowData.start) ? row.rowData.start : feature.start; endBP = (feature.end - 1 < row.rowData.end) ? feature.end - 1 : row.rowData.end; } /* Case when start and end are in the same row * |--------------------------------------------------------------------------------------| * FFFFFFFFFFFFFFFFFFFFFFFFFFF| |FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ if(startBP > endBP) { var bpStartMetrics1:Rectangle = sequenceContentHolder.bpMetricsByIndex(row.rowData.start); var bpEndMetrics1:Rectangle = sequenceContentHolder.bpMetricsByIndex(Math.min(endBP, contentHolder.sequenceProvider.sequence.length - 1)); var bpStartMetrics2:Rectangle = sequenceContentHolder.bpMetricsByIndex(startBP); var bpEndMetrics2:Rectangle = sequenceContentHolder.bpMetricsByIndex(Math.min(row.rowData.end, contentHolder.sequenceProvider.sequence.length - 1)); var featureX1:Number = bpStartMetrics1.x + 2; // +2 to look pretty var featureX2:Number = bpStartMetrics2.x + 2; // +2 to look pretty var featureYCommon:Number = bpStartMetrics1.y + row.sequenceMetrics.height + alignmentRowIndex * (DEFAULT_FEATURE_HEIGHT + DEFAULT_FEATURES_GAP) + DEFAULT_FEATURES_SEQUENCE_GAP; if(sequenceContentHolder.showAminoAcids1RevCom) { featureYCommon += 3 * sequenceContentHolder.aminoAcidsTextRenderer.textHeight; } var featureRowWidth1:Number = bpEndMetrics1.x - bpStartMetrics1.x + sequenceContentHolder.sequenceSymbolRenderer.textWidth; var featureRowWidth2:Number = bpEndMetrics2.x - bpStartMetrics2.x + sequenceContentHolder.sequenceSymbolRenderer.textWidth; var featureRowHeightCommon:Number = DEFAULT_FEATURE_HEIGHT; if(feature.strand == StrandType.UNKNOWN) { drawFeatureRect(g, featureX1, featureYCommon, featureRowWidth1, featureRowHeightCommon); drawFeatureRect(g, featureX2, featureYCommon, featureRowWidth2, featureRowHeightCommon); } else if(feature.strand == StrandType.FORWARD) { drawFeatureForwardArrow(g, featureX1, featureYCommon, featureRowWidth1, featureRowHeightCommon); drawFeatureForwardRect(g, featureX2, featureYCommon, featureRowWidth2, featureRowHeightCommon); } else if(feature.strand == StrandType.BACKWARD) { drawFeatureBackwardRect(g, featureX1, featureYCommon, featureRowWidth1, featureRowHeightCommon); drawFeatureBackwardArrow(g, featureX2, featureYCommon, featureRowWidth2, featureRowHeightCommon); } } else { var bpStartMetrics:Rectangle = sequenceContentHolder.bpMetricsByIndex(startBP); var bpEndMetrics:Rectangle = sequenceContentHolder.bpMetricsByIndex(Math.min(endBP, contentHolder.sequenceProvider.sequence.length - 1)); var featureX:Number = bpStartMetrics.x + 2; // +2 to look pretty var featureY:Number = bpStartMetrics.y + row.sequenceMetrics.height + alignmentRowIndex * (DEFAULT_FEATURE_HEIGHT + DEFAULT_FEATURES_GAP) + DEFAULT_FEATURES_SEQUENCE_GAP; if(sequenceContentHolder.showAminoAcids1RevCom) { featureY += 3 * sequenceContentHolder.aminoAcidsTextRenderer.textHeight; } var featureRowWidth:Number = bpEndMetrics.x - bpStartMetrics.x + sequenceContentHolder.sequenceSymbolRenderer.textWidth; var featureRowHeight:Number = DEFAULT_FEATURE_HEIGHT; if(feature.strand == StrandType.UNKNOWN) { drawFeatureRect(g, featureX, featureY, featureRowWidth, featureRowHeight); } else if(feature.strand == StrandType.FORWARD) { if(feature.end >= row.rowData.start && feature.end <= row.rowData.end) { drawFeatureForwardArrow(g, featureX, featureY, featureRowWidth, featureRowHeight); } else { drawFeatureForwardRect(g, featureX, featureY, featureRowWidth, featureRowHeight); } } else if(feature.strand == StrandType.BACKWARD) { if(feature.start >= row.rowData.start && feature.start <= row.rowData.end) { drawFeatureBackwardArrow(g, featureX, featureY, featureRowWidth, featureRowHeight); } else { drawFeatureBackwardRect(g, featureX, featureY, featureRowWidth, featureRowHeight); } } } g.endFill(); } } protected override function createToolTipLabel():void { tooltipLabel = feature.type + (feature.name == "" ? "" : (" - " + feature.name)) + ": " + (feature.start + 1) + ".." + (feature.end); } // Private Methods private function colorByType(featureType:String):int { var color:int = 0xCCCCCC; if(featureType == "promoter") { color = 0x31B440; } else if(featureType == "terminator"){ color = 0xF51600; } else if(featureType == "cds"){ color = 0xEF6500; } else if(featureType == "m_rna"){ color = 0xFFFF00; } else if(featureType == "misc_binding"){ color = 0x006FEF; } else if(featureType == "misc_feature"){ color = 0x006FEF; } else if(featureType == "misc_marker"){ color = 0x8DCEB1; } else if(featureType == "rep_origin"){ color = 0x878787; } return color; } private function drawFeatureRect(g:Graphics, x:Number, y:Number, width:Number, height:Number):void { g.drawRect(x, y, width, height); } private function drawFeatureForwardRect(g:Graphics, x:Number, y:Number, width:Number, height:Number):void { g.moveTo(x, y); g.curveTo(x + 3, y + height / 2, x, y + height); g.lineTo(x + width, y + height); g.lineTo(x + width, y); g.lineTo(x, y); } private function drawFeatureBackwardRect(g:Graphics, x:Number, y:Number, width:Number, height:Number):void { g.moveTo(x, y); g.lineTo(x, y + height); g.lineTo(x + width, y + height); g.curveTo(x + width - 3, y + height / 2, x + width, y); g.lineTo(x, y); } private function drawFeatureForwardArrow(g:Graphics, x:Number, y:Number, width:Number, height:Number):void { if(width > sequenceContentHolder.sequenceSymbolRenderer.width) { g.moveTo(x, y); g.lineTo(x + width - 8, y); g.lineTo(x + width, y + height / 2); g.lineTo(x + width - 8, y + height); g.lineTo(x, y + height); g.curveTo(x + 3, y + height / 2, x, y); } else { g.moveTo(x, y); g.lineTo(x + width, y + height / 2); g.lineTo(x, y + height); g.lineTo(x, y); } } private function drawFeatureBackwardArrow(g:Graphics, x:Number, y:Number, width:Number, height:Number):void { if(width > sequenceContentHolder.sequenceSymbolRenderer.width) { g.moveTo(x + 8, y); g.lineTo(x + width, y); g.curveTo(x + width - 3, y + height / 2, x + width, y + height); g.lineTo(x + 8, y + height); g.lineTo(x, y + height / 2); g.lineTo(x + 8, y); } else { g.moveTo(x, y + height / 2); g.lineTo(x + width, y); g.lineTo(x + width, y + height); g.lineTo(x, y + height / 2); } } } }
package org.jbei.components.sequenceClasses { import flash.display.Graphics; import flash.geom.Rectangle; import org.jbei.bio.sequence.common.StrandType; import org.jbei.bio.sequence.dna.Feature; import org.jbei.components.common.AnnotationRenderer; import org.jbei.components.common.IContentHolder; /** * @author Zinovii Dmytriv */ public class FeatureRenderer extends AnnotationRenderer { public static const DEFAULT_FEATURE_HEIGHT:int = 6; public static const DEFAULT_FEATURES_SEQUENCE_GAP:int = 3; public static const DEFAULT_FEATURES_GAP:int = 2; private var sequenceContentHolder:ContentHolder; // Contructor public function FeatureRenderer(contentHolder:IContentHolder, feature:Feature) { super(contentHolder, feature); sequenceContentHolder = contentHolder as ContentHolder; } // Properties public function get feature():Feature { return annotation as Feature; } // Public Methods public function update():void { needsMeasurement = true; invalidateDisplayList(); } // Protected Methods protected override function render():void { super.render(); var g:Graphics = graphics; g.clear(); var featureRows:Array = sequenceContentHolder.rowMapper.featureToRowMap[feature]; if(! featureRows) { return; } for(var i:int = 0; i < featureRows.length; i++) { var row:Row = sequenceContentHolder.rowMapper.rows[featureRows[i]] as Row; // find feature row index var alignmentRowIndex:int = -1; for(var r:int = 0; r < row.rowData.featuresAlignment.length; r++) { var rowFeatures:Array = row.rowData.featuresAlignment[r] as Array; for(var c:int = 0; c < rowFeatures.length; c++) { if((rowFeatures[c] as Feature) == feature) { alignmentRowIndex = r; break; } } if(alignmentRowIndex != -1) { break; } } g.lineStyle(1, 0x606060); g.beginFill(colorByType(feature.type.toLowerCase())); var startBP:int; var endBP:int; if(feature.start > feature.end) { // circular case /* |--------------------------------------------------------------------------------------| * FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF| */ if(feature.end >= row.rowData.start && feature.end <= row.rowData.end) { endBP = feature.end - 1; } /* |--------------------------------------------------------------------------------------| * FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ else if(row.rowData.end >= contentHolder.sequenceProvider.sequence.length) { endBP = contentHolder.sequenceProvider.sequence.length - 1; } else { endBP = row.rowData.end; } /* |--------------------------------------------------------------------------------------| * |FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ if(feature.start >= row.rowData.start && feature.start <= row.rowData.end) { startBP = feature.start; } /* |--------------------------------------------------------------------------------------| * FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ else { startBP = row.rowData.start; } } else { if (feature.start < row.rowData.start && feature.end <= row.rowData.start) { continue; // the feature is outside of the current row } else { startBP = (feature.start < row.rowData.start) ? row.rowData.start : feature.start; endBP = (feature.end - 1 < row.rowData.end) ? feature.end - 1 : row.rowData.end; } } /* Case when start and end are in the same row * |--------------------------------------------------------------------------------------| * FFFFFFFFFFFFFFFFFFFFFFFFFFF| |FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ if(startBP > endBP) { var bpStartMetrics1:Rectangle = sequenceContentHolder.bpMetricsByIndex(row.rowData.start); var bpEndMetrics1:Rectangle = sequenceContentHolder.bpMetricsByIndex(Math.min(endBP, contentHolder.sequenceProvider.sequence.length - 1)); var bpStartMetrics2:Rectangle = sequenceContentHolder.bpMetricsByIndex(startBP); var bpEndMetrics2:Rectangle = sequenceContentHolder.bpMetricsByIndex(Math.min(row.rowData.end, contentHolder.sequenceProvider.sequence.length - 1)); var featureX1:Number = bpStartMetrics1.x + 2; // +2 to look pretty var featureX2:Number = bpStartMetrics2.x + 2; // +2 to look pretty var featureYCommon:Number = bpStartMetrics1.y + row.sequenceMetrics.height + alignmentRowIndex * (DEFAULT_FEATURE_HEIGHT + DEFAULT_FEATURES_GAP) + DEFAULT_FEATURES_SEQUENCE_GAP; if(sequenceContentHolder.showAminoAcids1RevCom) { featureYCommon += 3 * sequenceContentHolder.aminoAcidsTextRenderer.textHeight; } var featureRowWidth1:Number = bpEndMetrics1.x - bpStartMetrics1.x + sequenceContentHolder.sequenceSymbolRenderer.textWidth; var featureRowWidth2:Number = bpEndMetrics2.x - bpStartMetrics2.x + sequenceContentHolder.sequenceSymbolRenderer.textWidth; var featureRowHeightCommon:Number = DEFAULT_FEATURE_HEIGHT; if(feature.strand == StrandType.UNKNOWN) { drawFeatureRect(g, featureX1, featureYCommon, featureRowWidth1, featureRowHeightCommon); drawFeatureRect(g, featureX2, featureYCommon, featureRowWidth2, featureRowHeightCommon); } else if(feature.strand == StrandType.FORWARD) { drawFeatureForwardArrow(g, featureX1, featureYCommon, featureRowWidth1, featureRowHeightCommon); drawFeatureForwardRect(g, featureX2, featureYCommon, featureRowWidth2, featureRowHeightCommon); } else if(feature.strand == StrandType.BACKWARD) { drawFeatureBackwardRect(g, featureX1, featureYCommon, featureRowWidth1, featureRowHeightCommon); drawFeatureBackwardArrow(g, featureX2, featureYCommon, featureRowWidth2, featureRowHeightCommon); } } else { var bpStartMetrics:Rectangle = sequenceContentHolder.bpMetricsByIndex(startBP); var bpEndMetrics:Rectangle = sequenceContentHolder.bpMetricsByIndex(Math.min(endBP, contentHolder.sequenceProvider.sequence.length - 1)); var featureX:Number = bpStartMetrics.x + 2; // +2 to look pretty var featureY:Number = bpStartMetrics.y + row.sequenceMetrics.height + alignmentRowIndex * (DEFAULT_FEATURE_HEIGHT + DEFAULT_FEATURES_GAP) + DEFAULT_FEATURES_SEQUENCE_GAP; if(sequenceContentHolder.showAminoAcids1RevCom) { featureY += 3 * sequenceContentHolder.aminoAcidsTextRenderer.textHeight; } var featureRowWidth:Number = bpEndMetrics.x - bpStartMetrics.x + sequenceContentHolder.sequenceSymbolRenderer.textWidth; var featureRowHeight:Number = DEFAULT_FEATURE_HEIGHT; if(feature.strand == StrandType.UNKNOWN) { drawFeatureRect(g, featureX, featureY, featureRowWidth, featureRowHeight); } else if(feature.strand == StrandType.FORWARD) { if(feature.end >= row.rowData.start && feature.end <= row.rowData.end + 1) { drawFeatureForwardArrow(g, featureX, featureY, featureRowWidth, featureRowHeight); } else { drawFeatureForwardRect(g, featureX, featureY, featureRowWidth, featureRowHeight); } } else if(feature.strand == StrandType.BACKWARD) { if(feature.start >= row.rowData.start && feature.start <= row.rowData.end) { drawFeatureBackwardArrow(g, featureX, featureY, featureRowWidth, featureRowHeight); } else { drawFeatureBackwardRect(g, featureX, featureY, featureRowWidth, featureRowHeight); } } } g.endFill(); } } protected override function createToolTipLabel():void { tooltipLabel = feature.type + (feature.name == "" ? "" : (" - " + feature.name)) + ": " + (feature.start + 1) + ".." + (feature.end); } // Private Methods private function colorByType(featureType:String):int { var color:int = 0xCCCCCC; if(featureType == "promoter") { color = 0x31B440; } else if(featureType == "terminator"){ color = 0xF51600; } else if(featureType == "cds"){ color = 0xEF6500; } else if(featureType == "m_rna"){ color = 0xFFFF00; } else if(featureType == "misc_binding"){ color = 0x006FEF; } else if(featureType == "misc_feature"){ color = 0x006FEF; } else if(featureType == "misc_marker"){ color = 0x8DCEB1; } else if(featureType == "rep_origin"){ color = 0x878787; } return color; } private function drawFeatureRect(g:Graphics, x:Number, y:Number, width:Number, height:Number):void { g.drawRect(x, y, width, height); } private function drawFeatureForwardRect(g:Graphics, x:Number, y:Number, width:Number, height:Number):void { g.moveTo(x, y); g.curveTo(x + 3, y + height / 2, x, y + height); g.lineTo(x + width, y + height); g.lineTo(x + width, y); g.lineTo(x, y); } private function drawFeatureBackwardRect(g:Graphics, x:Number, y:Number, width:Number, height:Number):void { g.moveTo(x, y); g.lineTo(x, y + height); g.lineTo(x + width, y + height); g.curveTo(x + width - 3, y + height / 2, x + width, y); g.lineTo(x, y); } private function drawFeatureForwardArrow(g:Graphics, x:Number, y:Number, width:Number, height:Number):void { if(width > sequenceContentHolder.sequenceSymbolRenderer.width) { g.moveTo(x, y); g.lineTo(x + width - 8, y); g.lineTo(x + width, y + height / 2); g.lineTo(x + width - 8, y + height); g.lineTo(x, y + height); g.curveTo(x + 3, y + height / 2, x, y); } else { g.moveTo(x, y); g.lineTo(x + width, y + height / 2); g.lineTo(x, y + height); g.lineTo(x, y); } } private function drawFeatureBackwardArrow(g:Graphics, x:Number, y:Number, width:Number, height:Number):void { if(width > sequenceContentHolder.sequenceSymbolRenderer.width) { g.moveTo(x + 8, y); g.lineTo(x + width, y); g.curveTo(x + width - 3, y + height / 2, x + width, y + height); g.lineTo(x + 8, y + height); g.lineTo(x, y + height / 2); g.lineTo(x + 8, y); } else { g.moveTo(x, y + height / 2); g.lineTo(x + width, y); g.lineTo(x + width, y + height); g.lineTo(x, y + height / 2); } } } }
fix feature rendering bug
[VectorCommon] fix feature rendering bug git-svn-id: adbdea8fc1759bd16b0eaf24a244a7e5f870a654@280 fe3f0490-d73e-11de-a956-c71e7d3a9d2f
ActionScript
bsd-3-clause
CIDARLAB/mage-editor,CIDARLAB/mage-editor,CIDARLAB/mage-editor
00eddfe78da3d7e08d17598bea58e6515d053060
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/SimpleCSSStyles.as
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/SimpleCSSStyles.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 org.apache.flex.events.Event; import org.apache.flex.events.EventDispatcher; /** * The SimpleCSSStyles class contains CSS style * properties supported by SimpleCSSValuesImpl. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class SimpleCSSStyles { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function SimpleCSSStyles() { super(); } private var _object:IStyleableObject; /** * The object to which these styles apply. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get object():IStyleableObject { return _object; } /** * @private */ public function set object(value:IStyleableObject):void { if (_object != value) { _object = value; } } public var top:*; public var bottom:*; public var left:*; public var right:*; public var padding:*; public var paddingLeft:*; public var paddingRight:*; public var paddingTop:*; public var paddingBottom:*; public var horizontalCenter:*; public var verticalCenter:*; public var horizontalAlign:*; public var verticalAlign:*; public var fontFamily:*; public var fontSize:*; public var color:*; public var backgroundAlpha:*; public var backgroundColor:*; public var backgroundImage:*; public var borderColor:*; public var borderStyle:*; public var borderRadius:*; } }
//////////////////////////////////////////////////////////////////////////////// // // 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 org.apache.flex.events.Event; import org.apache.flex.events.EventDispatcher; /** * The SimpleCSSStyles class contains CSS style * properties supported by SimpleCSSValuesImpl. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class SimpleCSSStyles { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function SimpleCSSStyles() { super(); } private var _object:IStyleableObject; /** * The object to which these styles apply. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get object():IStyleableObject { return _object; } /** * @private */ public function set object(value:IStyleableObject):void { if (_object != value) { _object = value; } } public var top:*; public var bottom:*; public var left:*; public var right:*; public var padding:*; public var paddingLeft:*; public var paddingRight:*; public var paddingTop:*; public var paddingBottom:*; public var horizontalCenter:*; public var verticalCenter:*; public var horizontalAlign:*; public var verticalAlign:*; public var fontFamily:*; public var fontSize:*; public var color:*; public var fontWeight:*; public var fontStyle:*; public var backgroundAlpha:*; public var backgroundColor:*; public var backgroundImage:*; public var borderColor:*; public var borderStyle:*; public var borderRadius:*; } }
add a few more styles
add a few more styles
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
33da92c794779c3a707c106a66313e34e8a14578
test/org/igniterealtime/xiff/util/DateTimeParserTest.as
test/org/igniterealtime/xiff/util/DateTimeParserTest.as
/* * Copyright (C) 2003-2011 Igniterealtime Community Contributors * * Daniel Henninger * Derrick Grigg <[email protected]> * Juga Paazmaya <[email protected]> * Nick Velloff <[email protected]> * Sean Treadway <[email protected]> * Sean Voisen <[email protected]> * Mark Walters <[email protected]> * Michael McCarthy <[email protected]> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.igniterealtime.xiff.util { import org.flexunit.asserts.assertEquals; public class DateTimeParserTest { [Test] public function testDate2String():void { var date:Date = new Date( 2000, 10, 30, 0, 0 ); var dateAsString:String = DateTimeParser.date2string( date ); assertEquals( "2000-12-30", dateAsString ); } } }
/* * Copyright (C) 2003-2011 Igniterealtime Community Contributors * * Daniel Henninger * Derrick Grigg <[email protected]> * Juga Paazmaya <[email protected]> * Nick Velloff <[email protected]> * Sean Treadway <[email protected]> * Sean Voisen <[email protected]> * Mark Walters <[email protected]> * Michael McCarthy <[email protected]> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.igniterealtime.xiff.util { import org.flexunit.asserts.assertEquals; public class DateTimeParserTest { [Test] public function testDate2String():void { var date:Date = new Date( 2000, 10, 30, 0, 0 ); var dateAsString:String = DateTimeParser.date2string( date ); assertEquals( "2000-11-30", dateAsString ); } } }
Revert of commit test.
Revert of commit test. git-svn-id: c197267f952b24206666de142881703007ca05d5@12597 b35dd754-fafc-0310-a699-88a17e54d16e
ActionScript
apache-2.0
nazoking/xiff
bf9871bb05464e06971798717a2434984b651487
src/aerys/minko/scene/node/mesh/Mesh.as
src/aerys/minko/scene/node/mesh/Mesh.as
package aerys.minko.scene.node.mesh { import aerys.minko.ns.minko; import aerys.minko.ns.minko_stream; import aerys.minko.scene.action.mesh.MeshAction; import aerys.minko.scene.node.AbstractScene; import aerys.minko.type.stream.IVertexStream; import aerys.minko.type.stream.IndexStream; import aerys.minko.type.stream.VertexStream; import aerys.minko.type.stream.VertexStreamList; import aerys.minko.type.vertex.format.VertexComponent; import aerys.minko.type.vertex.format.VertexFormat; public class Mesh extends AbstractScene implements IMesh { use namespace minko; use namespace minko_stream; private static var _id : uint = 0; protected var _vertexStream : IVertexStream = null; protected var _indexStream : IndexStream = null; public function get version() : uint { return _vertexStream.version + _indexStream.version; } public function get vertexStream() : IVertexStream { return _vertexStream; } public function set vertexStream(value : IVertexStream) : void { _vertexStream = value; } public function get indexStream() : IndexStream { return _indexStream; } public function set indexStream(value : IndexStream) : void { _indexStream = value; } public function Mesh(vertexStream : IVertexStream = null, indexStream : IndexStream = null) { super(); _vertexStream = vertexStream; _indexStream = indexStream; initialize(); } private function initialize() : void { if (!_indexStream && _vertexStream) _indexStream = new IndexStream(null, vertexStream.length, vertexStream.dynamic); actions[0] = MeshAction.meshAction; } /** * Create a new copy of the Mesh object with the specified VertexFormat. * * <p> * If no VertexFormat is specified, the original VertexFormat of the Mesh * will be used. Calling the "clone" method and specifying a VertexFormat * is a good way to create a lighter Mesh by copying only the required * vertex components data. * </p> * * @param vertexFormat * @return * */ public function clone(vertexFormat : VertexFormat = null) : IMesh { vertexFormat ||= _vertexStream.format.clone(); var meshes : Vector.<IMesh> = Vector.<IMesh>([this]) var vertexComponents : Vector.<VertexComponent> = vertexFormat.componentList; var mergedMesh : IMesh = createMesh(meshes, vertexComponents, vertexFormat); return mergedMesh; } /** * The "mergeMeshes" method will takes multiple Mesh objects and will * merge all their data to create a single and only Mesh out of it. * * <p> * Because all the Mesh objects can have multiple VertexFormat, the * result Mesh VertexFormat will be the biggest common set of * VertexComponent of all the merged meshes. * </p> * * @param meshes * @return * */ public static function mergeMeshes(meshes : Vector.<IMesh>) : IMesh { var vertexFormat : VertexFormat = computeVertexFormat(meshes); var vertexComponents : Vector.<VertexComponent> = vertexFormat.componentList; var mergedMesh : IMesh = createMesh(meshes, vertexComponents, vertexFormat); return mergedMesh; } private static function computeVertexFormat(meshes : Vector.<IMesh>) : VertexFormat { var newVertexFormat : VertexFormat = meshes[0].vertexStream.format.clone(); for each (var mesh : IMesh in meshes) newVertexFormat.intersectWith(mesh.vertexStream.format); return newVertexFormat; } private static function createMesh(meshes : Vector.<IMesh>, vertexComponents : Vector.<VertexComponent>, vertexFormat : VertexFormat) : IMesh { var newIndexStreamData : Vector.<uint> = new Vector.<uint>(); var newVertexStreamData : Vector.<Number> = new Vector.<Number>(); var componentCount : uint = vertexComponents.length; var vertexComponentOffsets : Vector.<uint> = new Vector.<uint>(componentCount, true); var vertexComponentSizes : Vector.<uint> = new Vector.<uint>(componentCount, true); var vertexComponentDwordsPerVertex : Vector.<uint> = new Vector.<uint>(componentCount, true); var vertexComponentDatas : Vector.<Vector.<Number>> = new Vector.<Vector.<Number>>(componentCount, true); var meshCount : uint = meshes.length; for (var i : uint = 0; i < meshCount; ++i) { var mesh : IMesh = meshes[i]; // append index data var indexData : Vector.<uint> = mesh.indexStream.getIndices(); var indexCount : uint = indexData.length; var indexOffset : uint = newVertexStreamData.length / vertexFormat.dwordsPerVertex; for (var j : uint = 0; j < indexCount; ++j) newIndexStreamData.push(indexData[j] + indexOffset); // get offsets, sizes, and buffers for components in the current mesh. for (var k : uint = 0; k < componentCount; ++k) { var vertexComponent : VertexComponent = vertexComponents[k]; var vertexStream : VertexStream = mesh.vertexStream.getSubStreamByComponent(vertexComponent); vertexComponentOffsets[k] = vertexStream.format.getOffsetForComponent(vertexComponent); vertexComponentDwordsPerVertex[k] = vertexStream.format.dwordsPerVertex; vertexComponentSizes[k] = vertexComponent.dwords; vertexComponentDatas[k] = vertexStream._data; } // push vertex data into the new buffer. var vertexCount : uint = mesh.vertexStream.length; for (var vertexId : uint = 0; vertexId < vertexCount; ++vertexId) for (var componentId : uint = 0; componentId < componentCount; ++componentId) { var vertexData : Vector.<Number> = vertexComponentDatas[componentId]; var componentSize : uint = vertexComponentSizes[componentId]; var componentOffset : uint = vertexComponentOffsets[componentId] + vertexId * vertexComponentDwordsPerVertex[componentId]; var componentLimit : uint = componentSize + componentOffset; for (var n : uint = componentOffset; n < componentLimit; ++n) newVertexStreamData.push(vertexData[n]); } } var newIndexStream : IndexStream = new IndexStream(newIndexStreamData); var newVertexStream : VertexStream = new VertexStream(newVertexStreamData, vertexFormat); var newVertexStreamList : VertexStreamList = new VertexStreamList(newVertexStream); return new Mesh(newVertexStreamList, newIndexStream); } } }
package aerys.minko.scene.node.mesh { import aerys.minko.ns.minko; import aerys.minko.ns.minko_stream; import aerys.minko.scene.action.mesh.MeshAction; import aerys.minko.scene.node.AbstractScene; import aerys.minko.type.stream.IVertexStream; import aerys.minko.type.stream.IndexStream; import aerys.minko.type.stream.VertexStream; import aerys.minko.type.stream.VertexStreamList; import aerys.minko.type.vertex.format.VertexComponent; import aerys.minko.type.vertex.format.VertexFormat; public class Mesh extends AbstractScene implements IMesh { use namespace minko; use namespace minko_stream; private static var _id : uint = 0; protected var _vertexStream : IVertexStream = null; protected var _indexStream : IndexStream = null; public function get version() : uint { return _vertexStream.version + _indexStream.version; } public function get vertexStream() : IVertexStream { return _vertexStream; } public function set vertexStream(value : IVertexStream) : void { _vertexStream = value; } public function get indexStream() : IndexStream { return _indexStream; } public function set indexStream(value : IndexStream) : void { _indexStream = value; } public function Mesh(vertexStream : IVertexStream = null, indexStream : IndexStream = null) { super(); _vertexStream = vertexStream; _indexStream = indexStream; initialize(); } private function initialize() : void { if (!_indexStream && _vertexStream) _indexStream = new IndexStream(null, vertexStream.length, vertexStream.dynamic); actions[0] = MeshAction.meshAction; } /** * Create a new copy of the Mesh object with the specified VertexFormat. * * <p> * If no VertexFormat is specified, the original VertexFormat of the Mesh * will be used. Calling the "clone" method and specifying a VertexFormat * is a good way to create a lighter Mesh by copying only the required * vertex components data. * </p> * * @param vertexFormat * @return * */ public function clone(vertexFormat : VertexFormat = null) : IMesh { vertexFormat ||= _vertexStream.format.clone(); var meshes : Vector.<IMesh> = Vector.<IMesh>([this]) var mergedMesh : IMesh = createMesh(meshes, vertexFormat); return mergedMesh; } /** * The "mergeMeshes" method will takes multiple Mesh objects and will * merge all their data to create a single and only Mesh out of it. * * <p> * Because all the Mesh objects can have multiple VertexFormat, the * result Mesh VertexFormat will be the biggest common set of * VertexComponent of all the merged meshes. * </p> * * @param meshes * @return * */ public static function mergeMeshes(meshes : Vector.<IMesh>) : IMesh { // insersect all meshes vertexformats var numMeshes : uint = meshes.length; var vertexFormat : VertexFormat = meshes[0].vertexStream.format.clone(); for (var meshId : uint = 1; meshId < numMeshes; ++meshId) { var mesh : IMesh = meshes[meshId]; vertexFormat.intersectWith(mesh.vertexStream.format); } var vertexComponents : Vector.<VertexComponent> = vertexFormat.componentList; var mergedMesh : IMesh = createMesh(meshes, vertexFormat); return mergedMesh; } private static function createMesh(meshes : Vector.<IMesh>, vertexFormat : VertexFormat) : IMesh { var newIndexStreamData : Vector.<uint> = new Vector.<uint>(); var newVertexStreamData : Vector.<Number> = new Vector.<Number>(); var components : Vector.<VertexComponent> = vertexFormat.componentList; var componentCount : uint = components.length; var componentOffsets : Vector.<uint> = new Vector.<uint>(componentCount, true); var componentSizes : Vector.<uint> = new Vector.<uint>(componentCount, true); var componentDwordsPerVertex : Vector.<uint> = new Vector.<uint>(componentCount, true); var componentDatas : Vector.<Vector.<Number>> = new Vector.<Vector.<Number>>(componentCount, true); var meshCount : uint = meshes.length; for (var i : uint = 0; i < meshCount; ++i) { var mesh : IMesh = meshes[i]; var vertexStream : IVertexStream = mesh.vertexStream; // append index data var indexData : Vector.<uint> = mesh.indexStream.getIndices(); var indexCount : uint = indexData.length; var indexOffset : uint = newVertexStreamData.length / vertexFormat.dwordsPerVertex; for (var j : uint = 0; j < indexCount; ++j) newIndexStreamData.push(indexData[j] + indexOffset); // get offsets, sizes, and buffers for components in the current mesh. for (var k : uint = 0; k < componentCount; ++k) { var vertexComponent : VertexComponent = components[k]; var subVertexStream : VertexStream = vertexStream.getSubStreamByComponent(vertexComponent); var subvertexFormat : VertexFormat = subVertexStream.format; componentOffsets[k] = subvertexFormat.getOffsetForComponent(vertexComponent); componentDwordsPerVertex[k] = subvertexFormat.dwordsPerVertex; componentSizes[k] = vertexComponent.dwords; componentDatas[k] = subVertexStream._data; } // push vertex data into the new buffer. var vertexCount : uint = mesh.vertexStream.length; for (var vertexId : uint = 0; vertexId < vertexCount; ++vertexId) for (var componentId : uint = 0; componentId < componentCount; ++componentId) { var vertexData : Vector.<Number> = componentDatas[componentId]; var componentSize : uint = componentSizes[componentId]; var componentOffset : uint = componentOffsets[componentId] + vertexId * componentDwordsPerVertex[componentId]; var componentLimit : uint = componentSize + componentOffset; for (var n : uint = componentOffset; n < componentLimit; ++n) newVertexStreamData.push(vertexData[n]); } } var newIndexStream : IndexStream = new IndexStream(newIndexStreamData); var newVertexStream : VertexStream = new VertexStream(newVertexStreamData, vertexFormat); var newVertexStreamList : VertexStreamList = new VertexStreamList(newVertexStream); return new Mesh(newVertexStreamList, newIndexStream); } } }
Optimize mesh cloning and merging.
Optimize mesh cloning and merging.
ActionScript
mit
aerys/minko-as3
b8f7e15d0444058acbc7e4df065653c4314f71e1
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; // public static var debugLogger:Boolean = false; //not used 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"; public static var config:Object = { 'buffer': 3, 'connectionTimeout': 10, 'scaleUp': false, 'allowFullscreen': true, 'debugLogger': 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; 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("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 { 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; } } } 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):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; 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)); 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.META, onMeta); client.start(); this.newPlaylistItem = false; } public function seek(position:String):void{ if (!client || !client.seek(Number(position))) { ErrorManager.dispatchError(828); } } 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.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 }; 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 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 = null; this.callAPI(EVENT_STREAM_STOPPED); /* If a new `play` has been queued, fire it */ if (this.newPlaylistItem) { start(); } } 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"; public static var config:Object = { 'buffer': 3, 'connectionTimeout': 10, 'scaleUp': false, 'allowFullscreen': true, 'debugLogger': 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; 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("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 { 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; } } } 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):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; 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)); 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.META, onMeta); client.start(); this.newPlaylistItem = false; } public function seek(position:String):void{ if (!client || !client.seek(Number(position))) { ErrorManager.dispatchError(828); } } 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.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 }; 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 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 = null; this.callAPI(EVENT_STREAM_STOPPED); /* If a new `play` has been queued, fire it */ if (this.newPlaylistItem) { start(); } } 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); } } } }
remove unused commented out variable Player::debugLogger
remove unused commented out variable Player::debugLogger
ActionScript
bsd-3-clause
AxisCommunications/locomote-video-player,gaetancollaud/locomote-video-player
56d67ccf3e4436437875cf3562ce508142804e36
frameworks/projects/framework/src/mx/binding/Binding.as
frameworks/projects/framework/src/mx/binding/Binding.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.binding { import mx.collections.errors.ItemPendingError; import mx.core.mx_internal; import flash.utils.Dictionary; use namespace mx_internal; [ExcludeClass] /** * @private */ public class Binding { include "../core/Version.as"; // Certain errors are normal during binding execution, so we swallow them. // 1507 - invalid null argument // 2005 - argument error (null gets converted to 0) mx_internal static var allowedErrors:Object = generateAllowedErrors(); mx_internal static function generateAllowedErrors():Object { var o:Object = {}; o[1507] = 1; o[2005] = 1; return o; } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Create a Binding object * * @param document The document that is the target of all of this work. * * @param srcFunc The function that returns us the value * to use in this Binding. * * @param destFunc The function that will take a value * and assign it to the destination. * * @param destString The destination represented as a String. * We can then tell the ValidationManager to validate this field. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function Binding(document:Object, srcFunc:Function, destFunc:Function, destString:String, srcString:String = null) { super(); this.document = document; this.srcFunc = srcFunc; this.destFunc = destFunc; this.destString = destString; this.srcString = srcString; this.destFuncFailed = false; if (this.srcFunc == null) { this.srcFunc = defaultSrcFunc; } if (this.destFunc == null) { this.destFunc = defaultDestFunc; } _isEnabled = true; isExecuting = false; isHandlingEvent = false; hasHadValue = false; uiComponentWatcher = -1; BindingManager.addBinding(document, destString, this); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Internal storage for isEnabled property. */ mx_internal var _isEnabled:Boolean; /** * @private * Indicates that a Binding is enabled. * Used to disable bindings. */ mx_internal function get isEnabled():Boolean { return _isEnabled; } /** * @private */ mx_internal function set isEnabled(value:Boolean):void { _isEnabled = value; if (value) { processDisabledRequests(); } } /** * @private * Indicates that a Binding is executing. * Used to prevent circular bindings from causing infinite loops. */ mx_internal var isExecuting:Boolean; /** * @private * Indicates that the binding is currently handling an event. * Used to prevent us from infinitely causing an event * that re-executes the the binding. */ mx_internal var isHandlingEvent:Boolean; /** * @private * Queue of watchers that fired while we were disabled. * We will resynch with our binding if isEnabled is set to true * and one or more of our watchers fired while we were disabled. */ mx_internal var disabledRequests:Dictionary; /** * @private * True as soon as a non-null or non-empty-string value has been used. * We don't auto-validate until this is true */ private var hasHadValue:Boolean; /** * @private * This is no longer used in Flex 3.0, but it is required to load * Flex 2.0.0 and Flex 2.0.1 modules. */ public var uiComponentWatcher:int; /** * @private * It's possible that there is a two-way binding set up, in which case * we'll do a rudimentary optimization by not executing ourselves * if our counterpart is already executing. */ public var twoWayCounterpart:Binding; /** * @private * If there is a twoWayCounterpart, hasHadValue is false, and * isTwoWayPrimary is true, then the twoWayCounterpart will be * executed first. */ public var isTwoWayPrimary:Boolean; /** * @private * True if a wrapped function call does not throw an error. This is used by * innerExecute() to tell if the srcFunc completed successfully. */ private var wrappedFunctionSuccessful:Boolean; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** * All Bindings hang off of a document for now, * but really it's just the root of where these functions live. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var document:Object; /** * The function that will return us the value. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var srcFunc:Function; /** * The function that takes the value and assigns it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var destFunc:Function; /** * @private */ mx_internal var destFuncFailed:Boolean; /** * The destination represented as a String. * This will be used so we can signal validation on a field. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var destString:String; /** * The source represented as a String. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 4 */ mx_internal var srcString:String; /** * @private * Used to suppress calls to destFunc when incoming value is either * a) an XML node identical to the previously assigned XML node, or * b) an XMLList containing the identical node sequence as the previously assigned XMLList */ private var lastValue:Object; //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- private function defaultDestFunc(value:Object):void { var chain:Array = destString.split("."); var element:Object = document; var i:uint = 0; if (chain[0] == "this") { i++; } while (i < (chain.length - 1)) { element = element[chain[i++]]; //if the element does not exist : avoid exception as it's heavy on memory allocations if(element == null || element == undefined) { destFuncFailed = true; if (BindingManager.debugDestinationStrings[destString]) { trace("Binding: destString = " + destString + ", error = 1009"); } return; } } element[chain[i]] = value; } private function defaultSrcFunc():Object { return document[srcString]; } /** * Execute the binding. * Call the source function and get the value we'll use. * Then call the destination function passing the value as an argument. * Finally try to validate the destination. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function execute(o:Object = null):void { if (!isEnabled) { if (o != null) { registerDisabledExecute(o); } return; } if (twoWayCounterpart && !twoWayCounterpart.hasHadValue && twoWayCounterpart.isTwoWayPrimary) { twoWayCounterpart.execute(); hasHadValue = true; return; } if (isExecuting || (twoWayCounterpart && twoWayCounterpart.isExecuting)) { // If there is a twoWayCounterpart already executing, that means that it is // assigning something of value so even though we won't execute we should be // sure to mark ourselves as having had a value so that future executions will // be correct. If isExecuting is true but we re-entered, that means we // clearly had a value so setting hasHadValue is safe. hasHadValue = true; return; } try { isExecuting = true; wrapFunctionCall(this, innerExecute, o); } catch(error:Error) { if (allowedErrors[error.errorID] == null) throw error; } finally { isExecuting = false; } } /** * @private * Take note of any execute request that occur when we are disabled. */ private function registerDisabledExecute(o:Object):void { if (o != null) { disabledRequests = (disabledRequests != null) ? disabledRequests : new Dictionary(true); disabledRequests[o] = true; } } /** * @private * Resynch with any watchers that may have updated while we were disabled. */ private function processDisabledRequests():void { if (disabledRequests != null) { for (var key:Object in disabledRequests) { execute(key); } disabledRequests = null; } } /** * @private * Note: use of this wrapper needs to be reexamined. Currently there's at least one situation where a * wrapped function invokes another wrapped function, which is unnecessary (i.e., only the inner function * will throw), and also risks future errors due to the 'wrappedFunctionSuccessful' member variable * being stepped on. Leaving alone for now to minimize pre-GMC volatility, but should be revisited for * an early dot release. * Also note that the set of suppressed error codes below is repeated verbatim in Watcher.wrapUpdate. * These need to be consolidated and the motivations for each need to be documented. */ protected function wrapFunctionCall(thisArg:Object, wrappedFunction:Function, object:Object = null, ...args):Object { wrappedFunctionSuccessful = false; try { var result:Object = wrappedFunction.apply(thisArg, args); if(destFuncFailed == true) { destFuncFailed = false; return null; } wrappedFunctionSuccessful = true; return result; } catch(itemPendingError:ItemPendingError) { itemPendingError.addResponder(new EvalBindingResponder(this, object)); if (BindingManager.debugDestinationStrings[destString]) { trace("Binding: destString = " + destString + ", error = " + itemPendingError); } } catch(rangeError:RangeError) { if (BindingManager.debugDestinationStrings[destString]) { trace("Binding: destString = " + destString + ", error = " + rangeError); } } catch(error:Error) { // Certain errors are normal when executing a srcFunc or destFunc, // so we swallow them: // Error #1006: Call attempted on an object that is not a function. // Error #1009: null has no properties. // Error #1010: undefined has no properties. // Error #1055: - has no properties. // Error #1069: Property - not found on - and there is no default value // We allow any other errors to be thrown. if ((error.errorID != 1006) && (error.errorID != 1009) && (error.errorID != 1010) && (error.errorID != 1055) && (error.errorID != 1069)) { throw error; } else { if (BindingManager.debugDestinationStrings[destString]) { trace("Binding: destString = " + destString + ", error = " + error); } } } return null; } /** * @private * true iff XMLLists x and y contain the same node sequence. */ private function nodeSeqEqual(x:XMLList, y:XMLList):Boolean { var n:uint = x.length(); if (n == y.length()) { for (var i:uint = 0; i < n && x[i] === y[i]; i++) { } return i == n; } else { return false; } } /** * @private */ private function innerExecute():void { destFuncFailed = false; var value:Object = wrapFunctionCall(document, srcFunc); if (BindingManager.debugDestinationStrings[destString]) { trace("Binding: destString = " + destString + ", srcFunc result = " + value); } if (hasHadValue || wrappedFunctionSuccessful) { // Suppress binding assignments on non-simple XML: identical single nodes, or // lists over identical node sequences. // Note: outer tests are inline for efficiency if (!(lastValue is XML && lastValue.hasComplexContent() && lastValue === value) && !(lastValue is XMLList && lastValue.hasComplexContent() && value is XMLList && nodeSeqEqual(lastValue as XMLList, value as XMLList))) { destFunc.call(document, value); if(destFuncFailed == false) { // Note: state is not updated if destFunc throws lastValue = value; hasHadValue = true; } } } } /** * This function is called when one of this binding's watchers * detects a property change. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function watcherFired(commitEvent:Boolean, cloneIndex:int):void { if (isHandlingEvent) return; try { isHandlingEvent = true; execute(cloneIndex); } finally { isHandlingEvent = false; } } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.binding { import mx.collections.errors.ItemPendingError; import mx.core.mx_internal; import flash.utils.Dictionary; use namespace mx_internal; [ExcludeClass] /** * @private */ public class Binding { include "../core/Version.as"; // Certain errors are normal during binding execution, so we swallow them. // 1507 - invalid null argument // 2005 - argument error (null gets converted to 0) mx_internal static var allowedErrors:Object = generateAllowedErrors(); mx_internal static function generateAllowedErrors():Object { var o:Object = {}; o[1507] = 1; o[2005] = 1; return o; } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Create a Binding object * * @param document The document that is the target of all of this work. * * @param srcFunc The function that returns us the value * to use in this Binding. * * @param destFunc The function that will take a value * and assign it to the destination. * * @param destString The destination represented as a String. * We can then tell the ValidationManager to validate this field. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function Binding(document:Object, srcFunc:Function, destFunc:Function, destString:String, srcString:String = null) { super(); this.document = document; this.srcFunc = srcFunc; this.destFunc = destFunc; this.destString = destString; this.srcString = srcString; this.destFuncFailed = false; if (this.srcFunc == null) { this.srcFunc = defaultSrcFunc; } if (this.destFunc == null) { this.destFunc = defaultDestFunc; } _isEnabled = true; isExecuting = false; isHandlingEvent = false; hasHadValue = false; uiComponentWatcher = -1; BindingManager.addBinding(document, destString, this); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Internal storage for isEnabled property. */ mx_internal var _isEnabled:Boolean; /** * @private * Indicates that a Binding is enabled. * Used to disable bindings. */ mx_internal function get isEnabled():Boolean { return _isEnabled; } /** * @private */ mx_internal function set isEnabled(value:Boolean):void { _isEnabled = value; if (value) { processDisabledRequests(); } } /** * @private * Indicates that a Binding is executing. * Used to prevent circular bindings from causing infinite loops. */ mx_internal var isExecuting:Boolean; /** * @private * Indicates that the binding is currently handling an event. * Used to prevent us from infinitely causing an event * that re-executes the the binding. */ mx_internal var isHandlingEvent:Boolean; /** * @private * Queue of watchers that fired while we were disabled. * We will resynch with our binding if isEnabled is set to true * and one or more of our watchers fired while we were disabled. */ mx_internal var disabledRequests:Dictionary; /** * @private * True as soon as a non-null or non-empty-string value has been used. * We don't auto-validate until this is true */ private var hasHadValue:Boolean; /** * @private * This is no longer used in Flex 3.0, but it is required to load * Flex 2.0.0 and Flex 2.0.1 modules. */ public var uiComponentWatcher:int; /** * @private * It's possible that there is a two-way binding set up, in which case * we'll do a rudimentary optimization by not executing ourselves * if our counterpart is already executing. */ public var twoWayCounterpart:Binding; /** * @private * If there is a twoWayCounterpart, hasHadValue is false, and * isTwoWayPrimary is true, then the twoWayCounterpart will be * executed first. */ public var isTwoWayPrimary:Boolean; /** * @private * True if a wrapped function call does not throw an error. This is used by * innerExecute() to tell if the srcFunc completed successfully. */ private var wrappedFunctionSuccessful:Boolean; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** * All Bindings hang off of a document for now, * but really it's just the root of where these functions live. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var document:Object; /** * The function that will return us the value. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var srcFunc:Function; /** * The function that takes the value and assigns it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var destFunc:Function; /** * @private */ mx_internal var destFuncFailed:Boolean; /** * The destination represented as a String. * This will be used so we can signal validation on a field. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var destString:String; /** * The source represented as a String. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 4 */ mx_internal var srcString:String; /** * @private * Used to suppress calls to destFunc when incoming value is either * a) an XML node identical to the previously assigned XML node, or * b) an XMLList containing the identical node sequence as the previously assigned XMLList */ private var lastValue:Object; //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- private function defaultDestFunc(value:Object):void { var chain:Array = destString.split("."); var element:Object = document; var i:uint = 0; if (chain[0] == "this") { i++; } while (i < (chain.length - 1)) { element = element[chain[i++]]; //if the element does not exist : avoid exception as it's heavy on memory allocations if (element == null) { destFuncFailed = true; if (BindingManager.debugDestinationStrings[destString]) { trace("Binding: destString = " + destString + ", error = 1009"); } return; } } element[chain[i]] = value; } private function defaultSrcFunc():Object { return document[srcString]; } /** * Execute the binding. * Call the source function and get the value we'll use. * Then call the destination function passing the value as an argument. * Finally try to validate the destination. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function execute(o:Object = null):void { if (!isEnabled) { if (o != null) { registerDisabledExecute(o); } return; } if (twoWayCounterpart && !twoWayCounterpart.hasHadValue && twoWayCounterpart.isTwoWayPrimary) { twoWayCounterpart.execute(); hasHadValue = true; return; } if (isExecuting || (twoWayCounterpart && twoWayCounterpart.isExecuting)) { // If there is a twoWayCounterpart already executing, that means that it is // assigning something of value so even though we won't execute we should be // sure to mark ourselves as having had a value so that future executions will // be correct. If isExecuting is true but we re-entered, that means we // clearly had a value so setting hasHadValue is safe. hasHadValue = true; return; } try { isExecuting = true; wrapFunctionCall(this, innerExecute, o); } catch(error:Error) { if (allowedErrors[error.errorID] == null) throw error; } finally { isExecuting = false; } } /** * @private * Take note of any execute request that occur when we are disabled. */ private function registerDisabledExecute(o:Object):void { if (o != null) { disabledRequests = (disabledRequests != null) ? disabledRequests : new Dictionary(true); disabledRequests[o] = true; } } /** * @private * Resynch with any watchers that may have updated while we were disabled. */ private function processDisabledRequests():void { if (disabledRequests != null) { for (var key:Object in disabledRequests) { execute(key); } disabledRequests = null; } } /** * @private * Note: use of this wrapper needs to be reexamined. Currently there's at least one situation where a * wrapped function invokes another wrapped function, which is unnecessary (i.e., only the inner function * will throw), and also risks future errors due to the 'wrappedFunctionSuccessful' member variable * being stepped on. Leaving alone for now to minimize pre-GMC volatility, but should be revisited for * an early dot release. * Also note that the set of suppressed error codes below is repeated verbatim in Watcher.wrapUpdate. * These need to be consolidated and the motivations for each need to be documented. */ protected function wrapFunctionCall(thisArg:Object, wrappedFunction:Function, object:Object = null, ...args):Object { wrappedFunctionSuccessful = false; try { var result:Object = wrappedFunction.apply(thisArg, args); if(destFuncFailed == true) { destFuncFailed = false; return null; } wrappedFunctionSuccessful = true; return result; } catch(itemPendingError:ItemPendingError) { itemPendingError.addResponder(new EvalBindingResponder(this, object)); if (BindingManager.debugDestinationStrings[destString]) { trace("Binding: destString = " + destString + ", error = " + itemPendingError); } } catch(rangeError:RangeError) { if (BindingManager.debugDestinationStrings[destString]) { trace("Binding: destString = " + destString + ", error = " + rangeError); } } catch(error:Error) { // Certain errors are normal when executing a srcFunc or destFunc, // so we swallow them: // Error #1006: Call attempted on an object that is not a function. // Error #1009: null has no properties. // Error #1010: undefined has no properties. // Error #1055: - has no properties. // Error #1069: Property - not found on - and there is no default value // We allow any other errors to be thrown. if ((error.errorID != 1006) && (error.errorID != 1009) && (error.errorID != 1010) && (error.errorID != 1055) && (error.errorID != 1069)) { throw error; } else { if (BindingManager.debugDestinationStrings[destString]) { trace("Binding: destString = " + destString + ", error = " + error); } } } return null; } /** * @private * true iff XMLLists x and y contain the same node sequence. */ private function nodeSeqEqual(x:XMLList, y:XMLList):Boolean { var n:uint = x.length(); if (n == y.length()) { for (var i:uint = 0; i < n && x[i] === y[i]; i++) { } return i == n; } else { return false; } } /** * @private */ private function innerExecute():void { destFuncFailed = false; var value:Object = wrapFunctionCall(document, srcFunc); if (BindingManager.debugDestinationStrings[destString]) { trace("Binding: destString = " + destString + ", srcFunc result = " + value); } if (hasHadValue || wrappedFunctionSuccessful) { // Suppress binding assignments on non-simple XML: identical single nodes, or // lists over identical node sequences. // Note: outer tests are inline for efficiency if (!(lastValue is XML && lastValue.hasComplexContent() && lastValue === value) && !(lastValue is XMLList && lastValue.hasComplexContent() && value is XMLList && nodeSeqEqual(lastValue as XMLList, value as XMLList))) { destFunc.call(document, value); if(destFuncFailed == false) { // Note: state is not updated if destFunc throws lastValue = value; hasHadValue = true; } } } } /** * This function is called when one of this binding's watchers * detects a property change. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function watcherFired(commitEvent:Boolean, cloneIndex:int):void { if (isHandlingEvent) return; try { isHandlingEvent = true; execute(cloneIndex); } finally { isHandlingEvent = false; } } } }
Remove compiler warning
Remove compiler warning
ActionScript
apache-2.0
shyamalschandra/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk
b2851541f9286a485576237f0377983854ff2aa9
src/aerys/minko/type/interpolation/BezierCubicSegment.as
src/aerys/minko/type/interpolation/BezierCubicSegment.as
package aerys.minko.type.interpolation { import aerys.minko.type.math.Vector4; import mx.validators.ValidationResult; public class BezierCubicSegment extends AbstractBezierSegment { protected var _control1 : Vector4; protected var _control2 : Vector4; private var _diff10 : Vector4 = null; private var _diff21 : Vector4 = null; private var _diff30 : Vector4 = null; override public function get firstControl() : Vector4 { return _control1; } override public function get lastControl() : Vector4 { return _control2; } override public function set start(value : Vector4) : void { super._start = value; _length = NaN; _dirty = true; } override public function set end(value : Vector4) : void { super._end = value; _length = NaN; _dirty = true; } public function set control1(value : Vector4) : void { _control1 = value; _length = NaN; _dirty = true; } public function set control2(value : Vector4) : void { _control2 = value; _length = NaN; _dirty = true; } public function BezierCubicSegment(start : Vector4, control1 : Vector4, control2 : Vector4, end : Vector4, at : Vector4 = null, up : Vector4 = null) { super(start, end, at, up); _control1 = control1; _control2 = control2; _diff10 = new Vector4(); _diff21 = new Vector4(); _diff30 = new Vector4(); _dirty = true; } override public function clone() : IInterpolation { return new BezierCubicSegment( _start.clone(), _control1.clone(), _control2.clone(), _end.clone(), _at.clone(), _up.clone() ); } override protected function updatePrecomputedTerms() : void { Vector4.subtract(_control1, _start, _diff10); Vector4.subtract(_control2, _control1, _diff21); Vector4.subtract(_end, _start, _diff30); _dirty = false; _tmpPosT = -1; _tmpPointAtT = -1; _tmpTangentT = -1; _length = NaN; } override protected function updatePosition(t : Number) : void { if (_dirty) updatePrecomputedTerms(); if (Math.abs(t - _tmpPosT) < 1e-6) return; _tmpPos.set( _start.x + t * ( 3 * _diff10.x + t * ( 3 * (_diff21.x - _diff10.x) + t * ( _diff30.x - 3 * _diff21.x ) ) ), _start.y + t * ( 3 * _diff10.y + t * ( 3 * (_diff21.y - _diff10.y) + t * ( _diff30.y - 3 * _diff21.y ) ) ), _start.z + t * ( 3 * _diff10.z + t * ( 3 * (_diff21.z - _diff10.z) + t * ( _diff30.z - 3 * _diff21.z ) ) ), _start.w + t * ( 3 * _diff10.w + t * ( 3 * (_diff21.w - _diff10.w) + t * ( _diff30.w - 3 * _diff21.w ) ) ) ); /* var term1 : Number = (1 - t) * (1 - t) * (1 - t); var term2 : Number = 3 * t * (1 - t) * (1 - t); var term3 : Number = 3 * t * t * (1 - t); var term4 : Number = t * t * t * t; _tmpPos.set( term1 * _start.x + term2 * _control1.x + term3 * _control2.x + term4 * _end.x, term1 * _start.y + term2 * _control1.y + term3 * _control2.y + term4 * _end.y, term1 * _start.z + term2 * _control1.z + term3 * _control2.z + term4 * _end.z, term1 * _start.w + term2 * _control1.w + term3 * _control2.w + term4 * _end.w ); */ _tmpPosT = t; } override protected function updateTangent(t : Number) : void { if (_dirty) updatePrecomputedTerms(); if (Math.abs(t - _tmpTangentT) < 1e-6) return; _tmpTangent.set( 3 * ( _diff10.x + t * ( 2 * (_diff21.x - _diff10.x) + t * (_diff30.x - 3 * _diff21.x) ) ), 3 * ( _diff10.y + t * ( 2 * (_diff21.y - _diff10.y) + t * (_diff30.y - 3 * _diff21.y) ) ), 3 * ( _diff10.z + t * ( 2 * (_diff21.z - _diff10.z) + t * (_diff30.z - 3 * _diff21.z) ) ), 3 * ( _diff10.w + t * ( 2 * (_diff21.w - _diff10.w) + t * (_diff30.w - 3 * _diff21.w) ) ) ).normalize(); /* var dTerm1_dT : Number = - 3 * (1 - t) * (1 - t); var dTerm2_dT : Number = 6 * (1 - t); var dTerm3_dT : Number = 3 * t * (2 - 3 * t * t); var dTerm4_dT : Number = 3 * t * t; _tmpTangent.set( dTerm1_dT * _start.x + dTerm2_dT * _control1.x + dTerm3_dT * _control2.x + dTerm4_dT * _end.x, dTerm1_dT * _start.y + dTerm2_dT * _control1.y + dTerm3_dT * _control2.y + dTerm4_dT * _end.y, dTerm1_dT * _start.z + dTerm2_dT * _control1.z + dTerm3_dT * _control2.z + dTerm4_dT * _end.z, dTerm1_dT * _start.w + dTerm2_dT * _control1.w + dTerm3_dT * _control2.w + dTerm4_dT * _end.w ).normalize(); */ _tmpTangentT = t; } override protected function updatePointAt(t : Number) : void { if (_dirty) updatePrecomputedTerms(); super.updatePointAt(t); } } }
package aerys.minko.type.interpolation { import aerys.minko.type.math.Vector4; public class BezierCubicSegment extends AbstractBezierSegment { protected var _control1 : Vector4; protected var _control2 : Vector4; private var _diff10 : Vector4 = null; private var _diff21 : Vector4 = null; private var _diff30 : Vector4 = null; override public function get firstControl() : Vector4 { return _control1; } override public function get lastControl() : Vector4 { return _control2; } override public function set start(value : Vector4) : void { super._start = value; _length = NaN; _dirty = true; } override public function set end(value : Vector4) : void { super._end = value; _length = NaN; _dirty = true; } public function set control1(value : Vector4) : void { _control1 = value; _length = NaN; _dirty = true; } public function set control2(value : Vector4) : void { _control2 = value; _length = NaN; _dirty = true; } public function BezierCubicSegment(start : Vector4, control1 : Vector4, control2 : Vector4, end : Vector4, at : Vector4 = null, up : Vector4 = null) { super(start, end, at, up); _control1 = control1; _control2 = control2; _diff10 = new Vector4(); _diff21 = new Vector4(); _diff30 = new Vector4(); _dirty = true; } override public function clone() : IInterpolation { return new BezierCubicSegment( _start.clone(), _control1.clone(), _control2.clone(), _end.clone(), _at.clone(), _up.clone() ); } override protected function updatePrecomputedTerms() : void { Vector4.subtract(_control1, _start, _diff10); Vector4.subtract(_control2, _control1, _diff21); Vector4.subtract(_end, _start, _diff30); _dirty = false; _tmpPosT = -1; _tmpPointAtT = -1; _tmpTangentT = -1; _length = NaN; } override protected function updatePosition(t : Number) : void { if (_dirty) updatePrecomputedTerms(); if (Math.abs(t - _tmpPosT) < 1e-6) return; _tmpPos.set( _start.x + t * ( 3 * _diff10.x + t * ( 3 * (_diff21.x - _diff10.x) + t * ( _diff30.x - 3 * _diff21.x ) ) ), _start.y + t * ( 3 * _diff10.y + t * ( 3 * (_diff21.y - _diff10.y) + t * ( _diff30.y - 3 * _diff21.y ) ) ), _start.z + t * ( 3 * _diff10.z + t * ( 3 * (_diff21.z - _diff10.z) + t * ( _diff30.z - 3 * _diff21.z ) ) ), _start.w + t * ( 3 * _diff10.w + t * ( 3 * (_diff21.w - _diff10.w) + t * ( _diff30.w - 3 * _diff21.w ) ) ) ); /* var term1 : Number = (1 - t) * (1 - t) * (1 - t); var term2 : Number = 3 * t * (1 - t) * (1 - t); var term3 : Number = 3 * t * t * (1 - t); var term4 : Number = t * t * t * t; _tmpPos.set( term1 * _start.x + term2 * _control1.x + term3 * _control2.x + term4 * _end.x, term1 * _start.y + term2 * _control1.y + term3 * _control2.y + term4 * _end.y, term1 * _start.z + term2 * _control1.z + term3 * _control2.z + term4 * _end.z, term1 * _start.w + term2 * _control1.w + term3 * _control2.w + term4 * _end.w ); */ _tmpPosT = t; } override protected function updateTangent(t : Number) : void { if (_dirty) updatePrecomputedTerms(); if (Math.abs(t - _tmpTangentT) < 1e-6) return; _tmpTangent.set( 3 * ( _diff10.x + t * ( 2 * (_diff21.x - _diff10.x) + t * (_diff30.x - 3 * _diff21.x) ) ), 3 * ( _diff10.y + t * ( 2 * (_diff21.y - _diff10.y) + t * (_diff30.y - 3 * _diff21.y) ) ), 3 * ( _diff10.z + t * ( 2 * (_diff21.z - _diff10.z) + t * (_diff30.z - 3 * _diff21.z) ) ), 3 * ( _diff10.w + t * ( 2 * (_diff21.w - _diff10.w) + t * (_diff30.w - 3 * _diff21.w) ) ) ).normalize(); /* var dTerm1_dT : Number = - 3 * (1 - t) * (1 - t); var dTerm2_dT : Number = 6 * (1 - t); var dTerm3_dT : Number = 3 * t * (2 - 3 * t * t); var dTerm4_dT : Number = 3 * t * t; _tmpTangent.set( dTerm1_dT * _start.x + dTerm2_dT * _control1.x + dTerm3_dT * _control2.x + dTerm4_dT * _end.x, dTerm1_dT * _start.y + dTerm2_dT * _control1.y + dTerm3_dT * _control2.y + dTerm4_dT * _end.y, dTerm1_dT * _start.z + dTerm2_dT * _control1.z + dTerm3_dT * _control2.z + dTerm4_dT * _end.z, dTerm1_dT * _start.w + dTerm2_dT * _control1.w + dTerm3_dT * _control2.w + dTerm4_dT * _end.w ).normalize(); */ _tmpTangentT = t; } override protected function updatePointAt(t : Number) : void { if (_dirty) updatePrecomputedTerms(); super.updatePointAt(t); } } }
Remove invalid import.
Remove invalid import.
ActionScript
mit
aerys/minko-as3
e1e69eb65c145d6dc14e43d98da5d73ec0585206
WeaveASJS/src/weavejs/data/source/WebSocketDataSource.as
WeaveASJS/src/weavejs/data/source/WebSocketDataSource.as
/* ***** BEGIN LICENSE BLOCK ***** * * This file is part of Weave. * * The Initial Developer of Weave is the Institute for Visualization * and Perception Research at the University of Massachusetts Lowell. * Portions created by the Initial Developer are Copyright (C) 2008-2015 * the Initial Developer. All Rights Reserved. * * 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/. * * ***** END LICENSE BLOCK ***** */ package weavejs.data.source { import weavejs.WeaveAPI; import weavejs.api.core.ILinkableHashMap; import weavejs.api.core.ILinkableVariable; import weavejs.api.data.IKeySet; import weavejs.api.data.Aggregation; import weavejs.api.data.ColumnMetadata; import weavejs.api.data.DataType; import weavejs.api.data.IAttributeColumn; import weavejs.api.data.IDataSource; import weavejs.api.data.IQualifiedKey; import weavejs.api.data.ISelectableAttributes; import weavejs.api.data.IWeaveTreeNode; import weavejs.core.LinkableHashMap; import weavejs.core.LinkableString; import weavejs.core.LinkableVariable; import weavejs.core.LinkableBoolean; import weavejs.core.LinkableNumber; import weavejs.data.column.DynamicColumn; import weavejs.data.column.ProxyColumn; import weavejs.data.column.StringColumn; import weavejs.data.hierarchy.ColumnTreeNode; import weavejs.data.ColumnUtils; import weavejs.data.DataSourceUtils; import weavejs.data.key.DynamicKeyFilter; import weavejs.util.JS; import weavejs.util.StandardLib; public class WebSocketDataSource extends AbstractDataSource { WeaveAPI.ClassRegistry.registerImplementation(IDataSource, WebSocketDataSource, "WebSocket Data Source"); public static const DATA_COLUMNNAME_META:String = "__WebSocketJsonPropertyName__"; public function WebSocketDataSource() { this.selectionFilter.targetPath = ["defaultSelectionKeySet"]; } public const keyType:LinkableString = Weave.linkableChild(this, LinkableString); public const keyProperty:LinkableString = Weave.linkableChild(this, LinkableString); public const keepLast:LinkableNumber = Weave.linkableChild(this, LinkableNumber, onKeepLastChange); public const selectionFilter:DynamicKeyFilter = Weave.linkableChild(this, DynamicKeyFilter, onSelectionFilterChange); //public const selectionFeedback:LinkableBoolean = Weave.linkableChild(this, LinkableBoolean); public const url:LinkableString = Weave.linkableChild(this, LinkableString, onUrlChange); private function onSelectionFilterChange():void { if (_socket && _socket.readyState == 1) { var ks:IKeySet = selectionFilter.getInternalKeyFilter() as IKeySet; _socket.send(JSON.stringify(ks.keys.map(function (key:IQualifiedKey, idx:int, a:Array):String { return key.localName; }))); } } private var _socket:Object = null; private function onUrlChange():void { reconnect(); records = []; propertyNames.clear(); } public function reconnect():void /* To be called from UI reconnect button. */ { if (_socket && _socket.readyState < 2) { _socket.close(1000, "No longer needed."); _socket = null; } _socket = new JS.global.WebSocket(url.value); _socket.onmessage = onMessage; _socket.onclose = onClose; _socket.onerror = onError; } private function onClose(event:Object):void { _socket = null; } private function onError(event:Object):void { JS.error(event); /* Should we automatically retry here? */ _socket = null; } private function onMessage(event:/*/MessageEvent/*/Object):void { var str:String = event.data; var record:Object = JSON.parse(str); if ((records.length == keepLast.value) && (keepLast.value > 0)) { records.shift(); } records.push(record); /* Update set of property names */ for each (var key:String in JS.objectKeys(record)) { propertyNames.add(key); } refreshAllProxyColumns(); } public function getPropertyNames():Array/*/<string>/*/ { return JS.mapKeys(propertyNames) } private function onKeepLastChange():void { var diff:int = records.length - keepLast.value; if (diff > 0) { records = records.slice(diff); } } /** * The session state maps a column name in dataColumns hash map to a value for its "aggregation" metadata. */ public const aggregationModes:ILinkableVariable = Weave.linkableChild(this, new LinkableVariable(null, typeofIsObject)); private function typeofIsObject(value:Object):Boolean { return typeof value == 'object'; } private var records:Array = []; private var propertyNames:Object = new JS.global.Set(); override public function getHierarchyRoot():IWeaveTreeNode { if (!_rootNode) _rootNode = new ColumnTreeNode({ cacheSettings: {"label": false}, dataSource: this, dependency: this, data: this, "label": getLabel, hasChildBranches: false, children: function():Array { return JS.mapValues(propertyNames).map( function (columnName:String, ..._):* { var meta:Object = {}; meta[DATA_COLUMNNAME_META] = columnName; return generateHierarchyNode(meta); } ); } }); return _rootNode; } override protected function generateHierarchyNode(metadata:Object):IWeaveTreeNode { if (!metadata) return null; metadata = getColumnMetadata(metadata[DATA_COLUMNNAME_META]); if (!metadata) return null; return new ColumnTreeNode({ dataSource: this, idFields: [DATA_COLUMNNAME_META], data: metadata }); } private function getColumnMetadata(dataColumnName:String):Object { var metadata:Object = {}; metadata[ColumnMetadata.KEY_TYPE] = keyType.value || DataType.STRING; metadata[DATA_COLUMNNAME_META] = dataColumnName; metadata[ColumnMetadata.TITLE] = dataColumnName; var aggState:Object = aggregationModes.getSessionState(); var aggregation:String = aggState ? aggState[dataColumnName] : null; aggregation = aggregation || Aggregation.LAST; /* Keep the last value by default, this makes more sense in streaming applications. */ metadata[ColumnMetadata.AGGREGATION] = aggregation; if (aggregation != Aggregation.SAME) metadata[ColumnMetadata.TITLE] = Weave.lang("{0} ({1})", metadata[ColumnMetadata.TITLE], aggregation); return metadata; } override protected function requestColumnFromSource(proxyColumn:ProxyColumn):void { var columnName:String = proxyColumn.getMetadata(DATA_COLUMNNAME_META); var keys:Array; var data:Array = StandardLib.lodash.map(records, columnName);/*.map( function (d:*,i:int,a:Array):* { return d !== undefined ? d : null; } );*/ if (keyProperty.value) { keys = StandardLib.lodash.map(records, keyProperty.value); } else { keys = StandardLib.lodash.range(data.length); } var metadata:Object = getColumnMetadata(columnName); var dataType:String = DataSourceUtils.guessDataType(data); metadata[ColumnMetadata.DATA_TYPE] = dataType; proxyColumn.setMetadata(metadata); DataSourceUtils.initColumn(proxyColumn, keys, data); } } }
/* ***** BEGIN LICENSE BLOCK ***** * * This file is part of Weave. * * The Initial Developer of Weave is the Institute for Visualization * and Perception Research at the University of Massachusetts Lowell. * Portions created by the Initial Developer are Copyright (C) 2008-2015 * the Initial Developer. All Rights Reserved. * * 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/. * * ***** END LICENSE BLOCK ***** */ package weavejs.data.source { import weavejs.WeaveAPI; import weavejs.api.core.ILinkableHashMap; import weavejs.api.core.ILinkableVariable; import weavejs.api.data.IKeySet; import weavejs.api.data.Aggregation; import weavejs.api.data.ColumnMetadata; import weavejs.api.data.DataType; import weavejs.api.data.IAttributeColumn; import weavejs.api.data.IDataSource; import weavejs.api.data.IQualifiedKey; import weavejs.api.data.ISelectableAttributes; import weavejs.api.data.IWeaveTreeNode; import weavejs.core.LinkableHashMap; import weavejs.core.LinkableString; import weavejs.core.LinkableVariable; import weavejs.core.LinkableBoolean; import weavejs.core.LinkableNumber; import weavejs.data.column.DynamicColumn; import weavejs.data.column.ProxyColumn; import weavejs.data.column.StringColumn; import weavejs.data.hierarchy.ColumnTreeNode; import weavejs.data.ColumnUtils; import weavejs.data.DataSourceUtils; import weavejs.data.key.DynamicKeyFilter; import weavejs.util.JS; import weavejs.util.StandardLib; public class WebSocketDataSource extends AbstractDataSource { WeaveAPI.ClassRegistry.registerImplementation(IDataSource, WebSocketDataSource, "WebSocket Data Source"); public static const DATA_COLUMNNAME_META:String = "__WebSocketJsonPropertyName__"; public function WebSocketDataSource() { this.selectionFilter.targetPath = ["defaultSelectionKeySet"]; } public const keyType:LinkableString = Weave.linkableChild(this, LinkableString); public const keyProperty:LinkableString = Weave.linkableChild(this, LinkableString); public const keepLast:LinkableNumber = Weave.linkableChild(this, LinkableNumber, onKeepLastChange); public const selectionFilter:DynamicKeyFilter = Weave.linkableChild(this, DynamicKeyFilter, onSelectionFilterChange); //public const selectionFeedback:LinkableBoolean = Weave.linkableChild(this, LinkableBoolean); public const url:LinkableString = Weave.linkableChild(this, LinkableString, onUrlChange); private function onSelectionFilterChange():void { if (_socket && _socket.readyState == 1) { var ks:IKeySet = selectionFilter.getInternalKeyFilter() as IKeySet; _socket.send(JSON.stringify(ks.keys.map(function (key:IQualifiedKey, idx:int, a:Array):String { return key.localName; }))); } } private var _socket:Object = null; private function onUrlChange():void { reconnect(); records = []; propertyNames.clear(); } public function reconnect():void /* To be called from UI reconnect button. */ { JS.global.clearTimeout(timeoutId); if (_socket && _socket.readyState < 2) { _socket.close(1000, "No longer needed."); _socket = null; } _socket = new JS.global.WebSocket(url.value); _socket.onmessage = onMessage; _socket.onclose = onClose; _socket.onerror = onError; } private var timeoutId:int = 0; private function onClose(event:Object):void { _socket = null; if (url.value && event.code == 1006 /* CLOSE_ABNORMAL */) { timeoutId = JS.global.setTimeout(reconnect, 1500) } } private function onError(event:Object):void { JS.error(event); /* Should we automatically retry here? */ _socket = null; } private function onMessage(event:/*/MessageEvent/*/Object):void { var str:String = event.data; var record:Object = JSON.parse(str); if ((records.length == keepLast.value) && (keepLast.value > 0)) { records.shift(); } records.push(record); /* Update set of property names */ for each (var key:String in JS.objectKeys(record)) { propertyNames.add(key); } refreshAllProxyColumns(); } public function getPropertyNames():Array/*/<string>/*/ { return JS.mapKeys(propertyNames) } private function onKeepLastChange():void { var diff:int = records.length - keepLast.value; if (diff > 0) { records = records.slice(diff); } } /** * The session state maps a column name in dataColumns hash map to a value for its "aggregation" metadata. */ public const aggregationModes:ILinkableVariable = Weave.linkableChild(this, new LinkableVariable(null, typeofIsObject)); private function typeofIsObject(value:Object):Boolean { return typeof value == 'object'; } private var records:Array = []; private var propertyNames:Object = new JS.global.Set(); override public function getHierarchyRoot():IWeaveTreeNode { if (!_rootNode) _rootNode = new ColumnTreeNode({ cacheSettings: {"label": false}, dataSource: this, dependency: this, data: this, "label": getLabel, hasChildBranches: false, children: function():Array { return JS.mapValues(propertyNames).map( function (columnName:String, ..._):* { var meta:Object = {}; meta[DATA_COLUMNNAME_META] = columnName; return generateHierarchyNode(meta); } ); } }); return _rootNode; } override protected function generateHierarchyNode(metadata:Object):IWeaveTreeNode { if (!metadata) return null; metadata = getColumnMetadata(metadata[DATA_COLUMNNAME_META]); if (!metadata) return null; return new ColumnTreeNode({ dataSource: this, idFields: [DATA_COLUMNNAME_META], data: metadata }); } private function getColumnMetadata(dataColumnName:String):Object { var metadata:Object = {}; metadata[ColumnMetadata.KEY_TYPE] = keyType.value || DataType.STRING; metadata[DATA_COLUMNNAME_META] = dataColumnName; metadata[ColumnMetadata.TITLE] = dataColumnName; var aggState:Object = aggregationModes.getSessionState(); var aggregation:String = aggState ? aggState[dataColumnName] : null; aggregation = aggregation || Aggregation.LAST; /* Keep the last value by default, this makes more sense in streaming applications. */ metadata[ColumnMetadata.AGGREGATION] = aggregation; if (aggregation != Aggregation.SAME) metadata[ColumnMetadata.TITLE] = Weave.lang("{0} ({1})", metadata[ColumnMetadata.TITLE], aggregation); return metadata; } override protected function requestColumnFromSource(proxyColumn:ProxyColumn):void { var columnName:String = proxyColumn.getMetadata(DATA_COLUMNNAME_META); var keys:Array; var data:Array = StandardLib.lodash.map(records, columnName);/*.map( function (d:*,i:int,a:Array):* { return d !== undefined ? d : null; } );*/ if (keyProperty.value) { keys = StandardLib.lodash.map(records, keyProperty.value); } else { keys = StandardLib.lodash.range(data.length); } var metadata:Object = getColumnMetadata(columnName); var dataType:String = DataSourceUtils.guessDataType(data); metadata[ColumnMetadata.DATA_TYPE] = dataType; proxyColumn.setMetadata(metadata); DataSourceUtils.initColumn(proxyColumn, keys, data); } } }
Reconnect on abnormal connection abort.
WebSocketDataSource: Reconnect on abnormal connection abort.
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
3739fe7c795f0a8ebaa4118ac10f5ab655513cfe
exporter/src/main/as/flump/export/Atlas.as
exporter/src/main/as/flump/export/Atlas.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.Sprite; import flash.filesystem.File; import flash.geom.Rectangle; import flump.SwfTexture; public class Atlas { public var name :String; public var w :int, h :int, id :int; public function Atlas(name :String, w :int, h :int) { this.name = name; this.w = w; this.h = h; _root = new Node(); _root.bounds = new Rectangle(0, 0, w, h); } // Try to place a texture in this atlas, return true if it fit public function place (texture :SwfTexture) :Boolean { var node :Node = _root.search(new Rectangle(0, 0, texture.w, texture.h)); if (node == null) { return false; } node.texture = texture; return true; } public function publish (dir :File) :void { var constructed :Sprite = new Sprite(); _root.forEach(function (node :Node) :void { var tex :SwfTexture = node.texture; constructed.addChild(tex.holder); tex.holder.x = node.bounds.x; tex.holder.y = node.bounds.y; }); PngPublisher.publish(dir.resolvePath(name + ".png"), w, h, constructed); } public function toXml () :String { var xml :String = '<atlas name="' + name + '" filename="' + name + '.png">\n'; _root.forEach(function (node :Node) :void { var tex :SwfTexture = node.texture; xml += ' <texture name="' + tex.libraryItem + '" xOffset="' + tex.offset.x + '" yOffset="' + tex.offset.y + '" md5="' + tex.md5 + '" xAtlas="' + node.bounds.x + '" yAtlas="' + node.bounds.y + '" wAtlas="' + tex.w + '" hAtlas="' + tex.h + '"/>\n'; }); return xml + '</atlas>\n'; } public function toJSON (_:*) :Object { var json :Object = { file: name + ".png", textures: [] }; _root.forEach(function (node :Node) :void { var tex :SwfTexture = node.texture; json.textures.push({ name: tex.symbol, offset: [ tex.offset.x, tex.offset.y ], rect: [ node.bounds.x, node.bounds.y, tex.w, tex.h ] }); }); return json; } protected var _root :Node; } } import flash.geom.Rectangle; import flump.SwfTexture; // A node in a k-d tree class Node { // The bounds of this node (and its children) public var bounds :Rectangle; // The texture that is placed here, if any public var texture :SwfTexture; // This node's two children public var left :Node; public var right :Node; // Find for free node in this tree big enough to fit a rect, or null public function search (rect :Rectangle) :Node { // There's already a texture here, terminate if (texture != null) { return null; } if (left != null && right != null) { // Try to fit it into this node's children var descendent :Node = left.search(rect); if (descendent == null) { descendent = right.search(rect); } return descendent; } else { if (bounds.width == rect.width && bounds.height == rect.height) { return this; } if (bounds.width < rect.width || bounds.height < rect.height) { return null; } left = new Node(); right = new Node(); var dw :Number = bounds.width - rect.width; var dh :Number = bounds.height - rect.height; if (dw > dh) { left.bounds = new Rectangle( bounds.x, bounds.y, rect.width, bounds.height); right.bounds = new Rectangle( bounds.x + rect.width, bounds.y, bounds.width - rect.width, bounds.height); } else { left.bounds = new Rectangle( bounds.x, bounds.y, bounds.width, rect.height); right.bounds = new Rectangle( bounds.x, bounds.y + rect.height, bounds.width, bounds.height - rect.height); } return left.search(rect); } } // Iterate over all nodes with textures in this tree public function forEach (fn :Function /* Node -> void */) :void { if (texture != null) { fn(this); } if (left != null && right != null) { left.forEach(fn); right.forEach(fn); } } }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.Sprite; import flash.filesystem.File; import flash.geom.Rectangle; import flump.SwfTexture; public class Atlas { public var name :String; public var w :int, h :int, id :int; public function Atlas(name :String, w :int, h :int) { this.name = name; this.w = w; this.h = h; _root = new Node(); _root.bounds = new Rectangle(0, 0, w, h); } // Try to place a texture in this atlas, return true if it fit public function place (texture :SwfTexture) :Boolean { var node :Node = _root.search( new Rectangle(0, 0, texture.w + 2*PADDING, texture.h + 2*PADDING)); if (node == null) { return false; } node.texture = texture; return true; } public function publish (dir :File) :void { var constructed :Sprite = new Sprite(); _root.forEach(function (node :Node) :void { var tex :SwfTexture = node.texture; constructed.addChild(tex.holder); tex.holder.x = node.bounds.x; tex.holder.y = node.bounds.y; }); PngPublisher.publish(dir.resolvePath(name + ".png"), w, h, constructed); } public function toXml () :String { var xml :String = '<atlas name="' + name + '" filename="' + name + '.png">\n'; _root.forEach(function (node :Node) :void { var tex :SwfTexture = node.texture; xml += ' <texture name="' + tex.libraryItem + '" xOffset="' + tex.offset.x + '" yOffset="' + tex.offset.y + '" md5="' + tex.md5 + '" xAtlas="' + (node.bounds.x + PADDING) '" yAtlas="' + (node.bounds.y + PADDING) '" wAtlas="' + tex.w + '" hAtlas="' + tex.h + '"/>\n'; }); return xml + '</atlas>\n'; } public function toJSON (_:*) :Object { var json :Object = { file: name + ".png", textures: [] }; _root.forEach(function (node :Node) :void { var tex :SwfTexture = node.texture; json.textures.push({ name: tex.symbol, offset: [ tex.offset.x, tex.offset.y ], rect: [ node.bounds.x + PADDING, node.bounds.y + PADDING, tex.w, tex.h ] }); }); return json; } // Empty pixels to border around each texture to prevent bleeding protected static const PADDING :int = 1; protected var _root :Node; } } import flash.geom.Rectangle; import flump.SwfTexture; // A node in a k-d tree class Node { // The bounds of this node (and its children) public var bounds :Rectangle; // The texture that is placed here, if any public var texture :SwfTexture; // This node's two children public var left :Node; public var right :Node; // Find for free node in this tree big enough to fit a rect, or null public function search (rect :Rectangle) :Node { // There's already a texture here, terminate if (texture != null) { return null; } if (left != null && right != null) { // Try to fit it into this node's children var descendent :Node = left.search(rect); if (descendent == null) { descendent = right.search(rect); } return descendent; } else { if (bounds.width == rect.width && bounds.height == rect.height) { return this; } if (bounds.width < rect.width || bounds.height < rect.height) { return null; } left = new Node(); right = new Node(); var dw :Number = bounds.width - rect.width; var dh :Number = bounds.height - rect.height; if (dw > dh) { left.bounds = new Rectangle( bounds.x, bounds.y, rect.width, bounds.height); right.bounds = new Rectangle( bounds.x + rect.width, bounds.y, bounds.width - rect.width, bounds.height); } else { left.bounds = new Rectangle( bounds.x, bounds.y, bounds.width, rect.height); right.bounds = new Rectangle( bounds.x, bounds.y + rect.height, bounds.width, bounds.height - rect.height); } return left.search(rect); } } // Iterate over all nodes with textures in this tree public function forEach (fn :Function /* Node -> void */) :void { if (texture != null) { fn(this); } if (left != null && right != null) { left.forEach(fn); right.forEach(fn); } } }
Put tiny gaps around textures to prevent atlas artifacts.
Put tiny gaps around textures to prevent atlas artifacts.
ActionScript
mit
tconkling/flump,mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,funkypandagame/flump
f98330d7e21d652fea9e28971622f3ec766df953
as3porject/src/Main.as
as3porject/src/Main.as
package { import org.flixel.*; [SWF(width="320", height="240", backgroundColor="#000000")] [Frame(factoryClass="Preloader")] public class Main extends FlxGame { public function Main() { super(320, 240, PlayState, 1, 20, 20); } } }
package { import org.flixel.*; [SWF(width="320", height="240", backgroundColor="#000000")] [Frame(factoryClass="Preloader")] public class Main extends FlxGame { public function Main() { //test super(320, 240, PlayState, 1, 20, 20); } } }
test office commit
test office commit
ActionScript
mit
kaleidosgu/letter-fighter
e18d1eb84a3095a066e428cbef4d0ee9518603f6
src/aerys/minko/scene/visitor/data/CameraData.as
src/aerys/minko/scene/visitor/data/CameraData.as
package aerys.minko.scene.visitor.data { import aerys.minko.type.math.Frustum; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.geom.Matrix; public class CameraData implements IWorldData { public static const POSITION : String = 'position'; public static const LOOK_AT : String = 'lookAt'; public static const UP : String = 'up'; public static const RATIO : String = 'ratio'; public static const FOV : String = 'fov'; public static const Z_NEAR : String = 'zNear'; public static const Z_FAR : String = 'zFar'; public static const Z_FAR_PARTS : String = 'zFarParts'; public static const VIEW : String = 'view'; public static const PROJECTION : String = 'projection'; public static const LOCAL_POSITION : String = 'localPosition'; public static const LOCAL_LOOK_AT : String = 'localLookAt'; public static const DIRECTION : String = 'direction'; public static const LOCAL_DIRECTION : String = 'localDirection'; public static const FRUSTUM : String = 'frustum'; // local data provider protected var _styleStack : StyleStack; protected var _localData : LocalData; // data available on initialisation protected var _position : Vector4; protected var _lookAt : Vector4; protected var _up : Vector4; protected var _ratio : Number; protected var _fov : Number; protected var _zNear : Number; protected var _zFar : Number; // computed data protected var _zFarParts : Vector4; protected var _zFarParts_invalidated : Boolean; protected var _view : Matrix4x4; protected var _view_positionVersion : uint; protected var _view_lookAtVersion : uint; protected var _view_upVersion : uint; protected var _projection : Matrix4x4; protected var _projection_invalidated : Boolean; protected var _localPosition : Vector4; protected var _localPosition_positionVersion : uint; protected var _localLookAt : Vector4; protected var _localLookAt_lookAtVersion : uint; protected var _frustum : Frustum; protected var _frustum_projectionVersion : uint; public function get position() : Vector4 { return _position; } public function get lookAt() : Vector4 { return _lookAt; } public function get up() : Vector4 { return _up; } public function get fieldOfView() : Number { return _fov; } public function get zNear() : Number { return _zNear; } public function get zFar() : Number { return _zFar; } public function get zFarParts() : Vector4 { if (_zFarParts_invalidated) { _zFarParts = new Vector4(0, 0.25 * _zFar, 0.5 * _zFar, 0.75 * _zFar); _zFarParts_invalidated = false; } return _zFarParts; } public function get view() : Matrix4x4 { if (_view_positionVersion != _position.version || _view_lookAtVersion != _lookAt.version || _view_upVersion != _up.version) { _view = Matrix4x4.lookAtLH(_position, _lookAt, _up, _view); _view_positionVersion = _position.version; _view_lookAtVersion = _lookAt.version; _view_upVersion = _lookAt.version; } return _view; } public function get projection() : Matrix4x4 { if (_projection_invalidated) { _projection = Matrix4x4.perspectiveFoVLH(_fov, _ratio, _zNear, _zFar, _projection); _projection_invalidated = false; } return _projection; } public function get frustrum() : Frustum { var projectionMatrix : Matrix4x4 = projection; if (_frustum_projectionVersion != projectionMatrix.version) { if (_frustum == null) _frustum = new Frustum(); _frustum.update(projectionMatrix); _frustum_projectionVersion = projectionMatrix.version; } return _frustum; } public function get localPosition() : Vector4 { if (_localPosition_positionVersion != _position.version) { _localPosition = _localData.world.multiplyVector(_position, _localPosition); _localPosition_positionVersion = _position.version; } return _localPosition; } public function get localLookAt() : Vector4 { if (_localLookAt_lookAtVersion != _lookAt.version) { _localLookAt = _localData.world.deltaMultiplyVector(_lookAt, _localLookAt); _localLookAt_lookAtVersion = _lookAt.version; } return _localLookAt; } public function get localDirection() : Vector4 { // FIXME: handle cache return Vector4.subtract(localPosition, localLookAt).normalize(); } public function get direction() : Vector4 { // FIXME: handle cache return Vector4.subtract(position, lookAt).normalize(); } public function set ratio(v : Number) : void { _ratio = v; _projection_invalidated = true; } public function set position(v : Vector4) : void { _position = v; } public function set lookAt(v : Vector4) : void { _lookAt = v; } public function set up(v : Vector4) : void { _up = v; } public function set fov(v : Number) : void { _fov = v; _projection_invalidated = true; } public function set zNear(v : Number) : void { _zNear = v; _projection_invalidated = true; } public function set zFar(v : Number) : void { _zFar = v; _projection_invalidated = true; } public function CameraData() { reset() } public function setLocalDataProvider(styleStack : StyleStack, localData : LocalData) : void { _styleStack = styleStack; _localData = localData; } public function invalidate() : void { // do nothing } public function reset() : void { _position = null; _lookAt = null; _up = null; _ratio = -1; _fov = -1; _zNear = -1; _zFar = -1; _view_positionVersion = uint.MAX_VALUE; _view_lookAtVersion = uint.MAX_VALUE; _view_upVersion = uint.MAX_VALUE; _localPosition_positionVersion = uint.MAX_VALUE; _localLookAt_lookAtVersion = uint.MAX_VALUE; _frustum_projectionVersion = uint.MAX_VALUE; _zFarParts_invalidated = true; _projection_invalidated = true; _localData && _localData.reset(); } } }
package aerys.minko.scene.visitor.data { import aerys.minko.type.math.Frustum; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; public class CameraData implements IWorldData { public static const POSITION : String = 'position'; public static const LOOK_AT : String = 'lookAt'; public static const UP : String = 'up'; public static const RATIO : String = 'ratio'; public static const FOV : String = 'fov'; public static const Z_NEAR : String = 'zNear'; public static const Z_FAR : String = 'zFar'; public static const Z_FAR_PARTS : String = 'zFarParts'; public static const VIEW : String = 'view'; public static const PROJECTION : String = 'projection'; public static const LOCAL_POSITION : String = 'localPosition'; public static const LOCAL_LOOK_AT : String = 'localLookAt'; public static const DIRECTION : String = 'direction'; public static const LOCAL_DIRECTION : String = 'localDirection'; public static const FRUSTUM : String = 'frustum'; // local data provider protected var _styleStack : StyleStack; protected var _localData : LocalData; // data available on initialisation protected var _position : Vector4; protected var _lookAt : Vector4; protected var _up : Vector4; protected var _ratio : Number; protected var _fov : Number; protected var _zNear : Number; protected var _zFar : Number; // computed data protected var _zFarParts : Vector4; protected var _zFarParts_invalidated : Boolean; protected var _view : Matrix4x4; protected var _view_positionVersion : uint; protected var _view_lookAtVersion : uint; protected var _view_upVersion : uint; protected var _projection : Matrix4x4; protected var _projection_invalidated : Boolean; protected var _localPosition : Vector4; protected var _localPosition_positionVersion : uint; protected var _localLookAt : Vector4; protected var _localLookAt_lookAtVersion : uint; protected var _frustum : Frustum; protected var _frustum_projectionVersion : uint; public function get position() : Vector4 { return _position; } public function get lookAt() : Vector4 { return _lookAt; } public function get up() : Vector4 { return _up; } public function get fieldOfView() : Number { return _fov; } public function get zNear() : Number { return _zNear; } public function get zFar() : Number { return _zFar; } public function get zFarParts() : Vector4 { if (_zFarParts_invalidated) { _zFarParts = new Vector4(0, 0.25 * _zFar, 0.5 * _zFar, 0.75 * _zFar); _zFarParts_invalidated = false; } return _zFarParts; } public function get view() : Matrix4x4 { if (_view_positionVersion != _position.version || _view_lookAtVersion != _lookAt.version || _view_upVersion != _up.version) { _view = Matrix4x4.lookAtLH(_position, _lookAt, _up, _view); _view_positionVersion = _position.version; _view_lookAtVersion = _lookAt.version; _view_upVersion = _lookAt.version; } return _view; } public function get projection() : Matrix4x4 { if (_projection_invalidated) { _projection = Matrix4x4.perspectiveFoVLH(_fov, _ratio, _zNear, _zFar, _projection); _projection_invalidated = false; } return _projection; } public function get frustrum() : Frustum { var projectionMatrix : Matrix4x4 = projection; if (_frustum_projectionVersion != projectionMatrix.version) { if (_frustum == null) _frustum = new Frustum(); _frustum.update(projectionMatrix); _frustum_projectionVersion = projectionMatrix.version; } return _frustum; } public function get localPosition() : Vector4 { if (_localPosition_positionVersion != _position.version) { _localPosition = _localData.world.multiplyVector(_position, _localPosition); _localPosition_positionVersion = _position.version; } return _localPosition; } public function get localLookAt() : Vector4 { if (_localLookAt_lookAtVersion != _lookAt.version) { _localLookAt = _localData.world.deltaMultiplyVector(_lookAt, _localLookAt); _localLookAt_lookAtVersion = _lookAt.version; } return _localLookAt; } public function get localDirection() : Vector4 { // FIXME: handle cache return Vector4.subtract(localPosition, localLookAt).normalize(); } public function get direction() : Vector4 { // FIXME: handle cache return Vector4.subtract(position, lookAt).normalize(); } public function set ratio(v : Number) : void { _ratio = v; _projection_invalidated = true; } public function set position(v : Vector4) : void { _position = v; } public function set lookAt(v : Vector4) : void { _lookAt = v; } public function set up(v : Vector4) : void { _up = v; } public function set fov(v : Number) : void { _fov = v; _projection_invalidated = true; } public function set zNear(v : Number) : void { _zNear = v; _projection_invalidated = true; } public function set zFar(v : Number) : void { _zFar = v; _projection_invalidated = true; } public function CameraData() { reset() } public function setLocalDataProvider(styleStack : StyleStack, localData : LocalData) : void { _styleStack = styleStack; _localData = localData; } public function invalidate() : void { // do nothing } public function reset() : void { _position = null; _lookAt = null; _up = null; _ratio = -1; _fov = -1; _zNear = -1; _zFar = -1; _view_positionVersion = uint.MAX_VALUE; _view_lookAtVersion = uint.MAX_VALUE; _view_upVersion = uint.MAX_VALUE; _localPosition_positionVersion = uint.MAX_VALUE; _localLookAt_lookAtVersion = uint.MAX_VALUE; _frustum_projectionVersion = uint.MAX_VALUE; _zFarParts_invalidated = true; _projection_invalidated = true; } } }
Fix minor bug in CameraData (reset method is not called on the reference to localData anymore)
Fix minor bug in CameraData (reset method is not called on the reference to localData anymore)
ActionScript
mit
aerys/minko-as3
886668ab13f4cfd2e956b18d96323efad1878764
bin/Data/Scripts/Editor/EditorViewDebugIcons.as
bin/Data/Scripts/Editor/EditorViewDebugIcons.as
// Editor debug icons BillboardSet@ debugIconsSetDirectionalLights; BillboardSet@ debugIconsSetSpotLights; BillboardSet@ debugIconsSetPointLights; BillboardSet@ debugIconsSetCameras; BillboardSet@ debugIconsSetSoundSources; BillboardSet@ debugIconsSetSoundSources3D; BillboardSet@ debugIconsSetSoundListeners; BillboardSet@ debugIconsSetZones; int stepDebugIconsUpdate = 30; //ms int timeToNextDebugIconsUpdate = 0; bool debugIconsShow = true; Vector2 debugIconsSize = Vector2(0.025, 0.025); void CreateDebugIcons() { if (editorScene is null) return; debugIconsSetDirectionalLights = editorScene.CreateComponent("BillboardSet"); debugIconsSetDirectionalLights.material = cache.GetResource("Material", "Materials/Editor/DebugIconLight.xml"); debugIconsSetDirectionalLights.material.renderOrder = 255; debugIconsSetDirectionalLights.sorted = true; debugIconsSetDirectionalLights.temporary = true; debugIconsSetDirectionalLights.viewMask = 0x80000000; debugIconsSetSpotLights = editorScene.CreateComponent("BillboardSet"); debugIconsSetSpotLights.material = cache.GetResource("Material", "Materials/Editor/DebugIconSpotLight.xml"); debugIconsSetSpotLights.material.renderOrder = 255; debugIconsSetSpotLights.sorted = true; debugIconsSetSpotLights.temporary = true; debugIconsSetSpotLights.viewMask = 0x80000000; debugIconsSetPointLights = editorScene.CreateComponent("BillboardSet"); debugIconsSetPointLights.material = cache.GetResource("Material", "Materials/Editor/DebugIconPointLight.xml"); debugIconsSetPointLights.material.renderOrder = 255; debugIconsSetPointLights.sorted = true; debugIconsSetPointLights.temporary = true; debugIconsSetPointLights.viewMask = 0x80000000; debugIconsSetCameras = editorScene.CreateComponent("BillboardSet"); debugIconsSetCameras.material = cache.GetResource("Material", "Materials/Editor/DebugIconCamera.xml"); debugIconsSetCameras.material.renderOrder = 255; debugIconsSetCameras.sorted = true; debugIconsSetCameras.temporary = true; debugIconsSetCameras.viewMask = 0x80000000; debugIconsSetSoundSources = editorScene.CreateComponent("BillboardSet"); debugIconsSetSoundSources.material = cache.GetResource("Material", "Materials/Editor/DebugIconSoundSource.xml"); debugIconsSetSoundSources.material.renderOrder = 255; debugIconsSetSoundSources.sorted = true; debugIconsSetSoundSources.temporary = true; debugIconsSetSoundSources.viewMask = 0x80000000; debugIconsSetSoundSources3D = editorScene.CreateComponent("BillboardSet"); debugIconsSetSoundSources3D.material = cache.GetResource("Material", "Materials/Editor/DebugIconSoundSource.xml"); debugIconsSetSoundSources3D.material.renderOrder = 255; debugIconsSetSoundSources3D.sorted = true; debugIconsSetSoundSources3D.temporary = true; debugIconsSetSoundSources3D.viewMask = 0x80000000; debugIconsSetSoundListeners = editorScene.CreateComponent("BillboardSet"); debugIconsSetSoundListeners.material = cache.GetResource("Material", "Materials/Editor/DebugIconSoundListener.xml"); debugIconsSetSoundListeners.material.renderOrder = 255; debugIconsSetSoundListeners.sorted = true; debugIconsSetSoundListeners.temporary = true; debugIconsSetSoundListeners.viewMask = 0x80000000; debugIconsSetZones = editorScene.CreateComponent("BillboardSet"); debugIconsSetZones.material = cache.GetResource("Material", "Materials/Editor/DebugIconZone.xml"); debugIconsSetZones.material.renderOrder = 255; debugIconsSetZones.sorted = true; debugIconsSetZones.temporary = true; debugIconsSetZones.viewMask = 0x80000000; } void UpdateViewDebugIcons() { if (timeToNextDebugIconsUpdate > time.systemTime) return; if (editorScene is null) return; // Checkout if scene do not have BBS component, add it once BillboardSet@ bbs = editorScene.GetComponent("BillboardSet"); if (bbs is null) { CreateDebugIcons(); } Vector3 camPos = cameraNode.worldPosition; if (debugIconsSetPointLights !is null) { debugIconsSetDirectionalLights.enabled = debugIconsShow; debugIconsSetSpotLights.enabled = debugIconsShow; debugIconsSetPointLights.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("Light", true); if (nodes.length > 0) { debugIconsSetDirectionalLights.numBillboards = 0; debugIconsSetSpotLights.numBillboards = 0; debugIconsSetPointLights.numBillboards = 0; debugIconsSetPointLights.Commit(); debugIconsSetSpotLights.Commit(); debugIconsSetDirectionalLights.Commit(); debugIconsSetDirectionalLights.numBillboards = nodes.length; debugIconsSetSpotLights.numBillboards = nodes.length; debugIconsSetPointLights.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Light@ light = nodes[i].GetComponent("Light"); if (light.lightType == LIGHT_POINT) { Billboard@ bb = debugIconsSetPointLights.billboards[i]; bb.position = nodes[i].worldPosition; bb.color = light.effectiveColor; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } else if (light.lightType == LIGHT_DIRECTIONAL) { Billboard@ bb = debugIconsSetDirectionalLights.billboards[i]; bb.position = nodes[i].worldPosition; bb.color = light.effectiveColor; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } else if (light.lightType == LIGHT_SPOT) { Billboard@ bb = debugIconsSetSpotLights.billboards[i]; bb.position = nodes[i].worldPosition; bb.color = light.effectiveColor; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } } debugIconsSetPointLights.Commit(); debugIconsSetSpotLights.Commit(); debugIconsSetDirectionalLights.Commit(); } } if (debugIconsSetCameras !is null) { debugIconsSetCameras.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("Camera", true); if (nodes.length > 0) { debugIconsSetCameras.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Camera@ camera = nodes[i].GetComponent("Camera"); Billboard@ bb = debugIconsSetCameras.billboards[i]; bb.position = nodes[i].worldPosition; // if mainCamera enough closer to selected camera then make bb size relative to distance float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } debugIconsSetCameras.Commit(); } } if (debugIconsSetSoundSources !is null) { debugIconsSetSoundSources.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("SoundSource", true); if (nodes.length > 0) { debugIconsSetSoundSources.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Component@ component = nodes[i].GetComponent("SoundSource"); Billboard@ bb = debugIconsSetSoundSources.billboards[i]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = component.enabled; } debugIconsSetSoundSources.Commit(); } } if (debugIconsSetSoundSources3D !is null) { debugIconsSetSoundSources3D.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("SoundSource3D", true); if (nodes.length > 0) { debugIconsSetSoundSources3D.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Component@ component = nodes[i].GetComponent("SoundSource3D"); Billboard@ bb = debugIconsSetSoundSources3D.billboards[i]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = component.enabled; } debugIconsSetSoundSources3D.Commit(); } } if (debugIconsSetSoundListeners !is null) { debugIconsSetSoundListeners.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("SoundListener" , true); if (nodes.length > 0) { debugIconsSetSoundListeners.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Component@ component = nodes[i].GetComponent("SoundListener"); Billboard@ bb = debugIconsSetSoundListeners.billboards[i]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = component.enabled; } debugIconsSetSoundListeners.Commit(); } } if (debugIconsSetZones !is null) { debugIconsSetZones.enabled = debugIconsShow; // Collect all scene's Zones and add it Array<Node@> nodes = editorScene.GetChildrenWithComponent("Zone", true); Zone@ zone = editorScene.GetComponent("Zone"); if (zone !is null) { debugIconsSetZones.numBillboards = 1; Billboard@ bb = debugIconsSetZones.billboards[0]; bb.position = Vector3(0,0,0); float distance = (camPos - bb.position).length; bb.size = debugIconsSize * distance; //bb.color = zone.ambientColor; bb.enabled = zone.enabled; } if (nodes.length > 0) { debugIconsSetZones.numBillboards = 1 + nodes.length; for (int i=0;i<nodes.length; i++) { Zone@ zone = nodes[i].GetComponent("Zone"); Billboard@ bb = debugIconsSetZones.billboards[i+1]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; //bb.color = zone.ambientColor; bb.enabled = zone.enabled; } debugIconsSetZones.Commit(); } } timeToNextDebugIconsUpdate = time.systemTime + stepDebugIconsUpdate; }
// Editor debug icons BillboardSet@ debugIconsSetDirectionalLights; BillboardSet@ debugIconsSetSpotLights; BillboardSet@ debugIconsSetPointLights; BillboardSet@ debugIconsSetCameras; BillboardSet@ debugIconsSetSoundSources; BillboardSet@ debugIconsSetSoundSources3D; BillboardSet@ debugIconsSetSoundListeners; BillboardSet@ debugIconsSetZones; Node@ debugIconsNode = null; int stepDebugIconsUpdate = 30; //ms int timeToNextDebugIconsUpdate = 0; bool debugIconsShow = true; Vector2 debugIconsSize = Vector2(0.025, 0.025); void CreateDebugIcons() { if (editorScene is null) return; debugIconsSetDirectionalLights = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetDirectionalLights.material = cache.GetResource("Material", "Materials/Editor/DebugIconLight.xml"); debugIconsSetDirectionalLights.material.renderOrder = 255; debugIconsSetDirectionalLights.sorted = true; debugIconsSetDirectionalLights.temporary = true; debugIconsSetDirectionalLights.viewMask = 0x80000000; debugIconsSetSpotLights = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSpotLights.material = cache.GetResource("Material", "Materials/Editor/DebugIconSpotLight.xml"); debugIconsSetSpotLights.material.renderOrder = 255; debugIconsSetSpotLights.sorted = true; debugIconsSetSpotLights.temporary = true; debugIconsSetSpotLights.viewMask = 0x80000000; debugIconsSetPointLights = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetPointLights.material = cache.GetResource("Material", "Materials/Editor/DebugIconPointLight.xml"); debugIconsSetPointLights.material.renderOrder = 255; debugIconsSetPointLights.sorted = true; debugIconsSetPointLights.temporary = true; debugIconsSetPointLights.viewMask = 0x80000000; debugIconsSetCameras = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetCameras.material = cache.GetResource("Material", "Materials/Editor/DebugIconCamera.xml"); debugIconsSetCameras.material.renderOrder = 255; debugIconsSetCameras.sorted = true; debugIconsSetCameras.temporary = true; debugIconsSetCameras.viewMask = 0x80000000; debugIconsSetSoundSources = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSoundSources.material = cache.GetResource("Material", "Materials/Editor/DebugIconSoundSource.xml"); debugIconsSetSoundSources.material.renderOrder = 255; debugIconsSetSoundSources.sorted = true; debugIconsSetSoundSources.temporary = true; debugIconsSetSoundSources.viewMask = 0x80000000; debugIconsSetSoundSources3D = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSoundSources3D.material = cache.GetResource("Material", "Materials/Editor/DebugIconSoundSource.xml"); debugIconsSetSoundSources3D.material.renderOrder = 255; debugIconsSetSoundSources3D.sorted = true; debugIconsSetSoundSources3D.temporary = true; debugIconsSetSoundSources3D.viewMask = 0x80000000; debugIconsSetSoundListeners = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSoundListeners.material = cache.GetResource("Material", "Materials/Editor/DebugIconSoundListener.xml"); debugIconsSetSoundListeners.material.renderOrder = 255; debugIconsSetSoundListeners.sorted = true; debugIconsSetSoundListeners.temporary = true; debugIconsSetSoundListeners.viewMask = 0x80000000; debugIconsSetZones = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetZones.material = cache.GetResource("Material", "Materials/Editor/DebugIconZone.xml"); debugIconsSetZones.material.renderOrder = 255; debugIconsSetZones.sorted = true; debugIconsSetZones.temporary = true; debugIconsSetZones.viewMask = 0x80000000; } void UpdateViewDebugIcons() { if (timeToNextDebugIconsUpdate > time.systemTime) return; if (editorScene is null) return; debugIconsNode = editorScene.GetChild("DebugIconsContainer", true); if (debugIconsNode is null) { debugIconsNode = editorScene.CreateChild("DebugIconsContainer", LOCAL); debugIconsNode.temporary = true; } // Checkout if debugIconsNode do not have any BBS component, add they at once BillboardSet@ bbs = debugIconsNode.GetComponent("BillboardSet"); if (bbs is null) { CreateDebugIcons(); } Vector3 camPos = cameraNode.worldPosition; if (debugIconsSetPointLights !is null) { debugIconsSetDirectionalLights.enabled = debugIconsShow; debugIconsSetSpotLights.enabled = debugIconsShow; debugIconsSetPointLights.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("Light", true); if (nodes.length > 0) { debugIconsSetDirectionalLights.numBillboards = 0; debugIconsSetSpotLights.numBillboards = 0; debugIconsSetPointLights.numBillboards = 0; debugIconsSetPointLights.Commit(); debugIconsSetSpotLights.Commit(); debugIconsSetDirectionalLights.Commit(); debugIconsSetDirectionalLights.numBillboards = nodes.length; debugIconsSetSpotLights.numBillboards = nodes.length; debugIconsSetPointLights.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Light@ light = nodes[i].GetComponent("Light"); if (light.lightType == LIGHT_POINT) { Billboard@ bb = debugIconsSetPointLights.billboards[i]; bb.position = nodes[i].worldPosition; bb.color = light.effectiveColor; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } else if (light.lightType == LIGHT_DIRECTIONAL) { Billboard@ bb = debugIconsSetDirectionalLights.billboards[i]; bb.position = nodes[i].worldPosition; bb.color = light.effectiveColor; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } else if (light.lightType == LIGHT_SPOT) { Billboard@ bb = debugIconsSetSpotLights.billboards[i]; bb.position = nodes[i].worldPosition; bb.color = light.effectiveColor; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } } debugIconsSetPointLights.Commit(); debugIconsSetSpotLights.Commit(); debugIconsSetDirectionalLights.Commit(); } } if (debugIconsSetCameras !is null) { debugIconsSetCameras.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("Camera", true); if (nodes.length > 0) { debugIconsSetCameras.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Camera@ camera = nodes[i].GetComponent("Camera"); Billboard@ bb = debugIconsSetCameras.billboards[i]; bb.position = nodes[i].worldPosition; // if mainCamera enough closer to selected camera then make bb size relative to distance float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } debugIconsSetCameras.Commit(); } } if (debugIconsSetSoundSources !is null) { debugIconsSetSoundSources.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("SoundSource", true); if (nodes.length > 0) { debugIconsSetSoundSources.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Component@ component = nodes[i].GetComponent("SoundSource"); Billboard@ bb = debugIconsSetSoundSources.billboards[i]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = component.enabled; } debugIconsSetSoundSources.Commit(); } } if (debugIconsSetSoundSources3D !is null) { debugIconsSetSoundSources3D.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("SoundSource3D", true); if (nodes.length > 0) { debugIconsSetSoundSources3D.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Component@ component = nodes[i].GetComponent("SoundSource3D"); Billboard@ bb = debugIconsSetSoundSources3D.billboards[i]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = component.enabled; } debugIconsSetSoundSources3D.Commit(); } } if (debugIconsSetSoundListeners !is null) { debugIconsSetSoundListeners.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("SoundListener" , true); if (nodes.length > 0) { debugIconsSetSoundListeners.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Component@ component = nodes[i].GetComponent("SoundListener"); Billboard@ bb = debugIconsSetSoundListeners.billboards[i]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = component.enabled; } debugIconsSetSoundListeners.Commit(); } } if (debugIconsSetZones !is null) { debugIconsSetZones.enabled = debugIconsShow; // Collect all scene's Zones and add it Array<Node@> nodes = editorScene.GetChildrenWithComponent("Zone", true); Zone@ zone = editorScene.GetComponent("Zone"); if (zone !is null) { debugIconsSetZones.numBillboards = 1; Billboard@ bb = debugIconsSetZones.billboards[0]; bb.position = Vector3(0,0,0); float distance = (camPos - bb.position).length; bb.size = debugIconsSize * distance; //bb.color = zone.ambientColor; bb.enabled = zone.enabled; } if (nodes.length > 0) { debugIconsSetZones.numBillboards = 1 + nodes.length; for (int i=0;i<nodes.length; i++) { Zone@ zone = nodes[i].GetComponent("Zone"); Billboard@ bb = debugIconsSetZones.billboards[i+1]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; //bb.color = zone.ambientColor; bb.enabled = zone.enabled; } debugIconsSetZones.Commit(); } } timeToNextDebugIconsUpdate = time.systemTime + stepDebugIconsUpdate; }
add debug temp container(node) and clear scene's scope
add debug temp container(node) and clear scene's scope
ActionScript
mit
bacsmar/Urho3D,luveti/Urho3D,SirNate0/Urho3D,cosmy1/Urho3D,carnalis/Urho3D,luveti/Urho3D,299299/Urho3D,codedash64/Urho3D,eugeneko/Urho3D,299299/Urho3D,bacsmar/Urho3D,helingping/Urho3D,SuperWangKai/Urho3D,codedash64/Urho3D,c4augustus/Urho3D,orefkov/Urho3D,codemon66/Urho3D,xiliu98/Urho3D,urho3d/Urho3D,kostik1337/Urho3D,xiliu98/Urho3D,rokups/Urho3D,xiliu98/Urho3D,iainmerrick/Urho3D,tommy3/Urho3D,codemon66/Urho3D,iainmerrick/Urho3D,SirNate0/Urho3D,luveti/Urho3D,299299/Urho3D,299299/Urho3D,carnalis/Urho3D,helingping/Urho3D,MonkeyFirst/Urho3D,tommy3/Urho3D,SuperWangKai/Urho3D,codemon66/Urho3D,tommy3/Urho3D,SuperWangKai/Urho3D,299299/Urho3D,codemon66/Urho3D,kostik1337/Urho3D,fire/Urho3D-1,weitjong/Urho3D,fire/Urho3D-1,PredatorMF/Urho3D,MonkeyFirst/Urho3D,orefkov/Urho3D,abdllhbyrktr/Urho3D,victorholt/Urho3D,c4augustus/Urho3D,kostik1337/Urho3D,abdllhbyrktr/Urho3D,PredatorMF/Urho3D,helingping/Urho3D,rokups/Urho3D,MeshGeometry/Urho3D,MonkeyFirst/Urho3D,henu/Urho3D,eugeneko/Urho3D,PredatorMF/Urho3D,iainmerrick/Urho3D,codedash64/Urho3D,victorholt/Urho3D,urho3d/Urho3D,tommy3/Urho3D,MonkeyFirst/Urho3D,SirNate0/Urho3D,orefkov/Urho3D,rokups/Urho3D,urho3d/Urho3D,carnalis/Urho3D,fire/Urho3D-1,victorholt/Urho3D,weitjong/Urho3D,tommy3/Urho3D,PredatorMF/Urho3D,cosmy1/Urho3D,rokups/Urho3D,henu/Urho3D,bacsmar/Urho3D,abdllhbyrktr/Urho3D,MeshGeometry/Urho3D,iainmerrick/Urho3D,carnalis/Urho3D,SirNate0/Urho3D,SuperWangKai/Urho3D,urho3d/Urho3D,kostik1337/Urho3D,abdllhbyrktr/Urho3D,cosmy1/Urho3D,xiliu98/Urho3D,MeshGeometry/Urho3D,luveti/Urho3D,SuperWangKai/Urho3D,MeshGeometry/Urho3D,kostik1337/Urho3D,MonkeyFirst/Urho3D,c4augustus/Urho3D,abdllhbyrktr/Urho3D,helingping/Urho3D,fire/Urho3D-1,eugeneko/Urho3D,c4augustus/Urho3D,MeshGeometry/Urho3D,henu/Urho3D,henu/Urho3D,carnalis/Urho3D,iainmerrick/Urho3D,weitjong/Urho3D,299299/Urho3D,helingping/Urho3D,fire/Urho3D-1,c4augustus/Urho3D,luveti/Urho3D,cosmy1/Urho3D,weitjong/Urho3D,cosmy1/Urho3D,xiliu98/Urho3D,victorholt/Urho3D,eugeneko/Urho3D,henu/Urho3D,orefkov/Urho3D,codedash64/Urho3D,codemon66/Urho3D,victorholt/Urho3D,rokups/Urho3D,SirNate0/Urho3D,weitjong/Urho3D,codedash64/Urho3D,bacsmar/Urho3D,rokups/Urho3D
db799c930ede0248b2c65eb2588166ac92434dc1
flex_src/src/com/nathancolgate/S3Signature.as
flex_src/src/com/nathancolgate/S3Signature.as
package com.nathancolgate { import com.elctech.S3UploadOptions; import com.adobe.net.MimeTypeMap; import flash.events.EventDispatcher; import flash.events.ProgressEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.events.HTTPStatusEvent; import flash.events.DataEvent; import flash.external.ExternalInterface; import flash.net.FileReference; import flash.net.URLVariables; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLRequestHeader; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; public class S3Signature extends EventDispatcher { [Event(name="complete", type="flash.event.COMPLETE")] public var upload_options:S3UploadOptions; private var signatureLoader:URLLoader; private var request:URLRequest; public function S3Signature(file:FileReference, signature:String, option_params:Object, file_params:Object) { upload_options = new S3UploadOptions; upload_options.FileSize = file.size.toString(); upload_options.FileName = getFileName(file); upload_options.ContentType = getContentType(upload_options.FileName); upload_options.key = upload_options.FileName; var variables:URLVariables = new URLVariables(); variables.key = upload_options.key; variables.content_type = upload_options.ContentType; var key:String; for(key in option_params) { if(option_params[key] is String) variables[key] = option_params[key]; } for(key in file_params) { if(file_params[key] is String) variables[key] = file_params[key]; } request = new URLRequest(signature); request.method = URLRequestMethod.GET; request.data = variables; signatureLoader = new URLLoader(); signatureLoader.dataFormat = URLLoaderDataFormat.TEXT; signatureLoader.addEventListener(Event.COMPLETE, onComplete); } public function load():void { signatureLoader.load(request); } private function onComplete(event:Event):void { var loader:URLLoader = URLLoader(event.target); var xml:XML = new XML(loader.data); upload_options.policy = xml.policy; upload_options.signature = xml.signature; upload_options.bucket = xml.bucket; upload_options.AWSAccessKeyId = xml.accesskeyid; upload_options.acl = xml.acl; upload_options.Expires = xml.expirationdate; upload_options.Secure = xml.https; upload_options.key = xml.key; upload_options.ContentDisposition = xml.contentdisposition; dispatchEvent(event); } private function getContentType(fileName:String):String { var fileNameArray:Array = fileName.split(/\./); var fileExtension:String = fileNameArray[fileNameArray.length - 1]; var mimeMap:MimeTypeMap = new MimeTypeMap; var contentType:String = mimeMap.getMimeType(fileExtension); return contentType; } private function getFileName(file:FileReference):String { var fileName:String = file.name.replace(/^.*(\\|\/)/gi, '').replace(/[^A-Za-z0-9\.\-]/gi, '_'); return fileName; } } }
package com.nathancolgate { import com.elctech.S3UploadOptions; import com.adobe.net.MimeTypeMap; import flash.events.EventDispatcher; import flash.events.ProgressEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.events.HTTPStatusEvent; import flash.events.DataEvent; import flash.external.ExternalInterface; import flash.net.FileReference; import flash.net.URLVariables; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLRequestHeader; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; public class S3Signature extends EventDispatcher { [Event(name="complete", type="flash.event.COMPLETE")] public var upload_options:S3UploadOptions; private var signatureLoader:URLLoader; private var request:URLRequest; public function S3Signature(file:FileReference, signature:String, option_params:Object, file_params:Object) { upload_options = new S3UploadOptions; upload_options.FileSize = file.size.toString(); upload_options.FileName = getFileName(file); upload_options.ContentType = getContentType(upload_options.FileName); upload_options.key = upload_options.FileName; var variables:URLVariables = new URLVariables(); variables.key = upload_options.key; variables.content_type = upload_options.ContentType; var key:String; for(key in option_params) { if(option_params[key] is String) variables[key] = option_params[key]; } for(key in file_params) { if(file_params[key] is String) variables[key] = file_params[key]; } request = new URLRequest(signature); request.method = URLRequestMethod.POST; request.data = variables; request.contentType = 'application/x-www-form-urlencoded'; signatureLoader = new URLLoader(); signatureLoader.dataFormat = URLLoaderDataFormat.TEXT; signatureLoader.addEventListener(Event.COMPLETE, onComplete); } public function load():void { signatureLoader.load(request); } private function onComplete(event:Event):void { var loader:URLLoader = URLLoader(event.target); var xml:XML = new XML(loader.data); upload_options.policy = xml.policy; upload_options.signature = xml.signature; upload_options.bucket = xml.bucket; upload_options.AWSAccessKeyId = xml.accesskeyid; upload_options.acl = xml.acl; upload_options.Expires = xml.expirationdate; upload_options.Secure = xml.https; upload_options.key = xml.key; upload_options.ContentDisposition = xml.contentdisposition; dispatchEvent(event); } private function getContentType(fileName:String):String { var fileNameArray:Array = fileName.split(/\./); var fileExtension:String = fileNameArray[fileNameArray.length - 1]; var mimeMap:MimeTypeMap = new MimeTypeMap; var contentType:String = mimeMap.getMimeType(fileExtension); return contentType; } private function getFileName(file:FileReference):String { var fileName:String = file.name.replace(/^.*(\\|\/)/gi, '').replace(/[^A-Za-z0-9\.\-]/gi, '_'); return fileName; } } }
use POST when interactive with signature endpoint
use POST when interactive with signature endpoint
ActionScript
mit
icebreaker/s3-swf-upload-plugin,icebreaker/s3-swf-upload-plugin
53529bf88f62f5a734ca5d89027601fb820f37dc
src/main/actionscript/com/castlabs/dash/utils/SmoothMonitor.as
src/main/actionscript/com/castlabs/dash/utils/SmoothMonitor.as
/* * Copyright (c) 2014 castLabs GmbH * * 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 com.castlabs.dash.utils { import com.castlabs.dash.DashContext; import flash.events.EventDispatcher; import flash.events.NetStatusEvent; import org.osmf.net.NetStreamCodes; public class SmoothMonitor { private static const ACCEPTED_BUFFERING_COUNT:uint = 1; private var _context:DashContext; private var _bufferingCount:Number = 0; public function SmoothMonitor(context:DashContext) { _context = context; } public function appendListeners(netStream:EventDispatcher):void { netStream.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus); } private function onNetStatus(event:NetStatusEvent):void { if (event.info.code == NetStreamCodes.NETSTREAM_BUFFER_EMPTY) { _bufferingCount++; _context.console.warn("Registered buffering incident, bufferingCount='" + _bufferingCount + "'"); } if (event.info.code == NetStreamCodes.NETSTREAM_SEEK_NOTIFY) { _bufferingCount = 0; _context.console.info("Reset buffering incidents counter"); } } public function get fix():Number { var fix:Number = _bufferingCount - ACCEPTED_BUFFERING_COUNT; return fix > 0 ? fix : 0; } } }
/* * Copyright (c) 2014 castLabs GmbH * * 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 com.castlabs.dash.utils { import com.castlabs.dash.DashContext; import flash.events.EventDispatcher; import flash.events.NetStatusEvent; import com.castlabs.dash.utils.NetStreamCodes; public class SmoothMonitor { private static const ACCEPTED_BUFFERING_COUNT:uint = 1; private var _context:DashContext; private var _bufferingCount:Number = 0; public function SmoothMonitor(context:DashContext) { _context = context; } public function appendListeners(netStream:EventDispatcher):void { netStream.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus); } private function onNetStatus(event:NetStatusEvent):void { if (event.info.code == NetStreamCodes.NETSTREAM_BUFFER_EMPTY) { _bufferingCount++; _context.console.warn("Registered buffering incident, bufferingCount='" + _bufferingCount + "'"); } if (event.info.code == NetStreamCodes.NETSTREAM_SEEK_NOTIFY) { _bufferingCount = 0; _context.console.info("Reset buffering incidents counter"); } } public function get fix():Number { var fix:Number = _bufferingCount - ACCEPTED_BUFFERING_COUNT; return fix > 0 ? fix : 0; } } }
Change OSMF NetStreamCodes to utils package
Change OSMF NetStreamCodes to utils package
ActionScript
mpl-2.0
XamanSoft/dashas,XamanSoft/dashas,XamanSoft/dashas
072ea8e5dc3716f678e3a20276ddaf40272523ee
src/aerys/minko/render/shader/SFloat.as
src/aerys/minko/render/shader/SFloat.as
package aerys.minko.render.shader { import aerys.minko.ns.minko_shader; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.compiler.graph.nodes.leaf.Constant; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Extract; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Instruction; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Overwriter; import aerys.minko.render.shader.compiler.register.Components; import aerys.minko.type.math.Matrix4x4; import flash.utils.Proxy; import flash.utils.flash_proxy; /** * SFloat (Shader Float) objects are GPU-side computed value proxies * declared, defined and used in ActionScript shaders. * * <p> * ActionScript shaders define what operations will be * performed on the GPU. Those operations take arguments and return * values that will be computed and accessible on the graphics hardware * only. Those values are represented by SFloat objects. * </p> * * <p> * Because SFloat objects are just hardware memory proxies, it is not * possible (and does not make sense to try) to read their actual value * using CPU-side code. For the very same reason, most of the errors will * be detected at runtime only. The only available property is the size * (number of components) of the corresponding value (ie. 3D vector * operations will return SFloat objects of size 3, dot-product will * return a scalar SFloat object of size 1, ...). * </p> * * <p> * SFloat objects also provide OOP shader programming by encapsulating * common operations (add, multiply, ...). They also allow the use of * dynamic properties in order to read or write sub-components of * non-scalar values. Example: * </p> * * <pre> * public function getOutputColor() : void * { * var diffuse : SFloat = sampleTexture(BasicStyle.DIFFUSE_MAP); * * // use the RGB components of the diffuse map but use a * // fixed alpha = 0.5 * return combine(diffuse.rgb, 0.5); * } * </pre> * * <p> * Each SFloat object wraps a shader graph node that will be evaluated * by the compiler in order to create the corresponding AGAL bytecode. * </p> * * @author Jean-Marc Le Roux * */ public dynamic final class SFloat extends Proxy { use namespace minko_shader; minko_shader var _node : AbstractNode = null; public final function get size() : uint { return _node.size; } public function SFloat(value : Object) { _node = getNode(value); } public final function scaleBy(arg : Object) : SFloat { _node = new Instruction(Instruction.MUL, _node, getNode(arg)); return this; } public final function incrementBy(value : Object) : SFloat { _node = new Instruction(Instruction.ADD, _node, getNode(value)); return this; } public final function decrementBy(value : Object) : SFloat { _node = new Instruction(Instruction.SUB, _node, getNode(value)); return this; } public final function normalize() : SFloat { _node = new Instruction(Instruction.NRM, _node); return this; } public final function negate() : SFloat { _node = new Instruction(Instruction.NEG, _node); return this; } override flash_proxy function getProperty(name : *) : * { return new SFloat(new Extract(_node, Components.stringToComponent(name))); } override flash_proxy function setProperty(name : *, value : *) : void { var nodeComponent : uint = Components.createContinuous(0, 0, _node.size, _node.size); var propertyComponent : uint = Components.stringToComponent(name); var propertyNode : AbstractNode = getNode(value); _node = new Overwriter( new <AbstractNode>[_node, propertyNode], new <uint>[nodeComponent, propertyComponent] ); } private function getNode(value : Object) : AbstractNode { if (value is AbstractNode) return value as AbstractNode; if (value is SFloat) return (value as SFloat)._node; if (value is uint || value is int || value is Number) return new Constant(new <Number>[Number(value)]); if (value is Matrix4x4) return new Constant(Matrix4x4(value).getRawData(null, 0, false)); throw new Error('This type cannot be casted to a shader value.'); } } }
package aerys.minko.render.shader { import aerys.minko.ns.minko_shader; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.compiler.graph.nodes.leaf.Constant; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Extract; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Instruction; import aerys.minko.render.shader.compiler.graph.nodes.vertex.Overwriter; import aerys.minko.render.shader.compiler.register.Components; import aerys.minko.type.math.Matrix4x4; import flash.utils.Proxy; import flash.utils.flash_proxy; /** * SFloat (Shader Float) objects are GPU-side computed value proxies * declared, defined and used in ActionScript shaders. * * <p> * ActionScript shaders define what operations will be * performed on the GPU. Those operations take arguments and return * values that will be computed and accessible on the graphics hardware * only. Those values are represented by SFloat objects. * </p> * * <p> * Because SFloat objects are just hardware memory proxies, it is not * possible (and does not make sense to try) to read their actual value * using CPU-side code. For the very same reason, most of the errors will * be detected at runtime only. The only available property is the size * (number of components) of the corresponding value (ie. 3D vector * operations will return SFloat objects of size 3, dot-product will * return a scalar SFloat object of size 1, ...). * </p> * * <p> * SFloat objects also provide OOP shader programming by encapsulating * common operations (add, multiply, ...). They also allow the use of * dynamic properties in order to read or write sub-components of * non-scalar values. Example: * </p> * * <pre> * public function getOutputColor() : void * { * var diffuse : SFloat = sampleTexture(BasicStyle.DIFFUSE_MAP); * * // use the RGB components of the diffuse map but use a * // fixed alpha = 0.5 * return combine(diffuse.rgb, 0.5); * } * </pre> * * <p> * Each SFloat object wraps a shader graph node that will be evaluated * by the compiler in order to create the corresponding AGAL bytecode. * </p> * * @author Jean-Marc Le Roux * */ public dynamic final class SFloat extends Proxy { use namespace minko_shader; minko_shader var _node : AbstractNode = null; public final function get size() : uint { return _node.size; } public function SFloat(value : Object) { _node = getNode(value); } public final function scaleBy(arg : Object) : SFloat { _node = new Instruction(Instruction.MUL, _node, getNode(arg)); return this; } public final function incrementBy(value : Object) : SFloat { _node = new Instruction(Instruction.ADD, _node, getNode(value)); return this; } public final function decrementBy(value : Object) : SFloat { _node = new Instruction(Instruction.SUB, _node, getNode(value)); return this; } public final function normalize() : SFloat { _node = new Instruction(Instruction.NRM, _node); return this; } public final function negate() : SFloat { _node = new Instruction(Instruction.NEG, _node); return this; } override flash_proxy function getProperty(name : *) : * { return new SFloat(new Extract(_node, Components.stringToComponent(name))); } override flash_proxy function setProperty(name : *, value : *) : void { var propertyName : String = String(name); var propertyComponent : uint = getPropertyWriteComponentMask(propertyName); var propertyNode : AbstractNode = getNode(value); var nodeComponent : uint = Components.createContinuous(0, 0, _node.size, _node.size); propertyNode = new Overwriter( new <AbstractNode>[propertyNode], new <uint>[Components.createContinuous(0, 0, 4, propertyNode.size)] ); _node = new Overwriter( new <AbstractNode>[_node, propertyNode], new <uint>[nodeComponent, propertyComponent] ); } public static function getPropertyWriteComponentMask(string : String) : uint { var result : uint = 0x04040404; for (var i : uint = 0; i < 4; ++i) if (i < string.length) switch (string.charAt(i)) { case 'x': case 'X': case 'r': case 'R': result = (0xffffff00 & result) | i; result |= i << (8 * 0); break; case 'y': case 'Y': case 'g': case 'G': result = (0xffff00ff & result) | i << 8; break; case 'z': case 'Z': case 'b': case 'B': result = (0xff00ffff & result) | i << 16; break; case 'w': case 'W': case 'a': case 'A': result = (0x00ffffff & result) | i << 24; break; default: throw new Error('Invalid string.'); } return result; } private function getNode(value : Object) : AbstractNode { if (value is AbstractNode) return value as AbstractNode; if (value is SFloat) return (value as SFloat)._node; if (value is uint || value is int || value is Number) return new Constant(new <Number>[Number(value)]); if (value is Matrix4x4) return new Constant(Matrix4x4(value).getRawData(null, 0, false)); throw new Error('This type cannot be casted to a shader value.'); } } }
fix SFloat.setProperty()
fix SFloat.setProperty()
ActionScript
mit
aerys/minko-as3
35dd9e9635e4cf51e9650c3899baf4c2b7b01bca
test/src/FRESteamWorksTest.as
test/src/FRESteamWorksTest.as
/* * FRESteamWorks.h * This file is part of FRESteamWorks. * * Created by David ´Oldes´ Oliva on 3/29/12. * Contributors: Ventero <http://github.com/Ventero> * Copyright (c) 2012 Amanita Design. All rights reserved. * Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved. */ package { import com.amanitadesign.steam.FRESteamWorks; import com.amanitadesign.steam.SteamConstants; import com.amanitadesign.steam.SteamEvent; import com.amanitadesign.steam.WorkshopConstants; import flash.desktop.NativeApplication; import flash.display.SimpleButton; import flash.display.Sprite; import flash.display.StageDisplayState; import flash.events.Event; import flash.events.MouseEvent; import flash.text.TextField; import flash.utils.ByteArray; public class FRESteamWorksTest extends Sprite { public var Steamworks:FRESteamWorks = new FRESteamWorks(); public var tf:TextField; private var _buttonPos:int = 5; private var _appId:uint; public function FRESteamWorksTest() { tf = new TextField(); tf.x = 160; tf.width = stage.stageWidth - tf.x; tf.height = stage.stageHeight; addChild(tf); addButton("Check stats/achievements", checkAchievements); addButton("Toggle achievement", toggleAchievement); addButton("Toggle cloud enabled", toggleCloudEnabled); addButton("Toggle file", toggleFile); addButton("Publish file", publishFile); addButton("Toggle fullscreen", toggleFullscreen); addButton("Show Friends overlay", activateOverlay); addButton("List subscribed files", enumerateSubscribedFiles); addButton("List shared files", enumerateSharedFiles); addButton("List workshop files", enumerateWorkshopFiles); Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse); Steamworks.addOverlayWorkaround(stage, true); NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit); try { //Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20"); if(!Steamworks.init()){ log("STEAMWORKS API is NOT available"); return; } log("STEAMWORKS API is available\n"); log("User ID: " + Steamworks.getUserID()); _appId = Steamworks.getAppID(); log("App ID: " + _appId); log("Persona name: " + Steamworks.getPersonaName()); log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp()); log("getFileCount() == "+Steamworks.getFileCount()); log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt')); log("getDLCCount() == " + Steamworks.getDLCCount()); Steamworks.resetAllStats(true); } catch(e:Error) { log("*** ERROR ***"); log(e.message); log(e.getStackTrace()); } } private function log(value:String):void{ tf.appendText(value+"\n"); tf.scrollV = tf.maxScrollV; } public function writeFileToCloud(fileName:String, data:String):Boolean { var dataOut:ByteArray = new ByteArray(); dataOut.writeUTFBytes(data); return Steamworks.fileWrite(fileName, dataOut); } public function readFileFromCloud(fileName:String):String { var dataIn:ByteArray = new ByteArray(); var result:String; dataIn.position = 0; dataIn.length = Steamworks.getFileSize(fileName); if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){ result = dataIn.readUTFBytes(dataIn.length); } return result; } private function checkAchievements(e:Event = null):void { if(!Steamworks.isReady) return; // current stats and achievement ids are from steam example app log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME")); log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE")); log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3)); log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2)); Steamworks.storeStats(); log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames')); log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled')); } private function toggleAchievement(e:Event = null):void{ if(!Steamworks.isReady) return; var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME"); log("isAchievement('ACH_WIN_ONE_GAME') == " + result); if(!result) { log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME")); } else { log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME")); } } private function toggleCloudEnabled(e:Event = null):void { if(!Steamworks.isReady) return; var enabled:Boolean = Steamworks.isCloudEnabledForApp(); log("isCloudEnabledForApp() == " + enabled); log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled)); log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp()); } private function toggleFile(e:Event = null):void { if(!Steamworks.isReady) return; var result:Boolean = Steamworks.fileExists('test.txt'); log("fileExists('test.txt') == " + result); if(result){ log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') ); log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt')); } else { log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click')); } } private function publishFile(e:Event = null):void { if(!Steamworks.isReady) return; var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId, "Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private, ["TestTag"], WorkshopConstants.FILETYPE_Community); log("publishWorkshopFile('test.txt' ...) == " + res); } private function toggleFullscreen(e:Event = null):void { if(stage.displayState == StageDisplayState.NORMAL) stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; else stage.displayState = StageDisplayState.NORMAL; } private function activateOverlay(e:Event = null):void { if(!Steamworks.isReady) return; log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled()); log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends")); log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled()); } private function enumerateSubscribedFiles(e:Event = null):void { if(!Steamworks.isReady) return; log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0)); } private function enumerateSharedFiles(e:Event = null):void { if(!Steamworks.isReady) return; var userID:String = Steamworks.getUserID(); var res:Boolean = Steamworks.enumerateUserSharedWorkshopFiles(userID, 0, [], []); log("enumerateSharedFiles(" + userID + ", 0, [], []) == " + res); } private function enumerateWorkshopFiles(e:Event = null):void { if(!Steamworks.isReady) return; var res:Boolean = Steamworks.enumeratePublishedWorkshopFiles( WorkshopConstants.ENUMTYPE_RankedByVote, 0, 10, 0, [], []); log("enumerateSharedFiles(...) == " + res); } private var id:String; private var handle:String; private function onSteamResponse(e:SteamEvent):void{ var apiCall:Boolean; var i:int; var file:String; switch(e.req_type){ case SteamConstants.RESPONSE_OnUserStatsStored: log("RESPONSE_OnUserStatsStored: "+e.response); break; case SteamConstants.RESPONSE_OnUserStatsReceived: log("RESPONSE_OnUserStatsReceived: "+e.response); break; case SteamConstants.RESPONSE_OnAchievementStored: log("RESPONSE_OnAchievementStored: "+e.response); break; case SteamConstants.RESPONSE_OnPublishWorkshopFile: log("RESPONSE_OnPublishWorkshopFile: " + e.response); file = Steamworks.publishWorkshopFileResult(); log("File published as " + file); log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file)); break; case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles: log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response); var subRes:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult(); log("User subscribed files: " + subRes.resultsReturned + "/" + subRes.totalResults); for(i = 0; i < subRes.resultsReturned; i++) { id = subRes.publishedFileId[i]; apiCall = Steamworks.getPublishedFileDetails(subRes.publishedFileId[i]); log(i + ": " + subRes.publishedFileId[i] + " (" + subRes.timeSubscribed[i] + ") - " + apiCall); } break; case SteamConstants.RESPONSE_OnEnumerateUserSharedWorkshopFiles: log("RESPONSE_OnEnumerateUserSharedWorkshopFiles: " + e.response); var userRes:UserFilesResult = Steamworks.enumerateUserSharedWorkshopFilesResult(); log("User shared files: " + userRes.resultsReturned + "/" + userRes.totalResults); for(i = 0; i < userRes.resultsReturned; i++) { log(i + ": " + userRes.publishedFileId[i]); } break; case SteamConstants.RESPONSE_OnEnumeratePublishedWorkshopFiles: log("RESPONSE_OnEnumeratePublishedWorkshopFiles: " + e.response); var fileRes:WorkshopFilesResult = Steamworks.enumeratePublishedWorkshopFilesResult(); log("Workshop files: " + fileRes.resultsReturned + "/" + fileRes.totalResults); for(i = 0; i < fileRes.resultsReturned; i++) { log(i + ": " + fileRes.publishedFileId[i] + " - " + fileRes.score[i]); } if(fileRes.resultsReturned > 0) { file = fileRes.publishedFileId[0]; log("updateUserPublishedItemVote(" + file + ", true)"); apiCall = Steamworks.updateUserPublishedItemVote(file, true); log("updateUserPublishedItemVote(" + file + ", true) == " + apiCall); } break; case SteamConstants.RESPONSE_OnGetPublishedFileDetails: log("RESPONSE_OnGetPublishedFileDetails: " + e.response); var res:FileDetailsResult = Steamworks.getPublishedFileDetailsResult(id); log("Result for " + id + ": " + res); if(res) { log("File: " + res.fileName + ", handle: " + res.fileHandle); handle = res.fileHandle; apiCall = Steamworks.UGCDownload(res.fileHandle, 0); log("UGCDownload(...) == " + apiCall); } break; case SteamConstants.RESPONSE_OnUGCDownload: log("RESPONSE_OnUGCDownload: " + e.response); var ugcResult:DownloadUGCResult = Steamworks.getUGCDownloadResult(handle); log("Result for " + handle + ": " + ugcResult); if(ugcResult) { log("File: " + ugcResult.fileName + ", handle: " + ugcResult.fileHandle + ", size: " + ugcResult.size); var ba:ByteArray = new ByteArray(); ba.length = ugcResult.size; apiCall = Steamworks.UGCRead(ugcResult.fileHandle, ugcResult.size, 0, ba); log("UGCRead(...) == " + apiCall); if(apiCall) { log("Result length: " + ba.position + "//" + ba.length); log("Result: " + ba.readUTFBytes(ugcResult.size)); } } break; default: log("STEAMresponse type:"+e.req_type+" response:"+e.response); } } private function onExit(e:Event):void{ log("Exiting application, cleaning up"); Steamworks.dispose(); } private function addButton(label:String, callback:Function):void { var button:Sprite = new Sprite(); button.graphics.beginFill(0xaaaaaa); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); button.buttonMode = true; button.useHandCursor = true; button.addEventListener(MouseEvent.CLICK, callback); button.x = 5; button.y = _buttonPos; _buttonPos += button.height + 5; button.addEventListener(MouseEvent.MOUSE_OVER, function(e:MouseEvent):void { button.graphics.clear(); button.graphics.beginFill(0xccccccc); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); }); button.addEventListener(MouseEvent.MOUSE_OUT, function(e:MouseEvent):void { button.graphics.clear(); button.graphics.beginFill(0xaaaaaa); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); }); var text:TextField = new TextField(); text.text = label; text.width = 140; text.height = 25; text.x = 5; text.y = 5; text.mouseEnabled = false; button.addChild(text); addChild(button); } } }
/* * FRESteamWorks.h * This file is part of FRESteamWorks. * * Created by David ´Oldes´ Oliva on 3/29/12. * Contributors: Ventero <http://github.com/Ventero> * Copyright (c) 2012 Amanita Design. All rights reserved. * Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved. */ package { import com.amanitadesign.steam.FRESteamWorks; import com.amanitadesign.steam.SteamConstants; import com.amanitadesign.steam.SteamEvent; import com.amanitadesign.steam.WorkshopConstants; import flash.desktop.NativeApplication; import flash.display.SimpleButton; import flash.display.Sprite; import flash.display.StageDisplayState; import flash.events.Event; import flash.events.MouseEvent; import flash.text.TextField; import flash.utils.ByteArray; public class FRESteamWorksTest extends Sprite { public var Steamworks:FRESteamWorks = new FRESteamWorks(); public var tf:TextField; private var _buttonPos:int = 5; private var _appId:uint; public function FRESteamWorksTest() { tf = new TextField(); tf.x = 160; tf.width = stage.stageWidth - tf.x; tf.height = stage.stageHeight; addChild(tf); addButton("Check stats/achievements", checkAchievements); addButton("Toggle achievement", toggleAchievement); addButton("Toggle cloud enabled", toggleCloudEnabled); addButton("Toggle file", toggleFile); addButton("Publish file", publishFile); addButton("Toggle fullscreen", toggleFullscreen); addButton("Show Friends overlay", activateOverlay); addButton("List subscribed files", enumerateSubscribedFiles); addButton("List shared files", enumerateSharedFiles); addButton("List workshop files", enumerateWorkshopFiles); addButton("Change file description", updateFile); Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse); Steamworks.addOverlayWorkaround(stage, true); NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit); try { //Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20"); if(!Steamworks.init()){ log("STEAMWORKS API is NOT available"); return; } log("STEAMWORKS API is available\n"); log("User ID: " + Steamworks.getUserID()); _appId = Steamworks.getAppID(); log("App ID: " + _appId); log("Persona name: " + Steamworks.getPersonaName()); log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp()); log("getFileCount() == "+Steamworks.getFileCount()); log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt')); log("getDLCCount() == " + Steamworks.getDLCCount()); Steamworks.resetAllStats(true); } catch(e:Error) { log("*** ERROR ***"); log(e.message); log(e.getStackTrace()); } } private function log(value:String):void{ tf.appendText(value+"\n"); tf.scrollV = tf.maxScrollV; } public function writeFileToCloud(fileName:String, data:String):Boolean { var dataOut:ByteArray = new ByteArray(); dataOut.writeUTFBytes(data); return Steamworks.fileWrite(fileName, dataOut); } public function readFileFromCloud(fileName:String):String { var dataIn:ByteArray = new ByteArray(); var result:String; dataIn.position = 0; dataIn.length = Steamworks.getFileSize(fileName); if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){ result = dataIn.readUTFBytes(dataIn.length); } return result; } private function checkAchievements(e:Event = null):void { if(!Steamworks.isReady) return; // current stats and achievement ids are from steam example app log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME")); log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE")); log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3)); log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2)); Steamworks.storeStats(); log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames')); log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled')); } private function toggleAchievement(e:Event = null):void{ if(!Steamworks.isReady) return; var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME"); log("isAchievement('ACH_WIN_ONE_GAME') == " + result); if(!result) { log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME")); } else { log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME")); } } private function toggleCloudEnabled(e:Event = null):void { if(!Steamworks.isReady) return; var enabled:Boolean = Steamworks.isCloudEnabledForApp(); log("isCloudEnabledForApp() == " + enabled); log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled)); log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp()); } private function toggleFile(e:Event = null):void { if(!Steamworks.isReady) return; var result:Boolean = Steamworks.fileExists('test.txt'); log("fileExists('test.txt') == " + result); if(result){ log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') ); log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt')); } else { log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click')); } } private function publishFile(e:Event = null):void { if(!Steamworks.isReady) return; var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId, "Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private, ["TestTag"], WorkshopConstants.FILETYPE_Community); log("publishWorkshopFile('test.txt' ...) == " + res); } private function toggleFullscreen(e:Event = null):void { if(stage.displayState == StageDisplayState.NORMAL) stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; else stage.displayState = StageDisplayState.NORMAL; } private function activateOverlay(e:Event = null):void { if(!Steamworks.isReady) return; log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled()); log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends")); log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled()); } private function enumerateSubscribedFiles(e:Event = null):void { if(!Steamworks.isReady) return; log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0)); } private function enumerateSharedFiles(e:Event = null):void { if(!Steamworks.isReady) return; var userID:String = Steamworks.getUserID(); var res:Boolean = Steamworks.enumerateUserSharedWorkshopFiles(userID, 0, [], []); log("enumerateSharedFiles(" + userID + ", 0, [], []) == " + res); } private function enumerateWorkshopFiles(e:Event = null):void { if(!Steamworks.isReady) return; var res:Boolean = Steamworks.enumeratePublishedWorkshopFiles( WorkshopConstants.ENUMTYPE_RankedByVote, 0, 10, 0, [], []); log("enumerateSharedFiles(...) == " + res); } private function updateFile(e:Event = null):void { if(!file) { log("No file handle set, publish or enumerate first"); return; } var handle:String = Steamworks.createPublishedFileUpdateRequest(file); var res:Boolean = Steamworks.updatePublishedFileDescription(handle, "Test updated description"); log("updatePublishedFileDescription(" + handle + ", ...) == " + res); if(!res) return; res = Steamworks.commitPublishedFileUpdate(handle); log("commitPublishedFileUpdate(...) == " + res); } private var id:String; private var handle:String; private var file:String; private function onSteamResponse(e:SteamEvent):void{ var apiCall:Boolean; var i:int; switch(e.req_type){ case SteamConstants.RESPONSE_OnUserStatsStored: log("RESPONSE_OnUserStatsStored: "+e.response); break; case SteamConstants.RESPONSE_OnUserStatsReceived: log("RESPONSE_OnUserStatsReceived: "+e.response); break; case SteamConstants.RESPONSE_OnAchievementStored: log("RESPONSE_OnAchievementStored: "+e.response); break; case SteamConstants.RESPONSE_OnPublishWorkshopFile: log("RESPONSE_OnPublishWorkshopFile: " + e.response); file = Steamworks.publishWorkshopFileResult(); log("File published as " + file); log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file)); break; case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles: log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response); var subRes:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult(); log("User subscribed files: " + subRes.resultsReturned + "/" + subRes.totalResults); for(i = 0; i < subRes.resultsReturned; i++) { id = subRes.publishedFileId[i]; apiCall = Steamworks.getPublishedFileDetails(subRes.publishedFileId[i]); log(i + ": " + subRes.publishedFileId[i] + " (" + subRes.timeSubscribed[i] + ") - " + apiCall); } break; case SteamConstants.RESPONSE_OnEnumerateUserSharedWorkshopFiles: log("RESPONSE_OnEnumerateUserSharedWorkshopFiles: " + e.response); var userRes:UserFilesResult = Steamworks.enumerateUserSharedWorkshopFilesResult(); log("User shared files: " + userRes.resultsReturned + "/" + userRes.totalResults); for(i = 0; i < userRes.resultsReturned; i++) { log(i + ": " + userRes.publishedFileId[i]); } break; case SteamConstants.RESPONSE_OnEnumeratePublishedWorkshopFiles: log("RESPONSE_OnEnumeratePublishedWorkshopFiles: " + e.response); var fileRes:WorkshopFilesResult = Steamworks.enumeratePublishedWorkshopFilesResult(); log("Workshop files: " + fileRes.resultsReturned + "/" + fileRes.totalResults); for(i = 0; i < fileRes.resultsReturned; i++) { log(i + ": " + fileRes.publishedFileId[i] + " - " + fileRes.score[i]); } if(fileRes.resultsReturned > 0) { file = fileRes.publishedFileId[0]; log("updateUserPublishedItemVote(" + file + ", true)"); apiCall = Steamworks.updateUserPublishedItemVote(file, true); log("updateUserPublishedItemVote(" + file + ", true) == " + apiCall); } break; case SteamConstants.RESPONSE_OnGetPublishedFileDetails: log("RESPONSE_OnGetPublishedFileDetails: " + e.response); var res:FileDetailsResult = Steamworks.getPublishedFileDetailsResult(id); log("Result for " + id + ": " + res); if(res) { log("File: " + res.fileName + ", handle: " + res.fileHandle); handle = res.fileHandle; apiCall = Steamworks.UGCDownload(res.fileHandle, 0); log("UGCDownload(...) == " + apiCall); } break; case SteamConstants.RESPONSE_OnUGCDownload: log("RESPONSE_OnUGCDownload: " + e.response); var ugcResult:DownloadUGCResult = Steamworks.getUGCDownloadResult(handle); log("Result for " + handle + ": " + ugcResult); if(ugcResult) { log("File: " + ugcResult.fileName + ", handle: " + ugcResult.fileHandle + ", size: " + ugcResult.size); var ba:ByteArray = new ByteArray(); ba.length = ugcResult.size; apiCall = Steamworks.UGCRead(ugcResult.fileHandle, ugcResult.size, 0, ba); log("UGCRead(...) == " + apiCall); if(apiCall) { log("Result length: " + ba.position + "//" + ba.length); log("Result: " + ba.readUTFBytes(ugcResult.size)); } } break; default: log("STEAMresponse type:"+e.req_type+" response:"+e.response); } } private function onExit(e:Event):void{ log("Exiting application, cleaning up"); Steamworks.dispose(); } private function addButton(label:String, callback:Function):void { var button:Sprite = new Sprite(); button.graphics.beginFill(0xaaaaaa); button.graphics.drawRoundRect(0, 0, 150, 25, 5, 5); button.graphics.endFill(); button.buttonMode = true; button.useHandCursor = true; button.addEventListener(MouseEvent.CLICK, callback); button.x = 5; button.y = _buttonPos; _buttonPos += button.height + 5; button.addEventListener(MouseEvent.MOUSE_OVER, function(e:MouseEvent):void { button.graphics.clear(); button.graphics.beginFill(0xccccccc); button.graphics.drawRoundRect(0, 0, 150, 25, 5, 5); button.graphics.endFill(); }); button.addEventListener(MouseEvent.MOUSE_OUT, function(e:MouseEvent):void { button.graphics.clear(); button.graphics.beginFill(0xaaaaaa); button.graphics.drawRoundRect(0, 0, 150, 25, 5, 5); button.graphics.endFill(); }); var text:TextField = new TextField(); text.text = label; text.width = 140; text.height = 25; text.x = 5; text.y = 5; text.mouseEnabled = false; button.addChild(text); addChild(button); } } }
Add test for FileUpdate stuff (only description so far)
Add test for FileUpdate stuff (only description so far)
ActionScript
bsd-2-clause
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
5cfe8db99d68d80ccef7d193c8e3c0f26c192ae6
frameworks/projects/Core/as/src/org/apache/flex/utils/Language.as
frameworks/projects/Core/as/src/org/apache/flex/utils/Language.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.utils { [ExcludeClass] COMPILE::AS3 public class Language {} COMPILE::JS public class Language { //-------------------------------------- // Static Property //-------------------------------------- //-------------------------------------- // Static Function //-------------------------------------- /** * _as() * * @export * @param {?} leftOperand The lefthand operand of the * binary as operator in AS3. * @param {?} rightOperand The righthand operand of the * binary operator in AS3. * @param {?=} coercion The cast is a coercion, * throw expception if it fails. * @return {?} Returns the lefthand operand if it is of the * type of the righthand operand, otherwise null. */ static public function _as(leftOperand:Object, rightOperand:Object, coercion:* = null):Object { var error:Error, itIs:Boolean, message:String; coercion = (coercion !== undefined) ? coercion : false; itIs = _is(leftOperand, rightOperand); if (!itIs && coercion) { message = 'Type Coercion failed'; if (TypeError) { error = new TypeError(message); } else { error = new Error(message); } throw error; } return (itIs) ? leftOperand : null; } /** * int() * * @export * @param {?} value The value to be cast. * @return {number} */ static public function _int(value:Number):int { return value >> 0; } /** * _is() * * @export * @param {?} leftOperand The lefthand operand of the * binary as operator in AS3. * @param {?} rightOperand The righthand operand of the * binary operator in AS3. * @return {boolean} */ static public function _is(leftOperand:Object, rightOperand:Object):Boolean { var checkInterfaces:Function, superClass:Object; if (!leftOperand) return false; if (leftOperand && !rightOperand) { return false; } checkInterfaces = function(left:Object):Boolean { var i:uint, interfaces:Array; interfaces = left.FLEXJS_CLASS_INFO.interfaces; for (i = interfaces.length - 1; i > -1; i--) { if (interfaces[i] === rightOperand) { return true; } if (interfaces[i].prototype.FLEXJS_CLASS_INFO.interfaces) { var isit:Boolean = checkInterfaces(new interfaces[i]()); if (isit) return true; } } return false; }; if ((rightOperand === String && typeof leftOperand === 'string') || (leftOperand instanceof /** @type {Object} */(rightOperand))) { return true; } if (typeof leftOperand === 'string') return false; // right was not String otherwise exit above if (typeof leftOperand === 'number') return rightOperand === Number; if (rightOperand === Array && Array.isArray(leftOperand)) return true; if (leftOperand.FLEXJS_CLASS_INFO === undefined) return false; // could be a function but not an instance if (leftOperand.FLEXJS_CLASS_INFO.interfaces) { if (checkInterfaces(leftOperand)) { return true; } } superClass = leftOperand.constructor.superClass_; if (superClass) { while (superClass && superClass.FLEXJS_CLASS_INFO) { if (superClass.FLEXJS_CLASS_INFO.interfaces) { if (checkInterfaces(superClass)) { return true; } } superClass = superClass.constructor.superClass_; } } return false; } /** * postdecrement handles foo++ * * @export * @param {Object} obj The object with the getter/setter. * @param {string} prop The name of a property. * @return {number} */ static public function postdecrement(obj:Object, prop:String):int { var value:int = obj[prop]; obj[prop] = value - 1; return value; } /** * postincrement handles foo++ * * @export * @param {Object} obj The object with the getter/setter. * @param {string} prop The name of a property. * @return {number} */ static public function postincrement(obj:Object, prop:String):int { var value:int = obj[prop]; obj[prop] = value + 1; return value; } /** * predecrement handles ++foo * * @export * @param {Object} obj The object with the getter/setter. * @param {string} prop The name of a property. * @return {number} */ static public function predecrement(obj:Object, prop:String):int { var value:int = obj[prop] - 1; obj[prop] = value; return value; } /** * preincrement handles --foo * * @export * @param {Object} obj The object with the getter/setter. * @param {string} prop The name of a property. * @return {number} */ static public function preincrement(obj:Object, prop:String):int { var value:int = obj[prop] + 1; obj[prop] = value; return value; } /** * superGetter calls the getter on the given class' superclass. * * @export * @param {Object} clazz The class. * @param {Object} pthis The this pointer. * @param {string} prop The name of the getter. * @return {Object} */ static public function superGetter(clazz:Object, pthis:Object, prop:String):Object { var superClass:Object = clazz.superClass_; var superdesc:Object = Object.getOwnPropertyDescriptor(superClass, prop); while (superdesc == null) { superClass = superClass.constructor.superClass_; superdesc = Object.getOwnPropertyDescriptor(superClass, prop); } return superdesc.get.call(pthis); } /** * superSetter calls the setter on the given class' superclass. * * @export * @param {Object} clazz The class. * @param {Object} pthis The this pointer. * @param {string} prop The name of the getter. * @param {Object} value The value. */ static public function superSetter(clazz:Object, pthis:Object, prop:String, value:Object):void { var superClass:Object = clazz.superClass_; var superdesc:Object = Object.getOwnPropertyDescriptor(superClass, prop); while (superdesc == null) { superClass = superClass.constructor.superClass_; superdesc = Object.getOwnPropertyDescriptor(superClass, prop); } superdesc.set.apply(pthis, [value]); } static public function trace(...rest):void { var theConsole:*; var msg:String = ''; for (var i:uint = 0; i < rest.length; i++) { if (i > 0) msg += ' '; msg += rest[i]; } theConsole = ["goog"]["global"]["console"]; if (theConsole === undefined && window.console !== undefined) theConsole = window.console; try { if (theConsole && theConsole.log) { theConsole.log(msg); } } catch (e:Error) { // ignore; at least we tried ;-) } } /** * uint() * * @export * @param {?} value The value to be cast. * @return {number} */ static public function uint(value:Number):uint { return value >>> 0; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.utils { [ExcludeClass] COMPILE::AS3 public class Language {} COMPILE::JS public class Language { //-------------------------------------- // Static Property //-------------------------------------- //-------------------------------------- // Static Function //-------------------------------------- /** * _as() * * @export * @param {?} leftOperand The lefthand operand of the * binary as operator in AS3. * @param {?} rightOperand The righthand operand of the * binary operator in AS3. * @param {?=} coercion The cast is a coercion, * throw expception if it fails. * @return {?} Returns the lefthand operand if it is of the * type of the righthand operand, otherwise null. */ static public function _as(leftOperand:Object, rightOperand:Object, coercion:* = null):Object { var error:Error, itIs:Boolean, message:String; coercion = (coercion !== undefined) ? coercion : false; itIs = _is(leftOperand, rightOperand); if (!itIs && coercion) { message = 'Type Coercion failed'; if (TypeError) { error = new TypeError(message); } else { error = new Error(message); } throw error; } return (itIs) ? leftOperand : null; } /** * int() * * @export * @param {?} value The value to be cast. * @return {number} */ static public function _int(value:Number):Number { return value >> 0; } /** * _is() * * @export * @param {?} leftOperand The lefthand operand of the * binary as operator in AS3. * @param {?} rightOperand The righthand operand of the * binary operator in AS3. * @return {boolean} */ static public function _is(leftOperand:Object, rightOperand:Object):Boolean { var checkInterfaces:Function, superClass:Object; if (!leftOperand) return false; if (leftOperand && !rightOperand) { return false; } checkInterfaces = function(left:Object):Boolean { var i:uint, interfaces:Array; interfaces = left.FLEXJS_CLASS_INFO.interfaces; for (i = interfaces.length - 1; i > -1; i--) { if (interfaces[i] === rightOperand) { return true; } if (interfaces[i].prototype.FLEXJS_CLASS_INFO.interfaces) { var isit:Boolean = checkInterfaces(new interfaces[i]()); if (isit) return true; } } return false; }; if ((rightOperand === String && typeof leftOperand === 'string') || (leftOperand instanceof /** @type {Object} */(rightOperand))) { return true; } if (typeof leftOperand === 'string') return false; // right was not String otherwise exit above if (typeof leftOperand === 'number') return rightOperand === Number; if (rightOperand === Array && Array.isArray(leftOperand)) return true; if (leftOperand.FLEXJS_CLASS_INFO === undefined) return false; // could be a function but not an instance if (leftOperand.FLEXJS_CLASS_INFO.interfaces) { if (checkInterfaces(leftOperand)) { return true; } } superClass = leftOperand.constructor.superClass_; if (superClass) { while (superClass && superClass.FLEXJS_CLASS_INFO) { if (superClass.FLEXJS_CLASS_INFO.interfaces) { if (checkInterfaces(superClass)) { return true; } } superClass = superClass.constructor.superClass_; } } return false; } /** * postdecrement handles foo++ * * @export * @param {Object} obj The object with the getter/setter. * @param {string} prop The name of a property. * @return {number} */ static public function postdecrement(obj:Object, prop:String):int { var value:int = obj[prop]; obj[prop] = value - 1; return value; } /** * postincrement handles foo++ * * @export * @param {Object} obj The object with the getter/setter. * @param {string} prop The name of a property. * @return {number} */ static public function postincrement(obj:Object, prop:String):int { var value:int = obj[prop]; obj[prop] = value + 1; return value; } /** * predecrement handles ++foo * * @export * @param {Object} obj The object with the getter/setter. * @param {string} prop The name of a property. * @return {number} */ static public function predecrement(obj:Object, prop:String):int { var value:int = obj[prop] - 1; obj[prop] = value; return value; } /** * preincrement handles --foo * * @export * @param {Object} obj The object with the getter/setter. * @param {string} prop The name of a property. * @return {number} */ static public function preincrement(obj:Object, prop:String):int { var value:int = obj[prop] + 1; obj[prop] = value; return value; } /** * superGetter calls the getter on the given class' superclass. * * @export * @param {Object} clazz The class. * @param {Object} pthis The this pointer. * @param {string} prop The name of the getter. * @return {Object} */ static public function superGetter(clazz:Object, pthis:Object, prop:String):Object { var superClass:Object = clazz.superClass_; var superdesc:Object = Object.getOwnPropertyDescriptor(superClass, prop); while (superdesc == null) { superClass = superClass.constructor.superClass_; superdesc = Object.getOwnPropertyDescriptor(superClass, prop); } return superdesc.get.call(pthis); } /** * superSetter calls the setter on the given class' superclass. * * @export * @param {Object} clazz The class. * @param {Object} pthis The this pointer. * @param {string} prop The name of the getter. * @param {Object} value The value. */ static public function superSetter(clazz:Object, pthis:Object, prop:String, value:Object):void { var superClass:Object = clazz.superClass_; var superdesc:Object = Object.getOwnPropertyDescriptor(superClass, prop); while (superdesc == null) { superClass = superClass.constructor.superClass_; superdesc = Object.getOwnPropertyDescriptor(superClass, prop); } superdesc.set.apply(pthis, [value]); } static public function trace(...rest):void { var theConsole:*; var msg:String = ''; for (var i:uint = 0; i < rest.length; i++) { if (i > 0) msg += ' '; msg += rest[i]; } theConsole = ["goog"]["global"]["console"]; if (theConsole === undefined && window.console !== undefined) theConsole = window.console; try { if (theConsole && theConsole.log) { theConsole.log(msg); } } catch (e:Error) { // ignore; at least we tried ;-) } } /** * uint() * * @export * @param {?} value The value to be cast. * @return {number} */ static public function uint(value:Number):Number { return value >>> 0; } } }
fix return type
fix return type
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
14b518dbe75992abb9cc1f8172e8510a0fa20cde
WEB-INF/lps/lfc/lzpreloader.as
WEB-INF/lps/lfc/lzpreloader.as
/** * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @affects lzpreloader * @access private * @topic LZX * @subtopic Services */ // // Code for lzpreloader frame 0 when there's a <splash> tag // This is compiled into lzpreloader.lzx which is attached to the lzpreloader // movieclip in SWFFile.java addPreloaderFrame() // // Debugging tips : // I put in a little debug code that will enables putting simple debug calls // in the code. To see the output when the debugger is up, type: // lzpreloader.trace() // It would be nice, for it to automatically output this info to the debugger // when it starts up, but I think this file isn't compiled the same way as the // LFC, since the $debug didn't seem to work. For now, you can just uncomment // the debug code below. [Sarah Allen 04-28-05] // Added text field where debug info is shown so it can be seen with debug=true // [sallen 06-06-2005] // necessary for consistent behavior - in netscape browsers HTML is ignored Stage.align = ('canvassalign' in global && global.canvassalign != null) ? global.canvassalign : "LT"; Stage.scaleMode = ('canvasscale' in global && global.canvasscale != null) ? global.canvasscale : "noScale"; /* // SWF-specific _root.createTextField("tfNewfield",1,100,10,150,700); _root.tfNewfield.text = "Splash Debugger"; _root.tfNewfield.autoSize = true; mydebugger = []; function mydebug(s) { this.mydebugger.push(s); _root.tfNewfield.text = _root.tfNewfield.text + '\n' + s; } function trace() { for (var i=0; i< this.mydebugger.length; i++) { _root.Debug.write(this.mydebugger[i]); } } */ this.protoviews = []; this.synctoloads = []; this._x = 0; this._y = 0; this._lastwidth = Stage.width; this._lastheight = Stage.height; // called by compiler (first thing) like: // lzpreloader.create({attrs: {}, name: "splash", children: // [{attrs: {x: 100, name: "logo", synctoload: true, resourcename: // logo, src: "logo.swf", y: 100}, name: "preloadresource"}]}); function create (iobj) { this.iobj = iobj } // Called by heartbeat to actually build the splash once the Stage has // non-zero size (to work around ActiveX control bug that initializes // the Stage to 0x0). function init () { if (Stage.width <= 100 || Stage.height <= 100) { // sometimes Safari still has heihgt/width 100. Be sure to hide the splash if this is the case. this.hideafterinit = true; return; } var iobj = this.iobj; delete this.iobj; this.name = iobj.name; this.hideafterinit = iobj.attrs.hideafterinit; var viewprops = {x: true, y: true, width: true, height: true}; var sr = _root.createEmptyMovieClip("spriteroot", 1000); var root = sr.createEmptyMovieClip(this.name, 0); this.splashroot = root; //this.mydebug('new root' + this.splashroot); for (var i = 0; i < iobj.children.length; i++) { var c = iobj.children[i].attrs; var n = (c.name == null) ? ("child" + i) : c.name; root.attachMovie(n, n, i + 1); var mc = root[n]; mc.name = n; this.protoviews.push(mc); // this.debug(" synctoload" + c.synctoload); if (c.synctoload) { if (c.lastframe == null) { mc.lastframe = mc._totalframes; } else { //this.mydebug('c.usepercent='+c.usepercent); mc.lastframe = c.lastframe * mc._totalframes; //this.mydebug('c.lastframe='+c.lastframe+ // 'mc.lastframe='+mc.lastframe ); } // this.debug(" synctoload" + this.synctoloads); this.synctoloads.push(mc); } for (var p in viewprops) { if (c[p] != null) { mc["_" + p] = c[p]; } } //this.debug(mc._target + " center=" + c.center); if (c.center != null) { mc._x = Stage.width / 2 - (mc._width / 2); mc._y = Stage.height / 2 - (mc._height / 2); //this.debug(" Stage.width=" + Stage.width); //this.debug(" mc._width=" + mc._width); //this.debug(" mc._x=" + mc._x); } } } this.createEmptyMovieClip("_heartbeat", 1000); this._heartbeat.onEnterFrame = function() { this._parent.heartbeat(); } // called by enterframe of the splash clip function heartbeat (p) { //this.mydebug('stage size ' + Stage.width + 'x' + Stage.height ); if (this.iobj && (Stage.width > 100 && Stage.height > 100) && (Stage.width == this._lastwidth && Stage.height == this._lastheight)) { // some browsers will pass 100% as 100 (or whatever %) for first // couple of heartbeats, ideally we would pass % from compiler // so we could ignore fewer cases and allow splash in small canvas // [sallen/max 6-05] this.init(); mc.gotoAndStop(0); } else { // SWF-specific var percload = _root.getBytesLoaded() / _root.getBytesTotal(); var id = _root.id; if (id) { var js = 'if (window.lz && lz.embed && lz.embed.applications && lz.embed.applications.' + id + ') lz.embed.applications.' + id + '._sendPercLoad(' + Math.floor(percload * 100) + ')'; _root.getURL('javascript:' + js + ';void(0);'); } for (var i = 0; i < this.synctoloads.length; i++) { var mc = this.synctoloads[i]; var p = Math.floor(mc.lastframe * percload); mc.gotoAndStop(p); } //this.mydebug('percent done='+p); } this._lastwidth = Stage.width; this._lastheight = Stage.height; } // called by the compiler (as the last instruction in the executable), // this causes the transition from loading animation to construction // animation. function done() { //this.mydebug('done'); lzpreloader._heartbeat.removeMovieClip(); delete this.heartbeat; if (this.iobj) this.init(); for (var i = 0; i < this.synctoloads.length; i++) { var mc = this.synctoloads[i]; mc.gotoAndStop(mc.lastframe); //this.mydebug('lastframe='+mc.lastframe); } var vis = (this.hideafterinit != true) ? true : false; var svd = canvas.sprite.__LZsvdepth; canvas.sprite.__LZsvdepth = 0; var v = new LzView(canvas, {name:this.name, visible:vis, options: {ignorelayout:true}}); v.sprite.setMovieClip(this.splashroot); canvas.sprite.__LZsvdepth = svd; //this.mydebug('splashmc='+v); for (var i = 0; i < this.protoviews.length; i++) { var mc = this.protoviews[i]; var ratio = mc.lastframe / mc._totalframes; var nv = new LzView(v, {name: mc.name, x: mc._x, y: mc._y, width: mc._width, height: mc._height, totalframes: mc._totalframes, ratio: ratio, options: {ignorelayout: true}}); //this.mydebug('new view='+nv); // If ratio is less than one, animate the remaining way using percentcreated if (ratio < 1) { nv.noteCreated = function (p) { this.stop(Math.floor(this.totalframes * (this.ratio + (1-this.ratio)*p))); }; var del = new _root.LzDelegate(nv, 'noteCreated', _root.canvas, 'onpercentcreated'); } nv.sprite.setMovieClip(mc); mc._visible = true; } }
/** * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @affects lzpreloader * @access private * @topic LZX * @subtopic Services */ // // Code for lzpreloader frame 0 when there's a <splash> tag // This is compiled into lzpreloader.lzx which is attached to the lzpreloader // movieclip in SWFFile.java addPreloaderFrame() // // Debugging tips : // I put in a little debug code that will enables putting simple debug calls // in the code. To see the output when the debugger is up, type: // lzpreloader.trace() // It would be nice, for it to automatically output this info to the debugger // when it starts up, but I think this file isn't compiled the same way as the // LFC, since the $debug didn't seem to work. For now, you can just uncomment // the debug code below. [Sarah Allen 04-28-05] // Added text field where debug info is shown so it can be seen with debug=true // [sallen 06-06-2005] // necessary for consistent behavior - in netscape browsers HTML is ignored Stage.align = ('canvassalign' in global && global.canvassalign != null) ? global.canvassalign : "LT"; Stage.scaleMode = ('canvasscale' in global && global.canvasscale != null) ? global.canvasscale : "noScale"; /* // SWF-specific _root.createTextField("tfNewfield",1,100,10,150,700); _root.tfNewfield.text = "Splash Debugger"; _root.tfNewfield.autoSize = true; mydebugger = []; function mydebug(s) { this.mydebugger.push(s); _root.tfNewfield.text = _root.tfNewfield.text + '\n' + s; } function trace() { for (var i=0; i< this.mydebugger.length; i++) { _root.Debug.write(this.mydebugger[i]); } } */ this.protoviews = []; this.synctoloads = []; this._x = 0; this._y = 0; this._lastwidth = Stage.width; this._lastheight = Stage.height; // called by compiler (first thing) like: // lzpreloader.create({attrs: {}, name: "splash", children: // [{attrs: {x: 100, name: "logo", synctoload: true, resourcename: // logo, src: "logo.swf", y: 100}, name: "preloadresource"}]}); function create (iobj) { this.iobj = iobj } // Called by heartbeat to actually build the splash once the Stage has // non-zero size (to work around ActiveX control bug that initializes // the Stage to 0x0). function init () { if (Stage.width <= 100 || Stage.height <= 100) { // sometimes Safari still has heihgt/width 100. Be sure to hide the splash if this is the case. this.hideafterinit = true; return; } var iobj = this.iobj; delete this.iobj; this.name = iobj.name; this.hideafterinit = iobj.attrs.hideafterinit; var viewprops = {x: true, y: true, width: true, height: true}; var sr = _root.createEmptyMovieClip("spriteroot", 1000); var root = sr.createEmptyMovieClip(this.name, 0); this.splashroot = root; //this.mydebug('new root' + this.splashroot); for (var i = 0; i < iobj.children.length; i++) { var c = iobj.children[i].attrs; var n = (c.name == null) ? ("child" + i) : c.name; root.attachMovie(n, n, i + 1); var mc = root[n]; mc.name = n; this.protoviews.push(mc); // this.debug(" synctoload" + c.synctoload); if (c.synctoload) { if (c.lastframe == null) { mc.lastframe = mc._totalframes; } else { //this.mydebug('c.usepercent='+c.usepercent); mc.lastframe = c.lastframe * mc._totalframes; //this.mydebug('c.lastframe='+c.lastframe+ // 'mc.lastframe='+mc.lastframe ); } // this.debug(" synctoload" + this.synctoloads); this.synctoloads.push(mc); } for (var p in viewprops) { if (c[p] != null) { mc["_" + p] = c[p]; } } //this.debug(mc._target + " center=" + c.center); if (c.center != null) { mc._x = Stage.width / 2 - (mc._width / 2); mc._y = Stage.height / 2 - (mc._height / 2); //this.debug(" Stage.width=" + Stage.width); //this.debug(" mc._width=" + mc._width); //this.debug(" mc._x=" + mc._x); } } } this.createEmptyMovieClip("_heartbeat", 1000); this._heartbeat.onEnterFrame = function() { this._parent.heartbeat(); } // called by enterframe of the splash clip function heartbeat (p) { //this.mydebug('stage size ' + Stage.width + 'x' + Stage.height ); if (this.iobj && (Stage.width > 100 && Stage.height > 100) && (Stage.width == this._lastwidth && Stage.height == this._lastheight)) { // some browsers will pass 100% as 100 (or whatever %) for first // couple of heartbeats, ideally we would pass % from compiler // so we could ignore fewer cases and allow splash in small canvas // [sallen/max 6-05] this.init(); mc.gotoAndStop(0); } else { // SWF-specific var percload = _root.getBytesLoaded() / _root.getBytesTotal(); var id = _root.id; if (id) { var js = 'if (window.lz && lz.embed && lz.embed.applications && lz.embed.applications.' + id + ') lz.embed.applications.' + id + '._sendPercLoad(' + Math.floor(percload * 100) + ')'; _root.getURL('javascript:' + js + ';void(0);'); } for (var i = 0; i < this.synctoloads.length; i++) { var mc = this.synctoloads[i]; var p = Math.floor(mc.lastframe * percload); mc.gotoAndStop(p); } //this.mydebug('percent done='+p); } this._lastwidth = Stage.width; this._lastheight = Stage.height; } // called by the compiler (as the last instruction in the executable), // this causes the transition from loading animation to construction // animation. function done() { //this.mydebug('done'); lzpreloader._heartbeat.removeMovieClip(); delete this.heartbeat; if (this.iobj) this.init(); for (var i = 0; i < this.synctoloads.length; i++) { var mc = this.synctoloads[i]; mc.gotoAndStop(mc.lastframe); //this.mydebug('lastframe='+mc.lastframe); } var vis = (this.hideafterinit != true) ? true : false; var svd = canvas.sprite.__LZsvdepth; canvas.sprite.__LZsvdepth = 0; var v = new LzView(canvas, {name:this.name || null, visible:vis, options: {ignorelayout:true}}); v.sprite.setMovieClip(this.splashroot); canvas.sprite.__LZsvdepth = svd; //this.mydebug('splashmc='+v); for (var i = 0; i < this.protoviews.length; i++) { var mc = this.protoviews[i]; var ratio = mc.lastframe / mc._totalframes; var nv = new LzView(v, {name: mc.name || null, x: mc._x, y: mc._y, width: mc._width, height: mc._height, totalframes: mc._totalframes, ratio: ratio, options: {ignorelayout: true}}); //this.mydebug('new view='+nv); // If ratio is less than one, animate the remaining way using percentcreated if (ratio < 1) { nv.noteCreated = function (p) { this.stop(Math.floor(this.totalframes * (this.ratio + (1-this.ratio)*p))); }; var del = new _root.LzDelegate(nv, 'noteCreated', _root.canvas, 'onpercentcreated'); } nv.sprite.setMovieClip(mc); mc._visible = true; } }
Change 20081212-maxcarlson-l by [email protected] on 2008-12-12 22:46:35 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20081212-maxcarlson-l by [email protected] on 2008-12-12 22:46:35 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk Summary: Prevent warnings for splash in swf8 Bugs Fixed: LPP-7458 - runtime errors when spash view included in nightly build 12036 swf8 Technical Reviewer: [email protected] QA Reviewer: promanik Details: Per Andre's comment, make sure name is null instead of undefined when undeclared. Tests: Both my-apps/copy-of-hello.lzx?lzr=swf8&debug=true and <canvas> <splash/> </canvas> no longer give warnings. git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@12096 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
0c3c0107c991b1e0b90bb30825e50bb19ea3b991
src/org/mangui/hls/demux/AACDemuxer.as
src/org/mangui/hls/demux/AACDemuxer.as
package org.mangui.hls.demux { import org.mangui.hls.HLSAudioTrack; import org.mangui.hls.flv.FLVTag; import flash.utils.ByteArray; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Constants and utilities for the AAC audio format. **/ public class AACDemuxer implements Demuxer { /** ADTS Syncword (111111111111), ID (MPEG4), layer (00) and protection_absent (1).**/ private static const SYNCWORD : uint = 0xFFF1; /** ADTS Syncword with MPEG2 stream ID (used by e.g. Squeeze 7). **/ private static const SYNCWORD_2 : uint = 0xFFF9; /** ADTS Syncword with MPEG2 stream ID (used by e.g. Envivio 4Caster). **/ private static const SYNCWORD_3 : uint = 0xFFF8; /** ADTS/ADIF sample rates index. **/ private static const RATES : Array = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; /** ADIF profile index (ADTS doesn't have Null). **/ private static const PROFILES : Array = ['Null', 'Main', 'LC', 'SSR', 'LTP', 'SBR']; /** Byte data to be read **/ private var _data : ByteArray; /* callback functions for audio selection, and parsing progress/complete */ private var _callback_audioselect : Function; private var _callback_progress : Function; private var _callback_complete : Function; /** append new data */ public function append(data : ByteArray) : void { _data.writeBytes(data); } /** cancel demux operation */ public function cancel() : void { _data = null; } public function notifycomplete() : void { CONFIG::LOGGING { Log.debug("AAC: extracting AAC tags"); } var audioTags : Vector.<FLVTag> = new Vector.<FLVTag>(); /* parse AAC, convert Elementary Streams to TAG */ _data.position = 0; var id3 : ID3 = new ID3(_data); // AAC should contain ID3 tag filled with a timestamp var frames : Vector.<AudioFrame> = AACDemuxer.getFrames(_data, _data.position); var adif : ByteArray = getADIF(_data, 0); var adifTag : FLVTag = new FLVTag(FLVTag.AAC_HEADER, id3.timestamp, id3.timestamp, true); adifTag.push(adif, 0, adif.length); audioTags.push(adifTag); var audioTag : FLVTag; var stamp : uint; var i : int = 0; while (i < frames.length) { stamp = Math.round(id3.timestamp + i * 1024 * 1000 / frames[i].rate); audioTag = new FLVTag(FLVTag.AAC_RAW, stamp, stamp, false); if (i != frames.length - 1) { audioTag.push(_data, frames[i].start, frames[i].length); } else { audioTag.push(_data, frames[i].start, _data.length - frames[i].start); } audioTags.push(audioTag); i++; } var audiotracks : Vector.<HLSAudioTrack> = new Vector.<HLSAudioTrack>(); audiotracks.push(new HLSAudioTrack('AAC ES', HLSAudioTrack.FROM_DEMUX, 0, true)); // report unique audio track. dont check return value as obviously the track will be selected _callback_audioselect(audiotracks); CONFIG::LOGGING { Log.debug("AAC: all tags extracted, callback demux"); } _callback_progress(audioTags); _callback_complete(); } public function AACDemuxer(callback_audioselect : Function, callback_progress : Function, callback_complete : Function) : void { _callback_audioselect = callback_audioselect; _callback_progress = callback_progress; _callback_complete = callback_complete; _data = new ByteArray(); }; public static function probe(data : ByteArray) : Boolean { var pos : uint = data.position; var id3 : ID3 = new ID3(data); // AAC should contain ID3 tag filled with a timestamp if (id3.hasTimestamp) { while (data.bytesAvailable > 1) { // Check for ADTS header var short : uint = data.readUnsignedShort(); if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) { // rewind to sync word data.position -= 2; return true; } else { data.position--; } } data.position = pos; } return false; } /** Get ADIF header from ADTS stream. **/ public static function getADIF(adts : ByteArray, position : uint) : ByteArray { adts.position = position; var short : uint; // we need at least 6 bytes, 2 for sync word, 4 for frame length while ((adts.bytesAvailable > 5) && (short != SYNCWORD) && (short != SYNCWORD_2) && (short != SYNCWORD_3)) { short = adts.readUnsignedShort(); } if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) { var profile : uint = (adts.readByte() & 0xF0) >> 6; // Correcting zero-index of ADIF and Flash playing only LC/HE. if (profile > 3) { profile = 5; } else { profile = 2; } adts.position--; var srate : uint = (adts.readByte() & 0x3C) >> 2; adts.position--; var channels : uint = (adts.readShort() & 0x01C0) >> 6; } else { throw new Error("Stream did not start with ADTS header."); } // 5 bits profile + 4 bits samplerate + 4 bits channels. var adif : ByteArray = new ByteArray(); adif.writeByte((profile << 3) + (srate >> 1)); adif.writeByte((srate << 7) + (channels << 3)); CONFIG::LOGGING { Log.debug('AAC: ' + PROFILES[profile] + ', ' + RATES[srate] + ' Hz ' + channels + ' channel(s)'); } // Reset position and return adif. adts.position -= 4; adif.position = 0; return adif; }; /** Get a list with AAC frames from ADTS stream. **/ public static function getFrames(adts : ByteArray, position : uint) : Vector.<AudioFrame> { var frames : Vector.<AudioFrame> = new Vector.<AudioFrame>(); var frame_start : uint; var frame_length : uint; var id3 : ID3 = new ID3(adts); position += id3.len; // Get raw AAC frames from audio stream. adts.position = position; var samplerate : uint; // we need at least 6 bytes, 2 for sync word, 4 for frame length while (adts.bytesAvailable > 5) { // Check for ADTS header var short : uint = adts.readUnsignedShort(); if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) { // Store samplerate for offsetting timestamps. if (!samplerate) { samplerate = RATES[(adts.readByte() & 0x3C) >> 2]; adts.position--; } // Store raw AAC preceding this header. if (frame_start) { frames.push(new AudioFrame(frame_start, frame_length, frame_length, samplerate)); } if (short == SYNCWORD_3) { // ADTS header is 9 bytes. frame_length = ((adts.readUnsignedInt() & 0x0003FFE0) >> 5) - 9; frame_start = adts.position + 3; adts.position += frame_length + 3; } else { // ADTS header is 7 bytes. frame_length = ((adts.readUnsignedInt() & 0x0003FFE0) >> 5) - 7; frame_start = adts.position + 1; adts.position += frame_length + 1; } } else { CONFIG::LOGGING { Log.debug("no ADTS header found, probing..."); } adts.position--; } } if (frame_start) { // check if we have a complete frame available at the end, i.e. last found frame is fitting in this PES packet var overflow : int = frame_start + frame_length - adts.length; if (overflow <= 0 ) { // no overflow, Write raw AAC after last header. frames.push(new AudioFrame(frame_start, frame_length, frame_length, samplerate)); } else { CONFIG::LOGGING { Log.debug2("ADTS overflow at the end of PES packet, missing " + overflow + " bytes to complete the ADTS frame"); } } } else if (frames.length == 0) { null; CONFIG::LOGGING { Log.warn("No ADTS headers found in this stream."); } } adts.position = position; return frames; }; } }
package org.mangui.hls.demux { import org.mangui.hls.HLSAudioTrack; import org.mangui.hls.flv.FLVTag; import flash.utils.ByteArray; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Constants and utilities for the AAC audio format. **/ public class AACDemuxer implements Demuxer { /** ADTS Syncword (111111111111), ID (MPEG4), layer (00) and protection_absent (1).**/ private static const SYNCWORD : uint = 0xFFF1; /** ADTS Syncword with MPEG2 stream ID (used by e.g. Squeeze 7). **/ private static const SYNCWORD_2 : uint = 0xFFF9; /** ADTS Syncword with MPEG2 stream ID (used by e.g. Envivio 4Caster). **/ private static const SYNCWORD_3 : uint = 0xFFF8; /** ADTS/ADIF sample rates index. **/ private static const RATES : Array = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; /** ADIF profile index (ADTS doesn't have Null). **/ private static const PROFILES : Array = ['Null', 'Main', 'LC', 'SSR', 'LTP', 'SBR']; /** Byte data to be read **/ private var _data : ByteArray; /* callback functions for audio selection, and parsing progress/complete */ private var _callback_audioselect : Function; private var _callback_progress : Function; private var _callback_complete : Function; /** append new data */ public function append(data : ByteArray) : void { _data.writeBytes(data); } /** cancel demux operation */ public function cancel() : void { _data = null; } public function notifycomplete() : void { CONFIG::LOGGING { Log.debug("AAC: extracting AAC tags"); } var audioTags : Vector.<FLVTag> = new Vector.<FLVTag>(); /* parse AAC, convert Elementary Streams to TAG */ _data.position = 0; var id3 : ID3 = new ID3(_data); // AAC should contain ID3 tag filled with a timestamp var frames : Vector.<AudioFrame> = AACDemuxer.getFrames(_data, _data.position); var adif : ByteArray = getADIF(_data, id3.len); var adifTag : FLVTag = new FLVTag(FLVTag.AAC_HEADER, id3.timestamp, id3.timestamp, true); adifTag.push(adif, 0, adif.length); audioTags.push(adifTag); var audioTag : FLVTag; var stamp : uint; var i : int = 0; while (i < frames.length) { stamp = Math.round(id3.timestamp + i * 1024 * 1000 / frames[i].rate); audioTag = new FLVTag(FLVTag.AAC_RAW, stamp, stamp, false); if (i != frames.length - 1) { audioTag.push(_data, frames[i].start, frames[i].length); } else { audioTag.push(_data, frames[i].start, _data.length - frames[i].start); } audioTags.push(audioTag); i++; } var audiotracks : Vector.<HLSAudioTrack> = new Vector.<HLSAudioTrack>(); audiotracks.push(new HLSAudioTrack('AAC ES', HLSAudioTrack.FROM_DEMUX, 0, true)); // report unique audio track. dont check return value as obviously the track will be selected _callback_audioselect(audiotracks); CONFIG::LOGGING { Log.debug("AAC: all tags extracted, callback demux"); } _callback_progress(audioTags); _callback_complete(); } public function AACDemuxer(callback_audioselect : Function, callback_progress : Function, callback_complete : Function) : void { _callback_audioselect = callback_audioselect; _callback_progress = callback_progress; _callback_complete = callback_complete; _data = new ByteArray(); }; public static function probe(data : ByteArray) : Boolean { var pos : uint = data.position; var id3 : ID3 = new ID3(data); // AAC should contain ID3 tag filled with a timestamp if (id3.hasTimestamp) { while (data.bytesAvailable > 1) { // Check for ADTS header var short : uint = data.readUnsignedShort(); if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) { // rewind to sync word data.position -= 2; return true; } else { data.position--; } } data.position = pos; } return false; } /** Get ADIF header from ADTS stream. **/ public static function getADIF(adts : ByteArray, position : uint) : ByteArray { adts.position = position; var short : uint; // we need at least 6 bytes, 2 for sync word, 4 for frame length while ((adts.bytesAvailable > 5) && (short != SYNCWORD) && (short != SYNCWORD_2) && (short != SYNCWORD_3)) { short = adts.readUnsignedShort(); } if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) { var profile : uint = (adts.readByte() & 0xF0) >> 6; // Correcting zero-index of ADIF and Flash playing only LC/HE. if (profile > 3) { profile = 5; } else { profile = 2; } adts.position--; var srate : uint = (adts.readByte() & 0x3C) >> 2; adts.position--; var channels : uint = (adts.readShort() & 0x01C0) >> 6; } else { throw new Error("Stream did not start with ADTS header."); } // 5 bits profile + 4 bits samplerate + 4 bits channels. var adif : ByteArray = new ByteArray(); adif.writeByte((profile << 3) + (srate >> 1)); adif.writeByte((srate << 7) + (channels << 3)); CONFIG::LOGGING { Log.debug('AAC: ' + PROFILES[profile] + ', ' + RATES[srate] + ' Hz ' + channels + ' channel(s)'); } // Reset position and return adif. adts.position -= 4; adif.position = 0; return adif; }; /** Get a list with AAC frames from ADTS stream. **/ public static function getFrames(adts : ByteArray, position : uint) : Vector.<AudioFrame> { var frames : Vector.<AudioFrame> = new Vector.<AudioFrame>(); var frame_start : uint; var frame_length : uint; var id3 : ID3 = new ID3(adts); position += id3.len; // Get raw AAC frames from audio stream. adts.position = position; var samplerate : uint; // we need at least 6 bytes, 2 for sync word, 4 for frame length while (adts.bytesAvailable > 5) { // Check for ADTS header var short : uint = adts.readUnsignedShort(); if (short == SYNCWORD || short == SYNCWORD_2 || short == SYNCWORD_3) { // Store samplerate for offsetting timestamps. if (!samplerate) { samplerate = RATES[(adts.readByte() & 0x3C) >> 2]; adts.position--; } // Store raw AAC preceding this header. if (frame_start) { frames.push(new AudioFrame(frame_start, frame_length, frame_length, samplerate)); } if (short == SYNCWORD_3) { // ADTS header is 9 bytes. frame_length = ((adts.readUnsignedInt() & 0x0003FFE0) >> 5) - 9; frame_start = adts.position + 3; adts.position += frame_length + 3; } else { // ADTS header is 7 bytes. frame_length = ((adts.readUnsignedInt() & 0x0003FFE0) >> 5) - 7; frame_start = adts.position + 1; adts.position += frame_length + 1; } } else { CONFIG::LOGGING { Log.debug("no ADTS header found, probing..."); } adts.position--; } } if (frame_start) { // check if we have a complete frame available at the end, i.e. last found frame is fitting in this PES packet var overflow : int = frame_start + frame_length - adts.length; if (overflow <= 0 ) { // no overflow, Write raw AAC after last header. frames.push(new AudioFrame(frame_start, frame_length, frame_length, samplerate)); } else { CONFIG::LOGGING { Log.debug2("ADTS overflow at the end of PES packet, missing " + overflow + " bytes to complete the ADTS frame"); } } } else if (frames.length == 0) { null; CONFIG::LOGGING { Log.warn("No ADTS headers found in this stream."); } } adts.position = position; return frames; }; } }
Fix for adif being found randomly in the stream
Fix for adif being found randomly in the stream When searching from position=0 and reading 2 bytes at the time, FFF1 is not found directly after the id3 when the id3 has an odd number of bytes. Search should starry after id3 tag in order to be aligned correctly.
ActionScript
mpl-2.0
dighan/flashls,fixedmachine/flashls,aevange/flashls,stevemayhew/flashls,Boxie5/flashls,NicolasSiver/flashls,jlacivita/flashls,thdtjsdn/flashls,jlacivita/flashls,stevemayhew/flashls,School-Improvement-Network/flashls,suuhas/flashls,loungelogic/flashls,Boxie5/flashls,vidible/vdb-flashls,viktorot/flashls,ryanhefner/flashls,viktorot/flashls,hola/flashls,tedconf/flashls,codex-corp/flashls,dighan/flashls,Corey600/flashls,fixedmachine/flashls,JulianPena/flashls,JulianPena/flashls,thdtjsdn/flashls,ryanhefner/flashls,School-Improvement-Network/flashls,hola/flashls,stevemayhew/flashls,ryanhefner/flashls,Peer5/flashls,clappr/flashls,NicolasSiver/flashls,suuhas/flashls,viktorot/flashls,neilrackett/flashls,mangui/flashls,tedconf/flashls,Peer5/flashls,aevange/flashls,neilrackett/flashls,loungelogic/flashls,School-Improvement-Network/flashls,codex-corp/flashls,ryanhefner/flashls,suuhas/flashls,Corey600/flashls,clappr/flashls,suuhas/flashls,Peer5/flashls,stevemayhew/flashls,mangui/flashls,Peer5/flashls,aevange/flashls,aevange/flashls,vidible/vdb-flashls
0bdaf12a8f9a38696d7d9147b7c86e20946fd4ec
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 { 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; } } }
//////////////////////////////////////////////////////////////////////////////// // 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; } public static function ensureOSLineEndings(text:String):String { return text ? text.replace(/\n/g, File.lineEnding) : ""; } } }
Add utility method to ensure OS line endings.
Add utility method to ensure OS line endings.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
eedf82cea0012c7566d1887bb7dd82560a5e32e9
src/org/mangui/chromeless/ChromelessPlayer.as
src/org/mangui/chromeless/ChromelessPlayer.as
package org.mangui.chromeless { import flash.net.URLStream; import org.mangui.HLS.parsing.Level; import org.mangui.HLS.*; import org.mangui.HLS.utils.*; import flash.display.*; import flash.events.*; import flash.external.ExternalInterface; import flash.geom.Rectangle; import flash.media.Video; import flash.media.SoundTransform; import flash.media.StageVideo; import flash.media.StageVideoAvailability; import flash.utils.setTimeout; public class ChromelessPlayer extends Sprite { /** reference to the framework. **/ private var _hls : HLS; /** Sheet to place on top of the video. **/ private var _sheet : Sprite; /** Reference to the stage video element. **/ private var _stageVideo : StageVideo = null; /** Reference to the video element. **/ private var _video : Video = null; /** Video size **/ private var _videoWidth : Number = 0; private var _videoHeight : Number = 0; /** current media position */ private var _media_position : Number; private var _duration : Number; /** Initialization. **/ public function ChromelessPlayer() : void { // Set stage properties stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState); stage.addEventListener(Event.RESIZE, _onStageResize); // Draw sheet for catching clicks _sheet = new Sprite(); _sheet.graphics.beginFill(0x000000, 0); _sheet.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); _sheet.addEventListener(MouseEvent.CLICK, _clickHandler); _sheet.buttonMode = true; addChild(_sheet); // Connect getters to JS. ExternalInterface.addCallback("getLevel", _getLevel); ExternalInterface.addCallback("getLevels", _getLevels); ExternalInterface.addCallback("getMetrics", _getMetrics); ExternalInterface.addCallback("getDuration", _getDuration); ExternalInterface.addCallback("getPosition", _getPosition); ExternalInterface.addCallback("getState", _getState); ExternalInterface.addCallback("getType", _getType); ExternalInterface.addCallback("getmaxBufferLength", _getmaxBufferLength); ExternalInterface.addCallback("getminBufferLength", _getminBufferLength); ExternalInterface.addCallback("getbufferLength", _getbufferLength); ExternalInterface.addCallback("getLogDebug", _getLogDebug); ExternalInterface.addCallback("getLogDebug2", _getLogDebug2); ExternalInterface.addCallback("getflushLiveURLCache", _getflushLiveURLCache); ExternalInterface.addCallback("getstartFromLowestLevel", _getstartFromLowestLevel); ExternalInterface.addCallback("getseekFromLowestLevel", _getseekFromLowestLevel); ExternalInterface.addCallback("getJSURLStream", _getJSURLStream); ExternalInterface.addCallback("getPlayerVersion", _getPlayerVersion); ExternalInterface.addCallback("getAudioTrackList", _getAudioTrackList); ExternalInterface.addCallback("getAudioTrackId", _getAudioTrackId); // Connect calls to JS. ExternalInterface.addCallback("playerLoad", _load); ExternalInterface.addCallback("playerPlay", _play); ExternalInterface.addCallback("playerPause", _pause); ExternalInterface.addCallback("playerResume", _resume); ExternalInterface.addCallback("playerSeek", _seek); ExternalInterface.addCallback("playerStop", _stop); ExternalInterface.addCallback("playerVolume", _volume); ExternalInterface.addCallback("playerSetLevel", _setLevel); ExternalInterface.addCallback("playerSetmaxBufferLength", _setmaxBufferLength); ExternalInterface.addCallback("playerSetminBufferLength", _setminBufferLength); ExternalInterface.addCallback("playerSetflushLiveURLCache", _setflushLiveURLCache); ExternalInterface.addCallback("playerSetstartFromLowestLevel", _setstartFromLowestLevel); ExternalInterface.addCallback("playerSetseekFromLowestLevel", _setseekFromLowestLevel); ExternalInterface.addCallback("playerSetLogDebug", _setLogDebug); ExternalInterface.addCallback("playerSetLogDebug2", _setLogDebug2); ExternalInterface.addCallback("playerSetAudioTrack", _setAudioTrack); ExternalInterface.addCallback("playerSetJSURLStream", _setJSURLStream); setTimeout(_pingJavascript, 50); }; /** Notify javascript the framework is ready. **/ private function _pingJavascript() : void { ExternalInterface.call("onHLSReady", ExternalInterface.objectID); }; /** Forward events from the framework. **/ private function _completeHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onComplete"); } }; private function _errorHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onError", event.message); } }; private function _fragmentHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onFragment", event.metrics.bandwidth, event.metrics.level, stage.stageWidth); } }; private function _manifestHandler(event : HLSEvent) : void { _duration = event.levels[0].duration; if (ExternalInterface.available) { ExternalInterface.call("onManifest", event.levels[0].duration); } }; private function _mediaTimeHandler(event : HLSEvent) : void { _duration = event.mediatime.duration; _media_position = event.mediatime.position; if (ExternalInterface.available) { ExternalInterface.call("onPosition", event.mediatime.position, event.mediatime.duration, event.mediatime.live_sliding); } var videoWidth : Number = _video ? _video.videoWidth : _stageVideo.videoWidth; var videoHeight : Number = _video ? _video.videoHeight : _stageVideo.videoHeight; if (videoWidth && videoHeight) { var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight; if (changed) { _videoHeight = videoHeight; _videoWidth = videoWidth; _resize(); if (ExternalInterface.available) { ExternalInterface.call("onVideoSize", _videoWidth, _videoHeight); } } } }; private function _stateHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onState", event.state); } }; private function _switchHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onSwitch", event.level); } }; private function _audioTracksListChange(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onAudioTracksListChange", _getAudioTrackList()); } } private function _audioTrackChange(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onAudioTrackChange", event.audioTrack); } } /** Javascript getters. **/ private function _getLevel() : Number { return _hls.level; }; private function _getLevels() : Vector.<Level> { return _hls.levels; }; private function _getMetrics() : Object { return _hls.metrics; }; private function _getDuration() : Number { return _duration; }; private function _getPosition() : Number { return _hls.position; }; private function _getState() : String { return _hls.state; }; private function _getType() : String { return _hls.type; }; private function _getbufferLength() : Number { return _hls.bufferLength; }; private function _getmaxBufferLength() : Number { return _hls.maxBufferLength; }; private function _getminBufferLength() : Number { return _hls.minBufferLength; }; private function _getflushLiveURLCache() : Boolean { return _hls.flushLiveURLCache; }; private function _getstartFromLowestLevel() : Boolean { return _hls.startFromLowestLevel; }; private function _getseekFromLowestLevel() : Boolean { return _hls.seekFromLowestLevel; }; private function _getLogDebug() : Boolean { return Log.LOG_DEBUG_ENABLED; }; private function _getLogDebug2() : Boolean { return Log.LOG_DEBUG2_ENABLED; }; private function _getJSURLStream() : Boolean { return (_hls.URLstream is JSURLStream); }; private function _getPlayerVersion() : Number { return 2; }; private function _getAudioTrackList() : Array { var list : Array = []; var vec : Vector.<HLSAudioTrack> = _hls.audioTracks; for (var i : Object in vec) { list.push(vec[i]); } return list; }; private function _getAudioTrackId() : Number { return _hls.audioTrack; }; /** Javascript calls. **/ private function _load(url : String) : void { _hls.load(url); }; private function _play() : void { _hls.stream.play(); }; private function _pause() : void { _hls.stream.pause(); }; private function _resume() : void { _hls.stream.resume(); }; private function _seek(position : Number) : void { _hls.stream.seek(position); }; private function _stop() : void { _hls.stream.close(); }; private function _volume(percent : Number) : void { _hls.stream.soundTransform = new SoundTransform(percent / 100); }; private function _setLevel(level : Number) : void { if (level != _hls.level) { _hls.level = level; if (!isNaN(_media_position) && level != -1) { _hls.stream.seek(_media_position); } } }; private function _setmaxBufferLength(new_len : Number) : void { _hls.maxBufferLength = new_len; }; private function _setminBufferLength(new_len : Number) : void { _hls.minBufferLength = new_len; }; private function _setflushLiveURLCache(flushLiveURLCache : Boolean) : void { _hls.flushLiveURLCache = flushLiveURLCache; }; private function _setstartFromLowestLevel(startFromLowestLevel : Boolean) : void { _hls.startFromLowestLevel = startFromLowestLevel; }; private function _setseekFromLowestLevel(seekFromLowestLevel : Boolean) : void { _hls.seekFromLowestLevel = seekFromLowestLevel; }; private function _setLogDebug(debug : Boolean) : void { Log.LOG_DEBUG_ENABLED = debug; }; private function _setLogDebug2(debug2 : Boolean) : void { Log.LOG_DEBUG2_ENABLED = debug2; }; private function _setJSURLStream(jsURLstream : Boolean) : void { if (jsURLstream) { _hls.URLstream = JSURLStream as Class; } else { _hls.URLstream = URLStream as Class; } }; private function _setAudioTrack(val : Number) : void { if (val == _hls.audioTrack) return; _hls.audioTrack = val; if (!isNaN(_media_position)) { _hls.stream.seek(_media_position); } }; /** Mouse click handler. **/ private function _clickHandler(event : MouseEvent) : void { if (stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE || stage.displayState == StageDisplayState.FULL_SCREEN) { stage.displayState = StageDisplayState.NORMAL; } else { stage.displayState = StageDisplayState.FULL_SCREEN; } }; /** StageVideo detector. **/ private function _onStageVideoState(event : StageVideoAvailabilityEvent) : void { var available : Boolean = (event.availability == StageVideoAvailability.AVAILABLE); _hls = new HLS(); _hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler); _hls.addEventListener(HLSEvent.ERROR, _errorHandler); _hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler); _hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler); _hls.addEventListener(HLSEvent.STATE, _stateHandler); _hls.addEventListener(HLSEvent.QUALITY_SWITCH, _switchHandler); _hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTracksListChange); _hls.addEventListener(HLSEvent.AUDIO_TRACK_CHANGE, _audioTrackChange); if (available && stage.stageVideos.length > 0) { _stageVideo = stage.stageVideos[0]; _stageVideo.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); _stageVideo.attachNetStream(_hls.stream); } else { _video = new Video(stage.stageWidth, stage.stageHeight); addChild(_video); _video.smoothing = true; _video.attachNetStream(_hls.stream); } stage.removeEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState); }; private function _onStageResize(event : Event) : void { stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); _sheet.width = stage.stageWidth; _sheet.height = stage.stageHeight; _resize(); }; private function _resize() : void { var rect : Rectangle; rect = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, stage.stageWidth, stage.stageHeight); // resize video if (_video) { _video.width = rect.width; _video.height = rect.height; _video.x = rect.x; _video.y = rect.y; } else if (_stageVideo) { _stageVideo.viewPort = rect; } } } }
package org.mangui.chromeless { import flash.net.URLStream; import org.mangui.HLS.parsing.Level; import org.mangui.HLS.*; import org.mangui.HLS.utils.*; import flash.display.*; import flash.events.*; import flash.external.ExternalInterface; import flash.geom.Rectangle; import flash.media.Video; import flash.media.SoundTransform; import flash.media.StageVideo; import flash.media.StageVideoAvailability; import flash.utils.setTimeout; public class ChromelessPlayer extends Sprite { /** reference to the framework. **/ private var _hls : HLS; /** Sheet to place on top of the video. **/ private var _sheet : Sprite; /** Reference to the stage video element. **/ private var _stageVideo : StageVideo = null; /** Reference to the video element. **/ private var _video : Video = null; /** Video size **/ private var _videoWidth : Number = 0; private var _videoHeight : Number = 0; /** current media position */ private var _media_position : Number; private var _duration : Number; /** Initialization. **/ public function ChromelessPlayer() : void { // Set stage properties stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState); stage.addEventListener(Event.RESIZE, _onStageResize); // Draw sheet for catching clicks _sheet = new Sprite(); _sheet.graphics.beginFill(0x000000, 0); _sheet.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); _sheet.addEventListener(MouseEvent.CLICK, _clickHandler); _sheet.buttonMode = true; addChild(_sheet); // Connect getters to JS. ExternalInterface.addCallback("getLevel", _getLevel); ExternalInterface.addCallback("getLevels", _getLevels); ExternalInterface.addCallback("getMetrics", _getMetrics); ExternalInterface.addCallback("getDuration", _getDuration); ExternalInterface.addCallback("getPosition", _getPosition); ExternalInterface.addCallback("getState", _getState); ExternalInterface.addCallback("getType", _getType); ExternalInterface.addCallback("getmaxBufferLength", _getmaxBufferLength); ExternalInterface.addCallback("getminBufferLength", _getminBufferLength); ExternalInterface.addCallback("getbufferLength", _getbufferLength); ExternalInterface.addCallback("getLogDebug", _getLogDebug); ExternalInterface.addCallback("getLogDebug2", _getLogDebug2); ExternalInterface.addCallback("getflushLiveURLCache", _getflushLiveURLCache); ExternalInterface.addCallback("getstartFromLowestLevel", _getstartFromLowestLevel); ExternalInterface.addCallback("getseekFromLowestLevel", _getseekFromLowestLevel); ExternalInterface.addCallback("getJSURLStream", _getJSURLStream); ExternalInterface.addCallback("getPlayerVersion", _getPlayerVersion); ExternalInterface.addCallback("getAudioTrackList", _getAudioTrackList); ExternalInterface.addCallback("getAudioTrackId", _getAudioTrackId); // Connect calls to JS. ExternalInterface.addCallback("playerLoad", _load); ExternalInterface.addCallback("playerPlay", _play); ExternalInterface.addCallback("playerPause", _pause); ExternalInterface.addCallback("playerResume", _resume); ExternalInterface.addCallback("playerSeek", _seek); ExternalInterface.addCallback("playerStop", _stop); ExternalInterface.addCallback("playerVolume", _volume); ExternalInterface.addCallback("playerSetLevel", _setLevel); ExternalInterface.addCallback("playerSmoothSetLevel", _smoothSetLevel); ExternalInterface.addCallback("playerSetmaxBufferLength", _setmaxBufferLength); ExternalInterface.addCallback("playerSetminBufferLength", _setminBufferLength); ExternalInterface.addCallback("playerSetflushLiveURLCache", _setflushLiveURLCache); ExternalInterface.addCallback("playerSetstartFromLowestLevel", _setstartFromLowestLevel); ExternalInterface.addCallback("playerSetseekFromLowestLevel", _setseekFromLowestLevel); ExternalInterface.addCallback("playerSetLogDebug", _setLogDebug); ExternalInterface.addCallback("playerSetLogDebug2", _setLogDebug2); ExternalInterface.addCallback("playerSetAudioTrack", _setAudioTrack); ExternalInterface.addCallback("playerSetJSURLStream", _setJSURLStream); setTimeout(_pingJavascript, 50); }; /** Notify javascript the framework is ready. **/ private function _pingJavascript() : void { ExternalInterface.call("onHLSReady", ExternalInterface.objectID); }; /** Forward events from the framework. **/ private function _completeHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onComplete"); } }; private function _errorHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onError", event.message); } }; private function _fragmentHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onFragment", event.metrics.bandwidth, event.metrics.level, stage.stageWidth); } }; private function _manifestHandler(event : HLSEvent) : void { _duration = event.levels[0].duration; if (ExternalInterface.available) { ExternalInterface.call("onManifest", event.levels[0].duration); } }; private function _mediaTimeHandler(event : HLSEvent) : void { _duration = event.mediatime.duration; _media_position = event.mediatime.position; if (ExternalInterface.available) { ExternalInterface.call("onPosition", event.mediatime.position, event.mediatime.duration, event.mediatime.live_sliding); } var videoWidth : Number = _video ? _video.videoWidth : _stageVideo.videoWidth; var videoHeight : Number = _video ? _video.videoHeight : _stageVideo.videoHeight; if (videoWidth && videoHeight) { var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight; if (changed) { _videoHeight = videoHeight; _videoWidth = videoWidth; _resize(); if (ExternalInterface.available) { ExternalInterface.call("onVideoSize", _videoWidth, _videoHeight); } } } }; private function _stateHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onState", event.state); } }; private function _switchHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onSwitch", event.level); } }; private function _audioTracksListChange(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onAudioTracksListChange", _getAudioTrackList()); } } private function _audioTrackChange(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onAudioTrackChange", event.audioTrack); } } /** Javascript getters. **/ private function _getLevel() : Number { return _hls.level; }; private function _getLevels() : Vector.<Level> { return _hls.levels; }; private function _getMetrics() : Object { return _hls.metrics; }; private function _getDuration() : Number { return _duration; }; private function _getPosition() : Number { return _hls.position; }; private function _getState() : String { return _hls.state; }; private function _getType() : String { return _hls.type; }; private function _getbufferLength() : Number { return _hls.bufferLength; }; private function _getmaxBufferLength() : Number { return _hls.maxBufferLength; }; private function _getminBufferLength() : Number { return _hls.minBufferLength; }; private function _getflushLiveURLCache() : Boolean { return _hls.flushLiveURLCache; }; private function _getstartFromLowestLevel() : Boolean { return _hls.startFromLowestLevel; }; private function _getseekFromLowestLevel() : Boolean { return _hls.seekFromLowestLevel; }; private function _getLogDebug() : Boolean { return Log.LOG_DEBUG_ENABLED; }; private function _getLogDebug2() : Boolean { return Log.LOG_DEBUG2_ENABLED; }; private function _getJSURLStream() : Boolean { return (_hls.URLstream is JSURLStream); }; private function _getPlayerVersion() : Number { return 2; }; private function _getAudioTrackList() : Array { var list : Array = []; var vec : Vector.<HLSAudioTrack> = _hls.audioTracks; for (var i : Object in vec) { list.push(vec[i]); } return list; }; private function _getAudioTrackId() : Number { return _hls.audioTrack; }; /** Javascript calls. **/ private function _load(url : String) : void { _hls.load(url); }; private function _play() : void { _hls.stream.play(); }; private function _pause() : void { _hls.stream.pause(); }; private function _resume() : void { _hls.stream.resume(); }; private function _seek(position : Number) : void { _hls.stream.seek(position); }; private function _stop() : void { _hls.stream.close(); }; private function _volume(percent : Number) : void { _hls.stream.soundTransform = new SoundTransform(percent / 100); }; private function _setLevel(level : Number) : void { _smoothSetLevel(level); if (!isNaN(_media_position) && level != -1) { _hls.stream.seek(_media_position); } }; private function _smoothSetLevel(level: Number) : void { if (level != _hls.level) { _hls.level = level; } }; private function _setmaxBufferLength(new_len : Number) : void { _hls.maxBufferLength = new_len; }; private function _setminBufferLength(new_len : Number) : void { _hls.minBufferLength = new_len; }; private function _setflushLiveURLCache(flushLiveURLCache : Boolean) : void { _hls.flushLiveURLCache = flushLiveURLCache; }; private function _setstartFromLowestLevel(startFromLowestLevel : Boolean) : void { _hls.startFromLowestLevel = startFromLowestLevel; }; private function _setseekFromLowestLevel(seekFromLowestLevel : Boolean) : void { _hls.seekFromLowestLevel = seekFromLowestLevel; }; private function _setLogDebug(debug : Boolean) : void { Log.LOG_DEBUG_ENABLED = debug; }; private function _setLogDebug2(debug2 : Boolean) : void { Log.LOG_DEBUG2_ENABLED = debug2; }; private function _setJSURLStream(jsURLstream : Boolean) : void { if (jsURLstream) { _hls.URLstream = JSURLStream as Class; } else { _hls.URLstream = URLStream as Class; } }; private function _setAudioTrack(val : Number) : void { if (val == _hls.audioTrack) return; _hls.audioTrack = val; if (!isNaN(_media_position)) { _hls.stream.seek(_media_position); } }; /** Mouse click handler. **/ private function _clickHandler(event : MouseEvent) : void { if (stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE || stage.displayState == StageDisplayState.FULL_SCREEN) { stage.displayState = StageDisplayState.NORMAL; } else { stage.displayState = StageDisplayState.FULL_SCREEN; } }; /** StageVideo detector. **/ private function _onStageVideoState(event : StageVideoAvailabilityEvent) : void { var available : Boolean = (event.availability == StageVideoAvailability.AVAILABLE); _hls = new HLS(); _hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler); _hls.addEventListener(HLSEvent.ERROR, _errorHandler); _hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler); _hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler); _hls.addEventListener(HLSEvent.STATE, _stateHandler); _hls.addEventListener(HLSEvent.QUALITY_SWITCH, _switchHandler); _hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTracksListChange); _hls.addEventListener(HLSEvent.AUDIO_TRACK_CHANGE, _audioTrackChange); if (available && stage.stageVideos.length > 0) { _stageVideo = stage.stageVideos[0]; _stageVideo.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); _stageVideo.attachNetStream(_hls.stream); } else { _video = new Video(stage.stageWidth, stage.stageHeight); addChild(_video); _video.smoothing = true; _video.attachNetStream(_hls.stream); } stage.removeEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState); }; private function _onStageResize(event : Event) : void { stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); _sheet.width = stage.stageWidth; _sheet.height = stage.stageHeight; _resize(); }; private function _resize() : void { var rect : Rectangle; rect = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, stage.stageWidth, stage.stageHeight); // resize video if (_video) { _video.width = rect.width; _video.height = rect.height; _video.x = rect.x; _video.y = rect.y; } else if (_stageVideo) { _stageVideo.viewPort = rect; } } } }
create playerSmoothSetLevel on ChromelessPlayer to change level without seeking
create playerSmoothSetLevel on ChromelessPlayer to change level without seeking
ActionScript
mpl-2.0
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
113f40d08604eb206e2e87e0cd6771072acae228
src/aerys/minko/render/material/realistic/RealisticMaterial.as
src/aerys/minko/render/material/realistic/RealisticMaterial.as
package aerys.minko.render.material.realistic { import aerys.minko.render.Effect; import aerys.minko.render.material.environment.EnvironmentMappingProperties; import aerys.minko.render.material.phong.PhongEffect; import aerys.minko.render.material.phong.PhongMaterial; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.IDataProvider; import flash.utils.Dictionary; public class RealisticMaterial extends PhongMaterial { private static const DEFAULT_NAME : String = 'RealisticMaterial'; private static const SCENE_TO_EFFECT : Dictionary = new Dictionary(true); public function get environmentMap() : ITextureResource { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP) as ITextureResource; } public function set environmentMap(value : ITextureResource) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP, value); } public function get environmentMapFiltering() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING); } public function set environmentMapFiltering(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, value); } public function get environmentMapMipMapping() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING); } public function set environmentMapMipMapping(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, value); } public function get environmentMapWrapping() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING); } public function set environmentMapWrapping(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, value); } public function get environmentMapFormat() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT); } public function set environmentMapFormat(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, value); } public function get reflectivity() : Number { return getProperty(EnvironmentMappingProperties.REFLECTIVITY) as Number; } public function set reflectivity(value : Number) : void { setProperty(EnvironmentMappingProperties.REFLECTIVITY, value); } public function get environmentMappingType() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE) as uint; } public function set environmentMappingType(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE, value); } public function get environmentBlending() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING) as uint; } public function set environmentBlending(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, value); } public function RealisticMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME) { super(properties, effect || new PhongEffect(new RealisticShader()), name); } override public function clone() : IDataProvider { return new RealisticMaterial(this, effect, name); } } }
package aerys.minko.render.material.realistic { import aerys.minko.render.Effect; import aerys.minko.render.material.environment.EnvironmentMappingProperties; import aerys.minko.render.material.phong.PhongEffect; import aerys.minko.render.material.phong.PhongMaterial; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.IDataProvider; import flash.utils.Dictionary; public class RealisticMaterial extends PhongMaterial { private static const DEFAULT_NAME : String = 'RealisticMaterial'; private static const DEFAULT_EFFECT : Effect = new PhongEffect( new RealisticShader() ); public function get environmentMap() : ITextureResource { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP) as ITextureResource; } public function set environmentMap(value : ITextureResource) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP, value); } public function get environmentMapFiltering() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING); } public function set environmentMapFiltering(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, value); } public function get environmentMapMipMapping() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING); } public function set environmentMapMipMapping(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, value); } public function get environmentMapWrapping() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING); } public function set environmentMapWrapping(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, value); } public function get environmentMapFormat() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT); } public function set environmentMapFormat(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, value); } public function get reflectivity() : Number { return getProperty(EnvironmentMappingProperties.REFLECTIVITY) as Number; } public function set reflectivity(value : Number) : void { setProperty(EnvironmentMappingProperties.REFLECTIVITY, value); } public function get environmentMappingType() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE) as uint; } public function set environmentMappingType(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE, value); } public function get environmentBlending() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING) as uint; } public function set environmentBlending(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, value); } public function RealisticMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME) { super(properties, effect || DEFAULT_EFFECT, name); } override public function clone() : IDataProvider { return new RealisticMaterial(this, effect, name); } } }
define a static const default effect for the RealisticMaterial and use it properly in the constructor
define a static const default effect for the RealisticMaterial and use it properly in the constructor
ActionScript
mit
aerys/minko-as3
a8f2b8e1467fe52d9afffa176a66a0106adbb895
runtime/src/main/as/flump/display/Layer.as
runtime/src/main/as/flump/display/Layer.as
// // Flump - Copyright 2013 Flump Authors package flump.display { import flump.mold.KeyframeMold; import flump.mold.LayerMold; import starling.animation.IAnimatable; import starling.display.DisplayObject; import starling.display.Sprite; /** * A logical wrapper around the DisplayObject(s) residing on the timeline of a single layer of a * Movie. Responsible for efficiently managing the creation and display of the DisplayObjects for * this layer on each frame. */ internal class Layer implements IAnimatable { public function Layer (movie :Movie, src :LayerMold, library :Library, flipbook :Boolean) { _keyframes = src.keyframes; _movie = movie; _name = src.name; const lastKf :KeyframeMold = _keyframes[_keyframes.length - 1]; _numFrames = lastKf.index + lastKf.duration; var lastItem :String; for (var ii :int = 0; ii < _keyframes.length && lastItem == null; ii++) { lastItem = _keyframes[ii].ref; } if (!flipbook && lastItem == null) { // The layer is empty. _currentDisplay = new Sprite(); _movie.addChild(_currentDisplay); } else { // Create the display objects for each keyframe. // If multiple consecutive keyframes refer to the same library item, // we reuse that item across those frames. _displays = new Vector.<DisplayObject>(_keyframes.length, true); for (ii = 0; ii < _keyframes.length; ++ii) { var kf :KeyframeMold = _keyframes[ii]; var display :DisplayObject = null; if (ii > 0 && _keyframes[ii - 1].ref == kf.ref) { display = _displays[ii - 1]; } else if (kf.ref == null) { display = new Sprite(); } else { display = library.createDisplayObject(kf.ref); } _displays[ii] = display; display.visible = false; _movie.addChild(display); } _currentDisplay = _displays[0]; _currentDisplay.visible = true; _frameOvershootDisplay = new Sprite(); _frameOvershootDisplay.visible = false; _movie.addChild(_frameOvershootDisplay); } _currentDisplay.name = _name; } /** Called by Movie when we loop. */ public function movieLooped () :void { _needsKeyframeUpdate = true; _keyframeIdx = 0; } /** Advances the playhead by the give number of seconds. From IAnimatable. */ public function advanceTime (dt :Number) :void { if (_currentDisplay is IAnimatable) { IAnimatable(_currentDisplay).advanceTime(dt); } } public function drawFrame (frame :int) :void { if (_displays == null) { // We have nothing to display. return; } else if (frame >= _numFrames) { // We've overshot our final frame. Show an empty sprite. if (_currentDisplay != _frameOvershootDisplay) { _currentDisplay.name = null; _currentDisplay.visible = false; _currentDisplay = _frameOvershootDisplay; _currentDisplay.name = _name; } // keep our keyframeIdx updated _keyframeIdx = _keyframes.length - 1; _needsKeyframeUpdate = true; return; } while (_keyframeIdx < _keyframes.length - 1 && _keyframes[_keyframeIdx + 1].index <= frame) { _keyframeIdx++; _needsKeyframeUpdate = true; } if (_needsKeyframeUpdate) { // Swap in the proper DisplayObject for this keyframe. const disp :DisplayObject = _displays[_keyframeIdx]; if (_currentDisplay != disp) { _currentDisplay.name = null; _currentDisplay.visible = false; // If we're swapping in a Movie, reset its timeline. if (disp is Movie) { Movie(disp).addedToLayer(); } _currentDisplay = disp; _currentDisplay.name = _name; } } _needsKeyframeUpdate = false; const kf :KeyframeMold = _keyframes[_keyframeIdx]; const layer :DisplayObject = _currentDisplay; if (_keyframeIdx == _keyframes.length - 1 || kf.index == frame || !kf.tweened) { layer.x = kf.x; layer.y = kf.y; layer.scaleX = kf.scaleX; layer.scaleY = kf.scaleY; layer.skewX = kf.skewX; layer.skewY = kf.skewY; layer.alpha = kf.alpha; } else { var interped :Number = (frame - kf.index) / kf.duration; var ease :Number = kf.ease; if (ease != 0) { var t :Number; if (ease < 0) { // Ease in var inv :Number = 1 - interped; t = 1 - inv * inv; ease = -ease; } else { // Ease out t = interped * interped; } interped = ease * t + (1 - ease) * interped; } const nextKf :KeyframeMold = _keyframes[_keyframeIdx + 1]; layer.x = kf.x + (nextKf.x - kf.x) * interped; layer.y = kf.y + (nextKf.y - kf.y) * interped; layer.scaleX = kf.scaleX + (nextKf.scaleX - kf.scaleX) * interped; layer.scaleY = kf.scaleY + (nextKf.scaleY - kf.scaleY) * interped; layer.skewX = kf.skewX + (nextKf.skewX - kf.skewX) * interped; layer.skewY = kf.skewY + (nextKf.skewY - kf.skewY) * interped; layer.alpha = kf.alpha + (nextKf.alpha - kf.alpha) * interped; } layer.pivotX = kf.pivotX; layer.pivotY = kf.pivotY; layer.visible = kf.visible; } protected var _keyframes :Vector.<KeyframeMold>; protected var _numFrames :int; // Stores this layer's DisplayObjects indexed by keyframe. protected var _displays :Vector.<DisplayObject>; // Created if the layer has fewer frames than its parent movie. If the layer is told to // draw a frame past its last frame, it will display this empty sprite. protected var _frameOvershootDisplay :Sprite; // The current DisplayObject being rendered for this layer protected var _currentDisplay :DisplayObject; protected var _movie :Movie; // The movie this layer belongs to // The index of the last keyframe drawn in drawFrame. Updated in drawFrame. When the parent // movie loops, it resets all of its layers' keyframeIdx's to 0. protected var _keyframeIdx :int; // true if the keyframe has changed since the last drawFrame protected var _needsKeyframeUpdate :Boolean; // name of the layer protected var _name :String; } }
// // Flump - Copyright 2013 Flump Authors package flump.display { import flump.mold.KeyframeMold; import flump.mold.LayerMold; import starling.animation.IAnimatable; import starling.display.DisplayObject; import starling.display.Sprite; /** * A logical wrapper around the DisplayObject(s) residing on the timeline of a single layer of a * Movie. Responsible for efficiently managing the creation and display of the DisplayObjects for * this layer on each frame. */ internal class Layer implements IAnimatable { public function Layer (movie :Movie, src :LayerMold, library :Library, flipbook :Boolean) { _keyframes = src.keyframes; _movie = movie; _name = src.name; const lastKf :KeyframeMold = _keyframes[_keyframes.length - 1]; _numFrames = lastKf.index + lastKf.duration; var lastItem :String; for (var ii :int = 0; ii < _keyframes.length && lastItem == null; ii++) { lastItem = _keyframes[ii].ref; } if (!flipbook && lastItem == null) { // The layer is empty. _currentDisplay = new Sprite(); _movie.addChild(_currentDisplay); } else { // Create the display objects for each keyframe. // If multiple consecutive keyframes refer to the same library item, // we reuse that item across those frames. _displays = new Vector.<DisplayObject>(_keyframes.length, true); for (ii = 0; ii < _keyframes.length; ++ii) { var kf :KeyframeMold = _keyframes[ii]; var display :DisplayObject = null; if (ii > 0 && _keyframes[ii - 1].ref == kf.ref) { display = _displays[ii - 1]; } else if (kf.ref == null) { display = new Sprite(); } else { display = library.createDisplayObject(kf.ref); } _displays[ii] = display; display.visible = false; _movie.addChild(display); } _currentDisplay = _displays[0]; _currentDisplay.visible = true; } _currentDisplay.name = _name; } /** Called by Movie when we loop. */ public function movieLooped () :void { _needsKeyframeUpdate = true; _keyframeIdx = 0; } /** Advances the playhead by the give number of seconds. From IAnimatable. */ public function advanceTime (dt :Number) :void { if (_currentDisplay is IAnimatable) { IAnimatable(_currentDisplay).advanceTime(dt); } } public function drawFrame (frame :int) :void { if (_displays == null) { // We have nothing to display. return; } else if (frame >= _numFrames) { // We've overshot our final frame. Hide the display _currentDisplay.visible = false; // keep our keyframeIdx updated _keyframeIdx = _keyframes.length - 1; _needsKeyframeUpdate = true; return; } while (_keyframeIdx < _keyframes.length - 1 && _keyframes[_keyframeIdx + 1].index <= frame) { _keyframeIdx++; _needsKeyframeUpdate = true; } if (_needsKeyframeUpdate) { // Swap in the proper DisplayObject for this keyframe. const disp :DisplayObject = _displays[_keyframeIdx]; if (_currentDisplay != disp) { _currentDisplay.name = null; _currentDisplay.visible = false; // If we're swapping in a Movie, reset its timeline. if (disp is Movie) { Movie(disp).addedToLayer(); } _currentDisplay = disp; _currentDisplay.name = _name; } } _needsKeyframeUpdate = false; const kf :KeyframeMold = _keyframes[_keyframeIdx]; const layer :DisplayObject = _currentDisplay; if (_keyframeIdx == _keyframes.length - 1 || kf.index == frame || !kf.tweened) { layer.x = kf.x; layer.y = kf.y; layer.scaleX = kf.scaleX; layer.scaleY = kf.scaleY; layer.skewX = kf.skewX; layer.skewY = kf.skewY; layer.alpha = kf.alpha; } else { var interped :Number = (frame - kf.index) / kf.duration; var ease :Number = kf.ease; if (ease != 0) { var t :Number; if (ease < 0) { // Ease in var inv :Number = 1 - interped; t = 1 - inv * inv; ease = -ease; } else { // Ease out t = interped * interped; } interped = ease * t + (1 - ease) * interped; } const nextKf :KeyframeMold = _keyframes[_keyframeIdx + 1]; layer.x = kf.x + (nextKf.x - kf.x) * interped; layer.y = kf.y + (nextKf.y - kf.y) * interped; layer.scaleX = kf.scaleX + (nextKf.scaleX - kf.scaleX) * interped; layer.scaleY = kf.scaleY + (nextKf.scaleY - kf.scaleY) * interped; layer.skewX = kf.skewX + (nextKf.skewX - kf.skewX) * interped; layer.skewY = kf.skewY + (nextKf.skewY - kf.skewY) * interped; layer.alpha = kf.alpha + (nextKf.alpha - kf.alpha) * interped; } layer.pivotX = kf.pivotX; layer.pivotY = kf.pivotY; layer.visible = kf.visible; } protected var _keyframes :Vector.<KeyframeMold>; protected var _numFrames :int; // Stores this layer's DisplayObjects indexed by keyframe. protected var _displays :Vector.<DisplayObject>; // The current DisplayObject being rendered for this layer protected var _currentDisplay :DisplayObject; protected var _movie :Movie; // The movie this layer belongs to // The index of the last keyframe drawn in drawFrame. Updated in drawFrame. When the parent // movie loops, it resets all of its layers' keyframeIdx's to 0. protected var _keyframeIdx :int; // true if the keyframe has changed since the last drawFrame protected var _needsKeyframeUpdate :Boolean; // name of the layer protected var _name :String; } }
remove frameOverShootDisplay sprite
remove frameOverShootDisplay sprite
ActionScript
mit
mathieuanthoine/flump,tconkling/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump
59c6998c30630453371516f40bfa19f6fd24cf36
src/as/com/threerings/flash/FrameSprite.as
src/as/com/threerings/flash/FrameSprite.as
// // $Id$ package com.threerings.flash { import flash.display.Sprite; import flash.events.Event; /** * Convenience superclass to use for sprites that need to update every frame. * (One must be very careful to remove all ENTER_FRAME listeners when not needed, as they * will prevent an object from being garbage collected!) */ public class FrameSprite extends Sprite { public function FrameSprite () { addEventListener(Event.ADDED_TO_STAGE, handleAdded); addEventListener(Event.REMOVED_FROM_STAGE, handleRemoved); } /** * Called when we're added to the stage. */ protected function handleAdded (... ignored) :void { addEventListener(Event.ENTER_FRAME, handleFrame); handleFrame(); // update immediately } /** * Called when we're added to the stage. */ protected function handleRemoved (... ignored) :void { removeEventListener(Event.ENTER_FRAME, handleFrame); } /** * Called to update our visual appearance prior to each frame. */ protected function handleFrame (... ignored) :void { // nothing here. Override in yor subclass. } } }
// // $Id$ package com.threerings.flash { import flash.display.Sprite; import flash.events.Event; /** * Convenience superclass to use for sprites that need to update every frame. * (One must be very careful to remove all ENTER_FRAME listeners when not needed, as they * will prevent an object from being garbage collected!) */ public class FrameSprite extends Sprite { /** * @param renderFrameUponAdding if true, the handleFrame() method * is called whenever an ADDED_TO_STAGE event is received. */ public function FrameSprite (renderFrameUponAdding :Boolean = true) { _renderOnAdd = renderFrameUponAdding; addEventListener(Event.ADDED_TO_STAGE, handleAdded); addEventListener(Event.REMOVED_FROM_STAGE, handleRemoved); } /** * Called when we're added to the stage. */ protected function handleAdded (... ignored) :void { addEventListener(Event.ENTER_FRAME, handleFrame); if (_renderOnAdd) { handleFrame(); // update immediately } } /** * Called when we're added to the stage. */ protected function handleRemoved (... ignored) :void { removeEventListener(Event.ENTER_FRAME, handleFrame); } /** * Called to update our visual appearance prior to each frame. */ protected function handleFrame (... ignored) :void { // nothing here. Override in yor subclass. } /** Should we call handleFrame() when we get ADDED_TO_STAGE? */ protected var _renderOnAdd :Boolean; } }
Allow subclasses to choose not to call handleFrame() when ADDED_TO_STAGE is received.
Allow subclasses to choose not to call handleFrame() when ADDED_TO_STAGE is received. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@253 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
417d3cc657d1c2febdfba4420339a96ad9b1566d
skin-src/goplayer/StandardSkin.as
skin-src/goplayer/StandardSkin.as
package goplayer { import flash.display.DisplayObject import flash.display.InteractiveObject import flash.display.Sprite import flash.text.TextField public class StandardSkin extends AbstractStandardSkin { private var _seekBarWidth : Number override public function update() : void { super.update() setPosition(largePlayButton, dimensions.center) setPosition(bufferingIndicator, dimensions.center) setDimensions(largePlayButton, dimensions.halved.innerSquare) upperPanel.x = 0 upperPanel.y = 0 packLeft (upperPanelLeft, [upperPanelMiddle, setUpperPanelWidth], upperPanelRight) controlBar.x = 0 controlBar.y = dimensions.height packLeft (showPlayPauseButton ? playPausePart : null, beforeLeftTimePart, showElapsedTime ? leftTimeBackgroundPart : null, afterLeftTimePart, [seekBar, setSeekBarWidth], beforeRightTimePart, showTotalTime ? rightTimeBackgroundPart : null, afterRightTimePart, showVolumeControl ? volumePart : null, showFullscreenButton ? fullscreenPart : null) leftTimeFieldPart.x = beforeLeftTimePart.x rightTimeFieldPart.x = beforeRightTimePart.x playPausePart.visible = showPlayPauseButton leftTimeBackgroundPart.visible = showElapsedTime leftTimeFieldPart.visible = showElapsedTime seekBarBuffer.visible = showSeekBar seekBarPlayhead.visible = showSeekBar seekBarTooltip.visible = showSeekBar seekBarTooltipField.visible = showSeekBar rightTimeBackgroundPart.visible = showTotalTime rightTimeFieldPart.visible = showTotalTime volumePart.visible = showVolumeControl fullscreenPart.visible = showFullscreenButton } private function packLeft(... items : Array) : void { Packer.$packLeft(dimensions.width, items) } private function setUpperPanelWidth(value : Number) : void { upperPanelMiddleBackground.width = value titleField.width = value } private function setSeekBarWidth(value : Number) : void { _seekBarWidth = value } override protected function get seekBarWidth() : Number { return _seekBarWidth } override protected function get upperPanel() : Sprite { return lookup("chrome.upperPanel") } private function get upperPanelLeft() : Sprite { return lookup("chrome.upperPanel.left") } private function get upperPanelMiddle() : Sprite { return lookup("chrome.upperPanel.middle") } private function get upperPanelMiddleBackground() : Sprite { return lookup("chrome.upperPanel.middle.background") } private function get upperPanelRight() : Sprite { return lookup("chrome.upperPanel.right") } override protected function get largePlayButton() : InteractiveObject { return lookup("largePlayButton") } override protected function get bufferingIndicator() : InteractiveObject { return lookup("bufferingIndicator") } override protected function get chrome() : Sprite { return lookup("chrome") } override protected function get titleField() : TextField { return lookup("chrome.upperPanel.middle.titleField") } override protected function get controlBar() : Sprite { return lookup("chrome.controlBar") } private function get playPausePart() : DisplayObject { return lookup("chrome.controlBar.playPause") } override protected function get playButton() : DisplayObject { return lookup("chrome.controlBar.playPause.playButton") } override protected function get pauseButton() : DisplayObject { return lookup("chrome.controlBar.playPause.pauseButton") } private function get beforeLeftTimePart() : DisplayObject { return lookup("chrome.controlBar.beforeLeftTime") } private function get leftTimeBackgroundPart() : DisplayObject { return lookup("chrome.controlBar.leftTimeBackground") } private function get leftTimeFieldPart() : DisplayObject { return lookup("chrome.controlBar.leftTime") } override protected function get leftTimeField() : TextField { return lookup("chrome.controlBar.leftTime.field") } private function get afterLeftTimePart() : DisplayObject { return lookup("chrome.controlBar.afterLeftTime") } override protected function get seekBar() : Sprite { return lookup("chrome.controlBar.seekBar") } override protected function get seekBarBackground() : DisplayObject { return lookup("chrome.controlBar.seekBar.background") } override protected function get seekBarBuffer() : DisplayObject { return lookup("chrome.controlBar.seekBar.buffer") } override protected function get seekBarPlayhead() : DisplayObject { return lookup("chrome.controlBar.seekBar.playhead") } override protected function get seekBarTooltip() : DisplayObject { return lookup("chrome.controlBar.seekBar.tooltip") } override protected function get seekBarTooltipField() : TextField { return lookup("chrome.controlBar.seekBar.tooltip.field") } private function get beforeRightTimePart() : DisplayObject { return lookup("chrome.controlBar.beforeRightTime") } private function get rightTimeBackgroundPart() : DisplayObject { return lookup("chrome.controlBar.rightTimeBackground") } private function get rightTimeFieldPart() : DisplayObject { return lookup("chrome.controlBar.rightTime") } override protected function get rightTimeField() : TextField { return lookup("chrome.controlBar.rightTime.field") } private function get afterRightTimePart() : DisplayObject { return lookup("chrome.controlBar.afterRightTime") } private function get volumePart() : DisplayObject { return lookup("chrome.controlBar.volume") } override protected function get muteButton() : DisplayObject { return lookup("chrome.controlBar.volume.muteButton") } override protected function get unmuteButton() : DisplayObject { return lookup("chrome.controlBar.volume.unmuteButton") } override protected function get volumeSlider() : Sprite { return lookup("chrome.controlBar.volume.slider") } override protected function get volumeSliderThumb() : DisplayObject { return lookup("chrome.controlBar.volume.slider.thumb") } override protected function get volumeSliderThumbGuide() : DisplayObject { return lookup("chrome.controlBar.volume.slider.thumbGuide") } override protected function get volumeSliderFill() : DisplayObject { return lookup("chrome.controlBar.volume.slider.fill") } private function get fullscreenPart() : DisplayObject { return lookup("chrome.controlBar.fullscreen") } override protected function get enableFullscreenButton() : DisplayObject { return lookup("chrome.controlBar.fullscreen.enableButton") } override protected function lookup(name : String) : * { return super.lookup("skinContent." + name) } } }
package goplayer { import flash.display.DisplayObject import flash.display.InteractiveObject import flash.display.Sprite import flash.text.TextField public class StandardSkin extends AbstractStandardSkin { private var _seekBarWidth : Number override public function update() : void { super.update() setPosition(largePlayButton, dimensions.center) setPosition(bufferingIndicator, dimensions.center) setDimensions(largePlayButton, dimensions.halved.innerSquare) upperPanel.x = 0 upperPanel.y = 0 packLeft (upperPanelLeft, [upperPanelMiddle, setUpperPanelWidth], upperPanelRight) controlBar.x = 0 controlBar.y = dimensions.height packLeft (showPlayPauseButton ? playPausePart : null, beforeLeftTimePart, showElapsedTime ? leftTimeBackgroundPart : null, afterLeftTimePart, [seekBar, setSeekBarWidth], beforeRightTimePart, showTotalTime ? rightTimeBackgroundPart : null, afterRightTimePart, showVolumeControl ? volumePart : null, showFullscreenButton ? fullscreenPart : null) leftTimeFieldPart.x = beforeLeftTimePart.x rightTimeFieldPart.x = beforeRightTimePart.x playPausePart.visible = showPlayPauseButton leftTimeBackgroundPart.visible = showElapsedTime leftTimeFieldPart.visible = showElapsedTime seekBar.visible = showSeekBar rightTimeBackgroundPart.visible = showTotalTime rightTimeFieldPart.visible = showTotalTime volumePart.visible = showVolumeControl fullscreenPart.visible = showFullscreenButton } private function packLeft(... items : Array) : void { Packer.$packLeft(dimensions.width, items) } private function setUpperPanelWidth(value : Number) : void { upperPanelMiddleBackground.width = value titleField.width = value } private function setSeekBarWidth(value : Number) : void { _seekBarWidth = value } override protected function get seekBarWidth() : Number { return _seekBarWidth } override protected function get upperPanel() : Sprite { return lookup("chrome.upperPanel") } private function get upperPanelLeft() : Sprite { return lookup("chrome.upperPanel.left") } private function get upperPanelMiddle() : Sprite { return lookup("chrome.upperPanel.middle") } private function get upperPanelMiddleBackground() : Sprite { return lookup("chrome.upperPanel.middle.background") } private function get upperPanelRight() : Sprite { return lookup("chrome.upperPanel.right") } override protected function get largePlayButton() : InteractiveObject { return lookup("largePlayButton") } override protected function get bufferingIndicator() : InteractiveObject { return lookup("bufferingIndicator") } override protected function get chrome() : Sprite { return lookup("chrome") } override protected function get titleField() : TextField { return lookup("chrome.upperPanel.middle.titleField") } override protected function get controlBar() : Sprite { return lookup("chrome.controlBar") } private function get playPausePart() : DisplayObject { return lookup("chrome.controlBar.playPause") } override protected function get playButton() : DisplayObject { return lookup("chrome.controlBar.playPause.playButton") } override protected function get pauseButton() : DisplayObject { return lookup("chrome.controlBar.playPause.pauseButton") } private function get beforeLeftTimePart() : DisplayObject { return lookup("chrome.controlBar.beforeLeftTime") } private function get leftTimeBackgroundPart() : DisplayObject { return lookup("chrome.controlBar.leftTimeBackground") } private function get leftTimeFieldPart() : DisplayObject { return lookup("chrome.controlBar.leftTime") } override protected function get leftTimeField() : TextField { return lookup("chrome.controlBar.leftTime.field") } private function get afterLeftTimePart() : DisplayObject { return lookup("chrome.controlBar.afterLeftTime") } override protected function get seekBar() : Sprite { return lookup("chrome.controlBar.seekBar") } override protected function get seekBarBackground() : DisplayObject { return lookup("chrome.controlBar.seekBar.background") } override protected function get seekBarBuffer() : DisplayObject { return lookup("chrome.controlBar.seekBar.buffer") } override protected function get seekBarPlayhead() : DisplayObject { return lookup("chrome.controlBar.seekBar.playhead") } override protected function get seekBarTooltip() : DisplayObject { return lookup("chrome.controlBar.seekBar.tooltip") } override protected function get seekBarTooltipField() : TextField { return lookup("chrome.controlBar.seekBar.tooltip.field") } private function get beforeRightTimePart() : DisplayObject { return lookup("chrome.controlBar.beforeRightTime") } private function get rightTimeBackgroundPart() : DisplayObject { return lookup("chrome.controlBar.rightTimeBackground") } private function get rightTimeFieldPart() : DisplayObject { return lookup("chrome.controlBar.rightTime") } override protected function get rightTimeField() : TextField { return lookup("chrome.controlBar.rightTime.field") } private function get afterRightTimePart() : DisplayObject { return lookup("chrome.controlBar.afterRightTime") } private function get volumePart() : DisplayObject { return lookup("chrome.controlBar.volume") } override protected function get muteButton() : DisplayObject { return lookup("chrome.controlBar.volume.muteButton") } override protected function get unmuteButton() : DisplayObject { return lookup("chrome.controlBar.volume.unmuteButton") } override protected function get volumeSlider() : Sprite { return lookup("chrome.controlBar.volume.slider") } override protected function get volumeSliderThumb() : DisplayObject { return lookup("chrome.controlBar.volume.slider.thumb") } override protected function get volumeSliderThumbGuide() : DisplayObject { return lookup("chrome.controlBar.volume.slider.thumbGuide") } override protected function get volumeSliderFill() : DisplayObject { return lookup("chrome.controlBar.volume.slider.fill") } private function get fullscreenPart() : DisplayObject { return lookup("chrome.controlBar.fullscreen") } override protected function get enableFullscreenButton() : DisplayObject { return lookup("chrome.controlBar.fullscreen.enableButton") } override protected function lookup(name : String) : * { return super.lookup("skinContent." + name) } } }
Fix bug: Seek bar tooltip visibility was being reverted all the time.
Fix bug: Seek bar tooltip visibility was being reverted all the time.
ActionScript
mit
dbrock/goplayer,dbrock/goplayer
074ee8976d0c8c96773a51f3a81f0bede4f50177
src/main/flex/org/servebox/cafe/core/application/Application.as
src/main/flex/org/servebox/cafe/core/application/Application.as
package org.servebox.cafe.core.application { import org.servebox.cafe.core.spring.ApplicationContext; import spark.components.Application; public class Application extends spark.components.Application implements CafeApplication { private var _context : ApplicationContext; public function Application() { super(); ApplicationInitializer.prepare( this ); _context = ApplicationInitializer.getDefaultContext(); } public function getContext():ApplicationContext { return null; } } }
package org.servebox.cafe.core.application { import org.servebox.cafe.core.spring.ApplicationContext; import spark.components.Application; public class Application extends spark.components.Application implements CafeApplication { private var _context : ApplicationContext; public function Application() { super(); ApplicationInitializer.prepare( this ); _context = ApplicationInitializer.getDefaultContext(); } public function getContext():ApplicationContext { return _context; } } }
Fix bug on getContext() null
Fix bug on getContext() null
ActionScript
mit
servebox/as-cafe
2ab945f9e067b208b47533debf801ee75fa666d5
sdk-remote/src/tests/bin/liburbi-check.as
sdk-remote/src/tests/bin/liburbi-check.as
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*- URBI_INIT # Avoid zombies and preserve debugging information. cleanup () { exit_status=$? # We can be killed even before children are spawned. test -n "$children" || exit $exit_status # In case we were caught by set -e, kill the children. children_kill children_harvest children_report children_sta=$(children_status remote) # Don't clean before calling children_status... test x$VERBOSE != x || children_clean case $exit_status:$children_sta in (0:0) ;; (0:*) # Maybe a children exited for SKIP etc. exit $children_sta;; (*:*) # If liburbi-check failed, there is a big problem. error SOFTWARE "liburbi-check itself failed with $exit_status";; esac # rst_expect sets exit=false if it saw a failure. $exit } for signal in 1 2 13 15; do trap 'error $((128 + $signal)) \ "received signal $signal ($(kill -l $signal))"' $signal done trap cleanup 0 # Overriden to include the test name. stderr () { echo >&2 "$(basename $0): $me: $@" echo >&2 } # Sleep some time, but taking into account the fact that # instrumentation slows down a lot. my_sleep () { if $INSTRUMENT; then sleep $(($1 * 5)) else sleep $1 fi } ## -------------- ## ## Main program. ## ## -------------- ## exec 3>&2 check_dir abs_builddir liburbi-check check_dir abs_top_builddir config.status check_dir abs_top_srcdir configure.ac # Make it absolute. chk=$(absolute "$1") if test ! -f "$chk.cc"; then fatal "no such file: $chk.cc" fi # ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x medir=$(basename $(dirname "$chk")) # ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x/andexp-pipeexp me=$medir/$(basename "$chk" ".cc") # ./../../../tests/2.x/andexp-pipeexp.chk -> andexp-pipeexp meraw=$(basename $me) # MERAW! srcdir=$(absolute $srcdir) export srcdir # Move to a private dir. rm -rf $me.dir mkdir -p $me.dir cd $me.dir # Help debugging set | rst_pre "$me variables" # $URBI_SERVER. # # If this SDK-Remote is part of the Kernel package, then we should not # use an installed urbi-console, but rather the one which is part of # this package. if test -d $abs_top_srcdir/../../src/kernel; then stderr "This SDK-Remote is part of a kernel package" \ " ($abs_top_srcdir/../../src/kernel exists)." export PATH=$abs_top_builddir/../tests/bin:$PATH else stderr "This SDK-Remote is standalone." fi # Leaves trailing files, so run it in subdir. find_urbi_server # Compute expected output. sed -n -e 's,//= ,,p' $chk.cc >output.exp touch error.exp echo 0 >status.exp # Start it. spawn_urbi_server # Start the test. valgrind=$(instrument "remote.val") cmd="$valgrind ../../tests --port-file server.port $meraw" echo "$cmd" >remote.cmd $cmd >remote.out.raw 2>remote.err & children_register remote # Let some time to run the tests. children_wait 10 # Ignore the "client errors". sed -e '/^E client error/d' remote.out.raw >remote.out.eff # Compare expected output with actual output. rst_expect output remote.out rst_pre "Error output" remote.err # Display Valgrind report. rst_pre "Valgrind" remote.val # Exit with success: liburbi-check made its job. But now clean (on # trap 0) will check $exit to see if there is a failure in the tests # and adjust the exit status accordingly. exit 0
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*- URBI_INIT # Avoid zombies and preserve debugging information. cleanup () { exit_status=$? # We can be killed even before children are spawned. test -n "$children" || exit $exit_status # In case we were caught by set -e, kill the children. children_kill children_harvest children_report children_sta=$(children_status remote) # Don't clean before calling children_status... test x$VERBOSE != x || children_clean case $exit_status:$children_sta in (0:0) ;; (0:*) # Maybe a children exited for SKIP etc. exit $children_sta;; (*:*) # If liburbi-check failed, there is a big problem. error SOFTWARE "liburbi-check itself failed with $exit_status";; esac # rst_expect sets exit=false if it saw a failure. $exit } for signal in 1 2 13 15; do trap 'error $((128 + $signal)) \ "received signal $signal ($(kill -l $signal))"' $signal done trap cleanup 0 # Overriden to include the test name. stderr () { echo >&2 "$(basename $0): $me: $@" echo >&2 } # Sleep some time, but taking into account the fact that # instrumentation slows down a lot. my_sleep () { if $INSTRUMENT; then sleep $(($1 * 5)) else sleep $1 fi } ## -------------- ## ## Main program. ## ## -------------- ## exec 3>&2 check_dir abs_builddir bin/liburbi-check check_dir abs_top_builddir config.status check_dir abs_top_srcdir configure.ac # Make it absolute. chk=$(absolute "$1") if test ! -f "$chk.cc"; then fatal "no such file: $chk.cc" fi # ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x medir=$(basename $(dirname "$chk")) # ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x/andexp-pipeexp me=$medir/$(basename "$chk" ".cc") # ./../../../tests/2.x/andexp-pipeexp.chk -> andexp-pipeexp meraw=$(basename $me) # MERAW! srcdir=$(absolute $srcdir) export srcdir # Move to a private dir. rm -rf $me.dir mkdir -p $me.dir cd $me.dir # Help debugging set | rst_pre "$me variables" # $URBI_SERVER. # # If this SDK-Remote is part of the Kernel package, then we should not # use an installed urbi-console, but rather the one which is part of # this package. if test -d $abs_top_srcdir/../../src/kernel; then stderr "This SDK-Remote is part of a kernel package" \ " ($abs_top_srcdir/../../src/kernel exists)." export PATH=$abs_top_builddir/../tests/bin:$PATH else stderr "This SDK-Remote is standalone." fi # Leaves trailing files, so run it in subdir. find_urbi_server # Compute expected output. sed -n -e 's,//= ,,p' $chk.cc >output.exp touch error.exp echo 0 >status.exp # Start it. spawn_urbi_server # Start the test. valgrind=$(instrument "remote.val") cmd="$valgrind ../../tests --port-file server.port $meraw" echo "$cmd" >remote.cmd $cmd >remote.out.raw 2>remote.err & children_register remote # Let some time to run the tests. children_wait 10 # Ignore the "client errors". sed -e '/^E client error/d' remote.out.raw >remote.out.eff # Compare expected output with actual output. rst_expect output remote.out rst_pre "Error output" remote.err # Display Valgrind report. rst_pre "Valgrind" remote.val # Exit with success: liburbi-check made its job. But now clean (on # trap 0) will check $exit to see if there is a failure in the tests # and adjust the exit status accordingly. exit 0
Update a dir witness.
Update a dir witness. * src/tests/bin/liburbi-check.as: liburbi-check is now in bin/. This remained unnoticed because the previous liburbi-check was still there.
ActionScript
bsd-3-clause
aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi
caf8a75b765ef008abe1b3d849264cc5da7828e7
krew-framework/krewfw/core/KrewActorDelegate.as
krew-framework/krewfw/core/KrewActorDelegate.as
package krewfw.core { import flash.media.Sound; import starling.display.Image; import starling.display.Sprite; import starling.textures.Texture; /** * Scene 上にのっていない Actor が Actor めいた仕事をしたいときの委譲先。 * バックエンドに存在する各 Scene のシステム Actor に処理を代行してもらう。 * 以下のように使う。 * * <pre> * import krewfw.utils.krew; * krew.delegate.sendMessage(...); * </pre> * * krewFramework は Actor の集まりで構成するという設計思想を持つが、 * static な Model クラスなどがリソースへのアクセスやメッセージングなどを * 行いたくなった時、または Actor を増やした時のオーバヘッドを減らしたい場合などに利用する。 * * ただしフレームワークのポリシー上、Actor にタスクを登録する系統のものは代行できない。 * そういうことをしたくなったクラスは Actor として Scene 上に生きなければならない。 */ //------------------------------------------------------------ public class KrewActorDelegate { /** system actor on current scene */ private static var _actor:KrewActor = null; //------------------------------------------------------------ // Called by framework //------------------------------------------------------------ public static function setSystemActor(actor:KrewActor):void { _actor = actor; } public static function clearSystemActor():void { _actor = null; } //------------------------------------------------------------ // Singleton interface //------------------------------------------------------------ private static var _instance:KrewActorDelegate; public function KrewActorDelegate() { if (_instance) { throw new Error("[KrewActorDelegate] Cannot instantiate singleton."); } } public static function get instance():KrewActorDelegate { if (_actor == null) { throw new Error("[KrewActorDelegate] System actor is not ready."); } if (!_instance) { _instance = new KrewActorDelegate(); } return _instance; } //------------------------------------------------------------ // Delegate methods //------------------------------------------------------------ public function getTexture(fileName:String):Texture { return _actor.getTexture(fileName); } public function getImage (fileName:String):Image { return _actor.getImage (fileName); } public function getSound (fileName:String):Sound { return _actor.getSound (fileName); } public function getXml (fileName:String):XML { return _actor.getXml (fileName); } public function getObject (fileName:String):Object { return _actor.getObject (fileName); } public function loadResources(fileNameList:Array, onLoadProgress:Function, onLoadComplete:Function):void { _actor.loadResources(fileNameList, onLoadProgress, onLoadComplete); } public function sendMessage(eventType:String, eventArgs:Object=null):void { _actor.sendMessage(eventType, eventArgs); } public function createActor(newActor:KrewActor, layerName:String):void { _actor.createActor(newActor, layerName); } } }
package krewfw.core { import flash.media.Sound; import starling.display.Image; import starling.display.Sprite; import starling.textures.Texture; import krewfw.core_internal.KrewSharedObjects; /** * Scene 上にのっていない Actor が Actor めいた仕事をしたいときの委譲先。 * バックエンドに存在する各 Scene のシステム Actor に処理を代行してもらう。 * 以下のように使う。 * * <pre> * import krewfw.utils.krew; * krew.delegate.sendMessage(...); * </pre> * * krewFramework は Actor の集まりで構成するという設計思想を持つが、 * static な Model クラスなどがリソースへのアクセスやメッセージングなどを * 行いたくなった時、または Actor を増やした時のオーバヘッドを減らしたい場合などに利用する。 * * ただしフレームワークのポリシー上、Actor にタスクを登録する系統のものは代行できない。 * そういうことをしたくなったクラスは Actor として Scene 上に生きなければならない。 */ //------------------------------------------------------------ public class KrewActorDelegate { /** system actor on current scene */ private static var _actor:KrewActor = null; //------------------------------------------------------------ // Called by framework //------------------------------------------------------------ public static function setSystemActor(actor:KrewActor):void { _actor = actor; } public static function clearSystemActor():void { _actor = null; } //------------------------------------------------------------ // Singleton interface //------------------------------------------------------------ private static var _instance:KrewActorDelegate; public function KrewActorDelegate() { if (_instance) { throw new Error("[KrewActorDelegate] Cannot instantiate singleton."); } } public static function get instance():KrewActorDelegate { if (_actor == null) { throw new Error("[KrewActorDelegate] System actor is not ready."); } if (!_instance) { _instance = new KrewActorDelegate(); } return _instance; } //------------------------------------------------------------ // Delegate methods //------------------------------------------------------------ public function get sharedObj():KrewSharedObjects { return _actor.sharedObj; } public function getTexture(fileName:String):Texture { return _actor.getTexture(fileName); } public function getImage (fileName:String):Image { return _actor.getImage (fileName); } public function getSound (fileName:String):Sound { return _actor.getSound (fileName); } public function getXml (fileName:String):XML { return _actor.getXml (fileName); } public function getObject (fileName:String):Object { return _actor.getObject (fileName); } public function loadResources(fileNameList:Array, onLoadProgress:Function, onLoadComplete:Function):void { _actor.loadResources(fileNameList, onLoadProgress, onLoadComplete); } public function sendMessage(eventType:String, eventArgs:Object=null):void { _actor.sendMessage(eventType, eventArgs); } public function createActor(newActor:KrewActor, layerName:String):void { _actor.createActor(newActor, layerName); } } }
Modify krewActorDelegate
Modify krewActorDelegate
ActionScript
mit
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
3d9a9bcd3f9ade3dfa719310ce2661066293ceab
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.5"; /** * 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.6"; /** * 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; } } }
bump version to 3.9.6
bump version to 3.9.6
ActionScript
agpl-3.0
shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp
69b7d70515d02ed4848a5aeff33ee786c9ed3e39
Game/Resources/elevatorScene/Scripts/LightsOutScript.as
Game/Resources/elevatorScene/Scripts/LightsOutScript.as
class LightsOutScript { Hub @hub; Entity @self; LightsOutScript(Entity @entity){ @hub = Managers(); @self = @entity; } // Index goes first row 0 -> 4, second row 5 -> 9 etc. void ButtonPress(int index) { // Check if button is not pressed, in which case we invert its neighbors (check for out of bounds) print("Pressed button nr `" + index + "`\n"); } void b_0_0() { ButtonPress(0); } void b_0_1() { ButtonPress(1); } void b_0_2() { ButtonPress(2); } void b_0_3() { ButtonPress(3); } void b_0_4() { ButtonPress(4); } void b_1_0() { ButtonPress(5); } void b_1_1() { ButtonPress(6); } void b_1_2() { ButtonPress(7); } void b_1_3() { ButtonPress(8); } void b_1_4() { ButtonPress(9); } void b_2_0() { ButtonPress(10); } void b_2_1() { ButtonPress(11); } void b_2_2() { ButtonPress(12); } void b_2_3() { ButtonPress(13); } void b_2_4() { ButtonPress(14); } void b_3_0() { ButtonPress(15); } void b_3_1() { ButtonPress(16); } void b_3_2() { ButtonPress(17); } void b_3_3() { ButtonPress(18); } void b_3_4() { ButtonPress(19); } void b_4_0() { ButtonPress(20); } void b_4_1() { ButtonPress(21); } void b_4_2() { ButtonPress(22); } void b_4_3() { ButtonPress(23); } void b_4_4() { ButtonPress(24); } }
class LightsOutScript { Hub @hub; Entity @self; LightsOutScript(Entity @entity){ @hub = Managers(); @self = @entity; } // Index goes first row 0 -> 4, second row 5 -> 9 etc. void ButtonPress(int index) { // Check if button is not pressed, in which case we invert its neighbors (check for out of bounds) print("Pressed button nr `" + index + "`\n"); } void b_0_0() { ButtonPress(0); } void b_0_1() { ButtonPress(1); } void b_0_2() { ButtonPress(2); } void b_0_3() { ButtonPress(3); } void b_0_4() { ButtonPress(4); } void b_1_0() { ButtonPress(5); } void b_1_1() { ButtonPress(6); } void b_1_2() { ButtonPress(7); } void b_1_3() { ButtonPress(8); } void b_1_4() { ButtonPress(9); } void b_2_0() { ButtonPress(10); } void b_2_1() { ButtonPress(11); } void b_2_2() { ButtonPress(12); } void b_2_3() { ButtonPress(13); } void b_2_4() { ButtonPress(14); } void b_3_0() { ButtonPress(15); } void b_3_1() { ButtonPress(16); } void b_3_2() { ButtonPress(17); } void b_3_3() { ButtonPress(18); } void b_3_4() { ButtonPress(19); } void b_4_0() { ButtonPress(20); } void b_4_1() { ButtonPress(21); } void b_4_2() { ButtonPress(22); } void b_4_3() { ButtonPress(23); } void b_4_4() { ButtonPress(24); } }
Change tabs to spaces in script.
Change tabs to spaces in script.
ActionScript
mit
Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/LargeGameProjectEngine
ed7737b113d66237200ad7d82affd9be1e917a69
src/aerys/minko/scene/node/camera/AbstractCamera.as
src/aerys/minko/scene/node/camera/AbstractCamera.as
package aerys.minko.scene.node.camera { import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.data.CameraDataProvider; import aerys.minko.scene.node.AbstractSceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.math.Frustum; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Ray; public class AbstractCamera extends AbstractSceneNode { public static const DEFAULT_ZNEAR : Number = .1; public static const DEFAULT_ZFAR : Number = 500.; protected var _cameraCtrl : CameraController; protected var _cameraData : CameraDataProvider; protected var _enabled : Boolean; protected var _activated : Signal; protected var _deactivated : Signal; public function get zNear() : Number { return _cameraData.zNear; } public function set zNear(value : Number) : void { _cameraData.zNear = value; } public function get zFar() : Number { return _cameraData.zFar; } public function set zFar(value : Number) : void { _cameraData.zFar = value; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { if (value != _enabled) { _enabled = value; if (_enabled) _activated.execute(this); else _deactivated.execute(this); } } public function get activated() : Signal { return _activated; } public function get deactivated() : Signal { return _deactivated; } public function get frustum() : Frustum { return _cameraData.frustum; } protected function get cameraController() : CameraController { return _cameraCtrl; } protected function get cameraData() : CameraDataProvider { return _cameraData; } public function AbstractCamera(zNear : Number = DEFAULT_ZNEAR, zFar : Number = DEFAULT_ZFAR) { super(); initializeCameraData(zNear, zFar); } override protected function initialize() : void { _enabled = true; super.initialize(); } override protected function initializeSignals():void { super.initializeSignals(); _activated = new Signal('Camera.activated'); _deactivated = new Signal('Camera.deactivated'); } override protected function initializeContollers():void { super.initializeContollers(); _cameraCtrl = new CameraController(); addController(_cameraCtrl); } override protected function initializeDataProviders():void { super.initializeDataProviders(); _cameraData = _cameraCtrl.cameraData; } protected function initializeCameraData(zNear : Number, zFar : Number) : void { _cameraData.zNear = zNear; _cameraData.zFar = zFar; } public function unproject(x : Number, y : Number, out : Ray = null) : Ray { throw new Error('Must be overriden.'); } /** * Return a copy of the world to view matrix. This method is an alias on the * getWorldToLocalTransform() method. * * @param output * @return * */ public function getWorldToViewTransform(forceUpdate : Boolean, output : Matrix4x4 = null) : Matrix4x4 { return getWorldToLocalTransform(forceUpdate, output); } /** * Return a copy of the view to world matrix. This method is an alias on the * getLocalToWorldTransform() method. * * @param output * @return * */ public function getViewToWorldTransform(forceUpdate : Boolean, output : Matrix4x4 = null) : Matrix4x4 { return getLocalToWorldTransform(forceUpdate, output); } /** * Return a copy of the projection matrix. * * @param output * @return * */ public function getProjection(output : Matrix4x4) : Matrix4x4 { output ||= new Matrix4x4(); return output.copyFrom(_cameraData.projection); } } }
package aerys.minko.scene.node.camera { import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.data.CameraDataProvider; import aerys.minko.scene.node.AbstractSceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.math.Frustum; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Ray; public class AbstractCamera extends AbstractSceneNode { public static const DEFAULT_ZNEAR : Number = .1; public static const DEFAULT_ZFAR : Number = 500.; protected var _cameraCtrl : CameraController; protected var _cameraData : CameraDataProvider; protected var _enabled : Boolean; protected var _activated : Signal; protected var _deactivated : Signal; public function get zNear() : Number { return _cameraData.zNear; } public function set zNear(value : Number) : void { _cameraData.zNear = value; } public function get zFar() : Number { return _cameraData.zFar; } public function set zFar(value : Number) : void { _cameraData.zFar = value; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { if (value != _enabled) { _enabled = value; if (_enabled) _activated.execute(this); else _deactivated.execute(this); } } public function get activated() : Signal { return _activated; } public function get deactivated() : Signal { return _deactivated; } public function get frustum() : Frustum { return _cameraData.frustum; } protected function get cameraController() : CameraController { return _cameraCtrl; } protected function get cameraData() : CameraDataProvider { return _cameraData; } public function AbstractCamera(zNear : Number = DEFAULT_ZNEAR, zFar : Number = DEFAULT_ZFAR) { super(); initializeCameraData(zNear, zFar); } override protected function initialize() : void { _enabled = true; super.initialize(); } override protected function initializeSignals():void { super.initializeSignals(); _activated = new Signal('Camera.activated'); _deactivated = new Signal('Camera.deactivated'); } override protected function initializeContollers():void { super.initializeContollers(); _cameraCtrl = new CameraController(); addController(_cameraCtrl); } override protected function initializeDataProviders():void { super.initializeDataProviders(); _cameraData = _cameraCtrl.cameraData; } protected function initializeCameraData(zNear : Number, zFar : Number) : void { _cameraData.zNear = zNear; _cameraData.zFar = zFar; } public function unproject(x : Number, y : Number, out : Ray = null) : Ray { throw new Error('Must be overriden.'); } /** * Return a copy of the world to view matrix. This method is an alias on the * getWorldToLocalTransform() method. * * @param output * @return * */ public function getWorldToViewTransform(forceUpdate : Boolean = false, output : Matrix4x4 = null) : Matrix4x4 { return getWorldToLocalTransform(forceUpdate, output); } /** * Return a copy of the view to world matrix. This method is an alias on the * getLocalToWorldTransform() method. * * @param output * @return * */ public function getViewToWorldTransform(forceUpdate : Boolean = false, output : Matrix4x4 = null) : Matrix4x4 { return getLocalToWorldTransform(forceUpdate, output); } /** * Return a copy of the projection matrix. * * @param output * @return * */ public function getProjection(output : Matrix4x4) : Matrix4x4 { output ||= new Matrix4x4(); return output.copyFrom(_cameraData.projection); } } }
set AbtractCamera.getWorldToViewTransform() and AbstractCamera.getViewToWorldTransform() forceUpdate argument to be false by default
set AbtractCamera.getWorldToViewTransform() and AbstractCamera.getViewToWorldTransform() forceUpdate argument to be false by default
ActionScript
mit
aerys/minko-as3
4baafbb15250b9284055575dc4e4e423becae221
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.Effect; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.TextureLoader; import flash.net.URLRequest; import spark.layouts.BasicLayout; /** * 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 _dependencyLoaderClosure : Function = defaultDependencyLoaderClosure; 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 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 dependencyLoaderClosure():Function { return _dependencyLoaderClosure; } public function set dependencyLoaderClosure(value:Function):void { _dependencyLoaderClosure = value; } public function get loadDependencies():Boolean { return _loadDependencies; } public function set loadDependencies(value:Boolean):void { _loadDependencies = value; } public function ParserOptions(loadDependencies : Boolean = false, dependencyLoaderClosure : Function = null, mipmapTextures : Boolean = true, meshEffect : Effect = null, vertexStreamUsage : uint = 0, indexStreamUsage : uint = 0, parser : Class = null) { _loadDependencies = loadDependencies; _dependencyLoaderClosure = _dependencyLoaderClosure || _dependencyLoaderClosure; _mipmapTextures = mipmapTextures; _meshEffect = meshEffect; _vertexStreamUsage = vertexStreamUsage; _indexStreamUsage = indexStreamUsage; _parser = parser; } private function defaultDependencyLoaderClosure(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.Effect; 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 _dependencyLoaderClosure : Function = defaultDependencyLoaderClosure; 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 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 dependencyLoaderClosure():Function { return _dependencyLoaderClosure; } public function set dependencyLoaderClosure(value:Function):void { _dependencyLoaderClosure = value; } public function get loadDependencies():Boolean { return _loadDependencies; } public function set loadDependencies(value:Boolean):void { _loadDependencies = value; } public function ParserOptions(loadDependencies : Boolean = false, dependencyLoaderClosure : Function = null, mipmapTextures : Boolean = true, meshEffect : Effect = null, vertexStreamUsage : uint = 0, indexStreamUsage : uint = 0, parser : Class = null) { _loadDependencies = loadDependencies; _dependencyLoaderClosure = _dependencyLoaderClosure || _dependencyLoaderClosure; _mipmapTextures = mipmapTextures; _meshEffect = meshEffect; _vertexStreamUsage = vertexStreamUsage; _indexStreamUsage = indexStreamUsage; _parser = parser; } private function defaultDependencyLoaderClosure(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 never use import
remove never use import
ActionScript
mit
aerys/minko-as3
4a0658830bd5713332adfd3f8987edf6381327ca
WEB-INF/lps/lfc/kernel/swf9/LzInputTextSprite.as
WEB-INF/lps/lfc/kernel/swf9/LzInputTextSprite.as
/** * LzInputTextSprite.as * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ /** * @shortdesc Used for input text. * */ class LzInputTextSprite extends LzTextSprite { #passthrough (toplevel:true) { import flash.display.*; import flash.events.*; import flash.text.*; }# #passthrough { function LzInputTextSprite (newowner = null, args = null) { super(newowner); } var __handlelostFocusdel; var enabled = true; var focusable = true; var hasFocus = false; var scroll = 0; override public function __initTextProperties (args:Object) { super.__initTextProperties(args); // We do not support html in input fields. if (this.enabled) { textfield.type = TextFieldType.INPUT; } else { textfield.type = TextFieldType.DYNAMIC; } textfield.mouseEnabled = false; /* TODO [hqm 2008-01] these handlers need to be implemented via Flash native event listenters: focusIn , focusOut change -- dispatched after text input is modified textInput -- dispatched before the content is modified Do we need to use this for intercepting when we have a pattern restriction on input? */ textfield.addEventListener(Event.CHANGE , __onChanged); //textfield.addEventListener(TextEvent.TEXT_INPUT, __onTextInput); textfield.addEventListener(FocusEvent.FOCUS_IN , __gotFocus); textfield.addEventListener(FocusEvent.FOCUS_OUT, __lostFocus); this.hasFocus = false; } /** * @access private */ public function gotFocus ( ){ //Debug.write('LzInputTextSprite.__handleOnFocus'); if ( this.hasFocus ) { return; } this.select(); this.hasFocus = true; } function select ( ){ textfield.setSelection(0, textfield.text.length); } // XXXX selectionBeginIndex property function deselect ( ){ textfield.setSelection(0,0); } /** * @access private */ function gotBlur ( ){ //Debug.write('LzInputTextSprite.__handleOnBlur'); this.hasFocus = false; this.deselect(); } /** * TODO [hqm 2008-01] I have no idea whether this comment * still applies: * Register for update on every frame when the text field gets the focus. * Set the behavior of the enter key depending on whether the field is * multiline or not. * * @access private */ function __gotFocus ( event:Event ){ // scroll text fields horizontally back to start if (owner) owner.inputtextevent('onfocus'); } /** * Register to be called when the text field is modified. Convert this * into a LFC ontext event. * @access private */ function __onChanged (event:Event ){ if (owner) owner.inputtextevent('onchange', this.text); } /** * @access private * TODO [hqm 2008-01] Does we still need this workaround??? */ function __lostFocus (event:Event){ __handlelostFocus(event); //trace('lost focus', event.target); //if (this['__handlelostFocusdel'] == null) this.__handlelostFocusdel = new LzDelegate(this, "__handlelostFocus"); //lz.Idle.callOnIdle(this.__handlelostFocusdel); } /** * TODO [hqm 2008-01] Does this comment still apply? Do we still need this workaround??? * * must be called after an idle event to prevent the selection from being * cleared prematurely, e.g. before a button click. If the selection is * cleared, the button doesn't send mouse events. * @access private */ function __handlelostFocus (evt ){ if (owner == lz.Focus.getFocus()) { lz.Focus.clearFocus(); if (owner) owner.inputtextevent('onblur'); } } /** * Get the current text for this inputtext-sprite. * @protected */ override public function getText():String { return textfield.text; } /** * Retrieves the contents of the text field for use by a datapath. See * <code>LzDatapath.updateData</code> for more on this. * @access protected */ function updateData (){ return textfield.text; } /** * Sets whether user can modify input text field * @param Boolean enabled: true if the text field can be edited */ function setEnabled (enabled){ this.enabled = enabled; if (enabled) { textfield.type = 'input'; } else { textfield.type = 'dynamic'; } } /** * Set the html flag on this text view */ function setHTML (htmlp) { // TODO [hqm 2008-10] what do we do here? } override public function getTextfieldHeight ( ){ return this.textfield.height; } /** * If a mouse event occurs in an input text field, find the focused view */ static function findSelection() :LzInputText { var f:InteractiveObject = LFCApplication.stage.focus; if (f is TextField && f.parent is LzInputTextSprite) { return (f.parent as LzInputTextSprite).owner; } return null; } }# // #passthrough } // End of LzInputTextSprite
/** * LzInputTextSprite.as * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ /** * @shortdesc Used for input text. * */ class LzInputTextSprite extends LzTextSprite { #passthrough (toplevel:true) { import flash.display.*; import flash.events.*; import flash.text.*; }# #passthrough { function LzInputTextSprite (newowner = null, args = null) { super(newowner); } var __handlelostFocusdel; var enabled = true; var focusable = true; var hasFocus = false; var scroll = 0; override public function __initTextProperties (args:Object) { super.__initTextProperties(args); // We do not support html in input fields. if (this.enabled) { textfield.type = TextFieldType.INPUT; } else { textfield.type = TextFieldType.DYNAMIC; } textfield.mouseEnabled = false; /* TODO [hqm 2008-01] these handlers need to be implemented via Flash native event listenters: focusIn , focusOut change -- dispatched after text input is modified textInput -- dispatched before the content is modified Do we need to use this for intercepting when we have a pattern restriction on input? */ textfield.addEventListener(Event.CHANGE , __onChanged); //textfield.addEventListener(TextEvent.TEXT_INPUT, __onTextInput); textfield.addEventListener(FocusEvent.FOCUS_IN , __gotFocus); textfield.addEventListener(FocusEvent.FOCUS_OUT, __lostFocus); this.hasFocus = false; } /** * @access private */ public function gotFocus ( ){ //Debug.write('LzInputTextSprite.__handleOnFocus'); if ( this.hasFocus ) { return; } this.select(); this.hasFocus = true; } function select ( ){ textfield.setSelection(0, textfield.text.length); } // XXXX selectionBeginIndex property function deselect ( ){ textfield.setSelection(0,0); } /** * @access private */ function gotBlur ( ){ //Debug.write('LzInputTextSprite.__handleOnBlur'); this.hasFocus = false; this.deselect(); } /** * TODO [hqm 2008-01] I have no idea whether this comment * still applies: * Register for update on every frame when the text field gets the focus. * Set the behavior of the enter key depending on whether the field is * multiline or not. * * @access private */ function __gotFocus ( event:Event ){ // scroll text fields horizontally back to start if (owner) owner.inputtextevent('onfocus'); } /** * Register to be called when the text field is modified. Convert this * into a LFC ontext event. * @access private */ function __onChanged (event:Event ){ if (owner) owner.inputtextevent('onchange', this.text); } /** * @access private * TODO [hqm 2008-01] Does we still need this workaround??? */ function __lostFocus (event:Event){ __handlelostFocus(event); //trace('lost focus', event.target); //if (this['__handlelostFocusdel'] == null) this.__handlelostFocusdel = new LzDelegate(this, "__handlelostFocus"); //lz.Idle.callOnIdle(this.__handlelostFocusdel); } /** * TODO [hqm 2008-01] Does this comment still apply? Do we still need this workaround??? * * must be called after an idle event to prevent the selection from being * cleared prematurely, e.g. before a button click. If the selection is * cleared, the button doesn't send mouse events. * @access private */ function __handlelostFocus (evt ){ if (owner == lz.Focus.getFocus()) { lz.Focus.clearFocus(); if (owner) owner.inputtextevent('onblur'); } } /** * Get the current text for this inputtext-sprite. * @protected */ override public function getText():String { // We normalize swf's \r to \n return this.textfield.text.split('\r').join('\n'); } /** * Retrieves the contents of the text field for use by a datapath. See * <code>LzDatapath.updateData</code> for more on this. * @access protected */ function updateData (){ return textfield.text; } /** * Sets whether user can modify input text field * @param Boolean enabled: true if the text field can be edited */ function setEnabled (enabled){ this.enabled = enabled; if (enabled) { textfield.type = 'input'; } else { textfield.type = 'dynamic'; } } /** * Set the html flag on this text view */ function setHTML (htmlp) { // TODO [hqm 2008-10] what do we do here? } override public function getTextfieldHeight ( ){ return this.textfield.height; } /** * If a mouse event occurs in an input text field, find the focused view */ static function findSelection() :LzInputText { var f:InteractiveObject = LFCApplication.stage.focus; if (f is TextField && f.parent is LzInputTextSprite) { return (f.parent as LzInputTextSprite).owner; } return null; } }# // #passthrough } // End of LzInputTextSprite
Change 20081025-hqm-q by [email protected] on 2008-10-25 23:48:41 EDT in /Users/hqm/openlaszlo/trunk4/WEB-INF/lps/lfc for http://svn.openlaszlo.org/openlaszlo/trunk/WEB-INF/lps/lfc
Change 20081025-hqm-q by [email protected] on 2008-10-25 23:48:41 EDT in /Users/hqm/openlaszlo/trunk4/WEB-INF/lps/lfc for http://svn.openlaszlo.org/openlaszlo/trunk/WEB-INF/lps/lfc Summary: make swf9 treatment of newlines in inputtext match swf8 New Features: Bugs Fixed: LPP-7221, LPP-5331 Technical Reviewer: hqm QA Reviewer: (pending) Doc Reviewer: (pending) Documentation: Release Notes: Details: Tests: see test case in bug report git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@11581 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
3209bd1c2e20e5c538b7e431ced30238343a9deb
src/flash/htmlelements/VideoElement.as
src/flash/htmlelements/VideoElement.as
package htmlelements { import flash.display.Sprite; import flash.events.*; import flash.net.NetConnection; import flash.net.NetStream; import flash.media.Video; import flash.media.SoundTransform; import flash.utils.Timer; import FlashMediaElement; import HtmlMediaEvent; public class VideoElement extends Sprite implements IMediaElement { private var _currentUrl:String = ""; private var _autoplay:Boolean = true; private var _preload:String = ""; private var _isPreloading:Boolean = false; private var _connection:NetConnection; private var _stream:NetStream; private var _video:Video; private var _element:FlashMediaElement; private var _soundTransform; private var _oldVolume:Number = 1; // event values private var _duration:Number = 0; private var _framerate:Number; private var _isPaused:Boolean = true; private var _isEnded:Boolean = false; private var _volume:Number = 1; private var _isMuted:Boolean = false; private var _bytesLoaded:Number = 0; private var _bytesTotal:Number = 0; private var _bufferedTime:Number = 0; private var _bufferEmpty:Boolean = false; private var _videoWidth:Number = -1; private var _videoHeight:Number = -1; private var _timer:Timer; private var _isRTMP:Boolean = false; private var _isConnected:Boolean = false; private var _playWhenConnected:Boolean = false; private var _hasStartedPlaying:Boolean = false; private var _parentReference:Object; public function setReference(arg:Object):void { _parentReference = arg; } public function setSize(width:Number, height:Number):void { _video.width = width; _video.height = height; } public function get video():Video { return _video; } public function get videoHeight():Number { return _videoHeight; } public function get videoWidth():Number { return _videoWidth; } public function duration():Number { return _duration; } public function currentProgress():Number { if(_stream != null) { return Math.round(_stream.bytesLoaded/_stream.bytesTotal*100); } else { return 0; } } public function currentTime():Number { if (_stream != null) { return _stream.time; } else { return 0; } } // (1) load() // calls _connection.connect(); // waits for NetConnection.Connect.Success // _stream gets created public function VideoElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number) { _element = element; _autoplay = autoplay; _volume = startVolume; _preload = preload; _video = new Video(); addChild(_video); _connection = new NetConnection(); _connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); _connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); //_connection.connect(null); _timer = new Timer(timerRate); _timer.addEventListener("timer", timerHandler); } private function timerHandler(e:TimerEvent) { _bytesLoaded = _stream.bytesLoaded; _bytesTotal = _stream.bytesTotal; if (!_isPaused) sendEvent(HtmlMediaEvent.TIMEUPDATE); //trace("bytes", _bytesLoaded, _bytesTotal); if (_bytesLoaded < _bytesTotal) sendEvent(HtmlMediaEvent.PROGRESS); } // internal events private function netStatusHandler(event:NetStatusEvent):void { trace("netStatus", event.info.code); switch (event.info.code) { case "NetStream.Buffer.Empty": _bufferEmpty = true; _isEnded ? sendEvent(HtmlMediaEvent.ENDED) : null; break; case "NetStream.Buffer.Full": _bytesLoaded = _stream.bytesLoaded; _bytesTotal = _stream.bytesTotal; _bufferEmpty = false; sendEvent(HtmlMediaEvent.PROGRESS); break; case "NetConnection.Connect.Success": connectStream(); break; case "NetStream.Play.StreamNotFound": trace("Unable to locate video"); break; // STREAM case "NetStream.Play.Start": _isPaused = false; sendEvent(HtmlMediaEvent.LOADEDDATA); sendEvent(HtmlMediaEvent.CANPLAY); if (!_isPreloading) { sendEvent(HtmlMediaEvent.PLAY); sendEvent(HtmlMediaEvent.PLAYING); } _timer.start(); break; case "NetStream.Seek.Notify": sendEvent(HtmlMediaEvent.SEEKED); break; case "NetStream.Pause.Notify": _isPaused = true; sendEvent(HtmlMediaEvent.PAUSE); break; case "NetStream.Play.Stop": _isEnded = true; _isPaused = false; _timer.stop(); _bufferEmpty ? sendEvent(HtmlMediaEvent.ENDED) : null; break; } } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function asyncErrorHandler(event:AsyncErrorEvent):void { // ignore AsyncErrorEvent events. } private function onMetaDataHandler(info:Object):void { _duration = info.duration; _framerate = info.framerate; _videoWidth = info.width; _videoHeight = info.height; // set size? sendEvent(HtmlMediaEvent.LOADEDMETADATA); if (_isPreloading) { _stream.pause(); _isPaused = true; _isPreloading = false; sendEvent(HtmlMediaEvent.PROGRESS); sendEvent(HtmlMediaEvent.TIMEUPDATE); } } // interface members public function setSrc(url:String):void { if (_isConnected && _stream) { // stop and restart _stream.pause(); } _currentUrl = url; _isRTMP = !!_currentUrl.match(/^rtmp(s|t|e|te)?\:\/\//); _isConnected = false; _hasStartedPlaying = false; } public function load():void { // disconnect existing stream and connection if (_isConnected && _stream) { _stream.pause(); _stream.close(); _connection.close(); } _isConnected = false; _isPreloading = false; _isEnded = false; _bufferEmpty = false; // start new connection if (_isRTMP) { _connection.connect(_currentUrl.replace(/\/[^\/]+$/,"/")); } else { _connection.connect(null); } // in a few moments the "NetConnection.Connect.Success" event will fire // and call createConnection which finishes the "load" sequence sendEvent(HtmlMediaEvent.LOADSTART); } private function connectStream():void { trace("connectStream"); _stream = new NetStream(_connection); // explicitly set the sound since it could have come before the connection was made _soundTransform = new SoundTransform(_volume); _stream.soundTransform = _soundTransform; _stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // same event as connection _stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); var customClient:Object = new Object(); customClient.onMetaData = onMetaDataHandler; _stream.client = customClient; _video.attachNetStream(_stream); // start downloading without playing )based on preload and play() hasn't been called) // I wish flash had a load() command to make this less awkward if (_preload != "none" && !_playWhenConnected) { _isPaused = true; //stream.bufferTime = 20; _stream.play(_currentUrl, 0, 0); _stream.pause(); _isPreloading = true; //_stream.pause(); // //sendEvent(HtmlMediaEvent.PAUSE); // have to send this because the "playing" event gets sent via event handlers } _isConnected = true; if (_playWhenConnected && !_hasStartedPlaying) { play(); _playWhenConnected = false; } } public function play():void { if (!_hasStartedPlaying && !_isConnected) { _playWhenConnected = true; load(); return; } if (_hasStartedPlaying) { if (_isPaused) { _stream.resume(); _timer.start(); _isPaused = false; sendEvent(HtmlMediaEvent.PLAY); sendEvent(HtmlMediaEvent.PLAYING); } } else { if (_isRTMP) { _stream.play(_currentUrl.split("/").pop()); } else { _stream.play(_currentUrl); } _timer.start(); _isPaused = false; _hasStartedPlaying = true; // don't toss play/playing events here, because we haven't sent a // canplay / loadeddata event yet. that'll be handled in the net // event listener } } public function pause():void { if (_stream == null) return; _stream.pause(); _isPaused = true; if (_bytesLoaded == _bytesTotal) { _timer.stop(); } _isPaused = true; sendEvent(HtmlMediaEvent.PAUSE); } public function stop():void { if (_stream == null) return; _stream.close(); _isPaused = false; _timer.stop(); sendEvent(HtmlMediaEvent.STOP); } public function setCurrentTime(pos:Number):void { if (_stream == null) return; sendEvent(HtmlMediaEvent.SEEKING); _stream.seek(pos); sendEvent(HtmlMediaEvent.TIMEUPDATE); } public function setVolume(volume:Number):void { if (_stream != null) { _soundTransform = new SoundTransform(volume); _stream.soundTransform = _soundTransform; } _volume = volume; _isMuted = (_volume == 0); sendEvent(HtmlMediaEvent.VOLUMECHANGE); } public function getVolume():Number { if(_isMuted) { return 0; } else { return _volume; } } public function setMuted(muted:Boolean):void { if (_isMuted == muted) return; if (muted) { _oldVolume = (_stream == null) ? _oldVolume : _stream.soundTransform.volume; setVolume(0); } else { setVolume(_oldVolume); } _isMuted = muted; } private function sendEvent(eventName:String) { // calculate this to mimic HTML5 _bufferedTime = _bytesLoaded / _bytesTotal * _duration; // build JSON var values:String = "duration:" + _duration + ",framerate:" + _framerate + ",currentTime:" + (_stream != null ? _stream.time : 0) + ",muted:" + _isMuted + ",paused:" + _isPaused + ",ended:" + _isEnded + ",volume:" + _volume + ",src:\"" + _currentUrl + "\"" + ",bytesTotal:" + _bytesTotal + ",bufferedBytes:" + _bytesLoaded + ",bufferedTime:" + _bufferedTime + ",videoWidth:" + _videoWidth + ",videoHeight:" + _videoHeight + ""; _element.sendEvent(eventName, values); } } }
package htmlelements { import flash.display.Sprite; import flash.events.*; import flash.net.NetConnection; import flash.net.NetStream; import flash.media.Video; import flash.media.SoundTransform; import flash.utils.Timer; import FlashMediaElement; import HtmlMediaEvent; public class VideoElement extends Sprite implements IMediaElement { private var _currentUrl:String = ""; private var _autoplay:Boolean = true; private var _preload:String = ""; private var _isPreloading:Boolean = false; private var _connection:NetConnection; private var _stream:NetStream; private var _video:Video; private var _element:FlashMediaElement; private var _soundTransform; private var _oldVolume:Number = 1; // event values private var _duration:Number = 0; private var _framerate:Number; private var _isPaused:Boolean = true; private var _isEnded:Boolean = false; private var _volume:Number = 1; private var _isMuted:Boolean = false; private var _bytesLoaded:Number = 0; private var _bytesTotal:Number = 0; private var _bufferedTime:Number = 0; private var _bufferEmpty:Boolean = false; private var _videoWidth:Number = -1; private var _videoHeight:Number = -1; private var _timer:Timer; private var _isRTMP:Boolean = false; private var _isConnected:Boolean = false; private var _playWhenConnected:Boolean = false; private var _hasStartedPlaying:Boolean = false; private var _parentReference:Object; public function setReference(arg:Object):void { _parentReference = arg; } public function setSize(width:Number, height:Number):void { _video.width = width; _video.height = height; } public function get video():Video { return _video; } public function get videoHeight():Number { return _videoHeight; } public function get videoWidth():Number { return _videoWidth; } public function duration():Number { return _duration; } public function currentProgress():Number { if(_stream != null) { return Math.round(_stream.bytesLoaded/_stream.bytesTotal*100); } else { return 0; } } public function currentTime():Number { if (_stream != null) { return _stream.time; } else { return 0; } } // (1) load() // calls _connection.connect(); // waits for NetConnection.Connect.Success // _stream gets created public function VideoElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number) { _element = element; _autoplay = autoplay; _volume = startVolume; _preload = preload; _video = new Video(); addChild(_video); _connection = new NetConnection(); _connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); _connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); //_connection.connect(null); _timer = new Timer(timerRate); _timer.addEventListener("timer", timerHandler); } private function timerHandler(e:TimerEvent) { _bytesLoaded = _stream.bytesLoaded; _bytesTotal = _stream.bytesTotal; if (!_isPaused) sendEvent(HtmlMediaEvent.TIMEUPDATE); //trace("bytes", _bytesLoaded, _bytesTotal); if (_bytesLoaded < _bytesTotal) sendEvent(HtmlMediaEvent.PROGRESS); } // internal events private function netStatusHandler(event:NetStatusEvent):void { trace("netStatus", event.info.code); switch (event.info.code) { case "NetStream.Buffer.Empty": _bufferEmpty = true; _isEnded ? sendEvent(HtmlMediaEvent.ENDED) : null; break; case "NetStream.Buffer.Full": _bytesLoaded = _stream.bytesLoaded; _bytesTotal = _stream.bytesTotal; _bufferEmpty = false; sendEvent(HtmlMediaEvent.PROGRESS); break; case "NetConnection.Connect.Success": connectStream(); break; case "NetStream.Play.StreamNotFound": trace("Unable to locate video"); break; // STREAM case "NetStream.Play.Start": _isPaused = false; sendEvent(HtmlMediaEvent.LOADEDDATA); sendEvent(HtmlMediaEvent.CANPLAY); if (!_isPreloading) { sendEvent(HtmlMediaEvent.PLAY); sendEvent(HtmlMediaEvent.PLAYING); } _timer.start(); break; case "NetStream.Seek.Notify": sendEvent(HtmlMediaEvent.SEEKED); break; case "NetStream.Pause.Notify": _isPaused = true; sendEvent(HtmlMediaEvent.PAUSE); break; case "NetStream.Play.Stop": _isEnded = true; _isPaused = false; _timer.stop(); _bufferEmpty ? sendEvent(HtmlMediaEvent.ENDED) : null; break; } } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function asyncErrorHandler(event:AsyncErrorEvent):void { // ignore AsyncErrorEvent events. } private function onMetaDataHandler(info:Object):void { _duration = info.duration; _framerate = info.framerate; _videoWidth = info.width; _videoHeight = info.height; // set size? sendEvent(HtmlMediaEvent.LOADEDMETADATA); if (_isPreloading) { _stream.pause(); _isPaused = true; _isPreloading = false; sendEvent(HtmlMediaEvent.PROGRESS); sendEvent(HtmlMediaEvent.TIMEUPDATE); } } // interface members public function setSrc(url:String):void { if (_isConnected && _stream) { // stop and restart _stream.pause(); } _currentUrl = url; _isRTMP = !!_currentUrl.match(/^rtmp(s|t|e|te)?\:\/\//); _isConnected = false; _hasStartedPlaying = false; } public function load():void { // disconnect existing stream and connection if (_isConnected && _stream) { _stream.pause(); _stream.close(); _connection.close(); } _isConnected = false; _isPreloading = false; _isEnded = false; _bufferEmpty = false; // start new connection if (_isRTMP) { _connection.connect(_currentUrl.replace(/\/[^\/]+$/,"/")); } else { _connection.connect(null); } // in a few moments the "NetConnection.Connect.Success" event will fire // and call createConnection which finishes the "load" sequence sendEvent(HtmlMediaEvent.LOADSTART); } private function connectStream():void { trace("connectStream"); _stream = new NetStream(_connection); // explicitly set the sound since it could have come before the connection was made _soundTransform = new SoundTransform(_volume); _stream.soundTransform = _soundTransform; _stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // same event as connection _stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); var customClient:Object = new Object(); customClient.onMetaData = onMetaDataHandler; _stream.client = customClient; _video.attachNetStream(_stream); // start downloading without playing )based on preload and play() hasn't been called) // I wish flash had a load() command to make this less awkward if (_preload != "none" && !_playWhenConnected) { _isPaused = true; //stream.bufferTime = 20; _stream.play(_currentUrl, 0, 0); _stream.pause(); _isPreloading = true; //_stream.pause(); // //sendEvent(HtmlMediaEvent.PAUSE); // have to send this because the "playing" event gets sent via event handlers } _isConnected = true; if (_playWhenConnected && !_hasStartedPlaying) { play(); _playWhenConnected = false; } } public function play():void { if (!_hasStartedPlaying && !_isConnected) { _playWhenConnected = true; load(); return; } if (_hasStartedPlaying) { if (_isPaused) { _stream.resume(); _timer.start(); _isPaused = false; sendEvent(HtmlMediaEvent.PLAY); sendEvent(HtmlMediaEvent.PLAYING); } } else { if (_isRTMP) { _stream.play(_currentUrl.split("/").pop()); } else { _stream.play(_currentUrl); } _timer.start(); _isPaused = false; _hasStartedPlaying = true; // don't toss play/playing events here, because we haven't sent a // canplay / loadeddata event yet. that'll be handled in the net // event listener } } public function pause():void { if (_stream == null) return; _stream.pause(); _isPaused = true; if (_bytesLoaded == _bytesTotal) { _timer.stop(); } _isPaused = true; sendEvent(HtmlMediaEvent.PAUSE); } public function stop():void { if (_stream == null) return; _stream.close(); _isPaused = false; _timer.stop(); sendEvent(HtmlMediaEvent.STOP); } public function setCurrentTime(pos:Number):void { if (_stream == null) return; sendEvent(HtmlMediaEvent.SEEKING); _stream.seek(pos); sendEvent(HtmlMediaEvent.TIMEUPDATE); } public function setVolume(volume:Number):void { if (_stream != null) { _soundTransform = new SoundTransform(volume); _stream.soundTransform = _soundTransform; } _volume = volume; _isMuted = (_volume == 0); sendEvent(HtmlMediaEvent.VOLUMECHANGE); } public function getVolume():Number { if(_isMuted) { return 0; } else { return _volume; } } public function setMuted(muted:Boolean):void { if (_isMuted == muted) return; if (muted) { _oldVolume = (_stream == null) ? _oldVolume : _stream.soundTransform.volume; setVolume(0); } else { setVolume(_oldVolume); } _isMuted = muted; } private function sendEvent(eventName:String) { // calculate this to mimic HTML5 _bufferedTime = _bytesLoaded / _bytesTotal * _duration; // build JSON var values:String = "duration:" + _duration + ",framerate:" + _framerate + ",currentTime:" + (_stream != null ? _stream.time : 0) + ",muted:" + _isMuted + ",paused:" + _isPaused + ",ended:" + _isEnded + ",volume:" + _volume + ",src:\"" + _currentUrl + "\"" + ",bytesTotal:" + _bytesTotal + ",bufferedBytes:" + _bytesLoaded + ",bufferedTime:" + _bufferedTime + ",videoWidth:" + _videoWidth + ",videoHeight:" + _videoHeight + ""; _element.sendEvent(eventName, values); } } }
Normalize line endings
Normalize line endings
ActionScript
agpl-3.0
libeo/Vibeo,libeo/Vibeo,libeo/Vibeo,libeo/Vibeo
a4d0d351fa1a4b3d4850bffb69737bd1ceedf2c3
WEB-INF/lps/lfc/kernel/swf/LzInputTextSprite.as
WEB-INF/lps/lfc/kernel/swf/LzInputTextSprite.as
/** * LzInputTextSprite.as * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ /** * @shortdesc Used for input text. * */ var LzInputTextSprite = function(newowner, args) { this.__LZdepth = newowner.immediateparent.sprite.__LZsvdepth++; this.__LZsvdepth = 0; this.owner = newowner; // Copied (eep!) from LzTextSprite //inherited attributes, documented in view this.fontname = args.font; this.fontsize = args.fontsize; this.fontstyle = args.fontstyle; this.sizeToHeight = false; this.yscroll = 0; this.xscroll = 0; this.resize = false; //////////////////////////////////////////////////////////////// this.masked = true; var mc = this.makeContainerResource(); // create the textfield on container movieclip - give it a unique name var txtname = '$LzText'; mc.createTextField( txtname, 1, 0, 0, 100, 12 ); var textclip = mc[txtname]; //Debug.write('created', textclip, 'in', mc, txtname); this.__LZtextclip = textclip; // set a pointer back to this view from the TextField object textclip.__lzview = this.owner; textclip._visible = true; this.password = args.password ? true : false; textclip.password = this.password; } LzInputTextSprite.prototype = new LzTextSprite(null); /** * @access private */ LzInputTextSprite.prototype.construct = function ( parent , args ){ } LzInputTextSprite.prototype.focusable = true; LzInputTextSprite.prototype.__initTextProperties = function (args) { var textclip = this.__LZtextclip; // conditionalize this; set to false for inputtext for back compatibility with lps 2.1 textclip.html = true; textclip.selectable = args.selectable; textclip.autoSize = false; this.setMultiline( args.multiline ); //inherited attributes, documented in view this.fontname = args.font; this.fontsize = args.fontsize; this.fontstyle = args.fontstyle; this.__setFormat(); this.text = args.text; textclip.htmlText = this.format + this.text + this.closeformat; textclip.background = false; // To compute our width: // + if text is multiline: // if no width is supplied, use parent width // + if text is single line: // if no width was supplied and there's no constraint, measure the text width: // if empty text content was supplied, use DEFAULT_WIDTH //(args.width == null || args.width instanceof LzInitExpr) // NOTE: [2008-02-13 ptw] No one will fess up to understanding why // we treat the presence of a constraint on width differently than // height. if (args.width == null) { // if there's text content, measure it's width if (this.text != null && this.text.length > 0) { args.width = this.getTextWidth(); } else { // Empty string would result in a zero width view, which confuses // developers, so use something reasonable instead. args.width = this.DEFAULT_WIDTH; } } // To compute our height: // + If height is supplied, use it. // + if no height supplied: // if single line, use font line height // else get height from flash textobject.textHeight // if (args.height == null || args.height instanceof LzInitExpr) { this.sizeToHeight = true; // set autoSize to get text measured textclip.autoSize = true; textclip.htmlText = this.format + "__ypgSAMPLE__" + this.closeformat; this.height = textclip._height; textclip.htmlText = this.format + this.text + this.closeformat; if (!this.multiline) { // But turn off autosizing for single line text, now that // we got a correct line height from flash. textclip.autoSize = false; } } else { textclip._height = args.height; //this.setHeight(args.height); } // Default the scrollheight to the visible height. this.scrollheight = this.height; //@field Number maxlength: maximum number of characters allowed in this field // default: null // if (args.maxlength != null) { this.setMaxLength(args.maxlength); } //@field String pattern: regexp describing set of characters allowed in this field // Restrict the characters that can be entered to a pattern // specified by a regular expression. // // Currently only the expression [ ]* enclosing a set of // characters or character ranges, preceded by an optional "^", is // supported. // // examples: [0-9]* , [a-zA-Z0-9]*, [^0-9]* // default: null // if (args.pattern != null) { this.setPattern(args.pattern); } // We do not support html in input fields. if ('enabled' in this && this.enabled) { textclip.type = 'input'; } else { textclip.type = 'dynamic'; } this.__LZtextclip.__cacheSelection = TextField.prototype.__cacheSelection; textclip.onSetFocus = TextField.prototype.__gotFocus; textclip.onKillFocus = TextField.prototype.__lostFocus; textclip.onChanged = TextField.prototype.__onChanged; this.hasFocus = false; textclip.onScroller = this.__updatefieldsize; } /** * @access private */ LzInputTextSprite.prototype.gotFocus = function ( ){ //Debug.write('LzInputTextSprite.__handleOnFocus'); if ( this.hasFocus ) { return; } this.select(); this.hasFocus = true; } LzInputTextSprite.prototype.select = function ( ){ var sf = targetPath(this.__LZtextclip); // calling setFocus() seems to bash the scroll value, so save it var myscroll = this.__LZtextclip.scroll; if( Selection.getFocus() != sf ) { Selection.setFocus( sf ); } this.__LZtextclip.hscroll = 0; // restore the scroll value this.__LZtextclip.scroll = myscroll; this.__LZtextclip.background = false; } LzInputTextSprite.prototype.deselect = function ( ){ var sf = targetPath(this.__LZtextclip); if( Selection.getFocus() == sf ) { Selection.setFocus( null ); } } /** * @access private */ LzInputTextSprite.prototype.gotBlur = function ( ){ //Debug.write('LzInputTextSprite.__handleOnBlur'); this.hasFocus = false; this.deselect(); } /** * Register for update on every frame when the text field gets the focus. * Set the behavior of the enter key depending on whether the field is * multiline or not. * * @access private */ TextField.prototype.__gotFocus = function ( oldfocus ){ // scroll text fields horizontally back to start if (this.__lzview) this.__lzview.inputtextevent('onfocus'); } /** * Register to be called when the text field is modified. Convert this * into a LFC ontext event. * @access private */ TextField.prototype.__onChanged = function ( ){ if (this.__lzview) this.__lzview.inputtextevent('onchange', this.text); } /** * @access private */ TextField.prototype.__lostFocus = function ( ){ if (this['__handlelostFocusdel'] == null) this.__handlelostFocusdel = new LzDelegate(this, "__handlelostFocus"); LzIdle.callOnIdle(this.__handlelostFocusdel); } /** * must be called after an idle event to prevent the selection from being * cleared prematurely, e.g. before a button click. If the selection is * cleared, the button doesn't send mouse events. * @access private */ TextField.prototype.__handlelostFocus = function ( ){ //Debug.write('lostfocus', this.__lzview.hasFocus, LzFocus.lastfocus, this, LzFocus.getFocus(), this.__lzview, this.__lzview.inputtextevent); if (this.__lzview == LzFocus.getFocus()) { LzFocus.clearFocus(); if (this.__lzview) this.__lzview.inputtextevent('onblur'); } } /** * Retrieves the contents of the text field for use by a datapath. See * <code>LzDatapath.updateData</code> for more on this. * @access protected */ LzInputTextSprite.prototype.updateData = function (){ return this.__LZtextclip.text; } /** * Sets whether user can modify input text field * @param Boolean enabled: true if the text field can be edited */ LzInputTextSprite.prototype.setEnabled = function (enabled){ var mc = this.__LZtextclip; this.enabled = enabled; if (enabled) { mc.type = 'input'; } else { mc.type = 'dynamic'; } } /** * Set the html flag on this text view */ LzInputTextSprite.prototype.setHTML = function (htmlp) { this.__LZtextclip.html = htmlp; } /** * setText sets the text of the field to display * @param String t: the string to which to set the text */ LzInputTextSprite.prototype.setText = function ( t ){ // Keep in sync with LzTextSprite.setText() //Debug.write('LzInputTextSprite.setText', this, t); if (typeof(t) == 'undefined' || t == null) { t = ""; } else if (typeof(t) != "string") { t = t.toString(); } this.text = t;// this.format + t if proper measurement were working var mc = this.__LZtextclip; // these must be done in this order, to get Flash to take the HTML styling // but not to ignore CR linebreak chars that might be in the string. if (mc.html) { mc.htmlText = this.format; } mc.text = t; /* if (this.resize && (this.multiline == false)) { // single line resizable fields adjust their width to match the text this.setWidth(this.getTextWidth()); }*/ //multiline resizable fields adjust their height if (this.multiline && this.sizeToHeight) { this.setHeight(mc._height); } if (this.multiline && this.scroll == 0 ) { var scrolldel = new LzDelegate(this, "__LZforceScrollAttrs"); LzIdle.callOnIdle(scrolldel); } // Fix for lpp-5449 var l = t.length; if (this._selectionstart > l || this._selectionend > l) { this.setSelection(l); } //@event ontext: Sent whenever the text in the field changes. //this.owner.ontext.sendEvent(t); } LzInputTextSprite.prototype.getTextfieldHeight = function ( ){ return this.__LZtextclip._height } LzTextSprite.prototype.getText = function ( ){ return this.__LZtextclip.text; }
/** * LzInputTextSprite.as * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ /** * @shortdesc Used for input text. * */ var LzInputTextSprite = function(newowner, args) { this.__LZdepth = newowner.immediateparent.sprite.__LZsvdepth++; this.__LZsvdepth = 0; this.owner = newowner; // Copied (eep!) from LzTextSprite //inherited attributes, documented in view this.fontname = args.font; this.fontsize = args.fontsize; this.fontstyle = args.fontstyle; this.sizeToHeight = false; this.yscroll = 0; this.xscroll = 0; this.resize = false; //////////////////////////////////////////////////////////////// this.masked = true; var mc = this.makeContainerResource(); // create the textfield on container movieclip - give it a unique name var txtname = '$LzText'; mc.createTextField( txtname, 1, 0, 0, 100, 12 ); var textclip = mc[txtname]; //Debug.write('created', textclip, 'in', mc, txtname); this.__LZtextclip = textclip; // set a pointer back to this view from the TextField object textclip.__lzview = this.owner; textclip._visible = true; this.password = args.password ? true : false; textclip.password = this.password; } LzInputTextSprite.prototype = new LzTextSprite(null); /** * @access private */ LzInputTextSprite.prototype.construct = function ( parent , args ){ } LzInputTextSprite.prototype.focusable = true; LzInputTextSprite.prototype.__initTextProperties = function (args) { var textclip = this.__LZtextclip; // conditionalize this; set to false for inputtext for back compatibility with lps 2.1 textclip.html = true; textclip.selectable = args.selectable; textclip.autoSize = false; this.setMultiline( args.multiline ); //inherited attributes, documented in view this.fontname = args.font; this.fontsize = args.fontsize; this.fontstyle = args.fontstyle; this.__setFormat(); this.text = args.text; textclip.htmlText = this.format + this.text + this.closeformat; textclip.background = false; // To compute our width: // + if text is multiline: // if no width is supplied, use parent width // + if text is single line: // if no width was supplied and there's no constraint, measure the text width: // if empty text content was supplied, use DEFAULT_WIDTH //(args.width == null || args.width instanceof LzInitExpr) // NOTE: [2008-02-13 ptw] No one will fess up to understanding why // we treat the presence of a constraint on width differently than // height. if (args.width == null) { // if there's text content, measure it's width if (this.text != null && this.text.length > 0) { args.width = this.getTextWidth(); } else { // Empty string would result in a zero width view, which confuses // developers, so use something reasonable instead. args.width = this.DEFAULT_WIDTH; } } // To compute our height: // + If height is supplied, use it. // + if no height supplied: // if single line, use font line height // else get height from flash textobject.textHeight // if (args.height == null || args.height instanceof LzInitExpr) { this.sizeToHeight = true; // set autoSize to get text measured textclip.autoSize = true; textclip.htmlText = this.format + "__ypgSAMPLE__" + this.closeformat; this.height = textclip._height; textclip.htmlText = this.format + this.text + this.closeformat; if (!this.multiline) { // But turn off autosizing for single line text, now that // we got a correct line height from flash. textclip.autoSize = false; } } else { textclip._height = args.height; //this.setHeight(args.height); } // Default the scrollheight to the visible height. this.scrollheight = this.height; //@field Number maxlength: maximum number of characters allowed in this field // default: null // if (args.maxlength != null) { this.setMaxLength(args.maxlength); } //@field String pattern: regexp describing set of characters allowed in this field // Restrict the characters that can be entered to a pattern // specified by a regular expression. // // Currently only the expression [ ]* enclosing a set of // characters or character ranges, preceded by an optional "^", is // supported. // // examples: [0-9]* , [a-zA-Z0-9]*, [^0-9]* // default: null // if (args.pattern != null) { this.setPattern(args.pattern); } // We do not support html in input fields. if ('enabled' in this && this.enabled) { textclip.type = 'input'; } else { textclip.type = 'dynamic'; } this.__LZtextclip.__cacheSelection = TextField.prototype.__cacheSelection; textclip.onSetFocus = TextField.prototype.__gotFocus; textclip.onKillFocus = TextField.prototype.__lostFocus; textclip.onChanged = TextField.prototype.__onChanged; this.hasFocus = false; textclip.onScroller = this.__updatefieldsize; } /** * @access private */ LzInputTextSprite.prototype.gotFocus = function ( ){ //Debug.write('LzInputTextSprite.__handleOnFocus'); if ( this.hasFocus ) { return; } this.select(); this.hasFocus = true; } LzInputTextSprite.prototype.select = function ( ){ var sf = targetPath(this.__LZtextclip); // calling setFocus() bashes the scroll and hscroll values, so save them var myscroll = this.__LZtextclip.scroll; var myhscroll = this.__LZtextclip.hscroll; if( Selection.getFocus() != sf ) { Selection.setFocus( sf ); } // restore the scroll and hscroll values this.__LZtextclip.scroll = myscroll; this.__LZtextclip.hscroll = myhscroll; this.__LZtextclip.background = false; } LzInputTextSprite.prototype.deselect = function ( ){ var sf = targetPath(this.__LZtextclip); if( Selection.getFocus() == sf ) { Selection.setFocus( null ); } } /** * @access private */ LzInputTextSprite.prototype.gotBlur = function ( ){ //Debug.write('LzInputTextSprite.__handleOnBlur'); this.hasFocus = false; this.deselect(); } /** * Register for update on every frame when the text field gets the focus. * Set the behavior of the enter key depending on whether the field is * multiline or not. * * @access private */ TextField.prototype.__gotFocus = function ( oldfocus ){ // scroll text fields horizontally back to start if (this.__lzview) this.__lzview.inputtextevent('onfocus'); } /** * Register to be called when the text field is modified. Convert this * into a LFC ontext event. * @access private */ TextField.prototype.__onChanged = function ( ){ if (this.__lzview) this.__lzview.inputtextevent('onchange', this.text); } /** * @access private */ TextField.prototype.__lostFocus = function ( ){ if (this['__handlelostFocusdel'] == null) this.__handlelostFocusdel = new LzDelegate(this, "__handlelostFocus"); LzIdle.callOnIdle(this.__handlelostFocusdel); } /** * must be called after an idle event to prevent the selection from being * cleared prematurely, e.g. before a button click. If the selection is * cleared, the button doesn't send mouse events. * @access private */ TextField.prototype.__handlelostFocus = function ( ){ //Debug.write('lostfocus', this.__lzview.hasFocus, LzFocus.lastfocus, this, LzFocus.getFocus(), this.__lzview, this.__lzview.inputtextevent); if (this.__lzview == LzFocus.getFocus()) { LzFocus.clearFocus(); if (this.__lzview) this.__lzview.inputtextevent('onblur'); } } /** * Retrieves the contents of the text field for use by a datapath. See * <code>LzDatapath.updateData</code> for more on this. * @access protected */ LzInputTextSprite.prototype.updateData = function (){ return this.__LZtextclip.text; } /** * Sets whether user can modify input text field * @param Boolean enabled: true if the text field can be edited */ LzInputTextSprite.prototype.setEnabled = function (enabled){ var mc = this.__LZtextclip; this.enabled = enabled; if (enabled) { mc.type = 'input'; } else { mc.type = 'dynamic'; } } /** * Set the html flag on this text view */ LzInputTextSprite.prototype.setHTML = function (htmlp) { this.__LZtextclip.html = htmlp; } /** * setText sets the text of the field to display * @param String t: the string to which to set the text */ LzInputTextSprite.prototype.setText = function ( t ){ // Keep in sync with LzTextSprite.setText() //Debug.write('LzInputTextSprite.setText', this, t); if (typeof(t) == 'undefined' || t == null) { t = ""; } else if (typeof(t) != "string") { t = t.toString(); } this.text = t;// this.format + t if proper measurement were working var mc = this.__LZtextclip; // these must be done in this order, to get Flash to take the HTML styling // but not to ignore CR linebreak chars that might be in the string. if (mc.html) { mc.htmlText = this.format; } mc.text = t; /* if (this.resize && (this.multiline == false)) { // single line resizable fields adjust their width to match the text this.setWidth(this.getTextWidth()); }*/ //multiline resizable fields adjust their height if (this.multiline && this.sizeToHeight) { this.setHeight(mc._height); } if (this.multiline && this.scroll == 0 ) { var scrolldel = new LzDelegate(this, "__LZforceScrollAttrs"); LzIdle.callOnIdle(scrolldel); } // Fix for lpp-5449 var l = t.length; if (this._selectionstart > l || this._selectionend > l) { this.setSelection(l); } //@event ontext: Sent whenever the text in the field changes. //this.owner.ontext.sendEvent(t); } LzInputTextSprite.prototype.getTextfieldHeight = function ( ){ return this.__LZtextclip._height } LzTextSprite.prototype.getText = function ( ){ return this.__LZtextclip.text; }
Change 20080314-maxcarlson-L by maxcarlson@Roboto on 2008-03-14 12:54:25 PDT in /Users/maxcarlson/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20080314-maxcarlson-L by maxcarlson@Roboto on 2008-03-14 12:54:25 PDT in /Users/maxcarlson/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk Summary: Reset both horizontal and vertical scrolling after setFocus() New Features: Bugs Fixed: LPP-5450 - Cursor position moves when clicking on inputtext containing text longer than its width Technical Reviewer: promanik QA Reviewer: [email protected] Doc Reviewer: (pending) Documentation: Release Notes: Details: Reset scrolling after setFocus() Tests: See LPP-5450. git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@8297 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo