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
08e116ebac192c66e1b7e003f8aebdbd4dbd5437
as3/xobjas3/src/com/rpath/xobj/XObjArrayCollection.as
as3/xobjas3/src/com/rpath/xobj/XObjArrayCollection.as
/* # # Copyright (c) 2007-2011 rPath, Inc. # # All rights reserved # */ package com.rpath.xobj { import flash.utils.Dictionary; import mx.collections.ArrayCollection; public class XObjArrayCollection extends ArrayCollection implements IXObjCollection { public function XObjArrayCollection(source:Array=null, typeMap:*=null) { super(source); if (!typeMap) this.type = {}; this.type = typeMap; } // the type of objects we expect in the collection // null means unknown type. Can be a single Class // or a Dictionary of typeMap entries [xobjTransient] public function get type():* { return _type; } private var _type:*; public function set type(t:*):void { _type = t; } public function elementType():Class { return (type as Class); } public function typeMap():Dictionary { return (type as Dictionary); } public function elementTypeForElementName(name:String):Class { return XObjTypeMap.elementTypeForElementName(type, name); } public function elementTagForMember(member:*):String { return XObjTypeMap.elementTagForMember(type, member); } public function addItemIfAbsent(value:Object):Boolean { return XObjUtils.addItemIfAbsent(this, value); } public function removeItemIfPresent(object:Object):Boolean { return XObjUtils.removeItemIfPresent(this, public); } public function isElementMember(propName:String):Boolean { return XObjUtils.isElementMember(this, propName); } [xobjTransient] public function get isByReference():Boolean { return _isByReference; } private var _isByReference:Boolean; public function set isByReference(b:Boolean):void { _isByReference = b; } } }
/* # # Copyright (c) 2007-2011 rPath, Inc. # # All rights reserved # */ package com.rpath.xobj { import flash.utils.Dictionary; import mx.collections.ArrayCollection; public class XObjArrayCollection extends ArrayCollection implements IXObjCollection { public function XObjArrayCollection(source:Array=null, typeMap:*=null) { super(source); if (!typeMap) this.type = {}; this.type = typeMap; } // the type of objects we expect in the collection // null means unknown type. Can be a single Class // or a Dictionary of typeMap entries [xobjTransient] public function get type():* { return _type; } private var _type:*; public function set type(t:*):void { _type = t; } public function elementType():Class { return (type as Class); } public function typeMap():Dictionary { return (type as Dictionary); } public function elementTypeForElementName(name:String):Class { return XObjTypeMap.elementTypeForElementName(type, name); } public function elementTagForMember(member:*):String { return XObjTypeMap.elementTagForMember(type, member); } public function addItemIfAbsent(value:Object):Boolean { if (getItemIndex(value) == -1) { addItem(value); return true; } return false; } public function removeItemIfPresent(object:Object):Boolean { return XObjUtils.removeItemIfPresent(this, object); } public function isElementMember(propName:String):Boolean { return XObjUtils.isElementMember(this, propName); } [xobjTransient] public function get isByReference():Boolean { return _isByReference; } private var _isByReference:Boolean; public function set isByReference(b:Boolean):void { _isByReference = b; } } }
Fix bug in new XObjArrayCollection class
Fix bug in new XObjArrayCollection class
ActionScript
apache-2.0
sassoftware/xobj,sassoftware/xobj,sassoftware/xobj,sassoftware/xobj
dd97cba16dbc908650eac8bab1bae7efd4092703
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 _loadSkin : Boolean = false; 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 { return new ParserOptions( _loadDependencies, _dependencyLoaderClosure, _loadSkin, _mipmapTextures, _meshEffect, _vertexStreamUsage, _indexStreamUsage, _parser ); } public function ParserOptions(loadDependencies : Boolean = false, dependencyLoaderClosure : Function = null, loadSkin : Boolean = true, mipmapTextures : Boolean = true, meshEffect : Effect = null, vertexStreamUsage : uint = 0, indexStreamUsage : uint = 0, parser : Class = null) { _loadDependencies = loadDependencies; _dependencyLoaderClosure = dependencyLoaderClosure || _dependencyLoaderClosure; _loadSkin = loadSkin; _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.scene.node.mesh.Mesh; 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 _loadSkin : Boolean = false; 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 { return new ParserOptions( _loadDependencies, _dependencyLoaderClosure, _loadSkin, _mipmapTextures, _meshEffect, _vertexStreamUsage, _indexStreamUsage, _parser ); } public function ParserOptions(loadDependencies : Boolean = false, dependencyLoaderClosure : Function = null, loadSkin : Boolean = true, mipmapTextures : Boolean = true, meshEffect : Effect = null, vertexStreamUsage : uint = 0, indexStreamUsage : uint = 0, parser : Class = null) { _loadDependencies = loadDependencies; _dependencyLoaderClosure = dependencyLoaderClosure || _dependencyLoaderClosure; _loadSkin = loadSkin; _mipmapTextures = mipmapTextures; _meshEffect = meshEffect || Mesh.DEFAULT_EFFECT; _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; } } }
use Mesh.DEFAULT_EFFECT as the fallback value for ParserOptions.effect
use Mesh.DEFAULT_EFFECT as the fallback value for ParserOptions.effect
ActionScript
mit
aerys/minko-as3
d220085ead39052666e27908e52008a88e8d27c5
src/aerys/minko/scene/controller/AnimationController.as
src/aerys/minko/scene/controller/AnimationController.as
package aerys.minko.scene.controller { import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.Signal; import aerys.minko.type.animation.TimeLabel; import aerys.minko.type.animation.timeline.ITimeline; import flash.utils.getTimer; /** * The AnimationController uses timelines to animate properties of scene nodes. * * @author Jean-Marc Le Roux * */ public class AnimationController extends AbstractController { public function get currentTime():int { return _currentTime; } public function get isPlaying():Boolean { return _isPlaying; } public static var DEFAULT_TIME_FUNCTION : Function = getTimer; private var _timelines : Vector.<ITimeline> = new Vector.<ITimeline>(); private var _isPlaying : Boolean = false; private var _loopBeginTime : int = 0; private var _loopEndTime : int = 0; private var _looping : Boolean = true; private var _currentTime : int = 0; private var _totalTime : int = 0; private var _timeFunction : Function = DEFAULT_TIME_FUNCTION; private var _labels : Vector.<TimeLabel> = null; private var _lastTime : Number = 0; private var _looped : Signal = new Signal(); private var _started : Signal = new Signal(); private var _stopped : Signal = new Signal(); public function get started():Signal { return _started; } public function get stopped() : Signal { return _stopped; } public function get looped():Signal { return _looped; } public function get totalTime() : int { return _totalTime; } public function get looping() : Boolean { return _looping; } public function set looping(value : Boolean) : void { _looping = value; } public function get isPlaying():Boolean { return _isPlaying; } public function set isPlaying(value:Boolean):void { _isPlaying = value; } public function get currentTime():int { return _currentTime; } public function set currentTime(value:int):void { _currentTime = value; } public function AnimationController(timelines : Vector.<ITimeline>) { super(); _timelines = timelines; initialize(); } public function getTimeline(index : uint = 0) : ITimeline { return _timelines[index]; } private function initialize() : void { var numTimelines : uint = _timelines.length; for (var timelineId : uint = 0; timelineId < numTimelines; ++timelineId) if (_totalTime < _timelines[timelineId].duration) _totalTime = _timelines[timelineId].duration; setPlaybackWindow(0, _totalTime); gotoAndPlay(0); } public function gotoAndPlay(time : Object) : void { var timeValue : uint = getAnimationTime(time); if (timeValue < _loopBeginTime || timeValue > _loopEndTime) throw new Error('Time value is outside of playback window. To reset playback window, call resetPlaybackWindow.'); _currentTime = timeValue; _lastTime = _timeFunction != null ? _timeFunction() : getTimer(); play(); } public function gotoAndStop(time : Object) : void { var timeValue : uint = getAnimationTime(time); if (timeValue < _loopBeginTime || timeValue > _loopEndTime) throw new Error('Time value is outside of playback window. To reset playback window, call resetPlaybackWindow.'); _currentTime = timeValue; _lastTime = _timeFunction != null ? _timeFunction() : getTimer(); stop(); } public function play() : void { _isPlaying = true; _started.execute(this); } public function stop() : void { _isPlaying = false; _stopped.execute(this); } public function setPlaybackWindow(beginTime : Object = null, endTime : Object = null) : void { _loopBeginTime = beginTime != null ? getAnimationTime(beginTime) : 0; _loopEndTime = endTime != null ? getAnimationTime(endTime) : _totalTime; if (_currentTime < _loopBeginTime || _currentTime > _loopEndTime) _currentTime = _loopBeginTime; } public function resetPlaybackWindow() : void { setPlaybackWindow(); } private function getAnimationTime(time : Object) : uint { var timeValue : uint; if (time is uint || time is int || time is Number) { timeValue = uint(time); } else if (time is String) { var labelCount : uint = _labels.length; for (var labelId : uint = 0; labelId < labelCount; ++labelId) if (_labels[labelId].name == time) timeValue = _labels[labelId].time; } else { throw new Error('Invalid argument type. Must be uint or String'); } return timeValue; } override protected function updateOnTime(time : Number) : Boolean { if (_isPlaying) { if (_timeFunction != null) time = _timeFunction(); var deltaT : Number = time - _lastTime; var lastCurrentTime : Number = _currentTime; _currentTime = _loopBeginTime + (_currentTime + deltaT - _loopBeginTime) % (_loopEndTime - _loopBeginTime); if (lastCurrentTime > _currentTime) { if (_looping) _looped.execute(this); else { _currentTime = _totalTime; stop(); return true; } } } _lastTime = time; return _isPlaying; } override protected function updateTarget(target : ISceneNode) : void { var numTimelines : int = _timelines.length; var group : Group = target as Group; for (var i : int = 0; i < numTimelines; ++i) { var timeline : ITimeline = _timelines[i] as ITimeline; timeline.updateAt( _currentTime % (timeline.duration + 1), target ); } } } }
package aerys.minko.scene.controller { import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.Signal; import aerys.minko.type.animation.TimeLabel; import aerys.minko.type.animation.timeline.ITimeline; import flash.utils.getTimer; /** * The AnimationController uses timelines to animate properties of scene nodes. * * @author Jean-Marc Le Roux * */ public class AnimationController extends AbstractController { public static var DEFAULT_TIME_FUNCTION : Function = getTimer; private var _timelines : Vector.<ITimeline> = new Vector.<ITimeline>(); private var _isPlaying : Boolean = false; private var _loopBeginTime : int = 0; private var _loopEndTime : int = 0; private var _looping : Boolean = true; private var _currentTime : int = 0; private var _totalTime : int = 0; private var _timeFunction : Function = DEFAULT_TIME_FUNCTION; private var _labels : Vector.<TimeLabel> = null; private var _lastTime : Number = 0; private var _looped : Signal = new Signal(); private var _started : Signal = new Signal(); private var _stopped : Signal = new Signal(); public function get started():Signal { return _started; } public function get stopped() : Signal { return _stopped; } public function get looped():Signal { return _looped; } public function get totalTime() : int { return _totalTime; } public function get looping() : Boolean { return _looping; } public function set looping(value : Boolean) : void { _looping = value; } public function get isPlaying():Boolean { return _isPlaying; } public function set isPlaying(value:Boolean):void { _isPlaying = value; } public function get currentTime():int { return _currentTime; } public function set currentTime(value:int):void { _currentTime = value; } public function AnimationController(timelines : Vector.<ITimeline>) { super(); _timelines = timelines; initialize(); } public function getTimeline(index : uint = 0) : ITimeline { return _timelines[index]; } private function initialize() : void { var numTimelines : uint = _timelines.length; for (var timelineId : uint = 0; timelineId < numTimelines; ++timelineId) if (_totalTime < _timelines[timelineId].duration) _totalTime = _timelines[timelineId].duration; setPlaybackWindow(0, _totalTime); gotoAndPlay(0); } public function gotoAndPlay(time : Object) : void { var timeValue : uint = getAnimationTime(time); if (timeValue < _loopBeginTime || timeValue > _loopEndTime) throw new Error('Time value is outside of playback window. To reset playback window, call resetPlaybackWindow.'); _currentTime = timeValue; _lastTime = _timeFunction != null ? _timeFunction() : getTimer(); play(); } public function gotoAndStop(time : Object) : void { var timeValue : uint = getAnimationTime(time); if (timeValue < _loopBeginTime || timeValue > _loopEndTime) throw new Error('Time value is outside of playback window. To reset playback window, call resetPlaybackWindow.'); _currentTime = timeValue; _lastTime = _timeFunction != null ? _timeFunction() : getTimer(); stop(); } public function play() : void { _isPlaying = true; _started.execute(this); } public function stop() : void { _isPlaying = false; _stopped.execute(this); } public function setPlaybackWindow(beginTime : Object = null, endTime : Object = null) : void { _loopBeginTime = beginTime != null ? getAnimationTime(beginTime) : 0; _loopEndTime = endTime != null ? getAnimationTime(endTime) : _totalTime; if (_currentTime < _loopBeginTime || _currentTime > _loopEndTime) _currentTime = _loopBeginTime; } public function resetPlaybackWindow() : void { setPlaybackWindow(); } private function getAnimationTime(time : Object) : uint { var timeValue : uint; if (time is uint || time is int || time is Number) { timeValue = uint(time); } else if (time is String) { var labelCount : uint = _labels.length; for (var labelId : uint = 0; labelId < labelCount; ++labelId) if (_labels[labelId].name == time) timeValue = _labels[labelId].time; } else { throw new Error('Invalid argument type. Must be uint or String'); } return timeValue; } override protected function updateOnTime(time : Number) : Boolean { if (_isPlaying) { if (_timeFunction != null) time = _timeFunction(); var deltaT : Number = time - _lastTime; var lastCurrentTime : Number = _currentTime; _currentTime = _loopBeginTime + (_currentTime + deltaT - _loopBeginTime) % (_loopEndTime - _loopBeginTime); if (lastCurrentTime > _currentTime) { if (_looping) _looped.execute(this); else { _currentTime = _totalTime; stop(); return true; } } } _lastTime = time; return _isPlaying; } override protected function updateTarget(target : ISceneNode) : void { var numTimelines : int = _timelines.length; var group : Group = target as Group; for (var i : int = 0; i < numTimelines; ++i) { var timeline : ITimeline = _timelines[i] as ITimeline; timeline.updateAt( _currentTime % (timeline.duration + 1), target ); } } } }
Fix double getter on totalTime and isPlaying after the merge
Fix double getter on totalTime and isPlaying after the merge
ActionScript
mit
aerys/minko-as3
dbe2882453b2d7f2d7ac59812650b9005c7b97f9
Agent.as
Agent.as
package { import flash.display.Sprite; import flash.events.Event; import flash.events.DataEvent; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.events.TimerEvent; import flash.net.Socket; import flash.system.System; import flash.utils.getTimer; import flash.utils.Timer; import flash.utils.getQualifiedClassName; import flash.sampler.*; public class Agent extends Sprite { private static const HOST:String = "localhost"; private static const PORT:int = 42624; private static const PREFIX:String = "[AGENT]"; private var _host:String; private var _port:int; private var _socket:Socket; private var _connected:Boolean; private var _sampleSender:Timer; public function Agent() { trace(PREFIX, "Loaded"); _host = loaderInfo.parameters["host"] || HOST; _port = loaderInfo.parameters["port"] || PORT; _socket = new Socket(); _socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, fail); _socket.addEventListener(IOErrorEvent.IO_ERROR, fail); _socket.addEventListener(ProgressEvent.SOCKET_DATA, dataReceived); _socket.addEventListener(Event.CONNECT, connected); _socket.addEventListener(Event.CLOSE, close); connect(); } private function dataReceived(e:ProgressEvent):void { if( _socket.bytesAvailable < 2 ) { // All commands are two-bytes. return; } var command:uint = _socket.readUnsignedShort(); trace(PREFIX, "Received command", command); switch( command ) { case 0x4202: _socket.writeShort(0x4203); _socket.writeUnsignedInt(getTimer()); _socket.writeUnsignedInt(System.totalMemory); _socket.flush(); return; // case "START SAMPLING": // startSampling(); // _socket.send("OK START " + new Date().time ); // return; // // case "PAUSE SAMPLING": // pauseSampling(); // _socket.send("OK PAUSE"); // return; // // case "STOP SAMPLING": // stopSampling(); // _socket.send("OK STOP"); // return; // // case "GET SAMPLES": // var count:int = getSampleCount(); // // trace(PREFIX, "Sending", count, "samples"); // // _socket.send("SENDING SAMPLES: " + count); // // var samples:Array = [] // // for each (var s:Sample in getSamples()) { // samples.push(s); // } // // var batchSize:int = 1000; // var offset:int = 0; // // _sampleSender = new Timer(100, Math.ceil(count / batchSize) ); // _sampleSender.addEventListener(TimerEvent.TIMER, function(e:Event):void { // var toSend:int = Math.min(count, offset + batchSize); // // trace(PREFIX, "Sending", offset, "-", toSend); // // for( var i:int = offset; i < toSend; i++ ) { // _socket.send(sampleToString(samples[i])); // // if( i % 100 == 0) { // trace(PREFIX, "Sent", i, "/", toSend); // } // } // // offset += batchSize; // }); // _sampleSender.addEventListener(TimerEvent.TIMER_COMPLETE, function(e:Event):void { // trace(PREFIX, "Done sending samples"); // // _sampleSender = null; // }); // _sampleSender.start(); // // return; // // case "CLEAR SAMPLES": // clearSamples(); // // _socket.send("OK CLEARED"); // return; default: _socket.writeShort(0x4200); _socket.writeUTF("UNKNOWN COMMAND"); _socket.flush(); return; } } private function sampleToString(s:Sample):String { if( s is NewObjectSample ) { var nos:NewObjectSample = s as NewObjectSample; return "[NewObjectSample" + "\n time: " + nos.time + "\n id: " + nos.id + "\n type: " + getQualifiedClassName(nos.type) + stackToString(nos.stack) + "\n]"; } else if( s is DeleteObjectSample ) { var dos:DeleteObjectSample = s as DeleteObjectSample; return "[DeleteObjectSample" + "\n time: " + dos.time + "\n id: " + dos.id + "\n size: " + dos.size + stackToString(dos.stack) + "\n]"; } return "[Sample" + "\n time: " + s.time + stackToString(s.stack) + "\n]"; } private function stackToString(stack:Array):String { if( null == stack ) { return ""; } var separator:String = "\n "; return "\n stack: " + separator + stack.join(separator); } private function connect():void { trace(PREFIX, "Trying to connect to", _host, ":", _port); try { _socket.connect(_host, _port); } catch (e:Error) { trace(PREFIX, "Unable to connect", e); } } private function connected(e:Event):void { _connected = true; trace(PREFIX, "Connected"); var now:uint = new Date().time; var seconds:uint = now / 1000; var timer:uint = getTimer(); _socket.writeShort(0x4201); _socket.writeUnsignedInt(seconds); _socket.writeShort(now - (seconds * 1000)); _socket.writeUnsignedInt(timer); _socket.flush(); trace(PREFIX, seconds, now - (seconds * 1000), timer); } private function close(e:Event):void { _connected = false; trace(PREFIX, "Disconnected"); } private function fail(e:Event):void { trace(PREFIX, "Communication failure", e); _socket.close(); _connected = false; } } }
package { import flash.display.Sprite; import flash.events.Event; import flash.events.DataEvent; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.events.TimerEvent; import flash.net.Socket; import flash.system.System; import flash.utils.getTimer; import flash.utils.Timer; import flash.utils.getQualifiedClassName; import flash.sampler.*; public class Agent extends Sprite { private static const HOST:String = "localhost"; private static const PORT:int = 42624; private static const PREFIX:String = "[AGENT]"; private var _host:String; private var _port:int; private var _socket:Socket; private var _connected:Boolean; private var _sampleSender:Timer; public function Agent() { trace(PREFIX, "Loaded"); _host = loaderInfo.parameters["host"] || HOST; _port = loaderInfo.parameters["port"] || PORT; _socket = new Socket(); _socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, fail); _socket.addEventListener(IOErrorEvent.IO_ERROR, fail); _socket.addEventListener(ProgressEvent.SOCKET_DATA, dataReceived); _socket.addEventListener(Event.CONNECT, connected); _socket.addEventListener(Event.CLOSE, close); connect(); } private function dataReceived(e:ProgressEvent):void { if( _socket.bytesAvailable < 2 ) { // All commands are two-bytes. return; } var command:uint = _socket.readUnsignedShort(); trace(PREFIX, "Received command", command); switch( command ) { case 0x4202: _socket.writeShort(0x4203); _socket.writeUnsignedInt(getTimer()); _socket.writeUnsignedInt(System.totalMemory); _socket.flush(); return; // case "START SAMPLING": // startSampling(); // _socket.send("OK START " + new Date().time ); // return; // // case "PAUSE SAMPLING": // pauseSampling(); // _socket.send("OK PAUSE"); // return; // // case "STOP SAMPLING": // stopSampling(); // _socket.send("OK STOP"); // return; // // case "GET SAMPLES": // var count:int = getSampleCount(); // // trace(PREFIX, "Sending", count, "samples"); // // _socket.send("SENDING SAMPLES: " + count); // // var samples:Array = [] // // for each (var s:Sample in getSamples()) { // samples.push(s); // } // // var batchSize:int = 1000; // var offset:int = 0; // // _sampleSender = new Timer(100, Math.ceil(count / batchSize) ); // _sampleSender.addEventListener(TimerEvent.TIMER, function(e:Event):void { // var toSend:int = Math.min(count, offset + batchSize); // // trace(PREFIX, "Sending", offset, "-", toSend); // // for( var i:int = offset; i < toSend; i++ ) { // _socket.send(sampleToString(samples[i])); // // if( i % 100 == 0) { // trace(PREFIX, "Sent", i, "/", toSend); // } // } // // offset += batchSize; // }); // _sampleSender.addEventListener(TimerEvent.TIMER_COMPLETE, function(e:Event):void { // trace(PREFIX, "Done sending samples"); // // _sampleSender = null; // }); // _sampleSender.start(); // // return; // // case "CLEAR SAMPLES": // clearSamples(); // // _socket.send("OK CLEARED"); // return; default: _socket.writeShort(0x4200); _socket.writeUTF("UNKNOWN COMMAND"); _socket.flush(); return; } } private function sampleToString(s:Sample):String { if( s is NewObjectSample ) { var nos:NewObjectSample = s as NewObjectSample; return "[NewObjectSample" + "\n time: " + nos.time + "\n id: " + nos.id + "\n type: " + getQualifiedClassName(nos.type) + stackToString(nos.stack) + "\n]"; } else if( s is DeleteObjectSample ) { var dos:DeleteObjectSample = s as DeleteObjectSample; return "[DeleteObjectSample" + "\n time: " + dos.time + "\n id: " + dos.id + "\n size: " + dos.size + stackToString(dos.stack) + "\n]"; } return "[Sample" + "\n time: " + s.time + stackToString(s.stack) + "\n]"; } private function stackToString(stack:Array):String { if( null == stack ) { return ""; } var separator:String = "\n "; return "\n stack: " + separator + stack.join(separator); } private function connect():void { trace(PREFIX, "Trying to connect to", _host, ":", _port); try { _socket.connect(_host, _port); } catch (e:Error) { trace(PREFIX, "Unable to connect", e); } } private function connected(e:Event):void { _connected = true; trace(PREFIX, "Connected"); var now:Number = new Date().getTime(); var seconds:uint = now / 1000; var timer:uint = getTimer(); _socket.writeShort(0x4201); _socket.writeUnsignedInt(seconds); _socket.writeShort(now - (seconds * 1000)); _socket.writeUnsignedInt(timer); _socket.flush(); trace(PREFIX, now, seconds, now - (seconds * 1000), timer); } private function close(e:Event):void { _connected = false; trace(PREFIX, "Disconnected"); } private function fail(e:Event):void { trace(PREFIX, "Communication failure", e); _socket.close(); _connected = false; } } }
use getTime() since its accurate.
use getTime() since its accurate.
ActionScript
apache-2.0
osi/flash-profiler
2bbd1a4c048c55eee52d21e9af54e1e2e0aa15cb
src/org/mangui/hls/loader/AltAudioLevelLoader.as
src/org/mangui/hls/loader/AltAudioLevelLoader.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.loader { import org.mangui.hls.model.Level; import flash.utils.getTimer; import flash.utils.clearTimeout; import flash.utils.setTimeout; import flash.events.ErrorEvent; import flash.events.SecurityErrorEvent; import flash.events.IOErrorEvent; import org.mangui.hls.HLSSettings; import org.mangui.hls.constant.HLSPlayStates; import org.mangui.hls.model.AudioTrack; import org.mangui.hls.model.Fragment; import org.mangui.hls.event.HLSError; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.playlist.AltAudioTrack; import org.mangui.hls.playlist.Manifest; import flash.net.URLLoader; import org.mangui.hls.HLS; public class AltAudioLevelLoader { CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Reference to the hls framework controller. **/ private var _hls : HLS; /** Object that fetches the manifest. **/ private var _urlloader : URLLoader; /** Link to the M3U8 file. **/ private var _url : String; /** Timeout ID for reloading live playlists. **/ private var _timeoutID : uint; /** last reload manifest time **/ private var _reload_playlists_timer : uint; /** current audio level **/ private var _current_track : int; /** reference to manifest being loaded **/ private var _manifest_loading : Manifest; /** is this loader closed **/ private var _closed : Boolean = false; /* playlist retry timeout */ private var _retry_timeout : Number; private var _retry_count : int; /** Setup the loader. **/ public function AltAudioLevelLoader(hls : HLS) { _hls = hls; _hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.addEventListener(HLSEvent.AUDIO_TRACK_SWITCH, _audioTrackSwitchHandler); }; public function dispose() : void { _close(); _hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.removeEventListener(HLSEvent.AUDIO_TRACK_SWITCH, _audioTrackSwitchHandler); } /** Loading failed; return errors. **/ private function _errorHandler(event : ErrorEvent) : void { var txt : String; var code : int; if (event is SecurityErrorEvent) { code = HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR; txt = "Cannot load M3U8: crossdomain access denied:" + event.text; } else if (event is IOErrorEvent && (HLSSettings.manifestLoadMaxRetry == -1 || _retry_count < HLSSettings.manifestLoadMaxRetry)) { CONFIG::LOGGING { Log.warn("I/O Error while trying to load Playlist, retry in " + _retry_timeout + " ms"); } _timeoutID = setTimeout(_loadAudioLevelPlaylist, _retry_timeout); /* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */ _retry_timeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retry_timeout); _retry_count++; return; } else { code = HLSError.MANIFEST_LOADING_IO_ERROR; txt = "Cannot load M3U8: " + event.text; } var hlsError : HLSError = new HLSError(code, _url, txt); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); }; /** parse a playlist **/ private function _parseAudioPlaylist(string : String, url : String, level : int) : void { if (string != null && string.length != 0) { CONFIG::LOGGING { Log.debug("audio level " + level + " playlist:\n" + string); } var frags : Vector.<Fragment> = Manifest.getFragments(string, url, level); // set fragment and update sequence number range var newLevel : Level = new Level(); newLevel.updateFragments(frags); newLevel.targetduration = Manifest.getTargetDuration(string); _hls.audioTracks[_current_track].level = newLevel; } _hls.dispatchEvent(new HLSEvent(HLSEvent.AUDIO_LEVEL_LOADED, level)); _manifest_loading = null; }; /** load/reload active M3U8 playlist **/ private function _loadAudioLevelPlaylist() : void { if (_closed) { return; } _reload_playlists_timer = getTimer(); var altAudioTrack : AltAudioTrack = _hls.altAudioTracks[_hls.audioTracks[_current_track].id]; _manifest_loading = new Manifest(); _manifest_loading.loadPlaylist(altAudioTrack.url, _parseAudioPlaylist, _errorHandler, _current_track, _hls.type, HLSSettings.flushLiveURLCache); _hls.dispatchEvent(new HLSEvent(HLSEvent.AUDIO_LEVEL_LOADING, _current_track)); }; /** When audio track switch occurs, assess the need of loading audio level playlist **/ private function _audioTrackSwitchHandler(event : HLSEvent) : void { _current_track = event.audioTrack; var audioTrack : AudioTrack = _hls.audioTracks[_current_track]; if (audioTrack.source == AudioTrack.FROM_PLAYLIST) { var altAudioTrack : AltAudioTrack = _hls.altAudioTracks[audioTrack.id]; if (altAudioTrack.url && audioTrack.level == null) { CONFIG::LOGGING { Log.debug("switch to audio track " + _current_track + ", load Playlist"); } clearTimeout(_timeoutID); _timeoutID = setTimeout(_loadAudioLevelPlaylist, 0); } } }; private function _close() : void { CONFIG::LOGGING { Log.debug("cancel any audio level load in progress"); } _closed = true; clearTimeout(_timeoutID); try { _urlloader.close(); if (_manifest_loading) { _manifest_loading.close(); } } catch(e : Error) { } } /** When the framework idles out, stop reloading manifest **/ private function _stateHandler(event : HLSEvent) : void { if (event.state == HLSPlayStates.IDLE) { _close(); } }; } }
/* 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.loader { import org.mangui.hls.model.Level; import flash.utils.getTimer; import flash.utils.clearTimeout; import flash.utils.setTimeout; import flash.events.ErrorEvent; import flash.events.SecurityErrorEvent; import flash.events.IOErrorEvent; import org.mangui.hls.HLSSettings; import org.mangui.hls.constant.HLSPlayStates; import org.mangui.hls.model.AudioTrack; import org.mangui.hls.model.Fragment; import org.mangui.hls.event.HLSError; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.playlist.AltAudioTrack; import org.mangui.hls.playlist.Manifest; import flash.net.URLLoader; import org.mangui.hls.HLS; public class AltAudioLevelLoader { CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Reference to the hls framework controller. **/ private var _hls : HLS; /** Object that fetches the manifest. **/ private var _urlloader : URLLoader; /** Link to the M3U8 file. **/ private var _url : String; /** Timeout ID for reloading live playlists. **/ private var _timeoutID : uint; /** last reload manifest time **/ private var _reload_playlists_timer : uint; /** current audio level **/ private var _current_track : int; /** reference to manifest being loaded **/ private var _manifest_loading : Manifest; /** is this loader closed **/ private var _closed : Boolean = false; /* playlist retry timeout */ private var _retry_timeout : Number; private var _retry_count : int; /** Setup the loader. **/ public function AltAudioLevelLoader(hls : HLS) { _hls = hls; _hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.addEventListener(HLSEvent.AUDIO_TRACK_SWITCH, _audioTrackSwitchHandler); }; public function dispose() : void { _close(); _hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.removeEventListener(HLSEvent.AUDIO_TRACK_SWITCH, _audioTrackSwitchHandler); } /** Loading failed; return errors. **/ private function _errorHandler(event : ErrorEvent) : void { var txt : String; var code : int; if (event is SecurityErrorEvent) { code = HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR; txt = "Cannot load M3U8: crossdomain access denied:" + event.text; } else if (event is IOErrorEvent && (HLSSettings.manifestLoadMaxRetry == -1 || _retry_count < HLSSettings.manifestLoadMaxRetry)) { CONFIG::LOGGING { Log.warn("I/O Error while trying to load Playlist, retry in " + _retry_timeout + " ms"); } _timeoutID = setTimeout(_loadAudioLevelPlaylist, _retry_timeout); /* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */ _retry_timeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retry_timeout); _retry_count++; return; } else { code = HLSError.MANIFEST_LOADING_IO_ERROR; txt = "Cannot load M3U8: " + event.text; } var hlsError : HLSError = new HLSError(code, _url, txt); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); }; /** parse a playlist **/ private function _parseAudioPlaylist(string : String, url : String, level : int) : void { if (string != null && string.length != 0) { CONFIG::LOGGING { Log.debug("audio level " + level + " playlist:\n" + string); } var frags : Vector.<Fragment> = Manifest.getFragments(string, url, level); // set fragment and update sequence number range var newLevel : Level = new Level(); newLevel.updateFragments(frags); newLevel.targetduration = Manifest.getTargetDuration(string); _hls.audioTracks[_current_track].level = newLevel; } _hls.dispatchEvent(new HLSEvent(HLSEvent.AUDIO_LEVEL_LOADED, level)); _manifest_loading = null; }; /** load/reload active M3U8 playlist **/ private function _loadAudioLevelPlaylist() : void { if (_closed) { return; } _reload_playlists_timer = getTimer(); var altAudioTrack : AltAudioTrack = _hls.altAudioTracks[_hls.audioTracks[_current_track].id]; _manifest_loading = new Manifest(); _manifest_loading.loadPlaylist(altAudioTrack.url, _parseAudioPlaylist, _errorHandler, _current_track, _hls.type, HLSSettings.flushLiveURLCache); _hls.dispatchEvent(new HLSEvent(HLSEvent.AUDIO_LEVEL_LOADING, _current_track)); }; /** When audio track switch occurs, assess the need of loading audio level playlist **/ private function _audioTrackSwitchHandler(event : HLSEvent) : void { _current_track = event.audioTrack; var audioTrack : AudioTrack = _hls.audioTracks[_current_track]; if (audioTrack.source == AudioTrack.FROM_PLAYLIST) { var altAudioTrack : AltAudioTrack = _hls.altAudioTracks[audioTrack.id]; if (altAudioTrack.url && audioTrack.level == null) { CONFIG::LOGGING { Log.debug("switch to audio track " + _current_track + ", load Playlist"); } _retry_timeout = 1000; _retry_count = 0; clearTimeout(_timeoutID); _timeoutID = setTimeout(_loadAudioLevelPlaylist, 0); } } }; private function _close() : void { CONFIG::LOGGING { Log.debug("cancel any audio level load in progress"); } _closed = true; clearTimeout(_timeoutID); try { _urlloader.close(); if (_manifest_loading) { _manifest_loading.close(); } } catch(e : Error) { } } /** When the framework idles out, stop reloading manifest **/ private function _stateHandler(event : HLSEvent) : void { if (event.state == HLSPlayStates.IDLE) { _close(); } }; } }
set timeout to reload alt-audio playlists
set timeout to reload alt-audio playlists
ActionScript
mpl-2.0
jlacivita/flashls,jlacivita/flashls,clappr/flashls,codex-corp/flashls,dighan/flashls,NicolasSiver/flashls,vidible/vdb-flashls,clappr/flashls,mangui/flashls,tedconf/flashls,aevange/flashls,tedconf/flashls,dighan/flashls,Peer5/flashls,Corey600/flashls,hola/flashls,fixedmachine/flashls,mangui/flashls,NicolasSiver/flashls,JulianPena/flashls,hola/flashls,vidible/vdb-flashls,thdtjsdn/flashls,loungelogic/flashls,viktorot/flashls,codex-corp/flashls,suuhas/flashls,aevange/flashls,viktorot/flashls,Peer5/flashls,suuhas/flashls,suuhas/flashls,suuhas/flashls,Boxie5/flashls,viktorot/flashls,aevange/flashls,Boxie5/flashls,fixedmachine/flashls,neilrackett/flashls,aevange/flashls,loungelogic/flashls,Peer5/flashls,neilrackett/flashls,thdtjsdn/flashls,JulianPena/flashls,Peer5/flashls,Corey600/flashls
7206841b980f7b4399fa378d1c115d3c5bbeba6c
src/renderers/FlashCommon.as
src/renderers/FlashCommon.as
/* * Copyright 2016 Google Inc. 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 { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.BlendMode; import flash.display.Loader; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.UncaughtErrorEvent; import flash.external.ExternalInterface; import flash.geom.Matrix; import flash.geom.Matrix3D; import flash.geom.PerspectiveProjection; import flash.geom.Point; import flash.geom.Rectangle; import flash.geom.Vector3D; import flash.net.URLRequest; import flash.system.Security; import flash.utils.Dictionary; public class FlashCommon extends Sprite { private var imageLoadedCallback:String = null; public function FlashCommon() { // Install event handler for uncaught errors. loaderInfo.uncaughtErrorEvents.addEventListener( UncaughtErrorEvent.UNCAUGHT_ERROR, handleError); // Declare external interface. ExternalInterface.marshallExceptions = true ExternalInterface.addCallback('isReady', isReady); ExternalInterface.addCallback('createLayer', createLayer); ExternalInterface.addCallback('destroyLayer', destroyLayer); ExternalInterface.addCallback('loadImage', loadImage); ExternalInterface.addCallback('cancelImage', cancelImage); ExternalInterface.addCallback('unloadImage', unloadImage); ExternalInterface.addCallback('createTexture', createTexture); ExternalInterface.addCallback('destroyTexture', destroyTexture); ExternalInterface.addCallback('drawCubeTiles', drawCubeTiles); ExternalInterface.addCallback('drawFlatTiles', drawFlatTiles); var callbacksObjName:String = loaderInfo.parameters.callbacksObjName as String; imageLoadedCallback = callbacksObjName + '.imageLoaded'; Security.allowDomain("*"); if (stage) { init(); } else { addEventListener(Event.ADDED_TO_STAGE, init); } } private function handleError(event:UncaughtErrorEvent):void { var message:String; if (event.error is Error) { message = Error(event.error).message; } else if (event.error is ErrorEvent) { message = ErrorEvent(event.error).text; } else { message = event.error.toString(); } debug('ERROR: ' + message); }; private function debug(str:String):void { ExternalInterface.call('console.log', str); } public function isReady():Boolean { return true; } private function init():void { removeEventListener(Event.ADDED_TO_STAGE, init); stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.frameRate = 60; } private function convertFov(fov:Number, thisDimension:Number, otherDimension:Number):Number { return 2 * Math.atan(otherDimension * Math.tan(fov / 2) / thisDimension); } private function getLayer(id:Number):Sprite { if (id in layerMap) { return layerMap[id]; } return null; } public function createLayer(id: Number):void { if (id in layerMap) { debug('createLayer: ' + id + ' already exists'); return; } var layer:Sprite = new Sprite(); layerMap[id] = layer; layer.transform.perspectiveProjection = new PerspectiveProjection(); layer.blendMode = BlendMode.LAYER; addChild(layer); } public function destroyLayer(id:Number):void { if (!(id in layerMap)) { debug('destroyLayer: ' + id + ' does not exist'); return; } var layer:Sprite = layerMap[id]; while (layer.numChildren > 0) { layer.removeChildAt(0); } removeChild(layer); delete layerMap[id]; } public function drawCubeTiles(layerId:Number, width:Number, height:Number, left:Number, top:Number, alpha:Number, yaw:Number, pitch:Number, roll:Number, fov:Number, tiles:Array):void { var layer:Sprite = getLayer(layerId); if (!layer) { debug('drawCubeTiles: layer ' + layerId + ' does not exist'); } // Remove all current children. while (layer.numChildren > 0) { layer.removeChildAt(0); } // Set viewport. layer.x = left; layer.y = top; layer.scrollRect = new Rectangle(0, 0, width, height); // Set opacity. layer.alpha = alpha; // Set fov. // Don't really know why this needs to be done; magic number adjusted from // https://github.com/fieldOfView/CuTy/blob/master/com/fieldofview/cuty/CutyScene.as#L260 var fieldOfView:Number = convertFov(fov, 1, 500/height); layer.transform.perspectiveProjection.fieldOfView = fieldOfView * 180/Math.PI; var projectionCenter:Point = new Point(width/2, height/2); layer.transform.perspectiveProjection.projectionCenter = projectionCenter; var focalLength:Number = layer.transform.perspectiveProjection.focalLength; var viewportCenter:Vector3D = new Vector3D(width/2, height/2, 0); var focalCenter:Vector3D = new Vector3D(width/2, height/2, -focalLength); for each (var t:Object in tiles) { var texture:Sprite = textureMap[t.textureId]; if (!texture) { debug('drawCubeTiles: texture ' + t.textureId + ' does not exist'); } var m:Matrix3D = new Matrix3D(); // Set the perspective depth. m.appendTranslation(0, 0, -focalLength); // Center tile in viewport. var offsetX:Number = width/2 - t.width/2; var offsetY:Number = height/2 - t.height/2; m.appendTranslation(offsetX, offsetY, 0); // Set tile offset within cube face. var translX:Number = t.centerX * t.levelSize - t.padLeft; var translY:Number = -t.centerY * t.levelSize - t.padTop; var translZ:Number = t.levelSize / 2; m.appendTranslation(translX, translY, translZ); // Set cube face rotation. m.appendRotation(-t.rotY, Vector3D.Y_AXIS, focalCenter); m.appendRotation(t.rotX, Vector3D.X_AXIS, focalCenter); // Set camera rotation. var rotX:Number = pitch*180/Math.PI; var rotY:Number = -yaw*180/Math.PI; var rotZ:Number = -roll*180/Math.PI; m.appendRotation(rotY, Vector3D.Y_AXIS, focalCenter); m.appendRotation(rotX, Vector3D.X_AXIS, focalCenter); m.appendRotation(rotZ, Vector3D.Z_AXIS, focalCenter); texture.transform.matrix3D = m; layer.addChild(texture); } } public function drawFlatTiles(layerId:Number, width:Number, height:Number, left:Number, top:Number, alpha:Number, x:Number, y:Number, zoomX:Number, zoomY:Number, tiles:Array):void { var layer:Sprite = getLayer(layerId); if (!layer) { debug('drawFlatTiles: layer ' + layerId + ' does not exist'); } // Remove all current children. while (layer.numChildren > 0) { layer.removeChildAt(0); } // Set viewport. layer.x = left; layer.y = top; layer.scrollRect = new Rectangle(0, 0, width, height); // Set opacity. layer.alpha = alpha; // Determine the zoom factor. zoomX = width / zoomX; zoomY = height / zoomY; for each (var t:Object in tiles) { var texture:Sprite = textureMap[t.textureId]; if (!texture) { debug('drawFlatTiles: texture ' + t.textureId + ' does not exist'); } var m:Matrix3D = new Matrix3D(); // Scale tile into correct size. var scaleX:Number = zoomX / t.levelWidth; var scaleY:Number = zoomY / t.levelHeight; m.appendScale(scaleX, scaleY, 1); // Place top left corner of tile at the center of the viewport. var offsetX:Number = width/2; var offsetY:Number = height/2; m.appendTranslation(offsetX, offsetY, 0); // Move tile into its position within the image. var cornerX:Number = t.centerX - t.scaleX / 2 + 0.5; var cornerY:Number = 0.5 - t.centerY - t.scaleY / 2; var posX:Number = cornerX * zoomX; var posY:Number = cornerY * zoomY; m.appendTranslation(posX, posY, 0); // Compensate for padding around the tile. m.appendTranslation(-t.padLeft, -t.padTop, 0); // Apply view offsets. var translX:Number = -x * zoomX; var translY:Number = -y * zoomY; m.appendTranslation(translX, translY, 0); texture.transform.matrix3D = m; layer.addChild(texture); } } private var imageMap:Dictionary = new Dictionary(); private var textureMap:Dictionary = new Dictionary(); private var layerMap:Dictionary = new Dictionary(); private var nextId:Number = 1; public function loadImage(url:String, width:Number, height:Number, x:Number, y:Number):Number { var id:Number = nextId++; var loader:Loader = new Loader(); imageMap[id] = loader; // TODO: Check if there are there other kinds of errors we can catch. loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadSuccess); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError); var urlRequest:URLRequest = new URLRequest(url); loader.load(urlRequest); return id; function loadSuccess(e:Event):void { if (!imageMap[id]) { // Probably canceled before load was complete; ignore. return; } var image:Bitmap = Bitmap(loader.content); // Convert relative offset/size to absolute values. x *= image.bitmapData.width; y *= image.bitmapData.height; width *= image.bitmapData.width; height *= image.bitmapData.height; var croppedData:BitmapData = new BitmapData(width, height); croppedData.copyPixels(image.bitmapData, new Rectangle(x, y, width, height), new Point(0,0)); imageMap[id] = croppedData; ExternalInterface.call(imageLoadedCallback, false, id); } function loadError(e:IOErrorEvent):void { if (!imageMap[id]) { // Probably canceled before load was complete; ignore. return; } delete imageMap[id]; ExternalInterface.call(imageLoadedCallback, true, id); } } public function cancelImage(id:Number):void { if (!imageMap[id]) { debug('cancelImage: image ' + id + ' does not exist'); return; } unloadImage(id); } public function unloadImage(id:Number):void { var loaderOrBitmapData:Object = imageMap[id]; if (!loaderOrBitmapData) { debug('unloadImage: image ' + id + ' does not exist'); return; } if (loaderOrBitmapData is Loader) { var loader:Loader = loaderOrBitmapData as Loader; // Calling close() after the load is complete seems to cause an error, // so first check that we are still loading. if (loader.contentLoaderInfo.bytesTotal != 0 && loader.contentLoaderInfo.bytesLoaded != loader.contentLoaderInfo.bytesTotal) { loader.close(); } } delete imageMap[id]; } public function createTexture(imageId:Number, width:Number, height:Number, padTop:Number, padBottom:Number, padLeft:Number, padRight:Number):Number { var image:BitmapData = imageMap[imageId]; var i:Number; var point:Point = new Point(); var rect:Rectangle = new Rectangle(); // Create new bitmap for texture. var bitmap:BitmapData = new BitmapData(width + padLeft + padRight, height + padTop + padBottom, true, 0x00FFFFFF); // Resize source image if the texture has a different size. // TODO: it would be better to call draw() directly on the final bitmap // with both a matrix and a clippingRect parameter; this would both be // faster and allocate less memory. However, the clippingRect parameter // for the draw() method doesn't seem to work as documented. var scaled:BitmapData; if (width !== image.width || height !== image.height) { scaled = new BitmapData(width, height, true, 0x00FFFFFF); var mat:Matrix = new Matrix(width / image.width, 0, 0, height / image.height, 0, 0); scaled.draw(image, mat, null, null, null, true); } else { scaled = image; } // Draw image into texture. rect.x = 0; rect.y = 0; rect.width = width; rect.height = height; point.x = padLeft; point.y = padTop; bitmap.copyPixels(scaled, rect, point); // Draw top padding. for (i = 0; i <= padTop; i++) { rect.x = padLeft; rect.y = padTop; rect.width = width; rect.height = 1; point.x = padLeft; point.y = i; bitmap.copyPixels(bitmap, rect, point); } // Draw left padding. for (i = 0; i <= padLeft; i++) { rect.x = padLeft; rect.y = padTop; rect.width = 1; rect.height = height; point.x = i; point.y = padTop; bitmap.copyPixels(bitmap, rect, point); } // Draw bottom padding. for (i = 0; i <= padBottom; i++) { rect.x = padLeft; rect.y = padTop + height - 1; rect.width = width; rect.height = 1; point.x = padLeft; point.y = padTop + height + i; bitmap.copyPixels(bitmap, rect, point); } // Draw right padding. for (i = 0; i <= padRight; i++) { rect.x = padLeft + width - 1; rect.y = padTop; rect.width = 1; rect.height = height; point.x = padLeft + width + i; point.y = padTop; bitmap.copyPixels(bitmap, rect, point); } var texture:Sprite = new Sprite(); texture.addChild(new Bitmap(bitmap)); var textureId:Number = imageId; textureMap[textureId] = texture; return textureId; } public function destroyTexture(id:Number):void { var texture:Sprite = textureMap[id]; if (!texture) { debug('destroyTexture: texture ' + id + ' does not exist'); return; } if (texture.parent) { texture.parent.removeChild(texture); } delete textureMap[id]; } } }
/* * Copyright 2016 Google Inc. 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 { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.BlendMode; import flash.display.Loader; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.UncaughtErrorEvent; import flash.external.ExternalInterface; import flash.geom.Matrix; import flash.geom.Matrix3D; import flash.geom.PerspectiveProjection; import flash.geom.Point; import flash.geom.Rectangle; import flash.geom.Vector3D; import flash.net.URLRequest; import flash.system.LoaderContext; import flash.system.Security; import flash.utils.Dictionary; public class FlashCommon extends Sprite { private var imageLoadedCallback:String = null; public function FlashCommon() { // Install event handler for uncaught errors. loaderInfo.uncaughtErrorEvents.addEventListener( UncaughtErrorEvent.UNCAUGHT_ERROR, handleError); // Declare external interface. ExternalInterface.marshallExceptions = true ExternalInterface.addCallback('isReady', isReady); ExternalInterface.addCallback('createLayer', createLayer); ExternalInterface.addCallback('destroyLayer', destroyLayer); ExternalInterface.addCallback('loadImage', loadImage); ExternalInterface.addCallback('cancelImage', cancelImage); ExternalInterface.addCallback('unloadImage', unloadImage); ExternalInterface.addCallback('createTexture', createTexture); ExternalInterface.addCallback('destroyTexture', destroyTexture); ExternalInterface.addCallback('drawCubeTiles', drawCubeTiles); ExternalInterface.addCallback('drawFlatTiles', drawFlatTiles); var callbacksObjName:String = loaderInfo.parameters.callbacksObjName as String; imageLoadedCallback = callbacksObjName + '.imageLoaded'; Security.allowDomain("*"); if (stage) { init(); } else { addEventListener(Event.ADDED_TO_STAGE, init); } } private function handleError(event:UncaughtErrorEvent):void { var message:String; if (event.error is Error) { message = Error(event.error).message; } else if (event.error is ErrorEvent) { message = ErrorEvent(event.error).text; } else { message = event.error.toString(); } debug('ERROR: ' + message); }; private function debug(str:String):void { ExternalInterface.call('console.log', str); } public function isReady():Boolean { return true; } private function init():void { removeEventListener(Event.ADDED_TO_STAGE, init); stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.frameRate = 60; } private function convertFov(fov:Number, thisDimension:Number, otherDimension:Number):Number { return 2 * Math.atan(otherDimension * Math.tan(fov / 2) / thisDimension); } private function getLayer(id:Number):Sprite { if (id in layerMap) { return layerMap[id]; } return null; } public function createLayer(id: Number):void { if (id in layerMap) { debug('createLayer: ' + id + ' already exists'); return; } var layer:Sprite = new Sprite(); layerMap[id] = layer; layer.transform.perspectiveProjection = new PerspectiveProjection(); layer.blendMode = BlendMode.LAYER; addChild(layer); } public function destroyLayer(id:Number):void { if (!(id in layerMap)) { debug('destroyLayer: ' + id + ' does not exist'); return; } var layer:Sprite = layerMap[id]; while (layer.numChildren > 0) { layer.removeChildAt(0); } removeChild(layer); delete layerMap[id]; } public function drawCubeTiles(layerId:Number, width:Number, height:Number, left:Number, top:Number, alpha:Number, yaw:Number, pitch:Number, roll:Number, fov:Number, tiles:Array):void { var layer:Sprite = getLayer(layerId); if (!layer) { debug('drawCubeTiles: layer ' + layerId + ' does not exist'); } // Remove all current children. while (layer.numChildren > 0) { layer.removeChildAt(0); } // Set viewport. layer.x = left; layer.y = top; layer.scrollRect = new Rectangle(0, 0, width, height); // Set opacity. layer.alpha = alpha; // Set fov. // Don't really know why this needs to be done; magic number adjusted from // https://github.com/fieldOfView/CuTy/blob/master/com/fieldofview/cuty/CutyScene.as#L260 var fieldOfView:Number = convertFov(fov, 1, 500/height); layer.transform.perspectiveProjection.fieldOfView = fieldOfView * 180/Math.PI; var projectionCenter:Point = new Point(width/2, height/2); layer.transform.perspectiveProjection.projectionCenter = projectionCenter; var focalLength:Number = layer.transform.perspectiveProjection.focalLength; var viewportCenter:Vector3D = new Vector3D(width/2, height/2, 0); var focalCenter:Vector3D = new Vector3D(width/2, height/2, -focalLength); for each (var t:Object in tiles) { var texture:Sprite = textureMap[t.textureId]; if (!texture) { debug('drawCubeTiles: texture ' + t.textureId + ' does not exist'); } var m:Matrix3D = new Matrix3D(); // Set the perspective depth. m.appendTranslation(0, 0, -focalLength); // Center tile in viewport. var offsetX:Number = width/2 - t.width/2; var offsetY:Number = height/2 - t.height/2; m.appendTranslation(offsetX, offsetY, 0); // Set tile offset within cube face. var translX:Number = t.centerX * t.levelSize - t.padLeft; var translY:Number = -t.centerY * t.levelSize - t.padTop; var translZ:Number = t.levelSize / 2; m.appendTranslation(translX, translY, translZ); // Set cube face rotation. m.appendRotation(-t.rotY, Vector3D.Y_AXIS, focalCenter); m.appendRotation(t.rotX, Vector3D.X_AXIS, focalCenter); // Set camera rotation. var rotX:Number = pitch*180/Math.PI; var rotY:Number = -yaw*180/Math.PI; var rotZ:Number = -roll*180/Math.PI; m.appendRotation(rotY, Vector3D.Y_AXIS, focalCenter); m.appendRotation(rotX, Vector3D.X_AXIS, focalCenter); m.appendRotation(rotZ, Vector3D.Z_AXIS, focalCenter); texture.transform.matrix3D = m; layer.addChild(texture); } } public function drawFlatTiles(layerId:Number, width:Number, height:Number, left:Number, top:Number, alpha:Number, x:Number, y:Number, zoomX:Number, zoomY:Number, tiles:Array):void { var layer:Sprite = getLayer(layerId); if (!layer) { debug('drawFlatTiles: layer ' + layerId + ' does not exist'); } // Remove all current children. while (layer.numChildren > 0) { layer.removeChildAt(0); } // Set viewport. layer.x = left; layer.y = top; layer.scrollRect = new Rectangle(0, 0, width, height); // Set opacity. layer.alpha = alpha; // Determine the zoom factor. zoomX = width / zoomX; zoomY = height / zoomY; for each (var t:Object in tiles) { var texture:Sprite = textureMap[t.textureId]; if (!texture) { debug('drawFlatTiles: texture ' + t.textureId + ' does not exist'); } var m:Matrix3D = new Matrix3D(); // Scale tile into correct size. var scaleX:Number = zoomX / t.levelWidth; var scaleY:Number = zoomY / t.levelHeight; m.appendScale(scaleX, scaleY, 1); // Place top left corner of tile at the center of the viewport. var offsetX:Number = width/2; var offsetY:Number = height/2; m.appendTranslation(offsetX, offsetY, 0); // Move tile into its position within the image. var cornerX:Number = t.centerX - t.scaleX / 2 + 0.5; var cornerY:Number = 0.5 - t.centerY - t.scaleY / 2; var posX:Number = cornerX * zoomX; var posY:Number = cornerY * zoomY; m.appendTranslation(posX, posY, 0); // Compensate for padding around the tile. m.appendTranslation(-t.padLeft, -t.padTop, 0); // Apply view offsets. var translX:Number = -x * zoomX; var translY:Number = -y * zoomY; m.appendTranslation(translX, translY, 0); texture.transform.matrix3D = m; layer.addChild(texture); } } private var imageMap:Dictionary = new Dictionary(); private var textureMap:Dictionary = new Dictionary(); private var layerMap:Dictionary = new Dictionary(); private var nextId:Number = 1; public function loadImage(url:String, width:Number, height:Number, x:Number, y:Number):Number { var id:Number = nextId++; var loader:Loader = new Loader(); imageMap[id] = loader; loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadSuccess); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError); // Check the server policy file for cross-domain requests. var loaderContext:LoaderContext = new LoaderContext(); loaderContext.checkPolicyFile = true; var urlRequest:URLRequest = new URLRequest(url); loader.load(urlRequest, loaderContext); return id; function loadSuccess(e:Event):void { if (!imageMap[id]) { // Probably canceled before load was complete; ignore. return; } var image:Bitmap = Bitmap(loader.content); // Convert relative offset/size to absolute values. x *= image.bitmapData.width; y *= image.bitmapData.height; width *= image.bitmapData.width; height *= image.bitmapData.height; var croppedData:BitmapData = new BitmapData(width, height); croppedData.copyPixels(image.bitmapData, new Rectangle(x, y, width, height), new Point(0,0)); imageMap[id] = croppedData; ExternalInterface.call(imageLoadedCallback, false, id); } function loadError(e:IOErrorEvent):void { if (!imageMap[id]) { // Probably canceled before load was complete; ignore. return; } delete imageMap[id]; ExternalInterface.call(imageLoadedCallback, true, id); } } public function cancelImage(id:Number):void { if (!imageMap[id]) { debug('cancelImage: image ' + id + ' does not exist'); return; } unloadImage(id); } public function unloadImage(id:Number):void { var loaderOrBitmapData:Object = imageMap[id]; if (!loaderOrBitmapData) { debug('unloadImage: image ' + id + ' does not exist'); return; } if (loaderOrBitmapData is Loader) { var loader:Loader = loaderOrBitmapData as Loader; // Calling close() after the load is complete seems to cause an error, // so first check that we are still loading. if (loader.contentLoaderInfo.bytesTotal != 0 && loader.contentLoaderInfo.bytesLoaded != loader.contentLoaderInfo.bytesTotal) { loader.close(); } } delete imageMap[id]; } public function createTexture(imageId:Number, width:Number, height:Number, padTop:Number, padBottom:Number, padLeft:Number, padRight:Number):Number { var image:BitmapData = imageMap[imageId]; var i:Number; var point:Point = new Point(); var rect:Rectangle = new Rectangle(); // Create new bitmap for texture. var bitmap:BitmapData = new BitmapData(width + padLeft + padRight, height + padTop + padBottom, true, 0x00FFFFFF); // Resize source image if the texture has a different size. // TODO: it would be better to call draw() directly on the final bitmap // with both a matrix and a clippingRect parameter; this would both be // faster and allocate less memory. However, the clippingRect parameter // for the draw() method doesn't seem to work as documented. var scaled:BitmapData; if (width !== image.width || height !== image.height) { scaled = new BitmapData(width, height, true, 0x00FFFFFF); var mat:Matrix = new Matrix(width / image.width, 0, 0, height / image.height, 0, 0); scaled.draw(image, mat, null, null, null, true); } else { scaled = image; } // Draw image into texture. rect.x = 0; rect.y = 0; rect.width = width; rect.height = height; point.x = padLeft; point.y = padTop; bitmap.copyPixels(scaled, rect, point); // Draw top padding. for (i = 0; i <= padTop; i++) { rect.x = padLeft; rect.y = padTop; rect.width = width; rect.height = 1; point.x = padLeft; point.y = i; bitmap.copyPixels(bitmap, rect, point); } // Draw left padding. for (i = 0; i <= padLeft; i++) { rect.x = padLeft; rect.y = padTop; rect.width = 1; rect.height = height; point.x = i; point.y = padTop; bitmap.copyPixels(bitmap, rect, point); } // Draw bottom padding. for (i = 0; i <= padBottom; i++) { rect.x = padLeft; rect.y = padTop + height - 1; rect.width = width; rect.height = 1; point.x = padLeft; point.y = padTop + height + i; bitmap.copyPixels(bitmap, rect, point); } // Draw right padding. for (i = 0; i <= padRight; i++) { rect.x = padLeft + width - 1; rect.y = padTop; rect.width = 1; rect.height = height; point.x = padLeft + width + i; point.y = padTop; bitmap.copyPixels(bitmap, rect, point); } var texture:Sprite = new Sprite(); texture.addChild(new Bitmap(bitmap)); var textureId:Number = imageId; textureMap[textureId] = texture; return textureId; } public function destroyTexture(id:Number):void { var texture:Sprite = textureMap[id]; if (!texture) { debug('destroyTexture: texture ' + id + ' does not exist'); return; } if (texture.parent) { texture.parent.removeChild(texture); } delete textureMap[id]; } } }
Fix cross-domain image loading on Flash.
Fix cross-domain image loading on Flash. In order to programmatically access the pixels of cross-domain images, Flash requires us to pass a LoaderContext with the checkPolicyFile option set into the loader. Otherwise, cross-domain image requests made by Flash will fail with a cryptic error.
ActionScript
apache-2.0
google/marzipano,google/marzipano,google/marzipano
136af2a6b90ed75af240b3f8ab037f01a5f058a6
src/as/com/threerings/crowd/chat/data/ChatChannel.as
src/as/com/threerings/crowd/chat/data/ChatChannel.as
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2008 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.crowd.chat.data { import com.threerings.io.SimpleStreamableObject; import com.threerings.util.Comparable; import com.threerings.util.Equalable; import com.threerings.presents.dobj.DSet_Entry; /** * Represents a chat channel. */ public /*abstract*/ class ChatChannel extends SimpleStreamableObject implements Comparable, Equalable, DSet_Entry { // from interface Comparable public function compareTo (other :Object) :int { throw new Error("abstract"); } // from interface Equalable public function equals (other :Object) :Boolean { throw new Error("abstract"); } // from interface DSet_Entry public function getKey () :Object { return this; } } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2008 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.crowd.chat.data { import com.threerings.io.SimpleStreamableObject; import com.threerings.util.Comparable; import com.threerings.util.Equalable; import com.threerings.presents.dobj.DSet_Entry; /** * Represents a chat channel. */ public /*abstract*/ class ChatChannel extends SimpleStreamableObject implements Comparable, Equalable, DSet_Entry { // from interface Comparable public function compareTo (other :Object) :int { throw new Error("abstract"); } // from interface Equalable public function equals (other :Object) :Boolean { return compareTo(other) == 0; } // from interface DSet_Entry public function getKey () :Object { return this; } } }
Implement equals() with compareTo().
Implement equals() with compareTo(). git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5379 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
596ef3faa8141de70ea47aebaaacc586cb6f2c63
src/org/jivesoftware/xiff/core/XMPPBOSHConnection.as
src/org/jivesoftware/xiff/core/XMPPBOSHConnection.as
package org.jivesoftware.xiff.core { import flash.events.ErrorEvent; import flash.events.TimerEvent; import flash.utils.Timer; import flash.xml.XMLDocument; import flash.xml.XMLNode; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.http.HTTPService; import org.jivesoftware.xiff.auth.Anonymous; import org.jivesoftware.xiff.auth.External; import org.jivesoftware.xiff.auth.Plain; import org.jivesoftware.xiff.auth.SASLAuth; import org.jivesoftware.xiff.data.IQ; import org.jivesoftware.xiff.data.bind.BindExtension; import org.jivesoftware.xiff.data.session.SessionExtension; import org.jivesoftware.xiff.events.ConnectionSuccessEvent; import org.jivesoftware.xiff.events.IncomingDataEvent; import org.jivesoftware.xiff.events.LoginEvent; import org.jivesoftware.xiff.events.XIFFErrorEvent; import org.jivesoftware.xiff.util.Callback; public class XMPPBOSHConnection extends XMPPConnection { private static var saslMechanisms:Object = { "PLAIN":Plain, "ANONYMOUS":Anonymous, "EXTERNAL":External }; private var maxConcurrentRequests:uint = 2; private var boshVersion:Number = 1.6; private var headers:Object = { "post": [], "get": ['Cache-Control', 'no-store', 'Cache-Control', 'no-cache', 'Pragma', 'no-cache'] }; private var requestCount:int = 0; private var failedRequests:Array = []; private var requestQueue:Array = []; private var responseQueue:Array = []; private const responseTimer:Timer = new Timer(0.0, 1); private var isDisconnecting:Boolean = false; private var boshPollingInterval:Number = 10000; private var sid:String; private var rid:Number; private var wait:int; private var inactivity:int; private var pollTimer:Timer; private var isCurrentlyPolling:Boolean = false; private var auth:SASLAuth; private var authHandler:Function; private var https:Boolean = false; private var _port:Number = -1; private var callbacks:Object = {}; public static var logger:Object = null; public override function connect(streamType:String=null):Boolean { if(logger) logger.log("CONNECT()", "INFO"); BindExtension.enable(); active = false; loggedIn = false; var attrs:Object = { xmlns: "http://jabber.org/protocol/httpbind", hold: maxConcurrentRequests, rid: nextRID, secure: https, wait: 10, ver: boshVersion } var result:XMLNode = new XMLNode(1, "body"); result.attributes = attrs; sendRequests(result); return true; } public static function registerSASLMechanism(name:String, authClass:Class):void { saslMechanisms[name] = authClass; } public static function disableSASLMechanism(name:String):void { saslMechanisms[name] = null; } public function set secure(flag:Boolean):void { https = flag; } public override function set port(portnum:Number):void { _port = portnum; } public override function get port():Number { if(_port == -1) return https ? 8483 : 8080; return _port; } public function get httpServer():String { return (https ? "https" : "http") + "://" + server + ":" + port + "/http-bind/"; } public override function disconnect():void { super.disconnect(); pollTimer.stop(); pollTimer = null; } public function processConnectionResponse(responseBody:XMLNode):void { var attributes:Object = responseBody.attributes; sid = attributes.sid; boshPollingInterval = attributes.polling * 1000; // if we have a polling interval of 1, we want to add an extra second for a little bit of // padding. if(boshPollingInterval <= 1000 && boshPollingInterval > 0) boshPollingInterval += 1000; wait = attributes.wait; inactivity = attributes.inactivity; var serverRequests:int = attributes.requests; if (serverRequests) maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests); active = true; configureConnection(responseBody); responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse); pollTimer = new Timer(boshPollingInterval, 1); pollTimer.addEventListener(TimerEvent.TIMER, pollServer); } private function processResponse(event:TimerEvent=null):void { // Read the data and send it to the appropriate parser var currentNode:XMLNode = responseQueue.shift(); var nodeName:String = currentNode.nodeName.toLowerCase(); switch( nodeName ) { case "stream:features": //we already handled this in httpResponse() break; case "stream:error": handleStreamError( currentNode ); break; case "iq": handleIQ( currentNode ); break; case "message": handleMessage( currentNode ); break; case "presence": handlePresence( currentNode ); break; case "success": handleAuthentication( currentNode ); break; default: dispatchError( "undefined-condition", "Unknown Error", "modify", 500 ); break; } resetResponseProcessor(); } private function resetResponseProcessor():void { if(responseQueue.length > 0) { responseTimer.reset(); responseTimer.start(); } } private function httpResponse(req:XMLNode, isPollResponse:Boolean, evt:ResultEvent):void { requestCount--; var rawXML:String = evt.result as String; if(logger) logger.log(rawXML, "INCOMING"); var xmlData:XMLDocument = new XMLDocument(); xmlData.ignoreWhite = this.ignoreWhite; xmlData.parseXML( rawXML ); var bodyNode:XMLNode = xmlData.firstChild; var event:IncomingDataEvent = new IncomingDataEvent(); event.data = xmlData; dispatchEvent( event ); if(bodyNode.attributes["type"] == "terminal") { dispatchError( "BOSH Error", bodyNode.attributes["condition"], "", -1 ); active = false; } for each(var childNode:XMLNode in bodyNode.childNodes) { if(childNode.nodeName == "stream:features") { _expireTagSearch = false; processConnectionResponse( bodyNode ); } else responseQueue.push(childNode); } resetResponseProcessor(); //if we just processed a poll response, we're no longer in mid-poll if(isPollResponse) isCurrentlyPolling = false; //if we have queued requests we want to send them before attempting to poll again //otherwise, if we don't already have a countdown going for the next poll, start one if (!sendQueuedRequests() && (!pollTimer || !pollTimer.running)) resetPollTimer(); } private function httpError(req:XMLNode, isPollResponse:Boolean, evt:FaultEvent):void { active = false; dispatchError("Unknown HTTP Error", evt.fault.rootCause.text, "", -1); } protected override function sendXML(body:*):void { sendQueuedRequests(body); } private function sendQueuedRequests(body:*=null):Boolean { if(body) requestQueue.push(body); else if(requestQueue.length == 0) return false; return sendRequests(); } //returns true if any requests were sent private function sendRequests(data:XMLNode = null, isPoll:Boolean=false):Boolean { if(requestCount >= maxConcurrentRequests) return false; if(isPoll) trace("Polling at: " + new Date().getSeconds()); requestCount++; if(!data) { if(isPoll) { data = createRequest(); } else { var temp:Array = []; for(var i:uint = 0; i < 10 && requestQueue.length > 0; i++) { temp.push(requestQueue.shift()); } data = createRequest(temp); } } //build the http request var request:HTTPService = new HTTPService(); request.method = "post"; request.headers = headers[request.method]; request.url = httpServer; request.resultFormat = HTTPService.RESULT_FORMAT_TEXT; request.contentType = "text/xml"; var responseCallback:Callback = new Callback(this, httpResponse, data, isPoll); var errorCallback:Callback = new Callback(this, httpError, data, isPoll); request.addEventListener(ResultEvent.RESULT, responseCallback.call, false); request.addEventListener(FaultEvent.FAULT, errorCallback.call, false); if(logger) logger.log(data, "OUTGOING"); request.send(data); resetPollTimer(); return true; } private function resetPollTimer():void { if(!pollTimer) return; pollTimer.reset(); pollTimer.start(); } private function pollServer(evt:TimerEvent):void { //We shouldn't poll if the connection is dead, if we had requests to send instead, or if there's already one in progress if(!isActive() || sendQueuedRequests() || isCurrentlyPolling) return; //this should be safe since sendRequests checks to be sure it's not over the concurrent requests limit, and we just ensured that the queue is empty by calling sendQueuedRequests() isCurrentlyPolling = sendRequests(null, true); } private function get nextRID():Number { if(!rid) rid = Math.floor(Math.random() * 1000000); return ++rid; } private function createRequest(bodyContent:Array=null):XMLNode { var attrs:Object = { xmlns: "http://jabber.org/protocol/httpbind", rid: nextRID, sid: sid } var req:XMLNode = new XMLNode(1, "body"); if(bodyContent) for each(var content:XMLNode in bodyContent) req.appendChild(content); req.attributes = attrs; return req; } private function handleAuthentication(responseBody:XMLNode):void { // if(!response || response.length == 0) { // return; // } var status:Object = auth.handleResponse(0, responseBody); if (status.authComplete) { if (status.authSuccess) { bindConnection(); } else { dispatchEvent(new ErrorEvent(ErrorEvent.ERROR)); disconnect(); } } } private function configureConnection(responseBody:XMLNode):void { var features:XMLNode = responseBody.firstChild; var authentication:Object = {}; for each(var feature:XMLNode in features.childNodes) { if (feature.nodeName == "mechanisms") authentication.auth = configureAuthMechanisms(feature); else if (feature.nodeName == "bind") authentication.bind = true; else if (feature.nodeName == "session") authentication.session = true; } auth = authentication.auth; dispatchEvent(new ConnectionSuccessEvent()); authHandler = handleAuthentication; sendXML(auth.request); } private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth { var authMechanism:SASLAuth; var authClass:Class; for each(var mechanism:XMLNode in mechanisms.childNodes) { authClass = saslMechanisms[mechanism.firstChild.nodeValue]; if(authClass) break; } if (!authClass) { dispatchError("SASL missing", "The server is not configured to support any available SASL mechanisms", "SASL", -1); return null; } return new authClass(this); } public function handleBindResponse(packet:IQ):void { var bind:BindExtension = packet.getExtension("bind") as BindExtension; var jid:String = bind.getJID(); var parts:Array = jid.split("/"); myResource = parts[1]; parts = parts[0].split("@"); myUsername = parts[0]; domain = parts[1]; establishSession(); } private function bindConnection():void { var bindIQ:IQ = new IQ(null, "set"); var bindExt:BindExtension = new BindExtension(); if(resource) bindExt.resource = resource; bindIQ.addExtension(bindExt); //this is laaaaaame, it should be a function bindIQ.callbackName = "handleBindResponse"; bindIQ.callbackScope = this; send(bindIQ); } public function handleSessionResponse(packet:IQ):void { dispatchEvent(new LoginEvent()); } private function establishSession():void { var sessionIQ:IQ = new IQ(null, "set"); sessionIQ.addExtension(new SessionExtension()); sessionIQ.callbackName = "handleSessionResponse"; sessionIQ.callbackScope = this; send(sessionIQ); } //do nothing, we use polling instead public override function sendKeepAlive():void {} } }
package org.jivesoftware.xiff.core { import flash.events.ErrorEvent; import flash.events.TimerEvent; import flash.utils.Timer; import flash.xml.XMLDocument; import flash.xml.XMLNode; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.http.HTTPService; import org.jivesoftware.xiff.auth.Anonymous; import org.jivesoftware.xiff.auth.External; import org.jivesoftware.xiff.auth.Plain; import org.jivesoftware.xiff.auth.SASLAuth; import org.jivesoftware.xiff.data.IQ; import org.jivesoftware.xiff.data.bind.BindExtension; import org.jivesoftware.xiff.data.session.SessionExtension; import org.jivesoftware.xiff.events.ConnectionSuccessEvent; import org.jivesoftware.xiff.events.IncomingDataEvent; import org.jivesoftware.xiff.events.LoginEvent; import org.jivesoftware.xiff.events.XIFFErrorEvent; import org.jivesoftware.xiff.util.Callback; public class XMPPBOSHConnection extends XMPPConnection { private static var saslMechanisms:Object = { "PLAIN":Plain, "ANONYMOUS":Anonymous, "EXTERNAL":External }; private var maxConcurrentRequests:uint = 2; private var boshVersion:Number = 1.6; private var headers:Object = { "post": [], "get": ['Cache-Control', 'no-store', 'Cache-Control', 'no-cache', 'Pragma', 'no-cache'] }; private var requestCount:int = 0; private var failedRequests:Array = []; private var requestQueue:Array = []; private var responseQueue:Array = []; private const responseTimer:Timer = new Timer(0.0, 1); private var isDisconnecting:Boolean = false; private var boshPollingInterval:Number = 10000; private var sid:String; private var rid:Number; private var wait:int; private var inactivity:int; private var pollTimer:Timer; private var isCurrentlyPolling:Boolean = false; private var auth:SASLAuth; private var authHandler:Function; private var https:Boolean = false; private var _port:Number = -1; private var callbacks:Object = {}; public static var logger:Object = null; public override function connect(streamType:String=null):Boolean { if(logger) logger.log("CONNECT()", "INFO"); BindExtension.enable(); active = false; loggedIn = false; var attrs:Object = { xmlns: "http://jabber.org/protocol/httpbind", hold: maxConcurrentRequests, rid: nextRID, secure: https, wait: 10, ver: boshVersion } var result:XMLNode = new XMLNode(1, "body"); result.attributes = attrs; sendRequests(result); return true; } public static function registerSASLMechanism(name:String, authClass:Class):void { saslMechanisms[name] = authClass; } public static function disableSASLMechanism(name:String):void { saslMechanisms[name] = null; } public function set secure(flag:Boolean):void { https = flag; } public override function set port(portnum:Number):void { _port = portnum; } public override function get port():Number { if(_port == -1) return https ? 8483 : 8080; return _port; } public function get httpServer():String { return (https ? "https" : "http") + "://" + server + ":" + port + "/http-bind/"; } public override function disconnect():void { super.disconnect(); pollTimer.stop(); pollTimer = null; } public function processConnectionResponse(responseBody:XMLNode):void { var attributes:Object = responseBody.attributes; sid = attributes.sid; boshPollingInterval = attributes.polling * 1000; wait = attributes.wait; inactivity = attributes.inactivity * 1000; if(inactivity - 2000 >= boshPollingInterval || (boshPollingInterval <= 1000 && boshPollingInterval > 0)) { boshPollingInterval += 1000; } var serverRequests:int = attributes.requests; if (serverRequests) maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests); active = true; configureConnection(responseBody); responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse); pollTimer = new Timer(boshPollingInterval, 1); pollTimer.addEventListener(TimerEvent.TIMER, pollServer); } private function processResponse(event:TimerEvent=null):void { // Read the data and send it to the appropriate parser var currentNode:XMLNode = responseQueue.shift(); var nodeName:String = currentNode.nodeName.toLowerCase(); switch( nodeName ) { case "stream:features": //we already handled this in httpResponse() break; case "stream:error": handleStreamError( currentNode ); break; case "iq": handleIQ( currentNode ); break; case "message": handleMessage( currentNode ); break; case "presence": handlePresence( currentNode ); break; case "success": handleAuthentication( currentNode ); break; default: dispatchError( "undefined-condition", "Unknown Error", "modify", 500 ); break; } resetResponseProcessor(); } private function resetResponseProcessor():void { if(responseQueue.length > 0) { responseTimer.reset(); responseTimer.start(); } } private function httpResponse(req:XMLNode, isPollResponse:Boolean, evt:ResultEvent):void { requestCount--; var rawXML:String = evt.result as String; if(logger) logger.log(rawXML, "INCOMING"); var xmlData:XMLDocument = new XMLDocument(); xmlData.ignoreWhite = this.ignoreWhite; xmlData.parseXML( rawXML ); var bodyNode:XMLNode = xmlData.firstChild; var event:IncomingDataEvent = new IncomingDataEvent(); event.data = xmlData; dispatchEvent( event ); if(bodyNode.attributes["type"] == "terminal") { dispatchError( "BOSH Error", bodyNode.attributes["condition"], "", -1 ); active = false; } for each(var childNode:XMLNode in bodyNode.childNodes) { if(childNode.nodeName == "stream:features") { _expireTagSearch = false; processConnectionResponse( bodyNode ); } else responseQueue.push(childNode); } resetResponseProcessor(); //if we just processed a poll response, we're no longer in mid-poll if(isPollResponse) isCurrentlyPolling = false; //if we have queued requests we want to send them before attempting to poll again //otherwise, if we don't already have a countdown going for the next poll, start one if (!sendQueuedRequests() && (!pollTimer || !pollTimer.running)) resetPollTimer(); } private function httpError(req:XMLNode, isPollResponse:Boolean, evt:FaultEvent):void { active = false; dispatchError("Unknown HTTP Error", evt.fault.rootCause.text, "", -1); } protected override function sendXML(body:*):void { sendQueuedRequests(body); } private function sendQueuedRequests(body:*=null):Boolean { if(body) requestQueue.push(body); else if(requestQueue.length == 0) return false; return sendRequests(); } //returns true if any requests were sent private function sendRequests(data:XMLNode = null, isPoll:Boolean=false):Boolean { if(requestCount >= maxConcurrentRequests) return false; if(isPoll) trace("Polling at: " + new Date().getSeconds()); requestCount++; if(!data) { if(isPoll) { data = createRequest(); } else { var temp:Array = []; for(var i:uint = 0; i < 10 && requestQueue.length > 0; i++) { temp.push(requestQueue.shift()); } data = createRequest(temp); } } //build the http request var request:HTTPService = new HTTPService(); request.method = "post"; request.headers = headers[request.method]; request.url = httpServer; request.resultFormat = HTTPService.RESULT_FORMAT_TEXT; request.contentType = "text/xml"; var responseCallback:Callback = new Callback(this, httpResponse, data, isPoll); var errorCallback:Callback = new Callback(this, httpError, data, isPoll); request.addEventListener(ResultEvent.RESULT, responseCallback.call, false); request.addEventListener(FaultEvent.FAULT, errorCallback.call, false); if(logger) logger.log(data, "OUTGOING"); request.send(data); resetPollTimer(); return true; } private function resetPollTimer():void { if(!pollTimer) return; pollTimer.reset(); pollTimer.start(); } private function pollServer(evt:TimerEvent):void { //We shouldn't poll if the connection is dead, if we had requests to send instead, or if there's already one in progress if(!isActive() || sendQueuedRequests() || isCurrentlyPolling) return; //this should be safe since sendRequests checks to be sure it's not over the concurrent requests limit, and we just ensured that the queue is empty by calling sendQueuedRequests() isCurrentlyPolling = sendRequests(null, true); } private function get nextRID():Number { if(!rid) rid = Math.floor(Math.random() * 1000000); return ++rid; } private function createRequest(bodyContent:Array=null):XMLNode { var attrs:Object = { xmlns: "http://jabber.org/protocol/httpbind", rid: nextRID, sid: sid } var req:XMLNode = new XMLNode(1, "body"); if(bodyContent) for each(var content:XMLNode in bodyContent) req.appendChild(content); req.attributes = attrs; return req; } private function handleAuthentication(responseBody:XMLNode):void { // if(!response || response.length == 0) { // return; // } var status:Object = auth.handleResponse(0, responseBody); if (status.authComplete) { if (status.authSuccess) { bindConnection(); } else { dispatchEvent(new ErrorEvent(ErrorEvent.ERROR)); disconnect(); } } } private function configureConnection(responseBody:XMLNode):void { var features:XMLNode = responseBody.firstChild; var authentication:Object = {}; for each(var feature:XMLNode in features.childNodes) { if (feature.nodeName == "mechanisms") authentication.auth = configureAuthMechanisms(feature); else if (feature.nodeName == "bind") authentication.bind = true; else if (feature.nodeName == "session") authentication.session = true; } auth = authentication.auth; dispatchEvent(new ConnectionSuccessEvent()); authHandler = handleAuthentication; sendXML(auth.request); } private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth { var authMechanism:SASLAuth; var authClass:Class; for each(var mechanism:XMLNode in mechanisms.childNodes) { authClass = saslMechanisms[mechanism.firstChild.nodeValue]; if(authClass) break; } if (!authClass) { dispatchError("SASL missing", "The server is not configured to support any available SASL mechanisms", "SASL", -1); return null; } return new authClass(this); } public function handleBindResponse(packet:IQ):void { var bind:BindExtension = packet.getExtension("bind") as BindExtension; var jid:String = bind.getJID(); var parts:Array = jid.split("/"); myResource = parts[1]; parts = parts[0].split("@"); myUsername = parts[0]; domain = parts[1]; establishSession(); } private function bindConnection():void { var bindIQ:IQ = new IQ(null, "set"); var bindExt:BindExtension = new BindExtension(); if(resource) bindExt.resource = resource; bindIQ.addExtension(bindExt); //this is laaaaaame, it should be a function bindIQ.callbackName = "handleBindResponse"; bindIQ.callbackScope = this; send(bindIQ); } public function handleSessionResponse(packet:IQ):void { dispatchEvent(new LoginEvent()); } private function establishSession():void { var sessionIQ:IQ = new IQ(null, "set"); sessionIQ.addExtension(new SessionExtension()); sessionIQ.callbackName = "handleSessionResponse"; sessionIQ.callbackScope = this; send(sessionIQ); } //do nothing, we use polling instead public override function sendKeepAlive():void {} } }
Add a little padding on BOSH polling; sacrifices a tiny bit of responsiveness for some safety, HOPEFULLY fixing XIFF-31. r=Daniel
Add a little padding on BOSH polling; sacrifices a tiny bit of responsiveness for some safety, HOPEFULLY fixing XIFF-31. r=Daniel
ActionScript
apache-2.0
igniterealtime/XIFF
5d3330d548377f95434d9749c87bb8a8ace61a87
src/aerys/minko/render/geometry/stream/iterator/TriangleIterator.as
src/aerys/minko/render/geometry/stream/iterator/TriangleIterator.as
package aerys.minko.render.geometry.stream.iterator { import aerys.minko.ns.minko_stream; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.IndexStream; import flash.utils.Proxy; import flash.utils.flash_proxy; /** * TriangleIterator allow per-triangle access on VertexStream objects. * * @author Jean-Marc Le Roux * */ public final class TriangleIterator extends Proxy { use namespace minko_stream; private var _singleReference : Boolean = true; private var _offset : int = 0; private var _index : int = 0; private var _vb : IVertexStream = null; private var _ib : IndexStream = null; private var _triangle : TriangleReference = null; public function get length() : int { return _ib ? _ib.length / 3 : _vb.numVertices / 3; } public function TriangleIterator(vertexStream : IVertexStream, indexStream : IndexStream, singleReference : Boolean = true) { super(); _vb = vertexStream; _ib = indexStream; _singleReference = singleReference; } override flash_proxy function hasProperty(name : *) : Boolean { return int(name) < _ib.length / 3; } override flash_proxy function nextNameIndex(index : int) : int { index -= _offset; _offset = 0; return index < _ib.length / 3 ? index + 1 : 0; } override flash_proxy function nextName(index : int) : String { return String(index - 1); } override flash_proxy function nextValue(index : int) : * { _index = index - 1; if (!_singleReference || !_triangle) _triangle = new TriangleReference(_vb, _ib, _index); if (_singleReference) { _triangle._index = _index; _triangle.v0._index = _ib._data[int(_index * 3)]; _triangle.v1._index = _ib._data[int(_index * 3 + 1)]; _triangle.v2._index = _ib._data[int(_index * 3 + 2)]; _triangle._update = TriangleReference.UPDATE_ALL; } return _triangle; } override flash_proxy function getProperty(name : *) : * { return new TriangleReference(_vb, _ib, int(name)); } override flash_proxy function deleteProperty(name : *) : Boolean { var index : uint = uint(name); _ib.deleteTriangleByIndex(index); return true; } } }
package aerys.minko.render.geometry.stream.iterator { import aerys.minko.ns.minko_stream; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.IndexStream; import flash.utils.Proxy; import flash.utils.flash_proxy; /** * TriangleIterator allow per-triangle access on VertexStream objects. * * @author Jean-Marc Le Roux * */ public final class TriangleIterator extends Proxy { use namespace minko_stream; private var _singleReference : Boolean = true; private var _offset : int = 0; private var _index : int = 0; private var _vb : IVertexStream = null; private var _ib : IndexStream = null; private var _triangle : TriangleReference = null; public function get length() : int { return _ib ? _ib.length / 3 : _vb.numVertices / 3; } public function TriangleIterator(vertexStream : IVertexStream, indexStream : IndexStream, singleReference : Boolean = true) { super(); _vb = vertexStream; _ib = indexStream; _singleReference = singleReference; } override flash_proxy function hasProperty(name : *) : Boolean { return int(name) < _ib.length / 3; } override flash_proxy function nextNameIndex(index : int) : int { index -= _offset; _offset = 0; return index < _ib.length / 3 ? index + 1 : 0; } override flash_proxy function nextName(index : int) : String { return String(index - 1); } override flash_proxy function nextValue(index : int) : * { _index = index - 1; if (!_singleReference || !_triangle) _triangle = new TriangleReference(_vb, _ib, _index); if (_singleReference) { _triangle._index = _index; _triangle.v0._index = _ib._data[int(_index * 3)]; _triangle.v1._index = _ib._data[int(_index * 3 + 1)]; _triangle.v2._index = _ib._data[int(_index * 3 + 2)]; _triangle._update = TriangleReference.UPDATE_ALL; } return _triangle; } override flash_proxy function getProperty(name : *) : * { return new TriangleReference(_vb, _ib, int(name)); } override flash_proxy function deleteProperty(name : *) : Boolean { var index : uint = uint(name); _ib.deleteTriangle(index); return true; } } }
fix TriangleIterator to use IVertexStream.deleteTriangle()
fix TriangleIterator to use IVertexStream.deleteTriangle()
ActionScript
mit
aerys/minko-as3
e05dbacdc0756c85478527f8ce961372069f26da
src/Player.as
src/Player.as
package { import org.flixel.FlxG; import org.flixel.FlxObject; import org.flixel.FlxPoint; import org.flixel.FlxSprite; import org.flixel.FlxTimer; import org.flixel.FlxU; import org.flixel.system.FlxAnim; // Player that has more complex running and jumping abilities. // It makes use of an animation delegate and has a simple state // tracking system. It also takes into account custom offsets. // It also allows for custom camera tracking. // This class is meant to be very configurable and has many hooks. public class Player extends FlxSprite { public var currently:uint; public static const STILL:uint = 0; public static const RUNNING:uint = 1; public static const LANDING:uint = 2; public static const RISING:uint = 101; public static const FALLING:uint = 102; // Note this is not always cleared. public var nextAction:uint; public static const NO_ACTION:uint = 0; public static const JUMP:uint = 1; public static const STOP:uint = 2; public static const START:uint = 3; public var controlled:Boolean; public var animDelegate:IPlayerAnimationDelegate; public var naturalForces:FlxPoint = new FlxPoint(1000, 500); public var pVelocity:FlxPoint; public var accelFactor:Number = 0.5; public var jumpMaxVelocity:FlxPoint; public var jumpAccel:FlxPoint; public var jumpAccelDecay:FlxPoint; // This should be small. Negative creates some drag. public var jumpAccelDecayFactor:Number = -0.001; public var oDrag:FlxPoint; public var jumpMinDuration:Number = 0.2; public var jumpMaxDuration:Number = 0.5; private var jumpTimer:FlxTimer; public var tailOffset:FlxPoint; public var headOffset:FlxPoint; public var cameraFocus:FlxObject; public var updateFocus:Boolean; // Basically, 1/n traveled per tween. public var cameraSpeed:Number = 30; public function Player(X:Number=0, Y:Number=0, SimpleGraphic:Class=null) { super(X, Y, SimpleGraphic); this.finished = true; this.currently = FALLING; this.nextAction = NO_ACTION; this.controlled = true; this.pVelocity = this.velocity; this.jumpMaxVelocity = new FlxPoint(); this.jumpAccel = new FlxPoint(); this.jumpAccelDecay = new FlxPoint(); this.oDrag = new FlxPoint(); jumpTimer = new FlxTimer(); jumpTimer.stop(); this.tailOffset = new FlxPoint(); this.headOffset = new FlxPoint(); this.cameraFocus = new FlxObject(this.x, this.y, this.width, this.height); this.updateFocus = true; FlxG.watch(this, 'currently', 'Currently'); FlxG.watch(this, 'nextAction', 'Next Action'); FlxG.watch(this.velocity, 'x', 'X Velocity'); FlxG.watch(this.velocity, 'y', 'Y Velocity'); FlxG.watch(this.acceleration, 'x', 'X Accel'); FlxG.watch(this.acceleration, 'y', 'Y Accel'); } public function init():void { this.drag.x = this.naturalForces.x; this.acceleration.y = this.naturalForces.y; this.oDrag.x = this.drag.x; this.jumpAccelDecay.x = this.oDrag.x * 2; // This prevents the "being dragged into the air" feeling. this.jumpAccelDecay.y = FlxG.framerate * this.jumpMinDuration; if (this.animDelegate == null) { throw new Error('Player animation delegate is required.'); } this.animDelegate.playerIsFalling(); } // Flixel Methods // -------------- override public function update():void { if (!this.controlled) return; // Horizontal // - Revert to still. (Our acceleration updates funny.) if (!this.inMidAir()) { this.acceleration.x = 0; } // - Basically handle switching direction, and running or being still // when not in the air. Note the player still runs in midair, but run // will behave differently. if (FlxG.keys.LEFT) { if (this.facing == FlxObject.RIGHT) { this.face(FlxObject.LEFT); } run(-1); } else if (FlxG.keys.RIGHT) { if (this.facing == FlxObject.LEFT) { this.face(FlxObject.RIGHT); } run(); } else if (!this.inMidAir()) { if (this.acceleration.x == 0) { this.nextAction = (this.velocity.x == 0) ? START : STOP; } if (this.velocity.x == 0) { this.currently = STILL; } } // Vertical // - Constrain jump and decay the jump force. if (!jumpTimer.finished) { // Negative is up, positive is down. this.velocity.y = FlxU.max(this.velocity.y, this.jumpMaxVelocity.y); this.acceleration.y += (this.naturalForces.y - this.acceleration.y) / this.jumpAccelDecay.y; } // - Basically handle starting and ending of jump, and starting of // falling. The tracking of pVelocity is an extra complexity. The // possibility of hitting the ceiling during jump is another one. if ( FlxG.keys.justPressed('UP') && jumpTimer.finished && this.isTouching(FlxObject.FLOOR) ) { // Try to jump. jumpStart(); } else if (FlxG.keys.justReleased('UP')) { jumpEnd(); } else if (this.isTouching(FlxObject.UP) && this.currently == RISING) { // Start falling. this.currently = FALLING; this.pVelocity = null; } else if (this.velocity.y > 0) { if (this.currently == FALLING) { this.pVelocity = this.velocity; } else { this.currently = FALLING; } } // - Handle ending of falling. if (this.justFell()) { this.currently = LANDING; } // - Handle focus. if (this.updateFocus) { this.cameraFocus.x += (this.x - this.cameraFocus.x) / this.cameraSpeed; this.cameraFocus.y += (this.y - this.cameraFocus.y) / this.cameraSpeed; } } // Animations get updated after movement. override protected function updateAnimation():void { this.animDelegate.playerWillUpdateAnimation(); if (this.currently == STILL) { this.animDelegate.playerIsStill(); } else if (this.currently == RUNNING) { this.animDelegate.playerIsRunning(); } else if (this.currently == LANDING) { this.animDelegate.playerIsLanding(); } else if (this.currently == RISING) { this.animDelegate.playerIsRising(); } else if (this.currently == FALLING) { this.animDelegate.playerIsFalling(); } super.updateAnimation(); this.animDelegate.playerDidUpdateAnimation(); } // Update API // ---------- public function justFell():Boolean { var did:Boolean = this.justTouched(FlxObject.DOWN) && this.currently == FALLING && this.pVelocity != null; return did; } public function inMidAir():Boolean { return this.currently >= RISING; } public function face(direction:uint):void { if ( this.velocity.x != 0 && this.nextAction != STOP && this.facing != direction ) { this.nextAction = STOP; if (!this.inMidAir()) { this.animDelegate.playerWillStop(); } } else if (this.finished) { this.nextAction = START; if (!this.inMidAir()) { this.animDelegate.playerWillStart(); } if (direction == FlxObject.RIGHT) { this.offset.x = this.tailOffset.x; this.facing = FlxObject.RIGHT; } else if (direction == FlxObject.LEFT) { this.offset.x = 0; this.facing = FlxObject.LEFT; } } } public function currentAnimation():FlxAnim { return this._curAnim; } // Update Routines // --------------- private function run(direction:int=1):void { var factor:Number = this.accelFactor; if (this.inMidAir()) { factor = this.jumpAccelDecayFactor; } else if (this.currently != RUNNING) { this.currently = RUNNING; } this.acceleration.x = this.drag.x * factor * direction; } private function jumpStart():void { var jumpMaxDuration:Number = this.jumpMinDuration + FlxU.abs(this.velocity.x/this.maxVelocity.x) * (this.jumpMaxDuration-this.jumpMinDuration); this.animDelegate.playerWillJump(); this.y--; this.currently = RISING; this.acceleration.y = this.jumpAccel.y; this.acceleration.x = 0; this.drag.x = this.jumpAccelDecay.x; jumpTimer.start(jumpMaxDuration, 1, function(timer:FlxTimer):void { jumpEnd(); }); } private function jumpEnd():void { this.acceleration.y = this.naturalForces.y; this.drag.x = this.oDrag.x; jumpTimer.stop(); } } }
package { import org.flixel.FlxG; import org.flixel.FlxObject; import org.flixel.FlxPoint; import org.flixel.FlxSprite; import org.flixel.FlxTimer; import org.flixel.FlxU; import org.flixel.system.FlxAnim; // Player that has more complex running and jumping abilities. // It makes use of an animation delegate and has a simple state // tracking system. It also takes into account custom offsets. // It also allows for custom camera tracking. // This class is meant to be very configurable and has many hooks. public class Player extends FlxSprite { public var currently:uint; public static const STILL:uint = 0; public static const RUNNING:uint = 1; public static const LANDING:uint = 2; public static const RISING:uint = 101; public static const FALLING:uint = 102; // Note this is not always cleared. public var nextAction:uint; public static const NO_ACTION:uint = 0; public static const JUMP:uint = 1; public static const STOP:uint = 2; public static const START:uint = 3; public var controlled:Boolean; public var animDelegate:IPlayerAnimationDelegate; public var naturalForces:FlxPoint = new FlxPoint(1000, 500); public var pVelocity:FlxPoint; public var accelFactor:Number = 0.5; public var jumpMaxVelocity:FlxPoint; public var jumpAccel:FlxPoint; public var jumpAccelDecay:FlxPoint; // This should be small. Negative creates some drag. public var jumpAccelDecayFactor:Number = -0.001; public var oDrag:FlxPoint; public var jumpMinDuration:Number = 0.2; public var jumpMaxDuration:Number = 0.5; private var jumpTimer:FlxTimer; public var tailOffset:FlxPoint; public var headOffset:FlxPoint; public var cameraFocus:FlxObject; public var updateFocus:Boolean; // Basically, 1/n traveled per tween. public var cameraSpeed:Number = 30; public function Player(X:Number=0, Y:Number=0, SimpleGraphic:Class=null) { super(X, Y, SimpleGraphic); this.finished = true; this.currently = FALLING; this.nextAction = NO_ACTION; this.controlled = true; this.pVelocity = this.velocity; this.jumpMaxVelocity = new FlxPoint(); this.jumpAccel = new FlxPoint(); this.jumpAccelDecay = new FlxPoint(); this.oDrag = new FlxPoint(); jumpTimer = new FlxTimer(); jumpTimer.stop(); this.tailOffset = new FlxPoint(); this.headOffset = new FlxPoint(); this.cameraFocus = new FlxObject(this.x, this.y, this.width, this.height); this.updateFocus = true; FlxG.watch(this, 'currently', 'Currently'); FlxG.watch(this, 'nextAction', 'Next Action'); FlxG.watch(this.velocity, 'x', 'X Velocity'); FlxG.watch(this.velocity, 'y', 'Y Velocity'); FlxG.watch(this.acceleration, 'x', 'X Accel'); FlxG.watch(this.acceleration, 'y', 'Y Accel'); } public function init():void { this.drag.x = this.naturalForces.x; this.acceleration.y = this.naturalForces.y; this.oDrag.x = this.drag.x; this.jumpAccelDecay.x = this.oDrag.x * 2; // This prevents the "being dragged into the air" feeling. this.jumpAccelDecay.y = FlxG.framerate * this.jumpMinDuration; if (this.animDelegate == null) { throw new Error('Player animation delegate is required.'); } this.animDelegate.playerIsFalling(); } // Flixel Methods // -------------- override public function update():void { if (!this.controlled) return; // Horizontal // - Revert to still. (Our acceleration updates funny.) if (!this.inMidAir()) { this.acceleration.x = 0; } // - Basically handle switching direction, and running or being still // when not in the air. Note the player still runs in midair, but run // will behave differently. if (FlxG.keys.LEFT) { if (this.facing == FlxObject.RIGHT) { this.face(FlxObject.LEFT); } run(-1); } else if (FlxG.keys.RIGHT) { if (this.facing == FlxObject.LEFT) { this.face(FlxObject.RIGHT); } run(); } else if (!this.inMidAir()) { if (this.acceleration.x == 0) { this.nextAction = (this.velocity.x == 0) ? START : STOP; } if (this.velocity.x == 0) { this.currently = STILL; } } // Vertical // - Constrain jump and decay the jump force. if (!jumpTimer.finished) { // Negative is up, positive is down. this.velocity.y = FlxU.max(this.velocity.y, this.jumpMaxVelocity.y); this.acceleration.y += (this.naturalForces.y - this.acceleration.y) / this.jumpAccelDecay.y; } // - Basically handle starting and ending of jump, and starting of // falling. The tracking of pVelocity is an extra complexity. The // possibility of hitting the ceiling during jump is another one. if ( FlxG.keys.justPressed('UP') && jumpTimer.finished && this.isTouching(FlxObject.FLOOR) ) { // Try to jump. jumpStart(); } else if (FlxG.keys.justReleased('UP')) { jumpEnd(); } else if (this.isTouching(FlxObject.UP) && this.currently == RISING) { // Start falling. this.currently = FALLING; this.pVelocity = null; } else if (this.velocity.y > 0) { if (this.currently == FALLING) { this.pVelocity = this.velocity; } else { this.currently = FALLING; } } // - Handle ending of falling. if (this.justFell()) { this.currently = LANDING; } // - Handle focus. if (this.updateFocus) { this.cameraFocus.x += FlxU.round((this.x - this.cameraFocus.x) / this.cameraSpeed); this.cameraFocus.y += FlxU.round((this.y - this.cameraFocus.y) / this.cameraSpeed); } } // Animations get updated after movement. override protected function updateAnimation():void { this.animDelegate.playerWillUpdateAnimation(); if (this.currently == STILL) { this.animDelegate.playerIsStill(); } else if (this.currently == RUNNING) { this.animDelegate.playerIsRunning(); } else if (this.currently == LANDING) { this.animDelegate.playerIsLanding(); } else if (this.currently == RISING) { this.animDelegate.playerIsRising(); } else if (this.currently == FALLING) { this.animDelegate.playerIsFalling(); } super.updateAnimation(); this.animDelegate.playerDidUpdateAnimation(); } // Update API // ---------- public function justFell():Boolean { var did:Boolean = this.justTouched(FlxObject.DOWN) && this.currently == FALLING && this.pVelocity != null; return did; } public function inMidAir():Boolean { return this.currently >= RISING; } public function face(direction:uint):void { if ( this.velocity.x != 0 && this.nextAction != STOP && this.facing != direction ) { this.nextAction = STOP; if (!this.inMidAir()) { this.animDelegate.playerWillStop(); } } else if (this.finished) { this.nextAction = START; if (!this.inMidAir()) { this.animDelegate.playerWillStart(); } if (direction == FlxObject.RIGHT) { this.offset.x = this.tailOffset.x; this.facing = FlxObject.RIGHT; } else if (direction == FlxObject.LEFT) { this.offset.x = 0; this.facing = FlxObject.LEFT; } } } public function currentAnimation():FlxAnim { return this._curAnim; } // Update Routines // --------------- private function run(direction:int=1):void { var factor:Number = this.accelFactor; if (this.inMidAir()) { factor = this.jumpAccelDecayFactor; } else if (this.currently != RUNNING) { this.currently = RUNNING; } this.acceleration.x = this.drag.x * factor * direction; } private function jumpStart():void { var jumpMaxDuration:Number = this.jumpMinDuration + FlxU.abs(this.velocity.x/this.maxVelocity.x) * (this.jumpMaxDuration-this.jumpMinDuration); this.animDelegate.playerWillJump(); this.y--; this.currently = RISING; this.acceleration.y = this.jumpAccel.y; this.acceleration.x = 0; this.drag.x = this.jumpAccelDecay.x; jumpTimer.start(jumpMaxDuration, 1, function(timer:FlxTimer):void { jumpEnd(); }); } private function jumpEnd():void { this.acceleration.y = this.naturalForces.y; this.drag.x = this.oDrag.x; jumpTimer.stop(); } } }
Fix bug with camera follow stopping glitchiness.
Fix bug with camera follow stopping glitchiness.
ActionScript
artistic-2.0
hlfcoding/morning-stroll
1995eae20cc7bd93a7d4c3c2d6e74497a7513527
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.text.TextField; import flash.text.TextFormat; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; import flash.utils.setTimeout; public class swfcat extends Sprite { /* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a crossdomain policy. */ private const DEFAULT_TOR_ADDR:Object = { host: "173.255.221.44", port: 9001 }; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "173.255.221.44", port: 9002 }; private const MAX_NUM_PROXY_PAIRS:uint = 1; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; // Socket to facilitator. private var s_f:Socket; /* TextField for debug output. */ private var output_text:TextField; private var fac_addr:Object; /* Number of proxy pairs currently connected (up to MAX_NUM_PROXY_PAIRS). */ private var num_proxy_pairs:int = 0; /* Number of proxy pairs ever connected. */ private var total_proxy_pairs:int = 0; /* Badge with a client counter */ [Embed(source="badge_con_counter.png")] private var BadgeImage:Class; private var client_count_tf:TextField; private var client_count_fmt:TextFormat; public function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function update_client_count():void { if (String(total_proxy_pairs).length == 1) client_count_tf.text = "0" + String(total_proxy_pairs); else client_count_tf.text = String(total_proxy_pairs); } public function swfcat() { // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; /* Setup client counter for badge. */ client_count_fmt = new TextFormat(); client_count_fmt.color = 0xFFFFFF; client_count_fmt.align = "center"; client_count_fmt.font = "courier-new"; client_count_fmt.bold = true; client_count_fmt.size = 10; client_count_tf = new TextField(); client_count_tf.width = 20; client_count_tf.height = 17; client_count_tf.background = false; client_count_tf.defaultTextFormat = client_count_fmt; client_count_tf.x=47; client_count_tf.y=3; /* Update the client counter on badge. */ update_client_count(); puts("Starting."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String; puts("Parameters loaded."); if (this.loaderInfo.parameters["debug"]) addChild(output_text); else { addChild(new BadgeImage()); /* Tried unsuccessfully to add counter to badge. */ /* For now, need two addChilds :( */ addChild(client_count_tf); } fac_spec = this.loaderInfo.parameters["facilitator"]; if (fac_spec) { puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = parse_addr_spec(fac_spec); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } } else { fac_addr = DEFAULT_FACILITATOR_ADDR; } main(); } /* The main logic begins here, after start-up issues are taken care of. */ private function main():void { if (num_proxy_pairs >= MAX_NUM_PROXY_PAIRS) { setTimeout(main, FACILITATOR_POLL_INTERVAL); return; } s_f = new Socket(); s_f.addEventListener(Event.CONNECT, fac_connected); s_f.addEventListener(Event.CLOSE, function (e:Event):void { puts("Facilitator: closed connection."); setTimeout(main, FACILITATOR_POLL_INTERVAL); }); s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); }); s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); }); puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + "."); s_f.connect(fac_addr.host, fac_addr.port); } private function fac_connected(e:Event):void { puts("Facilitator: connected."); s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data); s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n"); } private function fac_data(e:ProgressEvent):void { var client_spec:String; var client_addr:Object; var proxy_pair:Object; client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8"); puts("Facilitator: got \"" + client_spec + "\"."); client_addr = parse_addr_spec(client_spec); if (!client_addr) { puts("Error: Client spec must be in the form \"host:port\"."); return; } num_proxy_pairs++; total_proxy_pairs++; proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR); proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void { proxy_pair.log("Complete."); num_proxy_pairs--; }); proxy_pair.connect(); /* Update the client count on the badge. */ update_client_count(); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private static function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.display.Sprite; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.Socket; import flash.utils.ByteArray; /* An instance of a client-relay connection. */ class ProxyPair extends EventDispatcher { // Address ({host, port}) of client. private var addr_c:Object; // Address ({host, port}) of relay. private var addr_r:Object; // Socket to client. private var s_c:Socket; // Socket to relay. private var s_r:Socket; // Parent swfcat, for UI updates. private var ui:swfcat; public function log(msg:String):void { ui.puts(id() + ": " + msg) } // String describing this pair for output. public function id():String { return "<" + this.addr_c.host + ":" + this.addr_c.port + "," + this.addr_r.host + ":" + this.addr_r.port + ">"; } public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object) { this.ui = ui; this.addr_c = addr_c; this.addr_r = addr_r; } public function connect():void { s_r = new Socket(); s_r.addEventListener(Event.CONNECT, tor_connected); s_r.addEventListener(Event.CLOSE, function (e:Event):void { log("Tor: closed."); if (s_c.connected) s_c.close(); dispatchEvent(new Event(Event.COMPLETE)); }); s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Tor: I/O error: " + e.text + "."); if (s_c.connected) s_c.close(); dispatchEvent(new Event(Event.COMPLETE)); }); s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Tor: security error: " + e.text + "."); if (s_c.connected) s_c.close(); dispatchEvent(new Event(Event.COMPLETE)); }); log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + "."); s_r.connect(addr_r.host, addr_r.port); } private function tor_connected(e:Event):void { log("Tor: connected."); s_c = new Socket(); s_c.addEventListener(Event.CONNECT, client_connected); s_c.addEventListener(Event.CLOSE, function (e:Event):void { log("Client: closed."); if (s_r.connected) s_r.close(); dispatchEvent(new Event(Event.COMPLETE)); }); s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Client: I/O error: " + e.text + "."); if (s_r.connected) s_r.close(); dispatchEvent(new Event(Event.COMPLETE)); }); s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Client: security error: " + e.text + "."); if (s_r.connected) s_r.close(); dispatchEvent(new Event(Event.COMPLETE)); }); log("Client: connecting to " + addr_c.host + ":" + addr_c.port + "."); s_c.connect(addr_c.host, addr_c.port); } private function client_connected(e:Event):void { log("Client: connected."); s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_r.readBytes(bytes, 0, e.bytesLoaded); log("Tor: read " + bytes.length + "."); s_c.writeBytes(bytes); }); s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_c.readBytes(bytes, 0, e.bytesLoaded); log("Client: read " + bytes.length + "."); s_r.writeBytes(bytes); }); } }
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.text.TextField; import flash.text.TextFormat; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; import flash.utils.setTimeout; public class swfcat extends Sprite { /* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a crossdomain policy. */ private const DEFAULT_TOR_ADDR:Object = { host: "173.255.221.44", port: 9001 }; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "173.255.221.44", port: 9002 }; private const MAX_NUM_PROXY_PAIRS:uint = 1; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; // Bytes per second. public const RATE_LIMIT:Number = 10 * 1024; // Seconds. private const RATE_LIMIT_HISTORY:Number = 5.0; // Socket to facilitator. private var s_f:Socket; /* TextField for debug output. */ private var output_text:TextField; private var fac_addr:Object; /* Number of proxy pairs currently connected (up to MAX_NUM_PROXY_PAIRS). */ private var num_proxy_pairs:int = 0; /* Number of proxy pairs ever connected. */ private var total_proxy_pairs:int = 0; public var rate_limit:RateLimit; /* Badge with a client counter */ [Embed(source="badge_con_counter.png")] private var BadgeImage:Class; private var client_count_tf:TextField; private var client_count_fmt:TextFormat; public function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function update_client_count():void { if (String(total_proxy_pairs).length == 1) client_count_tf.text = "0" + String(total_proxy_pairs); else client_count_tf.text = String(total_proxy_pairs); } public function swfcat() { // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; /* Setup client counter for badge. */ client_count_fmt = new TextFormat(); client_count_fmt.color = 0xFFFFFF; client_count_fmt.align = "center"; client_count_fmt.font = "courier-new"; client_count_fmt.bold = true; client_count_fmt.size = 10; client_count_tf = new TextField(); client_count_tf.width = 20; client_count_tf.height = 17; client_count_tf.background = false; client_count_tf.defaultTextFormat = client_count_fmt; client_count_tf.x=47; client_count_tf.y=3; /* Update the client counter on badge. */ update_client_count(); rate_limit = new RateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY); puts("Starting."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String; puts("Parameters loaded."); if (this.loaderInfo.parameters["debug"]) addChild(output_text); else { addChild(new BadgeImage()); /* Tried unsuccessfully to add counter to badge. */ /* For now, need two addChilds :( */ addChild(client_count_tf); } fac_spec = this.loaderInfo.parameters["facilitator"]; if (fac_spec) { puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = parse_addr_spec(fac_spec); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } } else { fac_addr = DEFAULT_FACILITATOR_ADDR; } main(); } /* The main logic begins here, after start-up issues are taken care of. */ private function main():void { if (num_proxy_pairs >= MAX_NUM_PROXY_PAIRS) { setTimeout(main, FACILITATOR_POLL_INTERVAL); return; } s_f = new Socket(); s_f.addEventListener(Event.CONNECT, fac_connected); s_f.addEventListener(Event.CLOSE, function (e:Event):void { puts("Facilitator: closed connection."); setTimeout(main, FACILITATOR_POLL_INTERVAL); }); s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); }); s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); }); puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + "."); s_f.connect(fac_addr.host, fac_addr.port); } private function fac_connected(e:Event):void { puts("Facilitator: connected."); s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data); s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n"); } private function fac_data(e:ProgressEvent):void { var client_spec:String; var client_addr:Object; var proxy_pair:Object; client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8"); puts("Facilitator: got \"" + client_spec + "\"."); client_addr = parse_addr_spec(client_spec); if (!client_addr) { puts("Error: Client spec must be in the form \"host:port\"."); return; } num_proxy_pairs++; total_proxy_pairs++; proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR); proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void { proxy_pair.log("Complete."); num_proxy_pairs--; }); proxy_pair.connect(); /* Update the client count on the badge. */ update_client_count(); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private static function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.display.Sprite; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.Socket; import flash.utils.ByteArray; import flash.utils.clearTimeout; import flash.utils.getTimer; import flash.utils.setTimeout; class RateLimit { private var amount:Number; private var capacity:Number; private var time:Number; private var last_update:uint; public function RateLimit(capacity:Number, time:Number) { this.amount = 0.0; /* capacity / time is the rate we are aiming for. */ this.capacity = capacity; this.time = time; this.last_update = getTimer(); } private function age():void { var now:uint; var delta:Number; now = getTimer(); delta = (now - last_update) / 1000.0; last_update = now; amount -= delta * capacity / time; if (amount < 0.0) amount = 0.0; } public function update(n:Number):Boolean { age(); amount += n; return amount <= capacity; } public function when():Number { age(); return (amount - capacity) / (capacity / time); } public function is_limited():Boolean { age(); return amount > capacity; } } /* An instance of a client-relay connection. */ class ProxyPair extends EventDispatcher { // Address ({host, port}) of client. private var addr_c:Object; // Address ({host, port}) of relay. private var addr_r:Object; // Socket to client. private var s_c:Socket; // Socket to relay. private var s_r:Socket; // Parent swfcat, for UI updates and rate meter. private var ui:swfcat; // Pending byte read counts for relay and client sockets. private var r2c_schedule:Array; private var c2r_schedule:Array; // Callback id. private var flush_id:uint; public function log(msg:String):void { ui.puts(id() + ": " + msg) } // String describing this pair for output. public function id():String { return "<" + this.addr_c.host + ":" + this.addr_c.port + "," + this.addr_r.host + ":" + this.addr_r.port + ">"; } public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object) { this.ui = ui; this.addr_c = addr_c; this.addr_r = addr_r; this.c2r_schedule = []; this.r2c_schedule = []; } public function connect():void { s_r = new Socket(); s_r.addEventListener(Event.CONNECT, tor_connected); s_r.addEventListener(Event.CLOSE, function (e:Event):void { log("Tor: closed."); if (s_c.connected) s_c.close(); dispatchEvent(new Event(Event.COMPLETE)); }); s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Tor: I/O error: " + e.text + "."); if (s_c.connected) s_c.close(); dispatchEvent(new Event(Event.COMPLETE)); }); s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Tor: security error: " + e.text + "."); if (s_c.connected) s_c.close(); dispatchEvent(new Event(Event.COMPLETE)); }); log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + "."); s_r.connect(addr_r.host, addr_r.port); } private function tor_connected(e:Event):void { log("Tor: connected."); s_c = new Socket(); s_c.addEventListener(Event.CONNECT, client_connected); s_c.addEventListener(Event.CLOSE, function (e:Event):void { log("Client: closed."); if (s_r.connected) s_r.close(); dispatchEvent(new Event(Event.COMPLETE)); }); s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Client: I/O error: " + e.text + "."); if (s_r.connected) s_r.close(); dispatchEvent(new Event(Event.COMPLETE)); }); s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Client: security error: " + e.text + "."); if (s_r.connected) s_r.close(); dispatchEvent(new Event(Event.COMPLETE)); }); log("Client: connecting to " + addr_c.host + ":" + addr_c.port + "."); s_c.connect(addr_c.host, addr_c.port); } private function relay_to_client(e:ProgressEvent):void { r2c_schedule.push(e.bytesLoaded); flush(); } private function client_to_relay(e:ProgressEvent):void { c2r_schedule.push(e.bytesLoaded); flush(); } private function client_connected(e:Event):void { log("Client: connected."); s_r.addEventListener(ProgressEvent.SOCKET_DATA, relay_to_client); s_c.addEventListener(ProgressEvent.SOCKET_DATA, client_to_relay); } private function transfer_chunk(s_from:Socket, s_to:Socket, n:uint, label:String):void { var bytes:ByteArray; bytes = new ByteArray(); s_from.readBytes(bytes, 0, n); s_to.writeBytes(bytes); ui.rate_limit.update(n); log(label + ": read " + bytes.length + "."); } /* Send as much data as the rate limit currently allows. */ private function flush():void { while (!ui.rate_limit.is_limited() && (r2c_schedule.length > 0 || c2r_schedule.length > 0)) { if (r2c_schedule.length > 0) transfer_chunk(s_r, s_c, r2c_schedule.shift(), "Tor"); if (c2r_schedule.length > 0) transfer_chunk(s_c, s_r, c2r_schedule.shift(), "Client"); } if (flush_id) clearTimeout(flush_id); flush_id = undefined; /* Call again when safe, if necessary. */ if (r2c_schedule.length > 0 || c2r_schedule.length > 0) flush_id = setTimeout(flush, ui.rate_limit.when() * 1000); } }
Add a leaky bucket bandwidth limiter.
Add a leaky bucket bandwidth limiter.
ActionScript
mit
arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy
3a6d0d09721b04d4846f0918cae2b3da312a9f4c
src/as/com/threerings/flex/CommandMenu.as
src/as/com/threerings/flex/CommandMenu.as
// // $Id$ // // Nenya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.flex { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.geom.Rectangle; import mx.controls.Menu; import mx.core.mx_internal; import mx.core.Application; import mx.core.ScrollPolicy; import mx.events.MenuEvent; import mx.utils.ObjectUtil; import com.dougmccune.controls.ScrollableArrowMenu; import com.threerings.util.CommandEvent; use namespace mx_internal; /** * A pretty standard menu that can submit CommandEvents if menu items * have "command" and possibly "arg" properties. Commands are submitted to * controllers for processing. Alternatively, you may specify * "callback" properties that specify a function closure to call, with the * "arg" property containing either a single arg or an array of args. * * Example dataProvider array: * [ { label: "Go home", icon: homeIconClass, * command: Controller.GO_HOME, arg: homeId }, * { type: "separator"}, { label: "Crazytown", callback: setCrazy, arg: [ true, false ] }, * { label: "Other places", children: subMenuArray } * ]; * * See "Defining menu structure and data" in the Flex manual for the * full list. */ public class CommandMenu extends ScrollableArrowMenu { public function CommandMenu () { super(); verticalScrollPolicy = ScrollPolicy.OFF; addEventListener(MenuEvent.ITEM_CLICK, itemClicked); } /** * Factory method to create a command menu. * * @param items an array of menu items. */ public static function createMenu (items :Array) :CommandMenu { var menu :CommandMenu = new CommandMenu(); menu.owner = DisplayObjectContainer(Application.application); menu.tabEnabled = false; menu.showRoot = true; Menu.popUpMenu(menu, null, items); return menu; } /** * Actually pop up the menu. This can be used instead of show(). */ public function popUp ( trigger :DisplayObject, popUpwards :Boolean = false) :void { var r :Rectangle = trigger.getBounds(trigger.stage); if (popUpwards) { show(r.x, 0); // then, reposition the y once we know our size y = r.y - getExplicitOrMeasuredHeight(); } else { // position it below the trigger show(r.x, r.y + r.height); } } /** * Just like our superclass's show(), except that when invoked * with no args, causes the menu to show at the current mouse location * instead of the top-left corner of the application. */ override public function show (xShow :Object = null, yShow :Object = null) :void { if (xShow == null) { xShow = DisplayObject(Application.application).mouseX; } if (yShow == null) { yShow = DisplayObject(Application.application).mouseY; } super.show(xShow, yShow); } /** * Callback for MenuEvent.ITEM_CLICK. */ protected function itemClicked (event :MenuEvent) :void { var arg :Object = getItemProp(event.item, "arg"); var cmdOrFn :Object = getItemProp(event.item, "command"); if (cmdOrFn == null) { cmdOrFn = getItemProp(event.item, "callback"); } if (cmdOrFn != null) { event.stopImmediatePropagation(); CommandEvent.dispatch(mx_internal::parentDisplayObject, cmdOrFn, arg) } // else: no warning. There may be non-command menu items mixed in. } /** * Get the specified property for the specified item, if any. * Somewhat similar to bits in the DefaultDataDescriptor. */ protected function getItemProp (item :Object, prop :String) :Object { try { if (item is XML) { return String((item as XML).attribute(prop)); } else if (prop in item) { return item[prop]; } } catch (e :Error) { // alas; fall through } return null; } } }
// // $Id$ // // Nenya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.flex { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.geom.Rectangle; import mx.controls.Menu; import mx.core.mx_internal; import mx.core.Application; import mx.core.ScrollPolicy; import mx.events.MenuEvent; import mx.utils.ObjectUtil; import flexlib.controls.ScrollableArrowMenu; import com.threerings.util.CommandEvent; use namespace mx_internal; /** * A pretty standard menu that can submit CommandEvents if menu items * have "command" and possibly "arg" properties. Commands are submitted to * controllers for processing. Alternatively, you may specify * "callback" properties that specify a function closure to call, with the * "arg" property containing either a single arg or an array of args. * * Example dataProvider array: * [ { label: "Go home", icon: homeIconClass, * command: Controller.GO_HOME, arg: homeId }, * { type: "separator"}, { label: "Crazytown", callback: setCrazy, arg: [ true, false ] }, * { label: "Other places", children: subMenuArray } * ]; * * See "Defining menu structure and data" in the Flex manual for the * full list. */ public class CommandMenu extends ScrollableArrowMenu { public function CommandMenu () { super(); verticalScrollPolicy = ScrollPolicy.OFF; addEventListener(MenuEvent.ITEM_CLICK, itemClicked); } /** * Factory method to create a command menu. * * @param items an array of menu items. */ public static function createMenu (items :Array) :CommandMenu { var menu :CommandMenu = new CommandMenu(); menu.owner = DisplayObjectContainer(Application.application); menu.tabEnabled = false; menu.showRoot = true; Menu.popUpMenu(menu, null, items); return menu; } /** * Actually pop up the menu. This can be used instead of show(). */ public function popUp ( trigger :DisplayObject, popUpwards :Boolean = false) :void { var r :Rectangle = trigger.getBounds(trigger.stage); if (popUpwards) { show(r.x, 0); // then, reposition the y once we know our size y = r.y - getExplicitOrMeasuredHeight(); } else { // position it below the trigger show(r.x, r.y + r.height); } } /** * Just like our superclass's show(), except that when invoked * with no args, causes the menu to show at the current mouse location * instead of the top-left corner of the application. */ override public function show (xShow :Object = null, yShow :Object = null) :void { if (xShow == null) { xShow = DisplayObject(Application.application).mouseX; } if (yShow == null) { yShow = DisplayObject(Application.application).mouseY; } super.show(xShow, yShow); } /** * Callback for MenuEvent.ITEM_CLICK. */ protected function itemClicked (event :MenuEvent) :void { var arg :Object = getItemProp(event.item, "arg"); var cmdOrFn :Object = getItemProp(event.item, "command"); if (cmdOrFn == null) { cmdOrFn = getItemProp(event.item, "callback"); } if (cmdOrFn != null) { event.stopImmediatePropagation(); CommandEvent.dispatch(mx_internal::parentDisplayObject, cmdOrFn, arg) } // else: no warning. There may be non-command menu items mixed in. } /** * Get the specified property for the specified item, if any. * Somewhat similar to bits in the DefaultDataDescriptor. */ protected function getItemProp (item :Object, prop :String) :Object { try { if (item is XML) { return String((item as XML).attribute(prop)); } else if (prop in item) { return item[prop]; } } catch (e :Error) { // alas; fall through } return null; } } }
Extend the flexlib scrolling menu.
Extend the flexlib scrolling menu. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@184 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
ab544f4d51df872623b2440382a9109fd121d074
src/net/manaca/loaderqueue/LoaderQueue.as
src/net/manaca/loaderqueue/LoaderQueue.as
/* * Copyright (c) 2011, wersling.com All rights reserved. */ package net.manaca.loaderqueue { import flash.events.EventDispatcher; import flash.events.TimerEvent; import flash.utils.Dictionary; import flash.utils.Timer; /** * 任务队列全部完成后派发 * @eventType net.manaca.loaderqueue.LoaderQueueEvent.TASK_QUEUE_COMPLETED */ [Event(name="taskQueueCompleted", type="net.manaca.loaderqueue.LoaderQueueEvent")] /** * 任务队列及下载队列的管理器 * @example * var urlLoader:URLLoaderAdapter = * new URLLoaderAdapter(4,"http://ggg.ggg.com/a.swf"); * urlLoader.addEventListener(LoaderQueueEvent.TASK_COMPLETED, * onLoadedCompleted); * var loaderQueue:LoaderQueue = new LoaderQueue(); * loaderQueue.addItem(urlLoader); * * @see net.manaca.loaderqueue.adapter#URLLoaderAdapter * * @author Austin * @update sean */ public class LoaderQueue extends EventDispatcher implements ILoaderQueue { //========================================================================== // Constructor //========================================================================== /** * Constructs a new <code>Application</code> instance. * @param threadLimit 下载线程数的上限。默认2 * @param delay 下载队列排序延迟时间,单位毫秒。默认500毫秒 * @param jumpQueueIfCached 如果该url文件已经加载过,是否跳过队列直接加载。 * 该参数通过加载文件的url来判断。默认为true */ public function LoaderQueue(threadLimit:uint = 2, delay:int = 500, jumpQueueIfCached:Boolean = true) { this.threadLimit = threadLimit; this.delay = delay; this.jumpQueueIfCached = jumpQueueIfCached; timeOutToSort = new Timer(delay, 1); timeOutToSort.addEventListener(TimerEvent.TIMER_COMPLETE, timeOutToSort_timerCompleteHandler); } //========================================================================== // Variables //========================================================================== /** * 下载队列排序延迟时间,单位毫秒 */ private var delay:int; /** * 缓存已经加载过的url地址 */ private var cacheMap:Object = {}; //========================================================================== // Properties //========================================================================== /** * 如果该url文件已经加载过,是否跳过队列直接加载。 * 该参数通过加载文件的url来判断。默认为true * @default true */ public var jumpQueueIfCached:Boolean = true; /** * 最大线程数上限值 */ public var threadLimit:uint; /** * 等级排序时是否使用倒序(如4,3,2,1) */ public var reversePriority:Boolean = false; /** * 用于保存所有的下载项目 * p.s:已下载的会被清除 * @private */ private var loaderDict:Dictionary/* of ILoaderAdapter */= new Dictionary(); /** * 用于决定下载的等级的顺序 * @private */ private var loaderPriorityLib:Array /* of uint */ = []; /** * 用于保存目前正在下载的对象 * @private */ private var threadLib:Array /* of ILoaderAdapter */ = []; /** * 用于在添加新的Item后延迟触发排序. */ private var timeOutToSort:Timer; //========================================================================== // Methods //========================================================================== /** * @inheritDoc */ public function addItem(loaderAdapter:ILoaderAdapter):void { loaderAdapter.state = LoaderQueueConst.STATE_WAITING; //如果ignoreCache为true,则检查是否已经加载过,如果加载过,则不添加到队列, //而是直接开始加载 if(jumpQueueIfCached) { if(cacheMap[loaderAdapter.url]) { loaderAdapter.start(); return; } } if (loaderDict[loaderAdapter.priority] == null) { loaderDict[loaderAdapter.priority] = []; loaderPriorityLib.push(loaderAdapter.priority); } loaderDict[loaderAdapter.priority].push(loaderAdapter); loaderAdapter.addEventListener(LoaderQueueEvent.TASK_DISPOSE, loaderAdapter_disposeHandler); // 使用Timer调用是为防止同一时间多个添加造成的性能浪费 if (!timeOutToSort.running) { timeOutToSort.start(); } } /** * 将LoaderQueue实例中的所有内容消毁,并将下载队列清空 */ public function dispose():void { removeAllItem(); loaderDict = null; loaderPriorityLib = null; threadLib = null; timeOutToSort.stop(); timeOutToSort.removeEventListener(TimerEvent.TIMER_COMPLETE, timeOutToSort_timerCompleteHandler); timeOutToSort = null; } /** * 停止并移除队列中所有等级的下载项 */ public function removeAllItem():void { for each (var i:uint in loaderPriorityLib) { removeItemByPriority(i); } } /** * 停止并移除队列中指定的下载项 * 如想消毁Item实例需手动调用其自身的dispose方法 */ public function removeItem(loaderAdapter:ILoaderAdapter):void { disposeItem(loaderAdapter); loaderAdapter.state = LoaderQueueConst.STATE_REMOVED; } /** * 停止并移除队列中所有相应等级的下载项 * @param priority 需停止并移除的等级 */ public function removeItemByPriority(priority:uint):void { for each (var i:ILoaderAdapter in loaderDict[priority]) { removeItem(i); } } /** * 停止并移除队列中除指定等级以外的所有等级的下载项 * @param priority 需保留的等级 */ public function saveItemByPriority(priority:uint):void { for each (var i:ILoaderAdapter in loaderDict[priority]) { if (i.priority != priority) { removeItem(i); } } } /** * 取得当前正在运行的线程数 * @return uint */ public function get currentStartedNum():uint { return threadLib.length; } /** * 检查队列中是否还有项目需下载 * @private */ private function checkQueueHandle():Boolean { for each (var priority:uint in loaderPriorityLib) { if (loaderDict[priority].length > 0) { return true; } } dispatchEvent( new LoaderQueueEvent(LoaderQueueEvent.TASK_QUEUE_COMPLETED)); return false; } /** * 检查下载线程是否已到最大上限 * @private */ private function checkThreadHandle(loaderAdapter:ILoaderAdapter):void { if (loaderAdapter == null) { //执行到此处说明队列中的所有项目均正在执行 return; } if (threadLib.length < threadLimit) { threadLib.push(loaderAdapter); startItem(loaderAdapter); } else { threadFullHandle(loaderAdapter); } } /** * 将项目从线程池与队列中移出,但并不消毁其自身 * (如想消毁项目实例需手动调用其自身的dispose方法) * p.s:一般在item发生completed与error后调用 * * @private */ private function disposeItem(loaderAdapter:ILoaderAdapter):void { if (loaderAdapter.isStarted) { loaderAdapter.removeEventListener(LoaderQueueEvent.TASK_COMPLETED, loaderAdapter_completedHandler); loaderAdapter.removeEventListener(LoaderQueueEvent.TASK_ERROR, loaderAdapter_errorHandler); try { loaderAdapter.stop(); } catch (e:Error) { //屏蔽可能的错误 } } loaderAdapter.removeEventListener(LoaderQueueEvent.TASK_DISPOSE, loaderAdapter_disposeHandler); var num:uint = threadLib.indexOf(loaderAdapter); if (num != -1) { threadLib.splice(num, 1); } num = loaderDict[loaderAdapter.priority].indexOf(loaderAdapter); loaderDict[loaderAdapter.priority].splice(num, 1); } /** * 取得下一个需要下载的项目 * @private */ private function getNextIdleItem():ILoaderAdapter { for each (var priority:uint in loaderPriorityLib) { for each (var loaderAdapter:ILoaderAdapter in loaderDict[priority]) { if (!loaderAdapter.isStarted) { return loaderAdapter; } } } return null; } /** * 启动LoaderAdapter实例 * @private */ private function startItem(loaderAdapter:ILoaderAdapter):void { loaderAdapter.state = LoaderQueueConst.STATE_STARTED; loaderAdapter.addEventListener(LoaderQueueEvent.TASK_COMPLETED, loaderAdapter_completedHandler); loaderAdapter.addEventListener(LoaderQueueEvent.TASK_ERROR, loaderAdapter_errorHandler); loaderAdapter.start(); } /** * 停止LoaderAdapter实例并屏蔽可能引发的错误 * @private */ private function stopItem(loaderAdapter:ILoaderAdapter):void { loaderAdapter.state = LoaderQueueConst.STATE_WAITING; loaderAdapter.removeEventListener(LoaderQueueEvent.TASK_COMPLETED, loaderAdapter_completedHandler); loaderAdapter.removeEventListener(LoaderQueueEvent.TASK_ERROR, loaderAdapter_errorHandler); try { loaderAdapter.stop(); } catch (error:Error) { //屏蔽可能的错误 } } /** * 当下载线程全部被占用时,对新添加的实例进行的操作 * @private */ private function threadFullHandle(loaderAdapter:ILoaderAdapter):void { for (var i:uint = 0; i < threadLib.length; i++) { var reversePriorityResult:Boolean = checkReversePriority(ILoaderAdapter(threadLib[i]).priority, loaderAdapter.priority); if (reversePriorityResult) { stopItem(threadLib[i]); threadLib[i] = loaderAdapter; startItem(loaderAdapter); } } } /** * 将已启动的adapter重新排序 */ private function sortStartedItem():void { var itemLoader:ILoaderAdapter = getNextIdleItem(); if (itemLoader == null) { //已无项目,或是所有项目都已开始下载 //所以已无重新排序必要 return; } var oldPriority:int = itemLoader.priority; var idleLoaderAdapter:ILoaderAdapter; var runningLoaderAdapter:ILoaderAdapter; for (var i:uint = 0; i < threadLib.length; i++) { runningLoaderAdapter = threadLib[i]; var reversePriorityResult:Boolean = checkReversePriority( runningLoaderAdapter.priority, oldPriority); if (reversePriorityResult) { idleLoaderAdapter = getNextIdleItem(); reversePriorityResult = checkReversePriority(runningLoaderAdapter.priority, idleLoaderAdapter.priority); if (reversePriorityResult) { stopItem(runningLoaderAdapter); threadLib[i] = idleLoaderAdapter; startItem(idleLoaderAdapter); oldPriority = idleLoaderAdapter.priority; } else { oldPriority = runningLoaderAdapter.priority; } } else { oldPriority = runningLoaderAdapter.priority; } } } /** * 如线程池未全部使用,则将等待下载的项目装进线程池 */ private function fillThreadPool():void { var nextIdleAdapter:ILoaderAdapter; while (currentStartedNum < threadLimit) { nextIdleAdapter = getNextIdleItem(); if (nextIdleAdapter != null) { threadLib.push(nextIdleAdapter); startItem(nextIdleAdapter); nextIdleAdapter = null; } else { //线程未满,但已没有等待下载的项目时调用此处 break; } } } //========================================================================== // Event Handlers //========================================================================== private function loaderAdapter_completedHandler(event:LoaderQueueEvent):void { var loaderAdapter:ILoaderAdapter = event.currentTarget as ILoaderAdapter; if(jumpQueueIfCached) { cacheMap[loaderAdapter.url] = true; } disposeItem(loaderAdapter); if (checkQueueHandle()) { checkThreadHandle(getNextIdleItem()); } } private function loaderAdapter_errorHandler(event:LoaderQueueEvent):void { var loaderAdapter:ILoaderAdapter = event.currentTarget as ILoaderAdapter; disposeItem(loaderAdapter); if (checkQueueHandle()) { checkThreadHandle(getNextIdleItem()); } } /** * adataper实例自动调用其自身的dispose方法后触发此处 * @private */ private function loaderAdapter_disposeHandler(event:LoaderQueueEvent):void { removeItem(event.target as ILoaderAdapter); } private function timeOutToSort_timerCompleteHandler(event:TimerEvent):void { timeOutToSort.reset(); if (!reversePriority) { loaderPriorityLib.sort(Array.NUMERIC); } else { loaderPriorityLib.sort(Array.NUMERIC); loaderPriorityLib.reverse(); } if (threadLib.length > 0) { sortStartedItem(); } fillThreadPool(); } /** * 根据是否倒序,来得出两个等级之间优先级的结果 * @param priority1 * @param priority2 * @return * @private */ private function checkReversePriority(priority1:uint, priority2:uint):Boolean { if (!this.reversePriority) { return priority1 > priority2; } return priority2 > priority1; } } }
/* * Copyright (c) 2011, wersling.com All rights reserved. */ package net.manaca.loaderqueue { import flash.events.EventDispatcher; import flash.events.TimerEvent; import flash.utils.Dictionary; import flash.utils.Timer; /** * 任务队列全部完成后派发 * @eventType net.manaca.loaderqueue.LoaderQueueEvent.TASK_QUEUE_COMPLETED */ [Event(name="taskQueueCompleted", type="net.manaca.loaderqueue.LoaderQueueEvent")] /** * 任务队列及下载队列的管理器 * @example * var urlLoader:URLLoaderAdapter = * new URLLoaderAdapter(4,"http://ggg.ggg.com/a.swf"); * urlLoader.addEventListener(LoaderQueueEvent.TASK_COMPLETED, * onLoadedCompleted); * var loaderQueue:LoaderQueue = new LoaderQueue(); * loaderQueue.addItem(urlLoader); * * @see net.manaca.loaderqueue.adapter#URLLoaderAdapter * * @author Austin * @update sean */ public class LoaderQueue extends EventDispatcher implements ILoaderQueue { //========================================================================== // Constructor //========================================================================== /** * Constructs a new <code>Application</code> instance. * @param threadLimit 下载线程数的上限。默认2 * @param delay 下载队列排序延迟时间,单位毫秒。默认500毫秒 * @param jumpQueueIfCached 如果该url文件已经加载过,是否跳过队列直接加载。 * 该参数通过加载文件的url来判断。默认为true */ public function LoaderQueue(threadLimit:uint = 2, delay:int = 500, jumpQueueIfCached:Boolean = true) { this.threadLimit = threadLimit; this.delay = delay; this.jumpQueueIfCached = jumpQueueIfCached; timeOutToSort = new Timer(delay, 1); timeOutToSort.addEventListener(TimerEvent.TIMER_COMPLETE, timeOutToSort_timerCompleteHandler); } //========================================================================== // Variables //========================================================================== /** * 下载队列排序延迟时间,单位毫秒 */ private var delay:int; /** * 缓存已经加载过的url地址 */ private var cacheMap:Object = {}; /** * 用于保存所有的下载项目 * p.s:已下载的会被清除 * @private */ private var loaderDict:Dictionary/* of ILoaderAdapter */= new Dictionary(); /** * 用于决定下载的等级的顺序 * @private */ private var loaderPriorityLib:Array /* of uint */ = []; /** * 用于保存目前正在下载的对象 * @private */ private var threadLib:Array /* of ILoaderAdapter */ = []; /** * 用于在添加新的Item后延迟触发排序. */ private var timeOutToSort:Timer; //========================================================================== // Properties //========================================================================== /** * 如果该url文件已经加载过,是否跳过队列直接加载。 * 该参数通过加载文件的url来判断。默认为true * @default true */ public var jumpQueueIfCached:Boolean = true; /** * 最大线程数上限值 */ public var threadLimit:uint; /** * 等级排序时是否使用倒序(如4,3,2,1) */ public var reversePriority:Boolean = false; //========================================================================== // Methods //========================================================================== /** * @inheritDoc */ public function addItem(loaderAdapter:ILoaderAdapter):void { loaderAdapter.state = LoaderQueueConst.STATE_WAITING; //如果jumpQueueIfCached为true,则检查是否已经加载过,如果加载过,则不添加到队列, //而是直接开始加载 if(jumpQueueIfCached) { if(cacheMap[loaderAdapter.url]) { loaderAdapter.start(); return; } } if (loaderDict[loaderAdapter.priority] == null) { loaderDict[loaderAdapter.priority] = []; loaderPriorityLib.push(loaderAdapter.priority); } loaderDict[loaderAdapter.priority].push(loaderAdapter); loaderAdapter.addEventListener(LoaderQueueEvent.TASK_DISPOSE, loaderAdapter_disposeHandler); // 使用Timer调用是为防止同一时间多个添加造成的性能浪费 if (!timeOutToSort.running) { timeOutToSort.start(); } } /** * 将LoaderQueue实例中的所有内容消毁,并将下载队列清空 */ public function dispose():void { removeAllItem(); loaderDict = null; loaderPriorityLib = null; threadLib = null; timeOutToSort.stop(); timeOutToSort.removeEventListener(TimerEvent.TIMER_COMPLETE, timeOutToSort_timerCompleteHandler); timeOutToSort = null; } /** * 停止并移除队列中所有等级的下载项 */ public function removeAllItem():void { for each (var i:uint in loaderPriorityLib) { removeItemByPriority(i); } } /** * 停止并移除队列中指定的下载项 * 如想消毁Item实例需手动调用其自身的dispose方法 */ public function removeItem(loaderAdapter:ILoaderAdapter):void { disposeItem(loaderAdapter); loaderAdapter.state = LoaderQueueConst.STATE_REMOVED; } /** * 停止并移除队列中所有相应等级的下载项 * @param priority 需停止并移除的等级 */ public function removeItemByPriority(priority:uint):void { for each (var i:ILoaderAdapter in loaderDict[priority]) { removeItem(i); } } /** * 停止并移除队列中除指定等级以外的所有等级的下载项 * @param priority 需保留的等级 */ public function saveItemByPriority(priority:uint):void { for each (var i:ILoaderAdapter in loaderDict[priority]) { if (i.priority != priority) { removeItem(i); } } } /** * 取得当前正在运行的线程数 * @return uint */ public function get currentStartedNum():uint { return threadLib.length; } /** * 检查队列中是否还有项目需下载 * @private */ private function checkQueueHandle():Boolean { for each (var priority:uint in loaderPriorityLib) { if (loaderDict[priority].length > 0) { return true; } } dispatchEvent( new LoaderQueueEvent(LoaderQueueEvent.TASK_QUEUE_COMPLETED)); return false; } /** * 检查下载线程是否已到最大上限 * @private */ private function checkThreadHandle(loaderAdapter:ILoaderAdapter):void { if (loaderAdapter == null) { //执行到此处说明队列中的所有项目均正在执行 return; } if (threadLib.length < threadLimit) { threadLib.push(loaderAdapter); startItem(loaderAdapter); } else { threadFullHandle(loaderAdapter); } } /** * 将项目从线程池与队列中移出,但并不消毁其自身 * (如想消毁项目实例需手动调用其自身的dispose方法) * p.s:一般在item发生completed与error后调用 * * @private */ private function disposeItem(loaderAdapter:ILoaderAdapter):void { if (loaderAdapter.isStarted) { loaderAdapter.removeEventListener(LoaderQueueEvent.TASK_COMPLETED, loaderAdapter_completedHandler); loaderAdapter.removeEventListener(LoaderQueueEvent.TASK_ERROR, loaderAdapter_errorHandler); try { loaderAdapter.stop(); } catch (e:Error) { //屏蔽可能的错误 } } loaderAdapter.removeEventListener(LoaderQueueEvent.TASK_DISPOSE, loaderAdapter_disposeHandler); var num:uint = threadLib.indexOf(loaderAdapter); if (num != -1) { threadLib.splice(num, 1); } num = loaderDict[loaderAdapter.priority].indexOf(loaderAdapter); loaderDict[loaderAdapter.priority].splice(num, 1); } /** * 取得下一个需要下载的项目 * @private */ private function getNextIdleItem():ILoaderAdapter { for each (var priority:uint in loaderPriorityLib) { for each (var loaderAdapter:ILoaderAdapter in loaderDict[priority]) { if (!loaderAdapter.isStarted) { return loaderAdapter; } } } return null; } /** * 启动LoaderAdapter实例 * @private */ private function startItem(loaderAdapter:ILoaderAdapter):void { loaderAdapter.state = LoaderQueueConst.STATE_STARTED; loaderAdapter.addEventListener(LoaderQueueEvent.TASK_COMPLETED, loaderAdapter_completedHandler); loaderAdapter.addEventListener(LoaderQueueEvent.TASK_ERROR, loaderAdapter_errorHandler); loaderAdapter.start(); } /** * 停止LoaderAdapter实例并屏蔽可能引发的错误 * @private */ private function stopItem(loaderAdapter:ILoaderAdapter):void { loaderAdapter.state = LoaderQueueConst.STATE_WAITING; loaderAdapter.removeEventListener(LoaderQueueEvent.TASK_COMPLETED, loaderAdapter_completedHandler); loaderAdapter.removeEventListener(LoaderQueueEvent.TASK_ERROR, loaderAdapter_errorHandler); try { loaderAdapter.stop(); } catch (error:Error) { //屏蔽可能的错误 } } /** * 当下载线程全部被占用时,对新添加的实例进行的操作 * @private */ private function threadFullHandle(loaderAdapter:ILoaderAdapter):void { for (var i:uint = 0; i < threadLib.length; i++) { var reversePriorityResult:Boolean = checkReversePriority(ILoaderAdapter(threadLib[i]).priority, loaderAdapter.priority); if (reversePriorityResult) { stopItem(threadLib[i]); threadLib[i] = loaderAdapter; startItem(loaderAdapter); } } } /** * 将已启动的adapter重新排序 */ private function sortStartedItem():void { var itemLoader:ILoaderAdapter = getNextIdleItem(); if (itemLoader == null) { //已无项目,或是所有项目都已开始下载 //所以已无重新排序必要 return; } var oldPriority:int = itemLoader.priority; var idleLoaderAdapter:ILoaderAdapter; var runningLoaderAdapter:ILoaderAdapter; for (var i:uint = 0; i < threadLib.length; i++) { runningLoaderAdapter = threadLib[i]; var reversePriorityResult:Boolean = checkReversePriority( runningLoaderAdapter.priority, oldPriority); if (reversePriorityResult) { idleLoaderAdapter = getNextIdleItem(); reversePriorityResult = checkReversePriority(runningLoaderAdapter.priority, idleLoaderAdapter.priority); if (reversePriorityResult) { stopItem(runningLoaderAdapter); threadLib[i] = idleLoaderAdapter; startItem(idleLoaderAdapter); oldPriority = idleLoaderAdapter.priority; } else { oldPriority = runningLoaderAdapter.priority; } } else { oldPriority = runningLoaderAdapter.priority; } } } /** * 如线程池未全部使用,则将等待下载的项目装进线程池 */ private function fillThreadPool():void { var nextIdleAdapter:ILoaderAdapter; while (currentStartedNum < threadLimit) { nextIdleAdapter = getNextIdleItem(); if (nextIdleAdapter != null) { threadLib.push(nextIdleAdapter); startItem(nextIdleAdapter); nextIdleAdapter = null; } else { //线程未满,但已没有等待下载的项目时调用此处 break; } } } //========================================================================== // Event Handlers //========================================================================== private function loaderAdapter_completedHandler(event:LoaderQueueEvent):void { var loaderAdapter:ILoaderAdapter = event.currentTarget as ILoaderAdapter; if(jumpQueueIfCached) { cacheMap[loaderAdapter.url] = true; } disposeItem(loaderAdapter); if (checkQueueHandle()) { checkThreadHandle(getNextIdleItem()); } } private function loaderAdapter_errorHandler(event:LoaderQueueEvent):void { var loaderAdapter:ILoaderAdapter = event.currentTarget as ILoaderAdapter; disposeItem(loaderAdapter); if (checkQueueHandle()) { checkThreadHandle(getNextIdleItem()); } } /** * adataper实例自动调用其自身的dispose方法后触发此处 * @private */ private function loaderAdapter_disposeHandler(event:LoaderQueueEvent):void { removeItem(event.target as ILoaderAdapter); } private function timeOutToSort_timerCompleteHandler(event:TimerEvent):void { timeOutToSort.reset(); if (!reversePriority) { loaderPriorityLib.sort(Array.NUMERIC); } else { loaderPriorityLib.sort(Array.NUMERIC); loaderPriorityLib.reverse(); } if (threadLib.length > 0) { sortStartedItem(); } fillThreadPool(); } /** * 根据是否倒序,来得出两个等级之间优先级的结果 * @param priority1 * @param priority2 * @return * @private */ private function checkReversePriority(priority1:uint, priority2:uint):Boolean { if (!this.reversePriority) { return priority1 > priority2; } return priority2 > priority1; } } }
Format LoaderQueue code
Format LoaderQueue code
ActionScript
mit
wersling/manaca,wersling/manaca
1f4349c37687697208a63b2e19771a81f9305155
vendors/VASTNew/org/osmf/vast/media/VAST2MediaGenerator.as
vendors/VASTNew/org/osmf/vast/media/VAST2MediaGenerator.as
/***************************************************** * * Copyright 2010 Eyewonder, LLC. All Rights Reserved. * ***************************************************** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * * The Initial Developer of the Original Code is Eyewonder, LLC. * Portions created by Eyewonder, LLC. are Copyright (C) 2010 * Eyewonder, LLC. A Limelight Networks Business. All Rights Reserved. * *****************************************************/ package org.osmf.vast.media { import __AS3__.vec.Vector; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Rectangle; import org.osmf.elements.ProxyElement; import org.osmf.elements.SWFLoader; import org.osmf.elements.VideoElement; import org.osmf.elements.beaconClasses.Beacon; import org.osmf.events.MediaElementEvent; import org.osmf.media.MediaElement; import org.osmf.media.MediaFactory; import org.osmf.media.URLResource; import org.osmf.metadata.Metadata; import org.osmf.traits.DisplayObjectTrait; import org.osmf.traits.MediaTraitType; import org.osmf.utils.HTTPLoader; import org.osmf.vast.model.VAST2MediaFile; import org.osmf.vast.model.VAST2Translator; import org.osmf.vast.model.VASTTrackingEvent; import org.osmf.vast.model.VASTTrackingEventType; import org.osmf.vast.model.VASTUrl; import org.osmf.vast.parser.base.VAST2CompanionElement; import org.osmf.vpaid.elements.VPAIDElement; import org.osmf.vpaid.metadata.VPAIDMetadata; CONFIG::LOGGING { import org.osmf.logging.Logger; import org.osmf.logging.Log; } /** * Utility class for creating MediaElements from a VASTDocument. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 */ public class VAST2MediaGenerator { /** * Constructor. * * @param mediaFileResolver The resolver to use when a VASTDocument * contains multiple representations of the same content (MediaFile). * If null, this object will use a DefaultVASTMediaFileResolver. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 */ public function VAST2MediaGenerator(mediaFileResolver:IVAST2MediaFileResolver=null, mediaFactory:MediaFactory=null) { super(); this.mediaFileResolver = mediaFileResolver != null ? mediaFileResolver : new DefaultVAST2MediaFileResolver(); this.mediaFactory = mediaFactory; } /** * Creates all relevant MediaElements from the specified VAST document. * * @param vastDocument The VASTDocument that holds the raw VAST information. * * @returns A Vector of MediaElements, where each MediaElement * represents a different VASTAd within the VASTDocument. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 */ public function createMediaElements(vastDocument:VAST2Translator, vastPlacement:String = null,playerSize:Rectangle = null, translatorIndex:int = 0):Vector.<MediaElement> { var mediaElements:Vector.<MediaElement> = new Vector.<MediaElement>(); this.vastDocument = vastDocument; vastDocument.adPlacement = (vastPlacement == null)?vastDocument.PLACEMENT_LINEAR:vastPlacement; if(vastDocument.clickThruUrl != null || vastDocument.clickThruUrl != "") { clickThru = vastDocument.clickThruUrl } cacheBuster = new CacheBuster(); var trackingEvents:Vector.<VASTTrackingEvent> = new Vector.<VASTTrackingEvent>; var proxyChain:Vector.<ProxyElement> = new Vector.<ProxyElement>(); // Check for the Impressions. if (vastDocument.impressionArray != null && vastDocument.impressionArray.length > 0) { var impressionArray:Vector.<VASTUrl> = new Vector.<VASTUrl>; for each(var impressionObj:Object in vastDocument.impressionArray) { var impressionURL:VASTUrl = new VASTUrl(impressionObj.url); impressionArray.push(impressionURL); } } addTrackingEvent("trkClickThruEvent", VASTTrackingEventType.CLICK_THRU, trackingEvents); addTrackingEvent("errorArray", VASTTrackingEventType.ERROR, trackingEvents); addTrackingEvent("trkStartEvent", VASTTrackingEventType.START, trackingEvents); addTrackingEvent("trkMidPointEvent", VASTTrackingEventType.MIDPOINT, trackingEvents); addTrackingEvent("trkFirstQuartileEvent", VASTTrackingEventType.FIRST_QUARTILE, trackingEvents); addTrackingEvent("trkThirdQuartileEvent", VASTTrackingEventType.THIRD_QUARTILE, trackingEvents); addTrackingEvent("trkCompleteEvent", VASTTrackingEventType.COMPLETE, trackingEvents); addTrackingEvent("trkMuteEvent", VASTTrackingEventType.MUTE, trackingEvents); addTrackingEvent("trkCreativeViewEvent", VASTTrackingEventType.CREATIVE_VIEW, trackingEvents); addTrackingEvent("trkPauseEvent", VASTTrackingEventType.PAUSE,trackingEvents); addTrackingEvent("trkReplayEvent", VASTTrackingEventType.REPLAY, trackingEvents); addTrackingEvent("trkFullScreenEvent", VASTTrackingEventType.FULLSCREEN, trackingEvents); addTrackingEvent("trkStopEvent", VASTTrackingEventType.STOP, trackingEvents); addTrackingEvent("trkUnmuteEvent", VASTTrackingEventType.UNMUTE, trackingEvents); addTrackingEvent("trkCloseEvent", VASTTrackingEventType.CLOSE, trackingEvents); addTrackingEvent("trkRewindEvent", VASTTrackingEventType.REWIND, trackingEvents); addTrackingEvent("trkResumeEvent", VASTTrackingEventType.RESUME, trackingEvents); addTrackingEvent("trkExpandEvent", VASTTrackingEventType.EXPAND, trackingEvents); addTrackingEvent("trkCollapseEvent", VASTTrackingEventType.COLLAPSE, trackingEvents); addTrackingEvent("trkAcceptInvitationEvent", VASTTrackingEventType.ACCEPT_INVITATION, trackingEvents); addTrackingEvent("trkSkipEvent", VASTTrackingEventType.SKIP,trackingEvents ); addTrackingEvent("trkProgressEvent", VASTTrackingEventType.PROGRESS, trackingEvents); addTrackingEvent("trkExitFullScreenEvent", VASTTrackingEventType.EXIT_FULLSCREEN, trackingEvents ); addTrackingEvent("trkCloseLinearEvent", VASTTrackingEventType.CLOSE_LINEAR, trackingEvents ); // Check for Video. if (vastDocument.mediafileArray != null && vastDocument.mediafileArray.length > 0 && isLinear) { for each(var mediaObj:Object in vastDocument.mediafileArray) { var mediaFileObj:VAST2MediaFile = new VAST2MediaFile(); mediaFileObj.url = mediaObj.url; mediaFileObj.delivery = mediaObj.delivery; mediaFileObj.bitrate = mediaObj.bitrate; mediaFileObj.type = mediaObj.type; mediaFileObj.width = mediaObj.width; mediaFileObj.height = mediaObj.height; mediaFileObj.id = mediaObj.id; mediaFileObj.scalable = mediaObj.scalable; mediaFileObj.maintainAspectRatio = mediaObj.maintainAspectRatio; mediaFileObj.apiFramework = mediaObj.apiFramework; var mediaFileURL:Vector.<VAST2MediaFile> = new Vector.<VAST2MediaFile>; mediaFileURL.push(mediaFileObj); } // Resolve the correct one. var mediaFile:VAST2MediaFile = mediaFileResolver.resolveMediaFiles(mediaFileURL); if (mediaFile != null) { var mediaURL:String = mediaFile.url; // If streaming, we may need to strip off the extension. if (mediaFile.delivery == "streaming" && mediaFile.type != "application/x-shockwave-flash") { mediaURL = mediaURL.replace(/\.flv$|\.f4v$/i, ""); } var rootElement:MediaElement; if(mediaFile.type == "application/x-shockwave-flash" ||mediaFile.type == "swf" ) { if (mediaFile.scalable) { rootElement = new VPAIDElement(new URLResource(mediaFile.url), new SWFLoader(),playerSize.width,playerSize.height); } else { rootElement = new VPAIDElement(new URLResource(mediaFile.url), new SWFLoader(),mediaFile.width,mediaFile.height); } VPAIDMetadata(rootElement.getMetadata("org.osmf.vpaid.metadata.VPAIDMetadata")).addValue(VPAIDMetadata.NON_LINEAR_CREATIVE, false); } else { if (mediaFactory != null) { rootElement = mediaFactory.createMediaElement(new URLResource(mediaURL)) as VideoElement; //VideoElement(rootElement).smoothing = true; } else { rootElement = new VideoElement(new URLResource(mediaURL)); //VideoElement(rootElement).smoothing = true; } } var impressions:VASTImpressionProxyElement = new VAST2ImpressionProxyElement(impressionArray, null, rootElement, cacheBuster); var events:VASTTrackingProxyElement = new VAST2TrackingProxyElement(trackingEvents,null, impressions, cacheBuster,clickThru); var vastMediaElement:MediaElement = events; mediaElements.push(vastMediaElement); } } else if(vastDocument.nonlinearArray != null && vastDocument.nonlinearArray.length > 0 && isNonLinear) { //Non-linear check goes here. If available create VPAID Element for each(var element:Object in vastDocument.nonlinearArray) { if(element.creativeType == "application/x-shockwave-flash") { var vpaidElement:MediaElement = new VPAIDElement(new URLResource(element.URL), new SWFLoader()); var vpaidMetadata:Metadata = vpaidElement.getMetadata(VPAIDMetadata.NAMESPACE); vpaidMetadata.addValue(VPAIDMetadata.NON_LINEAR_CREATIVE, true); var impressionsNonLinear:VASTImpressionProxyElement = new VAST2ImpressionProxyElement(impressionArray, null, vpaidElement, cacheBuster); var eventsNonLinear:VASTTrackingProxyElement = new VAST2TrackingProxyElement(trackingEvents,null, impressionsNonLinear, cacheBuster, clickThru); var vastMediaElementNonLinear:MediaElement = eventsNonLinear; mediaElements.push(vastMediaElementNonLinear); } } } if(vastDocument.companionArray != null && vastDocument.companionArray.length > 0) { for each(var companionAd:VAST2CompanionElement in vastDocument.companionArray) { CONFIG::LOGGING { logger.debug("[VAST] Companion ad detected" + companionAd.staticResource); } var companionElement:CompanionElement = new CompanionElement(companionAd); companionElement.scriptPath = companionAd.staticResource; mediaElements.push(companionElement); } } return mediaElements; } private function get isLinear() : Boolean { return (vastDocument.adPlacement == VAST2Translator.PLACEMENT_LINEAR); } private function get isNonLinear() : Boolean { return (vastDocument.adPlacement == VAST2Translator.PLACEMENT_NONLINEAR); } /** * * @param evtName property name in vastDocument * @param evtType type of event * @return VASTTrackingEvent with the given evtType and the suitable URLs * */ private function addTrackingEvent(evtName:String, evtType:VASTTrackingEventType, trackingArray:Vector.<VASTTrackingEvent>): void { if(trackingArray && vastDocument[evtName] != null && vastDocument[evtName].length > 0) { var trkEvent:VASTTrackingEvent = new VASTTrackingEvent(evtType); var trkArray:Vector.<VASTUrl> = new Vector.<VASTUrl>; for each(var obj:Object in vastDocument[evtName]) { var url:VASTUrl = new VASTUrl(obj.url); trkArray.push(url); } trkEvent.urls = trkArray; trackingArray.push(trkEvent); } } private var mediaFactory:MediaFactory; private var clickThru:String; private var httpLoader:HTTPLoader; private var vastDocument:VAST2Translator; private var mediaFileResolver:IVAST2MediaFileResolver; private var vastTranslator:VAST2Translator; private var cacheBuster:CacheBuster; private var _adPlacement:String; CONFIG::LOGGING { private static const logger:Logger = Log.getLogger("org.osmf.vast.media.VAST2MediaGenerator"); } } }
/***************************************************** * * Copyright 2010 Eyewonder, LLC. All Rights Reserved. * ***************************************************** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * * The Initial Developer of the Original Code is Eyewonder, LLC. * Portions created by Eyewonder, LLC. are Copyright (C) 2010 * Eyewonder, LLC. A Limelight Networks Business. All Rights Reserved. * *****************************************************/ package org.osmf.vast.media { import __AS3__.vec.Vector; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Rectangle; import org.osmf.elements.ProxyElement; import org.osmf.elements.SWFLoader; import org.osmf.elements.VideoElement; import org.osmf.elements.beaconClasses.Beacon; import org.osmf.events.MediaElementEvent; import org.osmf.media.MediaElement; import org.osmf.media.MediaFactory; import org.osmf.media.URLResource; import org.osmf.metadata.Metadata; import org.osmf.traits.DisplayObjectTrait; import org.osmf.traits.MediaTraitType; import org.osmf.utils.HTTPLoader; import org.osmf.vast.model.VAST2MediaFile; import org.osmf.vast.model.VAST2Translator; import org.osmf.vast.model.VASTTrackingEvent; import org.osmf.vast.model.VASTTrackingEventType; import org.osmf.vast.model.VASTUrl; import org.osmf.vast.parser.base.VAST2CompanionElement; import org.osmf.vpaid.elements.VPAIDElement; import org.osmf.vpaid.metadata.VPAIDMetadata; CONFIG::LOGGING { import org.osmf.logging.Logger; import org.osmf.logging.Log; } /** * Utility class for creating MediaElements from a VASTDocument. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 */ public class VAST2MediaGenerator { /** * Constructor. * * @param mediaFileResolver The resolver to use when a VASTDocument * contains multiple representations of the same content (MediaFile). * If null, this object will use a DefaultVASTMediaFileResolver. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 */ public function VAST2MediaGenerator(mediaFileResolver:IVAST2MediaFileResolver=null, mediaFactory:MediaFactory=null) { super(); this.mediaFileResolver = mediaFileResolver != null ? mediaFileResolver : new DefaultVAST2MediaFileResolver(); this.mediaFactory = mediaFactory; } /** * Creates all relevant MediaElements from the specified VAST document. * * @param vastDocument The VASTDocument that holds the raw VAST information. * * @returns A Vector of MediaElements, where each MediaElement * represents a different VASTAd within the VASTDocument. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion OSMF 1.0 */ public function createMediaElements(vastDocument:VAST2Translator, vastPlacement:String = null,playerSize:Rectangle = null, translatorIndex:int = 0):Vector.<MediaElement> { var mediaElements:Vector.<MediaElement> = new Vector.<MediaElement>(); this.vastDocument = vastDocument; vastDocument.adPlacement = (vastPlacement == null)?vastDocument.PLACEMENT_LINEAR:vastPlacement; if(vastDocument.clickThruUrl != null || vastDocument.clickThruUrl != "") { clickThru = vastDocument.clickThruUrl } cacheBuster = new CacheBuster(); var trackingEvents:Vector.<VASTTrackingEvent> = new Vector.<VASTTrackingEvent>; var proxyChain:Vector.<ProxyElement> = new Vector.<ProxyElement>(); // Check for the Impressions. if (vastDocument.impressionArray != null && vastDocument.impressionArray.length > 0) { var impressionArray:Vector.<VASTUrl> = new Vector.<VASTUrl>; for each(var impressionObj:Object in vastDocument.impressionArray) { var impressionURL:VASTUrl = new VASTUrl(impressionObj.url); impressionArray.push(impressionURL); } } addTrackingEvent("trkClickThruEvent", VASTTrackingEventType.CLICK_THRU, trackingEvents); addTrackingEvent("errorArray", VASTTrackingEventType.ERROR, trackingEvents); addTrackingEvent("trkStartEvent", VASTTrackingEventType.START, trackingEvents); addTrackingEvent("trkMidPointEvent", VASTTrackingEventType.MIDPOINT, trackingEvents); addTrackingEvent("trkFirstQuartileEvent", VASTTrackingEventType.FIRST_QUARTILE, trackingEvents); addTrackingEvent("trkThirdQuartileEvent", VASTTrackingEventType.THIRD_QUARTILE, trackingEvents); addTrackingEvent("trkCompleteEvent", VASTTrackingEventType.COMPLETE, trackingEvents); addTrackingEvent("trkMuteEvent", VASTTrackingEventType.MUTE, trackingEvents); addTrackingEvent("trkCreativeViewEvent", VASTTrackingEventType.CREATIVE_VIEW, trackingEvents); addTrackingEvent("trkPauseEvent", VASTTrackingEventType.PAUSE,trackingEvents); addTrackingEvent("trkReplayEvent", VASTTrackingEventType.REPLAY, trackingEvents); addTrackingEvent("trkFullScreenEvent", VASTTrackingEventType.FULLSCREEN, trackingEvents); addTrackingEvent("trkStopEvent", VASTTrackingEventType.STOP, trackingEvents); addTrackingEvent("trkUnmuteEvent", VASTTrackingEventType.UNMUTE, trackingEvents); addTrackingEvent("trkCloseEvent", VASTTrackingEventType.CLOSE, trackingEvents); addTrackingEvent("trkRewindEvent", VASTTrackingEventType.REWIND, trackingEvents); addTrackingEvent("trkResumeEvent", VASTTrackingEventType.RESUME, trackingEvents); addTrackingEvent("trkExpandEvent", VASTTrackingEventType.EXPAND, trackingEvents); addTrackingEvent("trkCollapseEvent", VASTTrackingEventType.COLLAPSE, trackingEvents); addTrackingEvent("trkAcceptInvitationEvent", VASTTrackingEventType.ACCEPT_INVITATION, trackingEvents); addTrackingEvent("trkSkipEvent", VASTTrackingEventType.SKIP,trackingEvents ); addTrackingEvent("trkProgressEvent", VASTTrackingEventType.PROGRESS, trackingEvents); addTrackingEvent("trkExitFullScreenEvent", VASTTrackingEventType.EXIT_FULLSCREEN, trackingEvents ); addTrackingEvent("trkCloseLinearEvent", VASTTrackingEventType.CLOSE_LINEAR, trackingEvents ); // Check for Video. if (vastDocument.mediafileArray != null && vastDocument.mediafileArray.length > 0 && isLinear) { var mediaFileURL:Vector.<VAST2MediaFile> = new Vector.<VAST2MediaFile>; for each(var mediaObj:Object in vastDocument.mediafileArray) { var mediaFileObj:VAST2MediaFile = new VAST2MediaFile(); mediaFileObj.url = mediaObj.url; mediaFileObj.delivery = mediaObj.delivery; mediaFileObj.bitrate = mediaObj.bitrate; mediaFileObj.type = mediaObj.type; mediaFileObj.width = mediaObj.width; mediaFileObj.height = mediaObj.height; mediaFileObj.id = mediaObj.id; mediaFileObj.scalable = mediaObj.scalable; mediaFileObj.maintainAspectRatio = mediaObj.maintainAspectRatio; mediaFileObj.apiFramework = mediaObj.apiFramework; mediaFileURL.push(mediaFileObj); } // Resolve the correct one. var mediaFile:VAST2MediaFile = mediaFileResolver.resolveMediaFiles(mediaFileURL); if (mediaFile != null) { var mediaURL:String = mediaFile.url; // If streaming, we may need to strip off the extension. if (mediaFile.delivery == "streaming" && mediaFile.type != "application/x-shockwave-flash") { mediaURL = mediaURL.replace(/\.flv$|\.f4v$/i, ""); } var rootElement:MediaElement; if(mediaFile.type == "application/x-shockwave-flash" ||mediaFile.type == "swf" ) { if (mediaFile.scalable) { rootElement = new VPAIDElement(new URLResource(mediaFile.url), new SWFLoader(),playerSize.width,playerSize.height); } else { rootElement = new VPAIDElement(new URLResource(mediaFile.url), new SWFLoader(),mediaFile.width,mediaFile.height); } VPAIDMetadata(rootElement.getMetadata("org.osmf.vpaid.metadata.VPAIDMetadata")).addValue(VPAIDMetadata.NON_LINEAR_CREATIVE, false); } else { if (mediaFactory != null) { rootElement = mediaFactory.createMediaElement(new URLResource(mediaURL)) as VideoElement; //VideoElement(rootElement).smoothing = true; } else { rootElement = new VideoElement(new URLResource(mediaURL)); //VideoElement(rootElement).smoothing = true; } } var impressions:VASTImpressionProxyElement = new VAST2ImpressionProxyElement(impressionArray, null, rootElement, cacheBuster); var events:VASTTrackingProxyElement = new VAST2TrackingProxyElement(trackingEvents,null, impressions, cacheBuster,clickThru); var vastMediaElement:MediaElement = events; mediaElements.push(vastMediaElement); } } else if(vastDocument.nonlinearArray != null && vastDocument.nonlinearArray.length > 0 && isNonLinear) { //Non-linear check goes here. If available create VPAID Element for each(var element:Object in vastDocument.nonlinearArray) { if(element.creativeType == "application/x-shockwave-flash") { var vpaidElement:MediaElement = new VPAIDElement(new URLResource(element.URL), new SWFLoader()); var vpaidMetadata:Metadata = vpaidElement.getMetadata(VPAIDMetadata.NAMESPACE); vpaidMetadata.addValue(VPAIDMetadata.NON_LINEAR_CREATIVE, true); var impressionsNonLinear:VASTImpressionProxyElement = new VAST2ImpressionProxyElement(impressionArray, null, vpaidElement, cacheBuster); var eventsNonLinear:VASTTrackingProxyElement = new VAST2TrackingProxyElement(trackingEvents,null, impressionsNonLinear, cacheBuster, clickThru); var vastMediaElementNonLinear:MediaElement = eventsNonLinear; mediaElements.push(vastMediaElementNonLinear); } } } if(vastDocument.companionArray != null && vastDocument.companionArray.length > 0) { for each(var companionAd:VAST2CompanionElement in vastDocument.companionArray) { CONFIG::LOGGING { logger.debug("[VAST] Companion ad detected" + companionAd.staticResource); } var companionElement:CompanionElement = new CompanionElement(companionAd); companionElement.scriptPath = companionAd.staticResource; mediaElements.push(companionElement); } } return mediaElements; } private function get isLinear() : Boolean { return (vastDocument.adPlacement == VAST2Translator.PLACEMENT_LINEAR); } private function get isNonLinear() : Boolean { return (vastDocument.adPlacement == VAST2Translator.PLACEMENT_NONLINEAR); } /** * * @param evtName property name in vastDocument * @param evtType type of event * @return VASTTrackingEvent with the given evtType and the suitable URLs * */ private function addTrackingEvent(evtName:String, evtType:VASTTrackingEventType, trackingArray:Vector.<VASTTrackingEvent>): void { if(trackingArray && vastDocument[evtName] != null && vastDocument[evtName].length > 0) { var trkEvent:VASTTrackingEvent = new VASTTrackingEvent(evtType); var trkArray:Vector.<VASTUrl> = new Vector.<VASTUrl>; for each(var obj:Object in vastDocument[evtName]) { var url:VASTUrl = new VASTUrl(obj.url); trkArray.push(url); } trkEvent.urls = trkArray; trackingArray.push(trkEvent); } } private var mediaFactory:MediaFactory; private var clickThru:String; private var httpLoader:HTTPLoader; private var vastDocument:VAST2Translator; private var mediaFileResolver:IVAST2MediaFileResolver; private var vastTranslator:VAST2Translator; private var cacheBuster:CacheBuster; private var _adPlacement:String; CONFIG::LOGGING { private static const logger:Logger = Log.getLogger("org.osmf.vast.media.VAST2MediaGenerator"); } } }
allow fallback to a supported mediaFile, if mediaFiles list contains unsupported one (such as webm).
vast: allow fallback to a supported mediaFile, if mediaFiles list contains unsupported one (such as webm).
ActionScript
agpl-3.0
kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp
630a4f8b2e89d9455c2c8ceec500c72ee5333880
tests/GAv4/com/google/analytics/utils/FakeEnvironment.as
tests/GAv4/com/google/analytics/utils/FakeEnvironment.as
 package com.google.analytics.utils { public class FakeEnvironment extends Environment { private var _appName:String; private var _appVersion:Version; private var _url:String; private var _referrer:String; private var _documentTitle:String; private var _domainName:String; private var _locationPath:String; private var _locationSearch:String; private var _flashVersion:Version; private var _language:String; private var _languageEncoding:String; private var _operatingSystem:String; private var _playerType:String; private var _platform:String; private var _protocol:String; private var _screenWidth:Number; private var _screenHeight:Number; private var _screenColorDepth:String; private var _userAgent:String; private var _isInHTML:Boolean; private var _isAIR:Boolean; public function FakeEnvironment( appName:String = "", appVersion:Version = null, url:String = "", referrer:String = "", documentTitle:String = "", domainName:String = "", locationPath:String = "", locationSearch:String = "", flashVersion:Version = null, language:String = "", languageEncoding:String = "", operatingSystem:String = "", playerType:String = "", platform:String = "", protocol:String = null, screenWidth:Number = NaN, screenHeight:Number = NaN, screenColorDepth:String = "", userAgent:String = null, isInHTML:Boolean = false, isAIR:Boolean = false ) { super("", "", "", null); _appName = appName; _appVersion = appVersion; _url = url; _referrer = referrer; _documentTitle = documentTitle; _domainName = domainName; _locationPath = locationPath; _locationSearch = locationSearch; _flashVersion = flashVersion; _language = language; _languageEncoding = languageEncoding; _operatingSystem = operatingSystem; _playerType = playerType; _platform = platform; _protocol = protocol; _screenWidth = screenWidth; _screenHeight = screenHeight; _screenColorDepth = screenColorDepth; _userAgent = userAgent; _isInHTML = isInHTML; _isAIR = isAIR; } public override function get appName():String { return _appName; } public override function set appName( value:String ):void { _appName = value; } public override function get appVersion():Version { return _appVersion; } public override function set appVersion( value:Version ):void { _appVersion = value; } // ga_internal override function set url( value:String ):void // { // _url = value; // } public override function get locationSWFPath():String { return _url; } public override function get referrer():String { return _referrer; } public override function get documentTitle():String { return _documentTitle; } public override function get domainName():String { return _domainName; } public override function get locationPath():String { return _locationPath; } public override function get locationSearch():String { return _locationSearch; } public override function get flashVersion():Version { return _flashVersion; } public override function get language():String { return _language; } public override function get languageEncoding():String { return _languageEncoding; } public override function get operatingSystem():String { return _operatingSystem; } public override function get playerType():String { return _playerType; } public override function get platform():String { return _platform; } public override function get protocol():String { return _protocol; } public override function get screenWidth():Number { return _screenWidth; } public override function get screenHeight():Number { return _screenHeight; } public override function get screenColorDepth():String { return _screenColorDepth; } public override function get userAgent():String { return _userAgent; } public override function set userAgent( custom:String ):void { _userAgent = custom; } public override function isInHTML():Boolean { return _isInHTML; } public override function isAIR():Boolean { return _isAIR; } } }
 package com.google.analytics.utils { import core.version; public class FakeEnvironment extends Environment { private var _appName:String; private var _appVersion:version; private var _url:String; private var _referrer:String; private var _documentTitle:String; private var _domainName:String; private var _locationPath:String; private var _locationSearch:String; private var _flashVersion:version; private var _language:String; private var _languageEncoding:String; private var _operatingSystem:String; private var _playerType:String; private var _platform:String; private var _protocol:String; private var _screenWidth:Number; private var _screenHeight:Number; private var _screenColorDepth:String; private var _userAgent:String; private var _isInHTML:Boolean; private var _isAIR:Boolean; public function FakeEnvironment( appName:String = "", appVersion:version = null, url:String = "", referrer:String = "", documentTitle:String = "", domainName:String = "", locationPath:String = "", locationSearch:String = "", flashVersion:version = null, language:String = "", languageEncoding:String = "", operatingSystem:String = "", playerType:String = "", platform:String = "", protocol:String = null, screenWidth:Number = NaN, screenHeight:Number = NaN, screenColorDepth:String = "", userAgent:String = null, isInHTML:Boolean = false, isAIR:Boolean = false ) { super("", "", "", null); _appName = appName; _appVersion = appVersion; _url = url; _referrer = referrer; _documentTitle = documentTitle; _domainName = domainName; _locationPath = locationPath; _locationSearch = locationSearch; _flashVersion = flashVersion; _language = language; _languageEncoding = languageEncoding; _operatingSystem = operatingSystem; _playerType = playerType; _platform = platform; _protocol = protocol; _screenWidth = screenWidth; _screenHeight = screenHeight; _screenColorDepth = screenColorDepth; _userAgent = userAgent; _isInHTML = isInHTML; _isAIR = isAIR; } public override function get appName():String { return _appName; } public override function set appName( value:String ):void { _appName = value; } public override function get appVersion():version { return _appVersion; } public override function set appVersion( value:version ):void { _appVersion = value; } // ga_internal override function set url( value:String ):void // { // _url = value; // } public override function get locationSWFPath():String { return _url; } public override function get referrer():String { return _referrer; } public override function get documentTitle():String { return _documentTitle; } public override function get domainName():String { return _domainName; } public override function get locationPath():String { return _locationPath; } public override function get locationSearch():String { return _locationSearch; } public override function get flashVersion():version { return _flashVersion; } public override function get language():String { return _language; } public override function get languageEncoding():String { return _languageEncoding; } public override function get operatingSystem():String { return _operatingSystem; } public override function get playerType():String { return _playerType; } public override function get platform():String { return _platform; } public override function get protocol():String { return _protocol; } public override function get screenWidth():Number { return _screenWidth; } public override function get screenHeight():Number { return _screenHeight; } public override function get screenColorDepth():String { return _screenColorDepth; } public override function get userAgent():String { return _userAgent; } public override function set userAgent( custom:String ):void { _userAgent = custom; } public override function isInHTML():Boolean { return _isInHTML; } public override function isAIR():Boolean { return _isAIR; } } }
replace class Version by core.version
replace class Version by core.version
ActionScript
apache-2.0
nsdevaraj/gaforflash,minimedj/gaforflash,minimedj/gaforflash,nsdevaraj/gaforflash
aad3cfb01ab73053bd31c749489fa3e47c2f9363
src/com/mangui/HLS/streaming/Getter.as
src/com/mangui/HLS/streaming/Getter.as
package com.mangui.HLS.streaming { import com.mangui.HLS.*; import com.mangui.HLS.parsing.*; import com.mangui.HLS.utils.*; import flash.events.*; import flash.net.*; import flash.utils.*; /** Loader for hls streaming manifests. **/ public class Getter { /** Reference to the hls framework controller. **/ private var _hls:HLS; /** Array with levels. **/ private var _levels:Array = []; /** Object that fetches the manifest. **/ private var _urlloader:URLLoader; /** Link to the M3U8 file. **/ private var _url:String; /** Amount of playlists still need loading. **/ private var _toLoad:Number; /** are all playlists filled ? **/ private var _canStart:Boolean; /** initial reload timer **/ private var _fragmentDuration:Number = 5000; /** Timeout ID for reloading live playlists. **/ private var _timeoutID:Number; /** Streaming type (live, ondemand). **/ private var _type:String; /** last reload manifest time **/ private var _reload_playlists_timer:uint; /** Setup the loader. **/ public function Getter(hls:HLS) { _hls = hls; _hls.addEventListener(HLSEvent.STATE,_stateHandler); _levels = []; _urlloader = new URLLoader(); _urlloader.addEventListener(Event.COMPLETE,_loaderHandler); _urlloader.addEventListener(IOErrorEvent.IO_ERROR,_errorHandler); _urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,_errorHandler); }; /** Loading failed; return errors. **/ private function _errorHandler(event:ErrorEvent):void { var txt:String = "Cannot load M3U8: "+event.text; if(event is SecurityErrorEvent) { txt = "Cannot load M3U8: crossdomain access denied"; } else if (event is IOErrorEvent) { txt = "Cannot load M3U8: 404 not found"; } _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,txt)); }; /** return true if first two levels contain at least 2 fragments **/ private function _areFirstLevelsFilled():Boolean { for(var i:Number = 0; (i < _levels.length) && (i < 2); i++) { if(_levels[i].fragments.length < 2) { return false; } } return true; }; /** Return the current manifest. **/ public function getLevels():Array { return _levels; }; /** Return the stream type. **/ public function getType():String { return _type; }; /** Load the manifest file. **/ public function load(url:String):void { _url = url; _levels = []; _canStart = false; _reload_playlists_timer = getTimer(); _urlloader.load(new URLRequest(_url)); }; /** Manifest loaded; check and parse it **/ private function _loaderHandler(event:Event):void { _loadManifest(String(event.target.data)); }; /** load a playlist **/ private function _loadPlaylist(string:String,url:String,index:Number):void { if(string != null && string.length != 0) { var frags:Array = Manifest.getFragments(string,url); // set fragment and update sequence number range _levels[index].setFragments(frags); _levels[index].targetduration = Manifest.getTargetDuration(string); _levels[index].start_seqnum = frags[0].seqnum; _levels[index].end_seqnum = frags[frags.length-1].seqnum; _levels[index].duration = frags[frags.length-1].start + frags[frags.length-1].duration; } if(--_toLoad == 0) { // Check whether the stream is live or not finished yet if(Manifest.hasEndlist(string)) { _type = HLSTypes.VOD; } else { _type = HLSTypes.LIVE; var timeout:Number = Math.max(100,_reload_playlists_timer + _fragmentDuration - getTimer()); Log.txt("Live Playlist parsing finished: reload in " + timeout + " ms"); _timeoutID = setTimeout(_loadPlaylists,timeout); } if (!_canStart && (_canStart =_areFirstLevelsFilled())) { Log.txt("first 2 levels are filled with at least 2 fragments, notify event"); _fragmentDuration = frags[0].duration*1000; _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST,_levels)); } } }; /** load First Level Playlist **/ private function _loadManifest(string:String):void { // Check for M3U8 playlist or manifest. if(string.indexOf(Manifest.HEADER) == 0) { //1 level playlist, create unique level and parse playlist if(string.indexOf(Manifest.FRAGMENT) > 0) { var level:Level = new Level(); level.url = _url; _levels.push(level); _toLoad = 1; Log.txt("1 Level Playlist, load it"); _loadPlaylist(string,_url,0); } else if(string.indexOf(Manifest.LEVEL) > 0) { //adaptative playlist, extract levels from playlist, get them and parse them _levels = Manifest.extractLevels(string,_url); _loadPlaylists(); } } else { var message:String = "Manifest is not a valid M3U8 file" + _url; _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,message)); } }; /** load/reload all M3U8 playlists **/ private function _loadPlaylists():void { _reload_playlists_timer = getTimer(); _toLoad = _levels.length; //Log.txt("HLS Playlist, with " + _toLoad + " levels"); for(var i:Number = 0; i < _levels.length; i++) { new Manifest().loadPlaylist(_levels[i].url,_loadPlaylist,_errorHandler,i); } }; /** When the framework idles out, reloading is cancelled. **/ public function _stateHandler(event:HLSEvent):void { if(event.state == HLSStates.IDLE) { clearTimeout(_timeoutID); } }; } }
package com.mangui.HLS.streaming { import com.mangui.HLS.*; import com.mangui.HLS.parsing.*; import com.mangui.HLS.utils.*; import flash.events.*; import flash.net.*; import flash.utils.*; /** Loader for hls streaming manifests. **/ public class Getter { /** Reference to the hls framework controller. **/ private var _hls:HLS; /** Array with levels. **/ private var _levels:Array = []; /** Object that fetches the manifest. **/ private var _urlloader:URLLoader; /** Link to the M3U8 file. **/ private var _url:String; /** Amount of playlists still need loading. **/ private var _toLoad:Number; /** are all playlists filled ? **/ private var _canStart:Boolean; /** initial reload timer **/ private var _fragmentDuration:Number = 5000; /** Timeout ID for reloading live playlists. **/ private var _timeoutID:Number; /** Streaming type (live, ondemand). **/ private var _type:String; /** last reload manifest time **/ private var _reload_playlists_timer:uint; /** Setup the loader. **/ public function Getter(hls:HLS) { _hls = hls; _hls.addEventListener(HLSEvent.STATE,_stateHandler); _levels = []; _urlloader = new URLLoader(); _urlloader.addEventListener(Event.COMPLETE,_loaderHandler); _urlloader.addEventListener(IOErrorEvent.IO_ERROR,_errorHandler); _urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,_errorHandler); }; /** Loading failed; return errors. **/ private function _errorHandler(event:ErrorEvent):void { var txt:String = "Cannot load M3U8: "+event.text; if(event is SecurityErrorEvent) { txt = "Cannot load M3U8: crossdomain access denied"; } else if (event is IOErrorEvent) { txt = "Cannot load M3U8: 404 not found"; } _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,txt)); }; /** return true if first two levels contain at least 2 fragments **/ private function _areFirstLevelsFilled():Boolean { for(var i:Number = 0; (i < _levels.length) && (i < 2); i++) { if(_levels[i].fragments.length < 2) { return false; } } return true; }; /** Return the current manifest. **/ public function getLevels():Array { return _levels; }; /** Return the stream type. **/ public function getType():String { return _type; }; /** Load the manifest file. **/ public function load(url:String):void { _url = url; _levels = []; _canStart = false; _reload_playlists_timer = getTimer(); _urlloader.load(new URLRequest(_url)); }; /** Manifest loaded; check and parse it **/ private function _loaderHandler(event:Event):void { _loadManifest(String(event.target.data)); }; /** load a playlist **/ private function _loadPlaylist(string:String,url:String,index:Number):void { if(string != null && string.length != 0) { var frags:Array = Manifest.getFragments(string,url); // set fragment and update sequence number range _levels[index].setFragments(frags); _levels[index].targetduration = Manifest.getTargetDuration(string); _levels[index].start_seqnum = frags[0].seqnum; _levels[index].end_seqnum = frags[frags.length-1].seqnum; _levels[index].duration = frags[frags.length-1].start + frags[frags.length-1].duration; _fragmentDuration = _levels[index].targetduration; } if(--_toLoad == 0) { // Check whether the stream is live or not finished yet if(Manifest.hasEndlist(string)) { _type = HLSTypes.VOD; } else { _type = HLSTypes.LIVE; var timeout:Number = Math.max(100,_reload_playlists_timer + _fragmentDuration - getTimer()); Log.txt("Live Playlist parsing finished: reload in " + timeout + " ms"); _timeoutID = setTimeout(_loadPlaylists,timeout); } if (!_canStart && (_canStart =_areFirstLevelsFilled())) { Log.txt("first 2 levels are filled with at least 2 fragments, notify event"); _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST,_levels)); } } }; /** load First Level Playlist **/ private function _loadManifest(string:String):void { // Check for M3U8 playlist or manifest. if(string.indexOf(Manifest.HEADER) == 0) { //1 level playlist, create unique level and parse playlist if(string.indexOf(Manifest.FRAGMENT) > 0) { var level:Level = new Level(); level.url = _url; _levels.push(level); _toLoad = 1; Log.txt("1 Level Playlist, load it"); _loadPlaylist(string,_url,0); } else if(string.indexOf(Manifest.LEVEL) > 0) { //adaptative playlist, extract levels from playlist, get them and parse them _levels = Manifest.extractLevels(string,_url); _loadPlaylists(); } } else { var message:String = "Manifest is not a valid M3U8 file" + _url; _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,message)); } }; /** load/reload all M3U8 playlists **/ private function _loadPlaylists():void { _reload_playlists_timer = getTimer(); _toLoad = _levels.length; //Log.txt("HLS Playlist, with " + _toLoad + " levels"); for(var i:Number = 0; i < _levels.length; i++) { new Manifest().loadPlaylist(_levels[i].url,_loadPlaylist,_errorHandler,i); } }; /** When the framework idles out, reloading is cancelled. **/ public function _stateHandler(event:HLSEvent):void { if(event.state == HLSStates.IDLE) { clearTimeout(_timeoutID); } }; } }
use #EXT-X-TARGETDURATION for live playlist timer
use #EXT-X-TARGETDURATION for live playlist timer
ActionScript
mpl-2.0
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
3eb37406523487d71e9f8e41915b778955e46222
WeaveUI/src/weave/utils/ProbeTextUtils.as
WeaveUI/src/weave/utils/ProbeTextUtils.as
/* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Weave. If not, see <http://www.gnu.org/licenses/>. */ package weave.utils { import flash.display.Stage; import mx.controls.ToolTip; import mx.core.Application; import mx.core.IToolTip; import mx.managers.ToolTipManager; import mx.utils.ObjectUtil; import weave.Weave; import weave.api.data.IAttributeColumn; import weave.api.data.IKeySet; import weave.api.data.IQualifiedKey; import weave.api.primitives.IBounds2D; import weave.compiler.StringLib; import weave.core.LinkableHashMap; import weave.primitives.Bounds2D; import weave.visualization.layers.InteractiveVisualization; import weave.visualization.layers.SimpleInteractiveVisualization; /** * ProbeTextManager * A static class containing functions to manage a list of probed attribute columns * * @author adufilie */ public class ProbeTextUtils { public static function get probedColumns():LinkableHashMap { // this initializes the probed columns object map if not created yet, otherwise just returns the existing one return Weave.root.requestObject("Probed Columns", LinkableHashMap, true); } public static function get probeHeaderColumns():LinkableHashMap { return Weave.root.requestObject("Probe Header Columns", LinkableHashMap, true); } /** * getProbeText * @param keySet The key set you are interested in. * @param additionalColumns An array of additional columns (other than global probed columns) to be displayed in the probe tooltip * @param maxRecordsShown Maximum no. of records shown in one probe tooltip * @return A string to be displayed on a tooltip while probing */ public static function getProbeText(keySet:IKeySet, additionalColumns:Array = null):String { var result:String = ''; var columns:Array = probedColumns.getObjects(IAttributeColumn); if (additionalColumns != null) columns = columns.concat(additionalColumns); var headers:Array = probeHeaderColumns.getObjects(IAttributeColumn); var keys:Array = keySet.keys.concat().sort(ObjectUtil.compare); var key:IQualifiedKey; var recordCount:int = 0; var maxRecordsShown:Number = Weave.properties.maxTooltipRecordsShown.value; for (var iKey:int = 0; iKey < keys.length && iKey < maxRecordsShown; iKey++) { key = keys[iKey] as IQualifiedKey; var record:String = ''; for (var iHeader:int = 0; iHeader < headers.length; iHeader++) { var header:IAttributeColumn = headers[iHeader] as IAttributeColumn; var headerValue:String = StringLib.toString(header.getValueFromKey(key, String)); if (headerValue == '') continue; if (record != '') record += ', '; record += headerValue; } if (record != '') record += '\n'; var lookup:Object = new Object() ; for (var iColumn:int = 0; iColumn < columns.length; iColumn++) { var column:IAttributeColumn = columns[iColumn] as IAttributeColumn; var value:String = String(column.getValueFromKey(key, String)); if (value == '' || value == 'NaN') continue; var title:String = ColumnUtils.getTitle(column); var line:String = StringLib.lpad(value, 8) + ' (' + title + ')\n'; if(lookup[line] == undefined ) { record += line; lookup[line] = true; } } if (record != '') { result += record + '\n'; recordCount++; } } // remove ending '\n' while (result.substr(result.length - 1) == '\n') result = result.substr(0, result.length - 1); if (result == '') { result = 'Record Identifier' + (keys.length > 1 ? 's' : '') + ':\n'; for (var i:int = 0; i < keys.length && i < maxRecordsShown; i++) { key = keys[i] as IQualifiedKey; result += ' ' + key.keyType + '#' + key.localName + '\n'; recordCount++; } } if (recordCount >= maxRecordsShown && keys.length > maxRecordsShown) { result += '\n... (' + keys.length + ' records total, ' + recordCount + ' shown)'; } return result; } private static function setProbeToolTipAppearance():void { (probeToolTip as ToolTip).setStyle("backgroundAlpha", Weave.properties.probeToolTipBackgroundAlpha.value); if (isFinite(Weave.properties.probeToolTipBackgroundColor.value)) (probeToolTip as ToolTip).setStyle("backgroundColor", Weave.properties.probeToolTipBackgroundColor.value); } public static function showProbeToolTip(probeText:String, stageX:Number, stageY:Number, bounds:IBounds2D = null, margin:int = 5):void { if (bounds == null) { var stage:Stage = Application.application.stage; tempBounds.setBounds(stage.x, stage.y, stage.stageWidth, stage.stageHeight); bounds = tempBounds; } destroyProbeToolTip(); // create new tooltip probeToolTip = ToolTipManager.createToolTip(probeText, 0, 0); // make tooltip completely opaque because text + graphics on same sprite is slow setProbeToolTipAppearance() ; var xMin:Number = bounds.getXNumericMin(); var yMin:Number = bounds.getYNumericMin(); var xMax:Number = bounds.getXNumericMax() - probeToolTip.width; var yMax:Number = bounds.getYNumericMax() - probeToolTip.height; var b:Boolean = false; var yAxisToolTip:IToolTip = SimpleInteractiveVisualization.yAxisTooltipPtr ; var xAxisToolTip:IToolTip = SimpleInteractiveVisualization.xAxisTooltipPtr ; // calculate y coordinate var y:int; // calculate y pos depending on toolTipAbove setting if (toolTipAbove) { y = stageY - (probeToolTip.height + 2 * margin); if(yAxisToolTip != null) y = yAxisToolTip.y - margin - probeToolTip.height ; } else // below { y = stageY + margin * 2; if(yAxisToolTip != null) y = yAxisToolTip.y+yAxisToolTip.height+margin; } // flip y position if out of bounds if ((y < yMin && toolTipAbove) || (y > yMax && !toolTipAbove)) toolTipAbove = !toolTipAbove; // calculate x coordinate var x:int; if (cornerToolTip) { // want toolTip corner to be near probe point if (toolTipToTheLeft) { x = stageX - margin - probeToolTip.width; if(xAxisToolTip != null) x = xAxisToolTip.x - margin - probeToolTip.width; } else // to the right { x = stageX + margin; if(xAxisToolTip != null) x = xAxisToolTip.x+xAxisToolTip.width+margin; } // flip x position if out of bounds if ((x < xMin && toolTipToTheLeft) || (x > xMax && !toolTipToTheLeft)) toolTipToTheLeft = !toolTipToTheLeft; } else // center x coordinate { x = stageX - probeToolTip.width / 2; } // if at lower-right corner of mouse, shift to the right 10 pixels to get away from the mouse pointer if (x > stageX && y > stageY) x += 10; // enforce min/max values and position tooltip x = Math.max(xMin, Math.min(x, xMax)); y = Math.max(yMin, Math.min(y, yMax)); probeToolTip.move(x, y); } /** * cornerToolTip: * false = center of tooltip will be aligned with x probe coordinate * true = corner of tooltip will be aligned with x probe coordinate */ private static var cornerToolTip:Boolean = true; private static var toolTipAbove:Boolean = true; private static var toolTipToTheLeft:Boolean = false; private static var probeToolTip:IToolTip = null; private static const tempBounds:IBounds2D = new Bounds2D(); public static function destroyProbeToolTip():void { if (probeToolTip != null) { ToolTipManager.destroyToolTip(probeToolTip); probeToolTip = null; } } } }
/* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Weave. If not, see <http://www.gnu.org/licenses/>. */ package weave.utils { import flash.display.Stage; import mx.controls.ToolTip; import mx.core.Application; import mx.core.IToolTip; import mx.managers.ToolTipManager; import mx.utils.ObjectUtil; import weave.Weave; import weave.api.data.IAttributeColumn; import weave.api.data.IKeySet; import weave.api.data.IQualifiedKey; import weave.api.primitives.IBounds2D; import weave.compiler.StringLib; import weave.core.LinkableHashMap; import weave.primitives.Bounds2D; import weave.visualization.layers.InteractiveVisualization; import weave.visualization.layers.SimpleInteractiveVisualization; /** * ProbeTextManager * A static class containing functions to manage a list of probed attribute columns * * @author adufilie */ public class ProbeTextUtils { public static function get probedColumns():LinkableHashMap { // this initializes the probed columns object map if not created yet, otherwise just returns the existing one return Weave.root.requestObject("Probed Columns", LinkableHashMap, true); } public static function get probeHeaderColumns():LinkableHashMap { return Weave.root.requestObject("Probe Header Columns", LinkableHashMap, true); } /** * getProbeText * @param keySet The key set you are interested in. * @param additionalColumns An array of additional columns (other than global probed columns) to be displayed in the probe tooltip * @param maxRecordsShown Maximum no. of records shown in one probe tooltip * @return A string to be displayed on a tooltip while probing */ public static function getProbeText(keySet:IKeySet, additionalColumns:Array = null):String { var result:String = ''; var columns:Array = probedColumns.getObjects(IAttributeColumn); if (additionalColumns != null) columns = columns.concat(additionalColumns); var headers:Array = probeHeaderColumns.getObjects(IAttributeColumn); var keys:Array = keySet.keys.concat().sort(ObjectUtil.compare); var key:IQualifiedKey; var recordCount:int = 0; var maxRecordsShown:Number = Weave.properties.maxTooltipRecordsShown.value; for (var iKey:int = 0; iKey < keys.length && iKey < maxRecordsShown; iKey++) { key = keys[iKey] as IQualifiedKey; var record:String = ''; for (var iHeader:int = 0; iHeader < headers.length; iHeader++) { var header:IAttributeColumn = headers[iHeader] as IAttributeColumn; var headerValue:String = StringLib.toString(header.getValueFromKey(key, String)); if (headerValue == '') continue; if (record != '') record += ', '; record += headerValue; } if (record != '') record += '\n'; var lookup:Object = new Object() ; for (var iColumn:int = 0; iColumn < columns.length; iColumn++) { var column:IAttributeColumn = columns[iColumn] as IAttributeColumn; var value:String = String(column.getValueFromKey(key, String)); if (value == '' || value == 'NaN') continue; var title:String = ColumnUtils.getTitle(column); var line:String = StringLib.lpad(value, 8) + ' (' + title + ')\n'; if(lookup[line] == undefined ) { if (!(value.toLowerCase() == 'undefined' || title.toLowerCase() == 'undefined')) { record += line; lookup[line] = true; } } } if (record != '') { result += record + '\n'; recordCount++; } } // remove ending '\n' while (result.substr(result.length - 1) == '\n') result = result.substr(0, result.length - 1); if (result == '') { result = 'Record Identifier' + (keys.length > 1 ? 's' : '') + ':\n'; for (var i:int = 0; i < keys.length && i < maxRecordsShown; i++) { key = keys[i] as IQualifiedKey; result += ' ' + key.keyType + '#' + key.localName + '\n'; recordCount++; } } if (recordCount >= maxRecordsShown && keys.length > maxRecordsShown) { result += '\n... (' + keys.length + ' records total, ' + recordCount + ' shown)'; } return result; } private static function setProbeToolTipAppearance():void { (probeToolTip as ToolTip).setStyle("backgroundAlpha", Weave.properties.probeToolTipBackgroundAlpha.value); if (isFinite(Weave.properties.probeToolTipBackgroundColor.value)) (probeToolTip as ToolTip).setStyle("backgroundColor", Weave.properties.probeToolTipBackgroundColor.value); } public static function showProbeToolTip(probeText:String, stageX:Number, stageY:Number, bounds:IBounds2D = null, margin:int = 5):void { if (bounds == null) { var stage:Stage = Application.application.stage; tempBounds.setBounds(stage.x, stage.y, stage.stageWidth, stage.stageHeight); bounds = tempBounds; } destroyProbeToolTip(); // create new tooltip probeToolTip = ToolTipManager.createToolTip(probeText, 0, 0); // make tooltip completely opaque because text + graphics on same sprite is slow setProbeToolTipAppearance() ; var xMin:Number = bounds.getXNumericMin(); var yMin:Number = bounds.getYNumericMin(); var xMax:Number = bounds.getXNumericMax() - probeToolTip.width; var yMax:Number = bounds.getYNumericMax() - probeToolTip.height; var b:Boolean = false; var yAxisToolTip:IToolTip = SimpleInteractiveVisualization.yAxisTooltipPtr ; var xAxisToolTip:IToolTip = SimpleInteractiveVisualization.xAxisTooltipPtr ; // calculate y coordinate var y:int; // calculate y pos depending on toolTipAbove setting if (toolTipAbove) { y = stageY - (probeToolTip.height + 2 * margin); if(yAxisToolTip != null) y = yAxisToolTip.y - margin - probeToolTip.height ; } else // below { y = stageY + margin * 2; if(yAxisToolTip != null) y = yAxisToolTip.y+yAxisToolTip.height+margin; } // flip y position if out of bounds if ((y < yMin && toolTipAbove) || (y > yMax && !toolTipAbove)) toolTipAbove = !toolTipAbove; // calculate x coordinate var x:int; if (cornerToolTip) { // want toolTip corner to be near probe point if (toolTipToTheLeft) { x = stageX - margin - probeToolTip.width; if(xAxisToolTip != null) x = xAxisToolTip.x - margin - probeToolTip.width; } else // to the right { x = stageX + margin; if(xAxisToolTip != null) x = xAxisToolTip.x+xAxisToolTip.width+margin; } // flip x position if out of bounds if ((x < xMin && toolTipToTheLeft) || (x > xMax && !toolTipToTheLeft)) toolTipToTheLeft = !toolTipToTheLeft; } else // center x coordinate { x = stageX - probeToolTip.width / 2; } // if at lower-right corner of mouse, shift to the right 10 pixels to get away from the mouse pointer if (x > stageX && y > stageY) x += 10; // enforce min/max values and position tooltip x = Math.max(xMin, Math.min(x, xMax)); y = Math.max(yMin, Math.min(y, yMax)); probeToolTip.move(x, y); } /** * cornerToolTip: * false = center of tooltip will be aligned with x probe coordinate * true = corner of tooltip will be aligned with x probe coordinate */ private static var cornerToolTip:Boolean = true; private static var toolTipAbove:Boolean = true; private static var toolTipToTheLeft:Boolean = false; private static var probeToolTip:IToolTip = null; private static const tempBounds:IBounds2D = new Bounds2D(); public static function destroyProbeToolTip():void { if (probeToolTip != null) { ToolTipManager.destroyToolTip(probeToolTip); probeToolTip = null; } } } }
Fix Bug#283 Stop bar chart from showing "Undefined" column in probe
Fix Bug#283 Stop bar chart from showing "Undefined" column in probe
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
e5b6a0c5f9543fc2f9b5224748cf45a57b26c103
WEB-INF/lps/lfc/kernel/swf/LzMakeLoadSprite.as
WEB-INF/lps/lfc/kernel/swf/LzMakeLoadSprite.as
/** * LzMakeLoadSprite.as * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ /** * @access private */ var LzMakeLoadSprite = {}; /** * Makes the given view able to load a remote resource */ LzMakeLoadSprite.transform = function (v, src, cache, headers, filetype) { for (var k in this) { if (k != "transform") { if (typeof v[k] == 'function') { // replace old method with _methodname to support super v[ '___' + k ] = v[k]; } v[k] = this[k]; } } if (v.__LZmovieClipRef == null || ! v.__LZhaser) { //the view doesn't have the empty resource. We need to try and replace it v.makeContainerResource(); } v.createLoader(src, cache, headers, filetype); } /** * @access private */ LzMakeLoadSprite.createLoader = function (src, cache, headers, filetype) { this.loader = new LzMediaLoader(this, {}); this.updateDel = new LzDelegate(this, "updateAfterLoad", this.loader, "onloaddone"); this.errorDel = new LzDelegate(this, "__LZsendError", this.loader, "onerror"); this.timeoutDel = new LzDelegate(this, "__LZsendTimeout", this.loader, "ontimeout"); if (src != null) { this.setSource(src, cache, headers, filetype); } } /** * @access private * @param String src: The url from which to load the resource for this view. * @param String cache: If set, controls caching behavior. Choices are * "none" , "clientonly" , "serveronly" , "both" -- where both is the default. * @param String headers: Headers to send with the request (if any.) * @param String filetype: Filetype, e.g. 'mp3' or 'jpg'. If not specified, it will be derived from the URL. */ LzMakeLoadSprite.setSource = function (src, cache, headers, filetype) { // unload anything currently loading... if (this.loader.mc.loading == true) { LzLoadQueue.unloadRequest(this.loader.mc); } if (src == '' || src == ' ' || src == null) { if ($debug) Debug.error('setSource called with an empty url'); return; } this.stopTrackPlay(); this.isloaded = false; if (this.queuedplayaction == null) { this.queuePlayAction("checkPlayStatus"); } this.resource = src; //this.owner.resource = src; //if (this.owner.onresource) this.owner.onresource.sendEvent( src ); this.owner.__LZvizLoad = false; this.owner.__LZupdateShown(); this.loader.request(src, cache, headers, filetype); } /** * This method keeps the behavior of setResource consistent between * load-transformed views and those that aren't * @access private */ LzMakeLoadSprite.setResource = function (nresc) { // unload anything currently loading... if (this.loader.mc.loading == true) { LzLoadQueue.unloadRequest(this.loader.mc); } if (nresc == "empty") { // call shadowed setResource() this.___setResource(nresc); } else if (nresc.indexOf('http:') == 0 || nresc.indexOf('https:') == 0) { this.setSource(nresc); } else { this.loader.attachLoadMovie(nresc); if (this.queuedplayaction == null) { this.queuePlayAction("checkPlayStatus"); } // make sure resource is updated, but no "onload"-event is sent this.updateAfterLoad(null); // need to call manually because no "onload"-event was sent this.doQueuedPlayAction(); } } /** * Updates movieclip properties after the resource has loaded * @access private */ LzMakeLoadSprite.updateAfterLoad = function (mloader) { this.isloaded = true; var mc = this.getMCRef(); this.resourcewidth = mc._width; this.resourceheight = mc._height; this.currentframe = mc._currentframe; var tfchg = this.totalframes != mc._totalframes; if (tfchg) { this.totalframes = mc._totalframes; this.owner.resourceevent('totalframes', this.totalframes); } if (this.totalframes > 1) { this.checkPlayStatus(); } this.setHeight(this.hassetheight ? this.height : null); this.setWidth(this.hassetwidth ? this.width : null); // Install right-click context menu if there is one if (this.__contextmenu) mc.menu = this.__contextmenu.kernel.__LZcontextMenu(); this.owner.__LZvizLoad = true; this.owner.__LZupdateShown(); // skip event when called by setResource() var skip = (mloader == null); this.owner.resourceload({width: this.resourcewidth, height: this.resourceheight, resource: this.resource, skiponload: skip}); this.owner.reevaluateSize(); } /** * Unloads the media * @access private */ LzMakeLoadSprite.unload = function () { this.loader.unload(this.loader.mc); } /** * Get a reference to the control mc * @access private */ LzMakeLoadSprite.getMCRef = function () { //return null if not loaded if (this.loader.isaudio) return this.loader.mc; return this.isloaded ? this.loader.getLoadMC() : null; } /** * Get the number of bytes loaded so far * @return: A number that is the maximum offset for this resource */ LzMakeLoadSprite.getLoadBytes = function () { return this.getMCRef().getBytesLoaded(); } /** * Get the total number of bytes for the attached resource * @return: A number that is the maximum offset for this resource */ LzMakeLoadSprite.getMaxBytes = function () { return this.getMCRef().getBytesTotal(); } /** * @access private */ LzMakeLoadSprite.__LZsendError = function (e) { this.resourcewidth = 0; this.resourceheight = 0; if (this.owner) this.owner.resourceloaderror(e) } /** * @access private */ LzMakeLoadSprite.__LZsendTimeout = function (e) { this.resourcewidth = 0; this.resourceheight = 0; if (this.owner) this.owner.resourceloadtimeout(e) } /** * @access private */ LzMakeLoadSprite.destroy = function () { if ('updateDel' in this) this.updateDel.unregisterAll(); if ('errorDel' in this) this.errorDel.unregisterAll(); if ('timeoutDel' in this) this.timeoutDel.unregisterAll(); this.loader.unload(this.loader.mc); // call shadowed destroy() this.___destroy(); }
/** * LzMakeLoadSprite.as * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ /** * @access private */ var LzMakeLoadSprite = {}; /** * Makes the given view able to load a remote resource */ LzMakeLoadSprite.transform = function (v, src, cache, headers, filetype) { for (var k in this) { if (k != "transform") { if (typeof v[k] == 'function') { // replace old method with _methodname to support super v[ '___' + k ] = v[k]; } v[k] = this[k]; } } if (v.__LZmovieClipRef == null || ! v.__LZhaser) { //the view doesn't have the empty resource. We need to try and replace it v.makeContainerResource(); } v.createLoader(src, cache, headers, filetype); } /** * @access private */ LzMakeLoadSprite.createLoader = function (src, cache, headers, filetype) { this.loader = new LzMediaLoader(this, {}); this.updateDel = new LzDelegate(this, "updateAfterLoad", this.loader, "onloaddone"); this.errorDel = new LzDelegate(this, "__LZsendError", this.loader, "onerror"); this.timeoutDel = new LzDelegate(this, "__LZsendTimeout", this.loader, "ontimeout"); if (src != null) { this.setSource(src, cache, headers, filetype); } } /** * @access private * @param String src: The url from which to load the resource for this view. * @param String cache: If set, controls caching behavior. Choices are * "none" , "clientonly" , "serveronly" , "both" -- where both is the default. * @param String headers: Headers to send with the request (if any.) * @param String filetype: Filetype, e.g. 'mp3' or 'jpg'. If not specified, it will be derived from the URL. */ LzMakeLoadSprite.setSource = function (src, cache, headers, filetype) { // unload anything currently loading... if (this.loader.mc.loading == true) { LzLoadQueue.unloadRequest(this.loader.mc); } if (src == '' || src == ' ' || src == null) { if ($debug) Debug.error('setSource called with an empty url'); return; } this.stopTrackPlay(); this.isloaded = false; if (this.queuedplayaction == null) { this.queuePlayAction("checkPlayStatus"); } this.resource = src; //this.owner.resource = src; //if (this.owner.onresource) this.owner.onresource.sendEvent( src ); if (! this.__LZbuttonRef) { // only hide if we're not clickable - see LPP-4957 this.owner.__LZvizLoad = false; this.owner.__LZupdateShown(); } this.loader.request(src, cache, headers, filetype); } /** * This method keeps the behavior of setResource consistent between * load-transformed views and those that aren't * @access private */ LzMakeLoadSprite.setResource = function (nresc) { // unload anything currently loading... if (this.loader.mc.loading == true) { LzLoadQueue.unloadRequest(this.loader.mc); } if (nresc == "empty") { // call shadowed setResource() this.___setResource(nresc); } else if (nresc.indexOf('http:') == 0 || nresc.indexOf('https:') == 0) { this.setSource(nresc); } else { this.loader.attachLoadMovie(nresc); if (this.queuedplayaction == null) { this.queuePlayAction("checkPlayStatus"); } // make sure resource is updated, but no "onload"-event is sent this.updateAfterLoad(null); // need to call manually because no "onload"-event was sent this.doQueuedPlayAction(); } } /** * Updates movieclip properties after the resource has loaded * @access private */ LzMakeLoadSprite.updateAfterLoad = function (mloader) { this.isloaded = true; var mc = this.getMCRef(); this.resourcewidth = mc._width; this.resourceheight = mc._height; this.currentframe = mc._currentframe; var tfchg = this.totalframes != mc._totalframes; if (tfchg) { this.totalframes = mc._totalframes; this.owner.resourceevent('totalframes', this.totalframes); } if (this.totalframes > 1) { this.checkPlayStatus(); } this.setHeight(this.hassetheight ? this.height : null); this.setWidth(this.hassetwidth ? this.width : null); // Install right-click context menu if there is one if (this.__contextmenu) mc.menu = this.__contextmenu.kernel.__LZcontextMenu(); this.owner.__LZvizLoad = true; this.owner.__LZupdateShown(); // skip event when called by setResource() var skip = (mloader == null); this.owner.resourceload({width: this.resourcewidth, height: this.resourceheight, resource: this.resource, skiponload: skip}); this.owner.reevaluateSize(); } /** * Unloads the media * @access private */ LzMakeLoadSprite.unload = function () { this.loader.unload(this.loader.mc); } /** * Get a reference to the control mc * @access private */ LzMakeLoadSprite.getMCRef = function () { //return null if not loaded if (this.loader.isaudio) return this.loader.mc; return this.isloaded ? this.loader.getLoadMC() : null; } /** * Get the number of bytes loaded so far * @return: A number that is the maximum offset for this resource */ LzMakeLoadSprite.getLoadBytes = function () { return this.getMCRef().getBytesLoaded(); } /** * Get the total number of bytes for the attached resource * @return: A number that is the maximum offset for this resource */ LzMakeLoadSprite.getMaxBytes = function () { return this.getMCRef().getBytesTotal(); } /** * @access private */ LzMakeLoadSprite.__LZsendError = function (e) { this.resourcewidth = 0; this.resourceheight = 0; if (this.owner) this.owner.resourceloaderror(e) } /** * @access private */ LzMakeLoadSprite.__LZsendTimeout = function (e) { this.resourcewidth = 0; this.resourceheight = 0; if (this.owner) this.owner.resourceloadtimeout(e) } /** * @access private */ LzMakeLoadSprite.destroy = function () { if ('updateDel' in this) this.updateDel.unregisterAll(); if ('errorDel' in this) this.errorDel.unregisterAll(); if ('timeoutDel' in this) this.timeoutDel.unregisterAll(); this.loader.unload(this.loader.mc); // call shadowed destroy() this.___destroy(); }
Change 20081211-maxcarlson-I by [email protected] on 2008-12-11 01:08:07 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20081211-maxcarlson-I by [email protected] on 2008-12-11 01:08:07 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk Summary: Avoid hiding suring setSource for clickable sprites Bugs Fixed: LPP-4957 - onclick event lost after doing setSource onmouseover Technical Reviewer: [email protected] QA Reviewer: hminsky Details: Only hide sprite during setSource() if the sprite is not clickable - behavior now consistent across swf8, 9 and dhtml. Tests: See updated testcase for LPP-4957 git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@12066 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
5ab41e5f66d3724c7156cc86b2431e4eeca7bee7
src/aerys/minko/render/shader/node/leaf/Sampler.as
src/aerys/minko/render/shader/node/leaf/Sampler.as
package aerys.minko.render.shader.node.leaf { import aerys.minko.render.shader.compiler.visitor.IShaderNodeVisitor; import aerys.minko.render.shader.node.IFragmentNode; import aerys.minko.render.shader.node.INode; public class Sampler extends AbstractLeaf implements IFragmentNode { public static const _SAMPLER_FILTER_STRINGS:Vector.<String> = Vector.<String>(['nearest', 'linear']); public static const _SAMPLER_MIPMAP_STRINGS:Vector.<String> = Vector.<String>(['mipnone', 'mipnearest', 'miplinear']); public static const _SAMPLER_WRAPPING_STRINGS:Vector.<String> = Vector.<String>(['clamp', 'repeat']); public static const _SAMPLER_DIMENSION_STRINGS:Vector.<String> = Vector.<String>(['2d', 'cube', '3d']); public static const FILTER_NEAREST : uint = 0; public static const FILTER_LINEAR : uint = 1; public static const MIPMAP_DISABLE : uint = 0; public static const MIPMAP_NEAREST : uint = 1; public static const MIPMAP_LINEAR : uint = 2; public static const WRAPPING_CLAMP : uint = 0; public static const WRAPPING_REPEAT : uint = 1; public static const DIMENSION_2D : uint = 0; public static const DIMENSION_CUBE : uint = 1; protected var _id : uint; protected var _styleId : int; protected var _filter : uint; protected var _mipmap : uint; protected var _wrapping : uint; protected var _dimension : uint; override public function get size() : uint { return 0; } public function get styleId() : int { return _styleId; } public function get filter() : uint { return _filter; } public function get mipmap() : uint { return _mipmap; } public function get wrapping() : uint { return _wrapping; } public function get dimension() : uint { return _dimension; } public function get samplerId() : uint { return _id; } public function set samplerId(value : uint) : void { _id = value; } public function Sampler(styleId : int, filter : uint = FILTER_LINEAR, mipmap : uint = MIPMAP_DISABLE, wrapping : uint = WRAPPING_REPEAT, dimension : uint = DIMENSION_2D) { super(); _styleId = styleId; _filter = filter; _mipmap = mipmap; _wrapping = wrapping; _dimension = dimension; } override public function isSame(otherNode : INode) : Boolean { var samplerOtherNode : Sampler = otherNode as Sampler; if (samplerOtherNode == null) return false; return _styleId == samplerOtherNode._styleId && _filter == samplerOtherNode._filter && _mipmap == samplerOtherNode._mipmap && _wrapping == samplerOtherNode._wrapping && _dimension == samplerOtherNode._dimension } override public function toString() : String { return "Sampler\\nname=" + styleId; } } }
package aerys.minko.render.shader.node.leaf { import aerys.minko.render.shader.node.IFragmentNode; import aerys.minko.render.shader.node.INode; public class Sampler extends AbstractLeaf implements IFragmentNode { public static const _SAMPLER_FILTER_STRINGS:Vector.<String> = Vector.<String>(['nearest', 'linear']); public static const _SAMPLER_MIPMAP_STRINGS:Vector.<String> = Vector.<String>(['mipnone', 'mipnearest', 'miplinear']); public static const _SAMPLER_WRAPPING_STRINGS:Vector.<String> = Vector.<String>(['clamp', 'repeat']); public static const _SAMPLER_DIMENSION_STRINGS:Vector.<String> = Vector.<String>(['2d', 'cube', '3d']); public static const FILTER_NEAREST : uint = 0; public static const FILTER_LINEAR : uint = 1; public static const MIPMAP_DISABLE : uint = 0; public static const MIPMAP_NEAREST : uint = 1; public static const MIPMAP_LINEAR : uint = 2; public static const WRAPPING_CLAMP : uint = 0; public static const WRAPPING_REPEAT : uint = 1; public static const DIMENSION_2D : uint = 0; public static const DIMENSION_CUBE : uint = 1; protected var _id : uint; protected var _styleId : int; protected var _filter : uint; protected var _mipmap : uint; protected var _wrapping : uint; protected var _dimension : uint; override public function get size() : uint { return 0; } public function get styleId() : int { return _styleId; } public function get filter() : uint { return _filter; } public function get mipmap() : uint { return _mipmap; } public function get wrapping() : uint { return _wrapping; } public function get dimension() : uint { return _dimension; } public function get samplerId() : uint { return _id; } public function set samplerId(value : uint) : void { _id = value; } public function Sampler(styleId : int, filter : uint = FILTER_LINEAR, mipmap : uint = MIPMAP_DISABLE, wrapping : uint = WRAPPING_REPEAT, dimension : uint = DIMENSION_2D) { super(); _styleId = styleId; _filter = filter; _mipmap = mipmap; _wrapping = wrapping; _dimension = dimension; } override public function isSame(otherNode : INode) : Boolean { var samplerOtherNode : Sampler = otherNode as Sampler; if (samplerOtherNode == null) return false; return _styleId == samplerOtherNode._styleId && _filter == samplerOtherNode._filter && _mipmap == samplerOtherNode._mipmap && _wrapping == samplerOtherNode._wrapping && _dimension == samplerOtherNode._dimension } override public function toString() : String { return "Sampler\\nname=" + styleId; } } }
Remove unused import
Remove unused import
ActionScript
mit
aerys/minko-as3
acae4cba19bf1be697d25850f7f010557e8e3406
build-aux/base.as
build-aux/base.as
## -*- shell-script -*- ## base.as: This file is part of build-aux. ## Copyright (C) Gostai S.A.S., 2006-2008. ## ## This software is provided "as is" without warranty of any kind, ## either expressed or implied, including but not limited to the ## implied warranties of fitness for a particular purpose. ## ## See the LICENSE file for more information. ## For comments, bug reports and feedback: http://www.urbiforge.com ## m4_pattern_forbid([^_?URBI_])dnl # m4_define([_m4_divert(M4SH-INIT)], 5) m4_define([_m4_divert(URBI-INIT)], 10) m4_defun([_URBI_ABSOLUTE_PREPARE], [ # is_absolute PATH # ---------------- is_absolute () { case $[1] in ([[\\/]]* | ?:[[\\/]]*) return 0;; ( *) return 1;; esac } # absolute NAME -> ABS-NAME # ------------------------- # Return an absolute path to NAME. absolute () { local res AS_IF([is_absolute "$[1]"], [# Absolute paths do not need to be expanded. res=$[1]], [local dir=$(pwd)/$(dirname "$[1]") if test -d "$dir"; then res=$(cd "$dir" 2>/dev/null && pwd)/$(basename "$[1]") else fatal "absolute: not a directory: $dir" fi]) # On Windows, we must make sure we have a Windows-like UNIX-friendly path (of # the form C:/cygwin/path/to/somewhere instead of /path/to/somewhere, notice # the use of forward slashes in the Windows path. Windows *does* understand # paths with forward slashes). case $(uname -s) in (CYGWIN*) res=$(cygpath "$res") esac echo "$res" } ]) m4_defun([_URBI_FIND_PROG_PREPARE], [# find_prog PROG PATH # ------------------- # Return full path to PROG in PATH ($PATH_SEPARATOR separated), # nothing if not found. find_prog () { _AS_PATH_WALK([$[2]], [AS_IF([AS_TEST_X([$as_dir/$[1]])], [echo "$as_dir/$[1]"; break])]) } ]) m4_defun([_URBI_STDERR_PREPARE], [ # stderr LINES # ------------ stderr () { local i for i do echo >&2 "$as_me: $i" done echo >&2 } # error EXIT MESSAGES # ------------------- error () { local exit=$[1] shift stderr "$[@]" ex_exit $exit } # fatal MESSAGES # -------------- fatal () { # To help the user, just make sure that she is not confused between # the prototypes of fatal and error: the first argument is unlikely # to be integer. case $[1] in ([!0-9]) ;; (*) stderr "warning: possible confusion between fatal and error";; esac error 1 "$[@]" } # ex_to_string EXIT # ----------------- # Return a decoding of EXIT status if available, nothing otherwise. ex_to_string () { case $[1] in ( 0) echo ' (EX_OK: successful termination)';; ( 64) echo ' (EX_USAGE: command line usage error)';; ( 65) echo ' (EX_DATAERR: data format error)';; ( 66) echo ' (EX_NOINPUT: cannot open input)';; ( 67) echo ' (EX_NOUSER: addressee unknown)';; ( 68) echo ' (EX_NOHOST: host name unknown)';; ( 69) echo ' (EX_UNAVAILABLE: service unavailable)';; ( 70) echo ' (EX_SOFTWARE: internal software error)';; ( 71) echo ' (EX_OSERR: system error (e.g., cannot fork))';; ( 72) echo ' (EX_OSFILE: critical OS file missing)';; ( 73) echo ' (EX_CANTCREAT: cannot create (user) output file)';; ( 74) echo ' (EX_IOERR: input/output error)';; ( 75) echo ' (EX_TEMPFAIL: temp failure; user is invited to retry)';; ( 76) echo ' (EX_PROTOCOL: remote error in protocol)';; ( 77) echo ' (EX_NOPERM: permission denied)';; ( 78) echo ' (EX_CONFIG: configuration error)';; (176) echo ' (EX_SKIP: skip this test with unmet dependencies)';; (177) echo ' (EX_HARD: hard error that cannot be saved)';; (242) echo ' (killed by Valgrind)';; ( *) if test 127 -lt $[1]; then echo " (SIG$(kill -l $[1] || true))" fi;; esac } # ex_to_int CODE # -------------- # Decode the CODE and return the corresponding int. ex_to_int () { case $[1] in (OK |EX_OK) echo 0;; (USAGE |EX_USAGE) echo 64;; (DATAERR |EX_DATAERR) echo 65;; (NOINPUT |EX_NOINPUT) echo 66;; (NOUSER |EX_NOUSER) echo 67;; (NOHOST |EX_NOHOST) echo 68;; (UNAVAILABLE|EX_UNAVAILABLE) echo 69;; (SOFTWARE |EX_SOFTWARE) echo 70;; (OSERR |EX_OSERR) echo 71;; (OSFILE |EX_OSFILE) echo 72;; (CANTCREAT |EX_CANTCREAT) echo 73;; (IOERR |EX_IOERR) echo 74;; (TEMPFAIL |EX_TEMPFAIL) echo 75;; (PROTOCOL |EX_PROTOCOL) echo 76;; (NOPERM |EX_NOPERM) echo 77;; (CONFIG |EX_CONFIG) echo 78;; (SKIP |EX_SKIP) echo 176;; (HARD |EX_HARD) echo 177;; (*) echo $[1];; esac } ex_exit () { exit $(ex_to_int $[1]) } ]) # URBI_GET_OPTIONS # ---------------- # Generate get_options(). m4_define([URBI_GET_OPTIONS], [# Parse command line options get_options () { while test $[#] -ne 0; do case $[1] in (--*=*) opt=$(echo "$[1]" | sed -e 's/=.*//') val=$(echo "$[1]" | sed -e ['s/[^=]*=//']) shift set dummy "$opt" "$val" ${1+"$[@]"}; shift ;; esac case $[1] in $@ esac shift done } ]) m4_defun([_URBI_PREPARE], [ # truth TEST-ARGUMENTS... # ----------------------- # Run "test TEST-ARGUMENTS" and echo true/false depending on the result. truth () { if test "$[@]"; then echo true else echo false fi } _URBI_ABSOLUTE_PREPARE _URBI_FIND_PROG_PREPARE _URBI_STDERR_PREPARE ]) # URBI_PREPARE # ------------ # Output all the M4sh possible initialization into the initialization # diversion. m4_defun([URBI_PREPARE], [m4_divert_text([M4SH-INIT], [_URBI_PREPARE])dnl URBI_RST_PREPARE()dnl URBI_INSTRUMENT_PREPARE()dnl URBI_CHILDREN_PREPARE()dnl ]) # URBI_INIT # --------- # Replaces the AS_INIT invocation. # Must be defined via "m4_define", not "m4_defun" since it is AS_INIT # which will set up the diversions used for "m4_defun". m4_define([URBI_INIT], [AS_INIT()dnl URBI_PREPARE() set -e case $VERBOSE in (x) set -x;; esac : ${abs_builddir='@abs_builddir@'} : ${abs_top_builddir='@abs_top_builddir@'} : ${abs_top_srcdir='@abs_top_srcdir@'} ])
## -*- shell-script -*- ## base.as: This file is part of build-aux. ## Copyright (C) Gostai S.A.S., 2006-2008. ## ## This software is provided "as is" without warranty of any kind, ## either expressed or implied, including but not limited to the ## implied warranties of fitness for a particular purpose. ## ## See the LICENSE file for more information. ## For comments, bug reports and feedback: http://www.urbiforge.com ## m4_pattern_forbid([^_?URBI_])dnl # m4_define([_m4_divert(M4SH-INIT)], 5) m4_define([_m4_divert(URBI-INIT)], 10) m4_defun([_URBI_ABSOLUTE_PREPARE], [ # is_absolute PATH # ---------------- is_absolute () { case $[1] in ([[\\/]]* | ?:[[\\/]]*) return 0;; ( *) return 1;; esac } # absolute NAME -> ABS-NAME # ------------------------- # Return an absolute path to NAME. absolute () { local res AS_IF([is_absolute "$[1]"], [# Absolute paths do not need to be expanded. res=$[1]], [local dir=$(pwd)/$(dirname "$[1]") if test -d "$dir"; then res=$(cd "$dir" 2>/dev/null && pwd)/$(basename "$[1]") else fatal "absolute: not a directory: $dir" fi]) # On Windows, we must make sure we have a Windows-like UNIX-friendly path (of # the form C:/cygwin/path/to/somewhere instead of /path/to/somewhere, notice # the use of forward slashes in the Windows path. Windows *does* understand # paths with forward slashes). case $(uname -s) in (CYGWIN*) res=$(cygpath "$res") esac echo "$res" } ]) m4_defun([_URBI_FIND_PROG_PREPARE], [# find_prog PROG PATH # ------------------- # Return full path to PROG in PATH ($PATH_SEPARATOR separated), # nothing if not found. find_prog () { _AS_PATH_WALK([$[2]], [AS_IF([AS_TEST_X([$as_dir/$[1]])], [echo "$as_dir/$[1]"; break])]) } ]) m4_defun([_URBI_STDERR_PREPARE], [ # stderr LINES # ------------ stderr () { local i for i do echo >&2 "$as_me: $i" done echo >&2 } # error EXIT MESSAGES # ------------------- error () { local exit=$[1] shift stderr "$[@]" ex_exit $exit } # fatal MESSAGES # -------------- fatal () { # To help the user, just make sure that she is not confused between # the prototypes of fatal and error: the first argument is unlikely # to be integer. case $[1] in (*[[!0-9]]*|'') ;; (*) stderr "warning: possible confusion between fatal and error" \ "fatal $[*]";; esac error 1 "$[@]" } # ex_to_string EXIT # ----------------- # Return a decoding of EXIT status if available, nothing otherwise. ex_to_string () { case $[1] in ( 0) echo ' (EX_OK: successful termination)';; ( 64) echo ' (EX_USAGE: command line usage error)';; ( 65) echo ' (EX_DATAERR: data format error)';; ( 66) echo ' (EX_NOINPUT: cannot open input)';; ( 67) echo ' (EX_NOUSER: addressee unknown)';; ( 68) echo ' (EX_NOHOST: host name unknown)';; ( 69) echo ' (EX_UNAVAILABLE: service unavailable)';; ( 70) echo ' (EX_SOFTWARE: internal software error)';; ( 71) echo ' (EX_OSERR: system error (e.g., cannot fork))';; ( 72) echo ' (EX_OSFILE: critical OS file missing)';; ( 73) echo ' (EX_CANTCREAT: cannot create (user) output file)';; ( 74) echo ' (EX_IOERR: input/output error)';; ( 75) echo ' (EX_TEMPFAIL: temp failure; user is invited to retry)';; ( 76) echo ' (EX_PROTOCOL: remote error in protocol)';; ( 77) echo ' (EX_NOPERM: permission denied)';; ( 78) echo ' (EX_CONFIG: configuration error)';; (176) echo ' (EX_SKIP: skip this test with unmet dependencies)';; (177) echo ' (EX_HARD: hard error that cannot be saved)';; (242) echo ' (killed by Valgrind)';; ( *) if test 127 -lt $[1]; then echo " (SIG$(kill -l $[1] || true))" fi;; esac } # ex_to_int CODE # -------------- # Decode the CODE and return the corresponding int. ex_to_int () { case $[1] in (OK |EX_OK) echo 0;; (USAGE |EX_USAGE) echo 64;; (DATAERR |EX_DATAERR) echo 65;; (NOINPUT |EX_NOINPUT) echo 66;; (NOUSER |EX_NOUSER) echo 67;; (NOHOST |EX_NOHOST) echo 68;; (UNAVAILABLE|EX_UNAVAILABLE) echo 69;; (SOFTWARE |EX_SOFTWARE) echo 70;; (OSERR |EX_OSERR) echo 71;; (OSFILE |EX_OSFILE) echo 72;; (CANTCREAT |EX_CANTCREAT) echo 73;; (IOERR |EX_IOERR) echo 74;; (TEMPFAIL |EX_TEMPFAIL) echo 75;; (PROTOCOL |EX_PROTOCOL) echo 76;; (NOPERM |EX_NOPERM) echo 77;; (CONFIG |EX_CONFIG) echo 78;; (SKIP |EX_SKIP) echo 176;; (HARD |EX_HARD) echo 177;; (*) echo $[1];; esac } ex_exit () { exit $(ex_to_int $[1]) } ]) # URBI_GET_OPTIONS # ---------------- # Generate get_options(). m4_define([URBI_GET_OPTIONS], [# Parse command line options get_options () { while test $[#] -ne 0; do case $[1] in (--*=*) opt=$(echo "$[1]" | sed -e 's/=.*//') val=$(echo "$[1]" | sed -e ['s/[^=]*=//']) shift set dummy "$opt" "$val" ${1+"$[@]"}; shift ;; esac case $[1] in $@ esac shift done } ]) m4_defun([_URBI_PREPARE], [ # truth TEST-ARGUMENTS... # ----------------------- # Run "test TEST-ARGUMENTS" and echo true/false depending on the result. truth () { if test "$[@]"; then echo true else echo false fi } _URBI_ABSOLUTE_PREPARE _URBI_FIND_PROG_PREPARE _URBI_STDERR_PREPARE ]) # URBI_PREPARE # ------------ # Output all the M4sh possible initialization into the initialization # diversion. m4_defun([URBI_PREPARE], [m4_divert_text([M4SH-INIT], [_URBI_PREPARE])dnl URBI_RST_PREPARE()dnl URBI_INSTRUMENT_PREPARE()dnl URBI_CHILDREN_PREPARE()dnl ]) # URBI_INIT # --------- # Replaces the AS_INIT invocation. # Must be defined via "m4_define", not "m4_defun" since it is AS_INIT # which will set up the diversions used for "m4_defun". m4_define([URBI_INIT], [AS_INIT()dnl URBI_PREPARE() set -e case $VERBOSE in (x) set -x;; esac : ${abs_builddir='@abs_builddir@'} : ${abs_top_builddir='@abs_top_builddir@'} : ${abs_top_srcdir='@abs_top_srcdir@'} ])
Fix fatal (not the converse).
Fix fatal (not the converse). * build-aux/base.as (fatal): Beware of M4 quotation.
ActionScript
bsd-3-clause
aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport
95a41b2f8e781fb8fe099da928173079f0da4df0
as3/smartform/src/com/rpath/raf/util/ValidationHelper.as
as3/smartform/src/com/rpath/raf/util/ValidationHelper.as
/* # # Copyright (c) 2005-2009 rPath, Inc. # # All rights reserved # */ /* # # Copyright (c) 2009 rPath, Inc. # # This program is distributed under the terms of the MIT License as found # in a file called LICENSE. If it is not present, the license # is always available at http://www.opensource.org/licenses/mit-license.php. # # This program is distributed in the hope that it will be useful, but # without any waranty; without even the implied warranty of merchantability # or fitness for a particular purpose. See the MIT License for full details. */ package com.rpath.raf.util { import flash.events.IEventDispatcher; import flash.events.MouseEvent; import flash.utils.Dictionary; import mx.core.UIComponent; import mx.events.ValidationResultEvent; import mx.managers.ToolTipManager; import mx.validators.Validator; import mx.binding.utils.BindingUtils; [Bindable] public class ValidationHelper { public function ValidationHelper(vals:Array=null, target:*=null, property:String=null) { if (target && property) BindingUtils.bindProperty(target, property, this, ["isValid"], true, true); validators = vals; } public var isValid:Boolean; public function get validators():Array { return _validators; } private var _validators:Array; private var _vals:Array; private var _others:Array; public function set validators(vals:Array):void { var v:*; for each (v in _validators) { if (v is IEventDispatcher) { v.removeEventListener(ValidationResultEvent.VALID, validateNow); v.removeEventListener(ValidationResultEvent.INVALID, validateNow); } } _validators = vals; _vals = []; _others = []; for each (v in _validators) { if (v is Validator) { _vals.push(v); setupListeners(v); } else if (v is Array) { for each (var v2:* in v) { if (v2 is Validator) { _vals.push(v2); } else { _others.push(v2); } setupListeners(v2); } } else { _others.push(v); setupListeners(v); } } validateNow(); } protected function setupListeners(v:IEventDispatcher):void { v.addEventListener(ValidationResultEvent.VALID, validateNow,false,0,true); v.addEventListener(ValidationResultEvent.INVALID, validateNow,false,0,true); } /** * @private * Shows the tip immediately when the toolTip or errorTip property * becomes non-null and the mouse is over the target. */ public function showErrorImmediately(target:UIComponent):void { // we have to callLater this to avoid other fields that send events // that reset the timers and prevent the errorTip ever showing up. target.callLater(showDeferred, [target]); } private function showDeferred(target:UIComponent):void { var oldShowDelay:Number = ToolTipManager.showDelay; ToolTipManager.showDelay = 0; if (target.visible) { // try popping the resulting error flag via the hack // courtesy Adobe bug tracking system target.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OUT)); target.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OVER)); } ToolTipManager.showDelay = oldShowDelay; } public function clearErrorImmediately(target:UIComponent):void { target.callLater(clearDeferred, [target]); } private function clearDeferred(target:UIComponent):void { var oldDelay:Number = ToolTipManager.hideDelay; ToolTipManager.hideDelay = 0; if (target.visible) { // clear the errorTip try { target.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OVER)); target.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OUT)); } catch (e:Error) { // sometimes things aren't initialized fully when we try that trick } } ToolTipManager.hideDelay = oldDelay; } private var _validating:Boolean; public function validateNow(...args):void { if (!_validating) { _validating = true; var invalidValidators:Array = []; var seen:Dictionary = new Dictionary(); var validationEvent:ValidationResultEvent; var v:Validator; var vt:Object; // first test all validators, looking for invalid ones for each (v in _vals) { if (v.enabled) { vt = v.listener ? v.listener : v.source; if (vt && seen[vt] == undefined) { // careful not to send events! validationEvent = v.validate(null,true); if (validationEvent && validationEvent.type != ValidationResultEvent.VALID) { invalidValidators.push(v); seen[vt] = validationEvent; // send failures right away try { vt.validationResultHandler(seen[vt]); showErrorImmediately(vt as UIComponent); } catch (e:Error) { } } } } } // now all the valid validators that we haven't seen invalid // make sure we send a VALID event for each (v in _vals) { if (v.enabled) { vt = v.listener ? v.listener : v.source; if (vt && seen[vt] == undefined) { seen[vt] = true; try { vt.validationResultHandler(new ValidationResultEvent(ValidationResultEvent.VALID)); // make sure we clear any error flag clearErrorImmediately(vt as UIComponent); } catch (e:Error) { } } } } // are we valid overall? var valid:Boolean; valid = invalidValidators.length == 0; for each (var item:* in _others) { if (item.hasOwnProperty("isValid")) { valid = valid && item["isValid"]; } else if (item.hasOwnProperty("valid")) { valid = valid && item["valid"]; } } _validating = false; isValid = valid; } } public function checkAlso(...args):Boolean { var t:Boolean = isValid; for each (var b:Boolean in args) { t = t && b; if (!t) break; } return t; } } }
/* # # Copyright (c) 2005-2009 rPath, Inc. # # All rights reserved # */ /* # # Copyright (c) 2009 rPath, Inc. # # This program is distributed under the terms of the MIT License as found # in a file called LICENSE. If it is not present, the license # is always available at http://www.opensource.org/licenses/mit-license.php. # # This program is distributed in the hope that it will be useful, but # without any waranty; without even the implied warranty of merchantability # or fitness for a particular purpose. See the MIT License for full details. */ package com.rpath.raf.util { import flash.events.IEventDispatcher; import flash.events.MouseEvent; import flash.utils.Dictionary; import mx.core.UIComponent; import mx.events.ValidationResultEvent; import mx.managers.ToolTipManager; import mx.validators.Validator; import mx.binding.utils.BindingUtils; import mx.binding.utils.ChangeWatcher; [Bindable] public class ValidationHelper { public var target:*; private var cw:ChangeWatcher; public function ValidationHelper(vals:Array=null, target:*=null, property:String=null) { this.target = target; if (this.target && property) cw = BindingUtils.bindProperty(this.target, property, this, ["isValid"], true, true); validators = vals; } public var isValid:Boolean; public function get validators():Array { return _validators; } private var _validators:Array; private var _vals:Array; private var _others:Array; public function set validators(vals:Array):void { var v:*; for each (v in _validators) { if (v is IEventDispatcher) { v.removeEventListener(ValidationResultEvent.VALID, validateNow); v.removeEventListener(ValidationResultEvent.INVALID, validateNow); } } _validators = vals; _vals = []; _others = []; for each (v in _validators) { if (v is Validator) { _vals.push(v); setupListeners(v); } else if (v is Array) { for each (var v2:* in v) { if (v2 is Validator) { _vals.push(v2); } else { _others.push(v2); } setupListeners(v2); } } else { _others.push(v); setupListeners(v); } } validateNow(); } protected function setupListeners(v:IEventDispatcher):void { v.addEventListener(ValidationResultEvent.VALID, validateNow,false,0,true); v.addEventListener(ValidationResultEvent.INVALID, validateNow,false,0,true); } /** * @private * Shows the tip immediately when the toolTip or errorTip property * becomes non-null and the mouse is over the target. */ public function showErrorImmediately(target:UIComponent):void { // we have to callLater this to avoid other fields that send events // that reset the timers and prevent the errorTip ever showing up. target.callLater(showDeferred, [target]); } private function showDeferred(target:UIComponent):void { var oldShowDelay:Number = ToolTipManager.showDelay; ToolTipManager.showDelay = 0; if (target.visible) { // try popping the resulting error flag via the hack // courtesy Adobe bug tracking system target.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OUT)); target.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OVER)); } ToolTipManager.showDelay = oldShowDelay; } public function clearErrorImmediately(target:UIComponent):void { target.callLater(clearDeferred, [target]); } private function clearDeferred(target:UIComponent):void { var oldDelay:Number = ToolTipManager.hideDelay; ToolTipManager.hideDelay = 0; if (target.visible) { // clear the errorTip try { target.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OVER)); target.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OUT)); } catch (e:Error) { // sometimes things aren't initialized fully when we try that trick } } ToolTipManager.hideDelay = oldDelay; } private var _validating:Boolean; public function validateNow(...args):void { if (!_validating) { _validating = true; var invalidValidators:Array = []; var seen:Dictionary = new Dictionary(); var validationEvent:ValidationResultEvent; var v:Validator; var vt:Object; // first test all validators, looking for invalid ones for each (v in _vals) { if (v.enabled) { vt = v.listener ? v.listener : v.source; if (vt && seen[vt] == undefined) { // careful not to send events! validationEvent = v.validate(null,true); if (validationEvent && validationEvent.type != ValidationResultEvent.VALID) { invalidValidators.push(v); seen[vt] = validationEvent; // send failures right away try { vt.validationResultHandler(seen[vt]); showErrorImmediately(vt as UIComponent); } catch (e:Error) { } } } } } // now all the valid validators that we haven't seen invalid // make sure we send a VALID event for each (v in _vals) { if (v.enabled) { vt = v.listener ? v.listener : v.source; if (vt && seen[vt] == undefined) { seen[vt] = true; try { vt.validationResultHandler(new ValidationResultEvent(ValidationResultEvent.VALID)); // make sure we clear any error flag clearErrorImmediately(vt as UIComponent); } catch (e:Error) { } } } } // are we valid overall? var valid:Boolean; valid = invalidValidators.length == 0; for each (var item:* in _others) { if (item.hasOwnProperty("isValid")) { valid = valid && item["isValid"]; } else if (item.hasOwnProperty("valid")) { valid = valid && item["valid"]; } } _validating = false; isValid = valid; } } public function checkAlso(...args):Boolean { var t:Boolean = isValid; for each (var b:Boolean in args) { t = t && b; if (!t) break; } return t; } } }
Fix for nasty bug in ValidationHelper. GC was collecting the Binding before it could be triggered
Fix for nasty bug in ValidationHelper. GC was collecting the Binding before it could be triggered
ActionScript
apache-2.0
sassoftware/smartform
47ba48950a0c04ec0f366e6db4501cdf542e9f79
WEB-INF/lps/lfc/kernel/swf9/LzTextSprite.as
WEB-INF/lps/lfc/kernel/swf9/LzTextSprite.as
/** * LzTextSprite.as * * @copyright Copyright 2007, 2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 * @author Henry Minsky &lt;[email protected]&gt; */ public class LzTextSprite extends LzSprite { #passthrough (toplevel:true) { import flash.display.*; import flash.events.*; import flash.text.*; import flash.net.URLRequest; }# #passthrough { public var textfield:TextField = null; public static var PAD_TEXTWIDTH:Number = 4; public static var DEFAULT_SIZE = 11; var font = null; public var lineheight = 11; public var textcolor = 0; public var text:String = ""; public var resize:Boolean = true; public var multiline:Boolean = false; public var underline:Boolean = false; public var sizeToHeight:Boolean = false; public var password:Boolean = false; public var scrollheight:Number = 0; public function LzTextSprite (newowner = null, args = null) { super(newowner,false); // owner:*, isroot:Boolean this.textfield = createTextField(0,0,400,20); } override public function setClickable( c:Boolean ):void { if (this.clickable == c) return; this.textfield.mouseEnabled = c || this.textfield.selectable; this.setCancelBubbling(); this.clickable = c; if (c) { attachMouseEvents(this.textfield); } else { removeMouseEvents(this.textfield); } } // turn on/off canceling of mouse event bubbling private function setCancelBubbling():void { var dobj:DisplayObject = this.textfield; // base on the displayobject's mouseenabled property - on for selectable var prevent = this.textfield.mouseEnabled; // if clickable is on, we don't want to cancel events if (this.clickable) prevent = false; if (prevent) { dobj.addEventListener(MouseEvent.CLICK, __ignoreMouseEvent); dobj.addEventListener(MouseEvent.DOUBLE_CLICK, __ignoreMouseEvent); dobj.addEventListener(MouseEvent.MOUSE_DOWN, __ignoreMouseEvent); dobj.addEventListener(MouseEvent.MOUSE_UP, __ignoreMouseEvent); dobj.addEventListener(MouseEvent.MOUSE_OVER, __ignoreMouseEvent); dobj.addEventListener(MouseEvent.MOUSE_OUT, __ignoreMouseEvent); } else { dobj.removeEventListener(MouseEvent.CLICK, __ignoreMouseEvent); dobj.removeEventListener(MouseEvent.DOUBLE_CLICK, __ignoreMouseEvent); dobj.removeEventListener(MouseEvent.MOUSE_DOWN, __ignoreMouseEvent); dobj.removeEventListener(MouseEvent.MOUSE_UP, __ignoreMouseEvent); dobj.removeEventListener(MouseEvent.MOUSE_OVER, __ignoreMouseEvent); dobj.removeEventListener(MouseEvent.MOUSE_OUT, __ignoreMouseEvent); } } private function __ignoreMouseEvent(e:MouseEvent) :void { e.stopPropagation(); } public function enableClickableLinks( enabled:Boolean):void { if (enabled) { addEventListener(TextEvent.LINK, textLinkHandler); } else { removeEventListener(TextEvent.LINK, textLinkHandler); } } public function textLinkHandler(e:TextEvent) { this.owner.ontextlink.sendEvent(e.text); } public function makeTextLink(str, value) { return '<a href="event:'+value+'">'+str+'</a>'; } override public function setWidth( w:* ):void { super.setWidth(w); if (w) { this.textfield.width = w; } } override public function setHeight( h:* ):void { super.setHeight(h); if (h) { this.textfield.height = h; } } private function createTextField(nx:Number, ny:Number, w:Number, h:Number):TextField { var tfield:TextField = new TextField(); tfield.x = nx; tfield.y = ny; tfield.width = w; tfield.height = h; tfield.border = false; tfield.mouseEnabled = false; //tfield.cacheAsBitmap = true; addChild(tfield); return tfield; } public function __initTextProperties (args:Object) { this.password = args.password ? true : false; var textclip:TextField = this.textfield; textclip.displayAsPassword = this.password; textclip.selectable = args.selectable; textclip.autoSize = TextFieldAutoSize.NONE; // TODO [hqm 2008-01] have to figure out how the Flex textfield multiline // maps to Laszlo model. this.setMultiline( args.multiline ); //inherited attributes, documented in view this.fontname = args.font; this.fontsize = args.fontsize; this.fontstyle = args.fontstyle; textclip.background = false; // multiline text fields are left justified if (args.multiline) { textclip.autoSize = TextFieldAutoSize.LEFT; } // 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 && typeof(args.$refs.width) != "function") // 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) { this.sizeToHeight = true; } else if (! (args.height is LzValueExpr)) { // Does setting height of the text object do the right thing in swf9? textclip.height = args.height; } // Default the scrollheight to the visible height. this.scrollheight = this.height; // TODO [hqm 2008-01] There ought to be only call to // __setFormat during instantiation of an lzText. Figure // out how to suppress the other calls from setters. this.__setFormat(); this.setText(args.text); if (this.sizeToHeight) { //text and format is set, measure it var lm:TextLineMetrics = textclip.getLineMetrics(0); var h = lm.ascent + lm.descent + lm.leading; //TODO [anba 20080602] is this ok for multiline? if (this.multiline) h *= textclip.numLines; h += 4;//2*2px gutter, see flash docs for flash.text.TextLineMetrics this.setHeight(h); } } override public function setBGColor( c:* ):void { if (c == null) { this.textfield.background = false; } else { this.textfield.background = true; this.textfield.backgroundColor = c; } } public function setBorder ( onroff:Boolean):void { this.textfield.border = (onroff == true); } public function setEmbedFonts ( onroff:Boolean ):void { this.textfield.embedFonts = (onroff == true); } /* * setFontSize( Number:size ) o Sets the size of the font in pixels */ public function setFontSize ( fsize:String ):void { this.fontsize = fsize; this.__setFormat(); // force recompute of height if needed this.setText( this.text ); } public function setFontStyle ( fstyle:String ):void { this.fontstyle = fstyle; this.__setFormat(); // force recompute of height if needed this.setText( this.text ); } /* setFontName( String:name ) o Sets the name of the font o Can be a comma-separated list of font names */ override public function setFontName ( fname:String , prop=null):void{ this.fontname = fname; this.__setFormat(); // force recompute of height if needed this.setText( this.text ); } function setFontInfo () { this.font = LzFontManager.getFont( this.fontname , this.fontstyle ); //Debug.write('setFontInfo this.font = ', this.font, 'this.fontname = ', this.fontname, this.fontstyle); if (this.font != null) { //Debug.write('font.leading', this.font.leading, 'font.height = ',this.font.height, 'fontsize =',this.fontsize); this.lineheight = Number(this.font.leading) + ( Number(this.font.height) * Number(this.fontsize) / DEFAULT_SIZE ); } } /** * Sets the color of all the text in the field to the given hex color. * @param Number c: The color for the text -- from 0x0 (black) to 0xFFFFFF (white) */ public override function setColor ( col:* ):void { if (col != null) { this.textcolor = col; this.__setFormat(); this.setText( this.text ); } } public function appendText( t:String ):void { this.textfield.appendText(t); this.text = this.textfield.text; } public function getText():String { return this.text; } /** setText( String:text ) o Sets the contents to the specified text o Uses the widthchange callback method if multiline is false and text is not resizable o Uses the heightchange callback method if multiline is true */ /** * setText sets the text of the field to display * @param String t: the string to which to set the text */ public function setText ( t:String ):void { //this.textfield.cacheAsBitmap = false; if (t == null || typeof(t) == 'undefined' || t == 'null') { t = ""; } else if (typeof(t) != "string") { t = t.toString(); } this.text = t; this.textfield.htmlText = t; if (this.resize && (this.multiline == false)) { // single line resizable fields adjust their width to match the text var w:Number = this.getTextWidth(); //Debug.write('lztextsprite resize setwidth ', w, this.lzheight ); if (w != this.lzwidth) { this.setWidth(w); } } //multiline resizable fields adjust their height if (this.sizeToHeight) { if (this.multiline) { //FIXME [20080602 anba] won't possibly work, example: //textfield.textHeight=100 //textfield.height=10 //=> setHeight(Math.max(100, 10)) == setHeight(100) //setHeight sets textfield.height to 100 //next round: //textfield.textHeight=10 (new text was entered) //textfield.height=100 (set above!) //=> setHeight(Math.max(10, 100)) == setHeight(100) // => textfield.height still 100, sprite-height didn't change, but it should! this.setHeight(Math.max(this.textfield.textHeight, this.textfield.height)); } } //this.textfield.cacheAsBitmap = true; } /** * Sets the format string for the text field. * @access private */ public function __setFormat ():void { this.setFontInfo(); var cfontname = LzFontManager.__fontnameCacheMap[this.fontname]; if (cfontname == null) { cfontname = LzFontManager.__findMatchingFont(this.fontname); LzFontManager.__fontnameCacheMap[this.fontname] = cfontname; //Debug.write("caching fontname", this.fontname, cfontname); } // Debug.write("__setFormat this.font=", this.font, 'this.fontname = ',this.fontname, //'cfontname=', cfontname); var tf:TextFormat = new TextFormat(); tf.kerning = true; tf.size = this.fontsize; tf.font = (this.font == null ? cfontname : this.font.name); tf.color = this.textcolor; // If there is no font found, assume a device font if (this.font == null) { this.textfield.embedFonts = false; } else { this.textfield.embedFonts = true; } if (this.fontstyle == "bold" || this.fontstyle =="bolditalic"){ tf.bold = true; } if (this.fontstyle == "italic" || this.fontstyle =="bolditalic"){ tf.italic = true; } if (this.underline){ tf.underline = true; } this.textfield.defaultTextFormat = tf; } public function setMultiline ( ml:Boolean ):void { this.multiline = (ml == true); if (this.multiline) { this.textfield.multiline = true; this.textfield.wordWrap = true; } else { this.textfield.multiline = false; this.textfield.wordWrap = false; } } /** * Sets the selectability (with Ibeam cursor) of the text field * @param Boolean isSel: true if the text may be selected by the user */ public function setSelectable ( isSel:Boolean ):void { this.textfield.selectable = isSel; this.textfield.mouseEnabled = isSel || this.clickable; this.setCancelBubbling(); } public function getTextWidth ( ):Number { var tf:TextField = this.textfield; var ml:Boolean = tf.multiline; var mw:Boolean = tf.wordWrap; tf.multiline = false; tf.wordWrap = false; var twidth:Number = (tf.textWidth == 0) ? 0 : tf.textWidth + LzTextSprite.PAD_TEXTWIDTH; tf.multiline = ml; tf.wordWrap = mw; return twidth; } public function getTextHeight ( ):Number { return this.textfield.textHeight; } public function getTextfieldHeight ( ) { return this.textfield.height; } function setHScroll(s:Number) { this.textfield.scrollH = s; } function setAntiAliasType( aliasType:String ):void { var atype:String = (aliasType == 'advanced') ? flash.text.AntiAliasType.ADVANCED : flash.text.AntiAliasType.NORMAL; this.textfield.antiAliasType = atype; } function getAntiAliasType():String { return this.textfield.antiAliasType; } function setGridFit( gridFit ){} function getGridFit() {} function setSharpness( sharpness:Number ):void { this.textfield.sharpness = sharpness; } function getSharpness():Number { return this.textfield.sharpness; } function setThickness( thickness:Number ):void{ this.textfield.thickness = thickness; } function getThickness():Number { return this.textfield.thickness; } function setMaxLength(val:Number) { this.textfield.maxChars = val; } function setPattern ( val ){} function setSelection(start:Number, end:Number) { this.textfield.setSelection(start, end); } function setResize ( val:Boolean ) { this.resize = val; } function setScroll ( h:Number ) { this.textfield.scrollV = h; } function getScroll() { return this.textfield.scrollV; } function getMaxScroll() { return this.textfield.maxScrollV; } function getBottomScroll() { return this.textfield.bottomScrollV; } function setXScroll ( n ){ Debug.write("LzTextSprite.setXScroll not yet implemented"); } function setYScroll ( n ){ Debug.write("LzTextSprite.setYScroll not yet implemented"); } function setWordWrap ( wrap ){ Debug.write("LzTextSprite.setWordWrap not yet implemented"); } function getSelectionPosition() { return this.textfield.selectionBeginIndex; } function getSelectionSize() { return this.textfield.selectionEndIndex - this.textfield.selectionBeginIndex; } }# }
/** * LzTextSprite.as * * @copyright Copyright 2007, 2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 * @author Henry Minsky &lt;[email protected]&gt; */ public class LzTextSprite extends LzSprite { #passthrough (toplevel:true) { import flash.display.*; import flash.events.*; import flash.text.*; import flash.net.URLRequest; }# #passthrough { public var textfield:TextField = null; public static var PAD_TEXTWIDTH:Number = 4; public static var DEFAULT_SIZE = 11; var font = null; public var lineheight = 11; public var textcolor = 0; public var text:String = ""; public var resize:Boolean = true; public var multiline:Boolean = false; public var underline:Boolean = false; public var sizeToHeight:Boolean = false; public var password:Boolean = false; public var scrollheight:Number = 0; public function LzTextSprite (newowner = null, args = null) { super(newowner,false); // owner:*, isroot:Boolean this.textfield = createTextField(0,0,400,20); } override public function setClickable( c:Boolean ):void { if (this.clickable == c) return; this.textfield.mouseEnabled = c || this.textfield.selectable; this.setCancelBubbling(); this.clickable = c; if (c) { attachMouseEvents(this.textfield); } else { removeMouseEvents(this.textfield); } } // turn on/off canceling of mouse event bubbling private function setCancelBubbling():void { var dobj:DisplayObject = this.textfield; // base on the displayobject's mouseenabled property - on for selectable var prevent = this.textfield.mouseEnabled; // if clickable is on, we don't want to cancel events if (this.clickable) prevent = false; if (prevent) { dobj.addEventListener(MouseEvent.CLICK, __ignoreMouseEvent); dobj.addEventListener(MouseEvent.DOUBLE_CLICK, __ignoreMouseEvent); dobj.addEventListener(MouseEvent.MOUSE_DOWN, __ignoreMouseEvent); dobj.addEventListener(MouseEvent.MOUSE_UP, __ignoreMouseEvent); dobj.addEventListener(MouseEvent.MOUSE_OVER, __ignoreMouseEvent); dobj.addEventListener(MouseEvent.MOUSE_OUT, __ignoreMouseEvent); } else { dobj.removeEventListener(MouseEvent.CLICK, __ignoreMouseEvent); dobj.removeEventListener(MouseEvent.DOUBLE_CLICK, __ignoreMouseEvent); dobj.removeEventListener(MouseEvent.MOUSE_DOWN, __ignoreMouseEvent); dobj.removeEventListener(MouseEvent.MOUSE_UP, __ignoreMouseEvent); dobj.removeEventListener(MouseEvent.MOUSE_OVER, __ignoreMouseEvent); dobj.removeEventListener(MouseEvent.MOUSE_OUT, __ignoreMouseEvent); } } private function __ignoreMouseEvent(e:MouseEvent) :void { e.stopPropagation(); } public function enableClickableLinks( enabled:Boolean):void { if (enabled) { addEventListener(TextEvent.LINK, textLinkHandler); } else { removeEventListener(TextEvent.LINK, textLinkHandler); } } public function textLinkHandler(e:TextEvent) { this.owner.ontextlink.sendEvent(e.text); } public function makeTextLink(str, value) { return '<a href="event:'+value+'">'+str+'</a>'; } override public function setWidth( w:* ):void { super.setWidth(w); if (w) { this.textfield.width = w; } } override public function setHeight( h:* ):void { super.setHeight(h); if (h) { this.textfield.height = h; } } private function createTextField(nx:Number, ny:Number, w:Number, h:Number):TextField { var tfield:TextField = new TextField(); tfield.x = nx; tfield.y = ny; tfield.width = w; tfield.height = h; tfield.border = false; tfield.mouseEnabled = false; tfield.tabEnabled = false; //tfield.cacheAsBitmap = true; addChild(tfield); return tfield; } public function __initTextProperties (args:Object) { this.password = args.password ? true : false; var textclip:TextField = this.textfield; textclip.displayAsPassword = this.password; textclip.antiAliasType = flash.text.AntiAliasType.ADVANCED; textclip.selectable = args.selectable; textclip.autoSize = TextFieldAutoSize.NONE; // TODO [hqm 2008-01] have to figure out how the Flex textfield multiline // maps to Laszlo model. this.setMultiline( args.multiline ); //inherited attributes, documented in view this.fontname = args.font; this.fontsize = args.fontsize; this.fontstyle = args.fontstyle; textclip.background = false; // multiline text fields are left justified if (args.multiline) { textclip.autoSize = TextFieldAutoSize.LEFT; } // 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 && typeof(args.$refs.width) != "function") // 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) { this.sizeToHeight = true; } else if (! (args.height is LzValueExpr)) { // Does setting height of the text object do the right thing in swf9? textclip.height = args.height; } // Default the scrollheight to the visible height. this.scrollheight = this.height; // TODO [hqm 2008-01] There ought to be only call to // __setFormat during instantiation of an lzText. Figure // out how to suppress the other calls from setters. this.__setFormat(); this.setText(args.text); if (this.sizeToHeight) { //text and format is set, measure it var lm:TextLineMetrics = textclip.getLineMetrics(0); var h = lm.ascent + lm.descent + lm.leading; //TODO [anba 20080602] is this ok for multiline? if (this.multiline) h *= textclip.numLines; h += 4;//2*2px gutter, see flash docs for flash.text.TextLineMetrics this.setHeight(h); } } override public function setBGColor( c:* ):void { if (c == null) { this.textfield.background = false; } else { this.textfield.background = true; this.textfield.backgroundColor = c; } } public function setBorder ( onroff:Boolean):void { this.textfield.border = (onroff == true); } public function setEmbedFonts ( onroff:Boolean ):void { this.textfield.embedFonts = (onroff == true); } /* * setFontSize( Number:size ) o Sets the size of the font in pixels */ public function setFontSize ( fsize:String ):void { this.fontsize = fsize; this.__setFormat(); // force recompute of height if needed this.setText( this.text ); } public function setFontStyle ( fstyle:String ):void { this.fontstyle = fstyle; this.__setFormat(); // force recompute of height if needed this.setText( this.text ); } /* setFontName( String:name ) o Sets the name of the font o Can be a comma-separated list of font names */ override public function setFontName ( fname:String , prop=null):void{ this.fontname = fname; this.__setFormat(); // force recompute of height if needed this.setText( this.text ); } function setFontInfo () { this.font = LzFontManager.getFont( this.fontname , this.fontstyle ); //Debug.write('setFontInfo this.font = ', this.font, 'this.fontname = ', this.fontname, this.fontstyle); if (this.font != null) { //Debug.write('font.leading', this.font.leading, 'font.height = ',this.font.height, 'fontsize =',this.fontsize); this.lineheight = Number(this.font.leading) + ( Number(this.font.height) * Number(this.fontsize) / DEFAULT_SIZE ); } } /** * Sets the color of all the text in the field to the given hex color. * @param Number c: The color for the text -- from 0x0 (black) to 0xFFFFFF (white) */ public override function setColor ( col:* ):void { if (col != null) { this.textcolor = col; this.__setFormat(); this.setText( this.text ); } } public function appendText( t:String ):void { this.textfield.appendText(t); this.text = this.textfield.text; } public function getText():String { return this.text; } /** setText( String:text ) o Sets the contents to the specified text o Uses the widthchange callback method if multiline is false and text is not resizable o Uses the heightchange callback method if multiline is true */ /** * setText sets the text of the field to display * @param String t: the string to which to set the text */ public function setText ( t:String ):void { //this.textfield.cacheAsBitmap = false; if (t == null || typeof(t) == 'undefined' || t == 'null') { t = ""; } else if (typeof(t) != "string") { t = t.toString(); } this.text = t; this.textfield.htmlText = t; if (this.resize && (this.multiline == false)) { // single line resizable fields adjust their width to match the text var w:Number = this.getTextWidth(); //Debug.write('lztextsprite resize setwidth ', w, this.lzheight ); if (w != this.lzwidth) { this.setWidth(w); } } //multiline resizable fields adjust their height if (this.sizeToHeight) { if (this.multiline) { //FIXME [20080602 anba] won't possibly work, example: //textfield.textHeight=100 //textfield.height=10 //=> setHeight(Math.max(100, 10)) == setHeight(100) //setHeight sets textfield.height to 100 //next round: //textfield.textHeight=10 (new text was entered) //textfield.height=100 (set above!) //=> setHeight(Math.max(10, 100)) == setHeight(100) // => textfield.height still 100, sprite-height didn't change, but it should! this.setHeight(Math.max(this.textfield.textHeight, this.textfield.height)); } } //this.textfield.cacheAsBitmap = true; } /** * Sets the format string for the text field. * @access private */ public function __setFormat ():void { this.setFontInfo(); var cfontname = LzFontManager.__fontnameCacheMap[this.fontname]; if (cfontname == null) { cfontname = LzFontManager.__findMatchingFont(this.fontname); LzFontManager.__fontnameCacheMap[this.fontname] = cfontname; //Debug.write("caching fontname", this.fontname, cfontname); } // Debug.write("__setFormat this.font=", this.font, 'this.fontname = ',this.fontname, //'cfontname=', cfontname); var tf:TextFormat = new TextFormat(); tf.kerning = true; tf.size = this.fontsize; tf.font = (this.font == null ? cfontname : this.font.name); tf.color = this.textcolor; // If there is no font found, assume a device font if (this.font == null) { this.textfield.embedFonts = false; } else { this.textfield.embedFonts = true; } if (this.fontstyle == "bold" || this.fontstyle =="bolditalic"){ tf.bold = true; } if (this.fontstyle == "italic" || this.fontstyle =="bolditalic"){ tf.italic = true; } if (this.underline){ tf.underline = true; } this.textfield.defaultTextFormat = tf; } public function setMultiline ( ml:Boolean ):void { this.multiline = (ml == true); if (this.multiline) { this.textfield.multiline = true; this.textfield.wordWrap = true; } else { this.textfield.multiline = false; this.textfield.wordWrap = false; } } /** * Sets the selectability (with Ibeam cursor) of the text field * @param Boolean isSel: true if the text may be selected by the user */ public function setSelectable ( isSel:Boolean ):void { this.textfield.selectable = isSel; this.textfield.mouseEnabled = isSel || this.clickable; this.setCancelBubbling(); } public function getTextWidth ( ):Number { var tf:TextField = this.textfield; var ml:Boolean = tf.multiline; var mw:Boolean = tf.wordWrap; tf.multiline = false; tf.wordWrap = false; var twidth:Number = (tf.textWidth == 0) ? 0 : tf.textWidth + LzTextSprite.PAD_TEXTWIDTH; tf.multiline = ml; tf.wordWrap = mw; return twidth; } public function getTextHeight ( ):Number { return this.textfield.textHeight; } public function getTextfieldHeight ( ) { return this.textfield.height; } function setHScroll(s:Number) { this.textfield.scrollH = s; } function setAntiAliasType( aliasType:String ):void { var atype:String = (aliasType == 'advanced') ? flash.text.AntiAliasType.ADVANCED : flash.text.AntiAliasType.NORMAL; this.textfield.antiAliasType = atype; } function getAntiAliasType():String { return this.textfield.antiAliasType; } function setGridFit( gridFit ){} function getGridFit() {} function setSharpness( sharpness:Number ):void { this.textfield.sharpness = sharpness; } function getSharpness():Number { return this.textfield.sharpness; } function setThickness( thickness:Number ):void{ this.textfield.thickness = thickness; } function getThickness():Number { return this.textfield.thickness; } function setMaxLength(val:Number) { this.textfield.maxChars = val; } function setPattern ( val ){} function setSelection(start:Number, end:Number) { this.textfield.setSelection(start, end); } function setResize ( val:Boolean ) { this.resize = val; } function setScroll ( h:Number ) { this.textfield.scrollV = h; } function getScroll() { return this.textfield.scrollV; } function getMaxScroll() { return this.textfield.maxScrollV; } function getBottomScroll() { return this.textfield.bottomScrollV; } function setXScroll ( n ){ Debug.write("LzTextSprite.setXScroll not yet implemented"); } function setYScroll ( n ){ Debug.write("LzTextSprite.setYScroll not yet implemented"); } function setWordWrap ( wrap ){ Debug.write("LzTextSprite.setWordWrap not yet implemented"); } function getSelectionPosition() { return this.textfield.selectionBeginIndex; } function getSelectionSize() { return this.textfield.selectionEndIndex - this.textfield.selectionBeginIndex; } }# }
Change 20080927-hqm-D by [email protected] on 2008-09-27 22:22:01 EDT in /Users/hqm/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20080927-hqm-D by [email protected] on 2008-09-27 22:22:01 EDT in /Users/hqm/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk Summary: enable advanced antialiasing on swf9 text by default New Features: Bugs Fixed: Technical Reviewer: dtemkin QA Reviewer: (pending) Doc Reviewer: (pending) Documentation: Release Notes: Details: + set antiAliasType='advanced' by default on all text sprites Tests: <text id="t1" font="Arial" fontsize="9" width="800">Lorem ipsum dolor sit amet</text> should appear antialiased, compared to <text id="t2" font="Arial" fontsize="9"antiAliasType="normal" width="800">Lorem ipsum dolor sit amet</text> git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@11257 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
1b99ffee5f6fc7b194106ea9ffeab1b7269a2d3e
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; import flash.utils.setTimeout; [SWF(width="640", height="480")] public class swfcat extends Sprite { /* David's bridge (nickname eRYaZuvY02FpExln) that also serves a crossdomain policy. */ private const DEFAULT_TOR_ADDR:Object = { // host: "173.255.221.44", 3VXRyxz67OeRoqHn host: "69.164.193.231", port: 9001 }; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; // Socket to facilitator. private var s_f:Socket; private var output_text:TextField; private var fac_addr:Object; public function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function swfcat() { output_text = new TextField(); output_text.width = 640; output_text.height = 480; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; addChild(output_text); puts("Starting."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String; puts("Parameters loaded."); fac_spec = this.loaderInfo.parameters["facilitator"]; if (!fac_spec) { puts("Error: no \"facilitator\" specification provided."); return; } puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = parse_addr_spec(fac_spec); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } main(); } /* The main logic begins here, after start-up issues are taken care of. */ private function main():void { s_f = new Socket(); s_f.addEventListener(Event.CONNECT, fac_connected); s_f.addEventListener(Event.CLOSE, function (e:Event):void { puts("Facilitator: closed connection."); setTimeout(main, FACILITATOR_POLL_INTERVAL); }); s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); }); s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); }); puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + "."); s_f.connect(fac_addr.host, fac_addr.port); } private function fac_connected(e:Event):void { puts("Facilitator: connected."); s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data); s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n"); } private function fac_data(e:ProgressEvent):void { var client_spec:String; var client_addr:Object; var proxy_pair:Object; client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8"); puts("Facilitator: got \"" + client_spec + "\""); client_addr = parse_addr_spec(client_spec); if (!client_addr) { puts("Error: Client spec must be in the form \"host:port\"."); return; } if (client_addr.host == "0.0.0.0" && client_addr.port == 0) { puts("Error: Facilitator has no clients."); return; } proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR); proxy_pair.connect(); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private static function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.Socket; import flash.utils.ByteArray; /* An instance of a client-relay connection. */ class ProxyPair { // Address ({host, port}) of client. private var addr_c:Object; // Address ({host, port}) of relay. private var addr_r:Object; // Socket to client. private var s_c:Socket; // Socket to relay. private var s_r:Socket; // Parent swfcat, for UI updates. private var ui:swfcat; private function log(msg:String):void { ui.puts(id() + ": " + msg) } // String describing this pair for output. private function id():String { return "<" + this.addr_c.host + ":" + this.addr_c.port + "," + this.addr_r.host + ":" + this.addr_r.port + ">"; } public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object) { this.ui = ui; this.addr_c = addr_c; this.addr_r = addr_r; } public function connect():void { s_r = new Socket(); s_r.addEventListener(Event.CONNECT, tor_connected); s_r.addEventListener(Event.CLOSE, function (e:Event):void { log("Tor: closed."); if (s_c.connected) s_c.close(); }); s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Tor: I/O error: " + e.text + "."); if (s_c.connected) s_c.close(); }); s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Tor: security error: " + e.text + "."); if (s_c.connected) s_c.close(); }); log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + "."); s_r.connect(addr_r.host, addr_r.port); } private function tor_connected(e:Event):void { log("Tor: connected."); s_c = new Socket(); s_c.addEventListener(Event.CONNECT, client_connected); s_c.addEventListener(Event.CLOSE, function (e:Event):void { log("Client: closed."); if (s_r.connected) s_r.close(); }); s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Client: I/O error: " + e.text + "."); if (s_r.connected) s_r.close(); }); s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Client: security error: " + e.text + "."); if (s_r.connected) s_r.close(); }); log("Client: connecting to " + addr_c.host + ":" + addr_c.port + "."); s_c.connect(addr_c.host, addr_c.port); } private function client_connected(e:Event):void { log("Client: connected."); s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_r.readBytes(bytes, 0, e.bytesLoaded); log("Tor: read " + bytes.length + "."); s_c.writeBytes(bytes); }); s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_c.readBytes(bytes, 0, e.bytesLoaded); log("Client: read " + bytes.length + "."); s_r.writeBytes(bytes); }); } }
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; import flash.utils.setTimeout; [SWF(width="640", height="480")] public class swfcat extends Sprite { /* David's bridge (nickname eRYaZuvY02FpExln) that also serves a crossdomain policy. */ private const DEFAULT_TOR_ADDR:Object = { // host: "173.255.221.44", 3VXRyxz67OeRoqHn host: "69.164.193.231", port: 9001 }; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; // Socket to facilitator. private var s_f:Socket; private var output_text:TextField; private var fac_addr:Object; public function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function swfcat() { output_text = new TextField(); output_text.width = 640; output_text.height = 480; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; addChild(output_text); puts("Starting."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String; puts("Parameters loaded."); fac_spec = this.loaderInfo.parameters["facilitator"]; if (!fac_spec) { puts("Error: no \"facilitator\" specification provided."); return; } puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = parse_addr_spec(fac_spec); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } main(); } /* The main logic begins here, after start-up issues are taken care of. */ private function main():void { s_f = new Socket(); s_f.addEventListener(Event.CONNECT, fac_connected); s_f.addEventListener(Event.CLOSE, function (e:Event):void { puts("Facilitator: closed connection."); setTimeout(main, FACILITATOR_POLL_INTERVAL); }); s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); }); s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); }); puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + "."); s_f.connect(fac_addr.host, fac_addr.port); } private function fac_connected(e:Event):void { puts("Facilitator: connected."); s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data); s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n"); } private function fac_data(e:ProgressEvent):void { var client_spec:String; var client_addr:Object; var proxy_pair:Object; client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8"); puts("Facilitator: got \"" + client_spec + "\"."); client_addr = parse_addr_spec(client_spec); if (!client_addr) { puts("Error: Client spec must be in the form \"host:port\"."); return; } if (client_addr.host == "0.0.0.0" && client_addr.port == 0) { puts("Error: Facilitator has no clients."); return; } proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR); proxy_pair.connect(); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private static function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.Socket; import flash.utils.ByteArray; /* An instance of a client-relay connection. */ class ProxyPair { // Address ({host, port}) of client. private var addr_c:Object; // Address ({host, port}) of relay. private var addr_r:Object; // Socket to client. private var s_c:Socket; // Socket to relay. private var s_r:Socket; // Parent swfcat, for UI updates. private var ui:swfcat; private function log(msg:String):void { ui.puts(id() + ": " + msg) } // String describing this pair for output. private function id():String { return "<" + this.addr_c.host + ":" + this.addr_c.port + "," + this.addr_r.host + ":" + this.addr_r.port + ">"; } public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object) { this.ui = ui; this.addr_c = addr_c; this.addr_r = addr_r; } public function connect():void { s_r = new Socket(); s_r.addEventListener(Event.CONNECT, tor_connected); s_r.addEventListener(Event.CLOSE, function (e:Event):void { log("Tor: closed."); if (s_c.connected) s_c.close(); }); s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Tor: I/O error: " + e.text + "."); if (s_c.connected) s_c.close(); }); s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Tor: security error: " + e.text + "."); if (s_c.connected) s_c.close(); }); log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + "."); s_r.connect(addr_r.host, addr_r.port); } private function tor_connected(e:Event):void { log("Tor: connected."); s_c = new Socket(); s_c.addEventListener(Event.CONNECT, client_connected); s_c.addEventListener(Event.CLOSE, function (e:Event):void { log("Client: closed."); if (s_r.connected) s_r.close(); }); s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Client: I/O error: " + e.text + "."); if (s_r.connected) s_r.close(); }); s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Client: security error: " + e.text + "."); if (s_r.connected) s_r.close(); }); log("Client: connecting to " + addr_c.host + ":" + addr_c.port + "."); s_c.connect(addr_c.host, addr_c.port); } private function client_connected(e:Event):void { log("Client: connected."); s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_r.readBytes(bytes, 0, e.bytesLoaded); log("Tor: read " + bytes.length + "."); s_c.writeBytes(bytes); }); s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_c.readBytes(bytes, 0, e.bytesLoaded); log("Client: read " + bytes.length + "."); s_r.writeBytes(bytes); }); } }
Add missing period for uniformity.
Add missing period for uniformity.
ActionScript
mit
arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy
d1d9cde9164578a8db082fe4b4230d63350c39fa
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/NumericStepperView.as
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/NumericStepperView.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.IBeadView; import org.apache.flex.core.ILayoutParent; import org.apache.flex.core.IParent; import org.apache.flex.core.IParentIUIBase; import org.apache.flex.core.IRangeModel; import org.apache.flex.core.IStrand; import org.apache.flex.core.IUIBase; import org.apache.flex.core.UIBase; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.html.Label; import org.apache.flex.html.Spinner; import org.apache.flex.html.TextInput; import org.apache.flex.html.beads.layouts.HorizontalLayout; import org.apache.flex.html.supportClasses.Border; import org.apache.flex.html.supportClasses.ScrollBar; /** * The NumericStepperView class creates the visual elements of the * org.apache.flex.html.NumericStepper component. A NumberStepper consists of a * org.apache.flex.html.TextInput component to display the value and a * org.apache.flex.html.Spinner to change the value. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class NumericStepperView extends BeadViewBase implements IBeadView, ILayoutParent { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function NumericStepperView() { } private var label:Label; private var input:TextInput; private var spinner:Spinner; /** * @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; // add a horizontal layout bead value.addBead(new HorizontalLayout()); // add an input field input = new TextInput(); IParent(value).addElement(input); // add a spinner spinner = new Spinner(); spinner.addBead( UIBase(value).model ); IParent(value).addElement(spinner); spinner.width = 17; spinner.height = input.height; // listen for changes to the text input field which will reset the // value. ideally, we should either set the input to accept only // numeric values or, barring that, reject non-numeric entries. we // cannot do that right now however. input.model.addEventListener("textChange",inputChangeHandler); // listen for change events on the spinner so the value can be updated as // as resizing the component spinner.addEventListener("valueChange",spinnerValueChanged); IEventDispatcher(value).addEventListener("widthChanged",sizeChangeHandler); IEventDispatcher(value).addEventListener("heightChanged",sizeChangeHandler); // listen for changes to the model itself and update the UI accordingly IEventDispatcher(UIBase(value).model).addEventListener("valueChange",modelChangeHandler); IEventDispatcher(UIBase(value).model).addEventListener("minimumChange",modelChangeHandler); IEventDispatcher(UIBase(value).model).addEventListener("maximumChange",modelChangeHandler); IEventDispatcher(UIBase(value).model).addEventListener("stepSizeChange",modelChangeHandler); IEventDispatcher(UIBase(value).model).addEventListener("snapIntervalChange",modelChangeHandler); input.text = String(spinner.value); // set a default size which will trigger the sizeChangeHandler var minWidth:Number = Math.max(50+spinner.width,UIBase(value).width); UIBase(value).width = minWidth; UIBase(value).height = spinner.height; } /** * @private */ private function sizeChangeHandler(event:Event) : void { input.x = 2; input.y = (UIBase(_strand).height - input.height)/2; input.width = UIBase(_strand).width-spinner.width-2; spinner.x = input.width+2; spinner.y = 0; } /** * @private */ private function spinnerValueChanged(event:Event) : void { input.text = String(spinner.value); var newEvent:Event = new Event(event.type,event.bubbles); IEventDispatcher(_strand).dispatchEvent(newEvent); } /** * @private */ private function inputChangeHandler(event:Event) : void { var newValue:Number = Number(input.text); if( !isNaN(newValue) ) { spinner.value = newValue; } else { input.text = String(spinner.value); } } /** * @private */ private function modelChangeHandler( event:Event ) : void { var n:Number = IRangeModel(UIBase(_strand).model).value; input.text = String(IRangeModel(UIBase(_strand).model).value); } /** * The area containing the TextInput and Spinner controls. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get contentView():IParentIUIBase { return _strand as IParentIUIBase; } /** * @private */ public function get border():Border { return null; } /** * @private */ public function get vScrollBar():ScrollBar { return null; } /** * @private */ public function get hScrollBar():ScrollBar { return null; } /** * @private */ public function get resizableView():IUIBase { return _strand as IUIBase; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.IBeadView; import org.apache.flex.core.ILayoutChild; import org.apache.flex.core.ILayoutParent; import org.apache.flex.core.IParent; import org.apache.flex.core.IParentIUIBase; import org.apache.flex.core.IRangeModel; import org.apache.flex.core.IStrand; import org.apache.flex.core.IUIBase; import org.apache.flex.core.UIBase; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.html.Label; import org.apache.flex.html.Spinner; import org.apache.flex.html.TextInput; import org.apache.flex.html.beads.layouts.HorizontalLayout; import org.apache.flex.html.supportClasses.Border; import org.apache.flex.html.supportClasses.ScrollBar; /** * The NumericStepperView class creates the visual elements of the * org.apache.flex.html.NumericStepper component. A NumberStepper consists of a * org.apache.flex.html.TextInput component to display the value and a * org.apache.flex.html.Spinner to change the value. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class NumericStepperView extends BeadViewBase implements IBeadView, ILayoutParent { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function NumericStepperView() { } private var label:Label; private var input:TextInput; private var spinner:Spinner; /** * @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; // add a horizontal layout bead value.addBead(new HorizontalLayout()); // add an input field input = new TextInput(); IParent(value).addElement(input); // add a spinner spinner = new Spinner(); spinner.addBead( UIBase(value).model ); IParent(value).addElement(spinner); spinner.height = input.height; // listen for changes to the text input field which will reset the // value. ideally, we should either set the input to accept only // numeric values or, barring that, reject non-numeric entries. we // cannot do that right now however. input.model.addEventListener("textChange",inputChangeHandler); // listen for change events on the spinner so the value can be updated as // as resizing the component spinner.addEventListener("valueChange",spinnerValueChanged); IEventDispatcher(value).addEventListener("widthChanged",sizeChangeHandler); IEventDispatcher(value).addEventListener("heightChanged",sizeChangeHandler); IEventDispatcher(value).addEventListener("sizeChanged",sizeChangeHandler); // listen for changes to the model itself and update the UI accordingly IEventDispatcher(UIBase(value).model).addEventListener("valueChange",modelChangeHandler); IEventDispatcher(UIBase(value).model).addEventListener("minimumChange",modelChangeHandler); IEventDispatcher(UIBase(value).model).addEventListener("maximumChange",modelChangeHandler); IEventDispatcher(UIBase(value).model).addEventListener("stepSizeChange",modelChangeHandler); IEventDispatcher(UIBase(value).model).addEventListener("snapIntervalChange",modelChangeHandler); input.text = String(spinner.value); var host:ILayoutChild = ILayoutChild(value); if ((host.isWidthSizedToContent() || isNaN(host.explicitWidth)) && (host.isHeightSizedToContent() || isNaN(host.explicitHeight))) sizeChangeHandler(null); } /** * @private */ private function sizeChangeHandler(event:Event) : void { input.x = 2; input.y = (UIBase(_strand).height - input.height)/2; input.width = UIBase(_strand).width-spinner.width-2; spinner.x = input.width+2; spinner.y = 0; } /** * @private */ private function spinnerValueChanged(event:Event) : void { input.text = String(spinner.value); var newEvent:Event = new Event(event.type,event.bubbles); IEventDispatcher(_strand).dispatchEvent(newEvent); } /** * @private */ private function inputChangeHandler(event:Event) : void { var newValue:Number = Number(input.text); if( !isNaN(newValue) ) { spinner.value = newValue; } else { input.text = String(spinner.value); } } /** * @private */ private function modelChangeHandler( event:Event ) : void { var n:Number = IRangeModel(UIBase(_strand).model).value; input.text = String(IRangeModel(UIBase(_strand).model).value); } /** * The area containing the TextInput and Spinner controls. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get contentView():IParentIUIBase { return _strand as IParentIUIBase; } /** * @private */ public function get resizableView():IUIBase { return _strand as IUIBase; } } }
fix sizing of NS
fix sizing of NS
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
bb50ff59431a02de1ccce4f92fc9f0c9996b63f7
application/src/im/siver/logger/controllers/TraceController.as
application/src/im/siver/logger/controllers/TraceController.as
package im.siver.logger.controllers { import flash.display.BitmapData; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.MouseEvent; import flash.geom.Rectangle; import im.siver.logger.models.Constants; import im.siver.logger.utils.LoggerUtils; import im.siver.logger.views.components.Filter; import im.siver.logger.views.components.panels.TracePanel; import im.siver.logger.views.components.windows.SnapshotWindow; import im.siver.logger.views.components.windows.TraceWindow; import mx.collections.ArrayCollection; import mx.events.CollectionEvent; import mx.events.FlexEvent; import mx.events.ListEvent; import mx.utils.StringUtil; public final class TraceController extends EventDispatcher { [Bindable] private var _dataFilterd:ArrayCollection = new ArrayCollection(); private var _data:ArrayCollection = new ArrayCollection(); private var _panel:TracePanel; private var _send:Function; /** * Save panel */ public function TraceController(panel:TracePanel, send:Function) { _panel = panel; _send = send; _panel.addEventListener(FlexEvent.CREATION_COMPLETE, creationComplete, false, 0, true); } private function collectionDidChange(e:CollectionEvent):void { if (_panel.autoScrollButton.selected) { _panel.datagrid.validateNow(); _panel.datagrid.verticalScrollPosition = _panel.datagrid.maxVerticalScrollPosition; } } /** * Panel is ready to link data providers */ private function creationComplete(e:FlexEvent):void { _panel.removeEventListener(FlexEvent.CREATION_COMPLETE, creationComplete); _panel.datagrid.dataProvider = _dataFilterd; _panel.datagrid.addEventListener(ListEvent.ITEM_DOUBLE_CLICK, showTrace, false, 0, true); _panel.filter.addEventListener(Filter.CHANGED, filterChanged, false, 0, true); _panel.clearButton.addEventListener(MouseEvent.CLICK, clear, false, 0, true); _dataFilterd.addEventListener(CollectionEvent.COLLECTION_CHANGE, collectionDidChange, false, 0, true); } /** * Show a trace in an output window */ private function filterChanged(event:Event):void { // Check if a filter term is given if (_panel.filter.words.length == 0) { _dataFilterd.filterFunction = null; _dataFilterd.refresh(); } else { _dataFilterd.filterFunction = checkFilter; _dataFilterd.refresh(); } } private function addItem(item:Object):void { _dataFilterd.addItem(item); } private function simpleFilter(item:Object):Boolean { return false; } /** * Loop through the search terms and compare strings */ private function checkFilter(item:Object):Boolean { var message:String = item.message; var target:String = item.target; var label:String = item.label; var person:String = item.person; if (message == null) message = ""; if (target == null) target = ""; if (label == null) label = ""; if (person == null) person = ""; message = StringUtil.trim(message).toLowerCase(); target = StringUtil.trim(target).toLowerCase(); label = StringUtil.trim(label).toLowerCase(); person = StringUtil.trim(person).toLowerCase(); var i:int; // Clone words var words:Array = []; for (i = 0; i < _panel.filter.words.length; i++) { words[i] = _panel.filter.words[i]; } if (message != "") { for (i = 0; i < words.length; i++) { if (message.indexOf(words[i]) != -1) { words.splice(i, 1); i--; } } } if (words.length == 0) return true; if (target != "") { for (i = 0; i < words.length; i++) { if (target.indexOf(words[i]) != -1) { words.splice(i, 1); i--; } } } if (words.length == 0) return true; if (label != "") { for (i = 0; i < words.length; i++) { if (label.indexOf(words[i]) != -1) { words.splice(i, 1); i--; } } } if (words.length == 0) return true; if (person != "") { for (i = 0; i < words.length; i++) { if (person.indexOf(words[i]) != -1) { words.splice(i, 1); i--; } } } if (words.length == 0) return true; return false; } /** * Show a trace in an output window */ private function showTrace(event:ListEvent):void { // Check if the selected item is still available if (event.currentTarget.selectedItem != null) { // Get the data var item:Object = _dataFilterd.getItemAt(event.currentTarget.selectedIndex); // Check the window to open if (item.message == "Snapshot" && item.xml == null) { var snapshotWindow:SnapshotWindow = new SnapshotWindow(); snapshotWindow.setData(item); snapshotWindow.open(); } else { var traceWindow:TraceWindow = new TraceWindow(); traceWindow.setData(item); traceWindow.open(); } } } /** * Clear traces */ public function clear(event:MouseEvent = null):void { _data.removeAll(); _dataFilterd.removeAll(); _panel.datagrid.horizontalScrollPosition = 0; } /** * Data handler from client */ public function setData(data:Object):void { // Vars for loop var date:Date; var hours:String; var minutes:String; var seconds:String; var miliseconds:String; var time:String; var memory:String; var traceItem:Object; switch (data["command"]) { case Constants.COMMAND_CLEAR_TRACES: clear(); break; case Constants.COMMAND_TRACE: // Format the properties date = data["date"]; time = zeroPad(date.getHours(), 2) + ":" + zeroPad(date.getMinutes(), 2) + ":" + zeroPad(date.getSeconds(), 2) + "." + zeroPad(date.getMilliseconds(), 3); memory = Math.round(data["memory"] / 1024) + " Kb"; // Create the trace object traceItem = {}; // Check the label if (data["xml"]..node.length() > 1 && data["xml"]..node.length() <= 3) { if (data["xml"].node[0].@type == Constants.TYPE_STRING || data["xml"].node[0].@type == Constants.TYPE_BOOLEAN || data["xml"].node[0].@type == Constants.TYPE_NUMBER || data["xml"].node[0].@type == Constants.TYPE_INT || data["xml"].node[0].@type == Constants.TYPE_UINT) { traceItem.message = LoggerUtils.stripBreaks(LoggerUtils.htmlUnescape(data["xml"].node.children()[0].@label)); } else { traceItem.message = LoggerUtils.stripBreaks(LoggerUtils.htmlUnescape(data["xml"].node.@label)) + " ..."; } } else { traceItem.message = LoggerUtils.stripBreaks(LoggerUtils.htmlUnescape(data["xml"].node.@label)) + " ..."; } // Clean target if (data['target'].indexOf('object') != -1) { traceItem.target = String(data['target']).replace('object ', ''); } else { traceItem.target = data["target"]; } // Add extra info traceItem.line = _data.length + 1; traceItem.time = time; traceItem.memory = memory; traceItem.reference = data["reference"]; traceItem.label = data["label"]; traceItem.person = data["person"]; traceItem.color = data["color"]; traceItem.xml = data["xml"]; // Add to list _data.addItem(traceItem); addItem(traceItem); break; case Constants.COMMAND_SNAPSHOT: // Format the properties date = data["date"]; hours = (date.getHours() < 10) ? "0" + date.getHours().toString() : date.getHours().toString(); minutes = (date.getMinutes() < 10) ? "0" + date.getMinutes().toString() : date.getMinutes().toString(); seconds = (date.getSeconds() < 10) ? "0" + date.getSeconds().toString() : date.getSeconds().toString(); miliseconds = date.getMilliseconds().toString(); time = hours + ":" + minutes + ":" + seconds + "." + miliseconds; memory = Math.round(data["memory"] / 1024) + " Kb"; // Read the bitmap try { var bitmapData:BitmapData = new BitmapData(data["width"], data["height"]); bitmapData.setPixels(new Rectangle(0, 0, data["width"], data["height"]), data["bytes"]); } catch (e:Error) { return; } // Create the trace object traceItem = {}; traceItem.line = _data.length + 1; traceItem.time = time; traceItem.memory = memory; traceItem.width = data["width"]; traceItem.height = data["height"]; traceItem.bitmapData = bitmapData; traceItem.message = "Snapshot"; traceItem.target = data["target"]; traceItem.label = data["label"]; traceItem.person = data["person"]; traceItem.color = data["color"]; traceItem.xml = null; // Add to list _data.addItem(traceItem); addItem(traceItem); break; } } private function zeroPad(value:int, length:int, pad:String = '0'):String { var result:String = String(value); while (result.length < length) { result = pad + result; } return result; } } }
package im.siver.logger.controllers { import flash.display.BitmapData; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.MouseEvent; import flash.geom.Rectangle; import im.siver.logger.models.Constants; import im.siver.logger.utils.LoggerUtils; import im.siver.logger.views.components.Filter; import im.siver.logger.views.components.panels.TracePanel; import im.siver.logger.views.components.windows.SnapshotWindow; import im.siver.logger.views.components.windows.TraceWindow; import mx.collections.ArrayCollection; import mx.events.CollectionEvent; import mx.events.FlexEvent; import mx.events.ListEvent; import mx.utils.StringUtil; public final class TraceController extends EventDispatcher { [Bindable] private var _dataFiltered:ArrayCollection = new ArrayCollection(); private var _data:ArrayCollection = new ArrayCollection(); private var _panel:TracePanel; private var _send:Function; /** * Save panel */ public function TraceController(panel:TracePanel, send:Function) { _panel = panel; _send = send; _panel.addEventListener(FlexEvent.CREATION_COMPLETE, creationComplete, false, 0, true); } private function collectionDidChange(e:CollectionEvent):void { if (_panel.autoScrollButton.selected) { _panel.datagrid.validateNow(); _panel.datagrid.verticalScrollPosition = _panel.datagrid.maxVerticalScrollPosition; } } /** * Panel is ready to link data providers */ private function creationComplete(e:FlexEvent):void { _panel.removeEventListener(FlexEvent.CREATION_COMPLETE, creationComplete); _panel.datagrid.dataProvider = _dataFiltered; _panel.datagrid.addEventListener(ListEvent.ITEM_DOUBLE_CLICK, showTrace, false, 0, true); _panel.filter.addEventListener(Filter.CHANGED, filterChanged, false, 0, true); _panel.clearButton.addEventListener(MouseEvent.CLICK, clear, false, 0, true); _dataFiltered.addEventListener(CollectionEvent.COLLECTION_CHANGE, collectionDidChange, false, 0, true); } /** * Show a trace in an output window */ private function filterChanged(event:Event):void { // Check if a filter term is given if (_panel.filter.words.length == 0) { _dataFiltered.filterFunction = null; _dataFiltered.refresh(); } else { _dataFiltered.filterFunction = fullFilter; _dataFiltered.refresh(); } } /** * Look through targets and messages * @param item data-provider item * @return true if item has been found */ private function fullFilter(item:Object):Boolean { var message:String = item.message; var target:String = item.target; var i:int, words:Array = _panel.filter.words, len:int = words.length; if (target != null) { target = target.toLowerCase(); for (i = 0; i < len; ++i) { if (target.indexOf(words[i]) != -1) { return true; } } } if (message != null) { message = message.toLowerCase(); for (i = 0; i < len; ++i) { if (message.indexOf(words[i]) != -1) { return true; } } } return false; } /** * Show a trace in an output window */ private function showTrace(event:ListEvent):void { // Check if the selected item is still available if (event.currentTarget.selectedItem != null) { // Get the data var item:Object = _dataFiltered.getItemAt(event.currentTarget.selectedIndex); // Check the window to open if (item.message == "Snapshot" && item.xml == null) { var snapshotWindow:SnapshotWindow = new SnapshotWindow(); snapshotWindow.setData(item); snapshotWindow.open(); } else { var traceWindow:TraceWindow = new TraceWindow(); traceWindow.setData(item); traceWindow.open(); } } } /** * Clear traces */ public function clear(event:MouseEvent = null):void { _data.removeAll(); _dataFiltered.removeAll(); _panel.datagrid.horizontalScrollPosition = 0; } /** * Data handler from client */ public function setData(data:Object):void { // Vars for loop var date:Date; var hours:String; var minutes:String; var seconds:String; var miliseconds:String; var time:String; var memory:String; var traceItem:Object; switch (data["command"]) { case Constants.COMMAND_CLEAR_TRACES: clear(); break; case Constants.COMMAND_TRACE: // Format the properties date = data["date"]; time = zeroPad(date.getHours(), 2) + ":" + zeroPad(date.getMinutes(), 2) + ":" + zeroPad(date.getSeconds(), 2) + "." + zeroPad(date.getMilliseconds(), 3); memory = Math.round(data["memory"] / 1024) + " Kb"; // Create the trace object traceItem = {}; // Check the label if (data["xml"]..node.length() > 1 && data["xml"]..node.length() <= 3) { if (data["xml"].node[0].@type == Constants.TYPE_STRING || data["xml"].node[0].@type == Constants.TYPE_BOOLEAN || data["xml"].node[0].@type == Constants.TYPE_NUMBER || data["xml"].node[0].@type == Constants.TYPE_INT || data["xml"].node[0].@type == Constants.TYPE_UINT) { traceItem.message = LoggerUtils.stripBreaks(LoggerUtils.htmlUnescape(data["xml"].node.children()[0].@label)); } else { traceItem.message = LoggerUtils.stripBreaks(LoggerUtils.htmlUnescape(data["xml"].node.@label)) + " ..."; } } else { traceItem.message = LoggerUtils.stripBreaks(LoggerUtils.htmlUnescape(data["xml"].node.@label)) + " ..."; } // Clean target if (data['target'].indexOf('object') != -1) { traceItem.target = String(data['target']).replace('object ', ''); } else { traceItem.target = data["target"]; } // Add extra info traceItem.line = _data.length + 1; traceItem.time = time; traceItem.memory = memory; traceItem.reference = data["reference"]; traceItem.label = data["label"]; traceItem.person = data["person"]; traceItem.color = data["color"]; traceItem.xml = data["xml"]; // Add to list _data.addItem(traceItem); _dataFiltered.addItem(traceItem); break; case Constants.COMMAND_SNAPSHOT: // Format the properties date = data["date"]; hours = (date.getHours() < 10) ? "0" + date.getHours().toString() : date.getHours().toString(); minutes = (date.getMinutes() < 10) ? "0" + date.getMinutes().toString() : date.getMinutes().toString(); seconds = (date.getSeconds() < 10) ? "0" + date.getSeconds().toString() : date.getSeconds().toString(); miliseconds = date.getMilliseconds().toString(); time = hours + ":" + minutes + ":" + seconds + "." + miliseconds; memory = Math.round(data["memory"] / 1024) + " Kb"; // Read the bitmap try { var bitmapData:BitmapData = new BitmapData(data["width"], data["height"]); bitmapData.setPixels(new Rectangle(0, 0, data["width"], data["height"]), data["bytes"]); } catch (e:Error) { return; } // Create the trace object traceItem = {}; traceItem.line = _data.length + 1; traceItem.time = time; traceItem.memory = memory; traceItem.width = data["width"]; traceItem.height = data["height"]; traceItem.bitmapData = bitmapData; traceItem.message = "Snapshot"; traceItem.target = data["target"]; traceItem.label = data["label"]; traceItem.person = data["person"]; traceItem.color = data["color"]; traceItem.xml = null; // Add to list _data.addItem(traceItem); _dataFiltered.addItem(traceItem); break; } } private function zeroPad(value:int, length:int, pad:String = '0'):String { var result:String = String(value); while (result.length < length) { result = pad + result; } return result; } } }
Improve filtering
Improve filtering
ActionScript
mit
NicolasSiver/as3-logger
fc37f268fbd6562f1846ef4b52c85dd5ce15fc8c
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; BillboardSet@ debugIconsSetSplinesPoints; Node@ debugIconsNode = null; int stepDebugIconsUpdate = 40; //ms int timeToNextDebugIconsUpdate = 0; const int splinePathResolution = 16; bool debugIconsShow = true; Vector2 debugIconsSize = Vector2(0.025, 0.025); Vector2 debugIconsSizeSmall = debugIconsSize / 2.0; 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; debugIconsSetSplinesPoints = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSplinesPoints.material = cache.GetResource("Material", "Materials/Editor/DebugIconSplinePathPoint.xml"); debugIconsSetSplinesPoints.material.renderOrder = 255; debugIconsSetSplinesPoints.sorted = true; debugIconsSetSplinesPoints.temporary = true; debugIconsSetSplinesPoints.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(); } } if (debugIconsSetSplinesPoints !is null) { debugIconsSetSplinesPoints.enabled = debugIconsShow; // Collect all scene's SplinePath and add it Array<Node@> nodes = editorScene.GetChildrenWithComponent("SplinePath", true); if (nodes.length > 0) { debugIconsSetSplinesPoints.numBillboards = nodes.length * splinePathResolution; float splineStep = 1.0f / splinePathResolution; for(int i=0; i < nodes.length; i++) { SplinePath@ sp = nodes[i].GetComponent("SplinePath"); if(sp !is null) { Vector3 splinePoint; // Create path for(int step=0; step < splinePathResolution; step++) { splinePoint = sp.GetPoint(splineStep * step); float distance = (camPos - splinePoint).length; int index = (i * splinePathResolution) + step; Billboard@ bb = debugIconsSetSplinesPoints.billboards[index]; bb.position = splinePoint; bb.size = debugIconsSizeSmall * distance; if (step == 0) { bb.color = Color(1,1,0); bb.size = debugIconsSize * distance; } else if ((step+1) >= (splinePathResolution - splineStep)) { bb.color = Color(0,1,0); bb.size = debugIconsSize * distance; } else { bb.color = Color(1,1,1); bb.size = debugIconsSizeSmall * distance; } bb.enabled = sp.enabled; } } } debugIconsSetSplinesPoints.Commit(); } } timeToNextDebugIconsUpdate = time.systemTime + stepDebugIconsUpdate; }
// Editor debug icons BillboardSet@ debugIconsSetDirectionalLights; BillboardSet@ debugIconsSetSpotLights; BillboardSet@ debugIconsSetPointLights; BillboardSet@ debugIconsSetCameras; BillboardSet@ debugIconsSetSoundSources; BillboardSet@ debugIconsSetSoundSources3D; BillboardSet@ debugIconsSetSoundListeners; BillboardSet@ debugIconsSetZones; BillboardSet@ debugIconsSetSplinesPoints; Node@ debugIconsNode = null; int stepDebugIconsUpdate = 60; //ms int timeToNextDebugIconsUpdate = 0; int stepDebugIconsUpdateSplinePath = 500; //ms int timeToNextDebugIconsUpdateSplinePath = 0; const int splinePathResolution = 16; bool debugIconsShow = true; Vector2 debugIconsSize = Vector2(0.025, 0.025); Vector2 debugIconsSizeSmall = debugIconsSize / 2.0; 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; debugIconsSetSplinesPoints = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSplinesPoints.material = cache.GetResource("Material", "Materials/Editor/DebugIconSplinePathPoint.xml"); debugIconsSetSplinesPoints.material.renderOrder = 255; debugIconsSetSplinesPoints.sorted = true; debugIconsSetSplinesPoints.temporary = true; debugIconsSetSplinesPoints.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(); } } if (timeToNextDebugIconsUpdateSplinePath < time.systemTime) { if (debugIconsSetSplinesPoints !is null) { debugIconsSetSplinesPoints.enabled = debugIconsShow; // Collect all scene's SplinePath and add it Array<Node@> nodes = editorScene.GetChildrenWithComponent("SplinePath", true); if (nodes.length > 0) { debugIconsSetSplinesPoints.numBillboards = nodes.length * splinePathResolution; float splineStep = 1.0f / splinePathResolution; for(int i=0; i < nodes.length; i++) { SplinePath@ sp = nodes[i].GetComponent("SplinePath"); if(sp !is null) { Vector3 splinePoint; // Create path for(int step=0; step < splinePathResolution; step++) { splinePoint = sp.GetPoint(splineStep * step); float distance = (camPos - splinePoint).length; int index = (i * splinePathResolution) + step; Billboard@ bb = debugIconsSetSplinesPoints.billboards[index]; bb.position = splinePoint; bb.size = debugIconsSizeSmall * distance; if (step == 0) { bb.color = Color(1,1,0); bb.size = debugIconsSize * distance; } else if ((step+1) >= (splinePathResolution - splineStep)) { bb.color = Color(0,1,0); bb.size = debugIconsSize * distance; } else { bb.color = Color(1,1,1); bb.size = debugIconsSizeSmall * distance; } bb.enabled = sp.enabled; } } } debugIconsSetSplinesPoints.Commit(); } } timeToNextDebugIconsUpdateSplinePath = time.systemTime + stepDebugIconsUpdateSplinePath; } timeToNextDebugIconsUpdate = time.systemTime + stepDebugIconsUpdate; }
increase update time for splinepath
increase update time for splinepath
ActionScript
mit
rokups/Urho3D,codemon66/Urho3D,victorholt/Urho3D,victorholt/Urho3D,tommy3/Urho3D,299299/Urho3D,henu/Urho3D,codemon66/Urho3D,codedash64/Urho3D,weitjong/Urho3D,xiliu98/Urho3D,bacsmar/Urho3D,luveti/Urho3D,victorholt/Urho3D,fire/Urho3D-1,abdllhbyrktr/Urho3D,MonkeyFirst/Urho3D,tommy3/Urho3D,codemon66/Urho3D,tommy3/Urho3D,luveti/Urho3D,cosmy1/Urho3D,fire/Urho3D-1,victorholt/Urho3D,xiliu98/Urho3D,c4augustus/Urho3D,SirNate0/Urho3D,helingping/Urho3D,iainmerrick/Urho3D,iainmerrick/Urho3D,eugeneko/Urho3D,weitjong/Urho3D,fire/Urho3D-1,299299/Urho3D,rokups/Urho3D,urho3d/Urho3D,bacsmar/Urho3D,rokups/Urho3D,orefkov/Urho3D,orefkov/Urho3D,codedash64/Urho3D,weitjong/Urho3D,iainmerrick/Urho3D,cosmy1/Urho3D,carnalis/Urho3D,codemon66/Urho3D,urho3d/Urho3D,helingping/Urho3D,tommy3/Urho3D,carnalis/Urho3D,MonkeyFirst/Urho3D,bacsmar/Urho3D,cosmy1/Urho3D,henu/Urho3D,weitjong/Urho3D,bacsmar/Urho3D,eugeneko/Urho3D,kostik1337/Urho3D,SirNate0/Urho3D,henu/Urho3D,tommy3/Urho3D,kostik1337/Urho3D,codedash64/Urho3D,SirNate0/Urho3D,kostik1337/Urho3D,c4augustus/Urho3D,iainmerrick/Urho3D,henu/Urho3D,xiliu98/Urho3D,orefkov/Urho3D,cosmy1/Urho3D,urho3d/Urho3D,SirNate0/Urho3D,urho3d/Urho3D,PredatorMF/Urho3D,MeshGeometry/Urho3D,SuperWangKai/Urho3D,xiliu98/Urho3D,SuperWangKai/Urho3D,fire/Urho3D-1,weitjong/Urho3D,c4augustus/Urho3D,PredatorMF/Urho3D,SuperWangKai/Urho3D,helingping/Urho3D,MonkeyFirst/Urho3D,carnalis/Urho3D,abdllhbyrktr/Urho3D,xiliu98/Urho3D,helingping/Urho3D,helingping/Urho3D,MeshGeometry/Urho3D,MonkeyFirst/Urho3D,codedash64/Urho3D,kostik1337/Urho3D,rokups/Urho3D,MonkeyFirst/Urho3D,codemon66/Urho3D,PredatorMF/Urho3D,MeshGeometry/Urho3D,299299/Urho3D,SuperWangKai/Urho3D,carnalis/Urho3D,codedash64/Urho3D,MeshGeometry/Urho3D,299299/Urho3D,orefkov/Urho3D,SirNate0/Urho3D,henu/Urho3D,luveti/Urho3D,fire/Urho3D-1,PredatorMF/Urho3D,SuperWangKai/Urho3D,eugeneko/Urho3D,abdllhbyrktr/Urho3D,carnalis/Urho3D,abdllhbyrktr/Urho3D,MeshGeometry/Urho3D,299299/Urho3D,cosmy1/Urho3D,victorholt/Urho3D,iainmerrick/Urho3D,abdllhbyrktr/Urho3D,kostik1337/Urho3D,rokups/Urho3D,eugeneko/Urho3D,c4augustus/Urho3D,rokups/Urho3D,c4augustus/Urho3D,luveti/Urho3D,299299/Urho3D,luveti/Urho3D
262c6a5cabe512090f48b7045384d427457fbc2d
actionscript/src/com/freshplanet/ane/AirDeviceId/AirDeviceId.as
actionscript/src/com/freshplanet/ane/AirDeviceId/AirDeviceId.as
/* * Copyright 2017 FreshPlanet * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.freshplanet.ane.AirDeviceId { import com.freshplanet.ane.AirDeviceId.events.AirDeviceIdEvent; import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class AirDeviceId extends EventDispatcher { // --------------------------------------------------------------------------------------// // // // PUBLIC API // // // // --------------------------------------------------------------------------------------// /** AirAlert is supported on iOS and Android devices. */ public static function get isSupported() : Boolean { return isAndroid || isIOS; } /** * AirDeviceId instance * @return AirDeviceId instance */ public static function get instance() : AirDeviceId { return _instance ? _instance : new AirDeviceId(); } /** * Get device id * @param salt a developer specific salt */ public function getID( salt:String ) : String { if (isSupported) return _context.call( 'getID', salt ) as String; return null; } /** * Get vendor identifier * @return */ public function getIDFV():String { if (isSupported) return _context.call( 'getIDFV' ) as String; return null; } /** * Get advertising identifier * @return */ public function getIDFA() : void { if ( isSupported ) _context.call( 'getIDFA' ); } // --------------------------------------------------------------------------------------// // // // PRIVATE API // // // // --------------------------------------------------------------------------------------// private static const EXTENSION_ID : String = "com.freshplanet.ane.AirDeviceId"; private static var _instance : AirDeviceId = null; private var _context : ExtensionContext = null; /** * "private" singleton constructor */ public function AirDeviceId() { if ( !_instance ) { _context = ExtensionContext.createExtensionContext( EXTENSION_ID, null ); if (_context != null ) { _context.addEventListener( StatusEvent.STATUS, _onStatus ); } else { trace('[AirDeviceId] Error - Extension Context is null.'); } _instance = this; } else { throw Error( 'This is a singleton, use getInstance(), do not call the constructor directly.' ); } } /** * Status events allow the native part of the ANE to communicate with the ActionScript part. * We use event.code to represent the type of event, and event.level to carry the data. */ private function _onStatus( event:StatusEvent ) : void { if ( event.code == AirDeviceIdEvent.RECEIVED_IDFA ) { this.dispatchEvent(new AirDeviceIdEvent(AirDeviceIdEvent.RECEIVED_IDFA, event.level)); } else if ( event.code == "log" ) { trace( '[AirDeviceId] ' + event.level ); } } private static function get isIOS():Boolean { return Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0; } private static function get isAndroid():Boolean { return Capabilities.manufacturer.indexOf("Android") > -1; } } }
/* * Copyright 2017 FreshPlanet * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.freshplanet.ane.AirDeviceId { import com.freshplanet.ane.AirDeviceId.events.AirDeviceIdEvent; import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class AirDeviceId extends EventDispatcher { // --------------------------------------------------------------------------------------// // // // PUBLIC API // // // // --------------------------------------------------------------------------------------// /** AirAlert is supported on iOS and Android devices. */ public static function get isSupported() : Boolean { return isAndroid || isIOS; } /** * AirDeviceId instance * @return AirDeviceId instance */ public static function get instance() : AirDeviceId { return _instance ? _instance : new AirDeviceId(); } /** * Get vendor identifier * @return */ public function getIDFV():String { if (isSupported) return _context.call( 'getIDFV' ) as String; return null; } /** * Get advertising identifier * @return */ public function getIDFA() : void { if ( isSupported ) _context.call( 'getIDFA' ); } // --------------------------------------------------------------------------------------// // // // PRIVATE API // // // // --------------------------------------------------------------------------------------// private static const EXTENSION_ID : String = "com.freshplanet.ane.AirDeviceId"; private static var _instance : AirDeviceId = null; private var _context : ExtensionContext = null; /** * "private" singleton constructor */ public function AirDeviceId() { if ( !_instance ) { _context = ExtensionContext.createExtensionContext( EXTENSION_ID, null ); if (_context != null ) { _context.addEventListener( StatusEvent.STATUS, _onStatus ); } else { trace('[AirDeviceId] Error - Extension Context is null.'); } _instance = this; } else { throw Error( 'This is a singleton, use getInstance(), do not call the constructor directly.' ); } } /** * Status events allow the native part of the ANE to communicate with the ActionScript part. * We use event.code to represent the type of event, and event.level to carry the data. */ private function _onStatus( event:StatusEvent ) : void { if ( event.code == AirDeviceIdEvent.RECEIVED_IDFA ) { this.dispatchEvent(new AirDeviceIdEvent(AirDeviceIdEvent.RECEIVED_IDFA, event.level)); } else if ( event.code == "log" ) { trace( '[AirDeviceId] ' + event.level ); } } private static function get isIOS():Boolean { return Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0; } private static function get isAndroid():Boolean { return Capabilities.manufacturer.indexOf("Android") > -1; } } }
remove getID() from AS3 side
remove getID() from AS3 side
ActionScript
apache-2.0
freshplanet/ANE-DeviceId,freshplanet/ANE-DeviceId,freshplanet/ANE-DeviceId
b08298095cce86addd36dd63c0f1a94ccaf5a5a7
csi/flash/src/main/flex/org/shypl/biser/csi/client/Client.as
csi/flash/src/main/flex/org/shypl/biser/csi/client/Client.as
package org.shypl.biser.csi.client { import flash.events.EventDispatcher; import org.shypl.biser.csi.Address; import org.shypl.biser.csi.ConnectionCloseReason; import org.shypl.common.lang.IllegalStateException; import org.shypl.common.logging.LogManager; import org.shypl.common.logging.Logger; import org.shypl.common.logging.PrefixedLoggerProxy; [Event(type="org.shypl.biser.csi.client.ClientEvent", name="clientConnected")] [Event(type="org.shypl.biser.csi.client.ClientEvent", name="clientConnectionInterrupted")] [Event(type="org.shypl.biser.csi.client.ClientEvent", name="clientConnectionEstablished")] [Event(type="org.shypl.biser.csi.client.ClientConnectFailEvent", name="clientConnectFail")] [Event(type="org.shypl.biser.csi.client.ClientDisconnectedEvent", name="clientDisconnected")] [Event(type="org.shypl.biser.csi.client.ClientDisconnectWarningEvent", name="clientDisconnectWarning")] public class Client extends EventDispatcher { private static const LOGGER:Logger = LogManager.getLogger(Client); private var _channelProvider:ChannelProvider; private var _api:Api; private var _logger:PrefixedLoggerProxy; private var _connecting:Boolean; private var _connected:Boolean; private var _connection:Connection; public function Client(channelProvider:ChannelProvider, api:Api) { _channelProvider = channelProvider; _api = api; _logger = new PrefixedLoggerProxy(LOGGER, "[" + _api.name + "] "); } internal function get channelProvider():ChannelProvider { return _channelProvider; } internal function get api():Api { return _api; } public function isConnecting():Boolean { return _connecting; } public function isConnected():Boolean { return _connected; } public function connect(address:Address, authorizationKey:String):void { if (isConnecting() || isConnected()) { throw new IllegalStateException(); } _logger.info("Connecting to {}", address); _connecting = true; _connection = new Connection(this, address, authorizationKey); _api.setConnection(_connection); } public function disconnect():void { if (!isConnecting() && !isConnecting()) { throw new IllegalStateException(); } _connecting = false; _logger.info("Disconnecting"); _connection.close(ConnectionCloseReason.NONE); } internal function processConnected():void { _logger.info("Connected"); _connecting = false; _connected = true; dispatchEvent(new ClientEvent(ClientEvent.CLIENT_CONNECTED)); } internal function processDisconnected(reason:ConnectionCloseReason):void { _logger.info("Disconnected by reason {}", reason); _connecting = false; _connected = false; _connection = null; _api.setConnection(null); dispatchEvent(new ClientDisconnectedEvent(reason)); } internal function processConnectFail(reason:Error):void { _logger.info("Connect failed by reason {}", reason); _connecting = false; _connected = false; dispatchEvent(new ClientConnectFailEvent(reason)); } internal function processConnectionInterrupted():void { _logger.info("Connection is interrupted"); dispatchEvent(new ClientEvent(ClientEvent.CLIENT_CONNECTION_INTERRUPTED)); } internal function processConnectionEstablished():void { _logger.info("Connection is established"); dispatchEvent(new ClientEvent(ClientEvent.CLIENT_CONNECTION_ESTABLISHED)); } internal function processDisconnectWarning(timeout:int):void { _logger.info("warning to disconnect after {} seconds", timeout); dispatchEvent(new ClientDisconnectWarningEvent(timeout)); } } }
package org.shypl.biser.csi.client { import flash.events.EventDispatcher; import org.shypl.biser.csi.Address; import org.shypl.biser.csi.ConnectionCloseReason; import org.shypl.common.lang.IllegalStateException; import org.shypl.common.logging.LogManager; import org.shypl.common.logging.Logger; import org.shypl.common.logging.PrefixedLoggerProxy; [Event(type="org.shypl.biser.csi.client.ClientEvent", name="clientConnected")] [Event(type="org.shypl.biser.csi.client.ClientEvent", name="clientConnectionInterrupted")] [Event(type="org.shypl.biser.csi.client.ClientEvent", name="clientConnectionEstablished")] [Event(type="org.shypl.biser.csi.client.ClientConnectFailEvent", name="clientConnectFail")] [Event(type="org.shypl.biser.csi.client.ClientDisconnectedEvent", name="clientDisconnected")] [Event(type="org.shypl.biser.csi.client.ClientDisconnectWarningEvent", name="clientDisconnectWarning")] public class Client extends EventDispatcher { private static const LOGGER:Logger = LogManager.getLogger(Client); private var _channelProvider:ChannelProvider; private var _api:Api; private var _logger:PrefixedLoggerProxy; private var _connecting:Boolean; private var _connected:Boolean; private var _connection:Connection; public function Client(channelProvider:ChannelProvider, api:Api) { _channelProvider = channelProvider; _api = api; _logger = new PrefixedLoggerProxy(LOGGER, "[" + _api.name + "] "); } internal function get channelProvider():ChannelProvider { return _channelProvider; } internal function get api():Api { return _api; } public function isConnecting():Boolean { return _connecting; } public function isConnected():Boolean { return _connected; } public function connect(address:Address, authorizationKey:String):void { if (isConnecting() || isConnected()) { throw new IllegalStateException(); } _logger.info("Connecting to {}", address); _connecting = true; _connection = new Connection(this, address, authorizationKey); _api.setConnection(_connection); } public function disconnect():void { if (!_connecting && !_connected) { throw new IllegalStateException(); } _connecting = false; _logger.info("Disconnecting"); _connection.close(ConnectionCloseReason.NONE); } internal function processConnected():void { _logger.info("Connected"); _connecting = false; _connected = true; dispatchEvent(new ClientEvent(ClientEvent.CLIENT_CONNECTED)); } internal function processDisconnected(reason:ConnectionCloseReason):void { _logger.info("Disconnected by reason {}", reason); _connecting = false; _connected = false; _connection = null; _api.setConnection(null); dispatchEvent(new ClientDisconnectedEvent(reason)); } internal function processConnectFail(reason:Error):void { _logger.info("Connect failed by reason {}", reason); _connecting = false; _connected = false; dispatchEvent(new ClientConnectFailEvent(reason)); } internal function processConnectionInterrupted():void { _logger.info("Connection is interrupted"); dispatchEvent(new ClientEvent(ClientEvent.CLIENT_CONNECTION_INTERRUPTED)); } internal function processConnectionEstablished():void { _logger.info("Connection is established"); dispatchEvent(new ClientEvent(ClientEvent.CLIENT_CONNECTION_ESTABLISHED)); } internal function processDisconnectWarning(timeout:int):void { _logger.info("warning to disconnect after {} seconds", timeout); dispatchEvent(new ClientDisconnectWarningEvent(timeout)); } } }
Fix client disconnect
Fix client disconnect
ActionScript
apache-2.0
shypl/biser
f2e1d94e7aa962fc906fe1700fb8ce08ec2ab3d2
src/as/com/threerings/util/EmbeddedSwfLoader.as
src/as/com/threerings/util/EmbeddedSwfLoader.as
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { import flash.display.DisplayObject; import flash.display.Loader; import flash.display.LoaderInfo; import flash.errors.IllegalOperationError; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.utils.ByteArray; import flash.system.ApplicationDomain; import flash.system.LoaderContext; /** * Allows you to load an embeded SWF stored as a Byte Array then access any stored classes * within the SWF. * Embed your swf like: * [Embed(source="foo.swf", mimeType="application/octet-stream"] * Then, instantiate that class and pass it to load() as a ByteArray. * * An Event.COMPLETE will be dispatched upon the successful completion of a call to * {@link load}. IOErrorEvent.IO_ERROR will be dispatched if there's a problem reading the * ByteArray. * * @deprecated Content packs are coming, and symbols can be embedded directly * by using [Embed(source="foo.swf#somesymbol")] */ public class EmbeddedSwfLoader extends EventDispatcher { public function EmbeddedSwfLoader (useSubDomain :Boolean = false) { _useSubDomain = useSubDomain; _loader = new Loader(); _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, dispatchEvent); _loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, dispatchEvent); } // This doesn't work. We cannot write parameters to the contentLoaderInfo. // So: there is no way to pass parameters to content loaded using loadBytes, // and there's no way to pass parameters to any other content without // destroying caching (because you must append them to the url). Stupid flash. // /** // * Set a parameter accessible to the loaded content. // */ // public function setParameter (name :String, val :String) :void // { // _loader.contentLoaderInfo.parameters[name] = val; // } /** * Load the SWF from a Byte Array. A CLASS_LOADED event will be dispatched on successful * completion of the load. If any errors occur, a LOAD_ERROR event will be dispatched. */ public function load (byteArray :ByteArray) :void { var context :LoaderContext = new LoaderContext(); context.applicationDomain = _useSubDomain ? new ApplicationDomain(ApplicationDomain.currentDomain) : ApplicationDomain.currentDomain; _loader.loadBytes(byteArray, context); } /** * Get the top-level display object defined in the loaded SWF. */ public function getContent () :DisplayObject { checkLoaded(); return _loader.content; } /** * Retrieves a class definition from the loaded swf. * * @throws IllegalOperationError when the swf has not completed loading or the class does * not exist */ public function getClass (className :String) :Class { return getSymbol(className) as Class; } /** * Retrieves a Function definition from the loaded swf. * * @throws IllegalOperationError when the swf has not completed loading or the class does * not exist */ public function getFunction (functionName :String) :Function { return getSymbol(functionName) as Function; } /** * Retrieves a symbol definition from the loaded swf. * * @throws IllegalOperationError when the swf has not completed loading or the class does * not exist */ public function getSymbol (symbolName :String) :Object { checkLoaded(); try { return _loader.contentLoaderInfo.applicationDomain.getDefinition(symbolName); } catch (e: Error) { throw new IllegalOperationError(symbolName + " definition not found"); } return null; } /** * Checks if a symbol exists in the library. * * @throws IllegalOperationError when the swf has not completed loading. */ public function isSymbol (className :String) :Boolean { checkLoaded(); return _loader.contentLoaderInfo.applicationDomain.hasDefinition(className); } /** * Validate that the load operation is complete. */ protected function checkLoaded () :void { var loaderInfo :LoaderInfo = _loader.contentLoaderInfo; if (loaderInfo.bytesTotal == 0 || loaderInfo.bytesLoaded != loaderInfo.bytesTotal) { throw new IllegalOperationError("SWF has not completed loading"); } } protected var _loader :Loader; protected var _useSubDomain :Boolean; } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { import flash.display.DisplayObject; import flash.display.Loader; import flash.display.LoaderInfo; import flash.errors.IllegalOperationError; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.utils.ByteArray; import flash.system.ApplicationDomain; import flash.system.LoaderContext; /** * Allows you to load an embeded SWF stored as a Byte Array then access any stored classes * within the SWF. * Embed your swf like: * [Embed(source="foo.swf", mimeType="application/octet-stream")] * Then, instantiate that class and pass it to load() as a ByteArray. * * An Event.COMPLETE will be dispatched upon the successful completion of a call to * {@link load}. IOErrorEvent.IO_ERROR will be dispatched if there's a problem reading the * ByteArray. * * @deprecated Content packs are coming, and symbols can be embedded directly * by using [Embed(source="foo.swf#somesymbol")] */ public class EmbeddedSwfLoader extends EventDispatcher { public function EmbeddedSwfLoader (useSubDomain :Boolean = false) { _useSubDomain = useSubDomain; _loader = new Loader(); _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, dispatchEvent); _loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, dispatchEvent); } // This doesn't work. We cannot write parameters to the contentLoaderInfo. // So: there is no way to pass parameters to content loaded using loadBytes, // and there's no way to pass parameters to any other content without // destroying caching (because you must append them to the url). Stupid flash. // /** // * Set a parameter accessible to the loaded content. // */ // public function setParameter (name :String, val :String) :void // { // _loader.contentLoaderInfo.parameters[name] = val; // } /** * Load the SWF from a Byte Array. A CLASS_LOADED event will be dispatched on successful * completion of the load. If any errors occur, a LOAD_ERROR event will be dispatched. */ public function load (byteArray :ByteArray) :void { var context :LoaderContext = new LoaderContext(); context.applicationDomain = _useSubDomain ? new ApplicationDomain(ApplicationDomain.currentDomain) : ApplicationDomain.currentDomain; _loader.loadBytes(byteArray, context); } /** * Get the top-level display object defined in the loaded SWF. */ public function getContent () :DisplayObject { checkLoaded(); return _loader.content; } /** * Retrieves a class definition from the loaded swf. * * @throws IllegalOperationError when the swf has not completed loading or the class does * not exist */ public function getClass (className :String) :Class { return getSymbol(className) as Class; } /** * Retrieves a Function definition from the loaded swf. * * @throws IllegalOperationError when the swf has not completed loading or the class does * not exist */ public function getFunction (functionName :String) :Function { return getSymbol(functionName) as Function; } /** * Retrieves a symbol definition from the loaded swf. * * @throws IllegalOperationError when the swf has not completed loading or the class does * not exist */ public function getSymbol (symbolName :String) :Object { checkLoaded(); try { return _loader.contentLoaderInfo.applicationDomain.getDefinition(symbolName); } catch (e: Error) { throw new IllegalOperationError(symbolName + " definition not found"); } return null; } /** * Checks if a symbol exists in the library. * * @throws IllegalOperationError when the swf has not completed loading. */ public function isSymbol (className :String) :Boolean { checkLoaded(); return _loader.contentLoaderInfo.applicationDomain.hasDefinition(className); } /** * Validate that the load operation is complete. */ protected function checkLoaded () :void { var loaderInfo :LoaderInfo = _loader.contentLoaderInfo; if (loaderInfo.bytesTotal == 0 || loaderInfo.bytesLoaded != loaderInfo.bytesTotal) { throw new IllegalOperationError("SWF has not completed loading"); } } protected var _loader :Loader; protected var _useSubDomain :Boolean; } }
Comment fix.
Comment fix. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4716 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
c3c2403fe30a100540cfe3449cbdfd9e8ec6e85e
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 { import goog.bind; } /** * @flexjsignoreimport goog.bind */ COMPILE::JS public class Language { //-------------------------------------- // Static Property //-------------------------------------- //-------------------------------------- // Static Function //-------------------------------------- /** * as() * * @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 exception 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 = Language.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() * * @param value The value to be cast. * @return {number} */ static public function _int(value:Number):Number { return value >> 0; } /** * is() * * @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 == null) return false; if (leftOperand != null && rightOperand == null) { return false; } checkInterfaces = function(left:Object):Boolean { var i:int, 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 (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 = superClass.superClass_; if (superClass) { while (superClass && superClass.FLEXJS_CLASS_INFO) { if (superClass.FLEXJS_CLASS_INFO.interfaces) { if (checkInterfaces(superClass)) { return true; } } superClass = superClass.constructor; superClass = superClass.superClass_; } } return false; } /** * postdecrement handles foo++ * * @param obj The object with the getter/setter. * @param 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++ * * @param obj The object with the getter/setter. * @param 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 * * @param obj The object with the getter/setter. * @param 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 * * @param obj The object with the getter/setter. * @param 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. * * @param clazz The class. * @param pthis The this pointer. * @param 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 = superClass.superClass_; superdesc = Object.getOwnPropertyDescriptor(superClass, prop); } return superdesc.get.call(pthis); } /** * superSetter calls the setter on the given class' superclass. * * @param clazz The class. * @param pthis The this pointer. * @param prop The name of the getter. * @param 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 = superClass.superClass_; superdesc = Object.getOwnPropertyDescriptor(superClass, prop); } superdesc.set.apply(pthis, [value]); } static public function trace(...rest):void { var theConsole:*; var windowConsole:* = window.console; var msg:String = ''; for (var i:int = 0; i < rest.length; i++) { if (i > 0) msg += ' '; msg += rest[i]; } theConsole = window["goog"]["global"]["console"]; if (theConsole === undefined && windowConsole !== undefined) theConsole = windowConsole; try { if (theConsole && theConsole.log) { theConsole.log(msg); } } catch (e:Error) { // ignore; at least we tried ;-) } } /** * uint() * * @param value The value to be cast. * @return {number} */ static public function uint(value:Number):Number { return value >>> 0; } /** * caches closures and returns the one closure * * @param fn The method on the instance. * @param object The instance. * @param boundMethodName The name to use to cache the closure. * @return The closure. */ static public function closure(fn:Function, object:Object, boundMethodName:String):Function { if (object.hasOwnProperty(boundMethodName)) { return object[boundMethodName]; } var boundMethod:Function = goog.bind(fn, object); Object.defineProperty(object, boundMethodName, { value: boundMethod }); return boundMethod; }; } }
//////////////////////////////////////////////////////////////////////////////// // // 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 { import goog.bind; import goog.global; } /** * @flexjsignoreimport goog.bind * @flexjsignoreimport goog.global */ COMPILE::JS public class Language { //-------------------------------------- // Static Property //-------------------------------------- //-------------------------------------- // Static Function //-------------------------------------- /** * as() * * @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 exception 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 = Language.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() * * @param value The value to be cast. * @return {number} */ static public function _int(value:Number):Number { return value >> 0; } /** * is() * * @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 == null) return false; if (leftOperand != null && rightOperand == null) { return false; } checkInterfaces = function(left:Object):Boolean { var i:int, 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 (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 = superClass.superClass_; if (superClass) { while (superClass && superClass.FLEXJS_CLASS_INFO) { if (superClass.FLEXJS_CLASS_INFO.interfaces) { if (checkInterfaces(superClass)) { return true; } } superClass = superClass.constructor; superClass = superClass.superClass_; } } return false; } /** * postdecrement handles foo++ * * @param obj The object with the getter/setter. * @param 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++ * * @param obj The object with the getter/setter. * @param 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 * * @param obj The object with the getter/setter. * @param 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 * * @param obj The object with the getter/setter. * @param 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. * * @param clazz The class. * @param pthis The this pointer. * @param 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 = superClass.superClass_; superdesc = Object.getOwnPropertyDescriptor(superClass, prop); } return superdesc.get.call(pthis); } /** * superSetter calls the setter on the given class' superclass. * * @param clazz The class. * @param pthis The this pointer. * @param prop The name of the getter. * @param 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 = superClass.superClass_; superdesc = Object.getOwnPropertyDescriptor(superClass, prop); } superdesc.set.apply(pthis, [value]); } static public function trace(...rest):void { var theConsole:*; var windowConsole:* = window.console; var msg:String = ''; for (var i:int = 0; i < rest.length; i++) { if (i > 0) msg += ' '; msg += rest[i]; } theConsole = goog.global.console; if (theConsole === undefined && windowConsole !== undefined) theConsole = windowConsole; try { if (theConsole && theConsole.log) { theConsole.log(msg); } } catch (e:Error) { // ignore; at least we tried ;-) } } /** * uint() * * @param value The value to be cast. * @return {number} */ static public function uint(value:Number):Number { return value >>> 0; } /** * caches closures and returns the one closure * * @param fn The method on the instance. * @param object The instance. * @param boundMethodName The name to use to cache the closure. * @return The closure. */ static public function closure(fn:Function, object:Object, boundMethodName:String):Function { if (object.hasOwnProperty(boundMethodName)) { return object[boundMethodName]; } var boundMethod:Function = goog.bind(fn, object); Object.defineProperty(object, boundMethodName, { value: boundMethod }); return boundMethod; }; } }
fix trace
fix trace
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
c20791327b41070b5de2d34c49be14eb766be31d
src/avm2/tests/regress/correctness/callsuper7.as
src/avm2/tests/regress/correctness/callsuper7.as
package { class ClassA { public function ClassA() { trace('A'); } protected function foo() : void { trace('a'); } protected function bar() : void { trace('b'); } } class ClassC extends ClassA { public function ClassC() { trace('> C'); super(); foo(); bar(); trace('< C'); } override protected function bar() : void { super.bar(); trace('override b'); } } class ClassE extends ClassC { public function ClassE() { trace('> E'); super(); foo(); bar(); trace('< E'); } override protected function bar() : void { super.bar(); trace('override b again'); } } // var c = new ClassC(); // var e = new ClassE(); class X { protected var } trace("--"); }
package { class ClassA { public function ClassA() { trace('A'); } protected function foo() : void { trace('a'); } protected function bar() : void { trace('b'); } } class ClassC extends ClassA { public function ClassC() { trace('> C'); super(); foo(); bar(); trace('< C'); } override protected function bar() : void { super.bar(); trace('override b'); } } class ClassE extends ClassC { public function ClassE() { trace('> E'); super(); foo(); bar(); trace('< E'); } override protected function bar() : void { super.bar(); trace('override b again'); } } trace("--"); }
Fix call super test case.
Fix call super test case.
ActionScript
apache-2.0
mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,mbebenita/shumway
717e467aa0fbd9f4875ebc2c92b32db5a8c2ebba
Impetus.swf/ImpetusSound.as
Impetus.swf/ImpetusSound.as
package { import flash.media.Sound; import flash.media.SoundChannel; import flash.net.URLRequest; public class ImpetusSound { private var url:String; private var sound:Sound; private var channel:SoundChannel; public function ImpetusSound(url:String):void { this.url = url; this.sound = new Sound(); this.sound.load(new URLRequest(url)); this.channel = null; } public function getUrl():String { return this.url } public function play():void { } public function stop():void { this.channel.stop(); this.channel = null; } public function setPos(pos:int):void { } public function getPos():int { } } }
package { import flash.media.Sound; import flash.media.SoundChannel; import flash.net.URLRequest; public class ImpetusSound { private var url:String; private var sound:Sound; private var channel:SoundChannel; public function ImpetusSound(url:String):void { this.url = url; this.sound = new Sound(); this.sound.load(new URLRequest(url)); this.channel = null; } public function getUrl():String { return this.url } public function play():void { if(this.channel != null) { this.channel.stop(); } this.channel = sound.play(0); } public function stop():void { this.channel.stop(); this.channel = null; } public function setPos(pos:int):void { } public function getPos():int { } } }
Implement ImpetusSound::play()
Implement ImpetusSound::play()
ActionScript
mit
Julow/Impetus
8bf1c1fc45c368583ca376658d48af0d31613f8a
src/aerys/minko/render/DrawCall.as
src/aerys/minko/render/DrawCall.as
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } public function get depth() : Number { if (_invalidDepth) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { _localToWorld.transformVector(Vector4.ZERO, TMP_VECTOR4); var screenSpacePosition : Vector4 = _worldToScreen.transformVector(TMP_VECTOR4, TMP_VECTOR4); _depth = screenSpacePosition.z / screenSpacePosition.w; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { // if (_bindings != null) // unsetBindings(meshBindings, sceneBindings); _invalidDepth = computeDepth; setProgram(program); updateGeometry(geometry); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { for (var parameter : String in _bindings) { meshBindings.removeCallback(parameter, parameterChangedHandler); sceneBindings.removeCallback(parameter, parameterChangedHandler); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.concat(); _fsConstants = program._fsConstants.concat(); _fsTextures = program._fsTextures.concat(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(StreamUsage.DYNAMIC); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !vertexFormat.hasComponent(VertexComponent.NORMAL)) { geometry.computeNormals(StreamUsage.DYNAMIC); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { for (var parameter : String in _bindings) { meshBindings.addCallback(parameter, parameterChangedHandler); sceneBindings.addCallback(parameter, parameterChangedHandler); if (meshBindings.propertyExists(parameter)) setParameter(parameter, meshBindings.getProperty(parameter)); else if (sceneBindings.propertyExists(parameter)) setParameter(parameter, sceneBindings.getProperty(parameter)); } if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getNativeTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { var binding : IBinder = _bindings[name] as IBinder; if (binding != null) binding.set(_cpuConstants, _vsConstants, _fsConstants, _fsTextures, value); } private function parameterChangedHandler(dataBindings : DataBindings, property : String, oldValue : Object, newValue : Object) : void { newValue !== null && setParameter(property, newValue); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } public function get depth() : Number { if (_invalidDepth) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { _localToWorld.transformVector(Vector4.ZERO, TMP_VECTOR4); var screenSpacePosition : Vector4 = _worldToScreen.transformVector(TMP_VECTOR4, TMP_VECTOR4); _depth = screenSpacePosition.z / screenSpacePosition.w; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { // if (_bindings != null) // unsetBindings(meshBindings, sceneBindings); _invalidDepth = computeDepth; setProgram(program); updateGeometry(geometry); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { for (var parameter : String in _bindings) { meshBindings.removeCallback(parameter, parameterChangedHandler); sceneBindings.removeCallback(parameter, parameterChangedHandler); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.concat(); _fsConstants = program._fsConstants.concat(); _fsTextures = program._fsTextures.concat(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !vertexFormat.hasComponent(VertexComponent.NORMAL)) { geometry.computeNormals(); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { for (var parameter : String in _bindings) { meshBindings.addCallback(parameter, parameterChangedHandler); sceneBindings.addCallback(parameter, parameterChangedHandler); if (meshBindings.propertyExists(parameter)) setParameter(parameter, meshBindings.getProperty(parameter)); else if (sceneBindings.propertyExists(parameter)) setParameter(parameter, sceneBindings.getProperty(parameter)); } if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getNativeTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { var binding : IBinder = _bindings[name] as IBinder; if (binding != null) binding.set(_cpuConstants, _vsConstants, _fsConstants, _fsTextures, value); } private function parameterChangedHandler(dataBindings : DataBindings, property : String, oldValue : Object, newValue : Object) : void { newValue !== null && setParameter(property, newValue); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
update DrawCall.updateGeometry() to use default arguments for Geometry.computeTangentsSpace() and Geometry.computeNormals()
update DrawCall.updateGeometry() to use default arguments for Geometry.computeTangentsSpace() and Geometry.computeNormals()
ActionScript
mit
aerys/minko-as3
10d9a660441e9a505132b1810ff8fd751d59d857
src/flash/plupload/src/com/mxi/image/JPEG.as
src/flash/plupload/src/com/mxi/image/JPEG.as
/** * Copyright 2011, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ package com.mxi.image { import com.mxi.BinaryReader; import flash.external.ExternalInterface; import flash.utils.ByteArray; public class JPEG { protected var _markers:Object = { 0xFFE1: { app: 'EXIF', name: 'APP1', signature: "Exif" }, 0xFFE2: { app: 'ICC', name: 'APP2', signature: "ICC_PROFILE" }, 0xFFED: { app: 'IPTC', name: 'APP13', signature: "Photoshop 3.0" } }; protected var _headers:Array = []; protected var _br:BinaryReader; public function JPEG(binData:ByteArray) { _br = new BinaryReader; _br.init(binData); } static public function test(binData:ByteArray) : Boolean { var sign:Array = [ 255, 216 ]; for (var i:int = sign.length - 1; i >= 0 ; i--) { if (binData[i] != sign[i]) { return false; } } return true; } public function info() : Object { var idx:uint = 0, marker:uint, length:uint, limit:uint; limit = Math.min(1048576, _br.length); while (idx <= limit) { // make sure we examine just enough data marker = _br.SHORT(idx += 2); if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte) return { height: _br.SHORT(idx), width: _br.SHORT(idx += 2) }; } length = _br.SHORT(idx += 2); idx += length - 2; } return null; } public function extractHeaders() : Array { var idx:uint, limit:uint, marker:uint, length:uint; idx = 2; limit = Math.min(1048576, _br.length); while (idx <= limit) { marker = _br.SHORT(idx); // omit RST (restart) markers if (marker >= 0xFFD0 && marker <= 0xFFD7) { idx += 2; continue; } // no headers allowed after SOS marker if (marker === 0xFFDA || marker === 0xFFD9) { break; } length = _br.SHORT(idx + 2) + 2; if (_markers[marker] && _br.STRING(idx + 4, _markers[marker].signature.length) === _markers[marker].signature) { _headers.push({ hex: marker, app: _markers[marker].app.toUpperCase(), name: _markers[marker].name.toUpperCase(), start: idx, length: length, segment: _br.SEGMENT(idx, length) }); } idx += length; } return _headers; } public function getHeaders(app:String = null) : Array { var headers:Array, array:Array = []; headers = _headers.length ? _headers : extractHeaders(); if (!app) { return headers; } for (var i:uint = 0, max:uint = headers.length; i < max; i++) { if (headers[i].app === app.toUpperCase()) { array.push(headers[i].segment); } } return array; } public function setHeaders(app:String, segment:*) : void { var array:Array = []; if (segment is ByteArray) { array.push(segment); } else { array = segment; } for (var i:uint = 0, ii:uint = 0, max:uint = _headers.length; i < max; i++) { if (_headers[i].app === app.toUpperCase()) { _headers[i].segment = array[ii]; _headers[i].length = array[ii].length; ii++; } if (ii >= array.length) break; } } public function insertHeaders(binData:ByteArray, headers:Array = null) : ByteArray { var idx:uint, br:BinaryReader = new BinaryReader; if (!headers || !headers.length) { headers = _headers; } br.init(binData); // Check if data is jpeg if (br.SHORT(0) !== 0xFFD8) { throw new Error("Invalid JPEG"); } if (headers.length) { idx = br.SHORT(2) == 0xFFE0 ? 4 + br.SHORT(4) : 2; for (var i:uint = 0, max:uint = headers.length; i < max; i++) { br.SEGMENT(idx, 0, headers[i].segment); idx += headers[i].length; } } return br.SEGMENT(); } public function purge() : void { _br.clear(); } } }
/** * Copyright 2011, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ package com.mxi.image { import com.mxi.BinaryReader; import flash.external.ExternalInterface; import flash.utils.ByteArray; public class JPEG { protected var _markers:Object = { 0xFFE1: { app: 'EXIF', name: 'APP1', signature: "Exif" }, 0xFFE2: { app: 'ICC', name: 'APP2', signature: "ICC_PROFILE" }, 0xFFED: { app: 'IPTC', name: 'APP13', signature: "Photoshop 3.0" } }; protected var _headers:Array = []; protected var _br:BinaryReader; public function JPEG(binData:ByteArray) { _br = new BinaryReader; _br.init(binData); } static public function test(binData:ByteArray) : Boolean { var sign:Array = [ 255, 216 ]; for (var i:int = sign.length - 1; i >= 0 ; i--) { if (binData[i] != sign[i]) { return false; } } return true; } public function info() : Object { var idx:uint = 0, marker:uint, length:uint; // examine all through the end, since some images might have very large APP segments while (idx <= _br.length) { marker = _br.SHORT(idx += 2); if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte) return { height: _br.SHORT(idx), width: _br.SHORT(idx += 2) }; } length = _br.SHORT(idx += 2); idx += length - 2; } return null; } public function extractHeaders() : Array { var idx:uint, marker:uint, length:uint; idx = 2; while (idx <= _br.length) { marker = _br.SHORT(idx); // omit RST (restart) markers if (marker >= 0xFFD0 && marker <= 0xFFD7) { idx += 2; continue; } // no headers allowed after SOS marker if (marker === 0xFFDA || marker === 0xFFD9) { break; } length = _br.SHORT(idx + 2) + 2; if (_markers[marker] && _br.STRING(idx + 4, _markers[marker].signature.length) === _markers[marker].signature) { _headers.push({ hex: marker, app: _markers[marker].app.toUpperCase(), name: _markers[marker].name.toUpperCase(), start: idx, length: length, segment: _br.SEGMENT(idx, length) }); } idx += length; } return _headers; } public function getHeaders(app:String = null) : Array { var headers:Array, array:Array = []; headers = _headers.length ? _headers : extractHeaders(); if (!app) { return headers; } for (var i:uint = 0, max:uint = headers.length; i < max; i++) { if (headers[i].app === app.toUpperCase()) { array.push(headers[i].segment); } } return array; } public function setHeaders(app:String, segment:*) : void { var array:Array = []; if (segment is ByteArray) { array.push(segment); } else { array = segment; } for (var i:uint = 0, ii:uint = 0, max:uint = _headers.length; i < max; i++) { if (_headers[i].app === app.toUpperCase()) { _headers[i].segment = array[ii]; _headers[i].length = array[ii].length; ii++; } if (ii >= array.length) break; } } public function insertHeaders(binData:ByteArray, headers:Array = null) : ByteArray { var idx:uint, br:BinaryReader = new BinaryReader; if (!headers || !headers.length) { headers = _headers; } br.init(binData); // Check if data is jpeg if (br.SHORT(0) !== 0xFFD8) { throw new Error("Invalid JPEG"); } if (headers.length) { idx = br.SHORT(2) == 0xFFE0 ? 4 + br.SHORT(4) : 2; for (var i:uint = 0, max:uint = headers.length; i < max; i++) { br.SEGMENT(idx, 0, headers[i].segment); idx += headers[i].length; } } return br.SEGMENT(); } public function purge() : void { _br.clear(); } } }
Remove limit on JPEG format check - performance gain negligible, but in some cases causes wrong IMAGE_FORMAT_ERRORs.
Flash: Remove limit on JPEG format check - performance gain negligible, but in some cases causes wrong IMAGE_FORMAT_ERRORs.
ActionScript
agpl-3.0
vitr/fend005-plupload,envato/plupload,moxiecode/plupload,moxiecode/plupload,envato/plupload,vitr/fend005-plupload
78d71dcef7c44b3335f60ab0d605761e3844a353
lib/src/com/amanitadesign/steam/SteamConstants.as
lib/src/com/amanitadesign/steam/SteamConstants.as
package com.amanitadesign.steam { public class SteamConstants { public static const RESPONSE_OK:int = 1; public static const RESPONSE_FAILED:int = 2; public static const RESPONSE_OnUserStatsReceived:int = 0; public static const RESPONSE_OnUserStatsStored:int = 1; public static const RESPONSE_OnAchievementStored:int = 2; public static const RESPONSE_OnGameOverlayActivated:int = 3; } }
package com.amanitadesign.steam { public class SteamConstants { public static const RESPONSE_OK:int = 0; public static const RESPONSE_FAILED:int = 1; public static const RESPONSE_OnUserStatsReceived:int = 0; public static const RESPONSE_OnUserStatsStored:int = 1; public static const RESPONSE_OnAchievementStored:int = 2; public static const RESPONSE_OnGameOverlayActivated:int = 3; } }
Fix response values
Fix response values
ActionScript
bsd-2-clause
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
34527c2d24fd548de14e475112d730e9c5036534
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/beads/layouts/FlexibleFirstChildHorizontalLayout.as
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/beads/layouts/FlexibleFirstChildHorizontalLayout.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.layouts { import org.apache.flex.core.IBeadLayout; import org.apache.flex.core.ILayoutParent; import org.apache.flex.core.IStrand; import org.apache.flex.core.IParent; 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; /** * The FlexibleFirstChildHorizontalLayout class is a simple layout * bead. It takes the set of children and lays them out * horizontally in one row, separating them according to * CSS layout rules for margin and padding styles. But it * will size the first child to take up as much or little * room as possible. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class FlexibleFirstChildHorizontalLayout implements IBeadLayout { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function FlexibleFirstChildHorizontalLayout() { } private var _strand:IStrand; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(value).addEventListener("layoutNeeded", changeHandler); IEventDispatcher(value).addEventListener("widthChanged", changeHandler); IEventDispatcher(value).addEventListener("childrenAdded", changeHandler); IEventDispatcher(value).addEventListener("itemsCreated", changeHandler); } private function changeHandler(event:Event):void { var layoutParent:ILayoutParent = _strand.getBeadByType(ILayoutParent) as ILayoutParent; var contentView:IParent = layoutParent.contentView; var n:int = contentView.numElements; var marginLeft:Object; var marginRight:Object; var marginTop:Object; var marginBottom:Object; var margin:Object; var maxHeight:Number = 0; var verticalMargins:Array = []; var xx:Number = layoutParent.resizableView.width; var padding:Object = determinePadding(); xx -= padding.paddingLeft + padding.paddingRight; for (var i:int = n - 1; i >= 0; i--) { var child:IUIBase = contentView.getElementAt(i) as IUIBase; margin = ValuesManager.valuesImpl.getValue(child, "margin"); if (margin is Array) { if (margin.length == 1) marginLeft = marginTop = marginRight = marginBottom = margin[0]; else if (margin.length <= 3) { marginLeft = marginRight = margin[1]; marginTop = marginBottom = margin[0]; } else if (margin.length == 4) { marginLeft = margin[3]; marginBottom = margin[2]; marginRight = margin[1]; marginTop = margin[0]; } } else if (margin == null) { marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left"); marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top"); marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right"); marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom"); } else { marginLeft = marginTop = marginBottom = marginRight = margin; } var ml:Number; var mr:Number; var mt:Number; var mb:Number; var lastmr:Number; mt = Number(marginTop); if (isNaN(mt)) mt = 0; mb = Number(marginBottom); if (isNaN(mb)) mb = 0; if (marginLeft == "auto") ml = 0; else { ml = Number(marginLeft); if (isNaN(ml)) ml = 0; } if (marginRight == "auto") mr = 0; else { mr = Number(marginRight); if (isNaN(mr)) mr = 0; } child.y = mt; maxHeight = Math.max(maxHeight, ml + child.height + mr); if (i == 0) { child.x = ml; child.width = xx - mr; } else child.x = xx - child.width - mr; xx -= child.width + mr + ml; lastmr = mr; var valign:Object = ValuesManager.valuesImpl.getValue(child, "vertical-align"); verticalMargins.push({ marginTop: mt, marginBottom: mb, valign: valign }); } for (i = 0; i < n; i++) { var obj:Object = verticalMargins[0] child = contentView.getElementAt(i) as IUIBase; if (obj.valign == "middle") child.y = maxHeight - child.height / 2; else if (valign == "bottom") child.y = maxHeight - child.height - obj.marginBottom; else child.y = obj.marginTop; } layoutParent.resizableView.height = maxHeight; } // TODO (aharui): utility class or base class /** * 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 padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding"); if (typeof(padding) == "Array") { if (padding.length == 1) paddingLeft = paddingTop = paddingRight = padding[0]; else if (padding.length <= 3) { paddingLeft = padding[1]; paddingTop = padding[0]; paddingRight = padding[1]; } else if (padding.length == 4) { paddingLeft = padding[3]; paddingTop = padding[0]; paddingRight = padding[1]; } } 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"); } else { paddingLeft = paddingTop = paddingRight = padding; } var pl:Number = Number(paddingLeft); var pt:Number = Number(paddingTop); var pr:Number = Number(paddingRight); return {paddingLeft:pl, paddingTop:pt, paddingRight:pr}; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.layouts { import org.apache.flex.core.IBeadLayout; import org.apache.flex.core.ILayoutParent; import org.apache.flex.core.IStrand; import org.apache.flex.core.IParent; 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; /** * The FlexibleFirstChildHorizontalLayout class is a simple layout * bead. It takes the set of children and lays them out * horizontally in one row, separating them according to * CSS layout rules for margin and padding styles. But it * will size the first child to take up as much or little * room as possible. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class FlexibleFirstChildHorizontalLayout implements IBeadLayout { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function FlexibleFirstChildHorizontalLayout() { } private var _strand:IStrand; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(value).addEventListener("layoutNeeded", changeHandler); IEventDispatcher(value).addEventListener("widthChanged", changeHandler); IEventDispatcher(value).addEventListener("childrenAdded", changeHandler); IEventDispatcher(value).addEventListener("itemsCreated", changeHandler); } private function changeHandler(event:Event):void { var layoutParent:ILayoutParent = _strand.getBeadByType(ILayoutParent) as ILayoutParent; var contentView:IParent = layoutParent.contentView; var n:int = contentView.numElements; var marginLeft:Object; var marginRight:Object; var marginTop:Object; var marginBottom:Object; var margin:Object; var maxHeight:Number = 0; var verticalMargins:Array = []; var xx:Number = layoutParent.resizableView.width; var padding:Object = determinePadding(); xx -= padding.paddingLeft + padding.paddingRight; for (var i:int = n - 1; i >= 0; i--) { var child:IUIBase = contentView.getElementAt(i) as IUIBase; margin = ValuesManager.valuesImpl.getValue(child, "margin"); if (margin is Array) { if (margin.length == 1) marginLeft = marginTop = marginRight = marginBottom = margin[0]; else if (margin.length <= 3) { marginLeft = marginRight = margin[1]; marginTop = marginBottom = margin[0]; } else if (margin.length == 4) { marginLeft = margin[3]; marginBottom = margin[2]; marginRight = margin[1]; marginTop = margin[0]; } } else if (margin == null) { marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left"); marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top"); marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right"); marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom"); } else { marginLeft = marginTop = marginBottom = marginRight = margin; } var ml:Number; var mr:Number; var mt:Number; var mb:Number; var lastmr:Number; mt = Number(marginTop); if (isNaN(mt)) mt = 0; mb = Number(marginBottom); if (isNaN(mb)) mb = 0; if (marginLeft == "auto") ml = 0; else { ml = Number(marginLeft); if (isNaN(ml)) ml = 0; } if (marginRight == "auto") mr = 0; else { mr = Number(marginRight); if (isNaN(mr)) mr = 0; } child.y = mt; maxHeight = Math.max(maxHeight, mt + child.height + mb); if (i == 0) { child.x = ml; child.width = xx - mr; } else child.x = xx - child.width - mr; xx -= child.width + mr + ml; lastmr = mr; var valign:Object = ValuesManager.valuesImpl.getValue(child, "vertical-align"); verticalMargins.push({ marginTop: mt, marginBottom: mb, valign: valign }); } for (i = 0; i < n; i++) { var obj:Object = verticalMargins[0] child = contentView.getElementAt(i) as IUIBase; if (obj.valign == "middle") child.y = maxHeight - child.height / 2; else if (valign == "bottom") child.y = maxHeight - child.height - obj.marginBottom; else child.y = obj.marginTop; } layoutParent.resizableView.height = maxHeight; } // TODO (aharui): utility class or base class /** * 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 padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding"); if (typeof(padding) == "Array") { if (padding.length == 1) paddingLeft = paddingTop = paddingRight = padding[0]; else if (padding.length <= 3) { paddingLeft = padding[1]; paddingTop = padding[0]; paddingRight = padding[1]; } else if (padding.length == 4) { paddingLeft = padding[3]; paddingTop = padding[0]; paddingRight = padding[1]; } } 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"); } else { paddingLeft = paddingTop = paddingRight = padding; } var pl:Number = Number(paddingLeft); var pt:Number = Number(paddingTop); var pr:Number = Number(paddingRight); return {paddingLeft:pl, paddingTop:pt, paddingRight:pr}; } } }
fix height calculation
fix height calculation
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
6bddc435b03b1a475974578b3ab34811dd6eb876
mustella/as3/src/mustella/IncludeFileLocation.as
mustella/as3/src/mustella/IncludeFileLocation.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package { import flash.display.DisplayObject; import flash.net.URLLoader; import flash.net.URLRequest; import flash.events.Event; import flash.system.Capabilities; [Mixin] /** * A hash table of tests not to run, read from IncludeList.txt * The file is one test per line of the form ScriptName$TestID * The location of the file is assumed to be c:/tmp on windows, * or /tmp on Unix */ public class IncludeFileLocation { private static var loader:URLLoader; /** * tell UnitTester it should wait for this load to complete */ UnitTester.waitForIncludes = true; /** * Mixin callback that gets everything ready to go. * Table is of form: ScriptName$TestID: 1, */ public static function init(root:DisplayObject):void { var currentOS:String = Capabilities.os; var useFile:String; if (currentOS.indexOf ("Windows") != -1) { useFile = "c:/tmp/IncludeList.txt"; } else { useFile = "/tmp/IncludeList.txt"; } var req:URLRequest = new URLRequest(useFile); loader = new URLLoader(); loader.addEventListener("complete", completeHandler); loader.load(req); } private static function completeHandler(event:Event):void { var data:String = loader.data; // DOS end of line var delimiter:RegExp = new RegExp("\r\n", "g"); data = data.replace(delimiter, ","); // Unix end of line delimiter = new RegExp("\n", "g"); data = data.replace(delimiter, ","); UnitTester.includeList = new Object(); var items:Array = data.split(","); var n:int = items.length; for (var i:int = 0; i < n; i++) { var s:String = items[i]; if (s.length) UnitTester.includeList[s] = 1; } UnitTester.waitForIncludes = false; UnitTester.pre_startEventHandler(event); } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package { import flash.display.DisplayObject; import flash.net.URLLoader; import flash.net.URLRequest; import flash.events.Event; import flash.system.Capabilities; import flash.system.Security; [Mixin] /** * A hash table of tests not to run, read from IncludeList.txt * The file is one test per line of the form ScriptName$TestID * The location of the file is assumed to be c:/tmp on windows, * or /tmp on Unix */ public class IncludeFileLocation { private static var loader:URLLoader; /** * tell UnitTester it should wait for this load to complete */ UnitTester.waitForIncludes = true; /** * Mixin callback that gets everything ready to go. * Table is of form: ScriptName$TestID: 1, */ public static function init(root:DisplayObject):void { var currentOS:String = Capabilities.os; var useFile:String; if (currentOS.indexOf ("Windows") != -1) { useFile = "c:/tmp/IncludeList.txt"; } else { useFile = "/tmp/IncludeList.txt"; if (Security.sandboxType == Security.APPLICATION) useFile = "file:///tmp/IncludeList.txt"; } var req:URLRequest = new URLRequest(useFile); loader = new URLLoader(); loader.addEventListener("complete", completeHandler); loader.load(req); } private static function completeHandler(event:Event):void { var data:String = loader.data; // DOS end of line var delimiter:RegExp = new RegExp("\r\n", "g"); data = data.replace(delimiter, ","); // Unix end of line delimiter = new RegExp("\n", "g"); data = data.replace(delimiter, ","); UnitTester.includeList = new Object(); var items:Array = data.split(","); var n:int = items.length; for (var i:int = 0; i < n; i++) { var s:String = items[i]; if (s.length) UnitTester.includeList[s] = 1; } UnitTester.waitForIncludes = false; UnitTester.pre_startEventHandler(event); } } }
Allow -failures to work on AIR on Mac. Might need fixing on Windows, but haven't tried it yet.
Allow -failures to work on AIR on Mac. Might need fixing on Windows, but haven't tried it yet. git-svn-id: 7d913817b0a978d84de757191e4bce372605a781@1402724 13f79535-47bb-0310-9956-ffa450edef68
ActionScript
apache-2.0
shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,apache/flex-sdk
1604e84c787e15d041312d69553e72e7f6463f94
src/net/manaca/utils/Cookie.as
src/net/manaca/utils/Cookie.as
package net.manaca.utils { import flash.net.SharedObject; import flash.utils.Proxy; import flash.utils.flash_proxy; /** * The Cookie carry a proxy provide a more useful SharedObject. * @author v-seanzo * */ dynamic public class Cookie extends Proxy { //========================================================================== // Constructor //========================================================================== /** * Constructs a new <code>Cookie</code> instance. * @param name the SharedObject name. * @param timeOut the value time out value. * */ public function Cookie(name:String, timeOut:Number = 3600) { super(); this._name = name; this._timeOut = timeOut; _so = SharedObject.getLocal(name); } //========================================================================== // Variables //========================================================================== private var _name:String; private var _timeOut:Number; private var _so:SharedObject; //========================================================================== // Properties //========================================================================== /** * The SharedObject name. * @return * */ public function getName():String { return _name; } /** * Get time out value. * @return * */ public function getTimeOut():Number { return _timeOut; } /** * Get the SharedObject size. * @return * */ public function getSize():uint { return _so.size; } //========================================================================== // Methods //========================================================================== /** * Clear when timeout. */ public function clearTimeOut():void { var obj:* = _so.data.cookie; if (obj == null) return; for (var key:String in obj) { if (isTimeOut(obj[key].time)) { remove(key); } } _so.flush(); } /** * Remove all cookie. * */ public function clear():void { _so.clear(); _so.flush(); } /** * Check timeout. * @param time * @return * */ public function isTimeOut(time:Number):Boolean { var today:Date = new Date(); return time + _timeOut * 1000 < today.getTime(); } /** * Check Cookie item exist. * @param key * @return * */ public function isExist(key:String):Boolean { return _so.data.cookie != null && _so.data.cookie[key] != null; } /** * Remove Cookie item by key. * @param key * */ public function remove(key:String):void { if (isExist(key)) { delete _so.data.cookie[key]; _so.flush(); } } /** * * @param name * @return * */ override flash_proxy function getProperty(name:*):* { return isExist(name) ? _so.data.cookie[name].value : null; } /** * * @param name * @param value * */ override flash_proxy function setProperty(name:*, value:*):void { var obj:Object; if (isExist(name)) { obj = _so.data.cookie[name]; } else { obj = new Object(); } var today:Date = new Date(); obj.time = today.getTime().toString(); obj.name = name; obj.value = value; createCookie(); _so.data.cookie[name] = obj; _so.flush(); } private function createCookie():void { if (_so.data.cookie == null) { _so.data.cookie = new Object(); _so.flush(); } } } }
package net.manaca.utils { import flash.net.SharedObject; import flash.utils.Proxy; import flash.utils.flash_proxy; /** * The Cookie carry a proxy provide a more useful SharedObject. * @author v-seanzo * */ dynamic public class Cookie extends Proxy { //========================================================================== // Constructor //========================================================================== /** * Constructs a new <code>Cookie</code> instance. * @param name the SharedObject name. * @param timeOut the value time out value. * */ public function Cookie(name:String, timeOut:Number = 3600) { super(); this._name = name; this._timeOut = timeOut; so = SharedObject.getLocal(name); } //========================================================================== // Variables //========================================================================== private var so:SharedObject; //========================================================================== // Properties //========================================================================== private var _name:String; /** * The SharedObject name. * @return * */ public function getName():String { return _name; } private var _timeOut:Number; /** * Get time out value. * @return * */ public function getTimeOut():Number { return _timeOut; } /** * Get the SharedObject size. * @return * */ public function getSize():uint { return so.size; } //========================================================================== // Methods //========================================================================== /** * Clear when timeout. */ public function clearTimeOut():void { var obj:* = so.data.cookie; if (obj == null) { return; } for (var key:String in obj) { if (isTimeOut(obj[key].time)) { remove(key); } } so.flush(); } /** * Remove all cookie. * */ public function clear():void { so.clear(); so.flush(); } /** * Check timeout. * @param time * @return * */ public function isTimeOut(time:Number):Boolean { var today:Date = new Date(); return time + _timeOut * 1000 < today.getTime(); } /** * Check Cookie item exist. * @param key * @return * */ public function isExist(key:String):Boolean { return so.data.cookie != null && so.data.cookie[key] != null; } /** * Remove Cookie item by key. * @param key * */ public function remove(key:String):void { if (isExist(key)) { delete so.data.cookie[key]; so.flush(); } } /** * * @param name * @return * */ override flash_proxy function getProperty(name:*):* { return isExist(name) ? so.data.cookie[name].value : null; } /** * * @param name * @param value * */ override flash_proxy function setProperty(name:*, value:*):void { var obj:Object; if (isExist(name)) { obj = so.data.cookie[name]; } else { obj = new Object(); } var today:Date = new Date(); obj.time = today.getTime().toString(); obj.name = name; obj.value = value; createCookie(); so.data.cookie[name] = obj; so.flush(); } private function createCookie():void { if (so.data.cookie == null) { so.data.cookie = new Object(); so.flush(); } } } }
format code Cookie.as
format code Cookie.as
ActionScript
mit
wersling/manaca,wersling/manaca
ef86f39703cf4850a2c78bbfe25b758efe09a556
exporter/src/main/as/flump/export/Exporter.as
exporter/src/main/as/flump/export/Exporter.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.desktop.NativeApplication; import flash.display.NativeMenu; import flash.display.NativeMenuItem; import flash.display.NativeWindow; import flash.display.Stage; import flash.display.StageQuality; import flash.events.Event; import flash.events.MouseEvent; import flash.filesystem.File; import flash.net.SharedObject; import flash.utils.IDataOutput; import flump.executor.Executor; import flump.executor.Future; import flump.export.Ternary; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import mx.collections.ArrayList; import mx.events.CollectionEvent; import mx.events.PropertyChangeEvent; import spark.components.DataGrid; import spark.components.DropDownList; import spark.components.List; import spark.components.Window; import spark.events.GridSelectionEvent; import com.threerings.util.F; import com.threerings.util.Log; import com.threerings.util.StringUtil; import starling.display.Sprite; public class Exporter { public static const NA :NativeApplication = NativeApplication.nativeApplication; public function Exporter (win :ExporterWindow) { Log.setLevel("", Log.INFO); _win = win; _errors = _win.errors; _libraries = _win.libraries; function updatePreviewAndExport (..._) :void { _win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 && _libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); var status :DocStatus = _libraries.selectedItem as DocStatus; _win.preview.enabled = status != null && status.isValid; if (_exportChooser.dir == null) return; _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); } var fileMenuItem :NativeMenuItem; if (NativeApplication.supportsMenu) { // Grab the existing menu on macs. Use an index to get it as it's not going to be // 'File' in all languages fileMenuItem = NA.menu.getItemAt(1); // Add a separator before the existing close command fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 0); } else { _win.nativeWindow.menu = new NativeMenu(); fileMenuItem = _win.nativeWindow.menu.addSubmenu(new NativeMenu(), "File"); } // Add save and save as by index to work with the existing items on Mac // Mac menus have an existing "Close" item, so everything we add should go ahead of that var newMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("New"), 0); newMenuItem.keyEquivalent = "n"; newMenuItem.addEventListener(Event.SELECT, function (..._) :void { _confFile = null; _conf = new FlumpConf(); updatePublisher(); }); var openMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open..."), 1); openMenuItem.keyEquivalent = "o"; openMenuItem.addEventListener(Event.SELECT, function (..._) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { _confFile = file; openConf(); updatePublisher(); }); file.browseForOpen("Open Flump Configuration"); }); fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2); const saveMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save"), 3); saveMenuItem.keyEquivalent = "s"; function saveConf () :void { Files.write(_confFile, function (out :IDataOutput) :void { // Set directories relative to where this file is being saved. Fall back to absolute // paths if relative paths aren't possible. if (_importChooser.dir != null) { _conf.importDir = _confFile.parent.getRelativePath(_importChooser.dir, /*useDotDot=*/true); if (_conf.importDir == null) _conf.importDir = _importChooser.dir.nativePath; } if (_exportChooser.dir != null) { _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); if (_conf.exportDir == null) _conf.exportDir = _exportChooser.dir.nativePath; } out.writeUTFBytes(JSON.stringify(_conf, null, /*space=*/2)); }); }; function saveAs (..._) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { _confFile = file; trace("Conf file is now " + _confFile.nativePath); _settings.data["CONF_FILE"] = _confFile.nativePath; _settings.flush(); saveConf(); }); file.browseForSave("Save Flump Configuration"); }; saveMenuItem.addEventListener(Event.SELECT, function (..._) :void { if (_confFile == null) saveAs(); else saveConf(); }); function openConf () :void { try { _conf = FlumpConf.fromJSON(JSONFormat.readJSON(_confFile)); _win.title = _confFile.name; var dir :String = _confFile.parent.nativePath + File.separator + _conf.importDir; setImport(new File(dir)); } catch (e :Error) { log.warning("Unable to parse conf", e); _errors.dataProvider.addItem(new ParseError(_confFile.nativePath, ParseError.CRIT, "Unable to read configuration")); _confFile = null; } }; const saveAsMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save As..."), 4); saveAsMenuItem.keyEquivalent = "S"; saveAsMenuItem.addEventListener(Event.SELECT, saveAs); if (_settings.data.hasOwnProperty("CONF_FILE")) { _confFile = new File(_settings.data["CONF_FILE"]); openConf(); } var curSelection :DocStatus = null; _libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { log.info("Changed", "selected", _libraries.selectedIndices); updatePreviewAndExport(); if (curSelection != null) { curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } var newSelection :DocStatus = _libraries.selectedItem as DocStatus; if (newSelection != null) { newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } curSelection = newSelection; }); _win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void { setImport(_importChooser.dir); updatePreviewAndExport(); }); _win.export.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var status :DocStatus in _libraries.selectedItems) { exportFlashDocument(status); } }); _win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void { showPreviewWindow(_libraries.selectedItem.lib); }); _importChooser = new DirChooser(null, _win.importRoot, _win.browseImport); _importChooser.changed.add(setImport); setImport(_importChooser.dir); _exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport); _exportChooser.changed.add(updatePreviewAndExport); function updatePublisher (..._) :void { if (_confFile != null) { _importChooser.dir = (_conf.importDir != null) ? _confFile.parent.resolvePath(_conf.importDir) : null; _exportChooser.dir = (_conf.exportDir != null) ? _confFile.parent.resolvePath(_conf.exportDir) : null; } else { _importChooser.dir = null; _exportChooser.dir = null; } if (_exportChooser.dir == null || _conf.exports.length == 0) _publisher = null; else _publisher = new Publisher(_exportChooser.dir, Vector.<ExportConf>(_conf.exports)); var formatNames :Array = []; for each (var export :ExportConf in _conf.exports) formatNames.push(export.name); _win.formatOverview.text = formatNames.join(", "); }; _exportChooser.changed.add(updatePublisher); var editFormats :EditFormatsWindow; _win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void { if (editFormats == null || editFormats.closed) { editFormats = new EditFormatsWindow(); editFormats.open(); } else editFormats.orderToFront(); var dataProvider :ArrayList = new ArrayList(_conf.exports); dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, updatePublisher); editFormats.exports.dataProvider = dataProvider; editFormats.buttonAdd.addEventListener(MouseEvent.CLICK, function (..._) :void { var export :ExportConf = new ExportConf(); export.name = "format" + (_conf.exports.length+1); if (_conf.exports.length > 0) { export.format = _conf.exports[0].format; } dataProvider.addItem(export); }); editFormats.exports.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { editFormats.buttonRemove.enabled = (editFormats.exports.selectedItem != null); }); editFormats.buttonRemove.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var export :ExportConf in editFormats.exports.selectedItems) { dataProvider.removeItem(export); } }); }); updatePublisher(); _win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); }); } protected function setImport (root :File) :void { _libraries.dataProvider.removeAll(); _errors.dataProvider.removeAll(); if (root == null) return; _rootLen = root.nativePath.length + 1; if (_docFinder != null) _docFinder.shutdownNow(); _docFinder = new Executor(); findFlashDocuments(root, _docFinder, true); _win.reload.enabled = true; } protected function showPreviewWindow (lib :XflLibrary) :void { if (_previewController == null || _previewWindow.closed || _previewControls.closed) { _previewWindow = new PreviewWindow(); _previewControls = new PreviewControlsWindow(); _previewWindow.started = function (container :Sprite) :void { _previewController = new PreviewController(lib, container, _previewWindow, _previewControls); } _previewWindow.open(); _previewControls.open(); preventWindowClose(_previewWindow.nativeWindow); preventWindowClose(_previewControls.nativeWindow); } else { _previewController.lib = lib; _previewWindow.nativeWindow.visible = true; _previewControls.nativeWindow.visible = true; } _previewWindow.orderToFront(); _previewControls.orderToFront(); } // Causes a window to be hidden, rather than closed, when its close box is clicked protected static function preventWindowClose (window :NativeWindow) :void { window.addEventListener(Event.CLOSING, function (e :Event) :void { e.preventDefault(); window.visible = false; }); } protected var _previewController :PreviewController; protected var _previewWindow :PreviewWindow; protected var _previewControls :PreviewControlsWindow; protected function findFlashDocuments (base :File, exec :Executor, ignoreXflAtBase :Boolean = false) :void { Files.list(base, exec).succeeded.add(function (files :Array) :void { if (exec.isShutdown) return; for each (var file :File in files) { if (Files.hasExtension(file, "xfl")) { if (ignoreXflAtBase) { _errors.dataProvider.addItem(new ParseError(base.nativePath, ParseError.CRIT, "The import directory can't be an XFL directory, did you mean " + base.parent.nativePath + "?")); } else addFlashDocument(file); return; } } for each (file in files) { if (StringUtil.startsWith(file.name, ".", "RECOVER_")) { continue; // Ignore hidden VCS directories, and recovered backups created by Flash } if (file.isDirectory) findFlashDocuments(file, exec); else addFlashDocument(file); } }); } protected function exportFlashDocument (status :DocStatus) :void { const stage :Stage = NA.activeWindow.stage; const prevQuality :String = stage.quality; stage.quality = StageQuality.BEST; _publisher.publish(status.lib); stage.quality = prevQuality; status.updateModified(Ternary.FALSE); } protected function addFlashDocument (file :File) :void { var name :String = file.nativePath.substring(_rootLen).replace( new RegExp("\\" + File.separator, "g"), "/"); var load :Future; switch (Files.getExtension(file)) { case "xfl": name = name.substr(0, name.lastIndexOf("/")); load = new XflLoader().load(name, file.parent); break; case "fla": name = name.substr(0, name.lastIndexOf(".")); load = new FlaLoader().load(name, file); break; default: // Unsupported file type, ignore return; } const status :DocStatus = new DocStatus(name, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null); _libraries.dataProvider.addItem(status); load.succeeded.add(function (lib :XflLibrary) :void { status.lib = lib; status.updateModified(Ternary.of(_publisher == null || _publisher.modified(lib))); for each (var err :ParseError in lib.getErrors()) _errors.dataProvider.addItem(err); status.updateValid(Ternary.of(lib.valid)); }); load.failed.add(function (error :Error) :void { trace("Failed to load " + file.nativePath + ": " + error); status.updateValid(Ternary.FALSE); throw error; }); } protected var _rootLen :int; protected var _publisher :Publisher; protected var _docFinder :Executor; protected var _win :ExporterWindow; protected var _libraries :DataGrid; protected var _errors :DataGrid; protected var _exportChooser :DirChooser; protected var _importChooser :DirChooser; protected var _authoredResolution :DropDownList; protected var _conf :FlumpConf = new FlumpConf(); protected var _confFile :File; protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter"); private static const log :Log = Log.getLog(Exporter); } } import flash.events.EventDispatcher; import flump.export.Ternary; import flump.xfl.XflLibrary; import mx.core.IPropertyChangeNotifier; import mx.events.PropertyChangeEvent; class DocStatus extends EventDispatcher implements IPropertyChangeNotifier { public var path :String; public var modified :String; public var valid :String = QUESTION; public var lib :XflLibrary; public function DocStatus (path :String, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) { this.lib = lib; this.path = path; _uid = path; updateModified(modified); updateValid(valid); } public function updateValid (newValid :Ternary) :void { changeField("valid", function (..._) :void { if (newValid == Ternary.TRUE) valid = CHECK; else if (newValid == Ternary.FALSE) valid = FROWN; else valid = QUESTION; }); } public function get isValid () :Boolean { return valid == CHECK; } public function updateModified (newModified :Ternary) :void { changeField("modified", function (..._) :void { if (newModified == Ternary.TRUE) modified = CHECK; else if (newModified == Ternary.FALSE) modified = " "; else modified = QUESTION; }); } protected function changeField(fieldName :String, modifier :Function) :void { const oldValue :Object = this[fieldName]; modifier(); const newValue :Object = this[fieldName]; dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue)); } public function get uid () :String { return _uid; } public function set uid (uid :String) :void { _uid = uid; } protected var _uid :String; protected static const QUESTION :String = "?"; protected static const FROWN :String = "☹"; protected static const CHECK :String = "✓"; }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.desktop.NativeApplication; import flash.display.NativeMenu; import flash.display.NativeMenuItem; import flash.display.NativeWindow; import flash.display.Stage; import flash.display.StageQuality; import flash.events.Event; import flash.events.MouseEvent; import flash.filesystem.File; import flash.net.SharedObject; import flash.utils.IDataOutput; import flump.executor.Executor; import flump.executor.Future; import flump.export.Ternary; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import mx.collections.ArrayList; import mx.events.CollectionEvent; import mx.events.PropertyChangeEvent; import spark.components.DataGrid; import spark.components.DropDownList; import spark.components.List; import spark.components.Window; import spark.events.GridSelectionEvent; import com.threerings.util.F; import com.threerings.util.Log; import com.threerings.util.StringUtil; import starling.display.Sprite; public class Exporter { public static const NA :NativeApplication = NativeApplication.nativeApplication; public function Exporter (win :ExporterWindow) { Log.setLevel("", Log.INFO); _win = win; _errors = _win.errors; _libraries = _win.libraries; function updatePreviewAndExport (..._) :void { _win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 && _libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); var status :DocStatus = _libraries.selectedItem as DocStatus; _win.preview.enabled = status != null && status.isValid; if (_exportChooser.dir == null) return; _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); } var fileMenuItem :NativeMenuItem; if (NativeApplication.supportsMenu) { // Grab the existing menu on macs. Use an index to get it as it's not going to be // 'File' in all languages fileMenuItem = NA.menu.getItemAt(1); // Add a separator before the existing close command fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 0); } else { _win.nativeWindow.menu = new NativeMenu(); fileMenuItem = _win.nativeWindow.menu.addSubmenu(new NativeMenu(), "File"); } // Add save and save as by index to work with the existing items on Mac // Mac menus have an existing "Close" item, so everything we add should go ahead of that var newMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("New"), 0); newMenuItem.keyEquivalent = "n"; newMenuItem.addEventListener(Event.SELECT, function (..._) :void { _confFile = null; _conf = new FlumpConf(); updatePublisher(); }); var openMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open..."), 1); openMenuItem.keyEquivalent = "o"; openMenuItem.addEventListener(Event.SELECT, function (..._) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { _confFile = file; openConf(); updatePublisher(); }); file.browseForOpen("Open Flump Configuration"); }); fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2); const saveMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save"), 3); saveMenuItem.keyEquivalent = "s"; function saveConf () :void { Files.write(_confFile, function (out :IDataOutput) :void { // Set directories relative to where this file is being saved. Fall back to absolute // paths if relative paths aren't possible. if (_importChooser.dir != null) { _conf.importDir = _confFile.parent.getRelativePath(_importChooser.dir, /*useDotDot=*/true); if (_conf.importDir == null) _conf.importDir = _importChooser.dir.nativePath; } if (_exportChooser.dir != null) { _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); if (_conf.exportDir == null) _conf.exportDir = _exportChooser.dir.nativePath; } out.writeUTFBytes(JSON.stringify(_conf, null, /*space=*/2)); }); }; function saveAs (..._) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { _confFile = file; trace("Conf file is now " + _confFile.nativePath); _settings.data["CONF_FILE"] = _confFile.nativePath; _settings.flush(); saveConf(); }); file.browseForSave("Save Flump Configuration"); }; saveMenuItem.addEventListener(Event.SELECT, function (..._) :void { if (_confFile == null) saveAs(); else saveConf(); }); function openConf () :void { try { _conf = FlumpConf.fromJSON(JSONFormat.readJSON(_confFile)); _win.title = _confFile.name; var dir :String = _confFile.parent.resolvePath(_conf.importDir).nativePath; setImport(new File(dir)); } catch (e :Error) { log.warning("Unable to parse conf", e); _errors.dataProvider.addItem(new ParseError(_confFile.nativePath, ParseError.CRIT, "Unable to read configuration")); _confFile = null; } }; const saveAsMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save As..."), 4); saveAsMenuItem.keyEquivalent = "S"; saveAsMenuItem.addEventListener(Event.SELECT, saveAs); if (_settings.data.hasOwnProperty("CONF_FILE")) { _confFile = new File(_settings.data["CONF_FILE"]); openConf(); } var curSelection :DocStatus = null; _libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { log.info("Changed", "selected", _libraries.selectedIndices); updatePreviewAndExport(); if (curSelection != null) { curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } var newSelection :DocStatus = _libraries.selectedItem as DocStatus; if (newSelection != null) { newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } curSelection = newSelection; }); _win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void { setImport(_importChooser.dir); updatePreviewAndExport(); }); _win.export.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var status :DocStatus in _libraries.selectedItems) { exportFlashDocument(status); } }); _win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void { showPreviewWindow(_libraries.selectedItem.lib); }); _importChooser = new DirChooser(null, _win.importRoot, _win.browseImport); _importChooser.changed.add(setImport); setImport(_importChooser.dir); _exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport); _exportChooser.changed.add(updatePreviewAndExport); function updatePublisher (..._) :void { if (_confFile != null) { _importChooser.dir = (_conf.importDir != null) ? _confFile.parent.resolvePath(_conf.importDir) : null; _exportChooser.dir = (_conf.exportDir != null) ? _confFile.parent.resolvePath(_conf.exportDir) : null; } else { _importChooser.dir = null; _exportChooser.dir = null; } if (_exportChooser.dir == null || _conf.exports.length == 0) _publisher = null; else _publisher = new Publisher(_exportChooser.dir, Vector.<ExportConf>(_conf.exports)); var formatNames :Array = []; for each (var export :ExportConf in _conf.exports) formatNames.push(export.name); _win.formatOverview.text = formatNames.join(", "); }; _exportChooser.changed.add(updatePublisher); var editFormats :EditFormatsWindow; _win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void { if (editFormats == null || editFormats.closed) { editFormats = new EditFormatsWindow(); editFormats.open(); } else editFormats.orderToFront(); var dataProvider :ArrayList = new ArrayList(_conf.exports); dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, updatePublisher); editFormats.exports.dataProvider = dataProvider; editFormats.buttonAdd.addEventListener(MouseEvent.CLICK, function (..._) :void { var export :ExportConf = new ExportConf(); export.name = "format" + (_conf.exports.length+1); if (_conf.exports.length > 0) { export.format = _conf.exports[0].format; } dataProvider.addItem(export); }); editFormats.exports.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { editFormats.buttonRemove.enabled = (editFormats.exports.selectedItem != null); }); editFormats.buttonRemove.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var export :ExportConf in editFormats.exports.selectedItems) { dataProvider.removeItem(export); } }); }); updatePublisher(); _win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); }); } protected function setImport (root :File) :void { _libraries.dataProvider.removeAll(); _errors.dataProvider.removeAll(); if (root == null) return; _rootLen = root.nativePath.length + 1; if (_docFinder != null) _docFinder.shutdownNow(); _docFinder = new Executor(); findFlashDocuments(root, _docFinder, true); _win.reload.enabled = true; } protected function showPreviewWindow (lib :XflLibrary) :void { if (_previewController == null || _previewWindow.closed || _previewControls.closed) { _previewWindow = new PreviewWindow(); _previewControls = new PreviewControlsWindow(); _previewWindow.started = function (container :Sprite) :void { _previewController = new PreviewController(lib, container, _previewWindow, _previewControls); } _previewWindow.open(); _previewControls.open(); preventWindowClose(_previewWindow.nativeWindow); preventWindowClose(_previewControls.nativeWindow); } else { _previewController.lib = lib; _previewWindow.nativeWindow.visible = true; _previewControls.nativeWindow.visible = true; } _previewWindow.orderToFront(); _previewControls.orderToFront(); } // Causes a window to be hidden, rather than closed, when its close box is clicked protected static function preventWindowClose (window :NativeWindow) :void { window.addEventListener(Event.CLOSING, function (e :Event) :void { e.preventDefault(); window.visible = false; }); } protected var _previewController :PreviewController; protected var _previewWindow :PreviewWindow; protected var _previewControls :PreviewControlsWindow; protected function findFlashDocuments (base :File, exec :Executor, ignoreXflAtBase :Boolean = false) :void { Files.list(base, exec).succeeded.add(function (files :Array) :void { if (exec.isShutdown) return; for each (var file :File in files) { if (Files.hasExtension(file, "xfl")) { if (ignoreXflAtBase) { _errors.dataProvider.addItem(new ParseError(base.nativePath, ParseError.CRIT, "The import directory can't be an XFL directory, did you mean " + base.parent.nativePath + "?")); } else addFlashDocument(file); return; } } for each (file in files) { if (StringUtil.startsWith(file.name, ".", "RECOVER_")) { continue; // Ignore hidden VCS directories, and recovered backups created by Flash } if (file.isDirectory) findFlashDocuments(file, exec); else addFlashDocument(file); } }); } protected function exportFlashDocument (status :DocStatus) :void { const stage :Stage = NA.activeWindow.stage; const prevQuality :String = stage.quality; stage.quality = StageQuality.BEST; _publisher.publish(status.lib); stage.quality = prevQuality; status.updateModified(Ternary.FALSE); } protected function addFlashDocument (file :File) :void { var name :String = file.nativePath.substring(_rootLen).replace( new RegExp("\\" + File.separator, "g"), "/"); var load :Future; switch (Files.getExtension(file)) { case "xfl": name = name.substr(0, name.lastIndexOf("/")); load = new XflLoader().load(name, file.parent); break; case "fla": name = name.substr(0, name.lastIndexOf(".")); load = new FlaLoader().load(name, file); break; default: // Unsupported file type, ignore return; } const status :DocStatus = new DocStatus(name, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null); _libraries.dataProvider.addItem(status); load.succeeded.add(function (lib :XflLibrary) :void { status.lib = lib; status.updateModified(Ternary.of(_publisher == null || _publisher.modified(lib))); for each (var err :ParseError in lib.getErrors()) _errors.dataProvider.addItem(err); status.updateValid(Ternary.of(lib.valid)); }); load.failed.add(function (error :Error) :void { trace("Failed to load " + file.nativePath + ": " + error); status.updateValid(Ternary.FALSE); throw error; }); } protected var _rootLen :int; protected var _publisher :Publisher; protected var _docFinder :Executor; protected var _win :ExporterWindow; protected var _libraries :DataGrid; protected var _errors :DataGrid; protected var _exportChooser :DirChooser; protected var _importChooser :DirChooser; protected var _authoredResolution :DropDownList; protected var _conf :FlumpConf = new FlumpConf(); protected var _confFile :File; protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter"); private static const log :Log = Log.getLog(Exporter); } } import flash.events.EventDispatcher; import flump.export.Ternary; import flump.xfl.XflLibrary; import mx.core.IPropertyChangeNotifier; import mx.events.PropertyChangeEvent; class DocStatus extends EventDispatcher implements IPropertyChangeNotifier { public var path :String; public var modified :String; public var valid :String = QUESTION; public var lib :XflLibrary; public function DocStatus (path :String, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) { this.lib = lib; this.path = path; _uid = path; updateModified(modified); updateValid(valid); } public function updateValid (newValid :Ternary) :void { changeField("valid", function (..._) :void { if (newValid == Ternary.TRUE) valid = CHECK; else if (newValid == Ternary.FALSE) valid = FROWN; else valid = QUESTION; }); } public function get isValid () :Boolean { return valid == CHECK; } public function updateModified (newModified :Ternary) :void { changeField("modified", function (..._) :void { if (newModified == Ternary.TRUE) modified = CHECK; else if (newModified == Ternary.FALSE) modified = " "; else modified = QUESTION; }); } protected function changeField(fieldName :String, modifier :Function) :void { const oldValue :Object = this[fieldName]; modifier(); const newValue :Object = this[fieldName]; dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue)); } public function get uid () :String { return _uid; } public function set uid (uid :String) :void { _uid = uid; } protected var _uid :String; protected static const QUESTION :String = "?"; protected static const FROWN :String = "☹"; protected static const CHECK :String = "✓"; }
Fix for when importDir is an absolute path.
Fix for when importDir is an absolute path. We still need to handle absolute paths, since on Windows you can't have a relative path between different drive letters. Plus, absolute paths may be useful in some cases anyways.
ActionScript
mit
tconkling/flump,mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,funkypandagame/flump
bc0702e3361a353ad75260a04481c686cf4640f9
KalturaHLSPlugin/src/com/kaltura/kdpfl/plugin/KalturaHLSMediator.as
KalturaHLSPlugin/src/com/kaltura/kdpfl/plugin/KalturaHLSMediator.as
package com.kaltura.kdpfl.plugin { import com.kaltura.hls.SubtitleTrait; import com.kaltura.kdpfl.model.MediaProxy; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.view.controls.KTrace; import org.osmf.events.MediaElementEvent; import org.osmf.traits.DVRTrait; import org.osmf.traits.MediaTraitType; import org.puremvc.as3.interfaces.INotification; import org.puremvc.as3.patterns.mediator.Mediator; public class KalturaHLSMediator extends Mediator { public static const NAME:String = "KalturaHLSMediator"; public static const HLS_END_LIST:String = "hlsEndList"; public static const HLS_TRACK_SWITCH:String = "doTextTrackSwitch"; private var _mediaProxy:MediaProxy; private var _subtitleTrait:SubtitleTrait; public function KalturaHLSMediator( viewComponent:Object=null) { super(NAME, viewComponent); } override public function onRegister():void { _mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy; super.onRegister(); } override public function listNotificationInterests():Array { return [ NotificationType.DURATION_CHANGE, NotificationType.MEDIA_ELEMENT_READY, HLS_TRACK_SWITCH ]; } override public function handleNotification(notification:INotification):void { if ( notification.getName() == NotificationType.DURATION_CHANGE ) { if ( _mediaProxy.vo.isLive && _mediaProxy.vo.media.hasTrait(MediaTraitType.DVR) ) { var dvrTrait:DVRTrait = _mediaProxy.vo.media.getTrait(MediaTraitType.DVR) as DVRTrait; //recording stopped - endlist if ( !dvrTrait.isRecording ) { sendNotification( HLS_END_LIST ); } } } if ( notification.getName() == NotificationType.MEDIA_ELEMENT_READY ) { _mediaProxy.vo.media.addEventListener(MediaElementEvent.TRAIT_ADD, getSubtitleTrait); // catch and save SubtitleTrait the moment video object is ready } if ( notification.getName() == HLS_TRACK_SWITCH ) { //trigered by JS changeEmbeddedTextTrack helper in order to change language if ( _subtitleTrait && notification.getBody() && notification.getBody().hasOwnProperty("textIndex")) _subtitleTrait.language = _subtitleTrait.languages[ notification.getBody().textIndex ]; // change the language index inside subtitleTrait reference of video object else KTrace.getInstance().log("KalturaHLSMediator :: doTextTrackSwitch >> subtitleTrait or textIndex error."); } } protected function getSubtitleTrait(event:MediaElementEvent):void { if(event.traitType == SubtitleTrait.TYPE){ _mediaProxy.vo.media.removeEventListener(MediaElementEvent.TRAIT_ADD, getSubtitleTrait); _subtitleTrait = _mediaProxy.vo.media.getTrait( SubtitleTrait.TYPE ) as SubtitleTrait; // save SubtitleTrait in order to read languages if ( _subtitleTrait && _subtitleTrait.languages.length > 0 ) { var langArray:Array = new Array(); var i:int = 0; while (i < _subtitleTrait.languages.length){ langArray.push({"label":_subtitleTrait.languages[0], "index": i++}); // build languages array in a format that JS expects to receive } sendNotification("textTracksReceived", {languages:langArray}); //will triger ClosedCaptions textTracksReceived function, through kplayer onTextTracksReceived listener } } } } }
package com.kaltura.kdpfl.plugin { import com.kaltura.hls.SubtitleTrait; import com.kaltura.kdpfl.model.MediaProxy; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.view.controls.KTrace; import org.osmf.events.MediaElementEvent; import org.osmf.traits.DVRTrait; import org.osmf.traits.MediaTraitType; import org.puremvc.as3.interfaces.INotification; import org.puremvc.as3.patterns.mediator.Mediator; public class KalturaHLSMediator extends Mediator { public static const NAME:String = "KalturaHLSMediator"; public static const HLS_END_LIST:String = "hlsEndList"; public static const HLS_TRACK_SWITCH:String = "doTextTrackSwitch"; private var _mediaProxy:MediaProxy; private var _subtitleTrait:SubtitleTrait; public function KalturaHLSMediator( viewComponent:Object=null) { super(NAME, viewComponent); } override public function onRegister():void { _mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy; super.onRegister(); } override public function listNotificationInterests():Array { return [ NotificationType.DURATION_CHANGE, NotificationType.MEDIA_ELEMENT_READY, HLS_TRACK_SWITCH ]; } override public function handleNotification(notification:INotification):void { if ( notification.getName() == NotificationType.DURATION_CHANGE ) { if ( _mediaProxy.vo.isLive && _mediaProxy.vo.media.hasTrait(MediaTraitType.DVR) ) { var dvrTrait:DVRTrait = _mediaProxy.vo.media.getTrait(MediaTraitType.DVR) as DVRTrait; //recording stopped - endlist if ( !dvrTrait.isRecording ) { sendNotification( HLS_END_LIST ); } } } if ( notification.getName() == NotificationType.MEDIA_ELEMENT_READY ) { _mediaProxy.vo.media.addEventListener(MediaElementEvent.TRAIT_ADD, getSubtitleTrait); // catch and save SubtitleTrait the moment video object is ready } if ( notification.getName() == HLS_TRACK_SWITCH ) { //trigered by JS changeEmbeddedTextTrack helper in order to change language if ( _subtitleTrait && notification.getBody() && notification.getBody().hasOwnProperty("textIndex")) _subtitleTrait.language = _subtitleTrait.languages[ notification.getBody().textIndex ]; // change the language index inside subtitleTrait reference of video object else KTrace.getInstance().log("KalturaHLSMediator :: doTextTrackSwitch >> subtitleTrait or textIndex error."); } } protected function getSubtitleTrait(event:MediaElementEvent):void { if(event.traitType == SubtitleTrait.TYPE){ _mediaProxy.vo.media.removeEventListener(MediaElementEvent.TRAIT_ADD, getSubtitleTrait); _subtitleTrait = _mediaProxy.vo.media.getTrait( SubtitleTrait.TYPE ) as SubtitleTrait; // save SubtitleTrait in order to read languages if ( _subtitleTrait && _subtitleTrait.languages.length > 0 ) { var langArray:Array = new Array(); var i:int = 0; while (i < _subtitleTrait.languages.length){ langArray.push({"label":_subtitleTrait.languages[i], "index": i++}); // build languages array in a format that JS expects to receive } sendNotification("textTracksReceived", {languages:langArray}); //will triger ClosedCaptions textTracksReceived function, through kplayer onTextTracksReceived listener } } } } }
fix for languages labels
fix for languages labels VebVTT captions multi language stream - CC plugin menu was pulled with all the languages traits as eng. FIXED
ActionScript
agpl-3.0
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
042ba312293f0d80f72044425b89b6f891e52485
src/aerys/minko/render/renderer/DefaultRenderer.as
src/aerys/minko/render/renderer/DefaultRenderer.as
package aerys.minko.render.renderer { import aerys.minko.ns.minko; import aerys.minko.ns.minko_render; import aerys.minko.render.Viewport; import aerys.minko.render.renderer.state.RendererState; import aerys.minko.type.Factory; import aerys.minko.type.stream.IndexStream; import flash.display.BitmapData; import flash.display3D.Context3D; import flash.display3D.IndexBuffer3D; import flash.utils.getTimer; public class DefaultRenderer implements IRenderer { use namespace minko; use namespace minko_render; private static const RENDER_STATE : Factory = Factory.getFactory(RendererState); private static const SORT : Boolean = true; private static const DEBUG : Boolean = false; private var _context : Context3D = null; private var _currentState : RendererState = null; private var _numTriangles : uint = 0; private var _viewport : Viewport = null; private var _drawingTime : int = 0; private var _frame : uint = 0; private var _states : Vector.<RendererState> = new Vector.<RendererState>(); private var _numStates : int = 0; public function get state() : RendererState { return _currentState; } public function get numTriangles() : uint { return _numTriangles; } public function get viewport() : Viewport { return _viewport; } public function get drawingTime() : int { return _drawingTime; } public function get frameId() : uint { return _frame; } public function DefaultRenderer(viewport : Viewport, context : Context3D) { _viewport = viewport; _context = context; _context.enableErrorChecking = DEBUG; } public function begin() : void { _currentState = RENDER_STATE.create(true) as RendererState; _currentState.clear(); } public function end() : void { _states[int(_numStates++)] = _currentState; _currentState = null; } public function drawTriangles(offset : uint = 0, numTriangles : int = -1) : void { _currentState.offsets.push(offset); _currentState.numTriangles.push(numTriangles); } public function clear(red : Number = 0., green : Number = 0., blue : Number = 0., alpha : Number = 1., depth : Number = 1., stencil : uint = 0, mask : uint = 0xffffffff) :void { // _context.setScissorRectangle(null); // _context.clear(red, green, blue, alpha, depth, stencil, mask); _numTriangles = 0; _drawingTime = 0; _currentState = null; _numStates = 0; } public function drawToBackBuffer() : void { var time : int = getTimer(); if (SORT && _numStates > 1) RendererState.sort(_states, _numStates); var actualState : RendererState = null; for (var i : int = 0; i < _numStates; ++i) { var state : RendererState = _states[i]; var offsets : Vector.<uint> = state.offsets; var numTriangles : Vector.<int> = state.numTriangles; var numCalls : int = offsets.length; state.prepareContext(_context, actualState); for (var j : int = 0; j < numCalls; ++j) { var iStream : IndexStream = state._indexStream; var iBuffer : IndexBuffer3D = iStream.getIndexBuffer3D(_context); var count : int = numTriangles[j]; _numTriangles += count == -1 ? state._indexStream.length / 3. : count; _context.drawTriangles(iBuffer, offsets[j], count); } actualState = state; } _drawingTime += getTimer() - time; } public function present() : void { var time : int = getTimer(); if (_numStates != 0) _context.present(); _drawingTime += getTimer() - time; ++_frame; } public function dumpBackbuffer(bitmapData : BitmapData) : void { var time : int = getTimer(); _context.drawToBitmapData(bitmapData); _drawingTime += getTimer() - time; ++_frame; } } }
package aerys.minko.render.renderer { import aerys.minko.ns.minko; import aerys.minko.ns.minko_render; import aerys.minko.render.Viewport; import aerys.minko.render.renderer.state.RendererState; import aerys.minko.type.Factory; import aerys.minko.type.stream.IndexStream; import flash.display.BitmapData; import flash.display3D.Context3D; import flash.display3D.IndexBuffer3D; import flash.utils.getTimer; public class DefaultRenderer implements IRenderer { use namespace minko; use namespace minko_render; private static const RENDER_STATE : Factory = Factory.getFactory(RendererState); private static const SORT : Boolean = true; private static const DEBUG : Boolean = false; private var _context : Context3D = null; private var _currentState : RendererState = null; private var _numTriangles : uint = 0; private var _viewport : Viewport = null; private var _drawingTime : int = 0; private var _frame : uint = 0; private var _states : Vector.<RendererState> = new Vector.<RendererState>(); private var _numStates : int = 0; public function get state() : RendererState { return _currentState; } public function get numTriangles() : uint { return _numTriangles; } public function get viewport() : Viewport { return _viewport; } public function get drawingTime() : int { return _drawingTime; } public function get frameId() : uint { return _frame; } public function DefaultRenderer(viewport : Viewport, context : Context3D) { _viewport = viewport; _context = context; _context.enableErrorChecking = DEBUG; } public function begin() : void { _currentState = RENDER_STATE.create(true) as RendererState; _currentState.clear(); } public function end() : void { _states[int(_numStates++)] = _currentState; _currentState = null; } public function drawTriangles(offset : uint = 0, numTriangles : int = -1) : void { _currentState.offsets.push(offset); _currentState.numTriangles.push(numTriangles); } public function clear(red : Number = 0., green : Number = 0., blue : Number = 0., alpha : Number = 1., depth : Number = 1., stencil : uint = 0, mask : uint = 0xffffffff) :void { // _context.setScissorRectangle(null); // _context.clear(red, green, blue, alpha, depth, stencil, mask); _numTriangles = 0; _drawingTime = 0; _currentState = null; _numStates = 0; } public function drawToBackBuffer() : void { var time : int = getTimer(); if (SORT && _numStates > 1) RendererState.sort(_states, _numStates); var actualState : RendererState = null; for (var i : int = 0; i < _numStates; ++i) { var state : RendererState = _states[i]; var offsets : Vector.<uint> = state.offsets; var numTriangles : Vector.<int> = state.numTriangles; var numCalls : int = offsets.length; state.prepareContext(_context, actualState); for (var j : int = 0; j < numCalls; ++j) { var iStream : IndexStream = state._indexStream; var iBuffer : IndexBuffer3D = iStream.getIndexBuffer3D(_context); var count : int = numTriangles[j]; _numTriangles += count == -1 ? state._indexStream.length / 3. : count; _context.drawTriangles(iBuffer, offsets[j], count); } actualState = state; } _drawingTime += getTimer() - time; } public function present() : void { var time : int = getTimer(); if (_numStates != 0) _context.present(); _drawingTime += getTimer() - time; ++_frame; } public function dumpBackbuffer(bitmapData : BitmapData) : void { var time : int = getTimer(); if (_numStates != 0) _context.drawToBitmapData(bitmapData); _drawingTime += getTimer() - time; ++_frame; } } }
Fix rendering when scene is empty (backbuffer cannot be dumped when nothing was drawn on it) [Romain's fix].
Fix rendering when scene is empty (backbuffer cannot be dumped when nothing was drawn on it) [Romain's fix].
ActionScript
mit
aerys/minko-as3
0706fd4e131ab28c9bee5097168ebe8fd59b5a31
WEB-INF/lps/lfc/kernel/swf9/LzXMLTranslator.as
WEB-INF/lps/lfc/kernel/swf9/LzXMLTranslator.as
/** * LzXMLTranslator.lzs * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ /** * @shortdesc: Utility for converting native XML DOM object into LzDataNode tree */ public class LzXMLTranslator { static function copyXML (xmlobj, trimwhitespace, nsprefix) { var lfcnode = copyFlashXML(xmlobj, trimwhitespace, nsprefix); if (lfcnode == null) { trace('LzXMLTranslator.copyXML: lfcnode.children is null', lfcnode); } var fc = lfcnode; if ( fc is LzDataText ) { return null; } return fc; } static var whitespaceChars = {' ': true, '\r': true, '\n': true, '\t': true}; /** * trim whitespace from start and end of string * @access private */ static function trim( str ) { var whitech = whitespaceChars; var len = str.length; var sindex = 0; var eindex = str.length -1; var ch; while (sindex < len) { ch = str.charAt(sindex); if (whitech[ch] != true) break; sindex++; } while (eindex > sindex) { ch = str.charAt(eindex); if (whitech[ch] != true) break; eindex--; } return str.slice(sindex,eindex+1); } // Recursively copy a Flash XML(Node) tree into a LzDataElement // tree. Used by LzDataNode.stringToLzData /** * @param boolean trimwhitespace: trim whitespace from start and end of text nodes * @param boolean nsprefix: preserve namespace prefixes on node names and attribute names * @access private */ static function copyFlashXML (node, trimwhitespace, nsprefix) { var lfcnode = null; // text node? if (node.nodeKind() == 'text') { var nv = node.toString(); if (trimwhitespace == true) { nv = trim(nv); } lfcnode = new LzDataText(nv); //PBR Changed to match swf kernel // } else if (node.nodeKind() == 'element') { } else { var nattrs = node.attributes(); var cattrs = {}; for (var i:int = 0; i < nattrs.length(); i++) { var key = nsprefix ? nattrs[i].name() : nattrs[i].localName(); cattrs[key] = nattrs[i]; } var nname = node.localName(); if (nname && !nsprefix) { // strip namespace prefix var npos = nname.indexOf(':'); if (npos >= 0) { nname = nname.substring(npos+1); } } lfcnode = new LzDataElement(nname, cattrs); var children = node.children(); var newchildren = []; for (var i = 0; i < children.length(); i++ ) { var child = children[i]; var lfcchild = copyFlashXML(child, trimwhitespace, nsprefix); newchildren[i] = lfcchild; } lfcnode.setChildNodes(newchildren); } return lfcnode; } } // End of LzXMLTranslator
/** * LzXMLTranslator.lzs * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ /** * @shortdesc: Utility for converting native XML DOM object into LzDataNode tree */ public class LzXMLTranslator { static function copyXML (xmlobj:XML, trimwhitespace:Boolean, nsprefix:Boolean) :LzDataElementMixin { var lfcnode:LzDataNodeMixin = copyFlashXML(xmlobj, trimwhitespace, nsprefix); if (lfcnode == null) { trace('LzXMLTranslator.copyXML: lfcnode.children is null', lfcnode); } if ( lfcnode is LzDataText ) { return null; } return (lfcnode cast LzDataElementMixin); } static var whitespaceChars = {' ': true, '\r': true, '\n': true, '\t': true}; /** * trim whitespace from start and end of string * @access private */ static function trim( str:String ) :String { var whitech:Object = whitespaceChars; var len:int = str.length; var sindex:int = 0; var eindex:int = str.length -1; var ch:String; while (sindex < len) { ch = str.charAt(sindex); if (whitech[ch] != true) break; sindex++; } while (eindex > sindex) { ch = str.charAt(eindex); if (whitech[ch] != true) break; eindex--; } return str.slice(sindex,eindex+1); } // Recursively copy a Flash XML(Node) tree into a LzDataElement // tree. Used by LzDataNode.stringToLzData /** * @param boolean trimwhitespace: trim whitespace from start and end of text nodes * @param boolean nsprefix: preserve namespace prefixes on node names and attribute names * @access private */ static function copyFlashXML (node:XML, trimwhitespace:Boolean, nsprefix:Boolean) :LzDataNodeMixin { var lfcnode:LzDataNodeMixin = null; // text node? if (node.nodeKind() == 'text') { var nv:String = node.toString(); if (trimwhitespace == true) { nv = trim(nv); } lfcnode = new LzDataText(nv); //PBR Changed to match swf kernel // } else if (node.nodeKind() == 'element') { } else { var nattrs:XMLList = node.attributes(); var cattrs:Object = {}; for (var i:int = 0; i < nattrs.length(); i++) { var attr:XML = nattrs[i]; var qattr:QName = attr.name(); if (nsprefix) { var ns:Namespace = attr.namespace(); var key:String; if (ns != null && ns.prefix != "") { key = ns.prefix + ":" + qattr.localName; } else { key = qattr.localName; } cattrs[key] = attr.toString(); } else { cattrs[qattr.localName] = attr.toString(); } } var nname:String; var qname:QName = node.name(); if (nsprefix) { var ns:Namespace = node.namespace(); if (ns != null && ns.prefix != "") { nname = ns.prefix + ":" + qname.localName; } else { nname = qname.localName; } } else { nname = qname.localName; } lfcnode = new LzDataElement(nname, cattrs); var children:XMLList = node.children(); var newchildren:Array = []; for (var i:int = 0; i < children.length(); i++ ) { var child:XML = children[i]; var lfcchild:LzDataNodeMixin = copyFlashXML(child, trimwhitespace, nsprefix); newchildren[i] = lfcchild; } (lfcnode cast LzDataElement).setChildNodes(newchildren); } return lfcnode; } } // End of LzXMLTranslator
Change 20080601-bargull-Vzq by bargull@dell--p4--2-53 on 2008-06-01 00:56:07 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20080601-bargull-Vzq by bargull@dell--p4--2-53 on 2008-06-01 00:56:07 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk Summary: Add nsprefix support to swf9 New Features: Bugs Fixed: LPP-6078 Technical Reviewer: hminsky QA Reviewer: (pending) Doc Reviewer: (pending) Documentation: Release Notes: Details: Added support for nsprefix to the xml-translator. Tests: git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@9412 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
c49a3d270b1cedaff26b87770119785d428060e6
examples/web/app/classes/server/FMSClient.as
examples/web/app/classes/server/FMSClient.as
package server { dynamic public class FMSClient extends Object { public function FMSClient() { super(); } public function onRegisterUser(user:String, result:Object):void { trace('FMSClient.onRegisterUser:', user, result); } public function onSigninUser(user:String, result:Object):void { trace('FMSClient.onSigninUser:', user, result); } public function onStartGame(user:String):void { trace('FMSClient.onStartGame:', user); } public function onChangePlayer(user:String, player:uint):void { trace('FMSClient.onChangePlayer:', user, player); } public function onUpdateScore(score:uint):void { trace('FMSClient.onUpdateScore:', score); } public function onDisconnect(user:String):void { trace('FMSClient.onDisconnect:', user); } } }
package server { dynamic public class FMSClient extends Object { public function FMSClient() { super(); } public function onRegisterUser(user:String, result:Object):void { trace('FMSClient.onRegisterUser:', user, result); } public function onSigninUser(user:String, result:Object):void { trace('FMSClient.onSigninUser:', user, result); } public function onStartGame(user:String):void { trace('FMSClient.onStartGame:', user); } public function onChangePlayer(user:String, player:uint):void { trace('FMSClient.onChangePlayer:', user, player); } public function onUpdateScore(user:String, score:uint):void { trace('FMSClient.onUpdateScore:', user, score); } public function onDisconnect(user:String):void { trace('FMSClient.onDisconnect:', user); } } }
Update FMSClient.as
Update FMSClient.as
ActionScript
apache-2.0
adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler
b2104ff064da0c1174047c89f16740b10a57e92e
plugins/akamaiHDPlugin/src/com/kaltura/kdpfl/plugin/akamaiHDMediator.as
plugins/akamaiHDPlugin/src/com/kaltura/kdpfl/plugin/akamaiHDMediator.as
package com.kaltura.kdpfl.plugin { import com.akamai.osmf.utils.AkamaiStrings; import com.kaltura.kdpfl.model.ConfigProxy; import com.kaltura.kdpfl.model.MediaProxy; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.view.media.KMediaPlayerMediator; import org.osmf.events.MediaElementEvent; import org.osmf.traits.DVRTrait; import org.osmf.traits.MediaTraitType; import org.puremvc.as3.interfaces.INotification; import org.puremvc.as3.patterns.mediator.Mediator; public class akamaiHDMediator extends Mediator { public static const NAME:String = "akamaiHDMediator"; /** * default buffer length to be used when playing with HD Akamai plugin */ public static const DEFAULT_HD_BUFFER_LENGTH:int = 20; /** * default bandwith check time in seconds */ public static const DEFAULT_HD_BANDWIDTH_CHECK_TIME:int = 2; private var _mediaProxy:MediaProxy; private var _flashvars:Object; public function akamaiHDMediator(viewComponent:Object=null) { super(NAME, viewComponent); } override public function onRegister():void { _mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy; _flashvars = (facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy).vo.flashvars; super.onRegister(); } override public function listNotificationInterests():Array { return [ NotificationType.MEDIA_READY, NotificationType.PLAYER_PLAYED, NotificationType.MEDIA_ELEMENT_READY ]; } override public function handleNotification(notification:INotification):void { switch (notification.getName()) { case NotificationType.PLAYER_PLAYED: //workaround to display the bitrate that was automatically detected by akamai if (_flashvars.hdnetworkEnableBRDetection && _flashvars.hdnetworkEnableBRDetection=="true") { _mediaProxy.notifyStartingIndexChanged((facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).player.currentDynamicStreamIndex); } break; case NotificationType.MEDIA_READY: //add akamai metadata on the stream resource //find last index of resource metadata flashvars. var i:int = 0; while (_flashvars.hasOwnProperty("objMetadataNamespace" + i) && _flashvars.hasOwnProperty("objMetadataValues" + i)) { i++; } var bufferLength:int = DEFAULT_HD_BUFFER_LENGTH; if (_flashvars.hdnetworkBufferLength && _flashvars.hdnetworkBufferLength!="") { bufferLength = _flashvars.hdnetworkBufferLength; } //Then add akamai resource metadata on the next index _flashvars["objMetadataNamespace"+i] = AkamaiStrings.AKAMAI_ADVANCED_STREAMING_PLUGIN_METADATA_NAMESPACE; //set buffer length var akamaiMetadataValues:String = AkamaiStrings.AKAMAI_METADATA_KEY_MAX_BUFFER_LENGTH + "=" + bufferLength; if (_flashvars.hdnetworkEnableBRDetection && _flashvars.hdnetworkEnableBRDetection=="true") { //var bwEstimationObject:Object = new Object(); //bwEstimationObject.enabled = true; var bandwidthEstimationPeriodInSeconds:int; if (_flashvars.hdnetworkBRDetectionTime && _flashvars.hdnetworkBRDetectionTime!="") { bandwidthEstimationPeriodInSeconds = _flashvars.hdnetworkBRDetectionTime; } else { bandwidthEstimationPeriodInSeconds = DEFAULT_HD_BANDWIDTH_CHECK_TIME; } //enable akamai BW detection akamaiMetadataValues += "&"+ AkamaiStrings.AKAMAI_METADATA_KEY_SET_BANDWIDTH_ESTIMATION_ENABLED + "={enabled:true,bandwidthEstimationPeriodInSeconds:"+bandwidthEstimationPeriodInSeconds+"}"; } else { var preferedIndex:int = _mediaProxy.getFlavorByBitrate(_mediaProxy.vo.preferedFlavorBR); if (preferedIndex!=-1) { akamaiMetadataValues += "&" + AkamaiStrings.AKAMAI_METDATA_KEY_MBR_STARTING_INDEX + "=" + preferedIndex; _mediaProxy.notifyStartingIndexChanged(preferedIndex); } } _flashvars["objMetadataValues"+i] = akamaiMetadataValues; break; case NotificationType.MEDIA_ELEMENT_READY: if (_mediaProxy.vo.isLive && _mediaProxy.vo.canSeek && _mediaProxy.vo.media) { _mediaProxy.vo.media.addEventListener(MediaElementEvent.TRAIT_ADD, onMediaTraitAdd); } break; } } /** * sets DVR window size according to actual window size (including Akamai's padding) * @param e * */ private function onMediaTraitAdd(e: MediaElementEvent) : void { if (e.traitType==MediaTraitType.DVR) { var dvrTrait:DVRTrait = _mediaProxy.vo.media.getTrait(MediaTraitType.DVR) as DVRTrait; (facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).dvrWinSize = dvrTrait.windowDuration; _mediaProxy.vo.media.removeEventListener(MediaElementEvent.TRAIT_ADD, onMediaTraitAdd); } } } }
package com.kaltura.kdpfl.plugin { import com.akamai.osmf.utils.AkamaiStrings; import com.kaltura.kdpfl.model.ConfigProxy; import com.kaltura.kdpfl.model.MediaProxy; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.view.media.KMediaPlayerMediator; import org.osmf.events.MediaElementEvent; import org.osmf.traits.DVRTrait; import org.osmf.traits.MediaTraitType; import org.puremvc.as3.interfaces.INotification; import org.puremvc.as3.patterns.mediator.Mediator; public class akamaiHDMediator extends Mediator { public static const NAME:String = "akamaiHDMediator"; /** * default buffer length to be used when playing with HD Akamai plugin */ public static const DEFAULT_HD_BUFFER_LENGTH:int = 20; /** * default bandwith check time in seconds */ public static const DEFAULT_HD_BANDWIDTH_CHECK_TIME:int = 2; private var _mediaProxy:MediaProxy; private var _flashvars:Object; public function akamaiHDMediator(viewComponent:Object=null) { super(NAME, viewComponent); } override public function onRegister():void { _mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy; _flashvars = (facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy).vo.flashvars; super.onRegister(); } override public function listNotificationInterests():Array { return [ NotificationType.MEDIA_READY, NotificationType.PLAYER_PLAYED, NotificationType.MEDIA_ELEMENT_READY ]; } override public function handleNotification(notification:INotification):void { switch (notification.getName()) { case NotificationType.PLAYER_PLAYED: //workaround to display the bitrate that was automatically detected by akamai if (_flashvars.hdnetworkEnableBRDetection && _flashvars.hdnetworkEnableBRDetection=="true") { _mediaProxy.notifyStartingIndexChanged((facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).player.currentDynamicStreamIndex); } break; case NotificationType.MEDIA_READY: //add akamai metadata on the stream resource //find last index of resource metadata flashvars. var i:int = 0; while (_flashvars.hasOwnProperty("objMetadataNamespace" + i) && _flashvars.hasOwnProperty("objMetadataValues" + i)) { i++; } var bufferLength:int = DEFAULT_HD_BUFFER_LENGTH; if (_flashvars.hdnetworkBufferLength && _flashvars.hdnetworkBufferLength!="") { bufferLength = _flashvars.hdnetworkBufferLength; } //Then add akamai resource metadata on the next index _flashvars["objMetadataNamespace"+i] = AkamaiStrings.AKAMAI_ADVANCED_STREAMING_PLUGIN_METADATA_NAMESPACE; //set buffer length var akamaiMetadataValues:String = AkamaiStrings.AKAMAI_METADATA_KEY_MAX_BUFFER_LENGTH + "=" + bufferLength; if (_flashvars.hdnetworkEnableBRDetection && _flashvars.hdnetworkEnableBRDetection=="true") { //var bwEstimationObject:Object = new Object(); //bwEstimationObject.enabled = true; var bandwidthEstimationPeriodInSeconds:int; if (_flashvars.hdnetworkBRDetectionTime && _flashvars.hdnetworkBRDetectionTime!="") { bandwidthEstimationPeriodInSeconds = _flashvars.hdnetworkBRDetectionTime; } else { bandwidthEstimationPeriodInSeconds = DEFAULT_HD_BANDWIDTH_CHECK_TIME; } //enable akamai BW detection akamaiMetadataValues += "&"+ AkamaiStrings.AKAMAI_METADATA_KEY_SET_BANDWIDTH_ESTIMATION_ENABLED + "={enabled:true,bandwidthEstimationPeriodInSeconds:"+bandwidthEstimationPeriodInSeconds+"}"; } else { var preferedIndex:int = _mediaProxy.getFlavorByBitrate(_mediaProxy.vo.preferedFlavorBR); if (preferedIndex!=-1) { akamaiMetadataValues += "&" + AkamaiStrings.AKAMAI_METADATA_KEY_MBR_STARTING_INDEX + "=" + preferedIndex; _mediaProxy.notifyStartingIndexChanged(preferedIndex); } } _flashvars["objMetadataValues"+i] = akamaiMetadataValues; break; case NotificationType.MEDIA_ELEMENT_READY: if (_mediaProxy.vo.isLive && _mediaProxy.vo.canSeek && _mediaProxy.vo.media) { _mediaProxy.vo.media.addEventListener(MediaElementEvent.TRAIT_ADD, onMediaTraitAdd); } break; } } /** * sets DVR window size according to actual window size (including Akamai's padding) * @param e * */ private function onMediaTraitAdd(e: MediaElementEvent) : void { if (e.traitType==MediaTraitType.DVR) { var dvrTrait:DVRTrait = _mediaProxy.vo.media.getTrait(MediaTraitType.DVR) as DVRTrait; (facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).dvrWinSize = dvrTrait.windowDuration; _mediaProxy.vo.media.removeEventListener(MediaElementEvent.TRAIT_ADD, onMediaTraitAdd); } } } }
fix akamai mbr starting index type
fix akamai mbr starting index type
ActionScript
agpl-3.0
kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,shvyrev/kdp
08961ed24671a5d536366cb22680787e1762eff1
src/aerys/minko/type/loader/TextureLoader.as
src/aerys/minko/type/loader/TextureLoader.as
package aerys.minko.type.loader { import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.type.Signal; import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.DisplayObject; import flash.display.Loader; import flash.display.LoaderInfo; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.system.LoaderContext; import flash.utils.ByteArray; import flash.utils.getQualifiedClassName; public class TextureLoader implements ILoader { private var _progress : Signal; private var _error : Signal; private var _complete : Signal; private var _isComplete : Boolean; private var _mipmap : Boolean; private var _textureResource : TextureResource; public function get progress() : Signal { return _progress; } public function get error() : Signal { return _error; } public function get complete() : Signal { return _complete; } public function get isComplete() : Boolean { return _isComplete; } public function get textureResource() : TextureResource { return _textureResource; } public function TextureLoader(enableMipmapping : Boolean = true) { _mipmap = enableMipmapping; _textureResource = new TextureResource(); _isComplete = false; _error = new Signal('TextureLoader.error'); _progress = new Signal('TextureLoader.progress'); _complete = new Signal('TextureLoader.complete'); } public function load(request : URLRequest) : void { var loader : URLLoader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.BINARY; loader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler); loader.addEventListener(Event.COMPLETE, loadCompleteHandler); loader.addEventListener(IOErrorEvent.IO_ERROR, loadIoErrorHandler); loader.load(request); } private function loadIoErrorHandler(e : IOErrorEvent) : void { _textureResource = null; _error.execute(this, e.errorID, e.text); } private function loadProgressHandler(e : ProgressEvent) : void { _progress.execute(this, e.bytesLoaded, e.bytesTotal); } private function loadCompleteHandler(e : Event) : void { loadBytes(URLLoader(e.currentTarget).data); } public function loadClass(classObject : Class) : void { var assetObject : Object = new classObject(); if (assetObject is Bitmap || assetObject is BitmapData) { var bitmapData : BitmapData = assetObject as BitmapData; if (bitmapData == null) bitmapData = Bitmap(assetObject).bitmapData; // _textureResource = new TextureResource(); _textureResource.setContentFromBitmapData(bitmapData, _mipmap); _complete.execute(this, _textureResource); _isComplete = true; } else if (assetObject is ByteArray) { loadBytes(ByteArray(assetObject)); } else { var className : String = getQualifiedClassName(classObject); className = className.substr(className.lastIndexOf(':') + 1); _isComplete = true; throw new Error('No texture can be created from an object of type \'' + className + '\''); } } public function loadBytes(bytes : ByteArray) : void { bytes.position = 0; if (bytes.readByte() == 'A'.charCodeAt(0) && bytes.readByte() == 'T'.charCodeAt(0) && bytes.readByte() == 'F'.charCodeAt(0)) { bytes.position = 0; // _textureResource = new TextureResource(); _textureResource.setContentFromATF(bytes); _complete.execute(this, _textureResource); _isComplete = true; } else { bytes.position = 0; var loader : Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadBytesCompleteHandler); loader.loadBytes(bytes); } } private function loadBytesCompleteHandler(e : Event) : void { var displayObject : DisplayObject = LoaderInfo(e.currentTarget).content; if (displayObject is Bitmap) { _textureResource.setContentFromBitmapData(Bitmap(displayObject).bitmapData, _mipmap); _complete.execute(this, _textureResource); _isComplete = true; } else { var className : String = getQualifiedClassName(displayObject); className = className.substr(className.lastIndexOf(':') + 1); _isComplete = true; throw new Error('No texture can be created from an object of type \'' + className + '\''); } } public static function loadClass(classObject : Class, enableMipMapping : Boolean = true) : TextureResource { var textureLoader : TextureLoader = new TextureLoader(enableMipMapping); textureLoader.loadClass(classObject); return textureLoader.textureResource; } public static function load(request : URLRequest, enableMipMapping : Boolean = true) : TextureResource { var textureLoader : TextureLoader = new TextureLoader(enableMipMapping); textureLoader.load(request); return textureLoader.textureResource; } public static function loadBytes(bytes : ByteArray, enableMipMapping : Boolean = true) : TextureResource { var textureLoader : TextureLoader = new TextureLoader(enableMipMapping); textureLoader.loadBytes(bytes); return textureLoader.textureResource; } } }
package aerys.minko.type.loader { import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.type.Signal; import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.DisplayObject; import flash.display.Loader; import flash.display.LoaderInfo; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.system.LoaderContext; import flash.utils.ByteArray; import flash.utils.getQualifiedClassName; public class TextureLoader implements ILoader { private var _progress : Signal; private var _error : Signal; private var _complete : Signal; private var _isComplete : Boolean; private var _mipmap : Boolean; protected var _textureResource : TextureResource; public function get progress() : Signal { return _progress; } public function get error() : Signal { return _error; } public function get complete() : Signal { return _complete; } public function get isComplete() : Boolean { return _isComplete; } public function get textureResource() : TextureResource { return _textureResource; } public function TextureLoader(enableMipmapping : Boolean = true) { _mipmap = enableMipmapping; _textureResource = new TextureResource(); _isComplete = false; _error = new Signal('TextureLoader.error'); _progress = new Signal('TextureLoader.progress'); _complete = new Signal('TextureLoader.complete'); } public function load(request : URLRequest) : void { var loader : URLLoader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.BINARY; loader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler); loader.addEventListener(Event.COMPLETE, loadCompleteHandler); loader.addEventListener(IOErrorEvent.IO_ERROR, loadIoErrorHandler); loader.load(request); } private function loadIoErrorHandler(e : IOErrorEvent) : void { _textureResource = null; _error.execute(this, e.errorID, e.text); } private function loadProgressHandler(e : ProgressEvent) : void { _progress.execute(this, e.bytesLoaded, e.bytesTotal); } private function loadCompleteHandler(e : Event) : void { loadBytes(URLLoader(e.currentTarget).data); } public function loadClass(classObject : Class) : void { var assetObject : Object = new classObject(); if (assetObject is Bitmap || assetObject is BitmapData) { var bitmapData : BitmapData = assetObject as BitmapData; if (bitmapData == null) bitmapData = Bitmap(assetObject).bitmapData; // _textureResource = new TextureResource(); _textureResource.setContentFromBitmapData(bitmapData, _mipmap); _complete.execute(this, _textureResource); _isComplete = true; } else if (assetObject is ByteArray) { loadBytes(ByteArray(assetObject)); } else { var className : String = getQualifiedClassName(classObject); className = className.substr(className.lastIndexOf(':') + 1); _isComplete = true; throw new Error('No texture can be created from an object of type \'' + className + '\''); } } public function loadBytes(bytes : ByteArray) : void { bytes.position = 0; if (bytes.readByte() == 'A'.charCodeAt(0) && bytes.readByte() == 'T'.charCodeAt(0) && bytes.readByte() == 'F'.charCodeAt(0)) { bytes.position = 0; // _textureResource = new TextureResource(); _textureResource.setContentFromATF(bytes); _complete.execute(this, _textureResource); _isComplete = true; } else { bytes.position = 0; var loader : Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadBytesCompleteHandler); loader.loadBytes(bytes); } } private function loadBytesCompleteHandler(e : Event) : void { var displayObject : DisplayObject = LoaderInfo(e.currentTarget).content; if (displayObject is Bitmap) { _textureResource.setContentFromBitmapData(Bitmap(displayObject).bitmapData, _mipmap); _complete.execute(this, _textureResource); _isComplete = true; } else { var className : String = getQualifiedClassName(displayObject); className = className.substr(className.lastIndexOf(':') + 1); _isComplete = true; throw new Error('No texture can be created from an object of type \'' + className + '\''); } } public static function loadClass(classObject : Class, enableMipMapping : Boolean = true) : TextureResource { var textureLoader : TextureLoader = new TextureLoader(enableMipMapping); textureLoader.loadClass(classObject); return textureLoader.textureResource; } public static function load(request : URLRequest, enableMipMapping : Boolean = true) : TextureResource { var textureLoader : TextureLoader = new TextureLoader(enableMipMapping); textureLoader.load(request); return textureLoader.textureResource; } public static function loadBytes(bytes : ByteArray, enableMipMapping : Boolean = true) : TextureResource { var textureLoader : TextureLoader = new TextureLoader(enableMipMapping); textureLoader.loadBytes(bytes); return textureLoader.textureResource; } } }
Make TextureLoader extendable.
Make TextureLoader extendable.
ActionScript
mit
aerys/minko-as3
43d53e73a88b2e650bbe7d3482b176543b886001
src/as/com/threerings/ezgame/PlayersDisplay.as
src/as/com/threerings/ezgame/PlayersDisplay.as
// // $Id$ // // Vilya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/vilya/ // // 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.ezgame { import flash.display.DisplayObject; import flash.display.Sprite; import flash.text.StyleSheet; import flash.text.TextField; import flash.text.TextFieldAutoSize; /** * A sample component that displays the players of a game. If the game has a turn holder, the * current turn holder will be highlighted. * * This class demonstrates that the 'Game' interface may be implemented by any DisplayObject that * want access to the GameObject, not just the actual DisplayObject that is displaying the * game. Here, all we are interested in is the names of the players and the current turn holder. * * You may use this, with any modifications you desire, in your game. Feel free to copy/modify or * extend this class. */ public class PlayersDisplay extends Sprite implements StateChangedListener { /** * Set the game control that will be used with this display. */ public function setGameControl (gameCtrl :EZGameControl) :void { _gameCtrl = gameCtrl; _gameCtrl.registerListener(this); configureInterface(); } // from StateChangedListener public function stateChanged (event :StateChangedEvent) :void { displayCurrentTurn(); } /** * Set up the player labels and configure the look of the entire UI. */ protected function configureInterface () :void { var border :int = getBorderSpacing(); var pad :int = getInternalSpacing(); var y :Number = border; var maxWidth :Number = 0; var label :TextField; var icon :DisplayObject; // create a label at the top, above the player names label = createHeader(); if (label != null) { label.x = border; label.y = y; addChild(label); y += label.textHeight + pad; maxWidth = label.textWidth + TEXTWIDTH_ADD; } if (!_gameCtrl.isConnected()) { return; // nothing to do } var players :Array = _gameCtrl.seating.getPlayerIds(); // create a label for each player for each (var playerId :int in players) { var name :String = _gameCtrl.getOccupantName(playerId); label = createPlayerLabel(playerId, name); icon = createPlayerIcon(playerId, name); var iconW :int = 0; var iconH :int = 0; if (icon != null) { iconW = icon.width + pad; iconH = icon.height; icon.x = border; icon.y = y; addChild(icon); } label.x = border + iconW; label.y = y; addChild(label); y += Math.max(label.textHeight, iconH) + pad; maxWidth = Math.max(maxWidth, iconW + label.textWidth + TEXTWIDTH_ADD); _playerLabels.push(label); } // make all the player labels the same width (looks nice when highlighted) for each (label in _playerLabels) { label.autoSize = TextFieldAutoSize.NONE; label.width = maxWidth - (label.x - border); } // y has a pad at the end, we want border instead y += border - pad; drawBorder(maxWidth); displayCurrentTurn(); } protected function createHeader () :TextField { var label :TextField = new TextField(); // damn stylesheet doesn't seem to actually -work- // var style :StyleSheet = new StyleSheet(); // style.fontWeight = "bold"; // style.color = "#0000FF"; // style.fontFamily = "serif"; // style.fontSize = 18; // label.styleSheet = style; label.autoSize = TextFieldAutoSize.LEFT; label.selectable = false; label.text = "Players"; return label; } /** * Create a TextArea that will be used to display player names. */ protected function createPlayerLabel (playerId :int, name :String) :TextField { var label :TextField = new TextField(); label.autoSize = TextFieldAutoSize.LEFT; label.background = true; label.selectable = false; label.text = name; return label; } protected function createPlayerIcon (playerId :int, name :String) :DisplayObject { return null; } protected function drawBorder (var maxWidth :int) :void { // draw a blue rectangle around everything graphics.clear(); graphics.lineStyle(1, 0x0000FF); graphics.drawRect(0, 0, maxWidth + (border * 2), y); } protected function getBackground (isTurn :Boolean) :uint { return isTurn ? 0xFF9999 : 0xFFFFFF; } protected function getBorderSpacing () :int { return 6; } protected function getInternalSpacing () :int { return 2; } /** * Re-set the background color for every player label, highlighting only the player who has the * turn. */ protected function displayCurrentTurn () :void { var idx :int = _gameCtrl.isInPlay() ? _gameCtrl.seating.getPlayerPosition(_gameCtrl.getTurnHolder()) : -1; for (var ii :int = 0; ii < _playerLabels.length; ii++) { var label :TextField = (_playerLabels[ii] as TextField); label.backgroundColor = getBackground(ii == idx); } } /** Our game Control. */ protected var _gameCtrl :EZGameControl; /** An array of labels, one for each player name. */ protected var _playerLabels :Array = []; /** These are fucking ridiculous. */ protected static const TEXTWIDTH_ADD :int = 5; protected static const TEXTHEIGHT_ADD :int = 4; } }
// // $Id$ // // Vilya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/vilya/ // // 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.ezgame { import flash.display.DisplayObject; import flash.display.Sprite; import flash.text.StyleSheet; import flash.text.TextField; import flash.text.TextFieldAutoSize; /** * A sample component that displays the players of a game. If the game has a turn holder, the * current turn holder will be highlighted. * * This class demonstrates that the 'Game' interface may be implemented by any DisplayObject that * want access to the GameObject, not just the actual DisplayObject that is displaying the * game. Here, all we are interested in is the names of the players and the current turn holder. * * You may use this, with any modifications you desire, in your game. Feel free to copy/modify or * extend this class. */ public class PlayersDisplay extends Sprite implements StateChangedListener { /** * Set the game control that will be used with this display. */ public function setGameControl (gameCtrl :EZGameControl) :void { _gameCtrl = gameCtrl; _gameCtrl.registerListener(this); configureInterface(); } // from StateChangedListener public function stateChanged (event :StateChangedEvent) :void { displayCurrentTurn(); } /** * Set up the player labels and configure the look of the entire UI. */ protected function configureInterface () :void { var border :int = getBorderSpacing(); var pad :int = getInternalSpacing(); var y :Number = border; var maxWidth :Number = 0; var label :TextField; var icon :DisplayObject; // create a label at the top, above the player names label = createHeader(); if (label != null) { label.x = border; label.y = y; addChild(label); y += label.textHeight + pad; maxWidth = label.textWidth + TEXTWIDTH_ADD; } if (!_gameCtrl.isConnected()) { return; // nothing to do } var players :Array = _gameCtrl.seating.getPlayerIds(); // create a label for each player for each (var playerId :int in players) { var name :String = _gameCtrl.getOccupantName(playerId); label = createPlayerLabel(playerId, name); icon = createPlayerIcon(playerId, name); var iconW :int = 0; var iconH :int = 0; if (icon != null) { iconW = icon.width + pad; iconH = icon.height; icon.x = border; icon.y = y; addChild(icon); } label.x = border + iconW; label.y = y; addChild(label); y += Math.max(label.textHeight, iconH) + pad; maxWidth = Math.max(maxWidth, iconW + label.textWidth + TEXTWIDTH_ADD); _playerLabels.push(label); } // make all the player labels the same width (looks nice when highlighted) for each (label in _playerLabels) { label.autoSize = TextFieldAutoSize.NONE; label.width = maxWidth - (label.x - border); } // y has a pad at the end, we want border instead y += border - pad; drawBorder(maxWidth); displayCurrentTurn(); } protected function createHeader () :TextField { var label :TextField = new TextField(); // damn stylesheet doesn't seem to actually -work- // var style :StyleSheet = new StyleSheet(); // style.fontWeight = "bold"; // style.color = "#0000FF"; // style.fontFamily = "serif"; // style.fontSize = 18; // label.styleSheet = style; label.autoSize = TextFieldAutoSize.LEFT; label.selectable = false; label.text = "Players"; return label; } /** * Create a TextArea that will be used to display player names. */ protected function createPlayerLabel (playerId :int, name :String) :TextField { var label :TextField = new TextField(); label.autoSize = TextFieldAutoSize.LEFT; label.background = true; label.selectable = false; label.text = name; return label; } protected function createPlayerIcon (playerId :int, name :String) :DisplayObject { return null; } protected function drawBorder (maxWidth :int) :void { // draw a blue rectangle around everything graphics.clear(); graphics.lineStyle(1, 0x0000FF); graphics.drawRect(0, 0, maxWidth + (getBorderSpacing() * 2), y); } protected function getBackground (isTurn :Boolean) :uint { return isTurn ? 0xFF9999 : 0xFFFFFF; } protected function getBorderSpacing () :int { return 6; } protected function getInternalSpacing () :int { return 2; } /** * Re-set the background color for every player label, highlighting only the player who has the * turn. */ protected function displayCurrentTurn () :void { var idx :int = _gameCtrl.isInPlay() ? _gameCtrl.seating.getPlayerPosition(_gameCtrl.getTurnHolder()) : -1; for (var ii :int = 0; ii < _playerLabels.length; ii++) { var label :TextField = (_playerLabels[ii] as TextField); label.backgroundColor = getBackground(ii == idx); } } /** Our game Control. */ protected var _gameCtrl :EZGameControl; /** An array of labels, one for each player name. */ protected var _playerLabels :Array = []; /** These are fucking ridiculous. */ protected static const TEXTWIDTH_ADD :int = 5; protected static const TEXTHEIGHT_ADD :int = 4; } }
Fix booches.
Fix booches. git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@335 c613c5cb-e716-0410-b11b-feb51c14d237
ActionScript
lgpl-2.1
threerings/vilya,threerings/vilya
6f3e6e0cf6bd1178eb5aa12ccb1e9e179f9c420b
src/flails/mxml/ResourcefulServiceInvoker.as
src/flails/mxml/ResourcefulServiceInvoker.as
package flails.mxml { import com.asfusion.mate.actions.AbstractServiceInvoker; import com.asfusion.mate.actionLists.IScope; import com.asfusion.mate.actions.IAction; import mx.rpc.events.ResultEvent; import mx.rpc.events.FaultEvent; import flails.request.RequestPipe; import flails.resource.Resources; import flails.resource.Resource; public class ResourcefulServiceInvoker extends AbstractServiceInvoker implements IAction { public var resource:Resource; public var data:Array; public var type:String; public var id:String; public var parent:Object; [Bindable] public var result:Object; public function ResourcefulServiceInvoker() { currentInstance = this; } override protected function prepare(scope:IScope):void { super.prepare(scope); } override protected function run(scope:IScope):void { trace ("Using resource " + resource); var rp:RequestPipe = resource.newRequestPipe(); innerHandlersDispatcher = rp; if (resultHandlers && resultHandlers.length > 0) { createInnerHandlers(scope, ResultEvent.RESULT, resultHandlers); } if (faultHandlers && faultHandlers.length > 0) { createInnerHandlers(scope, FaultEvent.FAULT, faultHandlers); } trace("calling " + type + "()"); rp[type].apply(rp, data); } } }
package flails.mxml { import com.asfusion.mate.actions.AbstractServiceInvoker; import com.asfusion.mate.actionLists.IScope; import com.asfusion.mate.actions.IAction; import mx.rpc.events.ResultEvent; import mx.rpc.events.FaultEvent; import flails.request.RequestPipe; import flails.resource.Resources; import flails.resource.Resource; public class ResourcefulServiceInvoker extends AbstractServiceInvoker implements IAction { private var _data:Array; public var resource:Resource; public var type:String; public var id:String; public var parent:Object; [Bindable] public var result:Object; public function set data(args:Object):void { trace("setting data"); if (args is Array) _data = args as Array; else _data = [args]; } override protected function prepare(scope:IScope):void { currentInstance = this; super.prepare(scope); } override protected function run(scope:IScope):void { trace ("Using resource " + resource); var rp:RequestPipe = resource.newRequestPipe(); innerHandlersDispatcher = rp; if (resultHandlers && resultHandlers.length > 0) { createInnerHandlers(scope, ResultEvent.RESULT, resultHandlers); } if (faultHandlers && faultHandlers.length > 0) { createInnerHandlers(scope, FaultEvent.FAULT, faultHandlers); } trace("calling " + type + "() with " + _data); rp[type].apply(rp, _data); } } }
Set currentInstance on prepare, not on instantiation time.
Set currentInstance on prepare, not on instantiation time.
ActionScript
mit
lancecarlson/flails,lancecarlson/flails
18b61d4da083c6396cd85898473cfc4db5276e2b
frameworks/projects/Core/as/src/org/apache/flex/utils/BeadMetrics.as
frameworks/projects/Core/as/src/org/apache/flex/utils/BeadMetrics.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 { import org.apache.flex.core.UIMetrics; import org.apache.flex.core.ValuesManager; /** * The BeadMetrics class is a utility class that computes the offset of the content * in a container based on border-thickness and padding styles. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class BeadMetrics { /** * Compute the offset of the content * in a container based on border-thickness and padding styles. * * @param object The object with style values. * @return The offsets of the content. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public static function getMetrics(object:Object) : UIMetrics { var borderThickness:Object = ValuesManager.valuesImpl.getValue(object,"border-thickness"); var borderOffset:Number; if( borderThickness == null ) { borderOffset = 0; } else { borderOffset = Number(borderThickness); if( isNaN(borderOffset) ) borderOffset = 0; } var paddingLeft:Object; var paddingTop:Object; var paddingRight:Object; var paddingBottom:Object; var padding:Object = ValuesManager.valuesImpl.getValue(object, "padding"); if (padding is Array) { if (padding.length == 1) paddingLeft = paddingTop = padding[0]; else if (padding.length <= 3) { paddingTop = padding[0]; paddingLeft = padding[1]; paddingBottom = padding[0]; paddingRight = padding[1]; } else if (padding.length == 4) { paddingTop = padding[0]; paddingLeft = padding[1]; paddingBottom = padding[2]; paddingRight = padding[3]; } } else if (padding == null) { paddingLeft = ValuesManager.valuesImpl.getValue(object, "padding-left"); paddingTop = ValuesManager.valuesImpl.getValue(object, "padding-top"); paddingRight = ValuesManager.valuesImpl.getValue(object, "padding-right"); paddingBottom = ValuesManager.valuesImpl.getValue(object, "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); var marginLeft:Object; var marginRight:Object; var marginTop:Object; var marginBottom:Object; var margin:Object; margin = ValuesManager.valuesImpl.getValue(object, "margin"); if (margin is Array) { if (margin.length == 1) marginLeft = marginTop = marginRight = marginBottom = margin[0]; else if (margin.length <= 3) { marginLeft = marginRight = margin[1]; marginTop = marginBottom = margin[0]; } else if (margin.length == 4) { marginLeft = margin[3]; marginBottom = margin[2]; marginRight = margin[1]; marginTop = margin[0]; } } else if (margin == null) { marginLeft = ValuesManager.valuesImpl.getValue(object, "margin-left"); marginTop = ValuesManager.valuesImpl.getValue(object, "margin-top"); marginRight = ValuesManager.valuesImpl.getValue(object, "margin-right"); marginBottom = ValuesManager.valuesImpl.getValue(object, "margin-bottom"); } else { marginLeft = marginTop = marginBottom = marginRight = margin; } var ml:Number; var mr:Number; var mt:Number; var mb:Number; var lastmr:Number; if (marginLeft == "auto") ml = 0; else { ml = Number(marginLeft); if (isNaN(ml)) ml = 0; } if (marginRight == "auto") mr = 0; else { mr = Number(marginRight); if (isNaN(mr)) mr = 0; } mt = Number(marginTop); if (isNaN(mt)) mt = 0; mb = Number(marginBottom); if (isNaN(mb)) mb = 0; var result:UIMetrics = new UIMetrics(); result.top = borderOffset + pt; result.left = borderOffset + pl; result.bottom = borderOffset + pb; result.right = borderOffset + pr; result.marginTop = mt; result.marginLeft = ml; result.marginBottom = mb; result.marginRight = mr; return result; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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 { import org.apache.flex.core.UIMetrics; import org.apache.flex.core.ValuesManager; /** * The BeadMetrics class is a utility class that computes the offset of the content * in a container based on border-thickness and padding styles. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class BeadMetrics { /** * Compute the offset of the content * in a container based on border-thickness and padding styles. * * @param object The object with style values. * @return The offsets of the content. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public static function getMetrics(object:Object) : UIMetrics { var borderThickness:Object = ValuesManager.valuesImpl.getValue(object,"border-width"); var borderOffset:Number; if( borderThickness == null ) { borderThickness = ValuesManager.valuesImpl.getValue(object,"border"); if (borderThickness != null) { if (borderThickness is Array) borderOffset = CSSUtils.toNumber(borderThickness[0], object.width); else borderOffset = CSSUtils.toNumber(borderThickness as String, object.width); } else borderOffset = 0; } else { borderOffset = Number(borderThickness); if( isNaN(borderOffset) ) borderOffset = 0; } var paddingLeft:Object; var paddingTop:Object; var paddingRight:Object; var paddingBottom:Object; var padding:Object = ValuesManager.valuesImpl.getValue(object, "padding"); paddingLeft = ValuesManager.valuesImpl.getValue(object, "padding-left"); paddingTop = ValuesManager.valuesImpl.getValue(object, "padding-top"); paddingRight = ValuesManager.valuesImpl.getValue(object, "padding-right"); paddingBottom = ValuesManager.valuesImpl.getValue(object, "padding-bottom"); var pl:Number = CSSUtils.getLeftValue(paddingLeft, padding, object.width); var pt:Number = CSSUtils.getTopValue(paddingTop, padding, object.height); var pr:Number = CSSUtils.getRightValue(paddingRight, padding, object.width); var pb:Number = CSSUtils.getBottomValue(paddingBottom, padding, object.height); var marginLeft:Object; var marginRight:Object; var marginTop:Object; var marginBottom:Object; var margin:Object; margin = ValuesManager.valuesImpl.getValue(object, "margin"); marginLeft = ValuesManager.valuesImpl.getValue(object, "margin-left"); marginTop = ValuesManager.valuesImpl.getValue(object, "margin-top"); marginRight = ValuesManager.valuesImpl.getValue(object, "margin-right"); marginBottom = ValuesManager.valuesImpl.getValue(object, "margin-bottom"); var ml:Number; var mr:Number; var mt:Number; var mb:Number; var lastmr:Number; if (marginLeft == "auto") ml = 0; else { ml = CSSUtils.getLeftValue(marginLeft, margin, object.width); if (isNaN(ml)) ml = 0; } if (marginRight == "auto") mr = 0; else { mr = CSSUtils.getRightValue(marginRight, margin, object.width); if (isNaN(mr)) mr = 0; } mt = CSSUtils.getTopValue(marginTop, margin, object.height); if (isNaN(mt)) mt = 0; mb = CSSUtils.getBottomValue(marginBottom, margin, object.height); if (isNaN(mb)) mb = 0; borderOffset *= 2; // border on each side var result:UIMetrics = new UIMetrics(); result.top = borderOffset + pt; result.left = borderOffset + pl; result.bottom = borderOffset + pb; result.right = borderOffset + pr; result.marginTop = mt; result.marginLeft = ml; result.marginBottom = mb; result.marginRight = mr; return result; } } }
refactor to get style precedence correct
refactor to get style precedence correct
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
9fb221bc39317fa6872da6075545618996efd827
src/com/merlinds/miracle_tool/viewer/ViewerView.as
src/com/merlinds/miracle_tool/viewer/ViewerView.as
/** * User: MerlinDS * Date: 18.07.2014 * Time: 17:42 */ package com.merlinds.miracle_tool.viewer { import com.bit101.components.List; import com.bit101.components.Window; import com.merlinds.debug.log; import com.merlinds.miracle.Miracle; import com.merlinds.miracle.animations.AnimationHelper; import com.merlinds.miracle.display.MiracleAnimation; import com.merlinds.miracle.display.MiracleDisplayObject; import com.merlinds.miracle.geom.Color; import com.merlinds.miracle.utils.Asset; import com.merlinds.miracle.utils.MafReader; import com.merlinds.miracle_tool.models.AppModel; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; import flash.utils.setTimeout; [SWF(backgroundColor="0x333333", frameRate=60)] public class ViewerView extends Sprite { private var _model:AppModel; private var _assets:Vector.<Asset>; private var _window:Window; private var _name:String; private var _current:MiracleAnimation; public function ViewerView(model:AppModel = null) { super(); _model = model; if(_model == null){ _model = new AppModel(); } this.addEventListener(Event.ADDED_TO_STAGE, this.initialize); } //============================================================================== //{region PUBLIC METHODS //} endregion PUBLIC METHODS =================================================== //============================================================================== //{region PRIVATE\PROTECTED METHODS private function initialize(event:Event):void { this.removeEventListener(event.type, this.initialize); this.stage.scaleMode = StageScaleMode.NO_SCALE; this.stage.align = StageAlign.TOP_LEFT; Miracle.start(this.stage, this.createHandler, true); } private function choseAnimation():void { //find animation asset and add all of animations to chose list var n:int = _assets.length; for(var i:int = 0; i < n; i++){ var asset:Asset = _assets[i]; if(asset.type == Asset.TIMELINE_TYPE){ //parse output _window = new Window(this, 0, 0, "Chose animation"); var list:List = new List(_window, 0, 0, this.getAnimations(asset.output)); _window.x = this.stage.stageWidth - _window.width; _window.setSize(_window.height, list.height + 20); list.addEventListener(Event.SELECT, this.selectAnimationHandler); } } var w2:Window = new Window(this, _window.x, _window.y + _window.height + 10, "FPS"); list = new List(w2, 0, 0, [1, 5, 16, 24, 30, 35, 40, 60]); w2.height = 120; list.addEventListener(Event.SELECT, this.selectFpsHandler); } [Inline] private function getAnimations(bytes:ByteArray):Array { var result:Array = []; var reader:MafReader = new MafReader(); reader.execute(bytes, 1); var animations:Vector.<AnimationHelper> = reader.animations; for each(var animation:AnimationHelper in animations){ result.push(animation.name); } return result; } //} endregion PRIVATE\PROTECTED METHODS ======================================== //============================================================================== //{region EVENTS HANDLERS private function createHandler(animation:Boolean = false):void { //\TODO: Show view if it exit if(animation || _model.viewerInput == null){ _model.viewerInput = _model.lastFileDirection; _model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler); _model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite" + "file that you want to view"); } } private function selectFileHandler(event:Event):void { _model.viewerInput.removeEventListener(event.type, this.selectFileHandler); _model.lastFileDirection = _model.viewerInput.parent; var byteArray:ByteArray = new ByteArray(); var stream:FileStream = new FileStream(); stream.open(_model.viewerInput, FileMode.READ); stream.readBytes(byteArray); stream.close(); //parse if(_assets == null)_assets = new <Asset>[]; var asset:Asset = new Asset(_model.viewerInput.name, byteArray); if(asset.type == Asset.TIMELINE_TYPE){ _name = asset.name; } _assets.push(asset); if(_assets.length > 1){ this.choseAnimation(); Miracle.createScene(_assets,null, 1); Miracle.resume(); }else{ this.createHandler(true); } } private function selectAnimationHandler(event:Event):void { var list:List = event.target as List; //add animation to miracle var animation:String = list.selectedItem.toString(); log(this, "selectAnimationHandler", animation); var mesh:String = animation.substr(0, animation.lastIndexOf(".")); animation = animation.substr(animation.lastIndexOf(".") + 1); if(_current == null){ _current = Miracle.scene.createAnimation(mesh, animation, 60); _current.moveTO(this.stage.stageWidth >> 1, this.stage.stageHeight >> 1); _current.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage); }else{ _current.mesh = mesh; _current.animation = animation; _current.play(); } } private function imageAddedToStage(event:Event):void { trace("Added to stage"); } private function selectFpsHandler(event:Event):void { var list:List = event.target as List; //add animation to miracle if(_current != null){ _current.fps = int(list.selectedItem); } } //} endregion EVENTS HANDLERS ================================================== //============================================================================== //{region GETTERS/SETTERS //} endregion GETTERS/SETTERS ================================================== } }
/** * User: MerlinDS * Date: 18.07.2014 * Time: 17:42 */ package com.merlinds.miracle_tool.viewer { import com.bit101.components.List; import com.bit101.components.PushButton; import com.merlinds.miracle.Miracle; import com.merlinds.miracle.animations.AnimationHelper; import com.merlinds.miracle.display.MiracleDisplayObject; import com.merlinds.miracle.utils.Asset; import com.merlinds.miracle.utils.MafReader; import com.merlinds.miracle_tool.models.AppModel; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.net.FileFilter; import flash.utils.ByteArray; [SWF(backgroundColor="0x333333", frameRate=60)] public class ViewerView extends Sprite { private var _model:AppModel; private var _startBtn:PushButton; private var _texture:ByteArray; private var _animation:ByteArray; private var _fileName:String; private var _list:List; private var _instance:MiracleDisplayObject; public function ViewerView(model:AppModel = null) { super(); _model = model; if(_model == null){ _model = new AppModel(); } this.addEventListener(Event.ADDED_TO_STAGE, this.initialize); } //============================================================================== //{region PUBLIC METHODS //} endregion PUBLIC METHODS =================================================== //============================================================================== //{region PRIVATE\PROTECTED METHODS private function initialize(event:Event):void { this.removeEventListener(event.type, this.initialize); this.stage.scaleMode = StageScaleMode.NO_SCALE; this.stage.align = StageAlign.TOP_LEFT; _startBtn = new PushButton(this, this.stage.stageWidth >> 1, this.stage.stageHeight >> 1, "Start", this.startBtnHandler ); } function clear():void { if(_animation != null) _animation.clear(); if(_texture != null) _texture.clear(); _texture = null; _animation = null; _fileName = null; } private function startHandler():void { trace("Miracle was started"); var maf:Asset = new Asset(_fileName + ".maf", _animation); var mtf:Asset = new Asset(_fileName + ".mtf", _texture); Miracle.createScene(new <Asset>[maf, mtf], this.createdHandler, 1); } private function createdHandler():void { trace("Scene created"); this.getAnimationList(); } private function getAnimationList():void { var mafReader = new MafReader(); mafReader.execute(_animation, 1); var animationsName:Array = []; for each(var animation:AnimationHelper in mafReader.animations) { animationsName.push(animation.name); } trace("Was get animations", animationsName); _list = new List(this, this.stage.stageWidth - 200, 0, animationsName); _list.width = 200; _list.addEventListener(Event.SELECT, this.selectAnimationHandler); } private function getAnimation():void { var file:File = _model.lastFileDirection; file.browseForOpen("Get animation file", [new FileFilter("Miracle animation format", "*.maf")] ); file.addEventListener(Event.SELECT, this.animationSelected); file.addEventListener(Event.CANCEL, this.animationSelected); } private function readAnimation(file:File):void { _animation = new ByteArray(); var fileStream:FileStream = new FileStream(); fileStream.open(file, FileMode.READ); fileStream.readBytes(_animation); fileStream.close(); } private function getTexture(file:File):void { _fileName = file.name.substr(0, -file.extension.length - 1); file.browseForOpen("Get texture file", [new FileFilter("Miracle texture format", _fileName + ".mtf")] ); file.addEventListener(Event.SELECT, this.animationSelected); file.addEventListener(Event.CANCEL, this.animationSelected); } private function readTexture(file:File):void { _texture = new ByteArray(); var fileStream:FileStream = new FileStream(); fileStream.open(file, FileMode.READ); fileStream.readBytes(_texture); fileStream.close(); } public function startBtnHandler(event:Event):void{ _startBtn.visible = false; getAnimation(); } private function animationSelected(event:Event):void { if(event.type == Event.CANCEL) { this.clear(); _startBtn.visible = true; }else { if(_animation == null) { this.readAnimation(event.target as File); this.getTexture(event.target as File); }else { this.readTexture(event.target as File); trace("All loaded"); Miracle.start(this.stage, this.startHandler, true); } } } private function selectAnimationHandler(event:Event):void { if(_instance != null) { Miracle.scene.removeInstance(_instance); } var selected:String = _list.selectedItem as String; var dot:int = selected.lastIndexOf("."); var animation:String = selected.substr(dot+1); var mesh:String = selected.substr(0, dot); _instance = Miracle.scene.createAnimation(mesh, animation, 30); _instance.x = this.stage.stageWidth >> 1; _instance.y = this.stage.stageHeight >> 1; _instance.visible = true; } //} endregion EVENTS HANDLERS ================================================== //============================================================================== //{region GETTERS/SETTERS //} endregion GETTERS/SETTERS ================================================== } }
Fix viewer
Fix viewer
ActionScript
mit
MerlinDS/miracle_tool
d54fb8c4700b0eeb3ea3ed31b19708648bdd3e96
src/com/merlinds/miracle_tool/viewer/ViewerView.as
src/com/merlinds/miracle_tool/viewer/ViewerView.as
/** * User: MerlinDS * Date: 18.07.2014 * Time: 17:42 */ package com.merlinds.miracle_tool.viewer { import com.bit101.components.List; import com.bit101.components.Window; import com.merlinds.debug.log; import com.merlinds.miracle.Miracle; import com.merlinds.miracle.animations.AnimationHelper; import com.merlinds.miracle.display.MiracleAnimation; import com.merlinds.miracle.display.MiracleDisplayObject; import com.merlinds.miracle.geom.Color; import com.merlinds.miracle.utils.Asset; import com.merlinds.miracle.utils.MafReader; import com.merlinds.miracle_tool.models.AppModel; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; import flash.utils.setTimeout; [SWF(backgroundColor="0x333333", frameRate=60)] public class ViewerView extends Sprite { private var _model:AppModel; private var _assets:Vector.<Asset>; private var _window:Window; private var _name:String; private var _current:MiracleAnimation; public function ViewerView(model:AppModel = null) { super(); _model = model; if(_model == null){ _model = new AppModel(); } this.addEventListener(Event.ADDED_TO_STAGE, this.initialize); } //============================================================================== //{region PUBLIC METHODS //} endregion PUBLIC METHODS =================================================== //============================================================================== //{region PRIVATE\PROTECTED METHODS private function initialize(event:Event):void { this.removeEventListener(event.type, this.initialize); this.stage.scaleMode = StageScaleMode.NO_SCALE; this.stage.align = StageAlign.TOP_LEFT; Miracle.start(this.stage, this.createHandler, true); } private function choseAnimation():void { //find animation asset and add all of animations to chose list var n:int = _assets.length; for(var i:int = 0; i < n; i++){ var asset:Asset = _assets[i]; if(asset.type == Asset.TIMELINE_TYPE){ //parse output _window = new Window(this, 0, 0, "Chose animation"); var list:List = new List(_window, 0, 0, this.getAnimations(asset.output)); _window.x = this.stage.stageWidth - _window.width; _window.setSize(_window.height, list.height + 20); list.addEventListener(Event.SELECT, this.selectAnimationHandler); } } var w2:Window = new Window(this, _window.x, _window.y + _window.height + 10, "FPS"); list = new List(w2, 0, 0, [1, 5, 16, 24, 30, 35, 40, 60]); w2.height = 120; list.addEventListener(Event.SELECT, this.selectFpsHandler); } [Inline] private function getAnimations(bytes:ByteArray):Array { var result:Array = []; var reader:MafReader = new MafReader(); reader.execute(bytes, 1); var animations:Vector.<AnimationHelper> = reader.animations; for each(var animation:AnimationHelper in animations){ result.push(animation.name); } return result; } //} endregion PRIVATE\PROTECTED METHODS ======================================== //============================================================================== //{region EVENTS HANDLERS private function createHandler(animation:Boolean = false):void { //\TODO: Show view if it exit if(animation || _model.viewerInput == null){ _model.viewerInput = _model.lastFileDirection; _model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler); _model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite" + "file that you want to view"); } } private function selectFileHandler(event:Event):void { _model.viewerInput.removeEventListener(event.type, this.selectFileHandler); _model.lastFileDirection = _model.viewerInput.parent; var byteArray:ByteArray = new ByteArray(); var stream:FileStream = new FileStream(); stream.open(_model.viewerInput, FileMode.READ); stream.readBytes(byteArray); stream.close(); //parse if(_assets == null)_assets = new <Asset>[]; var asset:Asset = new Asset(_model.viewerInput.name, byteArray); if(asset.type == Asset.TIMELINE_TYPE){ _name = asset.name; } _assets.push(asset); if(_assets.length > 1){ this.choseAnimation(); Miracle.createScene(_assets,null, 1); Miracle.resume(); }else{ this.createHandler(true); } } private function selectAnimationHandler(event:Event):void { var list:List = event.target as List; //add animation to miracle var animation:String = list.selectedItem.toString(); log(this, "selectAnimationHandler", animation); var mesh:String = animation.substr(0, animation.lastIndexOf(".")); animation = animation.substr(animation.lastIndexOf(".") + 1); if(_current == null){ _current = Miracle.currentScene.createAnimation(mesh, animation, 60); _current.moveTO(this.stage.stageWidth >> 1, this.stage.stageHeight >> 1); _current.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage); }else{ _current.mesh = mesh; _current.animation = animation; _current.play(); } } private function imageAddedToStage(event:Event):void { trace("Added to stage"); } private function selectFpsHandler(event:Event):void { var list:List = event.target as List; //add animation to miracle if(_current != null){ _current.fps = int(list.selectedItem); } } //} endregion EVENTS HANDLERS ================================================== //============================================================================== //{region GETTERS/SETTERS //} endregion GETTERS/SETTERS ================================================== } }
/** * User: MerlinDS * Date: 18.07.2014 * Time: 17:42 */ package com.merlinds.miracle_tool.viewer { import com.bit101.components.List; import com.bit101.components.Window; import com.merlinds.debug.log; import com.merlinds.miracle.Miracle; import com.merlinds.miracle.animations.AnimationHelper; import com.merlinds.miracle.display.MiracleAnimation; import com.merlinds.miracle.display.MiracleDisplayObject; import com.merlinds.miracle.geom.Color; import com.merlinds.miracle.utils.Asset; import com.merlinds.miracle.utils.MafReader; import com.merlinds.miracle_tool.models.AppModel; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; import flash.utils.setTimeout; [SWF(backgroundColor="0x333333", frameRate=60)] public class ViewerView extends Sprite { private var _model:AppModel; private var _assets:Vector.<Asset>; private var _window:Window; private var _name:String; private var _current:MiracleAnimation; public function ViewerView(model:AppModel = null) { super(); _model = model; if(_model == null){ _model = new AppModel(); } this.addEventListener(Event.ADDED_TO_STAGE, this.initialize); } //============================================================================== //{region PUBLIC METHODS //} endregion PUBLIC METHODS =================================================== //============================================================================== //{region PRIVATE\PROTECTED METHODS private function initialize(event:Event):void { this.removeEventListener(event.type, this.initialize); this.stage.scaleMode = StageScaleMode.NO_SCALE; this.stage.align = StageAlign.TOP_LEFT; Miracle.start(this.stage, this.createHandler, true); } private function choseAnimation():void { //find animation asset and add all of animations to chose list var n:int = _assets.length; for(var i:int = 0; i < n; i++){ var asset:Asset = _assets[i]; if(asset.type == Asset.TIMELINE_TYPE){ //parse output _window = new Window(this, 0, 0, "Chose animation"); var list:List = new List(_window, 0, 0, this.getAnimations(asset.output)); _window.x = this.stage.stageWidth - _window.width; _window.setSize(_window.height, list.height + 20); list.addEventListener(Event.SELECT, this.selectAnimationHandler); } } var w2:Window = new Window(this, _window.x, _window.y + _window.height + 10, "FPS"); list = new List(w2, 0, 0, [1, 5, 16, 24, 30, 35, 40, 60]); w2.height = 120; list.addEventListener(Event.SELECT, this.selectFpsHandler); } [Inline] private function getAnimations(bytes:ByteArray):Array { var result:Array = []; var reader:MafReader = new MafReader(); reader.execute(bytes, 1); var animations:Vector.<AnimationHelper> = reader.animations; for each(var animation:AnimationHelper in animations){ result.push(animation.name); } return result; } //} endregion PRIVATE\PROTECTED METHODS ======================================== //============================================================================== //{region EVENTS HANDLERS private function createHandler(animation:Boolean = false):void { //\TODO: Show view if it exit if(animation || _model.viewerInput == null){ _model.viewerInput = _model.lastFileDirection; _model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler); _model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite" + "file that you want to view"); } } private function selectFileHandler(event:Event):void { _model.viewerInput.removeEventListener(event.type, this.selectFileHandler); _model.lastFileDirection = _model.viewerInput.parent; var byteArray:ByteArray = new ByteArray(); var stream:FileStream = new FileStream(); stream.open(_model.viewerInput, FileMode.READ); stream.readBytes(byteArray); stream.close(); //parse if(_assets == null)_assets = new <Asset>[]; var asset:Asset = new Asset(_model.viewerInput.name, byteArray); if(asset.type == Asset.TIMELINE_TYPE){ _name = asset.name; } _assets.push(asset); if(_assets.length > 1){ this.choseAnimation(); Miracle.createScene(_assets,null, 1); Miracle.resume(); }else{ this.createHandler(true); } } private function selectAnimationHandler(event:Event):void { var list:List = event.target as List; //add animation to miracle var animation:String = list.selectedItem.toString(); log(this, "selectAnimationHandler", animation); var mesh:String = animation.substr(0, animation.lastIndexOf(".")); animation = animation.substr(animation.lastIndexOf(".") + 1); if(_current == null){ _current = Miracle.scene.createAnimation(mesh, animation, 60); _current.moveTO(this.stage.stageWidth >> 1, this.stage.stageHeight >> 1); _current.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage); }else{ _current.mesh = mesh; _current.animation = animation; _current.play(); } } private function imageAddedToStage(event:Event):void { trace("Added to stage"); } private function selectFpsHandler(event:Event):void { var list:List = event.target as List; //add animation to miracle if(_current != null){ _current.fps = int(list.selectedItem); } } //} endregion EVENTS HANDLERS ================================================== //============================================================================== //{region GETTERS/SETTERS //} endregion GETTERS/SETTERS ================================================== } }
rename currentScene to scene
rename currentScene to scene
ActionScript
mit
MerlinDS/miracle_tool
faa885add0a8557a3a4d157eaccc4adc8e3cd470
WeaveUI/src/weave/visualization/tools/ExternalTool.as
WeaveUI/src/weave/visualization/tools/ExternalTool.as
/* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Weave. If not, see <http://www.gnu.org/licenses/>. */ package weave.visualization.tools { import weave.api.WeaveAPI; import weave.compiler.Compiler; import weave.core.LinkableHashMap; import weave.core.LinkableString; public class ExternalTool extends LinkableHashMap { private var toolUrl:LinkableString; private var toolPath:Array; private var windowName:String; public function ExternalTool() { toolUrl = requestObject("toolUrl", LinkableString, true); toolUrl.addGroupedCallback(this, toolPropertiesChanged); } private function toolPropertiesChanged():void { if (toolUrl.value != "") { launch(); } } public function launch():void { if (toolPath == null) { toolPath = WeaveAPI.SessionManager.getPath(WeaveAPI.globalHashMap, this); windowName = Compiler.stringify(toolPath); } WeaveAPI.executeJavaScript( { windowName: windowName, toolPath: toolPath, url: toolUrl.value, features: "menubar=no,status=no,toolbar=no" }, "if (!weave.external_tools) weave.external_tools = {};\ weave.external_tools[windowName] = window.open(url, windowName, features);\ weave.external_tools[windowName].toolPath = toolPath;\ weave.external_tools[windowName].weave = weave;" ); } override public function dispose():void { super.dispose(); WeaveAPI.executeJavaScript( {windowName: windowName}, "if (weave.external_tools && weave.external_tools[windowName])\ weave.external_tools[windowName].close();" ); } } }
/* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Weave. If not, see <http://www.gnu.org/licenses/>. */ package weave.visualization.tools { import weave.api.WeaveAPI; import weave.compiler.Compiler; import weave.core.LinkableHashMap; import weave.core.LinkableString; public class ExternalTool extends LinkableHashMap { private var toolUrl:LinkableString; private var toolPath:Array; private var windowName:String; public function ExternalTool() { toolUrl = requestObject("toolUrl", LinkableString, true); toolUrl.addImmediateCallback(this, toolPropertiesChanged); } private function toolPropertiesChanged():void { if (toolUrl.value != "") { launch(); } } public function launch():void { if (toolPath == null) { toolPath = WeaveAPI.SessionManager.getPath(WeaveAPI.globalHashMap, this); windowName = Compiler.stringify(toolPath); } WeaveAPI.executeJavaScript( { windowName: windowName, toolPath: toolPath, url: toolUrl.value, features: "menubar=no,status=no,toolbar=no" }, "if (!weave.external_tools) weave.external_tools = {};", "weave.external_tools[windowName] = window.open(url, windowName, features);", "console.log(toolPath);", "weave.external_tools[windowName].toolPath = toolPath;", "weave.external_tools[windowName].weave = weave;" ); } override public function dispose():void { super.dispose(); WeaveAPI.executeJavaScript( {windowName: windowName}, "if (weave.external_tools && weave.external_tools[windowName])\ weave.external_tools[windowName].close();" ); } } }
Switch to immediate callback for toolPropertiesChanged
ExternalTool: Switch to immediate callback for toolPropertiesChanged
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
d407ace801f3843a9a01acd7da96fbed75dcb93e
src/com/mangui/HLS/streaming/ManifestLoader.as
src/com/mangui/HLS/streaming/ManifestLoader.as
package com.mangui.HLS.streaming { import com.mangui.HLS.*; import com.mangui.HLS.parsing.*; import com.mangui.HLS.utils.*; import flash.events.*; import flash.net.*; import flash.utils.*; /** Loader for hls manifests. **/ public class ManifestLoader { /** Reference to the hls framework controller. **/ private var _hls:HLS; /** Array with levels. **/ private var _levels:Array = []; /** Object that fetches the manifest. **/ private var _urlloader:URLLoader; /** Link to the M3U8 file. **/ private var _url:String; /** Amount of playlists still need loading. **/ private var _toLoad:Number; /** are all playlists filled ? **/ private var _canStart:Boolean; /** initial reload timer **/ private var _fragmentDuration:Number = 5000; /** Timeout ID for reloading live playlists. **/ private var _timeoutID:Number; /** Streaming type (live, ondemand). **/ private var _type:String; /** last reload manifest time **/ private var _reload_playlists_timer:uint; /** Setup the loader. **/ public function ManifestLoader(hls:HLS) { _hls = hls; _hls.addEventListener(HLSEvent.STATE,_stateHandler); _levels = []; _urlloader = new URLLoader(); _urlloader.addEventListener(Event.COMPLETE,_loaderHandler); _urlloader.addEventListener(IOErrorEvent.IO_ERROR,_errorHandler); _urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,_errorHandler); }; /** Loading failed; return errors. **/ private function _errorHandler(event:ErrorEvent):void { var txt:String = "Cannot load M3U8: "+event.text; if(event is SecurityErrorEvent) { txt = "Cannot load M3U8: crossdomain access denied"; } else if (event is IOErrorEvent) { txt = "Cannot load M3U8: 404 not found"; } _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,txt)); }; /** return true if first two levels contain at least 2 fragments **/ private function _areFirstLevelsFilled():Boolean { for(var i:Number = 0; (i < _levels.length) && (i < 2); i++) { if(_levels[i].fragments.length < 2) { return false; } } return true; }; /** Return the current manifest. **/ public function getLevels():Array { return _levels; }; /** Return the stream type. **/ public function getType():String { return _type; }; /** Load the manifest file. **/ public function load(url:String):void { _url = url; _levels = []; _canStart = false; _reload_playlists_timer = getTimer(); _urlloader.load(new URLRequest(_url)); }; /** Manifest loaded; check and parse it **/ private function _loaderHandler(event:Event):void { _loadManifest(String(event.target.data)); }; /** load a playlist **/ private function _loadPlaylist(string:String,url:String,index:Number):void { if(string != null && string.length != 0) { var frags:Array = Manifest.getFragments(string,url); // set fragment and update sequence number range _levels[index].setFragments(frags); _levels[index].targetduration = Manifest.getTargetDuration(string); _levels[index].start_seqnum = frags[0].seqnum; _levels[index].end_seqnum = frags[frags.length-1].seqnum; _levels[index].duration = frags[frags.length-1].start + frags[frags.length-1].duration; _fragmentDuration = _levels[index].duration/frags.length; _levels[index].averageduration = _fragmentDuration; } if(--_toLoad == 0) { // Check whether the stream is live or not finished yet if(Manifest.hasEndlist(string)) { _type = HLSTypes.VOD; } else { _type = HLSTypes.LIVE; var timeout:Number = Math.max(100,_reload_playlists_timer + _fragmentDuration - getTimer()); Log.txt("Live Playlist parsing finished: reload in " + timeout + " ms"); _timeoutID = setTimeout(_loadPlaylists,timeout); } if (!_canStart && (_canStart =_areFirstLevelsFilled())) { Log.txt("first 2 levels are filled with at least 2 fragments, notify event"); _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST,_levels)); } } }; /** load First Level Playlist **/ private function _loadManifest(string:String):void { // Check for M3U8 playlist or manifest. if(string.indexOf(Manifest.HEADER) == 0) { //1 level playlist, create unique level and parse playlist if(string.indexOf(Manifest.FRAGMENT) > 0) { var level:Level = new Level(); level.url = _url; _levels.push(level); _toLoad = 1; Log.txt("1 Level Playlist, load it"); _loadPlaylist(string,_url,0); } else if(string.indexOf(Manifest.LEVEL) > 0) { //adaptative playlist, extract levels from playlist, get them and parse them _levels = Manifest.extractLevels(string,_url); _loadPlaylists(); } } else { var message:String = "Manifest is not a valid M3U8 file" + _url; _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,message)); } }; /** load/reload all M3U8 playlists **/ private function _loadPlaylists():void { _reload_playlists_timer = getTimer(); _toLoad = _levels.length; //Log.txt("HLS Playlist, with " + _toLoad + " levels"); for(var i:Number = 0; i < _levels.length; i++) { new Manifest().loadPlaylist(_levels[i].url,_loadPlaylist,_errorHandler,i); } }; /** When the framework idles out, reloading is cancelled. **/ public function _stateHandler(event:HLSEvent):void { if(event.state == HLSStates.IDLE) { clearTimeout(_timeoutID); } }; } }
package com.mangui.HLS.streaming { import com.mangui.HLS.*; import com.mangui.HLS.parsing.*; import com.mangui.HLS.utils.*; import flash.events.*; import flash.net.*; import flash.utils.*; /** Loader for hls manifests. **/ public class ManifestLoader { /** Reference to the hls framework controller. **/ private var _hls:HLS; /** Array with levels. **/ private var _levels:Array = []; /** Object that fetches the manifest. **/ private var _urlloader:URLLoader; /** Link to the M3U8 file. **/ private var _url:String; /** Amount of playlists still need loading. **/ private var _toLoad:Number; /** are all playlists filled ? **/ private var _canStart:Boolean; /** initial reload timer **/ private var _fragmentDuration:Number = 5000; /** Timeout ID for reloading live playlists. **/ private var _timeoutID:Number; /** Streaming type (live, ondemand). **/ private var _type:String; /** last reload manifest time **/ private var _reload_playlists_timer:uint; /** Setup the loader. **/ public function ManifestLoader(hls:HLS) { _hls = hls; _hls.addEventListener(HLSEvent.STATE,_stateHandler); _levels = []; _urlloader = new URLLoader(); _urlloader.addEventListener(Event.COMPLETE,_loaderHandler); _urlloader.addEventListener(IOErrorEvent.IO_ERROR,_errorHandler); _urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,_errorHandler); }; /** Loading failed; return errors. **/ private function _errorHandler(event:ErrorEvent):void { var txt:String = "Cannot load M3U8: "+event.text; if(event is SecurityErrorEvent) { txt = "Cannot load M3U8: crossdomain access denied"; } else if (event is IOErrorEvent) { txt = "Cannot load M3U8: 404 not found"; } _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,txt)); }; /** return true if first two levels contain at least 2 fragments **/ private function _areFirstLevelsFilled():Boolean { for(var i:Number = 0; (i < _levels.length) && (i < 2); i++) { if(_levels[i].fragments.length < 2) { return false; } } return true; }; /** Return the current manifest. **/ public function getLevels():Array { return _levels; }; /** Return the stream type. **/ public function getType():String { return _type; }; /** Load the manifest file. **/ public function load(url:String):void { _url = url; _levels = []; _canStart = false; _reload_playlists_timer = getTimer(); _urlloader.load(new URLRequest(_url)); }; /** Manifest loaded; check and parse it **/ private function _loaderHandler(event:Event):void { _loadManifest(String(event.target.data)); }; /** load a playlist **/ private function _loadPlaylist(string:String,url:String,index:Number):void { if(string != null && string.length != 0) { var frags:Array = Manifest.getFragments(string,url); // set fragment and update sequence number range _levels[index].setFragments(frags); _levels[index].targetduration = Manifest.getTargetDuration(string); _levels[index].start_seqnum = frags[0].seqnum; _levels[index].end_seqnum = frags[frags.length-1].seqnum; _levels[index].duration = frags[frags.length-1].start + frags[frags.length-1].duration; _fragmentDuration = _levels[index].duration/frags.length; _levels[index].averageduration = _fragmentDuration; } if(--_toLoad == 0) { // Check whether the stream is live or not finished yet if(Manifest.hasEndlist(string)) { _type = HLSTypes.VOD; } else { _type = HLSTypes.LIVE; var timeout:Number = Math.max(100,_reload_playlists_timer + 1000*_fragmentDuration - getTimer()); Log.txt("Live Playlist parsing finished: reload in " + timeout + " ms"); _timeoutID = setTimeout(_loadPlaylists,timeout); } if (!_canStart && (_canStart =_areFirstLevelsFilled())) { Log.txt("first 2 levels are filled with at least 2 fragments, notify event"); _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST,_levels)); } } }; /** load First Level Playlist **/ private function _loadManifest(string:String):void { // Check for M3U8 playlist or manifest. if(string.indexOf(Manifest.HEADER) == 0) { //1 level playlist, create unique level and parse playlist if(string.indexOf(Manifest.FRAGMENT) > 0) { var level:Level = new Level(); level.url = _url; _levels.push(level); _toLoad = 1; Log.txt("1 Level Playlist, load it"); _loadPlaylist(string,_url,0); } else if(string.indexOf(Manifest.LEVEL) > 0) { //adaptative playlist, extract levels from playlist, get them and parse them _levels = Manifest.extractLevels(string,_url); _loadPlaylists(); } } else { var message:String = "Manifest is not a valid M3U8 file" + _url; _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,message)); } }; /** load/reload all M3U8 playlists **/ private function _loadPlaylists():void { _reload_playlists_timer = getTimer(); _toLoad = _levels.length; //Log.txt("HLS Playlist, with " + _toLoad + " levels"); for(var i:Number = 0; i < _levels.length; i++) { new Manifest().loadPlaylist(_levels[i].url,_loadPlaylist,_errorHandler,i); } }; /** When the framework idles out, reloading is cancelled. **/ public function _stateHandler(event:HLSEvent):void { if(event.state == HLSStates.IDLE) { clearTimeout(_timeoutID); } }; } }
fix reload timer too small
fix reload timer too small
ActionScript
mpl-2.0
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
65a887817fb425dc899602dbd470b6457fcef06f
actionscript/src/com/freshplanet/ane/AirInAppPurchase/InAppPurchase.as
actionscript/src/com/freshplanet/ane/AirInAppPurchase/InAppPurchase.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.AirInAppPurchase { import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class InAppPurchase extends EventDispatcher { private var _context:ExtensionContext = null; private var _iosPendingPurchases:Vector.<Object> = new Vector.<Object>(); private static const EXTENSION_ID:String = "com.freshplanet.AirInAppPurchase"; private static var _instance:InAppPurchase = null; public function InAppPurchase(lock:SingletonLock) { if (!isSupported) return; _context = ExtensionContext.createExtensionContext(EXTENSION_ID, null); if (!_context) throw Error("Extension context is null. Please check if extension.xml is setup correctly."); _context.addEventListener(StatusEvent.STATUS, _onStatus); } public static function get instance():InAppPurchase { if (!_instance) _instance = new InAppPurchase(new SingletonLock()); return _instance; } public static function get isSupported():Boolean { return _isIOS() || _isAndroid(); } private static function _isIOS():Boolean { return Capabilities.manufacturer.indexOf("iOS") > -1; } private static function _isAndroid():Boolean { return Capabilities.manufacturer.indexOf("Android") > -1; } /** * INIT_SUCCESSFUL * INIT_ERROR * @param googlePlayKey * @param debug */ public function init(googlePlayKey:String, debug:Boolean = false):void { if (!isSupported) return; trace("[InAppPurchase] init library"); _context.call("initLib", googlePlayKey, debug); } /** * PURCHASE_SUCCESSFUL * PURCHASE_ERROR * @param productId */ public function makePurchase(productId:String):void { if (!isSupported) { _dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported"); return; } trace("[InAppPurchase] purchasing", productId); _context.call("makePurchase", productId); } /** * PURCHASE_SUCCESSFUL * PURCHASE_ERROR * @param productId */ public function makeSubscription(productId:String):void { if (_isAndroid()) { trace("[InAppPurchase] check user can make a subscription"); _context.call("makeSubscription", productId); } else { _dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "subscriptions not supported"); } } /** * CONSUME_SUCCESSFUL * CONSUME_ERROR * @param productId * @param receipt */ public function removePurchaseFromQueue(productId:String, receipt:String):void { if (!isSupported) return; trace("[InAppPurchase] removing product from queue", productId, receipt); _context.call("removePurchaseFromQueue", productId, receipt); if (Capabilities.manufacturer.indexOf("iOS") > -1) { var filterPurchase:Function = function(jsonPurchase:String, index:int, purchases:Vector.<Object>):Boolean { try { var purchase:Object = JSON.parse(jsonPurchase); return JSON.stringify(purchase.receipt) != receipt; } catch (error:Error) { trace("[InAppPurchase] Couldn't parse purchase: " + jsonPurchase); } return false; }; _iosPendingPurchases = _iosPendingPurchases.filter(filterPurchase); } } /** * PRODUCT_INFO_RECEIVED * PRODUCT_INFO_ERROR * @param productsId * @param subscriptionIds */ public function getProductsInfo(productsId:Array, subscriptionIds:Array):void { if (!isSupported) { _dispatchEvent(InAppPurchaseEvent.PRODUCT_INFO_ERROR, "InAppPurchase not supported"); return; } trace("[InAppPurchase] get Products Info"); if(!productsId) productsId = []; if(!subscriptionIds) subscriptionIds = []; _context.call("getProductsInfo", productsId, subscriptionIds); } /** * RESTORE_INFO_RECEIVED * RESTORE_INFO_ERROR */ public function restoreTransactions():void { if (_isAndroid()) _context.call("restoreTransaction"); else if (_isIOS()) { var jsonPurchases:String = "[" + _iosPendingPurchases.join(",") + "]"; var jsonData:String = "{ \"purchases\": " + jsonPurchases + "}"; _dispatchEvent(InAppPurchaseEvent.RESTORE_INFO_RECEIVED, jsonData); } } /** * * @param type * @param eventData */ private function _dispatchEvent(type:String, eventData:String):void { this.dispatchEvent(new InAppPurchaseEvent(type, eventData)) } /** * * @param event */ private function _onStatus(event:StatusEvent):void { trace(event); if (event.code == InAppPurchaseEvent.PURCHASE_SUCCESSFUL && _isIOS()) _iosPendingPurchases.push(event.level); _dispatchEvent(event.code, event.level); } } } class SingletonLock {}
////////////////////////////////////////////////////////////////////////////////////// // // 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.AirInAppPurchase { import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class InAppPurchase extends EventDispatcher { private var _context:ExtensionContext = null; private var _iosPendingPurchases:Vector.<Object> = new Vector.<Object>(); private static const EXTENSION_ID:String = "com.freshplanet.AirInAppPurchase"; private static var _instance:InAppPurchase = null; public function InAppPurchase(lock:SingletonLock) { if (!isSupported) return; _context = ExtensionContext.createExtensionContext(EXTENSION_ID, null); if (!_context) throw Error("Extension context is null. Please check if extension.xml is setup correctly."); _context.addEventListener(StatusEvent.STATUS, _onStatus); } public static function get instance():InAppPurchase { if (!_instance) _instance = new InAppPurchase(new SingletonLock()); return _instance; } public static function get isSupported():Boolean { return _isIOS() || _isAndroid(); } private static function _isIOS():Boolean { return Capabilities.manufacturer.indexOf("iOS") > -1; } private static function _isAndroid():Boolean { return Capabilities.manufacturer.indexOf("Android") > -1; } /** * INIT_SUCCESSFUL * INIT_ERROR * @param googlePlayKey * @param debug */ public function init(googlePlayKey:String, debug:Boolean = false):void { if (!isSupported) return; trace("[InAppPurchase] init library"); _context.call("initLib", googlePlayKey, debug); } /** * PURCHASE_SUCCESSFUL * PURCHASE_ERROR * @param productId */ public function makePurchase(productId:String):void { if (!isSupported) { _dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported"); return; } trace("[InAppPurchase] purchasing", productId); _context.call("makePurchase", productId); } /** * PURCHASE_SUCCESSFUL * PURCHASE_ERROR * @param productId */ public function makeSubscription(productId:String):void { _context.call("makeSubscription", productId); /* if (_isAndroid()) { trace("[InAppPurchase] check user can make a subscription"); _context.call("makeSubscription", productId); } else { _dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "subscriptions not supported"); } */ } /** * CONSUME_SUCCESSFUL * CONSUME_ERROR * @param productId * @param receipt */ public function removePurchaseFromQueue(productId:String, receipt:String):void { if (!isSupported) return; trace("[InAppPurchase] removing product from queue", productId, receipt); _context.call("removePurchaseFromQueue", productId, receipt); if (Capabilities.manufacturer.indexOf("iOS") > -1) { var filterPurchase:Function = function(jsonPurchase:String, index:int, purchases:Vector.<Object>):Boolean { try { var purchase:Object = JSON.parse(jsonPurchase); return JSON.stringify(purchase.receipt) != receipt; } catch (error:Error) { trace("[InAppPurchase] Couldn't parse purchase: " + jsonPurchase); } return false; }; _iosPendingPurchases = _iosPendingPurchases.filter(filterPurchase); } } /** * PRODUCT_INFO_RECEIVED * PRODUCT_INFO_ERROR * @param productsId * @param subscriptionIds */ public function getProductsInfo(productsId:Array, subscriptionIds:Array):void { if (!isSupported) { _dispatchEvent(InAppPurchaseEvent.PRODUCT_INFO_ERROR, "InAppPurchase not supported"); return; } trace("[InAppPurchase] get Products Info"); _context.call("getProductsInfo", productsId, subscriptionIds); } /** * RESTORE_INFO_RECEIVED * RESTORE_INFO_ERROR */ public function restoreTransactions():void { if (_isAndroid()) _context.call("restoreTransaction"); else if (_isIOS()) { var jsonPurchases:String = "[" + _iosPendingPurchases.join(",") + "]"; var jsonData:String = "{ \"purchases\": " + jsonPurchases + "}"; _dispatchEvent(InAppPurchaseEvent.RESTORE_INFO_RECEIVED, jsonData); } } /** * * @param type * @param eventData */ private function _dispatchEvent(type:String, eventData:String):void { this.dispatchEvent(new InAppPurchaseEvent(type, eventData)) } /** * * @param event */ private function _onStatus(event:StatusEvent):void { trace(event); if (event.code == InAppPurchaseEvent.PURCHASE_SUCCESSFUL && _isIOS()) _iosPendingPurchases.push(event.level); _dispatchEvent(event.code, event.level); } } } class SingletonLock {}
allow subscriptions for ios
allow subscriptions for ios
ActionScript
apache-2.0
freshplanet/ANE-In-App-Purchase,freshplanet/ANE-In-App-Purchase,freshplanet/ANE-In-App-Purchase
e1511d0de6715fe6382bc8e2a775258e04f60e69
src/org/mangui/HLS/streaming/ManifestLoader.as
src/org/mangui/HLS/streaming/ManifestLoader.as
package org.mangui.HLS.streaming { import org.mangui.HLS.*; import org.mangui.HLS.parsing.*; import org.mangui.HLS.utils.*; import flash.events.*; import flash.net.*; import flash.utils.*; /** Loader for hls manifests. **/ public class ManifestLoader { /** Reference to the hls framework controller. **/ private var _hls : HLS; /** levels vector. **/ private var _levels : Vector.<Level>; /** Object that fetches the manifest. **/ private var _urlloader : URLLoader; /** Link to the M3U8 file. **/ private var _url : String; /** are all playlists filled ? **/ private var _canStart : Boolean; /** Timeout ID for reloading live playlists. **/ private var _timeoutID : Number; /** Streaming type (live, ondemand). **/ private var _type : String; /** last reload manifest time **/ private var _reload_playlists_timer : uint; /** current level **/ private var _current_level : Number; /** current level **/ private var _load_in_progress : Boolean = false; /** flush live URL cache **/ private var _flushLiveURLCache : Boolean = false; /** Setup the loader. **/ public function ManifestLoader(hls : HLS) { _hls = hls; _hls.addEventListener(HLSEvent.STATE, _stateHandler); _hls.addEventListener(HLSEvent.QUALITY_SWITCH, _levelSwitchHandler); _levels = new Vector.<Level>(); _urlloader = new URLLoader(); _urlloader.addEventListener(Event.COMPLETE, _loaderHandler); _urlloader.addEventListener(IOErrorEvent.IO_ERROR, _errorHandler); _urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler); }; /** Loading failed; return errors. **/ private function _errorHandler(event : ErrorEvent) : void { var txt : String; if (event is SecurityErrorEvent) { var error : SecurityErrorEvent = event as SecurityErrorEvent; txt = "Cannot load M3U8: crossdomain access denied:" + error.text; } else if (event is IOErrorEvent && _levels.length) { Log.warn("I/O Error while trying to load Playlist, retry in 2s"); _timeoutID = setTimeout(_loadActiveLevelPlaylist, 2000); } else { txt = "Cannot load M3U8: " + event.text; } _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, txt)); }; /** Return the current manifest. **/ public function get levels() : Vector.<Level> { return _levels; }; /** Return the stream type. **/ public function get type() : String { return _type; }; /** Load the manifest file. **/ public function load(url : String) : void { _url = url; _levels = new Vector.<Level>(); _current_level = 0; _canStart = false; _reload_playlists_timer = getTimer(); _urlloader.load(new URLRequest(url)); }; /** Manifest loaded; check and parse it **/ private function _loaderHandler(event : Event) : void { var loader : URLLoader = URLLoader(event.target); _parseManifest(String(loader.data)); }; /** parse a playlist **/ private function _parseLevelPlaylist(string : String, url : String, index : Number) : void { if (string != null && string.length != 0) { Log.debug("level " + index + " playlist:\n" + string); var frags : Vector.<Fragment> = Manifest.getFragments(string, url); // set fragment and update sequence number range _levels[index].updateFragments(frags); _levels[index].targetduration = Manifest.getTargetDuration(string); _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYLIST_DURATION_UPDATED, _levels[index].duration)); } // Check whether the stream is live or not finished yet if (Manifest.hasEndlist(string)) { _type = HLSTypes.VOD; } else { _type = HLSTypes.LIVE; var timeout : Number = Math.max(100, _reload_playlists_timer + 1000 * _levels[index].averageduration - getTimer()); Log.debug("Level " + index + " Live Playlist parsing finished: reload in " + timeout.toFixed(0) + " ms"); _timeoutID = setTimeout(_loadActiveLevelPlaylist, timeout); } if (!_canStart) { _canStart = (_levels[index].fragments.length > 0); if (_canStart) { Log.debug("first level filled with at least 1 fragment, notify event"); _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADED, _levels)); } } _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_UPDATED, index)); _load_in_progress = false; }; /** Parse First Level Playlist **/ private function _parseManifest(string : String) : void { // Check for M3U8 playlist or manifest. if (string.indexOf(Manifest.HEADER) == 0) { // 1 level playlist, create unique level and parse playlist if (string.indexOf(Manifest.FRAGMENT) > 0) { var level : Level = new Level(); level.url = _url; _levels.push(level); Log.debug("1 Level Playlist, load it"); _parseLevelPlaylist(string, _url, 0); } else if (string.indexOf(Manifest.LEVEL) > 0) { Log.debug("adaptive playlist:\n" + string); // adaptative playlist, extract levels from playlist, get them and parse them _levels = Manifest.extractLevels(string, _url); _loadActiveLevelPlaylist(); if (string.indexOf(Manifest.ALTERNATE_AUDIO) > 0) { Log.debug("alternate audio level found"); // parse alternate audio tracks var altAudiolevels : Vector.<AltAudioTrack> = Manifest.extractAltAudioTracks(string, _url); _hls.dispatchEvent(new HLSEvent(HLSEvent.ALT_AUDIO_TRACKS_LIST_CHANGE, altAudiolevels)); } } } else { var message : String = "Manifest is not a valid M3U8 file" + _url; _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, message)); } }; /** load/reload active M3U8 playlist **/ private function _loadActiveLevelPlaylist() : void { _load_in_progress = true; _reload_playlists_timer = getTimer(); // load active M3U8 playlist only new Manifest().loadPlaylist(_levels[_current_level].url, _parseLevelPlaylist, _errorHandler, _current_level, _type, _flushLiveURLCache); }; /** When level switch occurs, assess the need of (re)loading new level playlist **/ public function _levelSwitchHandler(event : HLSEvent) : void { if (_current_level != event.level) { _current_level = event.level; Log.debug("switch to level " + _current_level); if (_type == HLSTypes.LIVE || _levels[_current_level].fragments.length == 0) { Log.debug("(re)load Playlist"); clearTimeout(_timeoutID); _timeoutID = setTimeout(_loadActiveLevelPlaylist, 0); } } }; /** When the framework idles out, reloading is cancelled. **/ public function _stateHandler(event : HLSEvent) : void { if (event.state == HLSStates.IDLE) { clearTimeout(_timeoutID); } }; public function set flushLiveURLCache(val : Boolean) : void { _flushLiveURLCache = val; } public function get flushLiveURLCache() : Boolean { return _flushLiveURLCache; } } }
package org.mangui.HLS.streaming { import org.mangui.HLS.*; import org.mangui.HLS.parsing.*; import org.mangui.HLS.utils.*; import flash.events.*; import flash.net.*; import flash.utils.*; /** Loader for hls manifests. **/ public class ManifestLoader { /** Reference to the hls framework controller. **/ private var _hls : HLS; /** levels vector. **/ private var _levels : Vector.<Level>; /** Object that fetches the manifest. **/ private var _urlloader : URLLoader; /** Link to the M3U8 file. **/ private var _url : String; /** are all playlists filled ? **/ private var _canStart : Boolean; /** Timeout ID for reloading live playlists. **/ private var _timeoutID : Number; /** Streaming type (live, ondemand). **/ private var _type : String; /** last reload manifest time **/ private var _reload_playlists_timer : uint; /** current level **/ private var _current_level : Number; /** current level **/ private var _load_in_progress : Boolean = false; /** flush live URL cache **/ private var _flushLiveURLCache : Boolean = false; /** Setup the loader. **/ public function ManifestLoader(hls : HLS) { _hls = hls; _hls.addEventListener(HLSEvent.STATE, _stateHandler); _hls.addEventListener(HLSEvent.QUALITY_SWITCH, _levelSwitchHandler); _levels = new Vector.<Level>(); _urlloader = new URLLoader(); _urlloader.addEventListener(Event.COMPLETE, _loaderHandler); _urlloader.addEventListener(IOErrorEvent.IO_ERROR, _errorHandler); _urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler); }; /** Loading failed; return errors. **/ private function _errorHandler(event : ErrorEvent) : void { var txt : String; if (event is SecurityErrorEvent) { var error : SecurityErrorEvent = event as SecurityErrorEvent; txt = "Cannot load M3U8: crossdomain access denied:" + error.text; } else if (event is IOErrorEvent && _levels.length) { Log.warn("I/O Error while trying to load Playlist, retry in 2s"); _timeoutID = setTimeout(_loadActiveLevelPlaylist, 2000); } else { txt = "Cannot load M3U8: " + event.text; } _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, txt)); }; /** Return the current manifest. **/ public function get levels() : Vector.<Level> { return _levels; }; /** Return the stream type. **/ public function get type() : String { return _type; }; /** Load the manifest file. **/ public function load(url : String) : void { _url = url; _levels = new Vector.<Level>(); _current_level = 0; _canStart = false; _reload_playlists_timer = getTimer(); _urlloader.load(new URLRequest(url)); }; /** Manifest loaded; check and parse it **/ private function _loaderHandler(event : Event) : void { var loader : URLLoader = URLLoader(event.target); _parseManifest(String(loader.data)); }; /** parse a playlist **/ private function _parseLevelPlaylist(string : String, url : String, index : Number) : void { if (string != null && string.length != 0) { Log.debug("level " + index + " playlist:\n" + string); var frags : Vector.<Fragment> = Manifest.getFragments(string, url); // set fragment and update sequence number range _levels[index].updateFragments(frags); _levels[index].targetduration = Manifest.getTargetDuration(string); _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYLIST_DURATION_UPDATED, _levels[index].duration)); } // Check whether the stream is live or not finished yet if (Manifest.hasEndlist(string)) { _type = HLSTypes.VOD; } else { _type = HLSTypes.LIVE; var timeout : Number = Math.max(100, _reload_playlists_timer + 1000 * _levels[index].averageduration - getTimer()); Log.debug("Level " + index + " Live Playlist parsing finished: reload in " + timeout.toFixed(0) + " ms"); _timeoutID = setTimeout(_loadActiveLevelPlaylist, timeout); } if (!_canStart) { _canStart = (_levels[index].fragments.length > 0); if (_canStart) { Log.debug("first level filled with at least 1 fragment, notify event"); _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADED, _levels)); } } _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_UPDATED, index)); _load_in_progress = false; }; /** Parse First Level Playlist **/ private function _parseManifest(string : String) : void { // Check for M3U8 playlist or manifest. if (string.indexOf(Manifest.HEADER) == 0) { // 1 level playlist, create unique level and parse playlist if (string.indexOf(Manifest.FRAGMENT) > 0) { var level : Level = new Level(); level.url = _url; _levels.push(level); Log.debug("1 Level Playlist, load it"); _parseLevelPlaylist(string, _url, 0); } else if (string.indexOf(Manifest.LEVEL) > 0) { Log.debug("adaptive playlist:\n" + string); // adaptative playlist, extract levels from playlist, get them and parse them _levels = Manifest.extractLevels(string, _url); _loadActiveLevelPlaylist(); if (string.indexOf(Manifest.ALTERNATE_AUDIO) > 0) { Log.debug("alternate audio level found"); // parse alternate audio tracks var altAudiolevels : Vector.<AltAudioTrack> = Manifest.extractAltAudioTracks(string, _url); _hls.dispatchEvent(new HLSEvent(HLSEvent.ALT_AUDIO_TRACKS_LIST_CHANGE, altAudiolevels)); } } } else { var message : String = "Manifest is not a valid M3U8 file" + _url; _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, message)); } }; /** load/reload active M3U8 playlist **/ private function _loadActiveLevelPlaylist() : void { _load_in_progress = true; _reload_playlists_timer = getTimer(); // load active M3U8 playlist only new Manifest().loadPlaylist(_levels[_current_level].url, _parseLevelPlaylist, _errorHandler, _current_level, _type, _flushLiveURLCache); }; /** When level switch occurs, assess the need of (re)loading new level playlist **/ private function _levelSwitchHandler(event : HLSEvent) : void { if (_current_level != event.level) { _current_level = event.level; Log.debug("switch to level " + _current_level); if (_type == HLSTypes.LIVE || _levels[_current_level].fragments.length == 0) { Log.debug("(re)load Playlist"); clearTimeout(_timeoutID); _timeoutID = setTimeout(_loadActiveLevelPlaylist, 0); } } }; /** When the framework idles out, reloading is cancelled. **/ private function _stateHandler(event : HLSEvent) : void { if (event.state == HLSStates.IDLE) { clearTimeout(_timeoutID); } }; public function set flushLiveURLCache(val : Boolean) : void { _flushLiveURLCache = val; } public function get flushLiveURLCache() : Boolean { return _flushLiveURLCache; } } }
move methods to private
move methods to private
ActionScript
mpl-2.0
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
c56dea832e2936755a6299b86f7adacf23682433
src/aerys/minko/scene/node/Group.as
src/aerys/minko/scene/node/Group.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.scene.SceneIterator; import aerys.minko.type.Signal; import aerys.minko.type.Sort; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.parser.ParserOptions; import aerys.minko.type.math.Ray; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.getQualifiedClassName; use namespace minko_scene; /** * Group objects can contain other scene nodes and applies a 3D * transformation to its descendants. * * @author Jean-Marc Le Roux */ public class Group extends AbstractVisibleSceneNode { minko_scene var _children : Vector.<ISceneNode>; minko_scene var _numChildren : uint; private var _numDescendants : uint; private var _descendantAdded : Signal; private var _descendantRemoved : Signal; /** * The number of children of the Group. */ public function get numChildren() : uint { return _numChildren; } /** * The number of descendants of the Group. * * @return * */ public function get numDescendants() : uint { return _numDescendants; } /** * The signal executed when a descendant is added to the Group. * Callbacks for this signal must accept the following arguments: * <ul> * <li>newParent : Group, the Group the descendant was actually added to</li> * <li>descendant : ISceneNode, the descendant that was just added</li> * </ul> * * @return * */ public function get descendantAdded() : Signal { return _descendantAdded } /** * The signal executed when a descendant is removed from the Group. * Callbacks for this signal must accept the following arguments: * <ul> * <li>oldParent : Group, the Group the descendant was actually removed from</li> * <li>descendant : ISceneNode, the descendant that was just removed</li> * </ul> * * @return * */ public function get descendantRemoved() : Signal { return _descendantRemoved; } public function Group(...children) { super(); initializeChildren(children); } override protected function initializeSignals() : void { super.initializeSignals(); _descendantAdded = new Signal('Group.descendantAdded'); _descendantRemoved = new Signal('Group.descendantRemoved'); } override protected function initializeSignalHandlers() : void { super.initializeSignalHandlers(); _descendantAdded.add(descendantAddedHandler); _descendantRemoved.add(descendantRemovedHandler); added.add(addedHandler); removed.add(removedHandler); } protected function initializeChildren(children : Array) : void { _children = new <ISceneNode>[]; while (children.length == 1 && children[0] is Array) children = children[0]; var childrenNum : uint = children.length; for (var childrenIndex : uint = 0; childrenIndex < childrenNum; ++childrenIndex) addChild(ISceneNode(children[childrenIndex])); } private function descendantAddedHandler(group : Group, child : ISceneNode) : void { if (group == this) { var childGroup : Group = child as Group; if (childGroup) { childGroup.descendantAdded.add(_descendantAdded.execute); childGroup.descendantRemoved.add(_descendantRemoved.execute); } } _numDescendants += (child is Group) ? (child as Group)._numDescendants + 1 : 1; } private function descendantRemovedHandler(group : Group, child : ISceneNode) : void { if (group == this) { var childGroup : Group = child as Group; if (childGroup) { childGroup.descendantAdded.remove(_descendantAdded.execute); childGroup.descendantRemoved.remove(_descendantRemoved.execute); } } _numDescendants -= (child is Group) ? (child as Group)._numDescendants + 1 : 1; } private function addedHandler(child : ISceneNode, ancestor : Group) : void { var numChildren : uint = this.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : ISceneNode = _children[childId]; child.added.execute(child, ancestor); } } private function removedHandler(child : ISceneNode, ancestor : Group) : void { var numChildren : uint = this.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : ISceneNode = _children[childId]; child.removed.execute(child, ancestor); } } /** * Return true if the specified scene node is a child of the Group, false otherwise. * * @param scene * @return * */ public function contains(scene : ISceneNode) : Boolean { return getChildIndex(scene) >= 0; } /** * Return the index of the speficied scene node or -1 if it is not in the Group. * * @param child * @return * */ public function getChildIndex(child : ISceneNode) : int { if (child == null) throw new Error('The \'child\' parameter cannot be null.'); for (var i : int = 0; i < _numChildren; i++) if (_children[i] === child) return i; return -1; } public function getChildByName(name : String) : ISceneNode { for (var i : int = 0; i < _numChildren; i++) if (_children[i].name === name) return _children[i]; return null; } /** * Add a child to the group. * * @param scene The child to add. */ public function addChild(node : ISceneNode) : Group { return addChildAt(node, _numChildren); } /** * Add a child to the group at the specified position. * * @param node * @param position * @return * */ public function addChildAt(node : ISceneNode, position : uint) : Group { if (!node) throw new Error('Parameter \'scene\' must not be null.'); node.parent = this; for (var i : int = _numChildren - 1; i > position; --i) _children[i] = _children[int(i - 1)]; _children[position] = node; return this; } /** * Remove a child from the container. * * @param myChild The child to remove. * @return Whether the child was actually removed or not. */ public function removeChild(child : ISceneNode) : Group { return removeChildAt(getChildIndex(child)); } public function removeChildAt(position : uint) : Group { if (position >= _numChildren) throw new Error('The scene node is not a child of the caller.'); (_children[position] as ISceneNode).parent = null; return this; } /** * Remove all the children. * * @return * */ public function removeAllChildren() : Group { while (_numChildren) removeChildAt(0); return this; } /** * Return the child at the specified position. * * @param position * @return * */ public function getChildAt(position : uint) : ISceneNode { return position < _numChildren ? _children[position] : null; } /** * Returns the list of descendant scene nodes that have the specified type. * * @param type * @param descendants * @return * */ public function getDescendantsByType(type : Class, descendants : Vector.<ISceneNode> = null) : Vector.<ISceneNode> { descendants ||= new Vector.<ISceneNode>(); for (var i : int = 0; i < _numChildren; ++i) { var child : ISceneNode = _children[i]; var group : Group = child as Group; if (child is type) descendants.push(child); if (group) group.getDescendantsByType(type, descendants); } return descendants; } public function toString() : String { return '[' + getQualifiedClassName(this) + ' ' + name + ']'; } /** * Load the 3D scene corresponding to the specified URLRequest object * and add it directly to the group. * * @param request * @param options * @return * */ public function load(request : URLRequest, options : ParserOptions = null) : ILoader { if (options != null && scene != null && options.assets == null) options.assets = scene.assets; var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.load(request); return loader; } /** * Load the 3D scene corresponding to the specified Class object * and add it directly to the group. * * @param classObject * @param options * @return */ public function loadClass(classObject : Class, options : ParserOptions = null) : SceneLoader { if (options != null && scene != null && options.assets == null) options.assets = scene.assets; var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.loadClass(classObject); return loader; } /** * Load the 3D scene corresponding to the specified ByteArray object * and add it directly to the group. * * @param bytes * @param options * @return * */ public function loadBytes(bytes : ByteArray, options : ParserOptions = null) : ILoader { if (options != null && scene != null && options.assets == null) options.assets = scene.assets; var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.loadBytes(bytes); return loader; } /** * Return the set of nodes matching the specified XPath query. * * @param xpath * @return * */ public function get(xpath : String) : SceneIterator { return new SceneIterator(xpath, new <ISceneNode>[this]); } private function loaderCompleteHandler(loader : ILoader, scene : ISceneNode) : void { addChild(scene); } /** * Return all the Mesh objects hit by the specified ray. * * @param ray * @param maxDistance * @return * */ public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY, tag : uint = 1) : SceneIterator { var meshes : Vector.<ISceneNode> = getDescendantsByType(Mesh); var numMeshes : uint = meshes.length; var hit : Array = []; var depth : Vector.<Number> = new <Number>[]; var numItems : uint = 0; for (var i : uint = 0; i < numMeshes; ++i) { var mesh : Mesh = meshes[i] as Mesh; var hitDepth : Number = mesh.cast(ray, maxDistance, tag); if (hitDepth >= 0.0) { hit[numItems] = mesh; depth[numItems] = hitDepth; ++numItems; } } if (numItems > 1) Sort.flashSort(depth, hit, numItems); return new SceneIterator(null, Vector.<ISceneNode>(hit)); } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Group = new Group(); clone.name = name; clone.transform.copyFrom(transform); for (var childId : uint = 0; childId < _numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(_children[childId]); var clonedChild : AbstractSceneNode = AbstractSceneNode(child.cloneNode()); clone.addChild(clonedChild); } return clone; } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.scene.SceneIterator; import aerys.minko.type.Signal; import aerys.minko.type.Sort; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.parser.ParserOptions; import aerys.minko.type.math.Ray; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.getQualifiedClassName; use namespace minko_scene; /** * Group objects can contain other scene nodes and applies a 3D * transformation to its descendants. * * @author Jean-Marc Le Roux */ public class Group extends AbstractVisibleSceneNode { minko_scene var _children : Vector.<ISceneNode>; minko_scene var _numChildren : uint; private var _numDescendants : uint; private var _descendantAdded : Signal; private var _descendantRemoved : Signal; /** * The number of children of the Group. */ public function get numChildren() : uint { return _numChildren; } /** * The number of descendants of the Group. * * @return * */ public function get numDescendants() : uint { return _numDescendants; } /** * The signal executed when a descendant is added to the Group. * Callbacks for this signal must accept the following arguments: * <ul> * <li>newParent : Group, the Group the descendant was actually added to</li> * <li>descendant : ISceneNode, the descendant that was just added</li> * </ul> * * @return * */ public function get descendantAdded() : Signal { return _descendantAdded } /** * The signal executed when a descendant is removed from the Group. * Callbacks for this signal must accept the following arguments: * <ul> * <li>oldParent : Group, the Group the descendant was actually removed from</li> * <li>descendant : ISceneNode, the descendant that was just removed</li> * </ul> * * @return * */ public function get descendantRemoved() : Signal { return _descendantRemoved; } public function Group(...children) { super(); initializeChildren(children); } override protected function initializeSignals() : void { super.initializeSignals(); _descendantAdded = new Signal('Group.descendantAdded'); _descendantRemoved = new Signal('Group.descendantRemoved'); } override protected function initializeSignalHandlers() : void { super.initializeSignalHandlers(); _descendantAdded.add(descendantAddedHandler); _descendantRemoved.add(descendantRemovedHandler); added.add(addedHandler); removed.add(removedHandler); } protected function initializeChildren(children : Array) : void { _children = new <ISceneNode>[]; while (children.length == 1 && children[0] is Array) children = children[0]; var childrenNum : uint = children.length; for (var childrenIndex : uint = 0; childrenIndex < childrenNum; ++childrenIndex) addChild(ISceneNode(children[childrenIndex])); } private function descendantAddedHandler(group : Group, child : ISceneNode) : void { if (group == this) { var childGroup : Group = child as Group; if (childGroup) { childGroup.descendantAdded.add(_descendantAdded.execute); childGroup.descendantRemoved.add(_descendantRemoved.execute); } } _numDescendants += (child is Group) ? (child as Group)._numDescendants + 1 : 1; } private function descendantRemovedHandler(group : Group, child : ISceneNode) : void { if (group == this) { var childGroup : Group = child as Group; if (childGroup) { childGroup.descendantAdded.remove(_descendantAdded.execute); childGroup.descendantRemoved.remove(_descendantRemoved.execute); } } _numDescendants -= (child is Group) ? (child as Group)._numDescendants + 1 : 1; } private function addedHandler(child : ISceneNode, ancestor : Group) : void { var numChildren : uint = this.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : ISceneNode = _children[childId]; child.added.execute(child, ancestor); } } private function removedHandler(child : ISceneNode, ancestor : Group) : void { var numChildren : uint = this.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : ISceneNode = _children[childId]; child.removed.execute(child, ancestor); } } /** * Return true if the specified scene node is a child of the Group, false otherwise. * * @param scene * @return * */ public function contains(scene : ISceneNode) : Boolean { return getChildIndex(scene) >= 0; } /** * Return the index of the speficied scene node or -1 if it is not in the Group. * * @param child * @return * */ public function getChildIndex(child : ISceneNode) : int { if (child == null) throw new Error('The \'child\' parameter cannot be null.'); for (var i : int = 0; i < _numChildren; i++) if (_children[i] === child) return i; return -1; } public function getChildByName(name : String) : ISceneNode { for (var i : int = 0; i < _numChildren; i++) if (_children[i].name === name) return _children[i]; return null; } /** * Add a child to the group. * * @param scene The child to add. */ public function addChild(node : ISceneNode) : Group { return addChildAt(node, _numChildren); } /** * Add a child to the group at the specified position. * * @param node * @param position * @return * */ public function addChildAt(node : ISceneNode, position : uint) : Group { if (!node) throw new Error('Parameter \'node\' must not be null.'); node.parent = this; for (var i : int = _numChildren - 1; i > position; --i) _children[i] = _children[int(i - 1)]; _children[position] = node; return this; } /** * Remove a child from the container. * * @param myChild The child to remove. * @return Whether the child was actually removed or not. */ public function removeChild(child : ISceneNode) : Group { return removeChildAt(getChildIndex(child)); } public function removeChildAt(position : uint) : Group { if (position >= _numChildren) throw new Error('The scene node is not a child of the caller.'); (_children[position] as ISceneNode).parent = null; return this; } /** * Remove all the children. * * @return * */ public function removeAllChildren() : Group { while (_numChildren) removeChildAt(0); return this; } /** * Return the child at the specified position. * * @param position * @return * */ public function getChildAt(position : uint) : ISceneNode { return position < _numChildren ? _children[position] : null; } /** * Returns the list of descendant scene nodes that have the specified type. * * @param type * @param descendants * @return * */ public function getDescendantsByType(type : Class, descendants : Vector.<ISceneNode> = null) : Vector.<ISceneNode> { descendants ||= new Vector.<ISceneNode>(); for (var i : int = 0; i < _numChildren; ++i) { var child : ISceneNode = _children[i]; var group : Group = child as Group; if (child is type) descendants.push(child); if (group) group.getDescendantsByType(type, descendants); } return descendants; } public function toString() : String { return '[' + getQualifiedClassName(this) + ' ' + name + ']'; } /** * Load the 3D scene corresponding to the specified URLRequest object * and add it directly to the group. * * @param request * @param options * @return * */ public function load(request : URLRequest, options : ParserOptions = null) : ILoader { if (options != null && scene != null && options.assets == null) options.assets = scene.assets; var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.load(request); return loader; } /** * Load the 3D scene corresponding to the specified Class object * and add it directly to the group. * * @param classObject * @param options * @return */ public function loadClass(classObject : Class, options : ParserOptions = null) : SceneLoader { if (options != null && scene != null && options.assets == null) options.assets = scene.assets; var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.loadClass(classObject); return loader; } /** * Load the 3D scene corresponding to the specified ByteArray object * and add it directly to the group. * * @param bytes * @param options * @return * */ public function loadBytes(bytes : ByteArray, options : ParserOptions = null) : ILoader { if (options != null && scene != null && options.assets == null) options.assets = scene.assets; var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.loadBytes(bytes); return loader; } /** * Return the set of nodes matching the specified XPath query. * * @param xpath * @return * */ public function get(xpath : String) : SceneIterator { return new SceneIterator(xpath, new <ISceneNode>[this]); } private function loaderCompleteHandler(loader : ILoader, scene : ISceneNode) : void { addChild(scene); } /** * Return all the Mesh objects hit by the specified ray. * * @param ray * @param maxDistance * @return * */ public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY, tag : uint = 1) : SceneIterator { var meshes : Vector.<ISceneNode> = getDescendantsByType(Mesh); var numMeshes : uint = meshes.length; var hit : Array = []; var depth : Vector.<Number> = new <Number>[]; var numItems : uint = 0; for (var i : uint = 0; i < numMeshes; ++i) { var mesh : Mesh = meshes[i] as Mesh; var hitDepth : Number = mesh.cast(ray, maxDistance, tag); if (hitDepth >= 0.0) { hit[numItems] = mesh; depth[numItems] = hitDepth; ++numItems; } } if (numItems > 1) Sort.flashSort(depth, hit, numItems); return new SceneIterator(null, Vector.<ISceneNode>(hit)); } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Group = new Group(); clone.name = name; clone.transform.copyFrom(transform); for (var childId : uint = 0; childId < _numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(_children[childId]); var clonedChild : AbstractSceneNode = AbstractSceneNode(child.cloneNode()); clone.addChild(clonedChild); } return clone; } } }
fix typo in error message
fix typo in error message
ActionScript
mit
aerys/minko-as3
0d8e8bfda485582ceb975979073f42d6a160f9c6
src/aerys/minko/scene/controller/AbstractScriptController.as
src/aerys/minko/scene/controller/AbstractScriptController.as
package aerys.minko.scene.controller { import aerys.minko.ns.minko_scene; import aerys.minko.render.Viewport; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.KeyboardManager; import aerys.minko.type.MouseManager; import flash.display.BitmapData; import flash.utils.Dictionary; use namespace minko_scene; public class AbstractScriptController extends EnterFrameController { private var _scene : Scene; private var _started : Dictionary; private var _lastTime : Number; private var _deltaTime : Number; private var _currentTarget : ISceneNode; private var _viewport : Viewport; private var _targetsListLocked : Boolean; private var _targetsToAdd : Vector.<ISceneNode>; private var _targetsToRemove : Vector.<ISceneNode>; private var _updateRate : Number; protected function get scene() : Scene { return _scene; } protected function get deltaTime() : Number { return _deltaTime; } protected function get keyboard() : KeyboardManager { return _viewport.keyboardManager; } protected function get mouse() : MouseManager { return _viewport.mouseManager; } protected function get viewport() : Viewport { return _viewport; } protected function get updateRate() : Number { return _updateRate; } protected function set updateRate(value : Number) : void { _updateRate = value; } public function AbstractScriptController(targetType : Class = null) { super(targetType); initialize(); } protected function initialize() : void { _started = new Dictionary(true); } override protected function targetAddedToScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (_scene && scene != _scene) throw new Error( 'The same ScriptController instance can not be used in more than one scene ' + 'at a time.' ); _scene = scene; } override protected function targetRemovedFromScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (getNumTargetsInScene(scene)) _scene = null; } override protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { _deltaTime = time - _lastTime; if (_updateRate != 0. && deltaTime < 1000. / _updateRate) return; _viewport = viewport; _lastTime = time; lockTargetsList(); beforeUpdate(); var numTargets : uint = this.numTargets; for (var i : uint = 0; i < numTargets; ++i) { var target : ISceneNode = getTarget(i); if (target.scene) { if (!_started[target]) { _started[target] = true; start(target); } update(target); } else if (_started[target]) { _started[target] = false; stop(target); } } afterUpdate(); unlockTargetsList(); } /** * The 'start' method is called on a script target at the first frame occuring after it * has been added to the scene. * * @param target * */ protected function start(target : ISceneNode) : void { // nothing } /** * The 'beforeUpdate' method is called before each target is updated via the 'update' * method. * */ protected function beforeUpdate() : void { // nothing } protected function update(target : ISceneNode) : void { // nothing } /** * The 'afterUpdate' method is called after each target has been updated via the 'update' * method. * */ protected function afterUpdate() : void { // nothing } /** * The 'start' method is called on a script target at the first frame occuring after it * has been removed from the scene. * * @param target * */ protected function stop(target : ISceneNode) : void { // nothing } private function lockTargetsList() : void { _targetsListLocked = true; } private function unlockTargetsList() : void { _targetsListLocked = false; if (_targetsToAdd) { var numTargetsToAdd : uint = _targetsToAdd.length; for (var i : uint = 0; i < numTargetsToAdd; ++i) addTarget(_targetsToAdd[i]); _targetsToAdd = null; } if (_targetsToRemove) { var numTargetsToRemove : uint = _targetsToRemove.length; for (var j : uint = 0; j < numTargetsToRemove; ++j) removeTarget(_targetsToRemove[j]); _targetsToRemove = null; } } override minko_scene function addTarget(target : ISceneNode) : void { if (_targetsListLocked) { if (_targetsToAdd) _targetsToAdd.push(target); else _targetsToAdd = new <ISceneNode>[target]; } else super.addTarget(target); } override minko_scene function removeTarget(target : ISceneNode) : void { if (_targetsListLocked) { if (_targetsToRemove) _targetsToRemove.push(target); else _targetsToRemove = new <ISceneNode>[target]; } else super.removeTarget(target); } } }
package aerys.minko.scene.controller { import aerys.minko.ns.minko_scene; import aerys.minko.render.Viewport; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.KeyboardManager; import aerys.minko.type.MouseManager; import flash.display.BitmapData; import flash.utils.Dictionary; use namespace minko_scene; public class AbstractScriptController extends EnterFrameController { private var _scene : Scene; private var _started : Dictionary; private var _lastTime : Number; private var _deltaTime : Number; private var _currentTarget : ISceneNode; private var _viewport : Viewport; private var _targetsListLocked : Boolean; private var _targetsToAdd : Vector.<ISceneNode>; private var _targetsToRemove : Vector.<ISceneNode>; private var _updateRate : Number = 0.; protected function get scene() : Scene { return _scene; } protected function get deltaTime() : Number { return _deltaTime; } protected function get keyboard() : KeyboardManager { return _viewport.keyboardManager; } protected function get mouse() : MouseManager { return _viewport.mouseManager; } protected function get viewport() : Viewport { return _viewport; } protected function get updateRate() : Number { return _updateRate; } protected function set updateRate(value : Number) : void { _updateRate = value; } public function AbstractScriptController(targetType : Class = null) { super(targetType); initialize(); } protected function initialize() : void { _started = new Dictionary(true); } override protected function targetAddedToScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (_scene && scene != _scene) throw new Error( 'The same ScriptController instance can not be used in more than one scene ' + 'at a time.' ); _scene = scene; } override protected function targetRemovedFromScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (getNumTargetsInScene(scene)) _scene = null; } override protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { _deltaTime = time - _lastTime; if (_updateRate != 0. && deltaTime < 1000. / _updateRate) return; _viewport = viewport; _lastTime = time; lockTargetsList(); beforeUpdate(); var numTargets : uint = this.numTargets; for (var i : uint = 0; i < numTargets; ++i) { var target : ISceneNode = getTarget(i); if (target.scene) { if (!_started[target]) { _started[target] = true; start(target); } update(target); } else if (_started[target]) { _started[target] = false; stop(target); } } afterUpdate(); unlockTargetsList(); } /** * The 'start' method is called on a script target at the first frame occuring after it * has been added to the scene. * * @param target * */ protected function start(target : ISceneNode) : void { // nothing } /** * The 'beforeUpdate' method is called before each target is updated via the 'update' * method. * */ protected function beforeUpdate() : void { // nothing } protected function update(target : ISceneNode) : void { // nothing } /** * The 'afterUpdate' method is called after each target has been updated via the 'update' * method. * */ protected function afterUpdate() : void { // nothing } /** * The 'start' method is called on a script target at the first frame occuring after it * has been removed from the scene. * * @param target * */ protected function stop(target : ISceneNode) : void { // nothing } private function lockTargetsList() : void { _targetsListLocked = true; } private function unlockTargetsList() : void { _targetsListLocked = false; if (_targetsToAdd) { var numTargetsToAdd : uint = _targetsToAdd.length; for (var i : uint = 0; i < numTargetsToAdd; ++i) addTarget(_targetsToAdd[i]); _targetsToAdd = null; } if (_targetsToRemove) { var numTargetsToRemove : uint = _targetsToRemove.length; for (var j : uint = 0; j < numTargetsToRemove; ++j) removeTarget(_targetsToRemove[j]); _targetsToRemove = null; } } override minko_scene function addTarget(target : ISceneNode) : void { if (_targetsListLocked) { if (_targetsToAdd) _targetsToAdd.push(target); else _targetsToAdd = new <ISceneNode>[target]; } else super.addTarget(target); } override minko_scene function removeTarget(target : ISceneNode) : void { if (_targetsListLocked) { if (_targetsToRemove) _targetsToRemove.push(target); else _targetsToRemove = new <ISceneNode>[target]; } else super.removeTarget(target); } } }
Fix invalid NaN comparison.
Fix invalid NaN comparison.
ActionScript
mit
aerys/minko-as3
bcf53bb3e4f020fec8d29c9a4a360b386a774acd
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.VisibilityController; 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.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 AbstractSceneNode { 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 : VisibilityController; 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); _material = value; if (value) _bindings.addProvider(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; _geometry = value; _geometryChanged.execute(this, oldGeometry, value); } } /** * Whether the mesh is visible or not. * * @return * */ public function get visible() : Boolean { return _visibility.visible; } public function set visible(value : Boolean) : void { _visibility.visible = value; } 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(); initialize(geometry, material, name); } private function initialize(geometry : Geometry, material : Material, name : String) : void { if (name) this.name = name; _cloned = new Signal('Mesh.clones'); _materialChanged = new Signal('Mesh.materialChanged'); _frameChanged = new Signal('Mesh.frameChanged'); _geometryChanged = new Signal('Mesh.geometryChanged'); _bindings = new DataBindings(this); this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE); _geometry = geometry; this.material = material || DEFAULT_MATERIAL; _visibility = new VisibilityController(); // _visibility.frustumCulling = FrustumCulling.BOX ^ FrustumCulling.TOP_BOX; addController(_visibility); } public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number { return _geometry.boundingBox.testRay( ray, worldToLocal, 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; } override protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void { super.addedToSceneHandler(child, scene); if (child === this) _bindings.addProvider(transformData); } override protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void { super.removedFromSceneHandler(child, scene); if (child === this) _bindings.removeProvider(transformData); } } }
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.VisibilityController; 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.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 AbstractSceneNode { 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 : VisibilityController; 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); _material = value; if (value) _bindings.addProvider(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 is visible or not. * * @return * */ public function get visible() : Boolean { return _visibility.visible; } public function set visible(value : Boolean) : void { _visibility.visible = value; } 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(); initialize(geometry, material, name); } private function initialize(geometry : Geometry, material : Material, name : String) : void { if (name) this.name = name; _cloned = new Signal('Mesh.clones'); _materialChanged = new Signal('Mesh.materialChanged'); _frameChanged = new Signal('Mesh.frameChanged'); _geometryChanged = new Signal('Mesh.geometryChanged'); _bindings = new DataBindings(this); this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE); this.geometry = geometry; this.material = material || DEFAULT_MATERIAL; _visibility = new VisibilityController(); // _visibility.frustumCulling = FrustumCulling.BOX ^ FrustumCulling.TOP_BOX; addController(_visibility); } public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number { return _geometry.boundingBox.testRay( ray, worldToLocal, 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; } override protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void { super.addedToSceneHandler(child, scene); if (child === this) _bindings.addProvider(transformData); } override protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void { super.removedFromSceneHandler(child, scene); if (child === this) _bindings.removeProvider(transformData); } private function geometryChangedHandler(geometry : Geometry) : void { _geometryChanged.execute(this, _geometry, _geometry); } } }
update Mesh.geometry setter to listen to the Geometry.changed signal and execute Mesh.geometryChanged when it's triggered
update Mesh.geometry setter to listen to the Geometry.changed signal and execute Mesh.geometryChanged when it's triggered
ActionScript
mit
aerys/minko-as3
3c8b087281c79af445de51ec3e8c3dfac660ac19
frameworks/projects/Charts/asjs/src/org/apache/flex/charts/supportClasses/BoxItemRenderer.as
frameworks/projects/Charts/asjs/src/org/apache/flex/charts/supportClasses/BoxItemRenderer.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.charts.supportClasses { import org.apache.flex.charts.core.IChartItemRenderer; import org.apache.flex.charts.core.IChartSeries; import org.apache.flex.core.IBead; import org.apache.flex.core.graphics.IFill; import org.apache.flex.core.graphics.IStroke; import org.apache.flex.core.graphics.Rect; import org.apache.flex.core.graphics.SolidColor; import org.apache.flex.html.supportClasses.DataItemRenderer; /** * The BoxItemRenderer displays a colored rectangular area suitable for use as * an itemRenderer for a BarChartSeries. This class implements the * org.apache.flex.charts.core.IChartItemRenderer * interface. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class BoxItemRenderer extends DataItemRenderer implements IChartItemRenderer { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function BoxItemRenderer() { super(); } override public function addedToParent():void { super.addedToParent(); } override public function addBead(bead:IBead):void { super.addBead(bead); } private var _series:IChartSeries; /** * The series to which this itemRenderer instance belongs. Or, the series * being presented. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get series():IChartSeries { return _series; } public function set series(value:IChartSeries):void { _series = value; } private var filledRect:Rect; private var _yField:String = "y"; /** * The name of the field containing the value for the Y axis. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get yField():String { return _yField; } public function set yField(value:String):void { _yField = value; } private var _xField:String = "x"; /** * The name of the field containing the value for the X axis. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get xField():String { return _xField; } public function set xField(value:String):void { _xField = value; } private var _fill:IFill; /** * The color used to fill the interior of the box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get fill():IFill { return _fill; } public function set fill(value:IFill):void { _fill = value; } private var _stroke:IStroke; /** * The outline of the box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get stroke():IStroke { return _stroke; } public function set stroke(value:IStroke):void { _stroke = value; } /** * @copy org.apache.flex.supportClasses.UIItemRendererBase#data * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set data(value:Object):void { super.data = value; drawBar(); } /** * @copy org.apache.flex.core.UIBase#width * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set width(value:Number):void { super.width = value; drawBar(); } /** * @copy org.apache.flex.core.UIBase#height * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set height(value:Number):void { super.height = value; drawBar(); } /** * @private */ protected function drawBar():void { if ((this.width > 0) && (this.height > 0)) { var needsAdd:Boolean = false; if (filledRect == null) { filledRect = new Rect(); needsAdd = true; } filledRect.fill = fill; filledRect.stroke = stroke; filledRect.x = 0; filledRect.y = 0; filledRect.width = this.width; filledRect.height = this.height; if (needsAdd) { addElement(filledRect); } } } private var hoverFill:SolidColor; override public function updateRenderer():void { super.updateRenderer(); if (down||selected||hovered) { if (hoverFill == null) { hoverFill = new SolidColor(); hoverFill.color = (fill as SolidColor).color; hoverFill.alpha = 0.5; } filledRect.fill = hoverFill; } else { filledRect.fill = fill; } filledRect.drawRect(filledRect.x, filledRect.y, filledRect.width, filledRect.height); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.charts.supportClasses { import org.apache.flex.charts.core.IChartItemRenderer; import org.apache.flex.charts.core.IChartSeries; import org.apache.flex.core.IBead; import org.apache.flex.core.graphics.IFill; import org.apache.flex.core.graphics.IStroke; import org.apache.flex.core.graphics.Rect; import org.apache.flex.core.graphics.SolidColor; import org.apache.flex.core.graphics.LinearGradient; import org.apache.flex.html.supportClasses.DataItemRenderer; /** * The BoxItemRenderer displays a colored rectangular area suitable for use as * an itemRenderer for a BarChartSeries. This class implements the * org.apache.flex.charts.core.IChartItemRenderer * interface. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class BoxItemRenderer extends DataItemRenderer implements IChartItemRenderer { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function BoxItemRenderer() { super(); } override public function addedToParent():void { super.addedToParent(); } override public function addBead(bead:IBead):void { super.addBead(bead); } private var _series:IChartSeries; /** * The series to which this itemRenderer instance belongs. Or, the series * being presented. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get series():IChartSeries { return _series; } public function set series(value:IChartSeries):void { _series = value; } private var filledRect:Rect; private var _yField:String = "y"; /** * The name of the field containing the value for the Y axis. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get yField():String { return _yField; } public function set yField(value:String):void { _yField = value; } private var _xField:String = "x"; /** * The name of the field containing the value for the X axis. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get xField():String { return _xField; } public function set xField(value:String):void { _xField = value; } private var _fill:IFill; /** * The color used to fill the interior of the box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get fill():IFill { return _fill; } public function set fill(value:IFill):void { _fill = value; } private var _stroke:IStroke; /** * The outline of the box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get stroke():IStroke { return _stroke; } public function set stroke(value:IStroke):void { _stroke = value; } /** * @copy org.apache.flex.supportClasses.UIItemRendererBase#data * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set data(value:Object):void { super.data = value; drawBar(); } /** * @copy org.apache.flex.core.UIBase#width * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set width(value:Number):void { super.width = value; drawBar(); } /** * @copy org.apache.flex.core.UIBase#height * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set height(value:Number):void { super.height = value; drawBar(); } /** * @private */ protected function drawBar():void { if ((this.width > 0) && (this.height > 0)) { var needsAdd:Boolean = false; if (filledRect == null) { filledRect = new Rect(); needsAdd = true; } filledRect.fill = fill; filledRect.stroke = stroke; filledRect.x = 0; filledRect.y = 0; filledRect.width = this.width; filledRect.height = this.height; if (needsAdd) { addElement(filledRect); } } } private var hoverFill:IFill; override public function updateRenderer():void { super.updateRenderer(); if (down||selected||hovered) { if (hoverFill == null) { if(fill is SolidColor) { hoverFill = new SolidColor(); (hoverFill as SolidColor).color = (fill as SolidColor).color; (hoverFill as SolidColor).alpha = 0.5; } else if(fill is LinearGradient) { hoverFill = new LinearGradient(); (hoverFill as LinearGradient).entries = (fill as LinearGradient).entries; for (var i:int=0; i<(hoverFill as LinearGradient).entries; i++) { (hoverFill as LinearGradient).entries[i].alpha = 0.5; } } } filledRect.fill = hoverFill; } else { filledRect.fill = fill; } filledRect.drawRect(filledRect.x, filledRect.y, filledRect.width, filledRect.height); } } }
Handle case where fill could be a LinearGradient or a SolidColor
Handle case where fill could be a LinearGradient or a SolidColor
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
a4a58ae1d8308bd96d364c96b7a2d4d5c8106ea8
frameworks/projects/HTML/as/src/org/apache/flex/html/ImageAndTextButton.as
frameworks/projects/HTML/as/src/org/apache/flex/html/ImageAndTextButton.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html { import org.apache.flex.events.Event; import org.apache.flex.html.beads.models.ImageAndTextModel; COMPILE::JS { import org.apache.flex.core.WrappedHTMLElement; } /** * The ImageTextButton class implements a basic button that * displays and image and text. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class ImageAndTextButton extends TextButton { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function ImageAndTextButton() { super(); } /** * @private */ COMPILE::JS override public function set text(value:String):void { ImageAndTextModel(model).text = value; COMPILE::JS { setInnerHTML(); } } /** * The URL of an icon to use in the button * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get image():String { return ImageAndTextModel(model).image; } /** * @private */ public function set image(value:String):void { ImageAndTextModel(model).image = value; COMPILE::JS { setInnerHTML(); } } /** * @flexjsignorecoercion org.apache.flex.core.WrappedHTMLElement */ COMPILE::JS override protected function createElement():WrappedHTMLElement { element = document.createElement('button') as WrappedHTMLElement; element.setAttribute('type', 'button'); positioner = element; positioner.style.position = 'relative'; element.flexjs_wrapper = this; return element; } /** */ COMPILE::JS protected function setInnerHTML():void { var inner:String = ''; if (image != null) inner += "<img src='" + image + "'/>"; inner += '&nbsp;'; inner += text; element.innerHTML = inner; }; } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html { import org.apache.flex.events.Event; import org.apache.flex.html.beads.models.ImageAndTextModel; COMPILE::JS { import org.apache.flex.core.WrappedHTMLElement; } /** * The ImageTextButton class implements a basic button that * displays and image and text. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class ImageAndTextButton extends TextButton { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function ImageAndTextButton() { super(); } /** * @private */ COMPILE::JS override public function get text():String { return ImageAndTextModel(model).text; } /** * @private */ COMPILE::JS override public function set text(value:String):void { ImageAndTextModel(model).text = value; COMPILE::JS { setInnerHTML(); } } /** * The URL of an icon to use in the button * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get image():String { return ImageAndTextModel(model).image; } /** * @private */ public function set image(value:String):void { ImageAndTextModel(model).image = value; COMPILE::JS { setInnerHTML(); } } /** * @flexjsignorecoercion org.apache.flex.core.WrappedHTMLElement */ COMPILE::JS override protected function createElement():WrappedHTMLElement { element = document.createElement('button') as WrappedHTMLElement; element.setAttribute('type', 'button'); positioner = element; positioner.style.position = 'relative'; element.flexjs_wrapper = this; return element; } /** */ COMPILE::JS protected function setInnerHTML():void { var inner:String = ''; if (image != null) inner += "<img src='" + image + "'/>"; inner += '&nbsp;'; inner += text; element.innerHTML = inner; }; } }
fix ImageAndTextButton
fix ImageAndTextButton
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
19c690b942e7ddcddf2ada553bc2ce690bdf67fd
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.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 _cameraData : CameraDataProvider = null; protected var _enabled : Boolean = true; protected var _activated : Signal = new Signal('Camera.activated'); protected var _deactivated : Signal = new Signal('Camera.deactivated'); public function get cameraData() : CameraDataProvider { return _cameraData; } 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 worldToView() : Matrix4x4 { return worldToLocal; } public function get viewToWorld() : Matrix4x4 { return localToWorld; } public function get worldToScreen() : Matrix4x4 { return _cameraData.worldToScreen; } public function AbstractCamera(zNear : Number = DEFAULT_ZNEAR, zFar : Number = DEFAULT_ZFAR) { super(); _cameraData = new CameraDataProvider(worldToView, viewToWorld); _cameraData.zNear = zNear; _cameraData.zFar = zFar; initialize(); } protected function initialize() : void { throw new Error('Must be overriden.'); } public function unproject(x : Number, u : Number, out : Ray = null) : Ray { throw new Error('Must be overriden.'); } public function getWorldToScreen(output : Matrix4x4) : Matrix4x4 { return output != null ? output.copyFrom(_cameraData.worldToScreen) : _cameraData.worldToScreen.clone(); } public function getScreenToWorld(output : Matrix4x4) : Matrix4x4 { return output != null ? output.copyFrom(_cameraData.screenToWorld) : _cameraData.screenToWorld.clone(); } public function getProjection(output : Matrix4x4) : Matrix4x4 { return output != null ? output.copyFrom(_cameraData.projection) : _cameraData.projection.clone(); } } }
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.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 _cameraData : CameraDataProvider = null; protected var _enabled : Boolean = true; protected var _activated : Signal = new Signal('Camera.activated'); protected var _deactivated : Signal = new Signal('Camera.deactivated'); public function get cameraData() : CameraDataProvider { return _cameraData; } 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 worldToView() : Matrix4x4 { return worldToLocal; } public function get viewToWorld() : Matrix4x4 { return localToWorld; } public function get worldToScreen() : Matrix4x4 { return _cameraData.worldToScreen; } public function AbstractCamera(zNear : Number = DEFAULT_ZNEAR, zFar : Number = DEFAULT_ZFAR) { super(); _cameraData = new CameraDataProvider(worldToView, viewToWorld); _cameraData.zNear = zNear; _cameraData.zFar = zFar; initialize(); } protected function initialize() : void { throw new Error('Must be overriden.'); } public function unproject(x : Number, v : Number, out : Ray = null) : Ray { throw new Error('Must be overriden.'); } public function getWorldToScreen(output : Matrix4x4) : Matrix4x4 { return output != null ? output.copyFrom(_cameraData.worldToScreen) : _cameraData.worldToScreen.clone(); } public function getScreenToWorld(output : Matrix4x4) : Matrix4x4 { return output != null ? output.copyFrom(_cameraData.screenToWorld) : _cameraData.screenToWorld.clone(); } public function getProjection(output : Matrix4x4) : Matrix4x4 { return output != null ? output.copyFrom(_cameraData.projection) : _cameraData.projection.clone(); } } }
fix typo
fix typo
ActionScript
mit
aerys/minko-as3
f8c96b92408f16db74cff773af30da6642fbbc7c
src/stdio/StandardProcess.as
src/stdio/StandardProcess.as
package stdio { import flash.display.* import flash.events.* import flash.utils.* import flash.net.* public class StandardProcess implements Process { private const buffered_stdin: BufferedStream = new BufferedStream private const stdin_socket: SocketStream = new SocketStream private const readline_socket: SocketStream = new SocketStream private const stdout_socket: SocketStream = new SocketStream private const stderr_socket: SocketStream = new SocketStream private var _env: Object private var _prompt: String = "> " public function StandardProcess(env: Object) { _env = env } public function initialize(callback: Function): void { if (available) { connect(callback) } else { callback() } } public function get available(): Boolean { return env["stdio.enabled"] } private function get http_url(): String { return env["stdio.http"] } private function get interactive(): Boolean { return env["stdio.interactive"] === "true" } private function connect(callback: Function): void { stdin_socket.onopen = onopen readline_socket.onopen = onopen stdout_socket.onopen = onopen stderr_socket.onopen = onopen var n: int = 0 function onopen(): void { if (++n === 3) { callback() } } stdin_socket.ondata = buffered_stdin.write stdin_socket.onclose = buffered_stdin.close readline_socket.ondata = buffered_stdin.write readline_socket.onclose = buffered_stdin.close const stdin_port: int = get_int("stdio.in") const readline_port: int = get_int("stdio.readline") if (interactive) { readline_socket.connect("localhost", readline_port) } else { stdin_socket.connect("localhost", stdin_port) } const stdout_port: int = get_int("stdio.out") const stderr_port: int = get_int("stdio.err") stdout_socket.connect("localhost", stdout_port) stderr_socket.connect("localhost", stderr_port) function get_int(name: String): int { return parseInt(env[name]) } } //---------------------------------------------------------------- public function get env(): * { return _env } public function get argv(): Array { if (env["stdio.argv"] === "") { return [] } else { return env["stdio.argv"].split(" ").map( function (argument: String, ...rest: Array): String { return decodeURIComponent(argument) } ) } } public function puts(value: *): void { if (available) { if (interactive) { readline_socket.puts("!" + value) } else { stdout.puts(value) } } else { debug.show("puts: " + value) } } public function warn(value: *): void { if (available) { stderr.puts(value) } else { debug.show("warn: " + value) } } public function die(value: *): void { if (available) { warn(value); exit(-1) } else { throw new Error("fatal error: " + String(value)) } } public function style(styles: String, string: String): String { const codes: Object = { none: 0, bold: 1, italic: 3, underline: 4, inverse: 7, black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37, gray: 90, grey: 90 } if (styles === "") { return string } else { return styles.split(/\s+/).map( function (style: String, ...rest: Array): String { if (style in codes) { return escape_sequence(codes[style]) } else { throw new Error("style not supported: " + style) } } ).join("") + string + escape_sequence(0) } function escape_sequence(code: int): String { return "\x1b[" + code + "m" } } public function gets(callback: Function): void { if (available) { if (interactive) { readline_socket.puts("?" + _prompt) } stdin.gets(callback) } else { callback(null) } } public function set prompt(value: String): void { _prompt = value } public function get stdin(): InputStream { return buffered_stdin } public function get stdout(): OutputStream { return stdout_socket } public function get stderr(): OutputStream { return stderr_socket } public function handle(error: *): void { if (error is UncaughtErrorEvent) { UncaughtErrorEvent(error).preventDefault() handle(UncaughtErrorEvent(error).error) exit(-1) } else if (error is Error) { // Important: Avoid the `Error(x)` casting syntax. http_post("/error", (error as Error).getStackTrace()) } else if (error is ErrorEvent) { http_post("/error", (error as ErrorEvent).text) } else { http_post("/error", String(error)) } } private function shell_quote(word: String): String { if (/^[-=.,\w]+$/.test(word)) { return word } else { return "'" + word.replace(/'/g, "'\\''") + "'" } } public function exec( command: *, callback: Function, errback: Function = null ): void { if (available) { var stdin: String = "" if (isPlainObject(command)) { if ("command" in command && "stdin" in command) { stdin = command.stdin command = command.command } else { throw new Error("bad command object: %i", command) } } if (command is String) { command = ["sh", "-c", command] } const url: String = "/exec?" + map( command, encodeURIComponent ).join("&") http_post(url, stdin, function (data: String): void { const result: XML = new XML(data) const status: int = result.@status const stdout: String = result.stdout.text() const stderr: String = result.stderr.text() if (status === 0) { if (callback.length === 1) { callback(stdout) } else { callback(stdout, stderr) } } else if (errback === null) { warn(stderr) } else if (errback.length === 1) { errback(status) } else if (errback.length === 2) { errback(status, stderr) } else { errback(status, stderr, stdout) } }) } else { throw new Error("cannot execute command: process not available") } } public function exit(status: int = 0): void { if (available) { when_ready(function (): void { http_post("/exit", String(status)) }) } else { throw new Error("cannot exit: process not available") } } //---------------------------------------------------------------- private var n_pending_requests: int = 0 private var ready_callbacks: Array = [] private function when_ready(callback: Function): void { if (n_pending_requests === 0) { callback() } else { ready_callbacks.push(callback) } } private function handle_ready(): void { for each (var callback: Function in ready_callbacks) { callback() } ready_callbacks = [] } private function http_post( path: String, content: String, callback: Function = null ): void { const request: URLRequest = new URLRequest(http_url + path) request.method = "POST" request.data = content const loader: URLLoader = new URLLoader ++n_pending_requests loader.addEventListener( Event.COMPLETE, function (event: Event): void { if (callback !== null) { callback(loader.data) } if (--n_pending_requests === 0) { handle_ready() } } ) loader.load(request) } } }
package stdio { import flash.display.* import flash.events.* import flash.utils.* import flash.net.* public class StandardProcess implements Process { private const buffered_stdin: BufferedStream = new BufferedStream private const stdin_socket: SocketStream = new SocketStream private const readline_socket: SocketStream = new SocketStream private const stdout_socket: SocketStream = new SocketStream private const stderr_socket: SocketStream = new SocketStream private var _env: Object private var _prompt: String = "> " public function StandardProcess(env: Object) { _env = env } public function initialize(callback: Function): void { if (available) { connect(callback) } else { callback() } } public function get available(): Boolean { return env["stdio.enabled"] } private function get http_url(): String { return env["stdio.http"] } private function get interactive(): Boolean { return env["stdio.interactive"] === "true" } private function connect(callback: Function): void { stdin_socket.onopen = onopen readline_socket.onopen = onopen stdout_socket.onopen = onopen stderr_socket.onopen = onopen var n: int = 0 function onopen(): void { if (++n === 3) { callback() } } stdin_socket.ondata = buffered_stdin.write stdin_socket.onclose = buffered_stdin.close readline_socket.ondata = buffered_stdin.write readline_socket.onclose = buffered_stdin.close const stdin_port: int = get_int("stdio.in") const readline_port: int = get_int("stdio.readline") if (interactive) { readline_socket.connect("localhost", readline_port) } else { stdin_socket.connect("localhost", stdin_port) } const stdout_port: int = get_int("stdio.out") const stderr_port: int = get_int("stdio.err") stdout_socket.connect("localhost", stdout_port) stderr_socket.connect("localhost", stderr_port) function get_int(name: String): int { return parseInt(env[name]) } } //---------------------------------------------------------------- public function get env(): * { return _env } public function get argv(): Array { if (env["stdio.argv"] === "") { return [] } else { return env["stdio.argv"].split(" ").map( function (argument: String, ...rest: Array): String { return decodeURIComponent(argument) } ) } } public function puts(value: *): void { if (available) { if (interactive) { readline_socket.puts("!" + value) } else { stdout.puts(value) } } else { debug.show("puts: " + value) } } public function warn(value: *): void { if (available) { stderr.puts(value) } else { debug.show("warn: " + value) } } public function die(value: *): void { if (available) { warn(value); exit(-1) } else { throw new Error("fatal error: " + String(value)) } } public function style(styles: String, string: String): String { const codes: Object = { none: 0, bold: 1, italic: 3, underline: 4, inverse: 7, black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37, gray: 90, grey: 90 } if (styles === "") { return string } else { return styles.split(/\s+/).map( function (style: String, ...rest: Array): String { if (style in codes) { return escape_sequence(codes[style]) } else { throw new Error("style not supported: " + style) } } ).join("") + string + escape_sequence(0) } function escape_sequence(code: int): String { return "\x1b[" + code + "m" } } public function gets(callback: Function): void { if (available) { if (interactive) { readline_socket.puts("?" + _prompt) } stdin.gets(callback) } else { callback(null) } } public function set prompt(value: String): void { _prompt = value } public function get stdin(): InputStream { return buffered_stdin } public function get stdout(): OutputStream { return stdout_socket } public function get stderr(): OutputStream { return stderr_socket } public function handle(error: *): void { if (error is UncaughtErrorEvent) { UncaughtErrorEvent(error).preventDefault() handle(UncaughtErrorEvent(error).error) exit(-1) } else if (error is Error) { // Important: Avoid the `Error(x)` casting syntax. http_post("/error", (error as Error).getStackTrace()) } else if (error is ErrorEvent) { http_post("/error", (error as ErrorEvent).text) } else { http_post("/error", String(error)) } } private function shell_quote(word: String): String { if (/^[-=.,\w]+$/.test(word)) { return word } else { return "'" + word.replace(/'/g, "'\\''") + "'" } } public function exec( command: *, callback: Function, errback: Function = null ): void { if (available) { var stdin: String = "" if (isPlainObject(command)) { if ("command" in command && "stdin" in command) { stdin = command.stdin command = command.command } else { throw new Error("bad command object: %i", command) } } if (command is String) { command = ["sh", "-c", command] } const url: String = "/exec?" + map( command, encodeURIComponent ).join("&") http_post(url, stdin, function (data: String): void { const result: XML = new XML(data) const status: int = result.@status const stdout: String = result.stdout.text() const stderr: String = result.stderr.text() if (status === 0) { if (callback.length === 1) { callback(stdout) } else { callback(stdout, stderr) } } else if (errback === null) { warn(stderr) } else if (errback.length === 1) { errback(new Error(stderr)) } else if (errback.length === 2) { errback(status, stderr) } else { errback(status, stderr, stdout) } }) } else { throw new Error("cannot execute command: process not available") } } public function exit(status: int = 0): void { if (available) { when_ready(function (): void { http_post("/exit", String(status)) }) } else { throw new Error("cannot exit: process not available") } } //---------------------------------------------------------------- private var n_pending_requests: int = 0 private var ready_callbacks: Array = [] private function when_ready(callback: Function): void { if (n_pending_requests === 0) { callback() } else { ready_callbacks.push(callback) } } private function handle_ready(): void { for each (var callback: Function in ready_callbacks) { callback() } ready_callbacks = [] } private function http_post( path: String, content: String, callback: Function = null ): void { const request: URLRequest = new URLRequest(http_url + path) request.method = "POST" request.data = content const loader: URLLoader = new URLLoader ++n_pending_requests loader.addEventListener( Event.COMPLETE, function (event: Event): void { if (callback !== null) { callback(loader.data) } if (--n_pending_requests === 0) { handle_ready() } } ) loader.load(request) } } }
Change `process.exec` to pass an Error instance to its errback.
Change `process.exec` to pass an Error instance to its errback.
ActionScript
mit
dbrock/stdio.as,dbrock/stdio.as,dbrock/stdio.as
bd2ab4d997cb0b973dc1bd5e5f1db46c8e15c4a3
src/aerys/minko/scene/controller/light/PointLightController.as
src/aerys/minko/scene/controller/light/PointLightController.as
package aerys.minko.scene.controller.light { import aerys.minko.scene.data.LightDataProvider; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.light.AbstractLight; import aerys.minko.scene.node.light.PointLight; import aerys.minko.type.enum.ShadowMappingType; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; /** * * @author Jean-Marc Le Roux * */ public final class PointLightController extends LightShadowController { private var _worldPosition : Vector4; private var _projection : Matrix4x4; public function PointLightController() { super( PointLight, ShadowMappingType.PCF | ShadowMappingType.DUAL_PARABOLOID | ShadowMappingType.VARIANCE | ShadowMappingType.EXPONENTIAL ); initialize(); } private function initialize() : void { _worldPosition = new Vector4(); _projection = new Matrix4x4(); } override protected function targetAddedHandler(ctrl : LightController, light : AbstractLight) : void { super.targetAddedHandler(ctrl, light); lightData.setLightProperty('worldPosition', _worldPosition); lightData.setLightProperty('projection', _projection); } override protected function lightAddedToScene(scene : Scene) : void { super.lightAddedToScene(scene); light.localToWorld(Vector4.ZERO, _worldPosition); updateProjectionMatrix(); light.localToWorldTransformChanged.add(lightLocalToWorldTransformChangedHandler); } protected function lightLocalToWorldTransformChangedHandler(light : AbstractLight, localToWorld : Matrix4x4) : void { localToWorld.getTranslation(_worldPosition); } override protected function lightDataChangedHandler(lightData : LightDataProvider, propertyName : String, bindingName : String, value : Object) : void { super.lightDataChangedHandler(lightData, propertyName, bindingName, propertyName); propertyName = LightDataProvider.getPropertyName(propertyName); if (propertyName == 'shadowZNear' || propertyName == 'shadowZFar') updateProjectionMatrix(); } private function updateProjectionMatrix() : void { var zNear : Number = lightData.getLightProperty('shadowZNear'); var zFar : Number = lightData.getLightProperty('shadowZFar'); var fd : Number = 1. / Math.tan(Math.PI / 4); var m33 : Number = 1. / (zFar - zNear); var m43 : Number = -zNear / (zFar - zNear); _projection.initialize( fd, 0., 0., 0., 0., fd, 0., 0., 0., 0., m33, 1., 0., 0., m43, 0. ); } } }
package aerys.minko.scene.controller.light { import aerys.minko.scene.data.LightDataProvider; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.light.AbstractLight; import aerys.minko.scene.node.light.PointLight; import aerys.minko.type.enum.ShadowMappingType; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; /** * * @author Jean-Marc Le Roux * */ public final class PointLightController extends LightShadowController { private var _worldPosition : Vector4; private var _projection : Matrix4x4; public function PointLightController() { super( PointLight, ShadowMappingType.PCF | ShadowMappingType.DUAL_PARABOLOID | ShadowMappingType.VARIANCE | ShadowMappingType.EXPONENTIAL ); initialize(); } private function initialize() : void { _worldPosition = new Vector4(); _projection = new Matrix4x4(); } override protected function targetAddedHandler(ctrl : LightController, light : AbstractLight) : void { super.targetAddedHandler(ctrl, light); lightData.setLightProperty('worldPosition', _worldPosition); lightData.setLightProperty('projection', _projection); } override protected function lightAddedToScene(scene : Scene) : void { super.lightAddedToScene(scene); light.localToWorld(Vector4.ZERO, _worldPosition); updateProjectionMatrix(); light.localToWorldTransformChanged.add(lightLocalToWorldTransformChangedHandler); } override protected function lightRemovedFromScene(scene:Scene):void { super.lightRemovedFromScene(scene); light.localToWorldTransformChanged.remove(lightLocalToWorldTransformChangedHandler); } protected function lightLocalToWorldTransformChangedHandler(light : AbstractLight, localToWorld : Matrix4x4) : void { localToWorld.getTranslation(_worldPosition); } override protected function lightDataChangedHandler(lightData : LightDataProvider, propertyName : String, bindingName : String, value : Object) : void { super.lightDataChangedHandler(lightData, propertyName, bindingName, propertyName); propertyName = LightDataProvider.getPropertyName(propertyName); if (propertyName == 'shadowZNear' || propertyName == 'shadowZFar') updateProjectionMatrix(); } private function updateProjectionMatrix() : void { var zNear : Number = lightData.getLightProperty('shadowZNear'); var zFar : Number = lightData.getLightProperty('shadowZFar'); var fd : Number = 1. / Math.tan(Math.PI / 4); var m33 : Number = 1. / (zFar - zNear); var m43 : Number = -zNear / (zFar - zNear); _projection.initialize( fd, 0., 0., 0., 0., fd, 0., 0., 0., 0., m33, 1., 0., 0., m43, 0. ); } } }
Remove a point light remove signal properly
Remove a point light remove signal properly
ActionScript
mit
aerys/minko-as3
3889814e66757d19e1d94e63d61fcf067d22c366
frameworks/as/projects/FlexJSUI/src/org/apache/flex/binding/SimpleBinding.as
frameworks/as/projects/FlexJSUI/src/org/apache/flex/binding/SimpleBinding.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.binding { import flash.events.IEventDispatcher; import flash.events.Event; import org.apache.flex.core.IBead; import org.apache.flex.core.IStrand; import org.apache.flex.core.IDocument; /** * The SimpleBinding class is lightweight data-binding class that * is optimized for simple assignments of one object's property to * another object's property. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class SimpleBinding implements IBead, IDocument { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function SimpleBinding() { } /** * The source object that dispatches an event * when the property changes * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var source:IEventDispatcher; /** * The host mxml document for the source and * destination objects. The source object * is either this document for simple bindings * like {foo} where foo is a property on * the mxml documnet, or found as document[sourceID] * for simple bindings like {someid.someproperty} * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var document:Object; /** * The destination object. It is always the same * as the strand. SimpleBindings are attached to * the strand of the destination object. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var destination:Object; /** * If not null, the id of the mxml tag who's property * is being watched for changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var sourceID:String; /** * If not null, the name of a property on the * mxml document that is being watched for changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var sourcePropertyName:String; /** * The event name that is dispatched when the source * property changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var eventName:String; /** * The name of the property on the strand that * is set when the source property changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var destinationPropertyName:String; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { destination = value; if (sourceID != null) source = document[sourceID] as IEventDispatcher; else source = document as IEventDispatcher; source.addEventListener(eventName, changeHandler); destination[destinationPropertyName] = source[sourcePropertyName]; } /** * @copy org.apache.flex.core.IDocument#setDocument() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function setDocument(document:Object, id:String = null):void { this.document = document; } private function changeHandler(event:Event):void { destination[destinationPropertyName] = source[sourcePropertyName]; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.binding { import flash.events.IEventDispatcher; import flash.events.Event; import org.apache.flex.core.IBead; import org.apache.flex.core.IStrand; import org.apache.flex.core.IDocument; /** * The SimpleBinding class is lightweight data-binding class that * is optimized for simple assignments of one object's property to * another object's property. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class SimpleBinding implements IBead, IDocument { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function SimpleBinding() { } /** * The source object that dispatches an event * when the property changes * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var source:IEventDispatcher; /** * The host mxml document for the source and * destination objects. The source object * is either this document for simple bindings * like {foo} where foo is a property on * the mxml documnet, or found as document[sourceID] * for simple bindings like {someid.someproperty} * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var document:Object; /** * The destination object. It is always the same * as the strand. SimpleBindings are attached to * the strand of the destination object. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var destination:Object; /** * If not null, the id of the mxml tag who's property * is being watched for changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var sourceID:String; /** * If not null, the name of a property on the * mxml document that is being watched for changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var sourcePropertyName:String; /** * The event name that is dispatched when the source * property changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var eventName:String; /** * The name of the property on the strand that * is set when the source property changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var destinationPropertyName:String; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { if (destination == null) destination = value; if (sourceID != null) source = document[sourceID] as IEventDispatcher; else source = document as IEventDispatcher; source.addEventListener(eventName, changeHandler); destination[destinationPropertyName] = source[sourcePropertyName]; } /** * @copy org.apache.flex.core.IDocument#setDocument() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function setDocument(document:Object, id:String = null):void { this.document = document; } private function changeHandler(event:Event):void { destination[destinationPropertyName] = source[sourcePropertyName]; } } }
allow override of desitination so SimpleBinding can be used for non-strands
allow override of desitination so SimpleBinding can be used for non-strands
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
29b25381a73d3e034c97baaa7ec077ffb2bad0f3
src/aerys/minko/scene/visitor/data/LocalData.as
src/aerys/minko/scene/visitor/data/LocalData.as
package aerys.minko.scene.visitor.data { import aerys.minko.type.math.Matrix4x4; public final class LocalData { public static const VIEW : String = 'view'; public static const WORLD : String = 'world'; public static const PROJECTION : String = 'projection'; public static const WORLD_INVERSE : String = 'worldInverse'; public static const VIEW_INVERSE : String = 'viewInverse'; public static const PROJECTION_INVERSE : String = 'projectionInverse'; public static const LOCAL_TO_VIEW : String = 'localToView'; public static const LOCAL_TO_SCREEN : String = 'localToScreen'; public static const LOCAL_TO_UV : String = 'localToUv'; private static const UPDATE_NONE : uint = 0; private static const UPDATE_WORLD_TO_LOCAL : uint = 1; private static const UPDATE_CAMERA_POSITION : uint = 2; private static const UPDATE_LOCAL_TO_VIEW : uint = 4; private static const UPDATE_LOCAL_TO_SCREEN : uint = 8; private static const UPDATE_VIEW_TO_LOCAL : uint = 16; private static const UPDATE_ALL : uint = UPDATE_WORLD_TO_LOCAL | UPDATE_CAMERA_POSITION | UPDATE_LOCAL_TO_VIEW | UPDATE_LOCAL_TO_SCREEN | UPDATE_VIEW_TO_LOCAL; private var _update : uint = 0; private var _world : Matrix4x4 = new Matrix4x4(); private var _view : Matrix4x4 = new Matrix4x4(); private var _projection : Matrix4x4 = new Matrix4x4(); private var _viewInverse : Matrix4x4 = null; private var _viewInverse_viewVersion : uint = 0; private var _worldInverse : Matrix4x4 = null; private var _worldInverse_worldVersion : uint = 0; private var _localToView : Matrix4x4 = null; private var _localToView_viewVersion : uint = 0; private var _localToView_worldVersion : uint = 0; private var _localToScreen : Matrix4x4 = null; private var _localToScreen_localToViewVersion : uint = 0; private var _localToScreen_projectionVersion : uint = 0; private var _localToUv : Matrix4x4 = null; private var _localToUv_localToScreenVersion : uint = 0; public function get view() : Matrix4x4 { return _view; } public function get world() : Matrix4x4 { return _world; } public function get projection() : Matrix4x4 { return _projection; } public function get worldInverse() : Matrix4x4 { var worldMatrix : Matrix4x4 = world; if (_worldInverse_worldVersion != worldMatrix.version) { _worldInverse = Matrix4x4.invert(worldMatrix, _worldInverse); _worldInverse_worldVersion = worldMatrix.version; } return _worldInverse; } public function get viewInverse() : Matrix4x4 { var viewMatrix : Matrix4x4 = view; if (_viewInverse_viewVersion != viewMatrix.version) { _viewInverse = Matrix4x4.invert(viewMatrix, _viewInverse); _viewInverse_viewVersion = viewMatrix.version; } return _viewInverse; } public function get localToView() : Matrix4x4 { var worldMatrix : Matrix4x4 = world; var viewMatrix : Matrix4x4 = view; if (_localToView_worldVersion != worldMatrix.version || _localToView_viewVersion != viewMatrix.version) { _localToView = Matrix4x4.multiply(viewMatrix, worldMatrix, _localToView); _localToView_worldVersion = worldMatrix.version; _localToView_viewVersion = viewMatrix.version; } return _localToView; } public function get localToScreen() : Matrix4x4 { var localToViewMatrix : Matrix4x4 = localToView; var projectionMatrix : Matrix4x4 = projection; if (_localToScreen_localToViewVersion != localToViewMatrix.version || _localToScreen_projectionVersion != projectionMatrix.version) { _localToScreen = Matrix4x4.multiply(projectionMatrix, localToViewMatrix, _localToScreen); _localToScreen_localToViewVersion = localToViewMatrix.version; _localToScreen_projectionVersion = projectionMatrix.version; } return _localToScreen; } /** * FIXME */ public function get screentoUv() : Matrix4x4 { var offset : Number = 0.5 + (0.5 / 2048); return new Matrix4x4( 0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, offset, offset, 0.0, 1.0 ); } public function get localToUv() : Matrix4x4 { var localToScreenMatrix : Matrix4x4 = localToScreen; var screenToUvMatrix : Matrix4x4 = screentoUv; if (_localToUv_localToScreenVersion != localToScreenMatrix.version) { _localToUv = Matrix4x4.multiply(screenToUvMatrix, localToScreenMatrix); _localToUv_localToScreenVersion = localToScreenMatrix.version; } return _localToUv; } public function set world(value : Matrix4x4) : void { Matrix4x4.copy(value, _world); _update |= UPDATE_LOCAL_TO_SCREEN | UPDATE_LOCAL_TO_VIEW | UPDATE_WORLD_TO_LOCAL; } public function set view(value : Matrix4x4) : void { Matrix4x4.copy(value, _view); _update |= UPDATE_LOCAL_TO_SCREEN | UPDATE_LOCAL_TO_VIEW | UPDATE_VIEW_TO_LOCAL; } public function set projection(value : Matrix4x4) : void { Matrix4x4.copy(value, _projection); _update |= UPDATE_LOCAL_TO_SCREEN; } public function LocalData() { reset(); } public function reset() : void { _viewInverse_viewVersion = uint.MAX_VALUE; _worldInverse_worldVersion = uint.MAX_VALUE; _localToView_viewVersion = uint.MAX_VALUE; _localToView_worldVersion = uint.MAX_VALUE; _localToScreen_localToViewVersion = uint.MAX_VALUE; _localToScreen_projectionVersion = uint.MAX_VALUE; } } }
package aerys.minko.scene.visitor.data { import aerys.minko.type.math.Matrix4x4; public final class LocalData { private static const _SCREEN_TO_UV : Matrix4x4 = new Matrix4x4( 0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 1.0 ); public static const VIEW : String = 'view'; public static const WORLD : String = 'world'; public static const PROJECTION : String = 'projection'; public static const WORLD_INVERSE : String = 'worldInverse'; public static const VIEW_INVERSE : String = 'viewInverse'; public static const SCREEN_TO_UV : String = 'screenToUv'; public static const LOCAL_TO_VIEW : String = 'localToView'; public static const LOCAL_TO_SCREEN : String = 'localToScreen'; public static const LOCAL_TO_UV : String = 'localToUv'; protected var _world : Matrix4x4; protected var _view : Matrix4x4; protected var _projection : Matrix4x4; protected var _viewInverse : Matrix4x4; protected var _viewInverse_viewVersion : uint; protected var _worldInverse : Matrix4x4; protected var _worldInverse_worldVersion : uint; protected var _localToView : Matrix4x4; protected var _localToView_viewVersion : uint; protected var _localToView_worldVersion : uint; protected var _localToScreen : Matrix4x4; protected var _localToScreen_localToViewVersion : uint; protected var _localToScreen_projectionVersion : uint; protected var _localToUv : Matrix4x4; protected var _localToUv_localToScreenVersion : uint; public function get view() : Matrix4x4 { return _view; } public function get world() : Matrix4x4 { return _world; } public function get projection() : Matrix4x4 { return _projection; } public function get worldInverse() : Matrix4x4 { var worldMatrix : Matrix4x4 = world; if (_worldInverse_worldVersion != worldMatrix.version) { _worldInverse = Matrix4x4.invert(worldMatrix, _worldInverse); _worldInverse_worldVersion = worldMatrix.version; } return _worldInverse; } public function get viewInverse() : Matrix4x4 { var viewMatrix : Matrix4x4 = view; if (_viewInverse_viewVersion != viewMatrix.version) { _viewInverse = Matrix4x4.invert(viewMatrix, _viewInverse); _viewInverse_viewVersion = viewMatrix.version; } return _viewInverse; } public function get localToView() : Matrix4x4 { var worldMatrix : Matrix4x4 = world; var viewMatrix : Matrix4x4 = view; if (_localToView_worldVersion != worldMatrix.version || _localToView_viewVersion != viewMatrix.version) { _localToView = Matrix4x4.multiply(viewMatrix, worldMatrix, _localToView); _localToView_worldVersion = worldMatrix.version; _localToView_viewVersion = viewMatrix.version; } return _localToView; } public function get localToScreen() : Matrix4x4 { var localToViewMatrix : Matrix4x4 = localToView; var projectionMatrix : Matrix4x4 = projection; if (_localToScreen_localToViewVersion != localToViewMatrix.version || _localToScreen_projectionVersion != projectionMatrix.version) { _localToScreen = Matrix4x4.multiply(projectionMatrix, localToViewMatrix, _localToScreen); _localToScreen_localToViewVersion = localToViewMatrix.version; _localToScreen_projectionVersion = projectionMatrix.version; } return _localToScreen; } public function get screentoUv() : Matrix4x4 { return _SCREEN_TO_UV; } public function get localToUv() : Matrix4x4 { var localToScreenMatrix : Matrix4x4 = localToScreen; var screenToUvMatrix : Matrix4x4 = screentoUv; if (_localToUv_localToScreenVersion != localToScreenMatrix.version) { _localToUv = Matrix4x4.multiply(screenToUvMatrix, localToScreenMatrix); _localToUv_localToScreenVersion = localToScreenMatrix.version; } return _localToUv; } public function set world(value : Matrix4x4) : void { Matrix4x4.copy(value, _world); } public function set view(value : Matrix4x4) : void { Matrix4x4.copy(value, _view); } public function set projection(value : Matrix4x4) : void { Matrix4x4.copy(value, _projection); } public function LocalData() { _world = new Matrix4x4(); _view = new Matrix4x4(); _projection = new Matrix4x4(); reset(); } public function reset() : void { _viewInverse_viewVersion = uint.MAX_VALUE; _worldInverse_worldVersion = uint.MAX_VALUE; _localToView_viewVersion = uint.MAX_VALUE; _localToView_worldVersion = uint.MAX_VALUE; _localToScreen_localToViewVersion = uint.MAX_VALUE; _localToScreen_projectionVersion = uint.MAX_VALUE; } } }
Update LocalData class to use cache the same way IWorldData's implementations do
Update LocalData class to use cache the same way IWorldData's implementations do
ActionScript
mit
aerys/minko-as3
309d5d11003b95d806b48d3e52c85294a92e8c97
asn_visualization/ProgressBar.as
asn_visualization/ProgressBar.as
package { import flare.display.TextSprite; import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.events.TimerEvent; import flash.net.URLLoader; import flash.utils.Timer; public class ProgressBar extends Sprite { private var _backColor:uint; private var _fillColor:uint; private var _barWidth:Number; private var _barHeight:Number; private var _msg:TextSprite; private var _bar:Sprite; private var _back:Shape; private var _fill:Shape; private var _progress:Number = 0; public function get progress():Number { return _progress; } public function set progress(v:Number):void { v = isNaN(v) ? 0 : v; _progress = v; _fill.graphics.clear(); _fill.graphics.beginFill(_fillColor); _fill.graphics.drawRoundRect(0, 0, v*_barWidth, _barHeight, _barHeight, _barHeight); } public function get bar():Sprite { return _bar; } public function get message():TextSprite { return _msg; } public function ProgressBar(message:String="LOADING", w:Number=200, h:Number=6, fillColor:uint=0xff3333, backColor:uint=0xcccccc) { _fillColor = fillColor; _backColor = backColor; _barWidth = w; _barHeight = h; addChild(_bar = new Sprite()); addChild(_msg = new TextSprite(message)); _bar.addChild(_back = new Shape()); _bar.addChild(_fill = new Shape()); _back.graphics.beginFill(_backColor); _back.graphics.drawRoundRect(0, 0, _barWidth, _barHeight, _barHeight, _barHeight); _msg.font = "Verdana"; _msg.size = 18; _msg.color = _fillColor; _msg.letterSpacing = 2; _msg.y = 1.5 * _barHeight; } public function loadURL(ldr:URLLoader, onComplete:Function=null, onError:Function=null):URLLoader { var bar:ProgressBar = this; ldr.addEventListener(Event.COMPLETE, function(evt:Event):void { this.progress = 1; // set progress bar to complete var timer:Timer = new Timer(1000); timer.addEventListener(TimerEvent.TIMER, function(e:Event):void { timer.stop(); timer = null; try { if (onComplete!=null) onComplete(); } catch (err:Error) { error(err); return; } // remove progress bar if (parent) parent.removeChild(bar); }); timer.start(); }); ldr.addEventListener(ProgressEvent.PROGRESS, function(evt:ProgressEvent):void { bar.progress = evt.bytesLoaded / evt.bytesTotal; } ); var error:Function = function(e:Object=null):void { bar.message.text = "FAILED"; trace(e.toString()); if (onError!=null) onError(); }; ldr.addEventListener(IOErrorEvent.IO_ERROR, error); ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR, error); return ldr; } } // end of class ProgressBar }
package { import flare.display.TextSprite; import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.events.TimerEvent; import flash.net.URLLoader; import flash.utils.Timer; public class ProgressBar extends Sprite { private var _backColor:uint; private var _fillColor:uint; private var _barWidth:Number; private var _barHeight:Number; private var _msg:TextSprite; private var _bar:Sprite; private var _back:Shape; private var _fill:Shape; private var _progress:Number = 0; public function get progress():Number { return _progress; } public function set progress(v:Number):void { v = isNaN(v) ? 0 : v; _progress = v; _fill.graphics.clear(); _fill.graphics.beginFill(_fillColor); _fill.graphics.drawRoundRect(0, 0, v*_barWidth, _barHeight, _barHeight, _barHeight); } public function get bar():Sprite { return _bar; } public function get message():TextSprite { return _msg; } public function ProgressBar(message:String="LOADING", w:Number=200, h:Number=6, fillColor:uint=0xff3333, backColor:uint=0xcccccc) { _fillColor = fillColor; _backColor = backColor; _barWidth = w; _barHeight = h; addChild(_bar = new Sprite()); addChild(_msg = new TextSprite(message)); _bar.addChild(_back = new Shape()); _bar.addChild(_fill = new Shape()); _back.graphics.beginFill(_backColor); _back.graphics.drawRoundRect(0, 0, _barWidth, _barHeight, _barHeight, _barHeight); _msg.font = "Verdana"; _msg.size = 18; _msg.color = _fillColor; _msg.letterSpacing = 2; _msg.y = 1.5 * _barHeight; } public function loadURL(ldr:URLLoader, onComplete:Function=null, onError:Function=null):URLLoader { var bar:ProgressBar = this; ldr.addEventListener(Event.COMPLETE, function(evt:Event):void { this.progress = 1; // set progress bar to complete var timer:Timer = new Timer(1000); timer.addEventListener(TimerEvent.TIMER, function(e:Event):void { timer.stop(); timer = null; try { if (onComplete!=null) onComplete(); } catch (err:Error) { var stack_Trace:String = err.getStackTrace(); error(err); return; } // remove progress bar if (parent) parent.removeChild(bar); }); timer.start(); }); ldr.addEventListener(ProgressEvent.PROGRESS, function(evt:ProgressEvent):void { bar.progress = evt.bytesLoaded / evt.bytesTotal; } ); var error:Function = function(e:Object=null):void { bar.message.text = "FAILED"; trace(e.toString()); if (onError!=null) onError(); }; ldr.addEventListener(IOErrorEvent.IO_ERROR, error); ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR, error); return ldr; } } // end of class ProgressBar }
Add error message.
Add error message.
ActionScript
bsd-3-clause
berkmancenter/netmaps-visualization,berkmancenter/netmaps-visualization,berkmancenter/netmaps-visualization
43cc4fae1600c805db15d51033eb5f13a611c4cf
src/widgets/supportClasses/ResultAttributes.as
src/widgets/supportClasses/ResultAttributes.as
package widgets.supportClasses { import com.esri.ags.FeatureSet; import com.esri.ags.Graphic; import com.esri.ags.layers.FeatureLayer; import com.esri.ags.layers.supportClasses.CodedValue; import com.esri.ags.layers.supportClasses.CodedValueDomain; import com.esri.ags.layers.supportClasses.FeatureType; import com.esri.ags.layers.supportClasses.Field; import com.esri.ags.layers.supportClasses.LayerDetails; import mx.core.FlexGlobals; import mx.core.LayoutDirection; import mx.formatters.DateFormatter; [Bindable] public class ResultAttributes { public var attributes:Object; public var title:String; public var content:String; public var link:String; public var linkAlias:String; public static function toResultAttributes(fields:XMLList, graphic:Graphic = null, featureSet:FeatureSet = null, layer:FeatureLayer = null, layerDetails:LayerDetails = null, fallbackTitle:String = null, titleField:String = null, linkField:String = null, linkAlias:String = null):ResultAttributes { var resultAttributes:ResultAttributes = new ResultAttributes; var value:String = ""; var title:String = ""; var content:String = ""; var link:String = ""; var linkAlias:String; var fieldsXMLList:XMLList = fields ? fields.field : null; if (fields && fields[0].@all[0] == "true") { if (layerDetails.fields) { for each (var field:Field in layerDetails.fields) { if (field.name in graphic.attributes) { displayFields(field.name, getFieldXML(field.name, fieldsXMLList), field); } } } else { for (var fieldName:String in graphic.attributes) { displayFields(fieldName, getFieldXML(fieldName, fieldsXMLList), null); } } } else { for each (var fieldXML:XML in fieldsXMLList) // display the fields in the same order as specified { if (fieldXML.@name[0] in graphic.attributes) { displayFields(fieldXML.@name[0], fieldXML, getField(layer, fieldXML.@name[0])); } } } resultAttributes.attributes = graphic.attributes; resultAttributes.title = title ? title : fallbackTitle; resultAttributes.content = content.replace(/\n$/, ''); resultAttributes.link = link ? link : null; resultAttributes.linkAlias = linkAlias; function displayFields(fieldName:String, fieldXML:XML, field:Field):void { var fieldNameTextValue:String = graphic.attributes[fieldName]; value = fieldNameTextValue ? fieldNameTextValue : ""; if (value) { var isDateField:Boolean; var useUTC:Boolean; var dateFormat:String; if (fieldXML) { useUTC = fieldXML.format.@useutc[0] || fieldXML.@useutc[0] == "true"; dateFormat = fieldXML.format.@dateformat[0] || fieldXML.@dateformat[0]; if (dateFormat) { isDateField = true; } } if (!isDateField && field) { isDateField = field.type == Field.TYPE_DATE; } if (isDateField) { var dateMS:Number = Number(value); if (!isNaN(dateMS)) { value = msToDate(dateMS, dateFormat, useUTC); } } else { var typeID:String = layerDetails.typeIdField ? graphic.attributes[layerDetails.typeIdField] : null; if (fieldName == layerDetails.typeIdField) { var featureType:FeatureType = getFeatureType(layer, typeID); if (featureType && featureType.name) { value = featureType.name; } } else { var codedValue:CodedValue = getCodedValue(layer, fieldName, value, typeID); if (codedValue) { value = codedValue.name; } } } } if (titleField && fieldName.toUpperCase() == titleField.toUpperCase()) { title = value; } else if (linkField && fieldName.toUpperCase() == linkField.toUpperCase()) { link = value; linkAlias = linkAlias; } else if (fieldName.toUpperCase() != "SHAPE_LENGTH" && fieldName.toUpperCase() != "SHAPE_AREA") { var fieldLabel:String; if (fieldXML && fieldXML.@alias[0]) { fieldLabel = fieldXML.@alias[0]; } else { fieldLabel = featureSet.fieldAliases[fieldName]; } if (FlexGlobals.topLevelApplication.layoutDirection == LayoutDirection.RTL) { content += value + " :" + fieldLabel + "\n"; } else { content += fieldLabel + ": " + value + "\n"; } } } return resultAttributes; } private static function getFieldXML(fieldName:String, fields:XMLList):XML { var result:XML; for each (var fieldXML:XML in fields) { if (fieldName == fieldXML.@name[0]) { result = fieldXML; break; } } return result; } private static function getField(layer:FeatureLayer, fieldName:String):Field { var result:Field; if (layer) { for each (var field:Field in layer.layerDetails.fields) { if (fieldName == field.name) { result = field; break; } } } return result; } private static function getFeatureType(layer:FeatureLayer, typeID:String):FeatureType { var result:FeatureType; if (layer) { for each (var featureType:FeatureType in layer.layerDetails.types) { if (typeID == featureType.id) { result = featureType; break; } } } return result; } private static function msToDate(ms:Number, dateFormat:String, useUTC:Boolean):String { var date:Date = new Date(ms); if (date.milliseconds == 999) // workaround for REST bug { date.milliseconds++; } if (useUTC) { date.minutes += date.timezoneOffset; } if (dateFormat) { var dateFormatter:DateFormatter = new DateFormatter(); dateFormatter.formatString = dateFormat; var result:String = dateFormatter.format(date); if (result) { return result; } else { return dateFormatter.error; } } else { return date.toLocaleString(); } } private static function getCodedValue(layer:FeatureLayer, fieldName:String, fieldValue:String, typeID:String):CodedValue { var result:CodedValue; var codedValueDomain:CodedValueDomain; if (typeID) { var featureType:FeatureType = getFeatureType(layer, typeID); if (featureType) { codedValueDomain = featureType.domains[fieldName] as CodedValueDomain; } } else { var field:Field = getField(layer, fieldName); if (field) { codedValueDomain = field.domain as CodedValueDomain; } } if (codedValueDomain) { for each (var codedValue:CodedValue in codedValueDomain.codedValues) { if (fieldValue == codedValue.code) { result = codedValue; break; } } } return result; } } }
package widgets.supportClasses { import com.esri.ags.FeatureSet; import com.esri.ags.Graphic; import com.esri.ags.layers.FeatureLayer; import com.esri.ags.layers.supportClasses.CodedValue; import com.esri.ags.layers.supportClasses.CodedValueDomain; import com.esri.ags.layers.supportClasses.FeatureType; import com.esri.ags.layers.supportClasses.Field; import com.esri.ags.layers.supportClasses.LayerDetails; import mx.core.FlexGlobals; import mx.core.LayoutDirection; import mx.formatters.DateFormatter; [Bindable] public class ResultAttributes { public var attributes:Object; public var title:String; public var content:String; public var link:String; public var linkAlias:String; public static function toResultAttributes(fields:XMLList, graphic:Graphic = null, featureSet:FeatureSet = null, layer:FeatureLayer = null, layerDetails:LayerDetails = null, fallbackTitle:String = null, titleField:String = null, linkField:String = null, linkAlias:String = null):ResultAttributes { var resultAttributes:ResultAttributes = new ResultAttributes; var value:String = ""; var title:String = ""; var content:String = ""; var link:String = ""; var linkAlias:String; var fieldsXMLList:XMLList = fields ? fields.field : null; if (fields && fields[0].@all[0] == "true") { if (layerDetails.fields) { for each (var field:Field in layerDetails.fields) { if (field.name in graphic.attributes) { displayFields(field.name, getFieldXML(field.name, fieldsXMLList), field); } } } else { for (var fieldName:String in graphic.attributes) { displayFields(fieldName, getFieldXML(fieldName, fieldsXMLList), null); } } } else { for each (var fieldXML:XML in fieldsXMLList) // display the fields in the same order as specified { if (fieldXML.@name[0] in graphic.attributes) { displayFields(fieldXML.@name[0], fieldXML, getField(layer, fieldXML.@name[0])); } } } resultAttributes.attributes = graphic.attributes; resultAttributes.title = title ? title : fallbackTitle; resultAttributes.content = content.replace(/\n$/, ''); resultAttributes.link = link ? link : null; resultAttributes.linkAlias = linkAlias; function displayFields(fieldName:String, fieldXML:XML, field:Field):void { var fieldNameTextValue:String = graphic.attributes[fieldName]; value = fieldNameTextValue ? fieldNameTextValue : ""; if (value) { var isDateField:Boolean; var useUTC:Boolean; var dateFormat:String; if (fieldXML) { useUTC = fieldXML.format.@useutc[0] == "true" || fieldXML.@useutc[0] == "true"; dateFormat = fieldXML.format.@dateformat[0] || fieldXML.@dateformat[0]; if (dateFormat) { isDateField = true; } } if (!isDateField && field) { isDateField = field.type == Field.TYPE_DATE; } if (isDateField) { var dateMS:Number = Number(value); if (!isNaN(dateMS)) { value = msToDate(dateMS, dateFormat, useUTC); } } else { var typeID:String = layerDetails.typeIdField ? graphic.attributes[layerDetails.typeIdField] : null; if (fieldName == layerDetails.typeIdField) { var featureType:FeatureType = getFeatureType(layer, typeID); if (featureType && featureType.name) { value = featureType.name; } } else { var codedValue:CodedValue = getCodedValue(layer, fieldName, value, typeID); if (codedValue) { value = codedValue.name; } } } } if (titleField && fieldName.toUpperCase() == titleField.toUpperCase()) { title = value; } else if (linkField && fieldName.toUpperCase() == linkField.toUpperCase()) { link = value; linkAlias = linkAlias; } else if (fieldName.toUpperCase() != "SHAPE_LENGTH" && fieldName.toUpperCase() != "SHAPE_AREA") { var fieldLabel:String; if (fieldXML && fieldXML.@alias[0]) { fieldLabel = fieldXML.@alias[0]; } else { fieldLabel = featureSet.fieldAliases[fieldName]; } if (FlexGlobals.topLevelApplication.layoutDirection == LayoutDirection.RTL) { content += value + " :" + fieldLabel + "\n"; } else { content += fieldLabel + ": " + value + "\n"; } } } return resultAttributes; } private static function getFieldXML(fieldName:String, fields:XMLList):XML { var result:XML; for each (var fieldXML:XML in fields) { if (fieldName == fieldXML.@name[0]) { result = fieldXML; break; } } return result; } private static function getField(layer:FeatureLayer, fieldName:String):Field { var result:Field; if (layer) { for each (var field:Field in layer.layerDetails.fields) { if (fieldName == field.name) { result = field; break; } } } return result; } private static function getFeatureType(layer:FeatureLayer, typeID:String):FeatureType { var result:FeatureType; if (layer) { for each (var featureType:FeatureType in layer.layerDetails.types) { if (typeID == featureType.id) { result = featureType; break; } } } return result; } private static function msToDate(ms:Number, dateFormat:String, useUTC:Boolean):String { var date:Date = new Date(ms); if (date.milliseconds == 999) // workaround for REST bug { date.milliseconds++; } if (useUTC) { date.minutes += date.timezoneOffset; } if (dateFormat) { var dateFormatter:DateFormatter = new DateFormatter(); dateFormatter.formatString = dateFormat; var result:String = dateFormatter.format(date); if (result) { return result; } else { return dateFormatter.error; } } else { return date.toLocaleString(); } } private static function getCodedValue(layer:FeatureLayer, fieldName:String, fieldValue:String, typeID:String):CodedValue { var result:CodedValue; var codedValueDomain:CodedValueDomain; if (typeID) { var featureType:FeatureType = getFeatureType(layer, typeID); if (featureType) { codedValueDomain = featureType.domains[fieldName] as CodedValueDomain; } } else { var field:Field = getField(layer, fieldName); if (field) { codedValueDomain = field.domain as CodedValueDomain; } } if (codedValueDomain) { for each (var codedValue:CodedValue in codedValueDomain.codedValues) { if (fieldValue == codedValue.code) { result = codedValue; break; } } } return result; } } }
Fix ResultAttributes useUTC assignment.
Fix ResultAttributes useUTC assignment.
ActionScript
apache-2.0
Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex
f03caf98fefc6c5de64c9ff3f19961a5920d69ba
src/as/com/threerings/util/SortedHashMap.as
src/as/com/threerings/util/SortedHashMap.as
// // $Id: HashMap.as 4848 2007-10-18 23:55:26Z ray $ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { /** * Guarantees a specific iteration order for keys(), values(), and forEach() with as little * additional overhead as possible. */ public class SortedHashMap extends HashMap { public static const COMPARABLE_KEYS :int = 0; public static const STRING_KEYS :int = 1; public static const NUMERIC_KEYS :int = 2; public function SortedHashMap ( keyType :int, loadFactor :Number = 1.75, equalsFn :Function = null, hashFn :Function = null) { super(loadFactor, equalsFn, hashFn); _keyType = keyType; } override public function put (key :Object, value :Object) :* { validateKey(key); return super.put(key, value); } override public function keys () :Array { var keys :Array = super.keys(); switch (_keyType) { case COMPARABLE_KEYS: ArrayUtil.sort(keys); break; case STRING_KEYS: default: keys.sort(); break; case NUMERIC_KEYS: keys.sort(Array.NUMERIC); break; } return keys; } override public function values () :Array { // not very optimal, we need to look up each value from the sorted keys. return keys().map(function (key :Object, ... rest) :Object { return get(key); }); } override public function forEach (fn :Function) :void { var keys :Array = keys(); for each (var key :Object in keys) { fn(key, get(key)); } } protected function validateKey (key :Object) :void // throws ArgumentError { if (key == null) { return; } switch (_keyType) { case COMPARABLE_KEYS: if (key is Comparable) { return; } break; case STRING_KEYS: if (key is String) { return; } break; case NUMERIC_KEYS: if (key is Number) { return; } break; default: // there is no return break; } throw new ArgumentError("Invalid key"); } /** The key type in use for this map. */ protected var _keyType :int; } }
// // $Id: HashMap.as 4848 2007-10-18 23:55:26Z ray $ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { /** * Guarantees a specific iteration order for keys(), values(), and forEach() with as little * additional overhead as possible. */ public class SortedHashMap extends HashMap { public static const COMPARABLE_KEYS :int = 0; public static const STRING_KEYS :int = 1; public static const NUMERIC_KEYS :int = 2; public function SortedHashMap ( keyType :int, loadFactor :Number = 1.75, equalsFn :Function = null, hashFn :Function = null) { super(loadFactor, equalsFn, hashFn); _keyType = keyType; } override public function put (key :Object, value :Object) :* { validateKey(key); return super.put(key, value); } override public function keys () :Array { var keys :Array = super.keys(); switch (_keyType) { case COMPARABLE_KEYS: ArrayUtil.sort(keys); break; case STRING_KEYS: default: keys.sort(); break; case NUMERIC_KEYS: keys.sort(Array.NUMERIC); break; } return keys; } override public function values () :Array { // not very optimal, we need to look up each value from the sorted keys. return keys().map(Util.adapt(get)); } override public function forEach (fn :Function) :void { var keys :Array = keys(); for each (var key :Object in keys) { fn(key, get(key)); } } protected function validateKey (key :Object) :void // throws ArgumentError { if (key == null) { return; } switch (_keyType) { case COMPARABLE_KEYS: if (key is Comparable) { return; } break; case STRING_KEYS: if (key is String) { return; } break; case NUMERIC_KEYS: if (key is Number) { return; } break; default: // there is no return break; } throw new ArgumentError("Invalid key"); } /** The key type in use for this map. */ protected var _keyType :int; } }
Use Util.adapt(). Look at this functional programming masterpiece. I'm not sure how much actual utility is here, and how much I just like the gee-whiz factor.
Use Util.adapt(). Look at this functional programming masterpiece. I'm not sure how much actual utility is here, and how much I just like the gee-whiz factor. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5731 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
d1044e9601b3390afe5d13a1f5e304c846e85b4b
exporter/src/main/as/flump/xfl/XflLibrary.as
exporter/src/main/as/flump/xfl/XflLibrary.as
// // Flump - Copyright 2013 Flump Authors package flump.xfl { import flash.filesystem.File; import flash.utils.ByteArray; import flash.utils.Dictionary; import com.adobe.crypto.MD5; import flump.SwfTexture; import flump.Util; import flump.executor.Executor; import flump.executor.Future; import flump.executor.FutureTask; import flump.executor.load.LoadedSwf; import flump.executor.load.SwfLoader; import flump.export.Atlas; import flump.export.ExportConf; import flump.export.Files; import flump.mold.KeyframeMold; import flump.mold.LayerMold; import flump.mold.LibraryMold; import flump.mold.MovieMold; import flump.mold.TextureGroupMold; import com.threerings.util.Log; import com.threerings.util.Map; import com.threerings.util.Maps; import com.threerings.util.Set; import com.threerings.util.Sets; import com.threerings.util.XmlUtil; public class XflLibrary { use namespace xflns; /** * When an exported movie contains an unexported movie, it gets assigned a generated symbol * name with this prefix. */ public static const IMPLICIT_PREFIX :String = "~"; public var swf :LoadedSwf; public var frameRate :Number; public var backgroundColor :int; // The MD5 of the published library SWF public var md5 :String; public var location :String; public const movies :Vector.<MovieMold> = new <MovieMold>[]; public const textures :Vector.<XflTexture> = new <XflTexture>[]; public function XflLibrary (location :String) { this.location = location; } public function getItem (id :String, requiredType :Class=null) :* { const result :* = _idToItem[id]; if (result === undefined) throw new Error("Unknown library item '" + id + "'"); else if (requiredType != null) return requiredType(result); else return result; } public function isExported (movie :MovieMold) :Boolean { return _moldToSymbol.containsKey(movie); } public function get publishedMovies () :Vector.<MovieMold> { const result :Vector.<MovieMold> = new <MovieMold>[]; for each (var movie :MovieMold in _toPublish.toArray().sortOn("id")) result.push(movie); return result; } public function finishLoading () :void { var movie :MovieMold = null; // Parse all un-exported movies that are referenced by the exported movies. for (var ii :int = 0; ii < movies.length; ++ii) { movie = movies[ii]; for each (var symbolName :String in XflMovie.getSymbolNames(movie).toArray()) { var xml :XML = _unexportedMovies.remove(symbolName); if (xml != null) parseMovie(xml); } } for each (movie in movies) if (isExported(movie)) prepareForPublishing(movie); } protected function prepareForPublishing (movie :MovieMold) :void { if (!_toPublish.add(movie) || movie.flipbook) return; for each (var layer :LayerMold in movie.layers) { for each (var kf :KeyframeMold in layer.keyframes) { if (kf.ref == null) continue; kf.ref = _libraryNameToId.get(kf.ref); var item :Object = _idToItem[kf.ref]; if (item == null) { addTopLevelError(ParseError.CRIT, "unrecognized library item '" + kf.ref + "'"); } else if (item is MovieMold) { prepareForPublishing(MovieMold(item)); } else if (item is XflTexture) { // Texture symbols have origins. For texture layer keyframes, // we combine the texture's origin with the keyframe's pivot point. var tex :SwfTexture = SwfTexture.fromTexture(this.swf, XflTexture(item)); kf.pivotX += tex.origin.x; kf.pivotY += tex.origin.y; } } } } public function createId (item :Object, libraryName :String, symbol :String) :String { if (symbol != null) _moldToSymbol.put(item, symbol); const id :String = symbol == null ? IMPLICIT_PREFIX + libraryName : symbol; _libraryNameToId.put(libraryName, id); _idToItem[id] = item; return id; } public function getErrors (sev :String=null) :Vector.<ParseError> { if (sev == null) return _errors; const sevOrdinal :int = ParseError.severityToOrdinal(sev); return _errors.filter(function (err :ParseError, ..._) :Boolean { return err.sevOrdinal >= sevOrdinal; }); } public function get valid () :Boolean { return getErrors(ParseError.CRIT).length == 0; } public function addTopLevelError (severity :String, message :String, e :Object=null) :void { addError(location, severity, message, e); } public function addError (location :String, severity :String, message :String, e :Object=null) :void { _errors.push(new ParseError(location, severity, message, e)); } public function toJSONString (atlases :Vector.<Atlas>, conf :ExportConf, pretty :Boolean=false) :String { return JSON.stringify(toMold(atlases, conf), null, pretty ? " " : null); } public function toMold (atlases :Vector.<Atlas>, conf :ExportConf) :LibraryMold { const mold :LibraryMold = new LibraryMold(); mold.frameRate = frameRate; mold.md5 = md5; mold.movies = publishedMovies.map(function (movie :MovieMold, ..._) :MovieMold { return movie.scale(conf.scale); }); mold.textureGroups = createTextureGroupMolds(atlases); return mold; } public function loadSWF (path :String, loader :Executor=null) :Future { const onComplete :FutureTask = new FutureTask(); const swfFile :File = new File(path); const loadSwfFile :Future = Files.load(swfFile, loader); loadSwfFile.succeeded.add(function (data :ByteArray) :void { md5 = MD5.hashBytes(data); const loadSwf :Future = new SwfLoader().loadFromBytes(data); loadSwf.succeeded.add(function (loadedSwf :LoadedSwf) :void { swf = loadedSwf; }); loadSwf.failed.add(function (error :Error) :void { addTopLevelError(ParseError.CRIT, error.message, error); }); loadSwf.completed.add(onComplete.succeed); }); loadSwfFile.failed.add(function (error :Error) :void { addTopLevelError(ParseError.CRIT, error.message, error); onComplete.fail(error); }); return onComplete; } /** * @returns A list of paths to symbols in this library. */ public function parseDocumentFile (fileData :ByteArray, path :String) :Vector.<String> { const xml :XML = Util.bytesToXML(fileData); frameRate = XmlUtil.getNumberAttr(xml, "frameRate", 24); const hex :String = XmlUtil.getStringAttr(xml, "backgroundColor", "#ffffff"); backgroundColor = parseInt(hex.substr(1), 16); if (xml.media != null) { for each (var bitmap :XML in xml.media.DOMBitmapItem) { if (XmlUtil.getBooleanAttr(bitmap, "linkageExportForAS", false)) { textures.push(new XflTexture(this, location, bitmap)); } } } const paths :Vector.<String> = new <String>[]; if (xml.symbols != null) { for each (var symbolXmlPath :XML in xml.symbols.Include) { paths.push("LIBRARY/" + XmlUtil.getStringAttr(symbolXmlPath, "href")); } } return paths; } public function parseLibraryFile (fileData :ByteArray, path :String) :void { const xml :XML = Util.bytesToXML(fileData); if (xml.name().localName != "DOMSymbolItem") { addTopLevelError(ParseError.DEBUG, "Skipping file since its root element isn't DOMSymbolItem"); return; } else if (XmlUtil.getStringAttr(xml, "symbolType", "") == "graphic") { addTopLevelError(ParseError.DEBUG, "Skipping file because symbolType=graphic"); return; } const isSprite :Boolean = XmlUtil.getBooleanAttr(xml, "isSpriteSubclass", false); log.debug("Parsing for library", "file", path, "isSprite", isSprite); try { if (isSprite) { // if "export in first frame" is not set, we won't be able to load the texture // from the swf. // TODO: remove this restriction by loading the entire swf before reading textures? if (!XmlUtil.getBooleanAttr(xml, "linkageExportInFirstFrame", true)) { addError(location + ":" + XmlUtil.getStringAttr(xml, "linkageClassName"), ParseError.CRIT, "\"Export in frame 1\" must be set"); return; } var texture :XflTexture = new XflTexture(this, location, xml); if (texture.isValid(swf)) textures.push(texture); else addError(location + ":" + texture.symbol, ParseError.CRIT, "Sprite is empty"); } else { // It's a movie. If it's exported, we parse it now. // Else, we save it for possible parsing later. // (Un-exported movies that are not referenced will not be published.) if (XflMovie.isExported(xml)) parseMovie(xml); else _unexportedMovies.put(XflMovie.getName(xml), xml); } } catch (e :Error) { var type :String = isSprite ? "sprite" : "movie"; addTopLevelError(ParseError.CRIT, "Unable to parse " + type + " in " + path, e); log.error("Unable to parse " + path, e); } } protected function parseMovie (xml :XML) :void { movies.push(XflMovie.parse(this, xml)); } /** Creates TextureGroupMolds from a list of Atlases */ protected static function createTextureGroupMolds (atlases :Vector.<Atlas>) :Vector.<TextureGroupMold> { const groups :Vector.<TextureGroupMold> = new <TextureGroupMold>[]; function getGroup (scaleFactor :int) :TextureGroupMold { for each (var group :TextureGroupMold in groups) { if (group.scaleFactor == scaleFactor) { return group; } } group = new TextureGroupMold(); group.scaleFactor = scaleFactor; groups.push(group); return group; } for each (var atlas :Atlas in atlases) { var group :TextureGroupMold = getGroup(atlas.scaleFactor); group.atlases.push(atlas.toMold()); } return groups; } /** Library name to XML for movies in the XFL that are not marked for export */ protected const _unexportedMovies :Map = Maps.newMapOf(String); /** Object to symbol name for all exported textures and movies in the library */ protected const _moldToSymbol :Map = Maps.newMapOf(Object); /** Library name to symbol or generated symbol for all textures and movies in the library */ protected const _libraryNameToId :Map = Maps.newMapOf(String); /** Exported movies or movies used in exported movies. */ protected const _toPublish :Set = Sets.newSetOf(MovieMold); /** Symbol or generated symbol to texture or movie. */ protected const _idToItem :Dictionary = new Dictionary(); protected const _errors :Vector.<ParseError> = new <ParseError>[]; private static const log :Log = Log.getLog(XflLibrary); } }
// // Flump - Copyright 2013 Flump Authors package flump.xfl { import flash.filesystem.File; import flash.utils.ByteArray; import flash.utils.Dictionary; import com.adobe.crypto.MD5; import flump.SwfTexture; import flump.Util; import flump.executor.Executor; import flump.executor.Future; import flump.executor.FutureTask; import flump.executor.load.LoadedSwf; import flump.executor.load.SwfLoader; import flump.export.Atlas; import flump.export.ExportConf; import flump.export.Files; import flump.mold.KeyframeMold; import flump.mold.LayerMold; import flump.mold.LibraryMold; import flump.mold.MovieMold; import flump.mold.TextureGroupMold; import com.threerings.util.Log; import com.threerings.util.Map; import com.threerings.util.Maps; import com.threerings.util.Set; import com.threerings.util.Sets; import com.threerings.util.XmlUtil; public class XflLibrary { use namespace xflns; /** * When an exported movie contains an unexported movie, it gets assigned a generated symbol * name with this prefix. */ public static const IMPLICIT_PREFIX :String = "~"; public var swf :LoadedSwf; public var frameRate :Number; public var backgroundColor :int; // The MD5 of the published library SWF public var md5 :String; public var location :String; public const movies :Vector.<MovieMold> = new <MovieMold>[]; public const textures :Vector.<XflTexture> = new <XflTexture>[]; public function XflLibrary (location :String) { this.location = location; } public function getItem (id :String, requiredType :Class=null) :* { const result :* = _idToItem[id]; if (result === undefined) throw new Error("Unknown library item '" + id + "'"); else if (requiredType != null) return requiredType(result); else return result; } public function isExported (movie :MovieMold) :Boolean { return _moldToSymbol.containsKey(movie); } public function get publishedMovies () :Vector.<MovieMold> { const result :Vector.<MovieMold> = new <MovieMold>[]; for each (var movie :MovieMold in _toPublish.toArray().sortOn("id")) result.push(movie); return result; } public function finishLoading () :void { var movie :MovieMold = null; // Parse all un-exported movies that are referenced by the exported movies. for (var ii :int = 0; ii < movies.length; ++ii) { movie = movies[ii]; for each (var symbolName :String in XflMovie.getSymbolNames(movie).toArray()) { var xml :XML = _unexportedMovies.remove(symbolName); if (xml != null) parseMovie(xml); } } for each (movie in movies) if (isExported(movie)) prepareForPublishing(movie); } protected function prepareForPublishing (movie :MovieMold) :void { if (!_toPublish.add(movie)) return; for each (var layer :LayerMold in movie.layers) { for each (var kf :KeyframeMold in layer.keyframes) { function adjustPivot (tex :SwfTexture) :void { // Texture symbols have origins. For texture layer keyframes, // we combine the texture's origin with the keyframe's pivot point. kf.pivotX += tex.origin.x; kf.pivotY += tex.origin.y; }; if (movie.flipbook) { adjustPivot(SwfTexture.fromFlipbook(this, movie, kf.index)); } else { if (kf.ref == null) continue; kf.ref = _libraryNameToId.get(kf.ref); var item :Object = _idToItem[kf.ref]; if (item == null) { addTopLevelError(ParseError.CRIT, "unrecognized library item '" + kf.ref + "'"); } else if (item is MovieMold) { prepareForPublishing(MovieMold(item)); } else if (item is XflTexture) { adjustPivot(SwfTexture.fromTexture(this.swf, XflTexture(item))); } } } } } public function createId (item :Object, libraryName :String, symbol :String) :String { if (symbol != null) _moldToSymbol.put(item, symbol); const id :String = symbol == null ? IMPLICIT_PREFIX + libraryName : symbol; _libraryNameToId.put(libraryName, id); _idToItem[id] = item; return id; } public function getErrors (sev :String=null) :Vector.<ParseError> { if (sev == null) return _errors; const sevOrdinal :int = ParseError.severityToOrdinal(sev); return _errors.filter(function (err :ParseError, ..._) :Boolean { return err.sevOrdinal >= sevOrdinal; }); } public function get valid () :Boolean { return getErrors(ParseError.CRIT).length == 0; } public function addTopLevelError (severity :String, message :String, e :Object=null) :void { addError(location, severity, message, e); } public function addError (location :String, severity :String, message :String, e :Object=null) :void { _errors.push(new ParseError(location, severity, message, e)); } public function toJSONString (atlases :Vector.<Atlas>, conf :ExportConf, pretty :Boolean=false) :String { return JSON.stringify(toMold(atlases, conf), null, pretty ? " " : null); } public function toMold (atlases :Vector.<Atlas>, conf :ExportConf) :LibraryMold { const mold :LibraryMold = new LibraryMold(); mold.frameRate = frameRate; mold.md5 = md5; mold.movies = publishedMovies.map(function (movie :MovieMold, ..._) :MovieMold { return movie.scale(conf.scale); }); mold.textureGroups = createTextureGroupMolds(atlases); return mold; } public function loadSWF (path :String, loader :Executor=null) :Future { const onComplete :FutureTask = new FutureTask(); const swfFile :File = new File(path); const loadSwfFile :Future = Files.load(swfFile, loader); loadSwfFile.succeeded.add(function (data :ByteArray) :void { md5 = MD5.hashBytes(data); const loadSwf :Future = new SwfLoader().loadFromBytes(data); loadSwf.succeeded.add(function (loadedSwf :LoadedSwf) :void { swf = loadedSwf; }); loadSwf.failed.add(function (error :Error) :void { addTopLevelError(ParseError.CRIT, error.message, error); }); loadSwf.completed.add(onComplete.succeed); }); loadSwfFile.failed.add(function (error :Error) :void { addTopLevelError(ParseError.CRIT, error.message, error); onComplete.fail(error); }); return onComplete; } /** * @returns A list of paths to symbols in this library. */ public function parseDocumentFile (fileData :ByteArray, path :String) :Vector.<String> { const xml :XML = Util.bytesToXML(fileData); frameRate = XmlUtil.getNumberAttr(xml, "frameRate", 24); const hex :String = XmlUtil.getStringAttr(xml, "backgroundColor", "#ffffff"); backgroundColor = parseInt(hex.substr(1), 16); if (xml.media != null) { for each (var bitmap :XML in xml.media.DOMBitmapItem) { if (XmlUtil.getBooleanAttr(bitmap, "linkageExportForAS", false)) { textures.push(new XflTexture(this, location, bitmap)); } } } const paths :Vector.<String> = new <String>[]; if (xml.symbols != null) { for each (var symbolXmlPath :XML in xml.symbols.Include) { paths.push("LIBRARY/" + XmlUtil.getStringAttr(symbolXmlPath, "href")); } } return paths; } public function parseLibraryFile (fileData :ByteArray, path :String) :void { const xml :XML = Util.bytesToXML(fileData); if (xml.name().localName != "DOMSymbolItem") { addTopLevelError(ParseError.DEBUG, "Skipping file since its root element isn't DOMSymbolItem"); return; } else if (XmlUtil.getStringAttr(xml, "symbolType", "") == "graphic") { addTopLevelError(ParseError.DEBUG, "Skipping file because symbolType=graphic"); return; } const isSprite :Boolean = XmlUtil.getBooleanAttr(xml, "isSpriteSubclass", false); log.debug("Parsing for library", "file", path, "isSprite", isSprite); try { if (isSprite) { // if "export in first frame" is not set, we won't be able to load the texture // from the swf. // TODO: remove this restriction by loading the entire swf before reading textures? if (!XmlUtil.getBooleanAttr(xml, "linkageExportInFirstFrame", true)) { addError(location + ":" + XmlUtil.getStringAttr(xml, "linkageClassName"), ParseError.CRIT, "\"Export in frame 1\" must be set"); return; } var texture :XflTexture = new XflTexture(this, location, xml); if (texture.isValid(swf)) textures.push(texture); else addError(location + ":" + texture.symbol, ParseError.CRIT, "Sprite is empty"); } else { // It's a movie. If it's exported, we parse it now. // Else, we save it for possible parsing later. // (Un-exported movies that are not referenced will not be published.) if (XflMovie.isExported(xml)) parseMovie(xml); else _unexportedMovies.put(XflMovie.getName(xml), xml); } } catch (e :Error) { var type :String = isSprite ? "sprite" : "movie"; addTopLevelError(ParseError.CRIT, "Unable to parse " + type + " in " + path, e); log.error("Unable to parse " + path, e); } } protected function parseMovie (xml :XML) :void { movies.push(XflMovie.parse(this, xml)); } /** Creates TextureGroupMolds from a list of Atlases */ protected static function createTextureGroupMolds (atlases :Vector.<Atlas>) :Vector.<TextureGroupMold> { const groups :Vector.<TextureGroupMold> = new <TextureGroupMold>[]; function getGroup (scaleFactor :int) :TextureGroupMold { for each (var group :TextureGroupMold in groups) { if (group.scaleFactor == scaleFactor) { return group; } } group = new TextureGroupMold(); group.scaleFactor = scaleFactor; groups.push(group); return group; } for each (var atlas :Atlas in atlases) { var group :TextureGroupMold = getGroup(atlas.scaleFactor); group.atlases.push(atlas.toMold()); } return groups; } /** Library name to XML for movies in the XFL that are not marked for export */ protected const _unexportedMovies :Map = Maps.newMapOf(String); /** Object to symbol name for all exported textures and movies in the library */ protected const _moldToSymbol :Map = Maps.newMapOf(Object); /** Library name to symbol or generated symbol for all textures and movies in the library */ protected const _libraryNameToId :Map = Maps.newMapOf(String); /** Exported movies or movies used in exported movies. */ protected const _toPublish :Set = Sets.newSetOf(MovieMold); /** Symbol or generated symbol to texture or movie. */ protected const _idToItem :Dictionary = new Dictionary(); protected const _errors :Vector.<ParseError> = new <ParseError>[]; private static const log :Log = Log.getLog(XflLibrary); } }
Apply the keyframe pivot to flipbooks too.
Apply the keyframe pivot to flipbooks too. Fixes #36. @tconkling, could you please verify and do an exporter release?
ActionScript
mit
funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump
8ac757c4f635cd40ed8becee61cb91ded2907373
fp10/src/as3isolib/display/scene/IsoScene.as
fp10/src/as3isolib/display/scene/IsoScene.as
/* as3isolib - An open-source ActionScript 3.0 Isometric Library developed to assist in creating isometrically projected content (such as games and graphics) targeted for the Flash player platform http://code.google.com/p/as3isolib/ Copyright (c) 2006 - 2008 J.W.Opitz, All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package as3isolib.display.scene { import as3isolib.bounds.IBounds; import as3isolib.bounds.SceneBounds; import as3isolib.core.IIsoDisplayObject; import as3isolib.core.IsoContainer; import as3isolib.core.as3isolib_internal; import as3isolib.data.INode; import as3isolib.display.renderers.DefaultSceneLayoutRenderer; import as3isolib.display.renderers.ISceneLayoutRenderer; import as3isolib.display.renderers.ISceneRenderer; import as3isolib.events.IsoEvent; import flash.display.DisplayObjectContainer; import mx.core.ClassFactory; import mx.core.IFactory; use namespace as3isolib_internal; /** * IsoScene is a base class for grouping and rendering IIsoDisplayObject children according to their isometric position-based depth. */ public class IsoScene extends IsoContainer implements IIsoScene { /////////////////////////////////////////////////////////////////////////////// // BOUNDS /////////////////////////////////////////////////////////////////////////////// /** * @private */ private var _isoBounds:IBounds; /** * @inheritDoc */ public function get isoBounds ():IBounds { /* if (!_isoBounds || isInvalidated) _isoBounds = */ return new SceneBounds(this); } /////////////////////////////////////////////////////////////////////////////// // HOST CONTAINER /////////////////////////////////////////////////////////////////////////////// /** * @private */ protected var host:DisplayObjectContainer; as3isolib_internal /** * @private */ public function get hostContainer ():DisplayObjectContainer { return host; } /** * @inheritDoc */ public function set hostContainer (value:DisplayObjectContainer):void { if (value && host != value) { if (host && host.contains(container)) { host.removeChild(container); ownerObject = null; } else if (hasParent) parent.removeChild(this); host = value; if (host) { host.addChild(container); ownerObject = host; parentNode = null; } } } /////////////////////////////////////////////////////////////////////////////// // INVALIDATE CHILDREN /////////////////////////////////////////////////////////////////////////////// /** * @private * * Array of invalidated children. Each child dispatches an IsoEvent.INVALIDATION event which notifies * the scene that that particular child is invalidated and subsequentally the scene is also invalidated. */ protected var invalidatedChildrenArray:Array = []; /** * @inheritDoc */ public function get invalidatedChildren ():Array { return invalidatedChildrenArray; } /////////////////////////////////////////////////////////////////////////////// // OVERRIDES /////////////////////////////////////////////////////////////////////////////// /** * @inheritDoc */ override public function addChildAt (child:INode, index:uint):void { if (child is IIsoDisplayObject) { super.addChildAt(child, index); child.addEventListener(IsoEvent.INVALIDATE, child_invalidateHandler); bIsInvalidated = true; //since the child most likely had fired an invalidation event prior to being added, manually invalidate the scene } else throw new Error ("parameter child is not of type IIsoDisplayObject"); } /** * @inheritDoc */ override public function setChildIndex (child:INode, index:uint):void { super.setChildIndex(child, index); bIsInvalidated = true; } /** * @inheritDoc */ override public function removeChildByID (id:String):INode { var child:INode = super.removeChildByID(id); if (child) { child.removeEventListener(IsoEvent.INVALIDATE, child_invalidateHandler); bIsInvalidated = true; } return child; } /** * @inheritDoc */ override public function removeAllChildren ():void { var child:INode for each (child in children) child.removeEventListener(IsoEvent.INVALIDATE, child_invalidateHandler); super.removeAllChildren(); bIsInvalidated = true; } /** * Renders the scene as invalidated if a child object is invalidated. * * @param evt The IsoEvent dispatched from the invalidated child. */ protected function child_invalidateHandler (evt:IsoEvent):void { var child:Object = evt.target; if (invalidatedChildrenArray.indexOf(child) == -1) invalidatedChildrenArray.push(child); bIsInvalidated = true; } /////////////////////////////////////////////////////////////////////////////// // LAYOUT RENDERER /////////////////////////////////////////////////////////////////////////////// /** * Flags the scene for possible layout rendering. * If false, child objects are sorted by the order they were added rather than by their isometric depth. */ public var layoutEnabled:Boolean = true; private var layoutRendererFactory:IFactory; /** * @private */ public function get layoutRenderer ():IFactory { return layoutRendererFactory; } /** * The factory used to create the ISceneLayoutRenderer responsible for the layout of the child objects. */ public function set layoutRenderer (value:IFactory):void { if (value && layoutRendererFactory != value) { layoutRendererFactory = value; bIsInvalidated = true; } } /////////////////////////////////////////////////////////////////////////////// // STYLE RENDERERS /////////////////////////////////////////////////////////////////////////////// /** * Flags the scene for possible style rendering. */ public var stylingEnabled:Boolean = true; private var styleRendererFactories:Array = []; /** * @private */ public function get styleRenderers ():Array { return styleRendererFactories; } /** * An array of IFactories whose class generators are ISceneRenderer. * If any value contained within the array is not of type IFactory, it will be ignored. */ public function set styleRenderers (value:Array):void { if (value) { var temp:Array = []; var obj:Object; for each (obj in value) { if (obj is IFactory) temp.push(obj); } styleRendererFactories = temp; bIsInvalidated = true; } } /////////////////////////////////////////////////////////////////////////////// // INVALIDATION /////////////////////////////////////////////////////////////////////////////// /** * Flags the scene as invalidated during the rendering process */ public function invalidateScene ():void { bIsInvalidated = true; } /////////////////////////////////////////////////////////////////////////////// // RENDER /////////////////////////////////////////////////////////////////////////////// /** * @inheritDoc */ override protected function renderLogic (recursive:Boolean = true):void { super.renderLogic(recursive); //push individual changes thru, then sort based on new visible content of each child if (bIsInvalidated) { //render the layout first var sceneLayoutRenderer:ISceneLayoutRenderer; if (layoutEnabled) { sceneLayoutRenderer = layoutRendererFactory.newInstance(); if (sceneLayoutRenderer) sceneLayoutRenderer.renderScene(this); } //apply styling mainContainer.graphics.clear(); //should we do this here? var sceneRenderer:ISceneRenderer; var factory:IFactory if (stylingEnabled) { for each (factory in styleRendererFactories) { sceneRenderer = factory.newInstance(); if (sceneRenderer) sceneRenderer.renderScene(this); } } bIsInvalidated = false; } } /** * @inheritDoc */ override protected function postRenderLogic ():void { invalidatedChildrenArray = []; super.postRenderLogic(); //should we still call sceneRendered()? sceneRendered(); } /** * This function has been deprecated. Please refer to postRenderLogic. */ protected function sceneRendered ():void { } /////////////////////////////////////////////////////////////////////////////// // CONSTRUCTOR /////////////////////////////////////////////////////////////////////////////// /** * Constructor */ public function IsoScene () { super(); layoutRendererFactory = new ClassFactory(DefaultSceneLayoutRenderer); } } }
/* as3isolib - An open-source ActionScript 3.0 Isometric Library developed to assist in creating isometrically projected content (such as games and graphics) targeted for the Flash player platform http://code.google.com/p/as3isolib/ Copyright (c) 2006 - 2008 J.W.Opitz, All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package as3isolib.display.scene { import as3isolib.bounds.IBounds; import as3isolib.bounds.SceneBounds; import as3isolib.core.IIsoDisplayObject; import as3isolib.core.IsoContainer; import as3isolib.core.as3isolib_internal; import as3isolib.data.INode; import as3isolib.display.renderers.DefaultSceneLayoutRenderer; import as3isolib.display.renderers.ISceneLayoutRenderer; import as3isolib.display.renderers.ISceneRenderer; import as3isolib.events.IsoEvent; import flash.display.DisplayObjectContainer; import mx.core.ClassFactory; import mx.core.IFactory; use namespace as3isolib_internal; /** * IsoScene is a base class for grouping and rendering IIsoDisplayObject children according to their isometric position-based depth. */ public class IsoScene extends IsoContainer implements IIsoScene { /////////////////////////////////////////////////////////////////////////////// // BOUNDS /////////////////////////////////////////////////////////////////////////////// /** * @private */ private var _isoBounds:IBounds; /** * @inheritDoc */ public function get isoBounds ():IBounds { /* if (!_isoBounds || isInvalidated) _isoBounds = */ return new SceneBounds(this); } /////////////////////////////////////////////////////////////////////////////// // HOST CONTAINER /////////////////////////////////////////////////////////////////////////////// /** * @private */ protected var host:DisplayObjectContainer; as3isolib_internal /** * @private */ public function get hostContainer ():DisplayObjectContainer { return host; } /** * @inheritDoc */ public function set hostContainer (value:DisplayObjectContainer):void { if (value && host != value) { if (host && host.contains(container)) { host.removeChild(container); ownerObject = null; } else if (hasParent) parent.removeChild(this); host = value; if (host) { host.addChild(container); ownerObject = host; parentNode = null; } } } /////////////////////////////////////////////////////////////////////////////// // INVALIDATE CHILDREN /////////////////////////////////////////////////////////////////////////////// /** * @private * * Array of invalidated children. Each child dispatches an IsoEvent.INVALIDATION event which notifies * the scene that that particular child is invalidated and subsequentally the scene is also invalidated. */ protected var invalidatedChildrenArray:Array = []; /** * @inheritDoc */ public function get invalidatedChildren ():Array { return invalidatedChildrenArray; } /////////////////////////////////////////////////////////////////////////////// // OVERRIDES /////////////////////////////////////////////////////////////////////////////// /** * @inheritDoc */ override public function addChildAt (child:INode, index:uint):void { if (child is IIsoDisplayObject) { super.addChildAt(child, index); child.addEventListener(IsoEvent.INVALIDATE, child_invalidateHandler); bIsInvalidated = true; //since the child most likely had fired an invalidation event prior to being added, manually invalidate the scene } else throw new Error ("parameter child is not of type IIsoDisplayObject"); } /** * @inheritDoc */ override public function setChildIndex (child:INode, index:uint):void { super.setChildIndex(child, index); bIsInvalidated = true; } /** * @inheritDoc */ override public function removeChildByID (id:String):INode { var child:INode = super.removeChildByID(id); if (child) { child.removeEventListener(IsoEvent.INVALIDATE, child_invalidateHandler); bIsInvalidated = true; } return child; } /** * @inheritDoc */ override public function removeAllChildren ():void { var child:INode for each (child in children) child.removeEventListener(IsoEvent.INVALIDATE, child_invalidateHandler); super.removeAllChildren(); bIsInvalidated = true; } /** * Renders the scene as invalidated if a child object is invalidated. * * @param evt The IsoEvent dispatched from the invalidated child. */ protected function child_invalidateHandler (evt:IsoEvent):void { var child:Object = evt.target; if (invalidatedChildrenArray.indexOf(child) == -1) invalidatedChildrenArray.push(child); bIsInvalidated = true; } /////////////////////////////////////////////////////////////////////////////// // LAYOUT RENDERER /////////////////////////////////////////////////////////////////////////////// /** * Flags the scene for possible layout rendering. * If false, child objects are sorted by the order they were added rather than by their isometric depth. */ public var layoutEnabled:Boolean = true; private var layoutRendererFactory:IFactory; /** * @private */ public function get layoutRenderer ():IFactory { return layoutRendererFactory; } /** * The factory used to create the ISceneLayoutRenderer responsible for the layout of the child objects. */ public function set layoutRenderer (value:IFactory):void { if (value && layoutRendererFactory != value) { layoutRendererFactory = value; bIsInvalidated = true; } } /////////////////////////////////////////////////////////////////////////////// // STYLE RENDERERS /////////////////////////////////////////////////////////////////////////////// /** * Flags the scene for possible style rendering. */ public var stylingEnabled:Boolean = true; private var styleRendererFactories:Array = []; /** * @private */ public function get styleRenderers ():Array { return styleRendererFactories; } /** * An array of IFactories whose class generators are ISceneRenderer. * If any value contained within the array is not of type IFactory, it will be ignored. */ public function set styleRenderers (value:Array):void { if (value) { var temp:Array = []; var obj:Object; for each (obj in value) { if (obj is IFactory) temp.push(obj); } styleRendererFactories = temp; bIsInvalidated = true; } } /////////////////////////////////////////////////////////////////////////////// // INVALIDATION /////////////////////////////////////////////////////////////////////////////// /** * Flags the scene as invalidated during the rendering process */ public function invalidateScene ():void { bIsInvalidated = true; } /////////////////////////////////////////////////////////////////////////////// // RENDER /////////////////////////////////////////////////////////////////////////////// /** * @inheritDoc */ override protected function renderLogic (recursive:Boolean = true):void { super.renderLogic(recursive); //push individual changes thru, then sort based on new visible content of each child if (bIsInvalidated) { //render the layout first var sceneLayoutRenderer:ISceneLayoutRenderer; if (layoutEnabled) { sceneLayoutRenderer = layoutRendererFactory.newInstance(); if (sceneLayoutRenderer) sceneLayoutRenderer.renderScene(this); } //fix for bug #20 - http://code.google.com/p/as3isolib/issues/detail?id=20 var sceneRenderer:ISceneRenderer; var factory:IFactory if (stylingEnabled && styleRendererFactories.length > 0) { mainContainer.graphics.clear(); for each (factory in styleRendererFactories) { sceneRenderer = factory.newInstance(); if (sceneRenderer) sceneRenderer.renderScene(this); } } bIsInvalidated = false; } } /** * @inheritDoc */ override protected function postRenderLogic ():void { invalidatedChildrenArray = []; super.postRenderLogic(); //should we still call sceneRendered()? sceneRendered(); } /** * This function has been deprecated. Please refer to postRenderLogic. */ protected function sceneRendered ():void { } /////////////////////////////////////////////////////////////////////////////// // CONSTRUCTOR /////////////////////////////////////////////////////////////////////////////// /** * Constructor */ public function IsoScene () { super(); layoutRendererFactory = new ClassFactory(DefaultSceneLayoutRenderer); } } }
fix for bug #20 - http://code.google.com/p/as3isolib/issues/detail?id=20
fix for bug #20 - http://code.google.com/p/as3isolib/issues/detail?id=20
ActionScript
mit
as3isolib/as3isolib.v1,dreamsxin/as3isolib.v1,liuju/as3isolib.v1,as3isolib/as3isolib.v1,dreamsxin/as3isolib.v1,liuju/as3isolib.v1
f71b7947120a808d94399c78547fc11658d31323
krew-framework/krewfw/utils/as3/KrewAsync.as
krew-framework/krewfw/utils/as3/KrewAsync.as
package krewfw.utils.as3 { /** * Flexible asynchronous tasker. * * Usage: * <pre> * //--- Basic sequential task * var async:KrewAsync = new KrewAsync({ * serial : [function_1, function_2, function_3], * error : _onErrorHandler, * anyway : _onFinallyHandler * }); * async.go(); * * * //--- Parallel task * var async:KrewAsync = new KrewAsync({ * parallel: [function_1, function_2, function_3], * error : _onErrorHandler, * anyway : _onFinallyHandler * }); * async.go(); * * * Throws error if both 'serial' and 'parallel' are specified. * * * //--- Function receives KrewAsync instance, * // and you should call done() or fail(). + * var async:KrewAsync = new KrewAsync({ * serial: [ * function(async:KrewAsync):void { * if (TASK_IS_SUCCEEDED) { * async.done(); * } else { * async.fail(); * } * } * ] * }); * * * //--- Sub task * var async:KrewAsync = new KrewAsync({ * serial: [ * function_1, * function_2, * {parallel: [ * function_3, * function_4, * {serial: [ * function_5, * function_6 * ]} * ]}, * function_7 * ], * error : _onErrorHandler, * anyway : _onFinallyHandler * }); * async.go(); * * [Sequence]: * |3 ------>| * | | * 1 -> 2 -> |4 ------>| -> 7 -> anyway * | | * |5 -> 6 ->| * * </pre> * * @param asyncDef Object or Function or instance of KrewAsync. Example: * <pre> * var async:KrewAsync = new KrewAsync(<asyncDef>); * * <asyncDef> ::= { * single : function(async:KrewAsync):void {} // KrewAsync uses internally * // OR * serial : [<asyncDef>, ... ] * // OR * parallel: [<asyncDef>, ... ] * * error : function():void {}, // optional * anyway : function():void {} // optional * } * * * If <asyncDef> == Function, then it is converted into: * {single: Function} * * * You can use class instances instead of asyncDef object: * * public class MyKrewAsyncTask extends KrewAsync { * public function MyKrewAsyncTask() { * super({ * parallel: [method_1, method_2, method_3] * }); * } * } * * var async:KrewAsync = new KrewAsync({ * serial: [ * function_1, * new MyKrewAsyncTask(), * function_2 * ] * }); * </pre> */ //------------------------------------------------------------ public class KrewAsync { private var _myTask:Function; private var _errorHandler:Function; private var _successHandler:Function; private var _finallyHandler:Function; private var _serialTasks :Vector.<KrewAsync>; private var _parallelTasks:Vector.<KrewAsync>; private var _serialTaskIndex:int = 0; private var _onComplete:Function = function():void {}; public static const UNDEF :int = 1; public static const RESOLVED:int = 2; public static const REJECTED:int = 3; private var _state:int = KrewAsync.UNDEF; private var _isResolved :Boolean = false; private var _isRejected :Boolean = false; private var _isFinalized:Boolean = false; //------------------------------------------------------------ public function KrewAsync(asyncDef:*) { if (asyncDef is Function) { _initWithFunction(asyncDef); return; } if (asyncDef is KrewAsync) { _initWithKrewAsync(asyncDef); return; } if (asyncDef is Array) { _initWithArray(asyncDef); return; } if (asyncDef is Object) { _initWithObject(asyncDef); return; } } //------------------------------------------------------------ // accessors //------------------------------------------------------------ public function get myTask() :Function { return _myTask; } public function get errorHandler() :Function { return _errorHandler; } public function get successHandler():Function { return _successHandler; } public function get finallyHandler():Function { return _finallyHandler; } public function get serialTasks() :Vector.<KrewAsync> { return _serialTasks; } public function get parallelTasks():Vector.<KrewAsync> { return _parallelTasks; } public function get state():int { return _state; } //------------------------------------------------------------ // public //------------------------------------------------------------ public function go(onComplete:Function=null):void { if (onComplete != null) { _onComplete = onComplete; } if (_myTask != null) { _myTask(this); return; } if (_serialTasks != null) { _kickNextSerialTask(); return; } if (_parallelTasks != null) { _kickParallelTasks(); return; } } public function done():void { _state = KrewAsync.RESOLVED; _finalize(); } public function fail():void { _state = KrewAsync.REJECTED; _finalize(); } //------------------------------------------------------------ // initializer //------------------------------------------------------------ private function _initWithObject(asyncDef:Object):void { _validateInitObject(asyncDef); if (asyncDef.single != null) { _myTask = asyncDef.single; } if (asyncDef.serial != null) { _serialTasks = _makeChildren(asyncDef.serial); } if (asyncDef.parallel != null) { _parallelTasks = _makeChildren(asyncDef.parallel); } if (asyncDef.success != null) { _successHandler = asyncDef.success; } if (asyncDef.error != null) { _errorHandler = asyncDef.error; } if (asyncDef.anyway != null) { _finallyHandler = asyncDef.anyway; } } private function _validateInitObject(asyncDef:Object):void { var exclusiveDefCount:uint = 0; if (asyncDef.single != null) { ++exclusiveDefCount; } if (asyncDef.serial != null) { ++exclusiveDefCount; } if (asyncDef.parallel != null) { ++exclusiveDefCount; } if (exclusiveDefCount != 1) { throw new Error("[KrewAsync] Error: Invalid async task definition."); } } private function _makeChildren(asyncDefList:Array):Vector.<KrewAsync> { var children:Vector.<KrewAsync> = new Vector.<KrewAsync>; for each (var def:* in asyncDefList) { var async:KrewAsync = (def is KrewAsync) ? def : new KrewAsync(def); children.push(async); } return children; } private function _initWithFunction(asyncDef:Function):void { _initWithObject({ single: asyncDef }); } private function _initWithArray(asyncDef:Array):void { _initWithObject({ serial: asyncDef }); } private function _initWithKrewAsync(asyncDef:KrewAsync):void { _myTask = asyncDef.myTask; _successHandler = asyncDef.successHandler; _errorHandler = asyncDef.errorHandler; _finallyHandler = asyncDef.finallyHandler; _serialTasks = asyncDef.serialTasks; _parallelTasks = asyncDef.parallelTasks; } //------------------------------------------------------------ // task runner //------------------------------------------------------------ private function _kickNextSerialTask():void { if (_serialTaskIndex >= _serialTasks.length) { _onResolve(); return; } var nextTask:KrewAsync = _serialTasks[_serialTaskIndex]; ++_serialTaskIndex; nextTask.go(function(async:KrewAsync):void { if (async.state == KrewAsync.RESOLVED) { _kickNextSerialTask(); } else { _onReject(); } }); } private function _kickParallelTasks():void { var doneCount:int = 0; for each (var task:KrewAsync in _parallelTasks) { task.go(function(async:KrewAsync):void { if (async.state == KrewAsync.RESOLVED) { ++doneCount; if (doneCount == _parallelTasks.length) { _onResolve(); } } else { _onReject(); } }); } } //------------------------------------------------------------ // result handler //------------------------------------------------------------ private function _onResolve():void { if (_isResolved) { return; } _isResolved = true; if (_successHandler != null) { _successHandler(); } done(); } private function _onReject():void { if (_isRejected) { return; } _isRejected = true; if (_errorHandler != null) { _errorHandler(); } fail(); } private function _finalize():void { if (_isFinalized) { return; } _isFinalized = true; if (_finallyHandler != null) { _finallyHandler(); } _onComplete(this); } } }
package krewfw.utils.as3 { /** * Flexible asynchronous tasker. * @see http://docs.tatsuya-koyama.com/krew-framework/samples/krewasync/ * * Usage: * <pre> * //--- Basic sequential task * var async:KrewAsync = new KrewAsync({ * serial : [function_1, function_2, function_3], * error : _onErrorHandler, * anyway : _onFinallyHandler * }); * async.go(); * * * //--- Parallel task * var async:KrewAsync = new KrewAsync({ * parallel: [function_1, function_2, function_3], * error : _onErrorHandler, * anyway : _onFinallyHandler * }); * async.go(); * * * Throws error if both 'serial' and 'parallel' are specified. * * * //--- Function receives KrewAsync instance, * // and you should call done() or fail(). + * var async:KrewAsync = new KrewAsync({ * serial: [ * function(async:KrewAsync):void { * if (TASK_IS_SUCCEEDED) { * async.done(); * } else { * async.fail(); * } * } * ] * }); * * * //--- Sub task * var async:KrewAsync = new KrewAsync({ * serial: [ * function_1, * function_2, * {parallel: [ * function_3, * function_4, * {serial: [ * function_5, * function_6 * ]} * ]}, * function_7 * ], * success: _onSuccessHandler, * error : _onErrorHandler, * anyway : _onFinallyHandler * }); * async.go(); * * [Sequence]: * |3 ------>| * | | * 1 -> 2 -> |4 ------>| -> 7 -> success -> anyway * | | (or error) * |5 -> 6 ->| * * </pre> * * @param asyncDef Object or Function or instance of KrewAsync. Example: * <pre> * var async:KrewAsync = new KrewAsync(<asyncDef>); * * <asyncDef> ::= { * single : function(async:KrewAsync):void {} // KrewAsync uses internally * // OR * serial : [<asyncDef>, ... ] * // OR * parallel: [<asyncDef>, ... ] * * success : function():void {}, // optional * error : function():void {}, // optional * anyway : function():void {} // optional * } * * * If <asyncDef> == Function, then it is converted into: * {single: Function} * * * You can use class instances instead of asyncDef object: * * public class MyKrewAsyncTask extends KrewAsync { * public function MyKrewAsyncTask() { * super({ * parallel: [method_1, method_2, method_3] * }); * } * } * * var async:KrewAsync = new KrewAsync({ * serial: [ * function_1, * new MyKrewAsyncTask(), * function_2 * ] * }); * </pre> */ //------------------------------------------------------------ public class KrewAsync { private var _myTask:Function; private var _errorHandler:Function; private var _successHandler:Function; private var _finallyHandler:Function; private var _serialTasks :Vector.<KrewAsync>; private var _parallelTasks:Vector.<KrewAsync>; private var _serialTaskIndex:int = 0; private var _onComplete:Function = function():void {}; public static const UNDEF :int = 1; public static const RESOLVED:int = 2; public static const REJECTED:int = 3; private var _state:int = KrewAsync.UNDEF; private var _isResolved :Boolean = false; private var _isRejected :Boolean = false; private var _isFinalized:Boolean = false; //------------------------------------------------------------ public function KrewAsync(asyncDef:*) { if (asyncDef is Function) { _initWithFunction(asyncDef); return; } if (asyncDef is KrewAsync) { _initWithKrewAsync(asyncDef); return; } if (asyncDef is Array) { _initWithArray(asyncDef); return; } if (asyncDef is Object) { _initWithObject(asyncDef); return; } } //------------------------------------------------------------ // accessors //------------------------------------------------------------ public function get myTask() :Function { return _myTask; } public function get errorHandler() :Function { return _errorHandler; } public function get successHandler():Function { return _successHandler; } public function get finallyHandler():Function { return _finallyHandler; } public function get serialTasks() :Vector.<KrewAsync> { return _serialTasks; } public function get parallelTasks():Vector.<KrewAsync> { return _parallelTasks; } public function get state():int { return _state; } //------------------------------------------------------------ // public //------------------------------------------------------------ public function go(onComplete:Function=null):void { if (onComplete != null) { _onComplete = onComplete; } if (_myTask != null) { _myTask(this); return; } if (_serialTasks != null) { _kickNextSerialTask(); return; } if (_parallelTasks != null) { _kickParallelTasks(); return; } } public function done():void { _state = KrewAsync.RESOLVED; _finalize(); } public function fail():void { _state = KrewAsync.REJECTED; _finalize(); } //------------------------------------------------------------ // initializer //------------------------------------------------------------ private function _initWithObject(asyncDef:Object):void { _validateInitObject(asyncDef); if (asyncDef.single != null) { _myTask = asyncDef.single; } if (asyncDef.serial != null) { _serialTasks = _makeChildren(asyncDef.serial); } if (asyncDef.parallel != null) { _parallelTasks = _makeChildren(asyncDef.parallel); } if (asyncDef.success != null) { _successHandler = asyncDef.success; } if (asyncDef.error != null) { _errorHandler = asyncDef.error; } if (asyncDef.anyway != null) { _finallyHandler = asyncDef.anyway; } } private function _validateInitObject(asyncDef:Object):void { var exclusiveDefCount:uint = 0; if (asyncDef.single != null) { ++exclusiveDefCount; } if (asyncDef.serial != null) { ++exclusiveDefCount; } if (asyncDef.parallel != null) { ++exclusiveDefCount; } if (exclusiveDefCount != 1) { throw new Error("[KrewAsync] Error: Invalid async task definition."); } } private function _makeChildren(asyncDefList:Array):Vector.<KrewAsync> { var children:Vector.<KrewAsync> = new Vector.<KrewAsync>; for each (var def:* in asyncDefList) { var async:KrewAsync = (def is KrewAsync) ? def : new KrewAsync(def); children.push(async); } return children; } private function _initWithFunction(asyncDef:Function):void { _initWithObject({ single: asyncDef }); } private function _initWithArray(asyncDef:Array):void { _initWithObject({ serial: asyncDef }); } private function _initWithKrewAsync(asyncDef:KrewAsync):void { _myTask = asyncDef.myTask; _successHandler = asyncDef.successHandler; _errorHandler = asyncDef.errorHandler; _finallyHandler = asyncDef.finallyHandler; _serialTasks = asyncDef.serialTasks; _parallelTasks = asyncDef.parallelTasks; } //------------------------------------------------------------ // task runner //------------------------------------------------------------ private function _kickNextSerialTask():void { if (_serialTaskIndex >= _serialTasks.length) { _onResolve(); return; } var nextTask:KrewAsync = _serialTasks[_serialTaskIndex]; ++_serialTaskIndex; nextTask.go(function(async:KrewAsync):void { if (async.state == KrewAsync.RESOLVED) { _kickNextSerialTask(); } else { _onReject(); } }); } private function _kickParallelTasks():void { var doneCount:int = 0; for each (var task:KrewAsync in _parallelTasks) { task.go(function(async:KrewAsync):void { if (async.state == KrewAsync.RESOLVED) { ++doneCount; if (doneCount == _parallelTasks.length) { _onResolve(); } } else { _onReject(); } }); } } //------------------------------------------------------------ // result handler //------------------------------------------------------------ private function _onResolve():void { if (_isResolved) { return; } _isResolved = true; if (_successHandler != null) { _successHandler(); } done(); } private function _onReject():void { if (_isRejected) { return; } _isRejected = true; if (_errorHandler != null) { _errorHandler(); } fail(); } private function _finalize():void { if (_isFinalized) { return; } _isFinalized = true; if (_finallyHandler != null) { _finallyHandler(); } _onComplete(this); } } }
Add comment to KrewAsync
Add comment to KrewAsync
ActionScript
mit
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
32597c8c41dbb2de496e0951ed62268bc5741715
FlexUnit4/src/org/flexunit/internals/runners/FlexUnit1ClassRunner.as
FlexUnit4/src/org/flexunit/internals/runners/FlexUnit1ClassRunner.as
/** * Copyright (c) 2009 Digital Primates IT Consulting Group * * 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. * * @author Michael Labriola <[email protected]> * @version **/ package org.flexunit.internals.runners { import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; import flex.lang.reflect.Klass; import flex.lang.reflect.Method; import flexunit.framework.Test; import flexunit.framework.TestCase; import flexunit.framework.TestListener; import flexunit.framework.TestResult; import flexunit.framework.TestSuite; import org.flexunit.runner.Description; import org.flexunit.runner.IDescribable; import org.flexunit.runner.IDescription; import org.flexunit.runner.IRunner; import org.flexunit.runner.manipulation.Filter; import org.flexunit.runner.manipulation.IFilterable; import org.flexunit.runner.notification.IRunNotifier; import org.flexunit.runners.model.FrameworkMethod; import org.flexunit.token.AsyncTestToken; import org.flexunit.token.ChildResult; import org.flexunit.utils.ClassNameUtil; public class FlexUnit1ClassRunner implements IRunner, IFilterable { private var test:Test; private var klassOrTest:*; private var totalTestCount:int = 0; private var numTestsRun:int = 0; private var filterRef:Filter = null; public function FlexUnit1ClassRunner( klassOrTest:* ) { super(); this.klassOrTest = klassOrTest; if ( klassOrTest is Test ) { this.test = klassOrTest; } else { //in this case, we need to make a suite this.test = createTestSuiteWithFilter( filterRef ); } } protected function describeChild( child:* ):IDescription { var method:FrameworkMethod = FrameworkMethod( child ); return Description.createTestDescription( klassOrTest, method.name, method.metadata?method.metadata[ 0 ]:null ); } private function shouldRun( item:* ):Boolean { return filterRef == null || filterRef.shouldRun( describeChild( item ) ); } private function getMethodListFromFilter( klassInfo:Klass, filter:Filter ):Array { var list:Array = []; for ( var i:int=0; i<klassInfo.methods.length; i++ ) { var method:Method = klassInfo.methods[ i ] as Method; var frameworkMethod:FrameworkMethod = new FrameworkMethod( method ); if ( shouldRun( frameworkMethod ) ) { list.push( method.name ); } } return list; } private function createTestSuiteWithFilter( filter:Filter = null ):Test { if ( !filter ) { return new TestSuite( klassOrTest ); } else { var suite:TestSuite = new TestSuite(); var klassInfo:Klass = new Klass( klassOrTest ); var methodList:Array = getMethodListFromFilter( klassInfo, filter ); for ( var i:int=0; i<methodList.length; i++ ) { suite.addTest( new klassOrTest( methodList[ i ] ) ); } return suite; } } public static function getClassFromTest( test:Test ):Class { var name:String = getQualifiedClassName( test ); return getDefinitionByName( name ) as Class; } public function run( notifier:IRunNotifier, previousToken:AsyncTestToken ):void { var token:AsyncTestToken = new AsyncTestToken( ClassNameUtil.getLoggerFriendlyClassName( this ) ); token.parentToken = previousToken; token.addNotificationMethod( handleTestComplete ); var result:TestResult = new TestResult(); result.addListener( createAdaptingListener( notifier, token )); totalTestCount = test.countTestCases(); test.runWithResult(result); } protected function handleTestComplete( result:ChildResult ):void { if ( ++numTestsRun == totalTestCount ) { var error:Error = result.error; var token:AsyncTestToken = result.token; token.parentToken.sendResult(); } } public static function createAdaptingListener( notifier:IRunNotifier, token:AsyncTestToken ):TestListener { return new OldTestClassAdaptingListener(notifier, token ); } public function get description():IDescription { return makeDescription( test ); } private function makeDescription( test:Test ):IDescription { if ( test is TestCase ) { var tc:TestCase = TestCase( test ); //return null; return Description.createTestDescription(getClassFromTest( tc ), tc.className ); } else if ( test is TestSuite ) { var ts:TestSuite = TestSuite( test ); var name:String = ts.className == null ? "" : ts.className; var description:IDescription = Description.createSuiteDescription(name); var n:int = ts.testCount(); var tests:Array = ts.getTests(); for ( var i:int = 0; i < n; i++) description.addChild( makeDescription( tests[i] ) ); return description; } else if (test is IDescribable) { var adapter:IDescribable = IDescribable( test ); return adapter.description; //// not currently supporting this as the old flex unit didn't have it /* } else if (test is TestDecorator) { TestDecorator decorator= (TestDecorator) test; return makeDescription(decorator.getTest()); */ } else { // This is the best we can do in this case return Description.createSuiteDescription( test.className ); } } public function filter( filter:Filter ):void { if ( test is IFilterable ) { var adapter:IFilterable = IFilterable( test ); adapter.filter(filter); } this.filterRef = filter; test = createTestSuiteWithFilter( filterRef ); } /* public void sort(Sorter sorter) { if (fTest instanceof Sortable) { Sortable adapter= (Sortable) fTest; adapter.sort(sorter); } } */ } } import flexunit.framework.TestListener; import org.flexunit.runner.notification.RunNotifier; import flexunit.framework.Test; import org.flexunit.runner.Description; import org.flexunit.runner.notification.Failure; import flexunit.framework.TestCase; import org.flexunit.runner.IDescribable; import flexunit.framework.AssertionFailedError; import org.flexunit.internals.runners.FlexUnit1ClassRunner; import org.flexunit.token.AsyncTestToken; import org.flexunit.runner.notification.IRunNotifier; import org.flexunit.runner.IDescription; class OldTestClassAdaptingListener implements TestListener { private var notifier:IRunNotifier; private var token:AsyncTestToken; public function OldTestClassAdaptingListener( notifier:IRunNotifier, token:AsyncTestToken ) { this.notifier = notifier; this.token = token; } public function endTest( test:Test ):void { notifier.fireTestFinished(asDescription(test)); token.sendResult(); } public function startTest( test:Test ):void { notifier.fireTestStarted(asDescription(test)); } // Implement junit.framework.TestListener public function addError( test:Test, error:Error ):void { var failure:Failure = new Failure(asDescription(test), error ); notifier.fireTestFailure(failure); } private function asDescription( test:Test ):IDescription { if (test is IDescribable) { var facade:IDescribable = test as IDescribable; return facade.description; } return Description.createTestDescription( FlexUnit1ClassRunner.getClassFromTest( test ), getName(test) ); } private function getName( test:Test ):String { if ( test is TestCase ) return TestCase( test ).methodName; else return test.toString(); } public function addFailure( test : Test, error : AssertionFailedError ) : void { addError( test, error ); } }
/** * Copyright (c) 2009 Digital Primates IT Consulting Group * * 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. * * @author Michael Labriola <[email protected]> * @version **/ package org.flexunit.internals.runners { import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; import flex.lang.reflect.Klass; import flex.lang.reflect.Method; import flexunit.framework.Test; import flexunit.framework.TestCase; import flexunit.framework.TestListener; import flexunit.framework.TestResult; import flexunit.framework.TestSuite; import org.flexunit.runner.Description; import org.flexunit.runner.IDescribable; import org.flexunit.runner.IDescription; import org.flexunit.runner.IRunner; import org.flexunit.runner.manipulation.Filter; import org.flexunit.runner.manipulation.IFilterable; import org.flexunit.runner.notification.IRunNotifier; import org.flexunit.runners.model.FrameworkMethod; import org.flexunit.token.AsyncTestToken; import org.flexunit.token.ChildResult; import org.flexunit.utils.ClassNameUtil; public class FlexUnit1ClassRunner implements IRunner, IFilterable { private var test:Test; private var klassOrTest:*; private var totalTestCount:int = 0; private var numTestsRun:int = 0; private var filterRef:Filter = null; public function FlexUnit1ClassRunner( klassOrTest:* ) { super(); this.klassOrTest = klassOrTest; if ( klassOrTest is Test ) { this.test = klassOrTest; } else { //in this case, we need to make a suite this.test = createTestSuiteWithFilter( filterRef ); } } protected function describeChild( child:* ):IDescription { var method:FrameworkMethod = FrameworkMethod( child ); return Description.createTestDescription( klassOrTest, method.name, method.metadata?method.metadata[ 0 ]:null ); } private function shouldRun( item:* ):Boolean { return filterRef == null || filterRef.shouldRun( describeChild( item ) ); } private function getMethodListFromFilter( klassInfo:Klass, filter:Filter ):Array { var list:Array = []; for ( var i:int=0; i<klassInfo.methods.length; i++ ) { var method:Method = klassInfo.methods[ i ] as Method; var frameworkMethod:FrameworkMethod = new FrameworkMethod( method ); if ( shouldRun( frameworkMethod ) ) { list.push( method.name ); } } return list; } private function createTestSuiteWithFilter( filter:Filter = null ):Test { if ( !filter ) { return new TestSuite( klassOrTest ); } else { var suite:TestSuite = new TestSuite(); var klassInfo:Klass = new Klass( klassOrTest ); var methodList:Array = getMethodListFromFilter( klassInfo, filter ); for ( var i:int=0; i<methodList.length; i++ ) { var numConstructorArgs:int = klassInfo.constructor.parameterTypes.length; var test:Test; if ( numConstructorArgs == 0 ) { test = klassInfo.constructor.newInstance() as Test; if ( test is TestCase ) { //If this is a testCase && it does not take a constructor argument //then we try to pass it into methodName TestCase( test ).methodName = methodList[ i ]; } } else if ( numConstructorArgs == 1 ) { test = klassInfo.constructor.newInstance( methodList[ i ] ) as Test; } else { throw new InitializationError( "Asking to instatiate TestClass with unknown number of arguments" ); } suite.addTest( test ); } return suite; } } public static function getClassFromTest( test:Test ):Class { var name:String = getQualifiedClassName( test ); return getDefinitionByName( name ) as Class; } public function run( notifier:IRunNotifier, previousToken:AsyncTestToken ):void { var token:AsyncTestToken = new AsyncTestToken( ClassNameUtil.getLoggerFriendlyClassName( this ) ); token.parentToken = previousToken; token.addNotificationMethod( handleTestComplete ); var result:TestResult = new TestResult(); result.addListener( createAdaptingListener( notifier, token )); totalTestCount = test.countTestCases(); test.runWithResult(result); } protected function handleTestComplete( result:ChildResult ):void { if ( ++numTestsRun == totalTestCount ) { var error:Error = result.error; var token:AsyncTestToken = result.token; token.parentToken.sendResult(); } } public static function createAdaptingListener( notifier:IRunNotifier, token:AsyncTestToken ):TestListener { return new OldTestClassAdaptingListener(notifier, token ); } public function get description():IDescription { return makeDescription( test ); } private function makeDescription( test:Test ):IDescription { if ( test is TestCase ) { var tc:TestCase = TestCase( test ); //return null; return Description.createTestDescription(getClassFromTest( tc ), tc.className ); } else if ( test is TestSuite ) { var ts:TestSuite = TestSuite( test ); var name:String = ts.className == null ? "" : ts.className; var description:IDescription = Description.createSuiteDescription(name); var n:int = ts.testCount(); var tests:Array = ts.getTests(); for ( var i:int = 0; i < n; i++) description.addChild( makeDescription( tests[i] ) ); return description; } else if (test is IDescribable) { var adapter:IDescribable = IDescribable( test ); return adapter.description; //// not currently supporting this as the old flex unit didn't have it /* } else if (test is TestDecorator) { TestDecorator decorator= (TestDecorator) test; return makeDescription(decorator.getTest()); */ } else { // This is the best we can do in this case return Description.createSuiteDescription( test.className ); } } public function filter( filter:Filter ):void { if ( test is IFilterable ) { var adapter:IFilterable = IFilterable( test ); adapter.filter(filter); } this.filterRef = filter; test = createTestSuiteWithFilter( filterRef ); } /* public void sort(Sorter sorter) { if (fTest instanceof Sortable) { Sortable adapter= (Sortable) fTest; adapter.sort(sorter); } } */ } } import flexunit.framework.TestListener; import org.flexunit.runner.notification.RunNotifier; import flexunit.framework.Test; import org.flexunit.runner.Description; import org.flexunit.runner.notification.Failure; import flexunit.framework.TestCase; import org.flexunit.runner.IDescribable; import flexunit.framework.AssertionFailedError; import org.flexunit.internals.runners.FlexUnit1ClassRunner; import org.flexunit.token.AsyncTestToken; import org.flexunit.runner.notification.IRunNotifier; import org.flexunit.runner.IDescription; class OldTestClassAdaptingListener implements TestListener { private var notifier:IRunNotifier; private var token:AsyncTestToken; public function OldTestClassAdaptingListener( notifier:IRunNotifier, token:AsyncTestToken ) { this.notifier = notifier; this.token = token; } public function endTest( test:Test ):void { notifier.fireTestFinished(asDescription(test)); token.sendResult(); } public function startTest( test:Test ):void { notifier.fireTestStarted(asDescription(test)); } // Implement junit.framework.TestListener public function addError( test:Test, error:Error ):void { var failure:Failure = new Failure(asDescription(test), error ); notifier.fireTestFailure(failure); } private function asDescription( test:Test ):IDescription { if (test is IDescribable) { var facade:IDescribable = test as IDescribable; return facade.description; } return Description.createTestDescription( FlexUnit1ClassRunner.getClassFromTest( test ), getName(test) ); } private function getName( test:Test ):String { if ( test is TestCase ) return TestCase( test ).methodName; else return test.toString(); } public function addFailure( test : Test, error : AssertionFailedError ) : void { addError( test, error ); } }
Fix for JIRA issue http://bugs.adobe.com/jira/browse/FXU-37
Fix for JIRA issue http://bugs.adobe.com/jira/browse/FXU-37 git-svn-id: 9278a788294a4258aac04586390fc35fb4a5f335@6909 a9308255-753e-0410-a2e9-80b3fbc4fff6
ActionScript
apache-2.0
apache/flex-flexunit,SlavaRa/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit
7bd1ec48016cadfbc3a7d5141d4a9e51b2760404
src/com/google/analytics/v4/Configuration.as
src/com/google/analytics/v4/Configuration.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.v4 { import com.google.analytics.campaign.CampaignKey; import com.google.analytics.core.Domain; import com.google.analytics.core.DomainNameMode; import com.google.analytics.core.Organic; import com.google.analytics.core.ServerOperationMode; import com.google.analytics.debug.DebugConfiguration; import com.google.analytics.utils.Timespan; /** * Google Analytic Tracker Code (GATC)'s configuration / state component. * This encapsulates all the configurations for the entire GATC module. */ public class Configuration { private var _debug:DebugConfiguration; private var _version:String = "4.3as"; /** * Sampling percentage of visitors to track. * @private */ private var _sampleRate:Number = 1; //100% private var _trackingLimitPerSession:int = 500; private var _domain:Domain; private var _organic:Organic = new Organic(); /** * Substring of host names to ignore when auto decorating href anchor elements for outbound link tracking. * @private */ //private var _ignoredOutboundHosts:Array = []; /** * This is the cse path that needs to be ignored for Google. * All referers with path cse from google donmains will be ignored from organic and referrer campaigns. * @private */ public var googleCsePath:String = "cse"; /** * The parameter used by google for the search keyword. * @private */ public var googleSearchParam:String = "q"; /** * Google string value. * @private */ public var google:String = "google"; /** * Name used by the SharedObject (read-only) */ private var _cookieName:String = "analytics"; /** * Unique domain hash for cookies. */ public var allowDomainHash:Boolean = true; /** * Enable use of anchors for campaigns. */ public var allowAnchor:Boolean = false ; /** * Enable linker functionality. */ public var allowLinker:Boolean = false ; /** * Indicates if has site overlay. */ public var hasSiteOverlay:Boolean = false ; /** * The rate of token being released into the token bucket. * Unit for this parameter is number of token released per second. * This is set to 0.20 right now, which translates to 1 token released every 5 seconds. */ public var tokenRate:Number = 0.20; /** * Default cookie expiration time in seconds. (6 months). */ public var conversionTimeout:Number = Timespan.sixmonths; /** * Default inactive session timeout in seconds (30 minutes). */ public var sessionTimeout:Number = Timespan.thirtyminutes; /** * Default idle timer loop time in seconds (30 seconds). */ public var idleLoop:Number = 30; /** * Default idle timer inactivity time in seconds (1 minute). */ public var idleTimeout:Number = 60; /** * Upper limit for number of href anchor tags to examine. * <p>If this number is set to -1, then we will examine all the href anchor tags.</p> * <p>In other words, a -1 value indicates that there is no upper limit.</p> * <p><b>Note:</b> maybe use Number.INFINITY instead of -1</p> */ public var maxOutboundLinkExamined:Number = 1000; /** * The number of tokens available at the start of the session. */ public var tokenCliff:int = 10; /** * Capacity of the token bucket. */ public var bucketCapacity:Number = 10; /** * Detect client browser information flag. */ public var detectClientInfo:Boolean = true; /** * Flash version detection option. */ public var detectFlash:Boolean = true; /** * Set document title detection option. */ public var detectTitle:Boolean = true; /** * The campaign key value of the application. * @see com.google.analytics.campaign.CampaignKey */ public var campaignKey:CampaignKey = new CampaignKey(); /** * Track campaign information flag. */ public var campaignTracking:Boolean = true; /** * Boolean flag to indicate if outbound links for subdomains of the current domain * needs to be considered as outbound links. Default value is false. */ public var isTrackOutboundSubdomains:Boolean = false; /** * Actual service model. * <p><b>Note :</b> "service" is wrong we name it server</p> */ public var serverMode:ServerOperationMode = ServerOperationMode.remote; /** * Local service mode GIF url. */ public var localGIFpath:String = "/__utm.gif"; /** * The remote service mode GIF url. */ public var remoteGIFpath:String = "http://www.google-analytics.com/__utm.gif"; /** * The secure remote service mode GIF url. */ public var secureRemoteGIFpath:String = "https://ssl.google-analytics.com/__utm.gif"; /** * Default cookie path to set in document header. */ public var cookiePath:String = "/" ; //SharedObjectPath /** * Delimiter for e-commerce transaction fields. */ public var transactionFieldDelim:String = "|"; /** * The domain name value. */ public var domainName:String = ""; /** * To be able to track in local mode (when protocol is file://) */ public var allowLocalTracking:Boolean = true; /** * Creates a new Configuration instance. */ public function Configuration( debug:DebugConfiguration = null ) { _debug = debug; _domain = new Domain( DomainNameMode.auto, "", _debug ); serverMode = ServerOperationMode.remote; _initOrganicSources(); } /** * @private */ private function _initOrganicSources():void { addOrganicSource( google, googleSearchParam ); addOrganicSource( "yahoo", "p" ); addOrganicSource( "msn", "q" ); addOrganicSource( "aol", "query" ); addOrganicSource( "aol", "encquery" ); addOrganicSource( "lycos", "query" ); addOrganicSource( "ask", "q" ); addOrganicSource( "altavista", "q" ); addOrganicSource( "netscape", "query" ); addOrganicSource( "cnn", "query" ); addOrganicSource( "looksmart", "qt" ); addOrganicSource( "about", "terms" ); addOrganicSource( "mamma", "query" ); addOrganicSource( "alltheweb", "q" ); addOrganicSource( "gigablast", "q" ); addOrganicSource( "voila", "rdata" ); addOrganicSource( "virgilio", "qs" ); addOrganicSource( "live", "q" ); addOrganicSource( "baidu", "wd" ); addOrganicSource( "alice", "qs" ); addOrganicSource( "yandex", "text" ); addOrganicSource( "najdi", "q" ); addOrganicSource( "aol", "q" ); addOrganicSource( "club-internet", "q" ); addOrganicSource( "mama", "query" ); addOrganicSource( "seznam", "q" ); addOrganicSource( "search", "q" ); addOrganicSource( "wp", "szukaj" ); addOrganicSource( "onet", "qt" ); addOrganicSource( "netsprint", "q" ); addOrganicSource( "google.interia", "q" ); addOrganicSource( "szukacz", "q" ); addOrganicSource( "yam", "k" ); addOrganicSource( "pchome", "q" ); addOrganicSource( "kvasir", "searchExpr" ); addOrganicSource( "sesam", "q" ); addOrganicSource( "ozu", "q" ); addOrganicSource( "terra", "query" ); addOrganicSource( "nostrum", "query" ); addOrganicSource( "mynet", "q" ); addOrganicSource( "ekolay", "q" ); addOrganicSource( "search.ilse", "search_for" ); } /** * Indicates the name of the cookie. */ public function get cookieName():String { return _cookieName; } /** * Indicates the version String representation of the application. */ public function get version():String { return _version; } /** * Domain name for cookies. * (auto | none | domain) * If this variable is set to "auto", * then we will try to resolve the domain name * based on the HTMLDocument object. * * note: * for Flash we try to auto detect * the domain name by using the URL info * if we are in HTTP or HTTPS * * if we can not detect the protocol or find file:// * then the "auto" domain is none. */ public function get domain():Domain { return _domain; } /** * Indicates the Organic reference. */ public function get organic():Organic { return _organic; } // /** // * Indicates the collection (Array) of all organic sources. // */ // public function get organicSources():Array // { // return _organicSources; // } // // /** // * @private // */ // public function set organicSources(sources:Array):void // { // _organicSources = sources; // } /** * Indicates the sample rate value of the application. */ public function get sampleRate():Number { return _sampleRate; } /** * Sampling percentage of visitors to track. */ public function set sampleRate( value:Number ):void { if( value <= 0 ) { value = 0.1; } if( value > 1 ) { value = 1; } value = Number( value.toFixed( 2 ) ); _sampleRate = value; } /** * This is the max number of tracking requests to the backend * allowed per session. */ public function get trackingLimitPerSession():int { return _trackingLimitPerSession; } /** * Adds a new organic source. * @param engine The engine value. * @param keyword The keyword of the specified engine value. */ public function addOrganicSource(engine:String, keyword:String):void { try { _organic.addSource( engine, keyword ); } catch( e:Error ) { if( _debug && _debug.active ) { _debug.warning( e.message ); } } } } }
/* * 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.v4 { import com.google.analytics.campaign.CampaignKey; import com.google.analytics.core.Domain; import com.google.analytics.core.DomainNameMode; import com.google.analytics.core.Organic; import com.google.analytics.core.ServerOperationMode; import com.google.analytics.debug.DebugConfiguration; import com.google.analytics.utils.Timespan; /** * Google Analytic Tracker Code (GATC)'s configuration / state component. * This encapsulates all the configurations for the entire GATC module. */ public class Configuration { private var _debug:DebugConfiguration; private var _version:String = "4.3as"; /** * Sampling percentage of visitors to track. * @private */ private var _sampleRate:Number = 1; //100% private var _trackingLimitPerSession:int = 500; private var _domain:Domain; private var _organic:Organic = new Organic(); /** * Substring of host names to ignore when auto decorating href anchor elements for outbound link tracking. * @private */ //private var _ignoredOutboundHosts:Array = []; /** * This is the cse path that needs to be ignored for Google. * All referers with path cse from google donmains will be ignored from organic and referrer campaigns. * @private */ public var googleCsePath:String = "cse"; /** * The parameter used by google for the search keyword. * @private */ public var googleSearchParam:String = "q"; /** * Google string value. * @private */ public var google:String = "google"; /** * Name used by the SharedObject (read-only) */ private var _cookieName:String = "analytics"; /** * Unique domain hash for cookies. */ public var allowDomainHash:Boolean = true; /** * Enable use of anchors for campaigns. */ public var allowAnchor:Boolean = false ; /** * Enable linker functionality. */ public var allowLinker:Boolean = false ; /** * Indicates if has site overlay. */ public var hasSiteOverlay:Boolean = false ; /** * The rate of token being released into the token bucket. * Unit for this parameter is number of token released per second. * This is set to 0.20 right now, which translates to 1 token released every 5 seconds. */ public var tokenRate:Number = 0.20; /** * Default cookie expiration time in seconds. (6 months). */ public var conversionTimeout:Number = Timespan.sixmonths; /** * Default inactive session timeout in seconds (30 minutes). */ public var sessionTimeout:Number = Timespan.thirtyminutes; /** * Upper limit for number of href anchor tags to examine. * <p>If this number is set to -1, then we will examine all the href anchor tags.</p> * <p>In other words, a -1 value indicates that there is no upper limit.</p> * <p><b>Note:</b> maybe use Number.INFINITY instead of -1</p> */ public var maxOutboundLinkExamined:Number = 1000; /** * The number of tokens available at the start of the session. */ public var tokenCliff:int = 10; /** * Capacity of the token bucket. */ public var bucketCapacity:Number = 10; /** * Detect client browser information flag. */ public var detectClientInfo:Boolean = true; /** * Flash version detection option. */ public var detectFlash:Boolean = true; /** * Set document title detection option. */ public var detectTitle:Boolean = true; /** * The campaign key value of the application. * @see com.google.analytics.campaign.CampaignKey */ public var campaignKey:CampaignKey = new CampaignKey(); /** * Track campaign information flag. */ public var campaignTracking:Boolean = true; /** * Boolean flag to indicate if outbound links for subdomains of the current domain * needs to be considered as outbound links. Default value is false. */ public var isTrackOutboundSubdomains:Boolean = false; /** * Actual service model. * <p><b>Note :</b> "service" is wrong we name it server</p> */ public var serverMode:ServerOperationMode = ServerOperationMode.remote; /** * Local service mode GIF url. */ public var localGIFpath:String = "/__utm.gif"; /** * The remote service mode GIF url. */ public var remoteGIFpath:String = "http://www.google-analytics.com/__utm.gif"; /** * The secure remote service mode GIF url. */ public var secureRemoteGIFpath:String = "https://ssl.google-analytics.com/__utm.gif"; /** * Default cookie path to set in document header. */ public var cookiePath:String = "/" ; //SharedObjectPath /** * Delimiter for e-commerce transaction fields. */ public var transactionFieldDelim:String = "|"; /** * The domain name value. */ public var domainName:String = ""; /** * To be able to track in local mode (when protocol is file://) */ public var allowLocalTracking:Boolean = true; /** * Creates a new Configuration instance. */ public function Configuration( debug:DebugConfiguration = null ) { _debug = debug; _domain = new Domain( DomainNameMode.auto, "", _debug ); serverMode = ServerOperationMode.remote; _initOrganicSources(); } /** * @private */ private function _initOrganicSources():void { addOrganicSource( google, googleSearchParam ); addOrganicSource( "yahoo", "p" ); addOrganicSource( "msn", "q" ); addOrganicSource( "aol", "query" ); addOrganicSource( "aol", "encquery" ); addOrganicSource( "lycos", "query" ); addOrganicSource( "ask", "q" ); addOrganicSource( "altavista", "q" ); addOrganicSource( "netscape", "query" ); addOrganicSource( "cnn", "query" ); addOrganicSource( "looksmart", "qt" ); addOrganicSource( "about", "terms" ); addOrganicSource( "mamma", "query" ); addOrganicSource( "alltheweb", "q" ); addOrganicSource( "gigablast", "q" ); addOrganicSource( "voila", "rdata" ); addOrganicSource( "virgilio", "qs" ); addOrganicSource( "live", "q" ); addOrganicSource( "baidu", "wd" ); addOrganicSource( "alice", "qs" ); addOrganicSource( "yandex", "text" ); addOrganicSource( "najdi", "q" ); addOrganicSource( "aol", "q" ); addOrganicSource( "club-internet", "q" ); addOrganicSource( "mama", "query" ); addOrganicSource( "seznam", "q" ); addOrganicSource( "search", "q" ); addOrganicSource( "wp", "szukaj" ); addOrganicSource( "onet", "qt" ); addOrganicSource( "netsprint", "q" ); addOrganicSource( "google.interia", "q" ); addOrganicSource( "szukacz", "q" ); addOrganicSource( "yam", "k" ); addOrganicSource( "pchome", "q" ); addOrganicSource( "kvasir", "searchExpr" ); addOrganicSource( "sesam", "q" ); addOrganicSource( "ozu", "q" ); addOrganicSource( "terra", "query" ); addOrganicSource( "nostrum", "query" ); addOrganicSource( "mynet", "q" ); addOrganicSource( "ekolay", "q" ); addOrganicSource( "search.ilse", "search_for" ); } /** * Indicates the name of the cookie. */ public function get cookieName():String { return _cookieName; } /** * Indicates the version String representation of the application. */ public function get version():String { return _version; } /** * Domain name for cookies. * (auto | none | domain) * If this variable is set to "auto", * then we will try to resolve the domain name * based on the HTMLDocument object. * * note: * for Flash we try to auto detect * the domain name by using the URL info * if we are in HTTP or HTTPS * * if we can not detect the protocol or find file:// * then the "auto" domain is none. */ public function get domain():Domain { return _domain; } /** * Indicates the Organic reference. */ public function get organic():Organic { return _organic; } // /** // * Indicates the collection (Array) of all organic sources. // */ // public function get organicSources():Array // { // return _organicSources; // } // // /** // * @private // */ // public function set organicSources(sources:Array):void // { // _organicSources = sources; // } /** * Indicates the sample rate value of the application. */ public function get sampleRate():Number { return _sampleRate; } /** * Sampling percentage of visitors to track. */ public function set sampleRate( value:Number ):void { if( value <= 0 ) { value = 0.1; } if( value > 1 ) { value = 1; } value = Number( value.toFixed( 2 ) ); _sampleRate = value; } /** * This is the max number of tracking requests to the backend * allowed per session. */ public function get trackingLimitPerSession():int { return _trackingLimitPerSession; } /** * Adds a new organic source. * @param engine The engine value. * @param keyword The keyword of the specified engine value. */ public function addOrganicSource(engine:String, keyword:String):void { try { _organic.addSource( engine, keyword ); } catch( e:Error ) { if( _debug && _debug.active ) { _debug.warning( e.message ); } } } } }
remove params related to idle timer
remove params related to idle timer
ActionScript
apache-2.0
DimaBaliakin/gaforflash,soumavachakraborty/gaforflash,jeremy-wischusen/gaforflash,jeremy-wischusen/gaforflash,drflash/gaforflash,Miyaru/gaforflash,jisobkim/gaforflash,Vigmar/gaforflash,jisobkim/gaforflash,mrthuanvn/gaforflash,dli-iclinic/gaforflash,mrthuanvn/gaforflash,Vigmar/gaforflash,soumavachakraborty/gaforflash,Miyaru/gaforflash,DimaBaliakin/gaforflash,dli-iclinic/gaforflash,drflash/gaforflash
ad990ea02ecb2a7825e2f8733f40cc937343a6fb
src/com/esri/builder/controllers/WidgetSyncController.as
src/com/esri/builder/controllers/WidgetSyncController.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.controllers.supportClasses.WellKnownDirectories; import com.esri.builder.eventbus.AppEvent; import com.esri.builder.model.Model; import com.esri.builder.model.WidgetType; import com.esri.builder.supportClasses.LogUtil; import flash.filesystem.File; import mx.logging.ILogger; import mx.logging.Log; public class WidgetSyncController { private static const LOG:ILogger = LogUtil.createLogger(WidgetSyncController); private var addedWidgetType:WidgetType; public function WidgetSyncController() { AppEvent.addListener(AppEvent.WIDGET_ADDED_TO_APP, widgetAddedToAppHandler); } private function widgetAddedToAppHandler(event:AppEvent):void { addedWidgetType = event.data as WidgetType; copyMissingFilesToApp(getWidgetDirectory()); } private function getWidgetDirectory():File { var widgetDirectory:File; if (addedWidgetType.isCustom) { widgetDirectory = WellKnownDirectories.getInstance().customFlexViewer.resolvePath("widgets/" + addedWidgetType.name); } else { widgetDirectory = WellKnownDirectories.getInstance().bundledFlexViewer.resolvePath("widgets/" + addedWidgetType.name); } return widgetDirectory; } private function copyMissingFilesToApp(widgetDirectory:File):void { if (!widgetDirectory.exists) { return; } if (Log.isInfo()) { LOG.info("Copying missing widget files."); } var directoryContents:Array = widgetDirectory.getDirectoryListing(); for each (var fileOrFolder:File in directoryContents) { if (fileOrFolder.isDirectory) { copyMissingFilesToApp(fileOrFolder); } else { copySafelyToApp(fileOrFolder); } } } private function copySafelyToApp(fileOrFolder:File):void { var relativePathToWidgetDirectory:String = getRelativePathToWidgetDirectory(fileOrFolder); var fileDestination:File = Model.instance.appDir.resolvePath(relativePathToWidgetDirectory); //only copying missing files if (!fileDestination.exists) { if (Log.isDebug()) { LOG.debug("Copying {0} to {1}", fileOrFolder.nativePath, fileDestination.nativePath); } try { fileOrFolder.copyTo(fileDestination); } catch (error:Error) { if (Log.isWarn()) { LOG.warn("Could not copy {0} to {1}: {2}", fileOrFolder.nativePath, fileDestination.nativePath, error.toString()); } //fail silently } } } private function getRelativePathToWidgetDirectory(fileOrFolder:File):String { if (addedWidgetType.isCustom) { return WellKnownDirectories.getInstance().customFlexViewer.getRelativePath(fileOrFolder); } else { return WellKnownDirectories.getInstance().bundledFlexViewer.getRelativePath(fileOrFolder); } } } }
//////////////////////////////////////////////////////////////////////////////// // 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.controllers.supportClasses.WellKnownDirectories; import com.esri.builder.eventbus.AppEvent; import com.esri.builder.model.Model; import com.esri.builder.model.WidgetType; import com.esri.builder.supportClasses.LogUtil; import flash.filesystem.File; import mx.logging.ILogger; import mx.logging.Log; public class WidgetSyncController { private static const LOG:ILogger = LogUtil.createLogger(WidgetSyncController); private var addedWidgetType:WidgetType; public function WidgetSyncController() { AppEvent.addListener(AppEvent.WIDGET_ADDED_TO_APP, widgetAddedToAppHandler); } private function widgetAddedToAppHandler(event:AppEvent):void { addedWidgetType = event.data as WidgetType; copyMissingFilesToApp(getWidgetDirectory()); } private function getWidgetDirectory():File { return addedWidgetType.isCustom ? WellKnownDirectories.getInstance().customFlexViewer.resolvePath("widgets/" + addedWidgetType.name) : WellKnownDirectories.getInstance().bundledFlexViewer.resolvePath("widgets/" + addedWidgetType.name); } private function copyMissingFilesToApp(widgetDirectory:File):void { if (!widgetDirectory.exists) { return; } if (Log.isInfo()) { LOG.info("Copying missing widget files."); } var directoryContents:Array = widgetDirectory.getDirectoryListing(); for each (var fileOrFolder:File in directoryContents) { if (fileOrFolder.isDirectory) { copyMissingFilesToApp(fileOrFolder); } else { copySafelyToApp(fileOrFolder); } } } private function copySafelyToApp(fileOrFolder:File):void { var relativePathToWidgetDirectory:String = getRelativePathToWidgetDirectory(fileOrFolder); var fileDestination:File = Model.instance.appDir.resolvePath(relativePathToWidgetDirectory); //only copying missing files if (!fileDestination.exists) { if (Log.isDebug()) { LOG.debug("Copying {0} to {1}", fileOrFolder.nativePath, fileDestination.nativePath); } try { fileOrFolder.copyTo(fileDestination); } catch (error:Error) { if (Log.isWarn()) { LOG.warn("Could not copy {0} to {1}: {2}", fileOrFolder.nativePath, fileDestination.nativePath, error.toString()); } //fail silently } } } private function getRelativePathToWidgetDirectory(fileOrFolder:File):String { return addedWidgetType.isCustom ? WellKnownDirectories.getInstance().customFlexViewer.getRelativePath(fileOrFolder) : WellKnownDirectories.getInstance().bundledFlexViewer.getRelativePath(fileOrFolder); } } }
Simplify WidgetSyncController logic.
Simplify WidgetSyncController logic.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
86f0387ed9e354ce5dbbde9f990da585b887c359
src/com/benoitfreslon/layoutmanager/LayoutLoader.as
src/com/benoitfreslon/layoutmanager/LayoutLoader.as
package com.benoitfreslon.layoutmanager { import flash.display.MovieClip; import flash.events.Event; import flash.utils.getDefinitionByName; import starling.display.Button; import starling.display.DisplayObject; import starling.display.DisplayObjectContainer; import starling.display.Image; import starling.display.Sprite; import starling.text.TextField; import starling.utils.AssetManager; /** * Loader of Layout * @version 1.01 * @author Benoît Freslon */ public class LayoutLoader { private var _movieclip : MovieClip; private var _displayObject : DisplayObjectContainer; private var _assetManager : AssetManager; static public var debug:Boolean = false; private var onLoad : Function = function() : void { }; public function LayoutLoader() { } public function loadLayout( displayObject : DisplayObjectContainer, LayoutClass : Class, assetManager : AssetManager, callBack : Function = null ) : void { _displayObject = displayObject; _assetManager = assetManager; _movieclip = new LayoutClass(); _movieclip.addEventListener( Event.ENTER_FRAME, layoutLoaded ); if ( onLoad != null ) onLoad = callBack } private function layoutLoaded( e : Event ) : void { _movieclip.removeEventListener( Event.ENTER_FRAME, layoutLoaded ); var child : BFObject; var n : int = _movieclip.numChildren; for ( var i : uint = 0; i < n; ++i ) { child = _movieclip.getChildAt( i ) as BFObject; if ( child && child is BFObject ) { if ( child.mainClass ) { var objectClass : Class if ( child.className ) { objectClass = getDefinitionByName( child.className ) as Class; } else { objectClass = getDefinitionByName( child.mainClass ) as Class; } var obj : DisplayObject; if ( child.mainClass == "starling.display.Image" ) { obj = addImage( objectClass, child as BFImage ); } else if ( child.mainClass == "starling.display.ButtonExtended" ) { obj = addButton( objectClass, child as BFButton ); } else if ( child.mainClass == "starling.text.TextField" ) { obj = addTextField( objectClass, child as BFTextField ); } else if ( child.mainClass == "starling.display.sprite" ) { obj = addSprite( objectClass, child as BFSprite ); } else { trace( new Error( "No mainClass defined " + child ) ); } if ( child.hasOwnProperty( "params" ) ) { for ( var metatags : String in child.params ) { if ( obj.hasOwnProperty( metatags ) ) obj[ metatags ] = child.params[ metatags ]; } } obj.name = child.name; obj.pivotX = obj.width / 2; obj.pivotY = obj.height / 2; obj.x = child.x; obj.y = child.y; //obj.scaleX = child.scaleX; //obj.scaleY = child.scaleY; obj.alpha = child.alpha; obj.rotation = child.rotation; obj.visible = child.isVisible; _displayObject.addChild( obj ); if ( obj.hasOwnProperty( "tag" ) ) { obj[ "tag" ] = child.tag; } if ( _displayObject.hasOwnProperty( child.name ) ) { _displayObject[ child.name ] = obj as objectClass; } } else { trace( new Error( "No className defined " + child ) ); } } } loaded(); } private function loaded() : void { _assetManager = null; _displayObject = null; _movieclip = null; onLoad(); } private function addImage( objectClass : Class, child : BFImage ) : Image { var img : Image = new objectClass( _assetManager.getTexture( child.texture ) ) as Image; //img.pivotX = img.width / 2; //img.pivotY = img.height / 2; return img; } private function addSprite( objectClass : Class, child : BFSprite ) : Sprite { var s : Sprite = new objectClass() as Sprite; return s; } private function addTextField( objectClass : Class, child : BFTextField ) : TextField { var t : TextField = new objectClass( child.width, child.height, "" ) as TextField; t.fontName = child.fontName; t.fontSize = child.fontSize; t.text = child.text; t.color = child.color; t.hAlign = child.hAlign; t.vAlign = child.vAlign; t.bold = child.bold; t.italic = child.italic; t.underline = child.underline; //t.pivotX = t.width / 2; //t.pivotY = t.height / 2; return t; } private function addButton( objectClass : Class, child : BFButton ) : Button { var bt : Button = new objectClass( _assetManager.getTexture( child.upState ) ) as Button; bt.fontBold = child.fontBold; bt.fontColor = child.fontColor; bt.fontName = child.fontName; bt.fontSize = child.fontSize; bt.text = child.text; //bt.pivotX = bt.width / 2; if ( child.downState ) bt.downState = _assetManager.getTexture( child.downState ); trace(child.onTouch, bt.hasOwnProperty( "onTouch" ), _displayObject.hasOwnProperty( child.onTouch )); if ( bt.hasOwnProperty( "onTouch" ) && _displayObject.hasOwnProperty( child.onTouch ) ) { trace(bt[ "onTouch" ], child.onTouch) bt[ "onTouch" ] = _displayObject[ child.onTouch ]; } else if (bt.hasOwnProperty( "onTouch" )) { trace( new Error("The public method " + child.onTouch + " is not defined in " + _displayObject)); } return bt; } } }
package com.benoitfreslon.layoutmanager { import flash.display.MovieClip; import flash.events.Event; import flash.utils.getDefinitionByName; import starling.display.Button; import starling.display.DisplayObject; import starling.display.DisplayObjectContainer; import starling.display.Image; import starling.display.Sprite; import starling.text.TextField; import starling.utils.AssetManager; /** * Loader of Layout * @version 1.01 * @author Benoît Freslon */ public class LayoutLoader { private var _movieclip : MovieClip; private var _displayObject : DisplayObjectContainer; private var _assetManager : AssetManager; static public var debug:Boolean = false; private var onLoad : Function = function() : void { }; public function LayoutLoader() { } public function loadLayout( displayObject : DisplayObjectContainer, LayoutClass : Class, assetManager : AssetManager, callBack : Function = null ) : void { _displayObject = displayObject; _assetManager = assetManager; _movieclip = new LayoutClass(); _movieclip.addEventListener( Event.ENTER_FRAME, layoutLoaded ); if ( onLoad != null ) onLoad = callBack } private function layoutLoaded( e : Event ) : void { _movieclip.removeEventListener( Event.ENTER_FRAME, layoutLoaded ); var child : BFObject; var n : int = _movieclip.numChildren; for ( var i : uint = 0; i < n; ++i ) { child = _movieclip.getChildAt( i ) as BFObject; if ( child && child is BFObject ) { if ( child.mainClass ) { var objectClass : Class if ( child.className ) { objectClass = getDefinitionByName( child.className ) as Class; } else { objectClass = getDefinitionByName( child.mainClass ) as Class; } var obj : DisplayObject; if ( child.mainClass == "starling.display.Image" ) { obj = addImage( objectClass, child as BFImage ); } else if ( child.mainClass == "starling.display.ButtonExtended" ) { obj = addButton( objectClass, child as BFButton ); } else if ( child.mainClass == "starling.text.TextField" ) { obj = addTextField( objectClass, child as BFTextField ); } else if ( child.mainClass == "starling.display.sprite" ) { obj = addSprite( objectClass, child as BFSprite ); } else { trace( new Error( "No mainClass defined " + child ) ); } if ( child.hasOwnProperty( "params" ) ) { for ( var metatags : String in child.params ) { if ( obj.hasOwnProperty( metatags ) ) obj[ metatags ] = child.params[ metatags ]; } } obj.name = child.name; obj.pivotX = obj.width / 2; obj.pivotY = obj.height / 2; obj.x = child.x; obj.y = child.y; //obj.scaleX = child.scaleX; //obj.scaleY = child.scaleY; obj.alpha = child.alpha; obj.rotation = child.rotation; obj.visible = child.isVisible; _displayObject.addChild( obj ); if ( obj.hasOwnProperty( "tag" ) ) { obj[ "tag" ] = child.tag; } if ( _displayObject.hasOwnProperty( child.name ) ) { _displayObject[ child.name ] = obj as objectClass; } } else { trace( new Error( "No className defined " + child ) ); } } } loaded(); } private function loaded() : void { _assetManager = null; _displayObject = null; _movieclip = null; onLoad(); } private function addImage( objectClass : Class, child : BFImage ) : Image { var img : Image = new objectClass( _assetManager.getTexture( child.texture ) ) as Image; //img.pivotX = img.width / 2; //img.pivotY = img.height / 2; return img; } private function addSprite( objectClass : Class, child : BFSprite ) : Sprite { var s : Sprite = new objectClass() as Sprite; return s; } private function addTextField( objectClass : Class, child : BFTextField ) : TextField { var t : TextField = new objectClass( child.width, child.height, "" ) as TextField; t.fontName = child.fontName; t.fontSize = child.fontSize; t.text = child.text; t.color = child.color; t.hAlign = child.hAlign; t.vAlign = child.vAlign; t.bold = child.bold; t.italic = child.italic; t.underline = child.underline; //t.pivotX = t.width / 2; //t.pivotY = t.height / 2; return t; } private function addButton( objectClass : Class, child : BFButton ) : Button { var bt : Button = new objectClass( _assetManager.getTexture( child.upState ) ) as Button; bt.fontBold = child.fontBold; bt.fontColor = child.fontColor; bt.fontName = child.fontName; bt.fontSize = child.fontSize; bt.text = child.text; //bt.pivotX = bt.width / 2; if ( child.downState ) bt.downState = _assetManager.getTexture( child.downState ); if ( bt.hasOwnProperty( "onTouch" ) && _displayObject.hasOwnProperty( child.onTouch ) ) { bt[ "onTouch" ] = _displayObject[ child.onTouch ]; } else if (bt.hasOwnProperty( "onTouch" )) { trace( new Error("The public method " + child.onTouch + " is not defined in " + _displayObject)); } return bt; } } }
Remove trace
Remove trace
ActionScript
mit
BenoitFreslon/benoitfreslon-layoutmanager
724c7a1fc808eeee6e4ca2df636e92347abf0bbc
dolly-framework/src/test/actionscript/dolly/CopierTest.as
dolly-framework/src/test/actionscript/dolly/CopierTest.as
package dolly { import dolly.core.dolly_internal; import dolly.data.ClassLevelCopyable; import dolly.data.PropertyLevelCopyable; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertNotNull; import org.flexunit.asserts.assertNull; use namespace dolly_internal; public class CopierTest { private var classLevelCopyable:ClassLevelCopyable; private var classLevelCopyableType:Type; private var propertyLevelCopyable:PropertyLevelCopyable; private var propertyLevelCopyableType:Type; [Before] public function before():void { classLevelCopyable = new ClassLevelCopyable(); classLevelCopyable.property1 = "value 1"; classLevelCopyable.property2 = "value 2"; classLevelCopyable.property3 = "value 3"; classLevelCopyable.writableField = "value 4"; propertyLevelCopyable = new PropertyLevelCopyable(); propertyLevelCopyable.property1 = "value 1"; propertyLevelCopyable.property2 = "value 2"; propertyLevelCopyable.property3 = "value 3"; propertyLevelCopyable.writableField = "value 4"; classLevelCopyableType = Type.forInstance(classLevelCopyable); propertyLevelCopyableType = Type.forInstance(propertyLevelCopyable); } [After] public function after():void { classLevelCopyable = null; classLevelCopyableType = null; propertyLevelCopyable = null; propertyLevelCopyableType = null; } [Test] public function testGetCopyableFieldsForType():void { var copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableType); assertNotNull(copyableFields); assertEquals(4, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); assertNotNull(copyableFields[3]); copyableFields = Copier.getCopyableFieldsForType(propertyLevelCopyableType); assertNotNull(copyableFields); assertEquals(3, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); } [Test] public function testCopyWithClassLevelMetadata():void { const copy:ClassLevelCopyable = Copier.copy(classLevelCopyable); assertNotNull(copy); assertNotNull(copy.property1); assertEquals(copy.property1, classLevelCopyable.property1); assertNotNull(copy.property2); assertEquals(copy.property2, classLevelCopyable.property2); assertNotNull(copy.property3); assertEquals(copy.property3, classLevelCopyable.property3); assertNotNull(copy.writableField); assertEquals(copy.writableField, classLevelCopyable.writableField); } [Test] public function testCopyWithPropertyLevelMetadata():void { const copy:PropertyLevelCopyable = Copier.copy(propertyLevelCopyable); assertNotNull(copy); assertNull(copy.property1); assertNotNull(copy.property2); assertEquals(copy.property2, classLevelCopyable.property2); assertNotNull(copy.property3); assertEquals(copy.property3, classLevelCopyable.property3); assertNotNull(copy.writableField); assertEquals(copy.writableField, classLevelCopyable.writableField); } } }
package dolly { import dolly.core.dolly_internal; import dolly.data.ClassLevelCopyable; import dolly.data.ClassLevelCopyableCloneable; import dolly.data.PropertyLevelCopyable; import dolly.data.PropertyLevelCopyableCloneable; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertNotNull; import org.flexunit.asserts.assertNull; use namespace dolly_internal; public class CopierTest { private var classLevelCopyable:ClassLevelCopyable; private var classLevelCopyableType:Type; private var classLevelCopyableCloneable:ClassLevelCopyableCloneable; private var classLevelCopyableCloneableType:Type; private var propertyLevelCopyable:PropertyLevelCopyable; private var propertyLevelCopyableType:Type; private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable; private var propertyLevelCopyableCloneableType:Type; [Before] public function before():void { classLevelCopyable = new ClassLevelCopyable(); classLevelCopyable.property1 = "value 1"; classLevelCopyable.property2 = "value 2"; classLevelCopyable.property3 = "value 3"; classLevelCopyable.writableField = "value 4"; classLevelCopyableType = Type.forInstance(classLevelCopyable); classLevelCopyableCloneable = new ClassLevelCopyableCloneable(); classLevelCopyableCloneable.property1 = "value 1"; classLevelCopyableCloneable.property2 = "value 2"; classLevelCopyableCloneable.property3 = "value 3"; classLevelCopyableCloneable.writableField = "value 4"; classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable); propertyLevelCopyable = new PropertyLevelCopyable(); propertyLevelCopyable.property1 = "value 1"; propertyLevelCopyable.property2 = "value 2"; propertyLevelCopyable.property3 = "value 3"; propertyLevelCopyable.writableField = "value 4"; propertyLevelCopyableType = Type.forInstance(propertyLevelCopyable); propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable(); propertyLevelCopyableCloneable.property1 = "value 1"; propertyLevelCopyableCloneable.property2 = "value 2"; propertyLevelCopyableCloneable.property3 = "value 3"; propertyLevelCopyableCloneable.writableField = "value 4"; propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable); } [After] public function after():void { classLevelCopyable = null; classLevelCopyableType = null; classLevelCopyableCloneable = null; classLevelCopyableCloneableType = null; propertyLevelCopyable = null; propertyLevelCopyableType = null; propertyLevelCopyableCloneable = null; propertyLevelCopyableCloneableType = null; } [Test] public function testGetCopyableFieldsForType():void { var copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableType); assertNotNull(copyableFields); assertEquals(4, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); assertNotNull(copyableFields[3]); copyableFields = Copier.getCopyableFieldsForType(classLevelCopyableCloneableType); assertNotNull(copyableFields); assertEquals(4, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); assertNotNull(copyableFields[3]); copyableFields = Copier.getCopyableFieldsForType(propertyLevelCopyableType); assertNotNull(copyableFields); assertEquals(3, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); copyableFields = Copier.getCopyableFieldsForType(propertyLevelCopyableCloneableType); assertNotNull(copyableFields); assertEquals(3, copyableFields.length); assertNotNull(copyableFields[0]); assertNotNull(copyableFields[1]); assertNotNull(copyableFields[2]); } [Test] public function testCopyWithClassLevelMetadata():void { const copy1:ClassLevelCopyable = Copier.copy(classLevelCopyable); assertNotNull(copy1); assertNotNull(copy1.property1); assertEquals(copy1.property1, classLevelCopyable.property1); assertNotNull(copy1.property2); assertEquals(copy1.property2, classLevelCopyable.property2); assertNotNull(copy1.property3); assertEquals(copy1.property3, classLevelCopyable.property3); assertNotNull(copy1.writableField); assertEquals(copy1.writableField, classLevelCopyable.writableField); const copy2:ClassLevelCopyableCloneable = Copier.copy(classLevelCopyableCloneable); assertNotNull(copy2); assertNotNull(copy2.property1); assertEquals(copy2.property1, classLevelCopyable.property1); assertNotNull(copy2.property2); assertEquals(copy2.property2, classLevelCopyable.property2); assertNotNull(copy2.property3); assertEquals(copy2.property3, classLevelCopyable.property3); assertNotNull(copy2.writableField); assertEquals(copy2.writableField, classLevelCopyable.writableField); } [Test] public function testCopyWithPropertyLevelMetadata():void { const copy1:PropertyLevelCopyable = Copier.copy(propertyLevelCopyable); assertNotNull(copy1); assertNull(copy1.property1); assertNotNull(copy1.property2); assertEquals(copy1.property2, classLevelCopyable.property2); assertNotNull(copy1.property3); assertEquals(copy1.property3, classLevelCopyable.property3); assertNotNull(copy1.writableField); assertEquals(copy1.writableField, classLevelCopyable.writableField); const copy2:PropertyLevelCopyableCloneable = Copier.copy(propertyLevelCopyableCloneable); assertNotNull(copy2); assertNull(copy2.property1); assertNotNull(copy2.property2); assertEquals(copy2.property2, classLevelCopyable.property2); assertNotNull(copy2.property3); assertEquals(copy2.property3, classLevelCopyable.property3); assertNotNull(copy2.writableField); assertEquals(copy2.writableField, classLevelCopyable.writableField); } } }
Test classes ClassLevelCopyableCloneable and PropertyLevelCopyableCloneable in CopierTest.
Test classes ClassLevelCopyableCloneable and PropertyLevelCopyableCloneable in CopierTest.
ActionScript
mit
Yarovoy/dolly
010ca426b22a1a85ccdf1dcfb2a23b6c2a63583d
exporter/src/main/as/flump/export/Exporter.as
exporter/src/main/as/flump/export/Exporter.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.desktop.NativeApplication; import flash.display.NativeWindow; import flash.display.Stage; import flash.display.StageQuality; import flash.events.Event; import flash.events.MouseEvent; import flash.filesystem.File; import flash.net.SharedObject; import com.adobe.crypto.MD5; import deng.fzip.FZip; import deng.fzip.FZipFile; import flump.bytesToXML; import flump.display.Movie; import flump.executor.Executor; import flump.executor.Future; import flump.export.Ternary; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import flump.xfl.XflMovie; import mx.collections.ArrayCollection; import spark.components.DataGrid; import spark.components.DropDownList; import spark.components.List; import spark.components.Window; import spark.events.GridSelectionEvent; import starling.display.Sprite; import com.threerings.util.F; import com.threerings.util.Log; import com.threerings.util.StringUtil; public class Exporter { public static const NA :NativeApplication = NativeApplication.nativeApplication; protected static const IMPORT_ROOT :String = "IMPORT_ROOT"; protected static const AUTHORED_RESOLUTION :String = "AUTHORED_RESOLUTION"; public function Exporter (win :ExporterWindow) { Log.setLevel("", Log.INFO); _win = win; _errors = _win.errors; _libraries = _win.libraries; _authoredResolution = _win.authoredResolutionPopup; _authoredResolution.dataProvider = new ArrayCollection(DeviceType.values().map( function (type :DeviceType, ..._) :Object { return new DeviceSelection(type); })); var initialSelection :DeviceType = null; if (_settings.data.hasOwnProperty(AUTHORED_RESOLUTION)) { try { initialSelection = DeviceType.valueOf(_settings.data[AUTHORED_RESOLUTION]); } catch (e :Error) {} } if (initialSelection == null) initialSelection = DeviceType.IPHONE_RETINA; _authoredResolution.selectedIndex = DeviceType.values().indexOf(initialSelection); _authoredResolution.addEventListener(Event.CHANGE, function (..._) :void { var selectedType :DeviceType = DeviceSelection(_authoredResolution.selectedItem).type; _settings.data[AUTHORED_RESOLUTION] = selectedType.name(); }); function updateExportEnabled (..._) :void { _win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 && _libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); } _libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { log.info("Changed", "selected", _libraries.selectedIndices); updateExportEnabled(); _win.preview.enabled = _libraries.selectedItem.isValid; }); _win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void { setImport(_importChooser.dir); }); _win.export.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var status :DocStatus in _libraries.selectedItems) { exportFlashDocument(status); } }); _win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void { showPreviewWindow(_libraries.selectedItem.lib); }); _importChooser = new DirChooser(_settings, "IMPORT_ROOT", _win.importRoot, _win.browseImport); _importChooser.changed.add(setImport); setImport(_importChooser.dir); _exportChooser = new DirChooser(_settings, "EXPORT_ROOT", _win.exportRoot, _win.browseExport); _exportChooser.changed.add(updateExportEnabled); function updatePublisher (..._) :void { if (_exportChooser.dir == null) _publisher = null; else { _publisher = new Publisher(_exportChooser.dir, new XMLFormat(), new JSONFormat(), new StarlingFormat()); } }; _exportChooser.changed.add(updatePublisher); updatePublisher(); _win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); }); } protected function setImport (root :File) :void { _libraries.dataProvider.removeAll(); _errors.dataProvider.removeAll(); if (root == null) return; _rootLen = root.nativePath.length + 1; if (_docFinder != null) _docFinder.shutdownNow(); _docFinder = new Executor(1); findFlashDocuments(root, _docFinder, true); _win.reload.enabled = true; } protected function showPreviewWindow (lib :XflLibrary) :void { if (_previewController == null || _previewWindow.closed || _previewControls.closed) { _previewWindow = new PreviewWindow(); _previewControls = new PreviewControlsWindow(); _previewWindow.started = function (container :Sprite) :void { _previewController = new PreviewController(lib, container, _previewWindow, _previewControls); } _previewWindow.open(); _previewControls.open(); preventWindowClose(_previewWindow.nativeWindow); preventWindowClose(_previewControls.nativeWindow); } else { _previewController.lib = lib; _previewWindow.nativeWindow.visible = true; _previewControls.nativeWindow.visible = true; } } // Causes a window to be hidden, rather than closed, when its close box is clicked protected static function preventWindowClose (window :NativeWindow) :void { window.addEventListener(Event.CLOSING, function (e :Event) :void { e.preventDefault(); window.visible = false; }); } protected var _previewController :PreviewController; protected var _previewWindow :PreviewWindow; protected var _previewControls :PreviewControlsWindow; protected function findFlashDocuments (base :File, exec :Executor, ignoreXflAtBase :Boolean = false) :void { Files.list(base, exec).succeeded.add(function (files :Array) :void { if (exec.isShutdown) return; for each (var file :File in files) { if (Files.hasExtension(file, "xfl")) { if (ignoreXflAtBase) { _errors.dataProvider.addItem(new ParseError(base.nativePath, ParseError.CRIT, "The import directory can't be an XFL directory, did you mean " + base.parent.nativePath + "?")); } else addFlashDocument(file.parent); return; } } for each (file in files) { if (StringUtil.startsWith(file.name, ".", "RECOVER_")) { continue; // Ignore hidden VCS directories, and recovered backups created by Flash } if (file.isDirectory) findFlashDocuments(file, exec); else if (Files.hasExtension(file, "fla")) addFlashDocument(file); } }); } protected function addFlashDocument (file :File) :void { const status :DocStatus = new DocStatus(file, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null); _libraries.dataProvider.addItem(status); loadFlashDocument(status); } protected function exportFlashDocument (status :DocStatus) :void { const stage :Stage = NA.activeWindow.stage; const prevQuality :String = stage.quality; stage.quality = StageQuality.BEST; _publisher.publish(status.lib, DeviceSelection(_authoredResolution.selectedItem).type); stage.quality = prevQuality; status.updateModified(Ternary.FALSE); } protected function loadFlashDocument (status :DocStatus) :void { if (Files.hasExtension(status.file, "xfl")) status.file = status.file.parent; if (status.file.isDirectory) { const name :String = status.file.nativePath .substring(_rootLen).replace(File.separator, "/"); const load :Future = new XflLoader().load(name, status.file); load.succeeded.add(function (lib :XflLibrary) :void { status.lib = lib; status.updateModified(Ternary.of(_publisher == null || _publisher.modified(lib))); for each (var err :ParseError in lib.getErrors()) _errors.dataProvider.addItem(err); status.updateValid(Ternary.of(lib.valid)); }); load.failed.add(function (e :Error) :void { trace("Failed to load " + status.file.nativePath + ":" + e); status.updateValid(Ternary.FALSE); throw e; }); } else loadFla(status.file); } protected function loadFla (file :File) :void { log.info("fla support not implemented", "path", file.nativePath); return; Files.load(file).succeeded.add(function (file :File) :void { const zip :FZip = new FZip(); zip.loadBytes(file.data); const files :Array = []; for (var ii :int = 0; ii < zip.getFileCount(); ii++) files.push(zip.getFileAt(ii)); const xmls :Array = F.filter(files, function (fz :FZipFile) :Boolean { return StringUtil.endsWith(fz.filename, ".xml"); }); const movies :Array = F.filter(xmls, function (fz :FZipFile) :Boolean { return StringUtil.startsWith(fz.filename, "LIBRARY/Animations/"); }); const textures :Array = F.filter(xmls, function (fz :FZipFile) :Boolean { return StringUtil.startsWith(fz.filename, "LIBRARY/Textures/"); }); function toFn (fz :FZipFile) :String { return fz.filename }; log.info("Loaded", "bytes", file.data.length, "movies", F.map(movies, toFn), "textures", F.map(textures, toFn)); for each (var fz :FZipFile in movies) { XflMovie.parse(null, bytesToXML(fz.content), MD5.hashBytes(fz.content)); } NA.exit(0); }); } protected var _rootLen :int; protected var _publisher :Publisher; protected var _docFinder :Executor; protected var _win :ExporterWindow; protected var _libraries :DataGrid; protected var _errors :DataGrid; protected var _exportChooser :DirChooser; protected var _importChooser :DirChooser; protected var _authoredResolution :DropDownList; protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter"); private static const log :Log = Log.getLog(Exporter); } } import flump.export.DeviceType; class DeviceSelection { public var type :DeviceType; public function DeviceSelection (type :DeviceType) { this.type = type; } public function toString () :String { return type.displayName + " (" + type.resWidth + "x" + type.resHeight + ")"; } } import flash.events.EventDispatcher; import flash.filesystem.File; import flump.export.Ternary; import flump.xfl.XflLibrary; import mx.core.IPropertyChangeNotifier; import mx.events.PropertyChangeEvent; class DocStatus extends EventDispatcher implements IPropertyChangeNotifier { public var path :String; public var modified :String; public var valid :String = QUESTION; public var file :File; public var lib :XflLibrary; public function DocStatus (file :File, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) { this.file = file; this.lib = lib; path = file.nativePath.substring(rootLen); _uid = path; updateModified(modified); updateValid(valid); } public function updateValid (newValid :Ternary) :void { changeField("valid", function (..._) :void { if (newValid == Ternary.TRUE) valid = CHECK; else if (newValid == Ternary.FALSE) valid = FROWN; else valid = QUESTION; }); } public function get isValid () :Boolean { return valid == CHECK; } public function updateModified (newModified :Ternary) :void { changeField("modified", function (..._) :void { if (newModified == Ternary.TRUE) modified = CHECK; else if (newModified == Ternary.FALSE) modified = " "; else modified = QUESTION; }); } protected function changeField(fieldName :String, modifier :Function) :void { const oldValue :Object = this[fieldName]; modifier(); const newValue :Object = this[fieldName]; dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue)); } public function get uid () :String { return _uid; } public function set uid (uid :String) :void { _uid = uid; } protected var _uid :String; protected static const QUESTION :String = "?"; protected static const FROWN :String = "☹"; protected static const CHECK :String = "✓"; }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.desktop.NativeApplication; import flash.display.NativeWindow; import flash.display.Stage; import flash.display.StageQuality; import flash.events.Event; import flash.events.MouseEvent; import flash.filesystem.File; import flash.net.SharedObject; import com.adobe.crypto.MD5; import deng.fzip.FZip; import deng.fzip.FZipFile; import flump.bytesToXML; import flump.display.Movie; import flump.executor.Executor; import flump.executor.Future; import flump.export.Ternary; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import flump.xfl.XflMovie; import mx.collections.ArrayCollection; import mx.events.PropertyChangeEvent; import spark.components.DataGrid; import spark.components.DropDownList; import spark.components.List; import spark.components.Window; import spark.events.GridSelectionEvent; import starling.display.Sprite; import com.threerings.util.F; import com.threerings.util.Log; import com.threerings.util.StringUtil; public class Exporter { public static const NA :NativeApplication = NativeApplication.nativeApplication; protected static const IMPORT_ROOT :String = "IMPORT_ROOT"; protected static const AUTHORED_RESOLUTION :String = "AUTHORED_RESOLUTION"; public function Exporter (win :ExporterWindow) { Log.setLevel("", Log.INFO); _win = win; _errors = _win.errors; _libraries = _win.libraries; _authoredResolution = _win.authoredResolutionPopup; _authoredResolution.dataProvider = new ArrayCollection(DeviceType.values().map( function (type :DeviceType, ..._) :Object { return new DeviceSelection(type); })); var initialSelection :DeviceType = null; if (_settings.data.hasOwnProperty(AUTHORED_RESOLUTION)) { try { initialSelection = DeviceType.valueOf(_settings.data[AUTHORED_RESOLUTION]); } catch (e :Error) {} } if (initialSelection == null) initialSelection = DeviceType.IPHONE_RETINA; _authoredResolution.selectedIndex = DeviceType.values().indexOf(initialSelection); _authoredResolution.addEventListener(Event.CHANGE, function (..._) :void { var selectedType :DeviceType = DeviceSelection(_authoredResolution.selectedItem).type; _settings.data[AUTHORED_RESOLUTION] = selectedType.name(); }); function updatePreviewAndExport (..._) :void { _win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 && _libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); var status :DocStatus = _libraries.selectedItem as DocStatus; _win.preview.enabled = (status != null && status.isValid); } var curSelection :DocStatus = null; _libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { log.info("Changed", "selected", _libraries.selectedIndices); updatePreviewAndExport(); if (curSelection != null) { curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } var newSelection :DocStatus = _libraries.selectedItem as DocStatus; if (newSelection != null) { newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } curSelection = newSelection; }); _win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void { setImport(_importChooser.dir); updatePreviewAndExport(); }); _win.export.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var status :DocStatus in _libraries.selectedItems) { exportFlashDocument(status); } }); _win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void { showPreviewWindow(_libraries.selectedItem.lib); }); _importChooser = new DirChooser(_settings, "IMPORT_ROOT", _win.importRoot, _win.browseImport); _importChooser.changed.add(setImport); setImport(_importChooser.dir); _exportChooser = new DirChooser(_settings, "EXPORT_ROOT", _win.exportRoot, _win.browseExport); _exportChooser.changed.add(updatePreviewAndExport); function updatePublisher (..._) :void { if (_exportChooser.dir == null) _publisher = null; else { _publisher = new Publisher(_exportChooser.dir, new XMLFormat(), new JSONFormat(), new StarlingFormat()); } }; _exportChooser.changed.add(updatePublisher); updatePublisher(); _win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); }); } protected function setImport (root :File) :void { _libraries.dataProvider.removeAll(); _errors.dataProvider.removeAll(); if (root == null) return; _rootLen = root.nativePath.length + 1; if (_docFinder != null) _docFinder.shutdownNow(); _docFinder = new Executor(1); findFlashDocuments(root, _docFinder, true); _win.reload.enabled = true; } protected function showPreviewWindow (lib :XflLibrary) :void { if (_previewController == null || _previewWindow.closed || _previewControls.closed) { _previewWindow = new PreviewWindow(); _previewControls = new PreviewControlsWindow(); _previewWindow.started = function (container :Sprite) :void { _previewController = new PreviewController(lib, container, _previewWindow, _previewControls); } _previewWindow.open(); _previewControls.open(); preventWindowClose(_previewWindow.nativeWindow); preventWindowClose(_previewControls.nativeWindow); } else { _previewController.lib = lib; _previewWindow.nativeWindow.visible = true; _previewControls.nativeWindow.visible = true; } } // Causes a window to be hidden, rather than closed, when its close box is clicked protected static function preventWindowClose (window :NativeWindow) :void { window.addEventListener(Event.CLOSING, function (e :Event) :void { e.preventDefault(); window.visible = false; }); } protected var _previewController :PreviewController; protected var _previewWindow :PreviewWindow; protected var _previewControls :PreviewControlsWindow; protected function findFlashDocuments (base :File, exec :Executor, ignoreXflAtBase :Boolean = false) :void { Files.list(base, exec).succeeded.add(function (files :Array) :void { if (exec.isShutdown) return; for each (var file :File in files) { if (Files.hasExtension(file, "xfl")) { if (ignoreXflAtBase) { _errors.dataProvider.addItem(new ParseError(base.nativePath, ParseError.CRIT, "The import directory can't be an XFL directory, did you mean " + base.parent.nativePath + "?")); } else addFlashDocument(file.parent); return; } } for each (file in files) { if (StringUtil.startsWith(file.name, ".", "RECOVER_")) { continue; // Ignore hidden VCS directories, and recovered backups created by Flash } if (file.isDirectory) findFlashDocuments(file, exec); else if (Files.hasExtension(file, "fla")) addFlashDocument(file); } }); } protected function addFlashDocument (file :File) :void { const status :DocStatus = new DocStatus(file, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null); _libraries.dataProvider.addItem(status); loadFlashDocument(status); } protected function exportFlashDocument (status :DocStatus) :void { const stage :Stage = NA.activeWindow.stage; const prevQuality :String = stage.quality; stage.quality = StageQuality.BEST; _publisher.publish(status.lib, DeviceSelection(_authoredResolution.selectedItem).type); stage.quality = prevQuality; status.updateModified(Ternary.FALSE); } protected function loadFlashDocument (status :DocStatus) :void { if (Files.hasExtension(status.file, "xfl")) status.file = status.file.parent; if (status.file.isDirectory) { const name :String = status.file.nativePath .substring(_rootLen).replace(File.separator, "/"); const load :Future = new XflLoader().load(name, status.file); load.succeeded.add(function (lib :XflLibrary) :void { status.lib = lib; status.updateModified(Ternary.of(_publisher == null || _publisher.modified(lib))); for each (var err :ParseError in lib.getErrors()) _errors.dataProvider.addItem(err); status.updateValid(Ternary.of(lib.valid)); }); load.failed.add(function (e :Error) :void { trace("Failed to load " + status.file.nativePath + ":" + e); status.updateValid(Ternary.FALSE); throw e; }); } else loadFla(status.file); } protected function loadFla (file :File) :void { log.info("fla support not implemented", "path", file.nativePath); return; Files.load(file).succeeded.add(function (file :File) :void { const zip :FZip = new FZip(); zip.loadBytes(file.data); const files :Array = []; for (var ii :int = 0; ii < zip.getFileCount(); ii++) files.push(zip.getFileAt(ii)); const xmls :Array = F.filter(files, function (fz :FZipFile) :Boolean { return StringUtil.endsWith(fz.filename, ".xml"); }); const movies :Array = F.filter(xmls, function (fz :FZipFile) :Boolean { return StringUtil.startsWith(fz.filename, "LIBRARY/Animations/"); }); const textures :Array = F.filter(xmls, function (fz :FZipFile) :Boolean { return StringUtil.startsWith(fz.filename, "LIBRARY/Textures/"); }); function toFn (fz :FZipFile) :String { return fz.filename }; log.info("Loaded", "bytes", file.data.length, "movies", F.map(movies, toFn), "textures", F.map(textures, toFn)); for each (var fz :FZipFile in movies) { XflMovie.parse(null, bytesToXML(fz.content), MD5.hashBytes(fz.content)); } NA.exit(0); }); } protected var _rootLen :int; protected var _publisher :Publisher; protected var _docFinder :Executor; protected var _win :ExporterWindow; protected var _libraries :DataGrid; protected var _errors :DataGrid; protected var _exportChooser :DirChooser; protected var _importChooser :DirChooser; protected var _authoredResolution :DropDownList; protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter"); private static const log :Log = Log.getLog(Exporter); } } import flump.export.DeviceType; class DeviceSelection { public var type :DeviceType; public function DeviceSelection (type :DeviceType) { this.type = type; } public function toString () :String { return type.displayName + " (" + type.resWidth + "x" + type.resHeight + ")"; } } import flash.events.EventDispatcher; import flash.filesystem.File; import flump.export.Ternary; import flump.xfl.XflLibrary; import mx.core.IPropertyChangeNotifier; import mx.events.PropertyChangeEvent; class DocStatus extends EventDispatcher implements IPropertyChangeNotifier { public var path :String; public var modified :String; public var valid :String = QUESTION; public var file :File; public var lib :XflLibrary; public function DocStatus (file :File, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) { this.file = file; this.lib = lib; path = file.nativePath.substring(rootLen); _uid = path; updateModified(modified); updateValid(valid); } public function updateValid (newValid :Ternary) :void { changeField("valid", function (..._) :void { if (newValid == Ternary.TRUE) valid = CHECK; else if (newValid == Ternary.FALSE) valid = FROWN; else valid = QUESTION; }); } public function get isValid () :Boolean { return valid == CHECK; } public function updateModified (newModified :Ternary) :void { changeField("modified", function (..._) :void { if (newModified == Ternary.TRUE) modified = CHECK; else if (newModified == Ternary.FALSE) modified = " "; else modified = QUESTION; }); } protected function changeField(fieldName :String, modifier :Function) :void { const oldValue :Object = this[fieldName]; modifier(); const newValue :Object = this[fieldName]; dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue)); } public function get uid () :String { return _uid; } public function set uid (uid :String) :void { _uid = uid; } protected var _uid :String; protected static const QUESTION :String = "?"; protected static const FROWN :String = "☹"; protected static const CHECK :String = "✓"; }
update the Preview and Export buttons when the "valid" status changes
update the Preview and Export buttons when the "valid" status changes
ActionScript
mit
tconkling/flump,funkypandagame/flump,tconkling/flump,funkypandagame/flump,mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump
d1275ddb89278d6aa35fdf3e312f2b5859998442
src/SoundManager2_SMSound_AS3.as
src/SoundManager2_SMSound_AS3.as
/* SoundManager 2: Javascript Sound for the Web ---------------------------------------------- http://schillmania.com/projects/soundmanager2/ Copyright (c) 2007, Scott Schiller. All rights reserved. Code licensed under the BSD License: http://www.schillmania.com/projects/soundmanager2/license.txt Flash 9 / ActionScript 3 version */ package { import flash.external.*; import flash.events.*; import flash.display.Sprite; import flash.display.StageDisplayState; import flash.display.StageScaleMode; import flash.display.StageAlign; import flash.geom.Rectangle; import flash.media.Sound; import flash.media.SoundChannel; import flash.media.SoundLoaderContext; import flash.media.SoundTransform; import flash.media.SoundMixer; import flash.media.Video; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.net.NetConnection; import flash.net.NetStream; public class SoundManager2_SMSound_AS3 extends Sound { public var sm: SoundManager2_AS3 = null; // externalInterface references (for Javascript callbacks) public var baseJSController: String = "soundManager"; public var baseJSObject: String = baseJSController + ".sounds"; public var soundChannel: SoundChannel = new SoundChannel(); public var urlRequest: URLRequest; public var soundLoaderContext: SoundLoaderContext; public var waveformData: ByteArray = new ByteArray(); public var waveformDataArray: Array = []; public var eqData: ByteArray = new ByteArray(); public var eqDataArray: Array = []; public var usePeakData: Boolean = false; public var useWaveformData: Boolean = false; public var useEQData: Boolean = false; public var sID: String; public var sURL: String; public var justBeforeFinishOffset: int; public var didJustBeforeFinish: Boolean; public var didFinish: Boolean; public var loaded: Boolean; public var connected: Boolean; public var failed: Boolean; public var paused: Boolean; public var duration: Number; public var totalBytes: Number; public var handledDataError: Boolean = false; public var ignoreDataError: Boolean = false; public var lastValues: Object = { bytes: 0, position: 0, volume: 100, pan: 0, nLoops: 1, leftPeak: 0, rightPeak: 0, waveformDataArray: null, eqDataArray: null, isBuffering: null }; public var didLoad: Boolean = false; public var sound: Sound = new Sound(); public var cc: Object; public var nc: NetConnection; public var ns: NetStream; public var st: SoundTransform; public var useNetstream: Boolean; public var useVideo: Boolean = false; public var bufferTime: Number = -1; public var lastNetStatus: String = null; public var serverUrl: String = null; public var oVideo: Video = null; public var videoWidth: Number = 0; public var videoHeight: Number = 0; public function SoundManager2_SMSound_AS3(oSoundManager: SoundManager2_AS3, sIDArg: String = null, sURLArg: String = null, usePeakData: Boolean = false, useWaveformData: Boolean = false, useEQData: Boolean = false, useNetstreamArg: Boolean = false, useVideo: Boolean = false, netStreamBufferTime: Number = -1, serverUrl: String = null, duration: Number = 0, totalBytes: Number = 0) { this.sm = oSoundManager; this.sID = sIDArg; this.sURL = sURLArg; this.usePeakData = usePeakData; this.useWaveformData = useWaveformData; this.useEQData = useEQData; this.urlRequest = new URLRequest(sURLArg); this.justBeforeFinishOffset = 0; this.didJustBeforeFinish = false; this.didFinish = false; // non-MP3 formats only this.loaded = false; this.connected = false; this.failed = false; this.soundChannel = null; this.lastNetStatus = null; this.useNetstream = useNetstreamArg; this.serverUrl = serverUrl; this.duration = duration; this.totalBytes = totalBytes; this.useVideo = useVideo; this.bufferTime = netStreamBufferTime; writeDebug('in SoundManager2_SMSound_AS3, got duration '+duration+' and totalBytes '+totalBytes); if (this.useNetstream) { this.cc = new Object(); this.nc = new NetConnection(); // Handle FMS bandwidth check callback. // @see onBWDone // @see http://www.adobe.com/devnet/flashmediaserver/articles/dynamic_stream_switching_04.html // @see http://www.johncblandii.com/index.php/2007/12/fms-a-quick-fix-for-missing-onbwdone-onfcsubscribe-etc.html this.nc.client = this; // TODO: security/IO error handling // this.nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doSecurityError); // this.nc.addEventListener(IOErrorEvent.IO_ERROR, doIOError); nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); writeDebug('Got server URL: '+ this.serverUrl); if (this.serverUrl != null) { writeDebug('NetConnection: connecting to server ' + this.serverUrl + '...'); } this.nc.connect(serverUrl); } else { this.connected = true; } } private function netStatusHandler(event:NetStatusEvent):void { switch (event.info.code) { case "NetConnection.Connect.Success": writeDebug('NetConnection: connected'); try { this.ns = new NetStream(this.nc); this.ns.checkPolicyFile = true; // bufferTime reference: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/NetStream.html#bufferTime if (this.bufferTime != -1) { this.ns.bufferTime = this.bufferTime; // set to 0.1 or higher. 0 is reported to cause playback issues with static files. } this.st = new SoundTransform(); this.cc.onMetaData = this.metaDataHandler; this.ns.client = this.cc; this.ns.receiveAudio(true); if (this.useVideo) { this.oVideo = new Video(); this.ns.receiveVideo(true); this.sm.stage.addEventListener(Event.RESIZE, this.resizeHandler); this.oVideo.smoothing = true; // http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html#smoothing this.oVideo.visible = false; // hide until metadata received this.sm.addChild(this.oVideo); this.oVideo.attachNetStream(this.ns); writeDebug('setting video w/h to stage: ' + this.sm.stage.stageWidth + 'x' + this.sm.stage.stageHeight); this.oVideo.width = this.sm.stage.stageWidth; this.oVideo.height = this.sm.stage.stageHeight; } this.connected = true; ExternalInterface.call(this.sm.baseJSObject + "['" + this.sID + "']._onconnect", 1); } catch(e: Error) { this.failed = true; writeDebug('netStream error: ' + e.toString()); } break; case "NetStream.Play.StreamNotFound": this.failed = true; writeDebug("NetConnection: Stream not found!"); break; case "NetConnection.Connect.Closed": this.failed = true; writeDebug("NetConnection: Connection closed!"); break; default: this.failed = true; writeDebug("NetConnection: got unhandled code '" + event.info.code + "'!"); ExternalInterface.call(this.sm.baseJSObject + "['" + this.sID + "']._onconnect", 0); break; } } public function resizeHandler(e: Event) : void { // scale video to stage dimensions // probably less performant than using native flash scaling, but that doesn't quite seem to work. I'm probably missing something simple. this.oVideo.width = this.sm.stage.stageWidth; this.oVideo.height = this.sm.stage.stageHeight; } public function writeDebug(s: String, bTimestamp: Boolean = false) : Boolean { return this.sm.writeDebug(s, bTimestamp); // defined in main SM object } public function doNetStatus(e: NetStatusEvent) : void { writeDebug('netStatusEvent: ' + e.info.code); } public function metaDataHandler(infoObject: Object) : void { /* var data:String = new String(); for (var prop:* in infoObject) { data += prop+': '+infoObject[prop]+' '; } ExternalInterface.call('soundManager._writeDebug','Metadata: '+data); */ if (this.oVideo) { // set dimensions accordingly if (!infoObject.width && !infoObject.height) { writeDebug('No width/height specified'); infoObject.width = 0; infoObject.height = 0; } writeDebug('video dimensions: ' + infoObject.width + 'x' + infoObject.height + ' (w/h)'); this.videoWidth = infoObject.width; this.videoHeight = infoObject.height; // implement a subset of metadata to pass over EI bridge // some formats have extra stuff, eg. "aacaot", "avcprofile" // http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000267.html var oMeta: Object = new Object(); var item: Object = null; for (item in infoObject) { // exclude seekpoints for now, presumed not useful and overly large. if (item != 'seekpoints') { oMeta[item] = infoObject[item]; } } ExternalInterface.call(baseJSObject + "['" + this.sID + "']._onmetadata", oMeta); writeDebug('showing video for ' + this.sID); this.oVideo.visible = true; // show ze video! } if (!this.loaded) { ExternalInterface.call(baseJSObject + "['" + this.sID + "']._whileloading", this.bytesLoaded, (this.bytesTotal || this.totalBytes), (infoObject.duration || this.duration)); } this.duration = infoObject.duration * 1000; // null this out for the duration of this object's existence. // it may be called multiple times. this.cc.onMetaData = function (infoObject: Object) : void {} } public function getWaveformData() : void { // http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundMixer.html#computeSpectrum() SoundMixer.computeSpectrum(this.waveformData, false, 0); // sample wave data at 44.1 KHz this.waveformDataArray = []; for (var i: int = 0, j: int = this.waveformData.length / 4; i < j; i++) { // get all 512 values (256 per channel) this.waveformDataArray.push(int(this.waveformData.readFloat() * 1000) / 1000); } } public function getEQData() : void { // http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundMixer.html#computeSpectrum() SoundMixer.computeSpectrum(this.eqData, true, 0); // sample EQ data at 44.1 KHz this.eqDataArray = []; for (var i: int = 0, j: int = this.eqData.length / 4; i < j; i++) { // get all 512 values (256 per channel) this.eqDataArray.push(int(this.eqData.readFloat() * 1000) / 1000); } } public function start(nMsecOffset: int, nLoops: int) : void { writeDebug("Called start nMsecOffset "+ nMsecOffset+ ' nLoops '+nLoops); this.sm.currentObject = this; // reference for video, full-screen if (this.useNetstream) { writeDebug('start: seeking to ' + nMsecOffset); this.cc.onMetaData = this.metaDataHandler; this.ns.seek(nMsecOffset); if (this.paused) { this.ns.resume(); // get the sound going again if (!this.didLoad) this.didLoad = true; } else if (!this.didLoad) { this.ns.play(this.sURL); this.didLoad = true; } // this.ns.addEventListener(Event.SOUND_COMPLETE, _onfinish); this.applyTransform(); } else { this.soundChannel = this.play(nMsecOffset, nLoops); this.addEventListener(Event.SOUND_COMPLETE, _onfinish); this.applyTransform(); } } private function _onfinish() : void { this.removeEventListener(Event.SOUND_COMPLETE, _onfinish); } public function loadSound(sURL: String, bStream: Boolean) : void { if (this.useNetstream) { if (this.didLoad != true) { ExternalInterface.call('loadSound(): loading ' + this.sURL); this.ns.play(this.sURL); this.didLoad = true; } // this.addEventListener(Event.SOUND_COMPLETE, _onfinish); this.applyTransform(); } else { try { this.didLoad = true; this.urlRequest = new URLRequest(sURL); this.soundLoaderContext = new SoundLoaderContext(1000, true); // check for policy (crossdomain.xml) file on remote domains - http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundLoaderContext.html this.load(this.urlRequest, this.soundLoaderContext); } catch(e: Error) { writeDebug('error during loadSound(): ' + e.toString()); } } } public function setVolume(nVolume: Number) : void { this.lastValues.volume = nVolume / 100; this.applyTransform(); } public function setPan(nPan: Number) : void { this.lastValues.pan = nPan / 100; this.applyTransform(); } public function applyTransform() : void { var st: SoundTransform = new SoundTransform(this.lastValues.volume, this.lastValues.pan); if (this.useNetstream) { this.ns.soundTransform = st; } else if (this.soundChannel) { this.soundChannel.soundTransform = st; // new SoundTransform(this.lastValues.volume, this.lastValues.pan); } } // Handle FMS bandwidth check callback. // @see http://www.adobe.com/devnet/flashmediaserver/articles/dynamic_stream_switching_04.html // @see http://www.johncblandii.com/index.php/2007/12/fms-a-quick-fix-for-missing-onbwdone-onfcsubscribe-etc.html public function onBWDone():void{ writeDebug('onBWDone: called and ignored'); } // NetStream client callback. Invoked when the song is complete public function onPlayStatus(info:Object):void { writeDebug('onPlayStatus called with '+info); switch(info.code) { case "NetStream.Play.Complete": writeDebug('Song has finished!'); break; } } } }
/* SoundManager 2: Javascript Sound for the Web ---------------------------------------------- http://schillmania.com/projects/soundmanager2/ Copyright (c) 2007, Scott Schiller. All rights reserved. Code licensed under the BSD License: http://www.schillmania.com/projects/soundmanager2/license.txt Flash 9 / ActionScript 3 version */ package { import flash.external.*; import flash.events.*; import flash.display.Sprite; import flash.display.StageDisplayState; import flash.display.StageScaleMode; import flash.display.StageAlign; import flash.geom.Rectangle; import flash.media.Sound; import flash.media.SoundChannel; import flash.media.SoundLoaderContext; import flash.media.SoundTransform; import flash.media.SoundMixer; import flash.media.Video; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.net.NetConnection; import flash.net.NetStream; public class SoundManager2_SMSound_AS3 extends Sound { public var sm: SoundManager2_AS3 = null; // externalInterface references (for Javascript callbacks) public var baseJSController: String = "soundManager"; public var baseJSObject: String = baseJSController + ".sounds"; public var soundChannel: SoundChannel = new SoundChannel(); public var urlRequest: URLRequest; public var soundLoaderContext: SoundLoaderContext; public var waveformData: ByteArray = new ByteArray(); public var waveformDataArray: Array = []; public var eqData: ByteArray = new ByteArray(); public var eqDataArray: Array = []; public var usePeakData: Boolean = false; public var useWaveformData: Boolean = false; public var useEQData: Boolean = false; public var sID: String; public var sURL: String; public var justBeforeFinishOffset: int; public var didJustBeforeFinish: Boolean; public var didFinish: Boolean; public var loaded: Boolean; public var connected: Boolean; public var failed: Boolean; public var paused: Boolean; public var duration: Number; public var totalBytes: Number; public var handledDataError: Boolean = false; public var ignoreDataError: Boolean = false; public var lastValues: Object = { bytes: 0, position: 0, volume: 100, pan: 0, nLoops: 1, leftPeak: 0, rightPeak: 0, waveformDataArray: null, eqDataArray: null, isBuffering: null }; public var didLoad: Boolean = false; public var sound: Sound = new Sound(); public var cc: Object; public var nc: NetConnection; public var ns: NetStream; public var st: SoundTransform; public var useNetstream: Boolean; public var useVideo: Boolean = false; public var bufferTime: Number = -1; public var lastNetStatus: String = null; public var serverUrl: String = null; public var oVideo: Video = null; public var videoWidth: Number = 0; public var videoHeight: Number = 0; public function SoundManager2_SMSound_AS3(oSoundManager: SoundManager2_AS3, sIDArg: String = null, sURLArg: String = null, usePeakData: Boolean = false, useWaveformData: Boolean = false, useEQData: Boolean = false, useNetstreamArg: Boolean = false, useVideo: Boolean = false, netStreamBufferTime: Number = -1, serverUrl: String = null, duration: Number = 0, totalBytes: Number = 0) { this.sm = oSoundManager; this.sID = sIDArg; this.sURL = sURLArg; this.usePeakData = usePeakData; this.useWaveformData = useWaveformData; this.useEQData = useEQData; this.urlRequest = new URLRequest(sURLArg); this.justBeforeFinishOffset = 0; this.didJustBeforeFinish = false; this.didFinish = false; // non-MP3 formats only this.loaded = false; this.connected = false; this.failed = false; this.soundChannel = null; this.lastNetStatus = null; this.useNetstream = useNetstreamArg; this.serverUrl = serverUrl; this.duration = duration; this.totalBytes = totalBytes; this.useVideo = useVideo; this.bufferTime = netStreamBufferTime; writeDebug('in SoundManager2_SMSound_AS3, got duration '+duration+' and totalBytes '+totalBytes); if (this.useNetstream) { this.cc = new Object(); this.nc = new NetConnection(); // Handle FMS bandwidth check callback. // @see onBWDone // @see http://www.adobe.com/devnet/flashmediaserver/articles/dynamic_stream_switching_04.html // @see http://www.johncblandii.com/index.php/2007/12/fms-a-quick-fix-for-missing-onbwdone-onfcsubscribe-etc.html this.nc.client = this; // TODO: security/IO error handling // this.nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doSecurityError); // this.nc.addEventListener(IOErrorEvent.IO_ERROR, doIOError); nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); writeDebug('Got server URL: '+ this.serverUrl); if (this.serverUrl != null) { writeDebug('NetConnection: connecting to server ' + this.serverUrl + '...'); } this.nc.connect(serverUrl); } else { this.connected = true; } } private function netStatusHandler(event:NetStatusEvent):void { switch (event.info.code) { case "NetConnection.Connect.Success": writeDebug('NetConnection: connected'); try { this.ns = new NetStream(this.nc); this.ns.checkPolicyFile = true; // bufferTime reference: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/NetStream.html#bufferTime if (this.bufferTime != -1) { this.ns.bufferTime = this.bufferTime; // set to 0.1 or higher. 0 is reported to cause playback issues with static files. } this.st = new SoundTransform(); this.cc.onMetaData = this.metaDataHandler; this.ns.client = this.cc; this.ns.receiveAudio(true); if (this.useVideo) { this.oVideo = new Video(); this.ns.receiveVideo(true); this.sm.stage.addEventListener(Event.RESIZE, this.resizeHandler); this.oVideo.smoothing = true; // http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html#smoothing this.oVideo.visible = false; // hide until metadata received this.sm.addChild(this.oVideo); this.oVideo.attachNetStream(this.ns); writeDebug('setting video w/h to stage: ' + this.sm.stage.stageWidth + 'x' + this.sm.stage.stageHeight); this.oVideo.width = this.sm.stage.stageWidth; this.oVideo.height = this.sm.stage.stageHeight; } this.connected = true; ExternalInterface.call(this.sm.baseJSObject + "['" + this.sID + "']._onconnect", 1); } catch(e: Error) { this.failed = true; writeDebug('netStream error: ' + e.toString()); } break; case "NetStream.Play.StreamNotFound": this.failed = true; writeDebug("NetConnection: Stream not found!"); break; case "NetConnection.Connect.Closed": this.failed = true; writeDebug("NetConnection: Connection closed!"); break; default: this.failed = true; writeDebug("NetConnection: got unhandled code '" + event.info.code + "'!"); ExternalInterface.call(this.sm.baseJSObject + "['" + this.sID + "']._onconnect", 0); break; } } public function resizeHandler(e: Event) : void { // scale video to stage dimensions // probably less performant than using native flash scaling, but that doesn't quite seem to work. I'm probably missing something simple. this.oVideo.width = this.sm.stage.stageWidth; this.oVideo.height = this.sm.stage.stageHeight; } public function writeDebug(s: String, bTimestamp: Boolean = false) : Boolean { return this.sm.writeDebug(s, bTimestamp); // defined in main SM object } public function doNetStatus(e: NetStatusEvent) : void { writeDebug('netStatusEvent: ' + e.info.code); } public function metaDataHandler(infoObject: Object) : void { /* var data:String = new String(); for (var prop:* in infoObject) { data += prop+': '+infoObject[prop]+' '; } ExternalInterface.call('soundManager._writeDebug','Metadata: '+data); */ if (this.oVideo) { // set dimensions accordingly if (!infoObject.width && !infoObject.height) { writeDebug('No width/height specified'); infoObject.width = 0; infoObject.height = 0; } writeDebug('video dimensions: ' + infoObject.width + 'x' + infoObject.height + ' (w/h)'); this.videoWidth = infoObject.width; this.videoHeight = infoObject.height; // implement a subset of metadata to pass over EI bridge // some formats have extra stuff, eg. "aacaot", "avcprofile" // http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000267.html var oMeta: Object = new Object(); var item: Object = null; for (item in infoObject) { // exclude seekpoints for now, presumed not useful and overly large. if (item != 'seekpoints') { oMeta[item] = infoObject[item]; } } ExternalInterface.call(baseJSObject + "['" + this.sID + "']._onmetadata", oMeta); writeDebug('showing video for ' + this.sID); this.oVideo.visible = true; // show ze video! } if (!this.loaded) { ExternalInterface.call(baseJSObject + "['" + this.sID + "']._whileloading", this.bytesLoaded, (this.bytesTotal || this.totalBytes), (infoObject.duration || this.duration)); } this.duration = infoObject.duration * 1000; // null this out for the duration of this object's existence. // it may be called multiple times. this.cc.onMetaData = function (infoObject: Object) : void {} } public function getWaveformData() : void { // http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundMixer.html#computeSpectrum() SoundMixer.computeSpectrum(this.waveformData, false, 0); // sample wave data at 44.1 KHz this.waveformDataArray = []; for (var i: int = 0, j: int = this.waveformData.length / 4; i < j; i++) { // get all 512 values (256 per channel) this.waveformDataArray.push(int(this.waveformData.readFloat() * 1000) / 1000); } } public function getEQData() : void { // http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundMixer.html#computeSpectrum() SoundMixer.computeSpectrum(this.eqData, true, 0); // sample EQ data at 44.1 KHz this.eqDataArray = []; for (var i: int = 0, j: int = this.eqData.length / 4; i < j; i++) { // get all 512 values (256 per channel) this.eqDataArray.push(int(this.eqData.readFloat() * 1000) / 1000); } } public function start(nMsecOffset: int, nLoops: int) : void { writeDebug("Called start nMsecOffset "+ nMsecOffset+ ' nLoops '+nLoops); this.sm.currentObject = this; // reference for video, full-screen if (this.useNetstream) { writeDebug('start: seeking to ' + nMsecOffset); this.cc.onMetaData = this.metaDataHandler; this.ns.seek(nMsecOffset); if (this.paused) { this.ns.resume(); // get the sound going again if (!this.didLoad) this.didLoad = true; this.paused = false; } else if (!this.didLoad) { this.ns.play(this.sURL); this.didLoad = true; this.paused = false; } // this.ns.addEventListener(Event.SOUND_COMPLETE, _onfinish); this.applyTransform(); } else { this.soundChannel = this.play(nMsecOffset, nLoops); this.addEventListener(Event.SOUND_COMPLETE, _onfinish); this.applyTransform(); } } private function _onfinish() : void { this.removeEventListener(Event.SOUND_COMPLETE, _onfinish); } public function loadSound(sURL: String, bStream: Boolean) : void { if (this.useNetstream) { if (this.didLoad != true) { ExternalInterface.call('loadSound(): loading ' + this.sURL); this.ns.play(this.sURL); this.didLoad = true; } // this.addEventListener(Event.SOUND_COMPLETE, _onfinish); this.applyTransform(); } else { try { this.didLoad = true; this.urlRequest = new URLRequest(sURL); this.soundLoaderContext = new SoundLoaderContext(1000, true); // check for policy (crossdomain.xml) file on remote domains - http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundLoaderContext.html this.load(this.urlRequest, this.soundLoaderContext); } catch(e: Error) { writeDebug('error during loadSound(): ' + e.toString()); } } } public function setVolume(nVolume: Number) : void { this.lastValues.volume = nVolume / 100; this.applyTransform(); } public function setPan(nPan: Number) : void { this.lastValues.pan = nPan / 100; this.applyTransform(); } public function applyTransform() : void { var st: SoundTransform = new SoundTransform(this.lastValues.volume, this.lastValues.pan); if (this.useNetstream) { this.ns.soundTransform = st; } else if (this.soundChannel) { this.soundChannel.soundTransform = st; // new SoundTransform(this.lastValues.volume, this.lastValues.pan); } } // Handle FMS bandwidth check callback. // @see http://www.adobe.com/devnet/flashmediaserver/articles/dynamic_stream_switching_04.html // @see http://www.johncblandii.com/index.php/2007/12/fms-a-quick-fix-for-missing-onbwdone-onfcsubscribe-etc.html public function onBWDone():void{ writeDebug('onBWDone: called and ignored'); } // NetStream client callback. Invoked when the song is complete public function onPlayStatus(info:Object):void { writeDebug('onPlayStatus called with '+info); switch(info.code) { case "NetStream.Play.Complete": writeDebug('Song has finished!'); break; } } } }
Fix pause issue. When track is played and then paused, paused state was not reset.
Fix pause issue. When track is played and then paused, paused state was not reset.
ActionScript
bsd-3-clause
snowman1ng/SoundManager2-Seek-Reverse,Nona-Creative/SoundManager2,Shinobi881/SoundManager2,josephsavona/SoundManager2,minorgod/SoundManager2,minorgod/SoundManager2,ubergrafik/SoundManager2,Shinobi881/SoundManager2,thecocce/SoundManager2,2947721120/SoundManager2,snowman1ng/SoundManager2-Seek-Reverse,ubergrafik/SoundManager2,acchoblues/SoundManager2,Zarel/SoundManager2,usergit/SoundManager2,relax/SoundManager2,oceanho/SoundManager2,acchoblues/SoundManager2,usergit/SoundManager2,usergit/SoundManager2,kyroskoh/SoundManager2,snowman1ng/SoundManager2-Seek-Reverse,Zarel/SoundManager2,kyroskoh/SoundManager2,Nona-Creative/SoundManager2,minorgod/SoundManager2,thecocce/SoundManager2,ali2mdj/SoundManager2,oceanho/SoundManager2,relax/SoundManager2,Erbolking/SoundManager2,Erbolking/SoundManager2,Erbolking/SoundManager2,2947721120/SoundManager2,Nona-Creative/SoundManager2,2947721120/SoundManager2,ubergrafik/SoundManager2,kidaa/SoundManager2,Shinobi881/SoundManager2,tchoulihan/SoundManager2,ali2mdj/SoundManager2,josephsavona/SoundManager2,kidaa/SoundManager2,tchoulihan/SoundManager2,ali2mdj/SoundManager2,relax/SoundManager2,tchoulihan/SoundManager2,kyroskoh/SoundManager2,oceanho/SoundManager2,thecocce/SoundManager2,kidaa/SoundManager2
18eea70bae1d2f2a86ac67c17c093577ab30187d
src/main/actionscript/com/dotfold/dotvimstat/view/summary/VideosSummary.as
src/main/actionscript/com/dotfold/dotvimstat/view/summary/VideosSummary.as
package com.dotfold.dotvimstat.view.summary { import asx.string.empty; import com.dotfold.dotvimstat.net.service.VimeoBasicService; import com.dotfold.dotvimstat.view.IView; import modena.core.Element; import modena.core.ElementContent; import modena.ui.Label; /** * VideosSummary view shows the count of videos retrieved from the Vimeo API. * * @author jamesmcnamee * */ public class VideosSummary extends Element implements IView { public static const ELEMENT_NAME:String = "videosSummary"; private var _label:Label; /** * Constructor. */ public function VideosSummary(styleClass:String = null) { super(styleClass); } /** * @inheritDoc */ override protected function createElementContent():ElementContent { var content:ElementContent = super.createElementContent(); _label = new Label("summaryCount"); content.addChild(_label); return content; } /** * Update the label with count of videos. */ public function set videosCount(value:int):void { _label.text = value.toString(); invalidateRender(); } override public function validateRender():void { super.validateRender(); _label.x = (width - _label.width) / 2; _label.y = (height - _label.height) / 2; } } }
package com.dotfold.dotvimstat.view.summary { import asx.string.empty; import com.dotfold.dotvimstat.net.service.VimeoBasicService; import com.dotfold.dotvimstat.view.IView; import com.greensock.TweenLite; import modena.core.Element; import modena.core.ElementContent; import modena.ui.Label; /** * VideosSummary view shows the count of videos retrieved from the Vimeo API. * * @author jamesmcnamee * */ public class VideosSummary extends Element implements IView { public static const ELEMENT_NAME:String = "videosSummary"; private var _label:Label; /** * Constructor. */ public function VideosSummary(styleClass:String = null) { super(styleClass); } /** * @inheritDoc */ override protected function createElementContent():ElementContent { var content:ElementContent = super.createElementContent(); _label = new Label("summaryCount"); content.addChild(_label); _label.alpha = 0; return content; } /** * Update the label with count of videos. */ public function set videosCount(value:int):void { _label.text = value.toString(); TweenLite.to(_label, 0.4, { alpha: 1, ease: 'easeInQuad' }); invalidateRender(); } override public function validateRender():void { super.validateRender(); _label.x = (width - _label.width) / 2; _label.y = (height - _label.height) / 2; } } }
add animation to VideosSummary
[feat] add animation to VideosSummary
ActionScript
mit
dotfold/dotvimstat
cb750d78c2709227f2093a170433f0092eae1eef
src/aerys/minko/render/shader/compiler/Serializer.as
src/aerys/minko/render/shader/compiler/Serializer.as
package aerys.minko.render.shader.compiler { import aerys.minko.ns.minko_math; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import avmplus.getQualifiedClassName; import flash.geom.Point; import flash.geom.Vector3D; /** * The Serializer class provides a set of static methods to serialize * CPU values into Vector.&lt;Number&gt; than can be used as shader constants. * * @author Jean-Marc Le Roux * */ public class Serializer { public function serializeKnownLength(data : Object, target : Vector.<Number>, offset : uint, size : uint) : void { if (data is Number) { var intData : Number = Number(data); if (size == 1) { target[offset] = intData; } else if (size == 2) { target[offset] = ((intData & 0xFFFF0000) >>> 16) / Number(0xffff); target[int(offset + 2)] = (intData & 0x0000FFFF) / Number(0xffff); } else if (size == 3) { target[offset] = ((intData & 0xFF0000) >>> 16) / 255.; target[int(offset + 1)] = ((intData & 0x00FF00) >>> 8) / 255.; target[int(offset + 2)] = (intData & 0x0000FF) / 255.; } else if (size == 4) { target[offset] = ((intData & 0xFF000000) >>> 24) / 255.; target[int(offset + 1)] = ((intData & 0x00FF0000) >>> 16) / 255.; target[int(offset + 2)] = ((intData & 0x0000FF00) >>> 8) / 255.; target[int(offset + 3)] = ((intData & 0x000000FF)) / 255.; } } else if (data is Vector4) { var vectorData : Vector3D = Vector4(data).minko_math::_vector; target[offset] = vectorData.x; size >= 2 && (target[int(offset + 1)] = vectorData.y); size >= 3 && (target[int(offset + 2)] = vectorData.z); size >= 4 && (target[int(offset + 3)] = vectorData.w); } else if (data is Matrix4x4) { Matrix4x4(data).getRawData(target, offset, true); } else if (data is Vector.<Number>) { var vectorNumberData : Vector.<Number> = Vector.<Number>(data); var vectorNumberDatalength : uint = vectorNumberData.length; for (var k : int = 0; k < size && k < vectorNumberDatalength; ++k) target[offset + k] = vectorNumberData[k]; } else if (data is Vector.<Vector4>) { var vectorVectorData : Vector.<Vector4> = Vector.<Vector4>(data); var vectorVectorDataLength : uint = vectorVectorData.length; for (var j : uint = 0; j < vectorVectorDataLength; ++j) { vectorData = vectorVectorData[j].minko_math::_vector; target[offset + 4 * j] = vectorData.x; target[int(offset + 4 * j + 1)] = vectorData.y; target[int(offset + 4 * j + 2)] = vectorData.z; target[int(offset + 4 * j + 3)] = vectorData.w; } } else if (data is Vector.<Matrix4x4>) { var matrixVectorData : Vector.<Matrix4x4> = Vector.<Matrix4x4>(data); var matrixVectorDataLength : uint = matrixVectorData.length; for (var i : uint = 0; i < matrixVectorDataLength; ++i) matrixVectorData[i].getRawData(target, offset + i * 16, true); } else if (data == null) { throw new Error('You cannot serialize a null value.'); } else { throw new Error('Unsupported type:' + getQualifiedClassName(data)); } } public function serializeUnknownLength(data : Object, target : Vector.<Number>, offset : uint) : void { if (data is Number) { target[offset] = Number(data); } else if (data is Point) { var pointData : Point = Point(data); target[offset] = pointData.x; target[int(offset + 1)] = pointData.y; } else if (data is Vector4) { var vectorData : Vector3D = Vector4(data).minko_math::_vector; target[offset] = vectorData.x; target[int(offset + 1)] = vectorData.y; target[int(offset + 2)] = vectorData.z; target[int(offset + 3)] = vectorData.w; } else if (data is Matrix4x4) { Matrix4x4(data).getRawData(target, offset, true); } else if (data is Array || data is Vector.<Number> || data is Vector.<Vector4> || data is Vector.<Matrix4x4>) { for each (var datum : Object in data) { serializeUnknownLength(datum, target, offset); offset = target.length; } } else if (data == null) { throw new Error('You cannot serialize a null value.'); } else { throw new Error('Unsupported type:' + getQualifiedClassName(data)); } } } }
package aerys.minko.render.shader.compiler { import aerys.minko.ns.minko_math; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.geom.Point; import flash.geom.Vector3D; import flash.utils.getQualifiedClassName; /** * The Serializer class provides a set of static methods to serialize * CPU values into Vector.&lt;Number&gt; than can be used as shader constants. * * @author Jean-Marc Le Roux * */ public class Serializer { public function serializeKnownLength(data : Object, target : Vector.<Number>, offset : uint, size : uint) : void { if (data is Number) { var intData : Number = Number(data); if (size == 1) { target[offset] = intData; } else if (size == 2) { target[offset] = ((intData & 0xFFFF0000) >>> 16) / Number(0xffff); target[int(offset + 2)] = (intData & 0x0000FFFF) / Number(0xffff); } else if (size == 3) { target[offset] = ((intData & 0xFF0000) >>> 16) / 255.; target[int(offset + 1)] = ((intData & 0x00FF00) >>> 8) / 255.; target[int(offset + 2)] = (intData & 0x0000FF) / 255.; } else if (size == 4) { target[offset] = ((intData & 0xFF000000) >>> 24) / 255.; target[int(offset + 1)] = ((intData & 0x00FF0000) >>> 16) / 255.; target[int(offset + 2)] = ((intData & 0x0000FF00) >>> 8) / 255.; target[int(offset + 3)] = ((intData & 0x000000FF)) / 255.; } } else if (data is Vector4) { var vectorData : Vector3D = Vector4(data).minko_math::_vector; target[offset] = vectorData.x; size >= 2 && (target[int(offset + 1)] = vectorData.y); size >= 3 && (target[int(offset + 2)] = vectorData.z); size >= 4 && (target[int(offset + 3)] = vectorData.w); } else if (data is Matrix4x4) { Matrix4x4(data).getRawData(target, offset, true); } else if (data is Vector.<Number>) { var vectorNumberData : Vector.<Number> = Vector.<Number>(data); var vectorNumberDatalength : uint = vectorNumberData.length; for (var k : int = 0; k < size && k < vectorNumberDatalength; ++k) target[offset + k] = vectorNumberData[k]; } else if (data is Vector.<Vector4>) { var vectorVectorData : Vector.<Vector4> = Vector.<Vector4>(data); var vectorVectorDataLength : uint = vectorVectorData.length; for (var j : uint = 0; j < vectorVectorDataLength; ++j) { vectorData = vectorVectorData[j].minko_math::_vector; target[offset + 4 * j] = vectorData.x; target[int(offset + 4 * j + 1)] = vectorData.y; target[int(offset + 4 * j + 2)] = vectorData.z; target[int(offset + 4 * j + 3)] = vectorData.w; } } else if (data is Vector.<Matrix4x4>) { var matrixVectorData : Vector.<Matrix4x4> = Vector.<Matrix4x4>(data); var matrixVectorDataLength : uint = matrixVectorData.length; for (var i : uint = 0; i < matrixVectorDataLength; ++i) matrixVectorData[i].getRawData(target, offset + i * 16, true); } else if (data == null) { throw new Error('You cannot serialize a null value.'); } else { throw new Error('Unsupported type:' + getQualifiedClassName(data); } } public function serializeUnknownLength(data : Object, target : Vector.<Number>, offset : uint) : void { if (data is Number) { target[offset] = Number(data); } else if (data is Point) { var pointData : Point = Point(data); target[offset] = pointData.x; target[int(offset + 1)] = pointData.y; } else if (data is Vector4) { var vectorData : Vector3D = Vector4(data).minko_math::_vector; target[offset] = vectorData.x; target[int(offset + 1)] = vectorData.y; target[int(offset + 2)] = vectorData.z; target[int(offset + 3)] = vectorData.w; } else if (data is Matrix4x4) { Matrix4x4(data).getRawData(target, offset, true); } else if (data is Array || data is Vector.<Number> || data is Vector.<Vector4> || data is Vector.<Matrix4x4>) { for each (var datum : Object in data) { serializeUnknownLength(datum, target, offset); offset = target.length; } } else if (data == null) { throw new Error('You cannot serialize a null value.'); } else { throw new Error('Unsupported type:' + getQualifiedClassName(data)); } } } }
fix wrong import for getQualifiedClassName()
fix wrong import for getQualifiedClassName()
ActionScript
mit
aerys/minko-as3
2db82a30c5c3e50ce15a849d87f06c8bc8eb821c
exporter/src/main/as/flump/export/FlaLoader.as
exporter/src/main/as/flump/export/FlaLoader.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.filesystem.File; import flash.utils.ByteArray; import deng.fzip.FZip; import deng.fzip.FZipFile; import flump.executor.Executor; import flump.executor.Future; import flump.executor.VisibleFuture; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import com.threerings.util.F; import com.threerings.util.Log; public class FlaLoader { public function load (name :String, file :File) :Future { log.info("Loading fla", "path", file.nativePath, "name", name); const future :VisibleFuture = new VisibleFuture(); _library = new XflLibrary(name); _loader.terminated.add(function (..._) :void { _library.finishLoading(); future.succeed(_library); }); var loadSWF :Future = _library.loadSWF(file.nativePath + ".swf"); loadSWF.succeeded.add(function () :void { // Since listLibrary shuts down the executor, wait for the swf to load first listLibrary(file); }); loadSWF.failed.add(F.adapt(_loader.shutdown)); return future; } protected function listLibrary (file :File) :void { const loadZip :Future = Files.load(file, _loader); loadZip.succeeded.add(function (data :ByteArray) :void { const zip :FZip = new FZip(); zip.loadBytes(data); const domFile :FZipFile = zip.getFileByName("DOMDocument.xml"); const symbolPaths :Vector.<String> = _library.parseDocumentFile( domFile.content, domFile.filename); for each (var path :String in symbolPaths) { var symbolFile :FZipFile = zip.getFileByName(path); _library.parseLibraryFile(symbolFile.content, path); } _loader.shutdown(); }); loadZip.failed.add(function (error :Object) :void { _library.addTopLevelError(ParseError.CRIT, "Unable to read " + file.nativePath, error); _loader.shutdown(); }); } protected const _loader :Executor = new Executor(); protected var _library :XflLibrary; private static const log :Log = Log.getLog(FlaLoader); } }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.filesystem.File; import flash.utils.ByteArray; import deng.fzip.FZip; import deng.fzip.FZipFile; import flump.executor.Executor; import flump.executor.Future; import flump.executor.VisibleFuture; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import com.threerings.util.F; import com.threerings.util.Log; public class FlaLoader { public function load (name :String, file :File) :Future { log.info("Loading fla", "path", file.nativePath, "name", name); const future :VisibleFuture = new VisibleFuture(); _library = new XflLibrary(name); _loader.terminated.add(function (..._) :void { _library.finishLoading(); future.succeed(_library); }); var loadSWF :Future = _library.loadSWF(Files.replaceExtension(file, "swf")); loadSWF.succeeded.add(function () :void { // Since listLibrary shuts down the executor, wait for the swf to load first listLibrary(file); }); loadSWF.failed.add(F.adapt(_loader.shutdown)); return future; } protected function listLibrary (file :File) :void { const loadZip :Future = Files.load(file, _loader); loadZip.succeeded.add(function (data :ByteArray) :void { const zip :FZip = new FZip(); zip.loadBytes(data); const domFile :FZipFile = zip.getFileByName("DOMDocument.xml"); const symbolPaths :Vector.<String> = _library.parseDocumentFile( domFile.content, domFile.filename); for each (var path :String in symbolPaths) { var symbolFile :FZipFile = zip.getFileByName(path); _library.parseLibraryFile(symbolFile.content, path); } _loader.shutdown(); }); loadZip.failed.add(function (error :Object) :void { _library.addTopLevelError(ParseError.CRIT, "Unable to read " + file.nativePath, error); _loader.shutdown(); }); } protected const _loader :Executor = new Executor(); protected var _library :XflLibrary; private static const log :Log = Log.getLog(FlaLoader); } }
load "MyFla.swf", not "MyFla.fla.swf"
FlaLoader: load "MyFla.swf", not "MyFla.fla.swf"
ActionScript
mit
mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump
d6fab14e32a7a23a8de6cfb259ccf1f5f5ebfc61
Bin/Data/Scripts/Vehicle.as
Bin/Data/Scripts/Vehicle.as
Scene@ testScene; Camera@ camera; Node@ cameraNode; Node@ vehicleHullNode; float yaw = 0.0; float pitch = 0.0; int drawDebug = 0; void Start() { if (!engine.headless) { InitConsole(); InitUI(); } else OpenConsoleWindow(); InitScene(); InitVehicle(); SubscribeToEvent("Update", "HandleUpdate"); SubscribeToEvent("PostUpdate", "HandlePostUpdate"); SubscribeToEvent("KeyDown", "HandleKeyDown"); SubscribeToEvent("MouseMove", "HandleMouseMove"); SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate"); } void InitConsole() { XMLFile@ uiStyle = cache.GetResource("XMLFile", "UI/DefaultStyle.xml"); engine.CreateDebugHud(); debugHud.defaultStyle = uiStyle; debugHud.mode = DEBUGHUD_SHOW_ALL; engine.CreateConsole(); console.defaultStyle = uiStyle; } void InitUI() { XMLFile@ uiStyle = cache.GetResource("XMLFile", "UI/DefaultStyle.xml"); Cursor@ newCursor = Cursor("Cursor"); newCursor.SetStyleAuto(uiStyle); newCursor.position = IntVector2(graphics.width / 2, graphics.height / 2); ui.cursor = newCursor; ui.cursor.visible = false; } void InitScene() { testScene = Scene("TestScene"); // Enable access to this script file & scene from the console script.defaultScene = testScene; script.defaultScriptFile = scriptFile; // Create the camera outside the scene so it is unaffected by scene load/save cameraNode = Node(); camera = cameraNode.CreateComponent("Camera"); camera.farClip = 1000; camera.nearClip = 0.5; cameraNode.position = Vector3(0, 20, 0); if (!engine.headless) { renderer.viewports[0] = Viewport(testScene, camera); audio.listener = cameraNode.CreateComponent("SoundListener"); } PhysicsWorld@ world = testScene.CreateComponent("PhysicsWorld"); testScene.CreateComponent("Octree"); testScene.CreateComponent("DebugRenderer"); Node@ zoneNode = testScene.CreateChild("Zone"); Zone@ zone = zoneNode.CreateComponent("Zone"); zone.ambientColor = Color(0.15, 0.15, 0.15); zone.fogColor = Color(0.5, 0.5, 0.7); zone.fogStart = 500.0; zone.fogEnd = 1000.0; zone.boundingBox = BoundingBox(-2000, 2000); { Node@ lightNode = testScene.CreateChild("GlobalLight"); lightNode.direction = Vector3(0.5, -0.5, 0.5); Light@ light = lightNode.CreateComponent("Light"); light.lightType = LIGHT_DIRECTIONAL; light.castShadows = true; light.shadowBias = BiasParameters(0.0001, 0.5); light.shadowCascade = CascadeParameters(15.0, 50.0, 200.0, 0.0, 0.8); light.specularIntensity = 0.5; } Terrain@ terrain; { Node@ terrainNode = testScene.CreateChild("Terrain"); terrainNode.position = Vector3(0, 0, 0); terrain = terrainNode.CreateComponent("Terrain"); terrain.patchSize = 64; terrain.spacing = Vector3(2, 0.1, 2); terrain.heightMap = cache.GetResource("Image", "Textures/HeightMap.png"); terrain.material = cache.GetResource("Material", "Materials/Terrain.xml"); terrain.occluder = true; RigidBody@ body = terrainNode.CreateComponent("RigidBody"); body.collisionLayer = 2; CollisionShape@ shape = terrainNode.CreateComponent("CollisionShape"); shape.SetTerrain(); shape.margin = 0.01; } for (uint i = 0; i < 1000; ++i) { Node@ objectNode = testScene.CreateChild("Mushroom"); Vector3 position(Random() * 2000 - 1000, 0, Random() * 2000 - 1000); position.y = terrain.GetHeight(position) - 0.1; objectNode.position = position; objectNode.rotation = Quaternion(Vector3(0, 1, 0), terrain.GetNormal(position)); objectNode.SetScale(3); StaticModel@ object = objectNode.CreateComponent("StaticModel"); object.model = cache.GetResource("Model", "Models/Mushroom.mdl"); object.material = cache.GetResource("Material", "Materials/Mushroom.xml"); object.castShadows = true; RigidBody@ body = objectNode.CreateComponent("RigidBody"); body.collisionLayer = 2; CollisionShape@ shape = objectNode.CreateComponent("CollisionShape"); shape.SetTriangleMesh(cache.GetResource("Model", "Models/Mushroom.mdl"), 0); } } void HandleUpdate(StringHash eventType, VariantMap& eventData) { float timeStep = eventData["TimeStep"].GetFloat(); // Nothing to do for now } void HandlePostUpdate(StringHash eventType, VariantMap& eventData) { float timeStep = eventData["TimeStep"].GetFloat(); // Physics update has completed. Position camera behind vehicle Quaternion dir(vehicleHullNode.rotation.yaw, Vector3(0, 1, 0));; dir = dir * Quaternion(yaw, Vector3(0, 1, 0)); dir = dir * Quaternion(pitch, Vector3(1, 0, 0)); Vector3 cameraTargetPos = vehicleHullNode.position - dir * Vector3(0, 0, 10); Vector3 cameraStartPos = vehicleHullNode.position; // Raycast camera against static objects (physics collision mask 2) // and move it closer to the vehicle if something in between Ray cameraRay(cameraStartPos, (cameraTargetPos - cameraStartPos).Normalized()); float cameraRayLength = (cameraTargetPos - cameraStartPos).length; PhysicsRaycastResult result = scene.physicsWorld.RaycastSingle(cameraRay, cameraRayLength, 2); if (result.body !is null) cameraTargetPos = cameraStartPos + cameraRay.direction * (result.distance - 0.5f); cameraNode.position = cameraTargetPos; cameraNode.rotation = dir; } void HandleKeyDown(StringHash eventType, VariantMap& eventData) { int key = eventData["Key"].GetInt(); if (key == KEY_ESC) { if (ui.focusElement is null) engine.Exit(); else console.visible = false; } if (key == KEY_F1) console.Toggle(); if (ui.focusElement is null) { if (key == '1') { int quality = renderer.textureQuality; ++quality; if (quality > 2) quality = 0; renderer.textureQuality = quality; } if (key == '2') { int quality = renderer.materialQuality; ++quality; if (quality > 2) quality = 0; renderer.materialQuality = quality; } if (key == '3') renderer.specularLighting = !renderer.specularLighting; if (key == '4') renderer.drawShadows = !renderer.drawShadows; if (key == '5') { int size = renderer.shadowMapSize; size *= 2; if (size > 2048) size = 512; renderer.shadowMapSize = size; } if (key == '6') renderer.shadowQuality = renderer.shadowQuality + 1; if (key == '7') { bool occlusion = renderer.maxOccluderTriangles > 0; occlusion = !occlusion; renderer.maxOccluderTriangles = occlusion ? 5000 : 0; } if (key == '8') renderer.dynamicInstancing = !renderer.dynamicInstancing; if (key == ' ') { drawDebug++; if (drawDebug > 2) drawDebug = 0; } if (key == 'T') debugHud.Toggle(DEBUGHUD_SHOW_PROFILER); } } void HandleMouseMove(StringHash eventType, VariantMap& eventData) { int mousedx = eventData["DX"].GetInt(); int mousedy = eventData["DY"].GetInt(); yaw += mousedx / 10.0; pitch += mousedy / 10.0; if (pitch < 0.0) pitch = 0.0; if (pitch > 60.0) pitch = 60.0; } void HandlePostRenderUpdate() { if (engine.headless) return; // Draw rendering debug geometry without depth test to see the effect of occlusion if (drawDebug == 1) renderer.DrawDebugGeometry(false); if (drawDebug == 2) testScene.physicsWorld.DrawDebugGeometry(true); } void InitVehicle() { vehicleHullNode = testScene.CreateChild("VehicleHull"); StaticModel@ hullObject = vehicleHullNode.CreateComponent("StaticModel"); RigidBody@ hullBody = vehicleHullNode.CreateComponent("RigidBody"); CollisionShape@ hullShape = vehicleHullNode.CreateComponent("CollisionShape"); vehicleHullNode.position = Vector3(0, 5, 0); vehicleHullNode.scale = Vector3(1.5, 1, 3); hullObject.model = cache.GetResource("Model", "Models/Box.mdl"); hullObject.material = cache.GetResource("Material", "Materials/Stone.xml"); hullObject.castShadows = true; hullShape.SetBox(Vector3(1, 1, 1)); hullBody.mass = 3; hullBody.linearDamping = 0.2; // Some air resistance hullBody.collisionLayer = 1; Node@ fl = InitVehicleWheel("FrontLeft", vehicleHullNode, Vector3(-0.6, -0.4, 0.3)); Node@ fr = InitVehicleWheel("FrontRight", vehicleHullNode, Vector3(0.6, -0.4, 0.3)); Node@ rr = InitVehicleWheel("RearLeft", vehicleHullNode, Vector3(-0.6, -0.4, -0.3)); Node@ rl = InitVehicleWheel("RearRight", vehicleHullNode, Vector3(0.6, -0.4, -0.3)); Vehicle@ vehicle = cast<Vehicle>(vehicleHullNode.CreateScriptObject(scriptFile, "Vehicle")); vehicle.SetWheels(fl, fr, rl, rr); } Node@ InitVehicleWheel(String name, Node@ vehicleHullNode, Vector3 offset) { Node@ wheelNode = testScene.CreateChild(name); wheelNode.position = vehicleHullNode.LocalToWorld(offset); wheelNode.rotation = vehicleHullNode.worldRotation * (offset.x >= 0.0 ? Quaternion(0, 0, -90) : Quaternion(0, 0, 90)); wheelNode.scale = Vector3(0.75, 0.5, 0.75); StaticModel@ wheelObject = wheelNode.CreateComponent("StaticModel"); RigidBody@ wheelBody = wheelNode.CreateComponent("RigidBody"); CollisionShape@ wheelShape = wheelNode.CreateComponent("CollisionShape"); Constraint@ wheelConstraint = wheelNode.CreateComponent("Constraint"); wheelObject.model = cache.GetResource("Model", "Models/Cylinder.mdl"); wheelObject.material = cache.GetResource("Material", "Materials/Stone.xml"); wheelObject.castShadows = true; wheelShape.SetCylinder(1, 1); wheelBody.friction = 1; wheelBody.mass = 1; wheelBody.linearDamping = 0.2; // Some air resistance wheelBody.angularDamping = 0.75; // Current version of Bullet used by Urho doesn't have rolling friction, so mimic that with // some angular damping on the wheels wheelBody.collisionLayer = 1; wheelConstraint.constraintType = CONSTRAINT_HINGE; wheelConstraint.otherBody = vehicleHullNode.GetComponent("RigidBody"); wheelConstraint.worldPosition = wheelNode.worldPosition; // Set constraint's both ends at wheel's location wheelConstraint.axis = Vector3(0, 1, 0); // Wheel rotates around its local Y-axis wheelConstraint.otherAxis = offset.x >= 0.0 ? Vector3(1, 0, 0) : Vector3(-1, 0, 0); // Wheel's hull axis points either left or right wheelConstraint.lowLimit = Vector2(-180, 0); // Let the wheel rotate freely around the axis wheelConstraint.highLimit = Vector2(180, 0); wheelConstraint.disableCollision = true; // Let the wheel intersect the vehicle hull return wheelNode; } class Vehicle : ScriptObject { Node@ frontLeft; Node@ frontRight; Node@ rearLeft; Node@ rearRight; Constraint@ frontLeftAxis; Constraint@ frontRightAxis; RigidBody@ hullBody; RigidBody@ frontLeftBody; RigidBody@ frontRightBody; RigidBody@ rearLeftBody; RigidBody@ rearRightBody; float steering = 0.0; float enginePower = 8.0; float downForce = 10.0; float maxWheelAngle = 22.5; void SetWheels(Node@ fl, Node@ fr, Node@ rl, Node@ rr) { frontLeft = fl; frontRight = fr; rearLeft = rl; rearRight = rr; hullBody = node.GetComponent("RigidBody"); frontLeftAxis = frontLeft.GetComponent("Constraint"); frontRightAxis = frontRight.GetComponent("Constraint"); frontLeftBody = frontLeft.GetComponent("RigidBody"); frontRightBody = frontRight.GetComponent("RigidBody"); rearLeftBody = rearLeft.GetComponent("RigidBody"); rearRightBody = rearRight.GetComponent("RigidBody"); } void FixedUpdate(float timeStep) { float newSteering = 0.0; float accelerator = 0.0; if (ui.focusElement is null) { if (input.keyDown['A']) newSteering = -1.0f; if (input.keyDown['D']) newSteering = 1.0f; if (input.keyDown['W']) accelerator = 1.0f; if (input.keyDown['S']) accelerator = -0.5f; } // When steering, wake up the wheel rigidbodies so that their orientation is updated if (newSteering != 0.0) { frontLeftBody.Activate(); frontRightBody.Activate(); steering = steering * 0.95 + newSteering * 0.05; } else steering = steering * 0.8 + newSteering * 0.2; Quaternion steeringRot(0, steering * maxWheelAngle, 0); frontLeftAxis.otherAxis = steeringRot * Vector3(-1, 0, 0); frontRightAxis.otherAxis = steeringRot * Vector3(1, 0, 0); if (accelerator != 0.0) { // Torques are applied in world space, so need to take the vehicle & wheel rotation into account Vector3 torqueVec = Vector3(enginePower * accelerator, 0, 0); frontLeftBody.ApplyTorque(node.rotation * steeringRot * torqueVec); frontRightBody.ApplyTorque(node.rotation * steeringRot * torqueVec); rearLeftBody.ApplyTorque(node.rotation * torqueVec); rearRightBody.ApplyTorque(node.rotation * torqueVec); } // Apply downforce proportional to velocity Vector3 localVelocity = node.worldRotation.Inverse() * hullBody.linearVelocity; hullBody.ApplyForce(Vector3(0, -1, 0) * Abs(localVelocity.z) * downForce); } }
Scene@ testScene; Camera@ camera; Node@ cameraNode; Node@ vehicleHullNode; float yaw = 0.0; float pitch = 0.0; int drawDebug = 0; void Start() { if (!engine.headless) { InitConsole(); InitUI(); } else OpenConsoleWindow(); InitScene(); InitVehicle(); SubscribeToEvent("Update", "HandleUpdate"); SubscribeToEvent("PostUpdate", "HandlePostUpdate"); SubscribeToEvent("KeyDown", "HandleKeyDown"); SubscribeToEvent("MouseMove", "HandleMouseMove"); SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate"); } void InitConsole() { XMLFile@ uiStyle = cache.GetResource("XMLFile", "UI/DefaultStyle.xml"); engine.CreateDebugHud(); debugHud.defaultStyle = uiStyle; debugHud.mode = DEBUGHUD_SHOW_ALL; engine.CreateConsole(); console.defaultStyle = uiStyle; } void InitUI() { XMLFile@ uiStyle = cache.GetResource("XMLFile", "UI/DefaultStyle.xml"); Cursor@ newCursor = Cursor("Cursor"); newCursor.SetStyleAuto(uiStyle); newCursor.position = IntVector2(graphics.width / 2, graphics.height / 2); ui.cursor = newCursor; ui.cursor.visible = false; } void InitScene() { testScene = Scene("TestScene"); // Enable access to this script file & scene from the console script.defaultScene = testScene; script.defaultScriptFile = scriptFile; // Create the camera outside the scene so it is unaffected by scene load/save cameraNode = Node(); camera = cameraNode.CreateComponent("Camera"); camera.farClip = 1000; camera.nearClip = 0.5; cameraNode.position = Vector3(0, 20, 0); if (!engine.headless) { renderer.viewports[0] = Viewport(testScene, camera); audio.listener = cameraNode.CreateComponent("SoundListener"); } PhysicsWorld@ world = testScene.CreateComponent("PhysicsWorld"); testScene.CreateComponent("Octree"); testScene.CreateComponent("DebugRenderer"); Node@ zoneNode = testScene.CreateChild("Zone"); Zone@ zone = zoneNode.CreateComponent("Zone"); zone.ambientColor = Color(0.15, 0.15, 0.15); zone.fogColor = Color(0.5, 0.5, 0.7); zone.fogStart = 500.0; zone.fogEnd = 1000.0; zone.boundingBox = BoundingBox(-2000, 2000); { Node@ lightNode = testScene.CreateChild("GlobalLight"); lightNode.direction = Vector3(0.5, -0.5, 0.5); Light@ light = lightNode.CreateComponent("Light"); light.lightType = LIGHT_DIRECTIONAL; light.castShadows = true; light.shadowBias = BiasParameters(0.0001, 0.5); light.shadowCascade = CascadeParameters(15.0, 50.0, 200.0, 0.0, 0.8); light.specularIntensity = 0.5; } Terrain@ terrain; { Node@ terrainNode = testScene.CreateChild("Terrain"); terrainNode.position = Vector3(0, 0, 0); terrain = terrainNode.CreateComponent("Terrain"); terrain.patchSize = 64; terrain.spacing = Vector3(2, 0.1, 2); terrain.heightMap = cache.GetResource("Image", "Textures/HeightMap.png"); terrain.material = cache.GetResource("Material", "Materials/Terrain.xml"); terrain.occluder = true; RigidBody@ body = terrainNode.CreateComponent("RigidBody"); body.collisionLayer = 2; CollisionShape@ shape = terrainNode.CreateComponent("CollisionShape"); shape.SetTerrain(); shape.margin = 0.01; } for (uint i = 0; i < 1000; ++i) { Node@ objectNode = testScene.CreateChild("Mushroom"); Vector3 position(Random() * 2000 - 1000, 0, Random() * 2000 - 1000); position.y = terrain.GetHeight(position) - 0.1; objectNode.position = position; objectNode.rotation = Quaternion(Vector3(0, 1, 0), terrain.GetNormal(position)); objectNode.SetScale(3); StaticModel@ object = objectNode.CreateComponent("StaticModel"); object.model = cache.GetResource("Model", "Models/Mushroom.mdl"); object.material = cache.GetResource("Material", "Materials/Mushroom.xml"); object.castShadows = true; RigidBody@ body = objectNode.CreateComponent("RigidBody"); body.collisionLayer = 2; CollisionShape@ shape = objectNode.CreateComponent("CollisionShape"); shape.SetTriangleMesh(cache.GetResource("Model", "Models/Mushroom.mdl"), 0); } } void HandleUpdate(StringHash eventType, VariantMap& eventData) { float timeStep = eventData["TimeStep"].GetFloat(); // Nothing to do for now } void HandlePostUpdate(StringHash eventType, VariantMap& eventData) { float timeStep = eventData["TimeStep"].GetFloat(); // Physics update has completed. Position camera behind vehicle Quaternion dir(vehicleHullNode.rotation.yaw, Vector3(0, 1, 0));; dir = dir * Quaternion(yaw, Vector3(0, 1, 0)); dir = dir * Quaternion(pitch, Vector3(1, 0, 0)); Vector3 cameraTargetPos = vehicleHullNode.position - dir * Vector3(0, 0, 10); Vector3 cameraStartPos = vehicleHullNode.position; // Raycast camera against static objects (physics collision mask 2) // and move it closer to the vehicle if something in between Ray cameraRay(cameraStartPos, (cameraTargetPos - cameraStartPos).Normalized()); float cameraRayLength = (cameraTargetPos - cameraStartPos).length; PhysicsRaycastResult result = scene.physicsWorld.RaycastSingle(cameraRay, cameraRayLength, 2); if (result.body !is null) cameraTargetPos = cameraStartPos + cameraRay.direction * (result.distance - 0.5f); cameraNode.position = cameraTargetPos; cameraNode.rotation = dir; } void HandleKeyDown(StringHash eventType, VariantMap& eventData) { int key = eventData["Key"].GetInt(); if (key == KEY_ESC) { if (ui.focusElement is null) engine.Exit(); else console.visible = false; } if (key == KEY_F1) console.Toggle(); if (ui.focusElement is null) { if (key == '1') { int quality = renderer.textureQuality; ++quality; if (quality > 2) quality = 0; renderer.textureQuality = quality; } if (key == '2') { int quality = renderer.materialQuality; ++quality; if (quality > 2) quality = 0; renderer.materialQuality = quality; } if (key == '3') renderer.specularLighting = !renderer.specularLighting; if (key == '4') renderer.drawShadows = !renderer.drawShadows; if (key == '5') { int size = renderer.shadowMapSize; size *= 2; if (size > 2048) size = 512; renderer.shadowMapSize = size; } if (key == '6') renderer.shadowQuality = renderer.shadowQuality + 1; if (key == '7') { bool occlusion = renderer.maxOccluderTriangles > 0; occlusion = !occlusion; renderer.maxOccluderTriangles = occlusion ? 5000 : 0; } if (key == '8') renderer.dynamicInstancing = !renderer.dynamicInstancing; if (key == ' ') { drawDebug++; if (drawDebug > 2) drawDebug = 0; } if (key == 'T') debugHud.Toggle(DEBUGHUD_SHOW_PROFILER); } } void HandleMouseMove(StringHash eventType, VariantMap& eventData) { int mousedx = eventData["DX"].GetInt(); int mousedy = eventData["DY"].GetInt(); yaw += mousedx / 10.0; pitch += mousedy / 10.0; if (pitch < 0.0) pitch = 0.0; if (pitch > 60.0) pitch = 60.0; } void HandlePostRenderUpdate() { if (engine.headless) return; // Draw rendering debug geometry without depth test to see the effect of occlusion if (drawDebug == 1) renderer.DrawDebugGeometry(false); if (drawDebug == 2) testScene.physicsWorld.DrawDebugGeometry(true); } void InitVehicle() { vehicleHullNode = testScene.CreateChild("VehicleHull"); StaticModel@ hullObject = vehicleHullNode.CreateComponent("StaticModel"); RigidBody@ hullBody = vehicleHullNode.CreateComponent("RigidBody"); CollisionShape@ hullShape = vehicleHullNode.CreateComponent("CollisionShape"); vehicleHullNode.position = Vector3(0, 5, 0); vehicleHullNode.scale = Vector3(1.5, 1, 3); hullObject.model = cache.GetResource("Model", "Models/Box.mdl"); hullObject.material = cache.GetResource("Material", "Materials/Stone.xml"); hullObject.castShadows = true; hullShape.SetBox(Vector3(1, 1, 1)); hullBody.mass = 3; hullBody.linearDamping = 0.2; // Some air resistance hullBody.collisionLayer = 1; Node@ fl = InitVehicleWheel("FrontLeft", vehicleHullNode, Vector3(-0.6, -0.4, 0.3)); Node@ fr = InitVehicleWheel("FrontRight", vehicleHullNode, Vector3(0.6, -0.4, 0.3)); Node@ rr = InitVehicleWheel("RearLeft", vehicleHullNode, Vector3(-0.6, -0.4, -0.3)); Node@ rl = InitVehicleWheel("RearRight", vehicleHullNode, Vector3(0.6, -0.4, -0.3)); Vehicle@ vehicle = cast<Vehicle>(vehicleHullNode.CreateScriptObject(scriptFile, "Vehicle")); vehicle.SetWheels(fl, fr, rl, rr); } Node@ InitVehicleWheel(String name, Node@ vehicleHullNode, Vector3 offset) { Node@ wheelNode = testScene.CreateChild(name); wheelNode.position = vehicleHullNode.LocalToWorld(offset); wheelNode.rotation = vehicleHullNode.worldRotation * (offset.x >= 0.0 ? Quaternion(0, 0, -90) : Quaternion(0, 0, 90)); wheelNode.scale = Vector3(0.75, 0.5, 0.75); StaticModel@ wheelObject = wheelNode.CreateComponent("StaticModel"); RigidBody@ wheelBody = wheelNode.CreateComponent("RigidBody"); CollisionShape@ wheelShape = wheelNode.CreateComponent("CollisionShape"); Constraint@ wheelConstraint = wheelNode.CreateComponent("Constraint"); wheelObject.model = cache.GetResource("Model", "Models/Cylinder.mdl"); wheelObject.material = cache.GetResource("Material", "Materials/Stone.xml"); wheelObject.castShadows = true; wheelShape.SetCylinder(1, 1); wheelBody.friction = 1; wheelBody.mass = 1; wheelBody.linearDamping = 0.2; // Some air resistance wheelBody.angularDamping = 0.75; // Current version of Bullet used by Urho doesn't have rolling friction, so mimic that with // some angular damping on the wheels wheelBody.collisionLayer = 1; wheelConstraint.constraintType = CONSTRAINT_HINGE; wheelConstraint.otherBody = vehicleHullNode.GetComponent("RigidBody"); wheelConstraint.worldPosition = wheelNode.worldPosition; // Set constraint's both ends at wheel's location wheelConstraint.axis = Vector3(0, 1, 0); // Wheel rotates around its local Y-axis wheelConstraint.otherAxis = offset.x >= 0.0 ? Vector3(1, 0, 0) : Vector3(-1, 0, 0); // Wheel's hull axis points either left or right wheelConstraint.lowLimit = Vector2(-180, 0); // Let the wheel rotate freely around the axis wheelConstraint.highLimit = Vector2(180, 0); wheelConstraint.disableCollision = true; // Let the wheel intersect the vehicle hull return wheelNode; } class Vehicle : ScriptObject { Node@ frontLeft; Node@ frontRight; Node@ rearLeft; Node@ rearRight; Constraint@ frontLeftAxis; Constraint@ frontRightAxis; RigidBody@ hullBody; RigidBody@ frontLeftBody; RigidBody@ frontRightBody; RigidBody@ rearLeftBody; RigidBody@ rearRightBody; float steering = 0.0; float enginePower = 8.0; float downForce = 10.0; float maxWheelAngle = 22.5; void SetWheels(Node@ fl, Node@ fr, Node@ rl, Node@ rr) { frontLeft = fl; frontRight = fr; rearLeft = rl; rearRight = rr; hullBody = node.GetComponent("RigidBody"); frontLeftAxis = frontLeft.GetComponent("Constraint"); frontRightAxis = frontRight.GetComponent("Constraint"); frontLeftBody = frontLeft.GetComponent("RigidBody"); frontRightBody = frontRight.GetComponent("RigidBody"); rearLeftBody = rearLeft.GetComponent("RigidBody"); rearRightBody = rearRight.GetComponent("RigidBody"); } void FixedUpdate(float timeStep) { float newSteering = 0.0; float accelerator = 0.0; if (ui.focusElement is null) { if (input.keyDown['A']) newSteering = -1.0f; if (input.keyDown['D']) newSteering = 1.0f; if (input.keyDown['W']) accelerator = 1.0f; if (input.keyDown['S']) accelerator = -0.5f; } // When steering, wake up the wheel rigidbodies so that their orientation is updated if (newSteering != 0.0) { frontLeftBody.Activate(); frontRightBody.Activate(); steering = steering * 0.95 + newSteering * 0.05; } else steering = steering * 0.8 + newSteering * 0.2; Quaternion steeringRot(0, steering * maxWheelAngle, 0); frontLeftAxis.otherAxis = steeringRot * Vector3(-1, 0, 0); frontRightAxis.otherAxis = steeringRot * Vector3(1, 0, 0); if (accelerator != 0.0) { // Torques are applied in world space, so need to take the vehicle & wheel rotation into account Vector3 torqueVec = Vector3(enginePower * accelerator, 0, 0); frontLeftBody.ApplyTorque(node.rotation * steeringRot * torqueVec); frontRightBody.ApplyTorque(node.rotation * steeringRot * torqueVec); rearLeftBody.ApplyTorque(node.rotation * torqueVec); rearRightBody.ApplyTorque(node.rotation * torqueVec); } // Apply downforce proportional to velocity Vector3 localVelocity = node.worldRotation.Inverse() * hullBody.linearVelocity; hullBody.ApplyForce(node.worldRotation * Vector3(0, -1, 0) * Abs(localVelocity.z) * downForce); } }
Align downforce to vehicle hull orientation.
Align downforce to vehicle hull orientation.
ActionScript
mit
codemon66/Urho3D,carnalis/Urho3D,abdllhbyrktr/Urho3D,codedash64/Urho3D,SuperWangKai/Urho3D,MonkeyFirst/Urho3D,abdllhbyrktr/Urho3D,tommy3/Urho3D,weitjong/Urho3D,codedash64/Urho3D,rokups/Urho3D,299299/Urho3D,MonkeyFirst/Urho3D,rokups/Urho3D,henu/Urho3D,SuperWangKai/Urho3D,helingping/Urho3D,kostik1337/Urho3D,kostik1337/Urho3D,fire/Urho3D-1,carnalis/Urho3D,rokups/Urho3D,fire/Urho3D-1,SirNate0/Urho3D,weitjong/Urho3D,299299/Urho3D,299299/Urho3D,orefkov/Urho3D,tommy3/Urho3D,cosmy1/Urho3D,luveti/Urho3D,c4augustus/Urho3D,victorholt/Urho3D,victorholt/Urho3D,MeshGeometry/Urho3D,eugeneko/Urho3D,codedash64/Urho3D,cosmy1/Urho3D,tommy3/Urho3D,eugeneko/Urho3D,iainmerrick/Urho3D,PredatorMF/Urho3D,weitjong/Urho3D,SirNate0/Urho3D,SuperWangKai/Urho3D,bacsmar/Urho3D,PredatorMF/Urho3D,PredatorMF/Urho3D,SuperWangKai/Urho3D,codemon66/Urho3D,helingping/Urho3D,urho3d/Urho3D,rokups/Urho3D,bacsmar/Urho3D,c4augustus/Urho3D,eugeneko/Urho3D,orefkov/Urho3D,urho3d/Urho3D,victorholt/Urho3D,kostik1337/Urho3D,MeshGeometry/Urho3D,orefkov/Urho3D,weitjong/Urho3D,299299/Urho3D,299299/Urho3D,carnalis/Urho3D,codemon66/Urho3D,iainmerrick/Urho3D,bacsmar/Urho3D,c4augustus/Urho3D,c4augustus/Urho3D,victorholt/Urho3D,luveti/Urho3D,SirNate0/Urho3D,helingping/Urho3D,MeshGeometry/Urho3D,luveti/Urho3D,SirNate0/Urho3D,tommy3/Urho3D,cosmy1/Urho3D,MeshGeometry/Urho3D,cosmy1/Urho3D,xiliu98/Urho3D,cosmy1/Urho3D,xiliu98/Urho3D,MonkeyFirst/Urho3D,luveti/Urho3D,codemon66/Urho3D,xiliu98/Urho3D,eugeneko/Urho3D,henu/Urho3D,orefkov/Urho3D,rokups/Urho3D,c4augustus/Urho3D,299299/Urho3D,SirNate0/Urho3D,abdllhbyrktr/Urho3D,fire/Urho3D-1,MonkeyFirst/Urho3D,urho3d/Urho3D,carnalis/Urho3D,iainmerrick/Urho3D,PredatorMF/Urho3D,urho3d/Urho3D,carnalis/Urho3D,abdllhbyrktr/Urho3D,iainmerrick/Urho3D,helingping/Urho3D,weitjong/Urho3D,henu/Urho3D,kostik1337/Urho3D,henu/Urho3D,xiliu98/Urho3D,rokups/Urho3D,fire/Urho3D-1,codedash64/Urho3D,codemon66/Urho3D,kostik1337/Urho3D,henu/Urho3D,abdllhbyrktr/Urho3D,iainmerrick/Urho3D,fire/Urho3D-1,tommy3/Urho3D,MonkeyFirst/Urho3D,codedash64/Urho3D,SuperWangKai/Urho3D,MeshGeometry/Urho3D,victorholt/Urho3D,helingping/Urho3D,xiliu98/Urho3D,luveti/Urho3D,bacsmar/Urho3D
9c18db35aac41b22e5ca828548a2e0b652930907
src/aerys/minko/scene/controller/camera/CameraController.as
src/aerys/minko/scene/controller/camera/CameraController.as
package aerys.minko.scene.controller.camera { import aerys.minko.ns.minko_scene; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.data.CameraDataProvider; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.camera.AbstractCamera; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.IDataProvider; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; public final class CameraController extends AbstractController { use namespace minko_scene; private var _camera : AbstractCamera = null; private var _ortho : Boolean = false; public function CameraController(ortho : Boolean = false) { super(AbstractCamera); _ortho = ortho; targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(controller : CameraController, target : AbstractCamera) : void { if (_camera != null) throw new Error('The CameraController can target only one Camera object.'); _camera = target; _camera.addedToScene.add(addedToSceneHandler); _camera.removedFromScene.add(removedFromSceneHandler); _camera.worldToLocal.changed.add(worldToLocalChangedHandler); } private function targetRemovedHandler(controller : CameraController, target : AbstractCamera) : void { _camera.addedToScene.remove(addedToSceneHandler); _camera.removedFromScene.remove(removedFromSceneHandler); _camera.worldToLocal.changed.remove(worldToLocalChangedHandler); _camera = null; } private function addedToSceneHandler(camera : AbstractCamera, scene : Scene) : void { var sceneBindings : DataBindings = scene.bindings; resetSceneCamera(scene); if (camera.enabled) sceneBindings.addProvider(camera.cameraData); camera.activated.add(cameraActivatedHandler); camera.deactivated.add(cameraDeactivatedHandler); camera.cameraData.changed.add(cameraPropertyChangedHandler); sceneBindings.addCallback('viewportWidth', viewportSizeChanged); sceneBindings.addCallback('viewportHeight', viewportSizeChanged); updateProjection(); } private function removedFromSceneHandler(camera : AbstractCamera, scene : Scene) : void { var sceneBindings : DataBindings = scene.bindings; resetSceneCamera(scene); if (camera.enabled) sceneBindings.removeProvider(camera.cameraData); camera.activated.remove(cameraActivatedHandler); camera.deactivated.remove(cameraDeactivatedHandler); camera.cameraData.changed.remove(cameraPropertyChangedHandler); sceneBindings.removeCallback('viewportWidth', viewportSizeChanged); sceneBindings.removeCallback('viewportHeight', viewportSizeChanged); } private function worldToLocalChangedHandler(worldToLocal : Matrix4x4) : void { var cameraData : CameraDataProvider = _camera.cameraData; var worldToScreen : Matrix4x4 = cameraData.worldToScreen; var screenToWorld : Matrix4x4 = cameraData.screenToWorld; var viewToWorld : Matrix4x4 = cameraData.viewToWorld; var cameraPosition : Vector4 = cameraData.position; var cameraDirection : Vector4 = cameraData.direction; worldToScreen.lock(); screenToWorld.lock(); cameraPosition.lock(); cameraDirection.lock(); worldToScreen.copyFrom(_camera.worldToLocal).append(cameraData.projection); screenToWorld.copyFrom(cameraData.screenToView).append(_camera.localToWorld); viewToWorld.transformVector(Vector4.ZERO, cameraPosition); viewToWorld.deltaTransformVector(Vector4.Z_AXIS, cameraDirection).normalize(); cameraData.frustum.updateFromMatrix(worldToScreen); worldToScreen.unlock(); screenToWorld.unlock(); cameraPosition.unlock(); cameraDirection.unlock(); } private function viewportSizeChanged(bindings : DataBindings, key : String, oldValue : Object, newValue : Object) : void { updateProjection(); } private function cameraPropertyChangedHandler(provider : IDataProvider, property : String) : void { if (property == 'zFar' || property == 'zNear' || property == 'fieldOfView' || property == 'zoom') updateProjection(); } private function updateProjection() : void { var sceneBindings : DataBindings = Scene(_camera.root).bindings; if (sceneBindings.propertyExists('viewportWidth') && sceneBindings.propertyExists('viewportHeight')) { var cameraData : CameraDataProvider = _camera.cameraData; var viewportWidth : Number = sceneBindings.getProperty('viewportWidth'); var viewportHeight : Number = sceneBindings.getProperty('viewportHeight'); var ratio : Number = viewportWidth / viewportHeight; var projection : Matrix4x4 = cameraData.projection; var screenToView : Matrix4x4 = cameraData.screenToView; var screenToWorld : Matrix4x4 = cameraData.screenToWorld; var worldToScreen : Matrix4x4 = cameraData.worldToScreen; projection.lock(); screenToView.lock(); screenToWorld.lock(); worldToScreen.lock(); if (_ortho) projection.ortho( viewportWidth / cameraData.zoom, viewportHeight / cameraData.zoom, cameraData.zNear, cameraData.zFar ); else projection.perspectiveFoV( cameraData.fieldOfView, ratio, cameraData.zNear, cameraData.zFar ); screenToView.copyFrom(projection).invert(); screenToWorld.copyFrom(screenToView).append(_camera.localToWorld); worldToScreen.copyFrom(_camera.worldToLocal).append(projection); cameraData.frustum.updateFromMatrix(worldToScreen); projection.unlock(); screenToView.unlock(); screenToWorld.unlock(); worldToScreen.unlock(); } } private function cameraActivatedHandler(camera : AbstractCamera) : void { var scene : Scene = camera.root as Scene; scene.bindings.addProvider(camera.cameraData); resetSceneCamera(scene); } private function cameraDeactivatedHandler(camera : AbstractCamera) : void { var scene : Scene = camera.root as Scene; scene.bindings.removeProvider(camera.cameraData); resetSceneCamera(scene); } private function resetSceneCamera(scene : Scene) : void { var cameras : Vector.<ISceneNode> = scene.getDescendantsByType(AbstractCamera); var numCameras : uint = cameras.length; var cameraId : uint = 0; var camera : AbstractCamera = null; if (_camera.enabled) { scene._camera = _camera; for (cameraId; cameraId < numCameras; ++cameraId) { camera = cameras[cameraId] as AbstractCamera; camera.enabled = camera == _camera; } } else { scene._camera = null; for (cameraId; cameraId < numCameras; ++cameraId) { camera = cameras[cameraId] as AbstractCamera; if (camera.enabled) scene._camera = camera; } } } } }
package aerys.minko.scene.controller.camera { import aerys.minko.ns.minko_scene; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.data.CameraDataProvider; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.camera.AbstractCamera; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.IDataProvider; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; public final class CameraController extends AbstractController { use namespace minko_scene; private var _camera : AbstractCamera = null; private var _ortho : Boolean = false; public function CameraController(ortho : Boolean = false) { super(AbstractCamera); _ortho = ortho; targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(controller : CameraController, target : AbstractCamera) : void { if (_camera != null) throw new Error('The CameraController can target only one Camera object.'); _camera = target; _camera.addedToScene.add(addedToSceneHandler); _camera.removedFromScene.add(removedFromSceneHandler); _camera.worldToLocal.changed.add(worldToLocalChangedHandler); } private function targetRemovedHandler(controller : CameraController, target : AbstractCamera) : void { _camera.addedToScene.remove(addedToSceneHandler); _camera.removedFromScene.remove(removedFromSceneHandler); _camera.worldToLocal.changed.remove(worldToLocalChangedHandler); _camera = null; } private function addedToSceneHandler(camera : AbstractCamera, scene : Scene) : void { var sceneBindings : DataBindings = scene.bindings; resetSceneCamera(scene); if (camera.enabled) sceneBindings.addProvider(camera.cameraData); camera.activated.add(cameraActivatedHandler); camera.deactivated.add(cameraDeactivatedHandler); camera.cameraData.changed.add(cameraPropertyChangedHandler); sceneBindings.addCallback('viewportWidth', viewportSizeChanged); sceneBindings.addCallback('viewportHeight', viewportSizeChanged); updateProjection(); } private function removedFromSceneHandler(camera : AbstractCamera, scene : Scene) : void { var sceneBindings : DataBindings = scene.bindings; resetSceneCamera(scene); if (camera.enabled) sceneBindings.removeProvider(camera.cameraData); camera.activated.remove(cameraActivatedHandler); camera.deactivated.remove(cameraDeactivatedHandler); camera.cameraData.changed.remove(cameraPropertyChangedHandler); sceneBindings.removeCallback('viewportWidth', viewportSizeChanged); sceneBindings.removeCallback('viewportHeight', viewportSizeChanged); } private function worldToLocalChangedHandler(worldToLocal : Matrix4x4) : void { var cameraData : CameraDataProvider = _camera.cameraData; var worldToScreen : Matrix4x4 = cameraData.worldToScreen; var screenToWorld : Matrix4x4 = cameraData.screenToWorld; var viewToWorld : Matrix4x4 = cameraData.viewToWorld; var cameraPosition : Vector4 = cameraData.position; var cameraDirection : Vector4 = cameraData.direction; worldToScreen.lock(); screenToWorld.lock(); cameraPosition.lock(); cameraDirection.lock(); worldToScreen.copyFrom(_camera.worldToLocal).append(cameraData.projection); screenToWorld.copyFrom(cameraData.screenToView).append(_camera.localToWorld); viewToWorld.transformVector(Vector4.ZERO, cameraPosition); viewToWorld.deltaTransformVector(Vector4.Z_AXIS, cameraDirection).normalize(); cameraData.frustum.updateFromMatrix(worldToScreen); worldToScreen.unlock(); screenToWorld.unlock(); cameraPosition.unlock(); cameraDirection.unlock(); } private function viewportSizeChanged(bindings : DataBindings, key : String, oldValue : Object, newValue : Object) : void { updateProjection(); } private function cameraPropertyChangedHandler(provider : IDataProvider, property : String) : void { if (property == 'zFar' || property == 'zNear' || property == 'fieldOfView' || property == 'zoom') updateProjection(); } private function updateProjection() : void { var sceneBindings : DataBindings = Scene(_camera.root).bindings; if (sceneBindings.propertyExists('viewportWidth') && sceneBindings.propertyExists('viewportHeight')) { var cameraData : CameraDataProvider = _camera.cameraData; var viewportWidth : Number = sceneBindings.getProperty('viewportWidth'); var viewportHeight : Number = sceneBindings.getProperty('viewportHeight'); var ratio : Number = viewportWidth / viewportHeight; var projection : Matrix4x4 = cameraData.projection; var screenToView : Matrix4x4 = cameraData.screenToView; var screenToWorld : Matrix4x4 = cameraData.screenToWorld; var worldToScreen : Matrix4x4 = cameraData.worldToScreen; projection.lock(); screenToView.lock(); screenToWorld.lock(); worldToScreen.lock(); if (_ortho) projection.ortho( viewportWidth / cameraData.zoom, viewportHeight / cameraData.zoom, cameraData.zNear, cameraData.zFar ); else projection.perspectiveFoV( cameraData.fieldOfView, ratio, cameraData.zNear, cameraData.zFar ); screenToView.copyFrom(projection).invert(); screenToWorld.copyFrom(screenToView).append(_camera.localToWorld); worldToScreen.copyFrom(_camera.worldToLocal).append(projection); cameraData.frustum.updateFromMatrix(worldToScreen); projection.unlock(); screenToView.unlock(); screenToWorld.unlock(); worldToScreen.unlock(); } } private function cameraActivatedHandler(camera : AbstractCamera) : void { var scene : Scene = camera.root as Scene; resetSceneCamera(scene); scene.bindings.addProvider(camera.cameraData); } private function cameraDeactivatedHandler(camera : AbstractCamera) : void { var scene : Scene = camera.root as Scene; resetSceneCamera(scene); scene.bindings.removeProvider(camera.cameraData); } private function resetSceneCamera(scene : Scene) : void { var cameras : Vector.<ISceneNode> = scene.getDescendantsByType(AbstractCamera); var numCameras : uint = cameras.length; var cameraId : uint = 0; var camera : AbstractCamera = null; if (_camera.enabled) { scene._camera = _camera; for (cameraId; cameraId < numCameras; ++cameraId) { camera = cameras[cameraId] as AbstractCamera; camera.enabled = camera == _camera; } } else { scene._camera = null; for (cameraId; cameraId < numCameras; ++cameraId) { camera = cameras[cameraId] as AbstractCamera; if (camera.enabled) scene._camera = camera; } } } } }
fix multiple cameras switch by patching CameraController to make sure the 'old' camera is deactivated and it's data provider out of the scene bindings before adding the data provider of the 'new' one
fix multiple cameras switch by patching CameraController to make sure the 'old' camera is deactivated and it's data provider out of the scene bindings before adding the data provider of the 'new' one
ActionScript
mit
aerys/minko-as3
a9ae90962a05238917630cacc2f94e438472397a
src/com/jonas/net/Multipart.as
src/com/jonas/net/Multipart.as
package com.jonas.net { import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLRequestHeader; import flash.utils.ByteArray; /** * * Based on RFC 1867 + real case observation * * RFC 1867 * https://tools.ietf.org/html/rfc1867 * */ public class Multipart { private var _url:String; private var _fields:Array = []; private var _files:Array = []; private var _data:ByteArray = new ByteArray(); private var _encoding:String = 'ascii'; //http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/charset-codes.html public function Multipart(url:String = null) { _url = url; } public function addFields(fields:Object):void { for (var s:String in fields) { addField(s, fields[s]); } } public function addField(name:String, value:String):void { _fields.push({name:name, value:value}); } public function addFile(name:String, byteArray:ByteArray, mimeType:String, fileName:String):void { _files.push({name:name, byteArray:byteArray, mimeType:mimeType, fileName:fileName}); } public function clear():void { _data = new ByteArray(); _fields = []; _files = []; } public function get request():URLRequest { var boundary: String = (Math.round(Math.random()*100000000)).toString(); var n:uint; var i:uint; // Add fields n = _fields.length; for(i=0; i<n; i++){ _writeString('--' + boundary + '\r\n' +'Content-Disposition: form-data; name="'+_fields[i].name+'"\r\n\r\n' +_fields[i].value+'\r\n'); } // Add files n = _files.length; for(i=0; i<n; i++){ _writeString('--'+boundary + '\r\n' +'Content-Disposition: form-data; name="'+_files[i].name+'"; filename="'+_files[i].fileName+'"\r\n' +'Content-Type: '+_files[i].mimeType+'\r\n\r\n'); _writeBytes(_files[i].byteArray); _writeString('\r\n'); } // Close _writeString('--' + boundary + '--\r\n'); var r: URLRequest = new URLRequest(_url); r.data = _data; r.method = URLRequestMethod.POST; r.requestHeaders.push( new URLRequestHeader('Content-type', 'multipart/form-data; boundary=' + boundary) ); return r; } public function get url():String { return _url; } public function set url(value:String):void { _url = value; } public function get encoding():String { return _encoding; } public function set encoding(value:String):void { _encoding = value; } private function _writeString(value:String):void { var b:ByteArray = new ByteArray(); b.writeMultiByte(value, _encoding); _data.writeBytes(b, 0, b.length); } private function _writeBytes(value:ByteArray):void { //_writeString("....FILE...."); value.position = 0; _data.writeBytes(value, 0, value.length); } } }
package com.jonas.net { import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLRequestHeader; import flash.utils.ByteArray; /** * * Based on RFC 1867 + real case observation * * RFC 1867 * https://tools.ietf.org/html/rfc1867 * */ public class Multipart { private var _url:String; private var _fields:Array = []; private var _files:Array = []; private var _data:ByteArray = new ByteArray(); private var _encoding:String = 'utf-8'; //http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/charset-codes.html public function Multipart(url:String = null) { _url = url; } public function addFields(fields:Object):void { for (var s:String in fields) { addField(s, fields[s]); } } public function addField(name:String, value:String):void { _fields.push({name:name, value:value}); } public function addFile(name:String, byteArray:ByteArray, mimeType:String, fileName:String):void { _files.push({name:name, byteArray:byteArray, mimeType:mimeType, fileName:fileName}); } public function clear():void { _data = new ByteArray(); _fields = []; _files = []; } public function get request():URLRequest { var boundary: String = (Math.round(Math.random()*100000000)).toString(); var n:uint; var i:uint; // Add fields n = _fields.length; for(i=0; i<n; i++){ _writeString('--' + boundary + '\r\n' + 'Content-Disposition: form-data; name="' + _fields[i].name+'"\r\n\r\n'); _writeString(_fields[i].value, _encoding); _writeString('\r\n'); } // Add files n = _files.length; for(i=0; i<n; i++){ _writeString('--'+boundary + '\r\n' +'Content-Disposition: form-data; name="'+_files[i].name+'"; filename="'+_files[i].fileName+'"\r\n' +'Content-Type: '+_files[i].mimeType+'\r\n\r\n'); _writeBytes(_files[i].byteArray); _writeString('\r\n'); } // Close _writeString('--' + boundary + '--\r\n'); var r: URLRequest = new URLRequest(_url); r.data = _data; r.method = URLRequestMethod.POST; r.requestHeaders.push( new URLRequestHeader('Content-type', 'multipart/form-data; boundary=' + boundary) ); return r; } public function get url():String { return _url; } public function set url(value:String):void { _url = value; } public function get encoding():String { return _encoding; } public function set encoding(value:String):void { _encoding = value; } private function _writeString(value:String, encoding:String = 'ascii'):void { var b:ByteArray = new ByteArray(); b.writeMultiByte(value, encoding); _data.writeBytes(b, 0, b.length); } private function _writeBytes(value:ByteArray):void { //_writeString("....FILE...."); value.position = 0; _data.writeBytes(value, 0, value.length); } } }
Support for not ascii compliant encodings. Also utf-8 as default encoding.
Support for not ascii compliant encodings. Also utf-8 as default encoding.
ActionScript
apache-2.0
jimojon/Multipart.as
4c1b7d4f3b56cdb7e74e1ee618c1b7ce736a60df
assets/scripts/entities/player.as
assets/scripts/entities/player.as
#include "entity.as" class player : entity { player(const glm::vec3& in position, const glm::quat& in rotation, const glm::vec3& in scale, const string& in mesh, const string& in skeleton) { super(position, rotation, scale); impl_.add_animation_component(mesh, skeleton); impl_.add_character_physics_component(box_shape(glm::vec3(0.6, 1, 0.3)), 10.f, 2.f); auto@ sc = impl_.add_state_component(); sc.emplace("stand", "scripts/character_states/stand.as"); sc.emplace("run", "scripts/character_states/run.as"); sc.emplace("walk_backward", "scripts/character_states/walk_backward.as"); } }
#include "entity.as" class player : entity { player(const glm::vec3& in position, const glm::quat& in rotation, const glm::vec3& in scale, const string& in mesh, const string& in skeleton) { super(position, rotation, scale); impl_.add_animation_component(mesh, skeleton); impl_.add_character_physics_component(box_shape(glm::vec3(0.6, 1, 0.3)), 10.f, 2.f); auto@ sc = impl_.add_state_component(); sc.emplace("stand", "scripts/character_states/stand.as"); sc.emplace("run", "scripts/character_states/run.as"); sc.emplace("walk_backward", "scripts/character_states/walk_backward.as"); sc.change_state("stand"); } }
Set initial player state in players ctor.
Set initial player state in players ctor.
ActionScript
mit
kasoki/project-zombye,kasoki/project-zombye,kasoki/project-zombye
b4c5370b98f802008211988df5f393a87a5f330f
frameworks/projects/charts/src/mx/charts/styles/HaloDefaults.as
frameworks/projects/charts/src/mx/charts/styles/HaloDefaults.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.charts.styles { import mx.core.mx_internal; import mx.graphics.IFill; import mx.graphics.IStroke; import mx.graphics.SolidColor; import mx.graphics.Stroke; import mx.styles.CSSStyleDeclaration; import mx.styles.IStyleManager2; use namespace mx_internal; /** * Initializes the core default styles for the charts classes. Each chart and element is responsible for initializing their own * style values, but they rely on the common values computed by the HaloDefaults class. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class HaloDefaults { include "../../core/Version.as"; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- /** * @private */ private static var inited:Boolean; [Inspectable(environment="none")] /** * The default selectors applied to the individual series in a chart. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal static var chartBaseChartSeriesStyles:Array; [Inspectable(environment="none")] /** * The default color values used by chart controls to color different series (or, in a PieSeries, different items). * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal static var defaultColors:Array = [ 0xE48701 ,0xA5BC4E ,0x1B95D9 ,0xCACA9E ,0x6693B0 ,0xF05E27 ,0x86D1E4 ,0xE4F9A0 ,0xFFD512 ,0x75B000 ,0x0662B0 ,0xEDE8C6 ,0xCC3300 ,0xD1DFE7 ,0x52D4CA ,0xC5E05D ,0xE7C174 ,0xFFF797 ,0xC5F68F ,0xBDF1E6 ,0x9E987D ,0xEB988D ,0x91C9E5 ,0x93DC4A ,0xFFB900 ,0x9EBBCD ,0x009797 ,0x0DB2C2 ]; [Inspectable(environment="none")] /** * The default SolidColor objects used as fills by chart controls to color different series (or, in a PieSeries, different items). * These Fill objects correspond to the values in the <code>defaultColors</code> Array. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal static var defaultFills:Array = []; [Inspectable(environment="none")] mx_internal static var pointStroke:IStroke; [Inspectable(environment="none")] /** * A pre-defined invisible Stroke that is used by several chart styles. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal static var emptyStroke:IStroke; //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- /** * Creates a CSSStyleDeclaration object or returns an existing one. * * @param selectorName The name of the selector to return. If no existing CSSStyleDeclaration object matches * this name, this method creates a new one and returns it. * * @param styleManager The styleManager instance to be used for getting and setting style declarations. * * @return The CSSStyleDeclaration object that matches the provided selector name. If no CSSStyleDeclaration object matches * that name, this method creates a new one and returns it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function createSelector( selectorName:String, styleManager:IStyleManager2):CSSStyleDeclaration { var selector:CSSStyleDeclaration = styleManager.getStyleDeclaration(selectorName); if (!selector) { selector = new CSSStyleDeclaration(); styleManager.setStyleDeclaration(selectorName, selector, false); } return selector; } /** * Initializes the common values used by the default styles for the chart and element classes. * * @param styleManager The styleManager instance to be used for getting and setting style declarations. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function init(styleManager:IStyleManager2):void { if (inited) return; var seriesStyleCount:int = defaultColors.length; for (var i:int = 0; i < seriesStyleCount; i++) { defaultFills[i] = new SolidColor(defaultColors[i]); } pointStroke = new Stroke(0, 0, 0.5); emptyStroke = new Stroke(0, 0, 0); chartBaseChartSeriesStyles = []; var f:Function; for (i = 0; i < seriesStyleCount; i++) { var styleName:String = "haloSeries" + i; chartBaseChartSeriesStyles[i] = styleName; var o:CSSStyleDeclaration = HaloDefaults.createSelector("." + styleName, styleManager); f = function (o:CSSStyleDeclaration, defaultFill:IFill,defaultStroke:IStroke):void { o.defaultFactory = function():void { this.fill = defaultFill; this.areaFill = defaultFill; this.areaStroke = emptyStroke; this.lineStroke = defaultStroke; } } f(o, HaloDefaults.defaultFills[i],new Stroke(defaultColors[i], 3, 1)); } } /** * Returns the CSSStyleDeclaration by chasing the chain of styleManagers * if necessary. * * @param name The name of the CSSStyleDeclaration * @return The CSSStyleDeclaration or null if not found */ public static function findStyleDeclaration(styleManager:IStyleManager2, name:String):CSSStyleDeclaration { var decl:CSSStyleDeclaration = styleManager.getStyleDeclaration(name); if (!decl) { var sm:IStyleManager2 = styleManager; while (sm.parent) { decl = sm.getStyleDeclaration(name); if (decl) break; sm = sm.parent; } } return decl; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.charts.styles { import mx.core.mx_internal; import mx.graphics.IFill; import mx.graphics.IStroke; import mx.graphics.SolidColor; import mx.graphics.Stroke; import mx.styles.CSSStyleDeclaration; import mx.styles.IStyleManager2; use namespace mx_internal; /** * Initializes the core default styles for the charts classes. Each chart and element is responsible for initializing their own * style values, but they rely on the common values computed by the HaloDefaults class. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class HaloDefaults { include "../../core/Version.as"; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- /** * @private */ private static var inited:Boolean; [Inspectable(environment="none")] /** * The default selectors applied to the individual series in a chart. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal static var chartBaseChartSeriesStyles:Array; [Inspectable(environment="none")] /** * The default color values used by chart controls to color different series (or, in a PieSeries, different items). * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal static var defaultColors:Array = [ 0xE48701 ,0xA5BC4E ,0x1B95D9 ,0xCACA9E ,0x6693B0 ,0xF05E27 ,0x86D1E4 ,0xE4F9A0 ,0xFFD512 ,0x75B000 ,0x0662B0 ,0xEDE8C6 ,0xCC3300 ,0xD1DFE7 ,0x52D4CA ,0xC5E05D ,0xE7C174 ,0xFFF797 ,0xC5F68F ,0xBDF1E6 ,0x9E987D ,0xEB988D ,0x91C9E5 ,0x93DC4A ,0xFFB900 ,0x9EBBCD ,0x009797 ,0x0DB2C2 ]; [Inspectable(environment="none")] /** * The default SolidColor objects used as fills by chart controls to color different series (or, in a PieSeries, different items). * These Fill objects correspond to the values in the <code>defaultColors</code> Array. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal static var defaultFills:Array = []; [Inspectable(environment="none")] mx_internal static var pointStroke:IStroke; [Inspectable(environment="none")] /** * A pre-defined invisible Stroke that is used by several chart styles. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal static var emptyStroke:IStroke; //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- /** * Creates a CSSStyleDeclaration object or returns an existing one. * * @param selectorName The name of the selector to return. If no existing CSSStyleDeclaration object matches * this name, this method creates a new one and returns it. * * @param styleManager The styleManager instance to be used for getting and setting style declarations. * * @return The CSSStyleDeclaration object that matches the provided selector name. If no CSSStyleDeclaration object matches * that name, this method creates a new one and returns it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function createSelector( selectorName:String, styleManager:IStyleManager2):CSSStyleDeclaration { var selector:CSSStyleDeclaration = styleManager.getStyleDeclaration(selectorName); if (!selector) { selector = new CSSStyleDeclaration(); styleManager.setStyleDeclaration(selectorName, selector, false); } return selector; } /** * Initializes the common values used by the default styles for the chart and element classes. * * @param styleManager The styleManager instance to be used for getting and setting style declarations. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function init(styleManager:IStyleManager2):void { if (inited) return; var seriesStyleCount:int = defaultColors.length; for (var i:int = 0; i < seriesStyleCount; i++) { defaultFills[i] = new SolidColor(defaultColors[i]); } pointStroke = new Stroke(0, 0, 0.5); emptyStroke = new Stroke(0, 0, 0); chartBaseChartSeriesStyles = []; var f:Function; for (i = 0; i < seriesStyleCount; i++) { var styleName:String = "haloSeries" + i; chartBaseChartSeriesStyles[i] = styleName; var o:CSSStyleDeclaration = HaloDefaults.createSelector("." + styleName, styleManager); f = function (o:CSSStyleDeclaration, defaultFill:IFill,defaultStroke:IStroke):void { o.defaultFactory = function():void { this.fill = defaultFill; this.areaFill = defaultFill; this.areaStroke = emptyStroke; this.lineStroke = defaultStroke; } } f(o, HaloDefaults.defaultFills[i],new Stroke(defaultColors[i], 3, 1)); } } /** * Returns the CSSStyleDeclaration by chasing the chain of styleManagers * if necessary. * * @param name The name of the CSSStyleDeclaration * @return The CSSStyleDeclaration or null if not found */ public static function findStyleDeclaration(styleManager:IStyleManager2, name:String):CSSStyleDeclaration { var decl:CSSStyleDeclaration = styleManager.getStyleDeclaration(name); if (!decl) { var sm:IStyleManager2 = styleManager.parent; while (sm) { decl = sm.getStyleDeclaration(name); if (decl) break; sm = sm.parent; } } return decl; } } }
fix for FLEX-34728
fix for FLEX-34728
ActionScript
apache-2.0
apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,adufilie/flex-sdk
6baad29b2f8f622446622dd15ed517b5b08f2841
src/flexlib/containers/AdvancedForm.as
src/flexlib/containers/AdvancedForm.as
/* Copyright (c) 2007 FlexLib Contributors. See: http://code.google.com/p/flexlib/wiki/ProjectContributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Class that provides Reset and Undo/Redo functionality for a Form */ package flexlib.containers { import flash.events.*; import flash.ui.KeyLocation; import flash.ui.Keyboard; import flash.utils.describeType; import mx.containers.*; import mx.controls.*; import mx.core.Container; import mx.core.UIComponent; import mx.events.ValidationResultEvent; import mx.messaging.errors.MessagingError; import mx.validators.ValidationResult; import mx.validators.Validator; [IconFile("AdvancedForm.png")] /** * The Advanced Form component provides Reset, Undo and Redo functionality. * * <p>The Advanced Form component provides Reset, Undo and Redo functionality. * Undo and Redo are accessed by pressing "ctrl-Z" and "ctrl-Y" repsectively.</p> * * @mxml * * <pre> * &lt;flexlib:AdvancedForm * <strong>Properties</strong> * undoHistorySize="5" * modelType="shared|memory" * * &gt; * ... * <i>child tags</i> * ... * &lt;/flexlib:AdvancedForm&gt; * </pre> */ public class AdvancedForm extends Form { //[Bindable] //public var debug:String = ""; //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private */ private var noSnapshotFlag:Boolean = false; /** * @private Key for reset snapshot */ private var resetSnapshotKey:String = "reset"; /** * @private */ private var undoCounter:int = 0; /** * @private */ private var undoCurrentIndex:int = -1; /** * @private */ private var modelStack:Object; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // validators //---------------------------------- /** * @private LookupTable of isValid flags */ private var validators:Object; //---------------------------------- // undoHistorySize //---------------------------------- /** * @private */ private var _undoHistorySize:int = 5; /** * The undoHistorySize defaults the number of undos. * * @default true */ public function set undoHistorySize( value:int ):void { _undoHistorySize = value; } public function get undoHistorySize():int { return _undoHistorySize; } //---------------------------------- // modelType //---------------------------------- /** * @private */ private var _modelType:String = "shared"; [Inspectable(category="General", enumeration="shared,memory", defaultValue="shared")] /** * The modelStack handles the data. * * @default true */ public function set modelType( value:String ):void { if( value == "shared" ) { } else { } } public function get modelType():String { return _modelType; } //---------------------------------- // isValid //---------------------------------- /** * Property that allows for one place to know if the From is valid * * Default to true, if any Validators are present then it will be set to false */ [Bindable] public var isValid:Boolean = true; //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Resets values of the form */ public function resetForm():void { var children:Array = this.getChildren(); resetValues( children, resetSnapshotKey ); undoCounter = 0; undoCurrentIndex = -1; modelStack = new Object(); snapshotValues( this.getChildren(), resetSnapshotKey ); } /** * @private */ private function myKeyDownHandler( event:KeyboardEvent ):void { if( event.ctrlKey && event.keyCode == 90 && !( event.target is NumericStepper ) ) { event.stopPropagation(); event.preventDefault() doUndo(); } else if( event.ctrlKey && event.keyCode == 89 && !( event.target is NumericStepper ) ) { doRedo(); } else { super.keyDownHandler( event ); } } /** * Creates snapshot of values for reseting */ override protected function childrenCreated():void { super.childrenCreated(); // Find Validators and add EventListeners parent.addEventListener( "creationComplete", setValidatorListenerEvents ); this.parent.addEventListener( KeyboardEvent.KEY_DOWN, myKeyDownHandler, false, 0, true ); } /** * Loop through all Validtors at the same level as the Form and set a Event listener for Valid and Invalid */ private function setValidatorListenerEvents( event:Event ):void { // Take First Snapshot After All Children have been created snapshotValues( this.getChildren(), resetSnapshotKey ); var container:Object = document; // Check parent control to make sure its capable of having children if( !( container is Container ) ) return; // Describe Parent var classInfo:XML = describeType( container ); // Reset Defaults validators = new Array(); isValid = true; // Loop over all parentDocument's properties looking for Validators for each (var a:XML in classInfo..accessor) { try { if( container[ a.@name ] is Validator ) { //Logger.debug( "setValidatorListenerEvents:Property is Validator: " + a.@name ); // If Validator is found default to false isValid = false; var obj:Object = new Object(); obj.reference = container[ a.@name ]; obj.isValid = false; validators.push( obj ); // Set Valid and Invalid week reference listeners on the Validators Validator( container[ a.@name ] ).addEventListener( ValidationResultEvent.VALID, setValidFlag, false, 0, true ); Validator( container[ a.@name ] ).addEventListener( ValidationResultEvent.INVALID, setValidFlag, false, 0, true ); } } catch( err:Error ) { if( err.errorID != 1077 ) { //Logger.error( "AdvancedForm:setValidatorListenerEvents: " + err.message ); } } } } /** * Handles all valid and invalid events on the validators */ private function setValidFlag( event:ValidationResultEvent ):void { var tmpFlag:Boolean = true; for( var i:int = 0; i < validators.length; i++ ) { if( validators[ i ].reference == event.target ) { //Logger.debug( "setValidFlag:event.target: " + event.type ); validators[ i ].isValid = ( event.type == ValidationResultEvent.VALID ); } tmpFlag = ( tmpFlag && validators[ i ].isValid ); } isValid = tmpFlag; } /** * */ private function snapshotValues( obj:Object, snapshotKey:String ):void { try { if( modelStack == null ) modelStack = new Object(); if( modelStack[ snapshotKey ] == null ) modelStack[ snapshotKey ] = new Object(); var snapshotModel:Object = modelStack[ snapshotKey ]; for( var a:String in obj ) { if( obj[ a ] is FormItem ) { snapshotValues( obj[ a ].getChildren(), snapshotKey ); } else { var tmpObj:Object = obj[ a ]; var tmpID:String = tmpObj.toString(); if( snapshotModel[ tmpID ] == undefined ) snapshotModel[ tmpID ] = new Object(); var value:Object; if( tmpObj is TextInput || tmpObj is TextArea ) value = tmpObj.text; if( tmpObj is RadioButton || tmpObj is CheckBox ) value = tmpObj.selected; if( tmpObj is ComboBox ) value = tmpObj.selectedIndex; if( tmpObj is NumericStepper ) value = tmpObj.value; if( tmpObj is TextInput || tmpObj is TextArea ) UIComponent( tmpObj ).addEventListener( FocusEvent.FOCUS_OUT, textInputChange ); else UIComponent( tmpObj ).addEventListener( Event.CHANGE, controlChange ); snapshotModel[ tmpID ] = value; } } } catch( err:Error ) { //Logger.error( "AdvancedForm:snapshotValues: " + err.message ); } } /** * @private */ private function textInputChange( event:FocusEvent ):void { var snapshotModel:Object = getLastestSnapshot(); var tmpKey:String = event.target.parent.toString(); if( snapshotModel[ tmpKey ] == undefined ) ;//throw new Error( "Snapshot not defined for key = " + tmpKey ); if( snapshotModel[ tmpKey ] != event.target.parent.text ) { takeSnapshot(); } } /** * @private */ private function controlChange( event:Event ):void { if( event.target is RadioButton && !event.target.selected ) takeSnapshot(); if( !(event.target is RadioButton) ) takeSnapshot(); } /** * @private */ private function doUndo():void { //debug += "\ndoUndo: undoCurrentIndex: " + undoCurrentIndex + " undoCounter: " + undoCounter; noSnapshotFlag = true; var index:int = undoCurrentIndex - 1; if( index >= ( undoCounter - 1 - undoHistorySize ) && index > -2 ) { undoCurrentIndex--; //debug += "\ndoUndo: resetValues: " + undoCurrentIndex; resetValues( this.getChildren(), getSnapshotKey( undoCurrentIndex ) ); } noSnapshotFlag = false; } /** * @private */ private function doRedo():void { //debug += "\ndoRedo: undoCurrentIndex: " + undoCurrentIndex + " undoCounter: " + undoCounter; noSnapshotFlag = true; var index:int = undoCurrentIndex + 1; if( index < undoCounter ) { undoCurrentIndex++; resetValues( this.getChildren(), getSnapshotKey( undoCurrentIndex ) ); } noSnapshotFlag = false; } /** * @private */ private function takeSnapshot():void { if( !noSnapshotFlag ) { if( undoCurrentIndex < undoCounter - 1 ) undoCounter = undoCurrentIndex + 1; //debug += "\ntakeSnaphost: undoCurrentIndex: " + undoCurrentIndex + " undoCounter: " + undoCounter; snapshotValues( this.getChildren(), undoCounter+"" ); undoCurrentIndex = undoCounter; undoCounter++; } } /** * @private */ private function getLastestSnapshot():Object { if( undoCurrentIndex > -1 ) return modelStack[ undoCurrentIndex+"" ]; else return modelStack[ resetSnapshotKey ]; } /** * @private */ private function getSnapshotKey( coutner:int ):String { if( coutner >= 0 ) return coutner+""; else return resetSnapshotKey; } /** * */ private function resetValues( obj:Object, snapshotKey:String ):void { if( modelStack[ snapshotKey ] == undefined ) throw new Error( "Invalid snapshot" ); // Disable all Validators try { for( var i:int = 0; i < validators.length; i++ ) { isValid = false; Validator( validators[ i ].reference ).enabled = false; validators[ i ].isValid = false; } } catch( err:Error ) { //Logger.error( "AdvancedForm:resetValues:Disabling Validators: " + err.message ); } var snapshotModel:Object = modelStack[ snapshotKey ]; for( var a:String in obj ) { if( obj[ a ] is FormItem ) { resetValues( obj[ a ].getChildren(), snapshotKey ); } else { var tmpObj:Object = obj[ a ]; var tmpID:String = tmpObj.toString(); if( snapshotModel[ tmpID ] == undefined && ( tmpObj is Container || ( !(tmpObj is TextInput) && !(tmpObj is RadioButton) && !(tmpObj is ComboBox) && !(tmpObj is NumericStepper) ) ) ) continue; if( snapshotModel[ tmpID ] == undefined ) throw new Error( "Invalid obj in snapshot: " + tmpID ); var value:Object; if( tmpObj is TextInput || tmpObj is TextArea ) tmpObj.text = snapshotModel[ tmpID ]; if( tmpObj is RadioButton || tmpObj is CheckBox ) tmpObj.selected = snapshotModel[ tmpID ]; if( tmpObj is ComboBox ) tmpObj.selectedIndex = snapshotModel[ tmpID ]; if( tmpObj is NumericStepper ) tmpObj.value = snapshotModel[ tmpID ]; } } // Enable all Validators try { for( i = 0; i < validators.length; i++ ) { Validator( validators[ i ].reference ).enabled = true; } } catch( err:Error ) { //Logger.error( "AdvancedForm:resetValues:Disabling Validators: " + err.message ); } } /** * Gather references and defaults of all the children */ private function strChildren( obj:Object ):String { var str:String = ""; for( var a:String in obj ) { str += a + "=[" + obj[ a ] + "]\n"; } return str; } } }
/* Copyright (c) 2007 FlexLib Contributors. See: http://code.google.com/p/flexlib/wiki/ProjectContributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Class t hat provides Reset and Undo/Redo functionality for a Form */ package flexlib.containers { import flash.events.*; import flash.ui.KeyLocation; import flash.ui.Keyboard; import flash.utils.describeType; import mx.containers.*; import mx.controls.*; import mx.core.Container; import mx.core.UIComponent; import mx.events.ValidationResultEvent; import mx.messaging.errors.MessagingError; import mx.validators.ValidationResult; import mx.validators.Validator; [IconFile("AdvancedForm.png")] /** * The Advanced Form component provides Reset, Undo and Redo functionality. * * <p>The Advanced Form component provides Reset, Undo and Redo functionality. * Undo and Redo are accessed by pressing "ctrl-Z" and "ctrl-Y" repsectively.</p> * * @mxml * * <pre> * &lt;flexlib:AdvancedForm * <strong>Properties</strong> * undoHistorySize="5" * modelType="shared|memory" * * &gt; * ... * <i>child tags</i> * ... * &lt;/flexlib:AdvancedForm&gt; * </pre> */ public class AdvancedForm extends Form { //[Bindable] //public var debug:String = ""; //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private */ private var noSnapshotFlag:Boolean = false; /** * @private Key for reset snapshot */ private var resetSnapshotKey:String = "reset"; /** * @private */ private var undoCounter:int = 0; /** * @private */ private var undoCurrentIndex:int = -1; /** * @private */ private var modelStack:Object; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // validators //---------------------------------- /** * @private LookupTable of isValid flags */ private var validators:Object; //---------------------------------- // undoHistorySize //---------------------------------- /** * @private */ private var _undoHistorySize:int = 5; /** * The undoHistorySize defaults the number of undos. * * @default true */ public function set undoHistorySize( value:int ):void { _undoHistorySize = value; } public function get undoHistorySize():int { return _undoHistorySize; } //---------------------------------- // modelType //---------------------------------- /** * @private */ private var _modelType:String = "shared"; [Inspectable(category="General", enumeration="shared,memory", defaultValue="shared")] /** * The modelStack handles the data. * * @default true */ public function set modelType( value:String ):void { if( value == "shared" ) { } else { } } public function get modelType():String { return _modelType; } //---------------------------------- // isValid //---------------------------------- /** * Property that allows for one place to know if the From is valid * * Default to true, if any Validators are present then it will be set to false */ [Bindable] public var isValid:Boolean = true; //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Resets values of the form */ public function resetForm():void { var children:Array = this.getChildren(); resetValues( children, resetSnapshotKey ); undoCounter = 0; undoCurrentIndex = -1; modelStack = new Object(); snapshotValues( this.getChildren(), resetSnapshotKey ); } /** * @private */ private function myKeyDownHandler( event:KeyboardEvent ):void { if( event.ctrlKey && event.keyCode == 90 && !( event.target is NumericStepper ) ) { event.stopPropagation(); event.preventDefault() doUndo(); } else if( event.ctrlKey && event.keyCode == 89 && !( event.target is NumericStepper ) ) { doRedo(); } else { super.keyDownHandler( event ); } } /** * Creates snapshot of values for reseting */ override protected function childrenCreated():void { super.childrenCreated(); // Find Validators and add EventListeners parent.addEventListener( "creationComplete", setValidatorListenerEvents ); this.parent.addEventListener( KeyboardEvent.KEY_DOWN, myKeyDownHandler, false, 0, true ); } /** * Loop through all Validtors at the same level as the Form and set a Event listener for Valid and Invalid */ private function setValidatorListenerEvents( event:Event ):void { // Take First Snapshot After All Children have been created snapshotValues( this.getChildren(), resetSnapshotKey ); var container:Object = document; // Check parent control to make sure its capable of having children if( !( container is Container ) ) return; // Describe Parent var classInfo:XML = describeType( container ); // Reset Defaults validators = new Array(); isValid = true; // Loop over all parentDocument's properties looking for Validators for each (var a:XML in classInfo..accessor) { try { if( container[ a.@name ] is Validator ) { //Logger.debug( "setValidatorListenerEvents:Property is Validator: " + a.@name ); // If Validator is found default to false isValid = false; var obj:Object = new Object(); obj.reference = container[ a.@name ]; obj.isValid = false; validators.push( obj ); // Set Valid and Invalid week reference listeners on the Validators Validator( container[ a.@name ] ).addEventListener( ValidationResultEvent.VALID, setValidFlag, false, 0, true ); Validator( container[ a.@name ] ).addEventListener( ValidationResultEvent.INVALID, setValidFlag, false, 0, true ); } } catch( err:Error ) { if( err.errorID != 1077 ) { //Logger.error( "AdvancedForm:setValidatorListenerEvents: " + err.message ); } } } } /** * Handles all valid and invalid events on the validators */ private function setValidFlag( event:ValidationResultEvent ):void { var tmpFlag:Boolean = true; for( var i:int = 0; i < validators.length; i++ ) { if( validators[ i ].reference == event.target ) { //Logger.debug( "setValidFlag:event.target: " + event.type ); validators[ i ].isValid = ( event.type == ValidationResultEvent.VALID ); } tmpFlag = ( tmpFlag && validators[ i ].isValid ); } isValid = tmpFlag; } /** * */ private function snapshotValues( obj:Object, snapshotKey:String ):void { try { if( modelStack == null ) modelStack = new Object(); if( modelStack[ snapshotKey ] == null ) modelStack[ snapshotKey ] = new Object(); var snapshotModel:Object = modelStack[ snapshotKey ]; for( var a:String in obj ) { if( obj[ a ] is FormItem ) { snapshotValues( obj[ a ].getChildren(), snapshotKey ); } else { var tmpObj:Object = obj[ a ]; var tmpID:String = tmpObj.toString(); if( snapshotModel[ tmpID ] == undefined ) snapshotModel[ tmpID ] = new Object(); var value:Object; if( tmpObj is TextInput || tmpObj is TextArea ) value = tmpObj.text; if( tmpObj is RadioButton || tmpObj is CheckBox ) value = tmpObj.selected; if( tmpObj is ComboBox ) value = tmpObj.selectedIndex; if( tmpObj is NumericStepper ) value = tmpObj.value; if( tmpObj is TextInput || tmpObj is TextArea ) UIComponent( tmpObj ).addEventListener( FocusEvent.FOCUS_OUT, textInputChange ); else UIComponent( tmpObj ).addEventListener( Event.CHANGE, controlChange ); snapshotModel[ tmpID ] = value; } } } catch( err:Error ) { //Logger.error( "AdvancedForm:snapshotValues: " + err.message ); } } /** * @private */ private function textInputChange( event:FocusEvent ):void { var snapshotModel:Object = getLastestSnapshot(); var tmpKey:String = event.target.parent.toString(); if( snapshotModel[ tmpKey ] == undefined ) ;//throw new Error( "Snapshot not defined for key = " + tmpKey ); if( snapshotModel[ tmpKey ] != event.target.parent.text ) { takeSnapshot(); } } /** * @private */ private function controlChange( event:Event ):void { if( event.target is RadioButton && !event.target.selected ) takeSnapshot(); if( !(event.target is RadioButton) ) takeSnapshot(); } /** * @private */ private function doUndo():void { //debug += "\ndoUndo: undoCurrentIndex: " + undoCurrentIndex + " undoCounter: " + undoCounter; noSnapshotFlag = true; var index:int = undoCurrentIndex - 1; if( index >= ( undoCounter - 1 - undoHistorySize ) && index > -2 ) { undoCurrentIndex--; //debug += "\ndoUndo: resetValues: " + undoCurrentIndex; resetValues( this.getChildren(), getSnapshotKey( undoCurrentIndex ) ); } noSnapshotFlag = false; } /** * @private */ private function doRedo():void { //debug += "\ndoRedo: undoCurrentIndex: " + undoCurrentIndex + " undoCounter: " + undoCounter; noSnapshotFlag = true; var index:int = undoCurrentIndex + 1; if( index < undoCounter ) { undoCurrentIndex++; resetValues( this.getChildren(), getSnapshotKey( undoCurrentIndex ) ); } noSnapshotFlag = false; } /** * @private */ private function takeSnapshot():void { if( !noSnapshotFlag ) { if( undoCurrentIndex < undoCounter - 1 ) undoCounter = undoCurrentIndex + 1; //debug += "\ntakeSnaphost: undoCurrentIndex: " + undoCurrentIndex + " undoCounter: " + undoCounter; snapshotValues( this.getChildren(), undoCounter+"" ); undoCurrentIndex = undoCounter; undoCounter++; } } /** * @private */ private function getLastestSnapshot():Object { if( undoCurrentIndex > -1 ) return modelStack[ undoCurrentIndex+"" ]; else return modelStack[ resetSnapshotKey ]; } /** * @private */ private function getSnapshotKey( coutner:int ):String { if( coutner >= 0 ) return coutner+""; else return resetSnapshotKey; } /** * */ private function resetValues( obj:Object, snapshotKey:String ):void { if( modelStack[ snapshotKey ] == undefined ) throw new Error( "Invalid snapshot" ); // Disable all Validators try { for( var i:int = 0; i < validators.length; i++ ) { isValid = false; Validator( validators[ i ].reference ).enabled = false; validators[ i ].isValid = false; } } catch( err:Error ) { //Logger.error( "AdvancedForm:resetValues:Disabling Validators: " + err.message ); } var snapshotModel:Object = modelStack[ snapshotKey ]; for( var a:String in obj ) { if( obj[ a ] is FormItem ) { resetValues( obj[ a ].getChildren(), snapshotKey ); } else { var tmpObj:Object = obj[ a ]; var tmpID:String = tmpObj.toString(); if( snapshotModel[ tmpID ] == undefined && ( tmpObj is Container || ( !(tmpObj is TextInput) && !(tmpObj is RadioButton) && !(tmpObj is ComboBox) && !(tmpObj is NumericStepper) ) ) ) continue; if( snapshotModel[ tmpID ] == undefined ) throw new Error( "Invalid obj in snapshot: " + tmpID ); var value:Object; if( tmpObj is TextInput || tmpObj is TextArea ) tmpObj.text = snapshotModel[ tmpID ]; if( tmpObj is RadioButton || tmpObj is CheckBox ) tmpObj.selected = snapshotModel[ tmpID ]; if( tmpObj is ComboBox ) tmpObj.selectedIndex = snapshotModel[ tmpID ]; if( tmpObj is NumericStepper ) tmpObj.value = snapshotModel[ tmpID ]; } } // Enable all Validators try { for( i = 0; i < validators.length; i++ ) { Validator( validators[ i ].reference ).enabled = true; } } catch( err:Error ) { //Logger.error( "AdvancedForm:resetValues:Disabling Validators: " + err.message ); } } /** * Gather references and defaults of all the children */ private function strChildren( obj:Object ):String { var str:String = ""; for( var a:String in obj ) { str += a + "=[" + obj[ a ] + "]\n"; } return str; } } }
Test commit rights, added a space in a comment.
Test commit rights, added a space in a comment.
ActionScript
mit
Acidburn0zzz/flexlib
910e2172b2987f35be2a8ae6f15f37a77d8cd582
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; public class swfcat extends Sprite { private const TOR_ADDRESS:String = "173.255.221.44"; private const TOR_PORT:int = 9001; private var output_text:TextField; // Socket to Tor relay. private var s_t:Socket; // Socket to facilitator. private var s_f:Socket; // Socket to client. private var s_c:Socket; private var fac_addr:Object; private function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function swfcat() { 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."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String; puts("Parameters loaded."); fac_spec = this.loaderInfo.parameters["facilitator"]; if (!fac_spec) { puts("Error: no \"facilitator\" specification provided."); return; } puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = parse_addr_spec(fac_spec); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } go(TOR_ADDRESS, TOR_PORT); } /* We connect first to the Tor relay; once that happens we connect to the facilitator to get a client address; once we have the address of a waiting client then we connect to the client and BAM! we're in business. */ private function go(tor_address:String, tor_port:int):void { s_t = new Socket(); s_t.addEventListener(Event.CONNECT, tor_connected); s_t.addEventListener(Event.CLOSE, function (e:Event):void { puts("Tor: closed."); if (s_c.connected) s_c.close(); }); s_t.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Tor: I/O error: " + e.text + "."); if (s_c.connected) s_c.close(); }); s_t.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Tor: security error: " + e.text + "."); if (s_c.connected) s_c.close(); }); puts("Tor: connecting to " + tor_address + ":" + tor_port + "."); s_t.connect(tor_address, tor_port); } private function tor_connected(e:Event):void { /* Got a connection to tor, now let's get served a client from the facilitator */ s_f = new Socket(); puts("Tor: connected."); s_f.addEventListener(Event.CONNECT, fac_connected); s_f.addEventListener(Event.CLOSE, function (e:Event):void { puts("Facilitator: closed connection."); }); s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); if (s_t.connected) s_t.close(); }); s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); if (s_t.connected) s_t.close(); }); puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + "."); s_f.connect(fac_addr.host, fac_addr.port); } private function fac_connected(e:Event):void { puts("Facilitator: connected."); s_f.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var client_spec:String; var client_addr:Object; client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8"); puts("Facilitator: got \"" + client_spec + "\""); client_addr = parse_addr_spec(client_spec); if (!client_addr) { puts("Error: Client spec must be in the form \"host:port\"."); return; } if (client_addr.host == "0.0.0.0" && client_addr.port == 0) { puts("Error: Facilitator has no clients."); return; } puts("Client: connecting to " + client_addr.host + ":" + client_addr.port + "."); s_c.connect(client_addr.host, client_addr.port); }); s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n"); } private function client_connected(e:Event):void { puts("Client: connected."); 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 + "."); s_c.writeBytes(bytes); }); s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_c.readBytes(bytes, 0, e.bytesLoaded); puts("Client: read " + bytes.length + "."); s_t.writeBytes(bytes); }); } private static function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } }
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; public class swfcat extends Sprite { /* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a crossdomain policy. */ private const DEFAULT_TOR_ADDR:Object = { host: "173.255.221.44", port: 9001 }; private var output_text:TextField; // Socket to Tor relay. private var s_t:Socket; // Socket to facilitator. private var s_f:Socket; // Socket to client. private var s_c:Socket; private var fac_addr:Object; private var tor_addr:Object; private function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function swfcat() { 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."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String; var tor_spec:String; puts("Parameters loaded."); fac_spec = this.loaderInfo.parameters["facilitator"]; if (!fac_spec) { puts("Error: no \"facilitator\" specification provided."); return; } puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = parse_addr_spec(fac_spec); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } tor_addr = DEFAULT_TOR_ADDR; go(); } /* We connect first to the Tor relay; once that happens we connect to the facilitator to get a client address; once we have the address of a waiting client then we connect to the client and BAM! we're in business. */ private function go():void { s_t = new Socket(); s_t.addEventListener(Event.CONNECT, tor_connected); s_t.addEventListener(Event.CLOSE, function (e:Event):void { puts("Tor: closed."); if (s_c.connected) s_c.close(); }); s_t.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Tor: I/O error: " + e.text + "."); if (s_c.connected) s_c.close(); }); s_t.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Tor: security error: " + e.text + "."); if (s_c.connected) s_c.close(); }); puts("Tor: connecting to " + tor_addr.host + ":" + tor_addr.port + "."); s_t.connect(tor_addr.host, tor_addr.port); } private function tor_connected(e:Event):void { /* Got a connection to tor, now let's get served a client from the facilitator */ s_f = new Socket(); puts("Tor: connected."); s_f.addEventListener(Event.CONNECT, fac_connected); s_f.addEventListener(Event.CLOSE, function (e:Event):void { puts("Facilitator: closed connection."); }); s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); if (s_t.connected) s_t.close(); }); s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); if (s_t.connected) s_t.close(); }); puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + "."); s_f.connect(fac_addr.host, fac_addr.port); } private function fac_connected(e:Event):void { puts("Facilitator: connected."); s_f.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var client_spec:String; var client_addr:Object; client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8"); puts("Facilitator: got \"" + client_spec + "\""); client_addr = parse_addr_spec(client_spec); if (!client_addr) { puts("Error: Client spec must be in the form \"host:port\"."); return; } if (client_addr.host == "0.0.0.0" && client_addr.port == 0) { puts("Error: Facilitator has no clients."); return; } puts("Client: connecting to " + client_addr.host + ":" + client_addr.port + "."); s_c.connect(client_addr.host, client_addr.port); }); s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n"); } private function client_connected(e:Event):void { puts("Client: connected."); 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 + "."); s_c.writeBytes(bytes); }); s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_c.readBytes(bytes, 0, e.bytesLoaded); puts("Client: read " + bytes.length + "."); s_t.writeBytes(bytes); }); } private static function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } }
Handle the Tor relay address as an instance variable.
Handle the Tor relay address as an instance variable. Comment the hardcoded relay address.
ActionScript
mit
arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy
f9e0873b48c3c91674c43e437676b3e81669d3f3
src/aerys/minko/render/shader/compiler/DebugCompiler.as
src/aerys/minko/render/shader/compiler/DebugCompiler.as
package aerys.minko.render.shader.compiler { import aerys.minko.render.shader.compiler.allocator.Allocation; import aerys.minko.render.shader.compiler.allocator.ParameterAllocation; import aerys.minko.render.shader.compiler.visitor.writer.WriteAgal; import aerys.minko.render.shader.compiler.visitor.writer.WriteDot; 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.shader.node.operation.AbstractOperation; import flash.display.BitmapData; import flash.geom.Matrix; import flash.geom.Rectangle; import flash.text.TextField; public class DebugCompiler extends Compiler { internal static const FIELD_WIDTH : uint = 20; internal static const FIELD_HEIGHT : uint = 25; public function DebugCompiler() { super(); } public function compileAgalVertexShader() : String { return new WriteAgal( _attrAllocator, _fsTmpAllocator, _varyingAllocator, _fsConstAllocator, _vsTmpAllocator, _vsConstAllocator ).processVertexShader(_vertexOps); } public function compileAgalFragmentShader() : String { return new WriteAgal( _attrAllocator, _fsTmpAllocator, _varyingAllocator, _fsConstAllocator, _vsTmpAllocator, _vsConstAllocator ).processFragmentShader(_colorNode); } public function writeDotGraph() : String { return new WriteDot().processShader(_clipspacePosNode, _colorNode); } public function writeConstantAllocationSummary(vertexShader : Boolean = true) : String { var offsetToLetter : Vector.<String> = Vector.<String>(['x', 'y', 'z', 'w']); var summary : String = ''; var allocationTable : Vector.<ParameterAllocation> = vertexShader ? _vsParams : _fsParams; var constantTable : Vector.<Number> = vertexShader ? _vsConstData : _fsConstData; var occupiedRegisters : uint = constantTable.length / 4; for (var registerId : uint = 0; registerId < occupiedRegisters; ++registerId) for (var offsetId : uint = 0; offsetId < 4; ++offsetId) { var foundInParameterTable : Boolean = false; for each (var allocation : ParameterAllocation in allocationTable) { if (allocation.offset == 4 * registerId + offsetId) { foundInParameterTable = true; summary += (vertexShader ? "vc" : "fc"); if (allocation.size < 4) { summary += registerId + '.'; for (var i : uint = allocation.offset % 4; i < allocation.offset % 4 + allocation.size && i < 4; ++i) summary += offsetToLetter[i]; } else if (allocation.size == 16) { summary += '[' + registerId + '-' + (registerId + 3) + ']'; } var parameter : AbstractParameter = allocation.parameter; if (parameter is StyleParameter) { var styleParam : StyleParameter = parameter as StyleParameter; summary += "\t\tStyleParameter['" + styleParam.key + "']\n"; } else if (parameter is WorldParameter) { var worldParam : WorldParameter = parameter as WorldParameter; summary += "\t\tWorldParameter[class='" + worldParam.className + "', index='" + worldParam.index + "', field='" + worldParam.field + "']\n"; } else if (parameter is TransformParameter) { var transformParam : TransformParameter = parameter as TransformParameter; summary += "\t\tTransformParameter[key='" + transformParam.key + "']\n"; } break; } else if (allocation.offset < 4 * registerId + offsetId && allocation.offset + allocation.size > 4 * registerId + offsetId) { foundInParameterTable = true; break; } } if (!foundInParameterTable) { summary += (vertexShader ? "vc" : "fc") + registerId.toString() + '.' + offsetToLetter[offsetId] + "\t\tConstant[value='" + constantTable[4 * registerId + offsetId] + "']\n"; } } return summary; } public function writeTemporaryAllocationSummary(vertexShader : Boolean = true) : BitmapData { var allocations : Vector.<Allocation> = vertexShader ? _vsTmpAllocator.allocations : _fsTmpAllocator.allocations; var allocation : Allocation; var maxOpId : uint = 0; var maxOffset : uint = 0; for each (allocation in allocations) { if (allocation.endId > maxOpId) maxOpId = allocation.endId; if (allocation.offset + allocation.size > maxOffset) maxOffset = allocation.offset + allocation.size } var bitmapData : BitmapData = new BitmapData(FIELD_HEIGHT * maxOffset, FIELD_WIDTH * maxOpId, false, 0xFFFFFF); var textField : TextField = new TextField(); for each (allocation in allocations) { var rect : Rectangle = new Rectangle( allocation.offset * FIELD_HEIGHT, (allocation.beginId - 1) * FIELD_WIDTH, allocation.size * FIELD_HEIGHT, (allocation.endId - allocation.beginId) * FIELD_WIDTH ); bitmapData.fillRect(rect, Math.random() * 0x505050 + 0x909090); textField.text = AbstractOperation(allocation.node).instructionName; bitmapData.draw(textField, new Matrix(1, 0, 0, 1, rect.x, rect.y)); } var offsetId : uint; for (offsetId = 1; offsetId < maxOffset; offsetId += 1) bitmapData.fillRect(new Rectangle( offsetId * FIELD_HEIGHT, 0, 1, FIELD_WIDTH * maxOpId ), 0xBBBBBB); for (var operationId : uint = 1; operationId < maxOpId; ++operationId) bitmapData.fillRect(new Rectangle( 0, operationId * FIELD_WIDTH, maxOffset * FIELD_HEIGHT, 1 ), 0xBBBBBB); for (offsetId = 4; offsetId < maxOffset; offsetId += 4) bitmapData.fillRect(new Rectangle( offsetId * FIELD_HEIGHT, 0, 1, FIELD_WIDTH * maxOpId ), 0); return bitmapData; } } }
package aerys.minko.render.shader.compiler { import aerys.minko.render.shader.compiler.allocator.Allocation; import aerys.minko.render.shader.compiler.allocator.ParameterAllocation; import aerys.minko.render.shader.compiler.visitor.writer.WriteAgal; import aerys.minko.render.shader.compiler.visitor.writer.WriteDot; 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.shader.node.operation.AbstractOperation; import flash.display.BitmapData; import flash.geom.Matrix; import flash.geom.Rectangle; import flash.text.TextField; public class DebugCompiler extends Compiler { internal static const FIELD_WIDTH : uint = 20; internal static const FIELD_HEIGHT : uint = 25; public function DebugCompiler() { super(); } public function compileAgalVertexShader() : String { return new WriteAgal( _attrAllocator, _fsTmpAllocator, _varyingAllocator, _fsConstAllocator, _vsTmpAllocator, _vsConstAllocator ).processVertexShader(_vertexOps); } public function compileAgalFragmentShader() : String { return new WriteAgal( _attrAllocator, _fsTmpAllocator, _varyingAllocator, _fsConstAllocator, _vsTmpAllocator, _vsConstAllocator ).processFragmentShader(_colorNode); } public function writeDotGraph() : String { return new WriteDot().processShader(_clipspacePosNode, _colorNode); } public function writeConstantAllocationSummary(vertexShader : Boolean = true) : String { var offsetToLetter : Vector.<String> = Vector.<String>(['x', 'y', 'z', 'w']); var summary : String = ''; var allocationTable : Vector.<ParameterAllocation> = vertexShader ? _vsParams : _fsParams; var constantTable : Vector.<Number> = vertexShader ? _vsConstData : _fsConstData; var occupiedRegisters : uint = constantTable.length / 4; for (var registerId : uint = 0; registerId < occupiedRegisters; ++registerId) for (var offsetId : uint = 0; offsetId < 4; ++offsetId) { var foundInParameterTable : Boolean = false; for each (var allocation : ParameterAllocation in allocationTable) { if (allocation.offset == 4 * registerId + offsetId) { foundInParameterTable = true; summary += (vertexShader ? "vc" : "fc"); if (allocation.size < 4) { summary += registerId + '.'; for (var i : uint = allocation.offset % 4; i < allocation.offset % 4 + allocation.size && i < 4; ++i) summary += offsetToLetter[i]; } else if (allocation.size == 4) { summary += registerId; } else if (allocation.size == 16) { summary += '[' + registerId + '-' + (registerId + 3) + ']'; } var parameter : AbstractParameter = allocation.parameter; if (parameter is StyleParameter) { var styleParam : StyleParameter = parameter as StyleParameter; summary += "\t\tStyleParameter['" + styleParam.key + "']\n"; } else if (parameter is WorldParameter) { var worldParam : WorldParameter = parameter as WorldParameter; summary += "\t\tWorldParameter[class='" + worldParam.className + "', index='" + worldParam.index + "', field='" + worldParam.field + "']\n"; } else if (parameter is TransformParameter) { var transformParam : TransformParameter = parameter as TransformParameter; summary += "\t\tTransformParameter[key='" + transformParam.key + "']\n"; } break; } else if (allocation.offset < 4 * registerId + offsetId && allocation.offset + allocation.size > 4 * registerId + offsetId) { foundInParameterTable = true; break; } } if (!foundInParameterTable) { summary += (vertexShader ? "vc" : "fc") + registerId.toString() + '.' + offsetToLetter[offsetId] + "\t\tConstant[value='" + constantTable[4 * registerId + offsetId] + "']\n"; } } return summary; } public function writeTemporaryAllocationSummary(vertexShader : Boolean = true) : BitmapData { var allocations : Vector.<Allocation> = vertexShader ? _vsTmpAllocator.allocations : _fsTmpAllocator.allocations; var allocation : Allocation; var maxOpId : uint = 0; var maxOffset : uint = 0; for each (allocation in allocations) { if (allocation.endId > maxOpId) maxOpId = allocation.endId; if (allocation.offset + allocation.size > maxOffset) maxOffset = allocation.offset + allocation.size } var bitmapData : BitmapData = new BitmapData(FIELD_HEIGHT * maxOffset, FIELD_WIDTH * maxOpId, false, 0xFFFFFF); var textField : TextField = new TextField(); for each (allocation in allocations) { var rect : Rectangle = new Rectangle( allocation.offset * FIELD_HEIGHT, (allocation.beginId - 1) * FIELD_WIDTH, allocation.size * FIELD_HEIGHT, (allocation.endId - allocation.beginId) * FIELD_WIDTH ); bitmapData.fillRect(rect, Math.random() * 0x505050 + 0x909090); textField.text = AbstractOperation(allocation.node).instructionName; bitmapData.draw(textField, new Matrix(1, 0, 0, 1, rect.x, rect.y)); } var offsetId : uint; for (offsetId = 1; offsetId < maxOffset; offsetId += 1) bitmapData.fillRect(new Rectangle( offsetId * FIELD_HEIGHT, 0, 1, FIELD_WIDTH * maxOpId ), 0xBBBBBB); for (var operationId : uint = 1; operationId < maxOpId; ++operationId) bitmapData.fillRect(new Rectangle( 0, operationId * FIELD_WIDTH, maxOffset * FIELD_HEIGHT, 1 ), 0xBBBBBB); for (offsetId = 4; offsetId < maxOffset; offsetId += 4) bitmapData.fillRect(new Rectangle( offsetId * FIELD_HEIGHT, 0, 1, FIELD_WIDTH * maxOpId ), 0); return bitmapData; } } }
Fix bug in debug compiler when creating a constant allocation summary with 4 sized allocations
Fix bug in debug compiler when creating a constant allocation summary with 4 sized allocations
ActionScript
mit
aerys/minko-as3
7bb45cdf7203272b88d2361ce6d3fbb936dcd72c
src/aerys/minko/type/Signal.as
src/aerys/minko/type/Signal.as
package aerys.minko.type { public final class Signal { private var _name : String = null; private var _callbacks : Array = []; private var _numCallbacks : uint = 0; private var _executed : Boolean = false; private var _numAdded : uint = 0; private var _toAdd : Array = null; private var _numRemoved : uint = 0; private var _toRemove : Array = null; public function get numCallbacks() : uint { return _numCallbacks; } public function Signal(name : String) { _name = name; } public function add(callback : Function) : void { if (_executed) { if (_toAdd) _toAdd.push(callback); else _toAdd = [callback]; ++_numAdded; return ; } _callbacks[_numCallbacks] = callback; ++_numCallbacks; } public function remove(callback : Function) : void { if (_executed) { if (_toRemove) _toRemove.push(callback); else _toRemove = [callback]; ++_numRemoved; return ; } var index : int = _callbacks.indexOf(callback); if (index < 0) throw new Error('This callback does not exist.'); --_numCallbacks; _callbacks[index] = _callbacks[_numCallbacks]; _callbacks.length = _numCallbacks; } public function hasCallback(callback : Function) : Boolean { return _callbacks.indexOf(callback) >= 0; } public function execute(...params) : void { _executed = true; for (var i : uint = 0; i < _numCallbacks; ++i) (_callbacks[i] as Function).apply(null, params); _executed = false; for (i = 0; i < _numAdded; ++i) add(_toAdd[i]); _numAdded = 0; _toAdd = null; for (i = 0; i < _numRemoved; ++i) remove(_toRemove[i]); _numRemoved = 0; _toRemove = null; } } }
package aerys.minko.type { public final class Signal { private var _name : String = null; private var _callbacks : Array = []; private var _numCallbacks : uint = 0; private var _executed : Boolean = false; private var _numAdded : uint = 0; private var _toAdd : Array = null; private var _numRemoved : uint = 0; private var _toRemove : Array = null; public function get numCallbacks() : uint { return _numCallbacks; } public function Signal(name : String) { _name = name; } public function add(callback : Function) : void { if (_executed) { if (_toAdd) _toAdd.push(callback); else _toAdd = [callback]; ++_numAdded; return ; } _callbacks[_numCallbacks] = callback; ++_numCallbacks; } public function remove(callback : Function) : void { var index : int = _callbacks.indexOf(callback); if (index < 0) throw new Error('This callback does not exist.'); if (_executed) { if (_toRemove) _toRemove.push(callback); else _toRemove = [callback]; ++_numRemoved; return ; } --_numCallbacks; _callbacks[index] = _callbacks[_numCallbacks]; _callbacks.length = _numCallbacks; } public function hasCallback(callback : Function) : Boolean { return _callbacks.indexOf(callback) >= 0; } public function execute(...params) : void { _executed = true; for (var i : uint = 0; i < _numCallbacks; ++i) (_callbacks[i] as Function).apply(null, params); _executed = false; for (i = 0; i < _numAdded; ++i) add(_toAdd[i]); _numAdded = 0; _toAdd = null; for (i = 0; i < _numRemoved; ++i) remove(_toRemove[i]); _numRemoved = 0; _toRemove = null; } } }
check the callack actually exists at the begining of Signal.removeCallback()
check the callack actually exists at the begining of Signal.removeCallback()
ActionScript
mit
aerys/minko-as3
7445596fc42ff05ad4a37f84329c903afbfbff1c
Arguments/src/logic/ModusPonens.as
Arguments/src/logic/ModusPonens.as
package logic { /** AGORA - an interactive and web-based argument mapping tool that stimulates reasoning, reflection, critique, deliberation, and creativity in individual argument construction and in collaborative or adversarial settings. Copyright (C) 2011 Georgia Institute of Technology This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import classes.ArgumentPanel; import components.ArgSelector; import mx.controls.Alert; import mx.messaging.channels.StreamingAMFChannel; public class ModusPonens extends ParentArg { public function ModusPonens() { _langTypes = ["If-then","Implies","Whenever","Only if","Provided that","Sufficient condition","Necessary condition"]; dbLangTypeNames = ["ifthen","implies","whenever","onlyif","providedthat","sufficient","necessary"]; _expLangTypes = ["If-then","Whenever","Provided that"]; myname = MOD_PON; _dbType = "MP"; } override public function getLanguageType(dbString:String):String { for(var i:int=0;i<dbLangTypeNames.length;i++) { if(dbString.indexOf(dbLangTypeNames[i]) >= 0) { return _langTypes[i]; } } return ""; } override public function createLinks():void { if(inference.claim.inference != null && inference.claim.statementNegated) { Alert.show("Error: Statement cannot be negative"); } //make claim and reason un-multiStatement if(inference.claim.multiStatement) { inference.claim.multiStatement = false; } for(var i:int=0; i < inference.reasons.length; i++) { if(inference.reasons[i].multiStatement) { inference.reasons[i].multiStatement = false; } } trace('claim user entered value:'+inference.claim.userEntered); if(inference.claim.userEntered == false && inference.claim.inference == null && inference.claim.rules.length < 2) { inference.claim.input1.text = "P"; inference.reasons[0].input1.text = "Q"; //make them uneditable. It automatically //sets the displayTxt Text control inference.claim.makeUnEditable(); inference.reasons[0].makeUnEditable(); } //claim and reasons should not be negated if(inference.claim.statementNegated) { inference.claim.statementNegated = false; } for(i=0; i < inference.reasons.length; i++) { if(inference.reasons[i].statementNegated) { inference.reasons[i].statementNegated = false; } } inference.implies = true; super.createLinks(); } override public function correctUsage():String { var output:String = ""; var reason:Vector.<ArgumentPanel> = inference.reasons; var claim:ArgumentPanel = inference.claim; var i:int; var reasonStr:String; switch(inference.myschemeSel.selectedType) { case _langTypes[0]: reasonStr = ""; output += "If " for(i=0; i < reason.length - 1; i++) { output += reason[i].stmt + " and if "; reasonStr = reasonStr + reason[i].stmt + " and if "; } output += reason[i].stmt + ", then " + claim.stmt; reasonStr = reasonStr + reason[i].stmt; inference.inputs[1].text = reasonStr; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[1]: // Implies output += reason[0].stmt + " implies " + claim.stmt; inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[2]: //Whenever reasonStr = ""; output += "Whenever " for(i=0;i<reason.length-1;i++) { output += reason[i].stmt + " and "; reasonStr += reason[i].stmt + " and "; } output += reason[i].stmt + ", "+ claim.stmt; reasonStr = reasonStr + reason[i].stmt; inference.inputs[1].text = reasonStr; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[3]: // Only if output += reason[0].stmt + " only if " + claim.stmt; inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[4]: // Provided that reasonStr = ""; output += claim.stmt + " provided that "; for(i=0;i<reason.length-1;i++) { output += reason[i].stmt + " and "; reasonStr += reason[i].stmt + " and "; } output += reason[i].stmt; reasonStr = reasonStr + reason[i].stmt; inference.inputs[1].text = reasonStr; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[5]: // Sufficient condition output += reason[0].stmt + " is a sufficient condition for " + claim.stmt; inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[6]: // Necessary condition output += claim.stmt + " is a necessary condition for " + reason[0].stmt; inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[7]: //If and only if output += claim.stmt + " if and only if " + reason[0].stmt; // IMP!! TODO: if-and-only-if2 : both claim and reason negated inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[8]: //Necessary and sufficient condition output += claim.stmt + " is a necessary and sufficient condition for " + reason[0].stmt; inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt;// TODO: Necessary-and-sufficient2 : both claim and reason negated inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[9]: //Equivalent output += claim.stmt + " and " + reason[0].stmt + " are equivalent"; // TODO: Equivalent2 : both claim and reason negated inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); } return output; } } }
package logic { /** AGORA - an interactive and web-based argument mapping tool that stimulates reasoning, reflection, critique, deliberation, and creativity in individual argument construction and in collaborative or adversarial settings. Copyright (C) 2011 Georgia Institute of Technology This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import classes.ArgumentPanel; import components.ArgSelector; import mx.controls.Alert; import mx.messaging.channels.StreamingAMFChannel; public class ModusPonens extends ParentArg { public function ModusPonens() { _langTypes = ["If-then","Implies","Whenever","Only if","Provided that","Sufficient condition","Necessary condition"]; dbLangTypeNames = ["ifthen","implies","whenever","onlyif","providedthat","sufficient","necessary"]; _expLangTypes = ["If-then","Whenever","Provided that"]; myname = MOD_PON; _dbType = "MP"; } override public function getLanguageType(dbString:String):String { for(var i:int=0;i<dbLangTypeNames.length;i++) { if(dbString.indexOf(dbLangTypeNames[i]) >= 0) { return _langTypes[i]; } } return ""; } override public function createLinks():void { if(inference.claim.inference != null && inference.claim.statementNegated) { Alert.show("Error: Statement cannot be negative"); } //make claim and reason un-multiStatement if(inference.claim.multiStatement) { inference.claim.multiStatement = false; } for(var i:int=0; i < inference.reasons.length; i++) { if(inference.reasons[i].multiStatement) { inference.reasons[i].multiStatement = false; } } trace('claim user entered value:'+inference.claim.userEntered); if(inference.claim.userEntered == false && inference.claim.inference == null && inference.claim.rules.length < 2) { inference.claim.input1.text = "P"; inference.reasons[0].input1.text = "Q"; //make them uneditable. It automatically //sets the displayTxt Text control inference.claim.makeUnEditable(); inference.reasons[0].makeUnEditable(); } //claim and reasons should not be negated if(inference.claim.statementNegated) { inference.claim.statementNegated = false; } for(i=0; i < inference.reasons.length; i++) { if(inference.reasons[i].statementNegated) { inference.reasons[i].statementNegated = false; } } inference.implies = true; super.createLinks(); } override public function correctUsage():String { var output:String = ""; var reason:Vector.<ArgumentPanel> = inference.reasons; var claim:ArgumentPanel = inference.claim; var i:int; var reasonStr:String; switch(inference.myschemeSel.selectedType) { case _langTypes[0]: reasonStr = ""; output += "If "; for(i=0; i < reason.length - 1; i++) { output += reason[i].stmt + " and if "; reasonStr = reasonStr + reason[i].stmt + " and if "; } output += reason[i].stmt + ", then " + claim.stmt; reasonStr = reasonStr + reason[i].stmt; inference.inputs[1].text = reasonStr; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[1]: // Implies output += reason[0].stmt + " implies " + claim.stmt; inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[2]: //Whenever reasonStr = ""; output += "Whenever " for(i=0;i<reason.length-1;i++) { output += reason[i].stmt + " and "; reasonStr += reason[i].stmt + " and "; } output += reason[i].stmt + ", "+ claim.stmt; reasonStr = reasonStr + reason[i].stmt; inference.inputs[1].text = reasonStr; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[3]: // Only if output += reason[0].stmt + " only if " + claim.stmt; inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[4]: // Provided that reasonStr = ""; output += claim.stmt + " provided that "; for(i=0;i<reason.length-1;i++) { output += reason[i].stmt + " and "; reasonStr += reason[i].stmt + " and "; } output += reason[i].stmt; reasonStr = reasonStr + reason[i].stmt; inference.inputs[1].text = reasonStr; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[5]: // Sufficient condition output += reason[0].stmt + " is a sufficient condition for " + claim.stmt; inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[6]: // Necessary condition output += claim.stmt + " is a necessary condition for " + reason[0].stmt; inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[7]: //If and only if output += claim.stmt + " if and only if " + reason[0].stmt; // IMP!! TODO: if-and-only-if2 : both claim and reason negated inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[8]: //Necessary and sufficient condition output += claim.stmt + " is a necessary and sufficient condition for " + reason[0].stmt; inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt;// TODO: Necessary-and-sufficient2 : both claim and reason negated inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); break; case _langTypes[9]: //Equivalent output += claim.stmt + " and " + reason[0].stmt + " are equivalent"; // TODO: Equivalent2 : both claim and reason negated inference.inputs[1].text = reason[0].stmt; inference.inputs[0].text = claim.stmt; inference.inputs[0].forwardUpdate(); inference.inputs[1].forwardUpdate(); } return output; } } }
Fix obvious semicolon error
Fix obvious semicolon error
ActionScript
agpl-3.0
mbjornas3/AGORA,mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA
b7ffc487535ea54e7536eef5b8dbcb56ecb45d92
src/MorningStroll.as
src/MorningStroll.as
package { import flash.text.TextField; import org.flixel.FlxG; import org.flixel.FlxGame; import org.flixel.FlxU; [SWF(width=416, height=600, backgroundColor="#000000")] [Frame(factoryClass="Preloader")] // Custom FlxGame extensions. public class MorningStroll extends FlxGame { public function MorningStroll() { super(416, 600, MenuState, 1, 24, 24); } override protected function createFocusScreen():void { // Draw transparent black backdrop. // From Flixel. this._focus.graphics.moveTo(0, 0); this._focus.graphics.beginFill(0, 0.8); this._focus.graphics.lineTo(FlxG.width, 0); this._focus.graphics.lineTo(FlxG.width, FlxG.height); this._focus.graphics.lineTo(0, FlxG.height); this._focus.graphics.lineTo(0, 0); this._focus.graphics.endFill(); var pauseTitle:TextField = new Text(0, 0, FlxG.width, "Paused", Text.H1).getTextField(); var quitText:TextField = new Text(0, 0, FlxG.width, "Press Q to quit").getTextField(); pauseTitle.y = Text.BASELINE * 6; quitText.y = pauseTitle.y + Text.BASELINE * 2; this._focus.addChild(pauseTitle); this._focus.addChild(quitText); addChild(this._focus); } public static function endGame():void { FlxG.fade(0xff000000, 1, function():void { FlxG.resetGame(); }); } } }
package { import flash.text.TextField; import org.flixel.FlxG; import org.flixel.FlxGame; import org.flixel.FlxU; [SWF(width=416, height=600, backgroundColor="#000000")] [Frame(factoryClass="Preloader")] // Custom FlxGame extensions. public class MorningStroll extends FlxGame { public function MorningStroll() { super(416, 600, MenuState, 1, 24, 24); } override protected function createFocusScreen():void { // Draw transparent black backdrop. // From Flixel. this._focus.graphics.moveTo(0, 0); this._focus.graphics.beginFill(0, 0.8); this._focus.graphics.lineTo(FlxG.width, 0); this._focus.graphics.lineTo(FlxG.width, FlxG.height); this._focus.graphics.lineTo(0, FlxG.height); this._focus.graphics.lineTo(0, 0); this._focus.graphics.endFill(); var pauseTitle:TextField = new Text(0, 0, FlxG.width, "Paused", Text.H1).getTextField(); var instructions:TextField = new Text(0, 0, FlxG.width, [ "Arrow keys to move", "Press Q to quit", "Press 0, -, + for volume" ].join("\n\n")).getTextField(); pauseTitle.y = Text.BASELINE * 6; instructions.y = pauseTitle.y + Text.BASELINE * 2; this._focus.addChild(pauseTitle); this._focus.addChild(instructions); addChild(this._focus); } public static function endGame():void { FlxG.fade(0xff000000, 1, function():void { FlxG.resetGame(); }); } } }
Update instructions on pause screen.
Update instructions on pause screen.
ActionScript
artistic-2.0
hlfcoding/morning-stroll
25932820c8ec3316a6569ed4fd5cbb1f6496f5e3
assets/scripts/character_states/stand.as
assets/scripts/character_states/stand.as
void enter(entity_impl& out owner) { owner.get_animation_component().play_ani("stand"); } void update(float delta_time, entity_impl& out owner) { } void leave(entity_impl& out owner) { }
void enter(entity_impl& out owner) { owner.get_animation_component().play_ani("stand"); owner.get_character_physics_component().velocity(0); owner.get_character_physics_component().angular_velocity(0); } void update(float delta_time, entity_impl& out owner) { } void leave(entity_impl& out owner) { }
set velocity to zero in 'stand'-states enter function.
set velocity to zero in 'stand'-states enter function.
ActionScript
mit
kasoki/project-zombye,kasoki/project-zombye,kasoki/project-zombye
ba3be6f30e19d58eb058a8c5c429ba5ffbc51f4e
Arguments/src/Controller/logic/NotAllSyllogism.as
Arguments/src/Controller/logic/NotAllSyllogism.as
package Controller.logic { import Model.AGORAModel; import Model.ArgumentTypeModel; import Model.InferenceModel; import Model.SimpleStatementModel; import Model.StatementModel; import ValueObjects.AGORAParameters; import components.ArgSelector; import components.ArgumentPanel; import components.MenuPanel; import mx.controls.Alert; import mx.core.FlexGlobals; public class NotAllSyllogism extends ParentArg { private static var instance:NotAllSyllogism; public function NotAllSyllogism() { label = AGORAParameters.getInstance().NOT_ALL_SYLL; } public static function getInstance():NotAllSyllogism{ if(instance==null){ instance = new NotAllSyllogism; } return instance; } override public function formText(argumentTypeModel:ArgumentTypeModel):void{ var output:String = ""; var reasonText:String = ""; var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels; var claimModel:StatementModel = argumentTypeModel.claimModel; var argSelector:ArgSelector = MenuPanel(FlexGlobals.topLevelApplication.map.agoraMap.menuPanelsHash[argumentTypeModel.ID]).schemeSelector; var i:int; output = "It cannot be the case, at the same time, that "; for(i=0; i<reasonModels.length; i++){ reasonText = reasonText + reasonModels[i].statement.text + " and that "; argumentTypeModel.inferenceModel.statements[i+1].text = reasonModels[i].statement.text; } output = output + reasonText + claimModel.statement.positiveText; argumentTypeModel.inferenceModel.statements[0].text = claimModel.statement.text; argumentTypeModel.inferenceModel.statement.text = output; } override public function deleteLinks(argumentTypeModel:ArgumentTypeModel):void{ var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels; var claimModel:StatementModel = argumentTypeModel.claimModel; var inferenceModel:StatementModel = argumentTypeModel.inferenceModel; //remove negativity from the inference inferenceModel.negated = false; //if first claim's argument, remove //negativity from the claim if(claimModel.firstClaim){ claimModel.negated = false; } //remove links from claim to the inference's statement var simpleStatement:SimpleStatementModel; var statementTobeUnLinked:SimpleStatementModel; simpleStatement = claimModel.statement; statementTobeUnLinked = inferenceModel.statements[0]; removeDependence(simpleStatement, statementTobeUnLinked); if(reasonModels.length > 1){ trace("NotAllSyllogism::deleteLinks: This should not be occuring."); } //remove links from reasons to the inference's statement simpleStatement = reasonModels[0].statement; statementTobeUnLinked = inferenceModel.statements[1]; removeDependence(simpleStatement, statementTobeUnLinked); //delete the unnecessary statements in the infernece //but this is not required as the scheme could be changed //only when there is one reason. If there is only one reasons //the number of statements in the inference is going to be //only two, which is the default. } override public function link(argumentTypeModel:ArgumentTypeModel):void{ var claimModel:StatementModel = argumentTypeModel.claimModel; var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels; var inferenceModel:StatementModel = argumentTypeModel.inferenceModel; //inference is a disjunction inferenceModel.connectingString = StatementModel.DISJUNCTION; //if first claim, change it to negative if(claimModel.firstClaim){ claimModel.negated = true; } //connect the claim's statement to the inference's first statement //claimModel.statement.forwardList.push(inferenceModel.statements[0]); claimModel.statement.addDependentStatement(inferenceModel.statements[0]); //connect the reason's statement to the infernece's second statement //reasonModels[0].statement.forwardList.push(inferenceModel.statements[1]); for(var i:int=0; i<reasonModels.length; i++){ reasonModels[i].statement.addDependentStatement(inferenceModel.statements[i+1]); } } /* override public function get dbType():String { return _dbType; } override public function getLanguageType(dbString:String):String{ return _langTypes[0]; } override public function createLinks():void { if(inference.claim.inference != null && !inference.claim.statementNegated) { Alert.show("Error: Statement cannot be positive"); } if(inference.claim.multiStatement) { inference.claim.multiStatement = false; } for(var i:int=0; i < inference.reasons.length; i++) { if(inference.reasons[i].multiStatement) { inference.reasons[i].multiStatement = false; } } if(inference.claim.userEntered == false && inference.claim.inference == null && inference.claim.rules.length < 2) { inference.claim.input1.text = "P"; inference.claim.makeUnEditable(); inference.reasons[0].input1.text = "Q"; inference.reasons[0].makeUnEditable(); } if(!inference.claim.statementNegated) { inference.claim.statementNegated = true; } for(i=0; i < inference.reasons.length; i++) { if(inference.reasons[i].statementNegated) { inference.reasons[i].statementNegated = false; } } inference.implies = false; super.createLinks(); } override public function correctUsage():String { var output:String = ""; var reasonStr:String; var i:int; output += "It cannot be the case, at the same time, that "; for(i=0;i<inference.reasons.length;i++) { output += inference.reasons[i].stmt + " and that "; //inference.inputs[i+1].text = inference.reasons[i].stmt; //inference.inputs[i+1].forwardUpdate(); } output += inference.claim.positiveStmt; //inference.inputs[0].text = inference.claim.positiveStmt; //inference.inputs[0].forwardUpdate(); return output; } */ } }
package Controller.logic { import Model.AGORAModel; import Model.ArgumentTypeModel; import Model.InferenceModel; import Model.SimpleStatementModel; import Model.StatementModel; import ValueObjects.AGORAParameters; import components.ArgSelector; import components.ArgumentPanel; import components.MenuPanel; import mx.controls.Alert; import mx.core.FlexGlobals; public class NotAllSyllogism extends ParentArg { private static var instance:NotAllSyllogism; public function NotAllSyllogism() { label = AGORAParameters.getInstance().NOT_ALL_SYLL; } public static function getInstance():NotAllSyllogism{ if(instance==null){ instance = new NotAllSyllogism; } return instance; } override public function formText(argumentTypeModel:ArgumentTypeModel):void{ var output:String = ""; var reasonText:String = ""; var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels; var claimModel:StatementModel = argumentTypeModel.claimModel; var argSelector:ArgSelector = MenuPanel(FlexGlobals.topLevelApplication.map.agoraMap.menuPanelsHash[argumentTypeModel.ID]).schemeSelector; var i:int; output = "It cannot be the case, at the same time, that "; for(i=0; i<reasonModels.length; i++){ reasonText = reasonText + reasonModels[i].statement.text + " and that "; argumentTypeModel.inferenceModel.statements[i+1].text = reasonModels[i].statement.text; } output = output + reasonText + claimModel.statement.positiveText; argumentTypeModel.inferenceModel.statements[0].text = claimModel.statement.text; argumentTypeModel.inferenceModel.statement.text = output; } override public function deleteLinks(argumentTypeModel:ArgumentTypeModel):void{ var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels; var claimModel:StatementModel = argumentTypeModel.claimModel; var inferenceModel:StatementModel = argumentTypeModel.inferenceModel; //remove negativity from the inference inferenceModel.negated = false; //if first claim's argument, remove //negativity from the claim if(claimModel.firstClaim){ claimModel.negated = false; } //remove links from claim to the inference's statement var simpleStatement:SimpleStatementModel; var statementTobeUnLinked:SimpleStatementModel; simpleStatement = claimModel.statement; statementTobeUnLinked = inferenceModel.statements[0]; removeDependence(simpleStatement, statementTobeUnLinked); if(reasonModels.length > 1){ trace("NotAllSyllogism::deleteLinks: This should not be occuring."); } //remove links from reasons to the inference's statement simpleStatement = reasonModels[0].statement; statementTobeUnLinked = inferenceModel.statements[1]; removeDependence(simpleStatement, statementTobeUnLinked); //delete the unnecessary statements in the infernece //but this is not required as the scheme could be changed //only when there is one reason. If there is only one reasons //the number of statements in the inference is going to be //only two, which is the default. } override public function link(argumentTypeModel:ArgumentTypeModel):void{ var claimModel:StatementModel = argumentTypeModel.claimModel; var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels; var inferenceModel:StatementModel = argumentTypeModel.inferenceModel; //inference is a disjunction inferenceModel.connectingString = StatementModel.DISJUNCTION; //if first claim, change it to negative if(claimModel.firstClaim){ claimModel.negated = true; } //connect the claim's statement to the inference's first statement //claimModel.statement.forwardList.push(inferenceModel.statements[0]); claimModel.statement.addDependentStatement(inferenceModel.statements[0]); //connect the reason's statement to the infernece's second statement //reasonModels[0].statement.forwardList.push(inferenceModel.statements[1]); for(var i:int=0; i<reasonModels.length; i++){ reasonModels[i].statement.addDependentStatement(inferenceModel.statements[i+1]); } } } }
clean up
clean up
ActionScript
agpl-3.0
MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA,mbjornas3/AGORA
21e7e214748cbe2a1b6c87d5b9eacb76b4eb9f5e
project/PinkPlayer/src/com/fenhongxiang/cue/CuePoint.as
project/PinkPlayer/src/com/fenhongxiang/cue/CuePoint.as
//------------------------------------------------------------------------------ // // Copyright 2016 www.fenhongxiang.com // All rights reserved. // By :ljh // //------------------------------------------------------------------------------ package com.fenhongxiang.cue { import com.fenhongxiang.event.FResizeEvent; import com.fenhongxiang.view.FSprite; import flash.events.MouseEvent; public class CuePoint extends FSprite { public function CuePoint() { this.buttonMode = true; this.useHandCursor = true; border = false; backgroudColor = 0xA6A6A6; resize(3, 10); addEventListeners(); } private var _container:FSprite; private var _data:CueData; public function get data():CueData { return _data; } public function set toogleTip(value:Function):void { _toogleTip = value; } private var _toogleTip:Function; public function set container(value:FSprite):void { _container = value; if (_container != null) { _container.addEventListener(FResizeEvent.SIZE_CHANGE, onContainerResize, false, 0, true); this.x = (_data == null ? 0 : _data.pos * _container.width) + _container.x; this.y = 0; this.height = _container.height; _container.addChild(this); } } private function onContainerResize(e:FResizeEvent):void { this.x = (_data == null ? 0 : _data.pos * _container.width) + _container.x; this.y = 0; this.height = _container.height; } public function set data(value:CueData):void { _data = value; } private function addEventListeners():void { this.addEventListener(MouseEvent.MOUSE_OUT, hideTip, false, 0, true); this.addEventListener(MouseEvent.MOUSE_OVER, showTip, false, 0, true); } private function hideTip(e:MouseEvent):void { backgroudColor = 0xA6A6A6; if(_toogleTip != null) { _toogleTip(null); } } private function showTip(e:MouseEvent):void { backgroudColor = 0xFF0000; if(_toogleTip != null) { _toogleTip(this); } } } }
//------------------------------------------------------------------------------ // // Copyright 2016 www.fenhongxiang.com // All rights reserved. // By :ljh // //------------------------------------------------------------------------------ package com.fenhongxiang.cue { import com.fenhongxiang.event.FResizeEvent; import com.fenhongxiang.view.FSprite; import flash.events.MouseEvent; public class CuePoint extends FSprite { public function CuePoint() { this.buttonMode = true; this.useHandCursor = true; border = false; backgroudColor = 0xffb81d; resize(3, 10); addEventListeners(); } private var _container:FSprite; private var _data:CueData; public function get data():CueData { return _data; } public function set toogleTip(value:Function):void { _toogleTip = value; } private var _toogleTip:Function; public function set container(value:FSprite):void { _container = value; if (_container != null) { _container.addEventListener(FResizeEvent.SIZE_CHANGE, onContainerResize, false, 0, true); this.x = (_data == null ? 0 : _data.pos * _container.width) + _container.x; this.y = 0; this.height = _container.height; _container.addChild(this); } } private function onContainerResize(e:FResizeEvent):void { this.x = (_data == null ? 0 : _data.pos * _container.width) + _container.x; this.y = 0; this.height = _container.height; } public function set data(value:CueData):void { _data = value; } private function addEventListeners():void { this.addEventListener(MouseEvent.MOUSE_OUT, hideTip, false, 0, true); this.addEventListener(MouseEvent.MOUSE_OVER, showTip, false, 0, true); } private function hideTip(e:MouseEvent):void { backgroudColor = 0xffb81d; if(_toogleTip != null) { _toogleTip(null); } } private function showTip(e:MouseEvent):void { backgroudColor = 0xffaf00; if(_toogleTip != null) { _toogleTip(this); } } } }
update style
update style
ActionScript
mit
luojianghong/HLSPlayer,luojianghong/HLSPlayer
cc3976a213e597aa1a858617ddc39859315c9e2a
src/as/com/threerings/ezgame/client/EZGameController.as
src/as/com/threerings/ezgame/client/EZGameController.as
// // $Id$ // // Vilya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/vilya/ // // 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.ezgame.client { import flash.events.Event; import com.threerings.util.Name; import com.threerings.presents.dobj.AttributeChangedEvent; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.parlor.game.client.GameController; import com.threerings.parlor.game.data.GameObject; import com.threerings.parlor.turn.client.TurnGameController; import com.threerings.parlor.turn.client.TurnGameControllerDelegate; import com.threerings.ezgame.data.EZGameObject; /** * A controller for flash games. */ public class EZGameController extends GameController implements TurnGameController { public function EZGameController () { addDelegate(_turnDelegate = new TurnGameControllerDelegate(this)); } /** * This is called by the GameControlBackend once it has initialized and made contact with * usercode. */ public function userCodeIsConnected (autoReady :Boolean) :void { if (autoReady) { playerIsReady(); } } /** * Called by the GameControlBackend when the game is ready to start. If the game has ended, * this can be called by all clients to start the game anew. */ public function playerIsReady () :void { playerReady(); } // from PlaceController override public function willEnterPlace (plobj :PlaceObject) :void { _ezObj = (plobj as EZGameObject); super.willEnterPlace(plobj); } // from PlaceController override public function didLeavePlace (plobj :PlaceObject) :void { super.didLeavePlace(plobj); _ezObj = null; } // from TurnGameController public function turnDidChange (turnHolder :Name) :void { _panel.backend.turnDidChange(); } // from GameController override public function attributeChanged (event :AttributeChangedEvent) :void { var name :String = event.getName(); if (EZGameObject.CONTROLLER_OID == name) { _panel.backend.controlDidChange(); } else if (GameObject.ROUND_ID == name) { if ((event.getValue() as int) > 0) { _panel.backend.roundStateChanged(true); } else { _panel.backend.roundStateChanged(false); } } else { super.attributeChanged(event); } } // from GameController override protected function playerReady () :void { // we require the user to be connected, and we redundantly only do this if the user is in // the players array if (_panel.backend.isConnected()) { var bobj :BodyObject = (_ctx.getClient().getClientObject() as BodyObject); if (_gobj.getPlayerIndex(bobj.getVisibleName()) != -1) { super.playerReady(); } } else { log.debug("Waiting to call playerReady, userCode not yet connected."); } } // from GameController override protected function gameDidStart () :void { super.gameDidStart(); _panel.backend.gameStateChanged(true); } // from GameController override protected function gameDidEnd () :void { super.gameDidEnd(); _panel.backend.gameStateChanged(false); } // from PlaceController override protected function createPlaceView (ctx :CrowdContext) :PlaceView { return new EZGamePanel(ctx, this); } // from PlaceController override protected function didInit () :void { super.didInit(); // we can't just assign _panel in createPlaceView() for some exciting reason _panel = (_view as EZGamePanel); } protected var _ezObj :EZGameObject; protected var _turnDelegate :TurnGameControllerDelegate; protected var _panel :EZGamePanel; } }
// // $Id$ // // Vilya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/vilya/ // // 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.ezgame.client { import flash.events.Event; import com.threerings.util.Name; import com.threerings.presents.dobj.AttributeChangedEvent; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.parlor.game.client.GameController; import com.threerings.parlor.game.data.GameObject; import com.threerings.parlor.turn.client.TurnGameController; import com.threerings.parlor.turn.client.TurnGameControllerDelegate; import com.threerings.ezgame.data.EZGameObject; /** * A controller for flash games. */ public class EZGameController extends GameController implements TurnGameController { public function EZGameController () { addDelegate(_turnDelegate = new TurnGameControllerDelegate(this)); } /** * This is called by the GameControlBackend once it has initialized and made contact with * usercode. */ public function userCodeIsConnected (autoReady :Boolean) :void { if (autoReady) { // let the game manager know that we're here and we want to start the game now playerIsReady(); } else { // let the game manager know that we're here even though we don't want the game to // start yet _gobj.manager.invoke("playerInRoom"); } } /** * Called by the GameControlBackend when the game is ready to start. If the game has ended, * this can be called by all clients to start the game anew. */ public function playerIsReady () :void { playerReady(); } // from PlaceController override public function willEnterPlace (plobj :PlaceObject) :void { _ezObj = (plobj as EZGameObject); super.willEnterPlace(plobj); } // from PlaceController override public function didLeavePlace (plobj :PlaceObject) :void { super.didLeavePlace(plobj); _ezObj = null; } // from TurnGameController public function turnDidChange (turnHolder :Name) :void { _panel.backend.turnDidChange(); } // from GameController override public function attributeChanged (event :AttributeChangedEvent) :void { var name :String = event.getName(); if (EZGameObject.CONTROLLER_OID == name) { _panel.backend.controlDidChange(); } else if (GameObject.ROUND_ID == name) { if ((event.getValue() as int) > 0) { _panel.backend.roundStateChanged(true); } else { _panel.backend.roundStateChanged(false); } } else { super.attributeChanged(event); } } // from GameController override protected function playerReady () :void { // we require the user to be connected, and we redundantly only do this if the user is in // the players array if (_panel.backend.isConnected()) { var bobj :BodyObject = (_ctx.getClient().getClientObject() as BodyObject); if (_gobj.getPlayerIndex(bobj.getVisibleName()) != -1) { super.playerReady(); } } else { log.debug("Waiting to call playerReady, userCode not yet connected."); } } // from GameController override protected function gameDidStart () :void { super.gameDidStart(); _panel.backend.gameStateChanged(true); } // from GameController override protected function gameDidEnd () :void { super.gameDidEnd(); _panel.backend.gameStateChanged(false); } // from PlaceController override protected function createPlaceView (ctx :CrowdContext) :PlaceView { return new EZGamePanel(ctx, this); } // from PlaceController override protected function didInit () :void { super.didInit(); // we can't just assign _panel in createPlaceView() for some exciting reason _panel = (_view as EZGamePanel); } protected var _ezObj :EZGameObject; protected var _turnDelegate :TurnGameControllerDelegate; protected var _panel :EZGamePanel; } }
Use playerInRoom() to let the game manager know we've arrived but aren't ready to start the game yet.
Use playerInRoom() to let the game manager know we've arrived but aren't ready to start the game yet. git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@419 c613c5cb-e716-0410-b11b-feb51c14d237
ActionScript
lgpl-2.1
threerings/vilya,threerings/vilya
3e220b05c270eaf33518a92fb36005e1665edf14
as3/smartform/src/com/rpath/raf/util/LifecycleObject.as
as3/smartform/src/com/rpath/raf/util/LifecycleObject.as
/* # # Copyright (c) 2008-2010 rPath, Inc. # # This program is distributed under the terms of the MIT License as found # in a file called LICENSE. If it is not present, the license # is always available at http://www.opensource.org/licenses/mit-license.php. # # This program is distributed in the hope that it will be useful, but # without any warranty; without even the implied warranty of merchantability # or fitness for a particular purpose. See the MIT License for full details. */ package com.rpath.raf.util { import flash.utils.Dictionary; import mx.core.FlexGlobals; public class LifecycleObject { public function LifecycleObject() { super(); } // INVALIDATION AND COMMITPROPERTIES PATTERN private var invalidatePropertiesFlag:Boolean; public function invalidateProperties():void { if (!invalidatePropertiesFlag) { invalidatePropertiesFlag = true; invalidateObject(this); } } protected function commitProperties():void { // override this } // -- INVALIDATION SUPPORT private static var invalidObjects:Dictionary = new Dictionary(true); private static var validatePending:Boolean = false; public static function invalidateObject(obj:LifecycleObject):void { invalidObjects[obj] = true; if (!validatePending) { validatePending = true; FlexGlobals.topLevelApplication.callLater(validateObjects); } } protected static function validateObjects():void { var invalidQueue:Dictionary = invalidObjects; // start a fresh tracker for further invalidations // that are a side effect of this pass invalidObjects = new Dictionary(true); // ready to receive another call validatePending = false; for (var o:* in invalidQueue) { var rm:LifecycleObject = o as LifecycleObject; if (rm) { // clear the flag first, in case we're reentrant // on any given instance rm.invalidatePropertiesFlag = false; rm.commitProperties(); } } } } }
/* # # Copyright (c) 2008-2010 rPath, Inc. # # This program is distributed under the terms of the MIT License as found # in a file called LICENSE. If it is not present, the license # is always available at http://www.opensource.org/licenses/mit-license.php. # # This program is distributed in the hope that it will be useful, but # without any warranty; without even the implied warranty of merchantability # or fitness for a particular purpose. See the MIT License for full details. */ package com.rpath.raf.util { import flash.utils.Dictionary; import mx.core.FlexGlobals; import flash.events.EventDispatcher; public class LifecycleObject extends EventDispatcher { public function LifecycleObject() { super(); } // INVALIDATION AND COMMITPROPERTIES PATTERN private var invalidatePropertiesFlag:Boolean; public function invalidateProperties():void { if (!invalidatePropertiesFlag) { invalidatePropertiesFlag = true; invalidateObject(this); } } protected function commitProperties():void { // override this } // -- INVALIDATION SUPPORT private static var invalidObjects:Dictionary = new Dictionary(true); private static var validatePending:Boolean = false; public static function invalidateObject(obj:LifecycleObject):void { invalidObjects[obj] = true; if (!validatePending) { validatePending = true; FlexGlobals.topLevelApplication.callLater(validateObjects); } } protected static function validateObjects():void { var invalidQueue:Dictionary = invalidObjects; // start a fresh tracker for further invalidations // that are a side effect of this pass invalidObjects = new Dictionary(true); // ready to receive another call validatePending = false; for (var o:* in invalidQueue) { var rm:LifecycleObject = o as LifecycleObject; if (rm) { // clear the flag first, in case we're reentrant // on any given instance rm.invalidatePropertiesFlag = false; rm.commitProperties(); } } } } }
Make LifeCycleObject subclass of EventDispatcher
Make LifeCycleObject subclass of EventDispatcher
ActionScript
apache-2.0
sassoftware/smartform
41ea9389ae9e00157404174abbf3f3d47a0fc288
src/com/phylake/fsm/impl/Fsm.as
src/com/phylake/fsm/impl/Fsm.as
package com.phylake.fsm.impl { import com.phylake.fsm.core.*; import flash.errors.IllegalOperationError; import flash.utils.Dictionary; public class Fsm implements IFsm { private var _events:Vector.<IEvent> = new Vector.<IEvent>(); private var _currentState:IState; public var unmappedEventException:Boolean; /* key: IEvent.name value: [ITransition] */ private var _eventMap:Object = {}; public function init(value:IState):void { _currentState = value; } public function get currentState():IState { return _currentState; } // TODO validate reachability of states public function set states(value:Vector.<IState>):void {} public function mapEvent(ie:IEvent, it:ITransition):void { _eventMap[ie.name] ||= []; _eventMap[ie.name].push(it); } public function pushEvent(value:IEvent):void { _events.push(value); eventLoop(); } protected function executeAction(action:IAction, event:IEvent):void { if (action) { action.execute(this, event); } } protected function executeSubmachines(state:IState, event:IEvent):void { for each ( var fsm:IFsm in state.subMachines ) { fsm.pushEvent(event); } } protected function eventLoop():void { // with this loop I'm leaving the possibility open to altering // _events outside of pushEvent while still clearing the queue var event:IEvent; var transition:ITransition; var foundTransition:ITransition; var guard:IGuard; var trueGuard:IGuard;//the guard allowing a state transition var submachine:IFsm; while (event = _events.shift()) { if (!(event.name in _eventMap)) { if (unmappedEventException) { throw new IllegalOperationError("event" + event.name + " isn't mapped"); } continue; } trueGuard = null; foundTransition = null; outer: for each (transition in _eventMap[event.name]) { if (transition.from == currentState) { for each (guard in transition.guards) { if (guard.evaluate(this, event)) { if (trueGuard) { throw new IllegalOperationError("> 1 unguarded transition for " + currentState.id); // while this is an exception we have a valid transition from which to continue continue outer;// TODO consider returning instead } trueGuard = guard; foundTransition = transition; } } } } if (foundTransition) { // execute transition action executeAction(foundTransition.action, event); // complete transition _currentState = foundTransition.to; // execute enterState action for the new state executeAction(currentState.enterState, event); } // execute submachines with current event executeSubmachines(currentState, event); } } } }
package com.phylake.fsm.impl { import com.phylake.fsm.core.*; import flash.errors.IllegalOperationError; import flash.utils.Dictionary; public class Fsm implements IFsm { private var _events:Vector.<IEvent> = new Vector.<IEvent>(); private var _currentState:IState; public var unmappedEventException:Boolean; /* key: IEvent.name value: [ITransition] */ private var _eventMap:Object = {}; public function init(value:IState):void { _currentState = value; } public function get currentState():IState { return _currentState; } // TODO validate reachability of states public function set states(value:Vector.<IState>):void {} public function mapEvent(ie:IEvent, it:ITransition):void { _eventMap[ie.name] ||= []; _eventMap[ie.name].push(it); } public function pushEvent(value:IEvent):void { _events.push(value); eventLoop(); } protected function executeAction(action:IAction, event:IEvent):void { if (action) { action.execute(this, event); } } protected function executeSubmachines(state:IState, event:IEvent):void { for each ( var fsm:IFsm in state.subMachines ) { fsm.pushEvent(event); } } protected function eventLoop():void { // with this loop I'm leaving the possibility open to altering // _events outside of pushEvent while still clearing the queue var event:IEvent; var transition:ITransition; var foundTransition:ITransition; var guard:IGuard; var trueGuard:IGuard;//the guard allowing a state transition var submachine:IFsm; while (event = _events.shift()) { if (!(event.name in _eventMap)) { if (unmappedEventException) { throw new IllegalOperationError("event" + event.name + " isn't mapped"); } continue; } trueGuard = null; foundTransition = null; outer: for each (transition in _eventMap[event.name]) { if (transition.from == currentState) { for each (guard in transition.guards) { if (guard.evaluate(this, event)) { if (trueGuard) { throw new IllegalOperationError("> 1 unguarded transition for " + currentState.id); // while this is an exception we have a valid transition from which to continue break outer;// TODO consider returning instead } trueGuard = guard; foundTransition = transition; } } } } if (foundTransition) { // execute transition action executeAction(foundTransition.action, event); // complete transition _currentState = foundTransition.to; // execute enterState action for the new state executeAction(currentState.enterState, event); } // execute submachines with current event executeSubmachines(currentState, event); } } } }
break instead
break instead
ActionScript
mit
phylake/stratum
e36fddc2eb8bff647b4bfdcbde3064e4c9dbf40f
src/aerys/minko/scene/controller/AnimationController.as
src/aerys/minko/scene/controller/AnimationController.as
package aerys.minko.scene.controller { import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.Signal; import aerys.minko.type.animation.TimeLabel; import aerys.minko.type.animation.timeline.ITimeline; import flash.utils.getTimer; public class AnimationController extends AbstractController { public static var DEFAULT_TIME_FUNCTION : Function = getTimer; private var _timelines : Vector.<ITimeline> = new Vector.<ITimeline>(); private var _isPlaying : Boolean = false; private var _loopBeginTime : int = 0; private var _loopEndTime : int = 0; private var _looping : Boolean = true; private var _currentTime : int = 0; private var _totalTime : int = 0; private var _timeFunction : Function = DEFAULT_TIME_FUNCTION; private var _labels : Vector.<TimeLabel> = null; private var _lastTime : Number = 0; private var _looped : Signal = new Signal(); private var _started : Signal = new Signal(); private var _stopped : Signal = new Signal(); public function get started():Signal { return _started; } public function get stopped() : Signal { return _stopped; } public function get looped():Signal { return _looped; } public function get totalTime() : int { return _totalTime; } public function get looping() : Boolean { return _looping; } public function set looping(value : Boolean) : void { _looping = value; } public function AnimationController(timelines : Vector.<ITimeline>) { super(); _timelines = timelines; initialize(); } public function getTimeline(index : uint = 0) : ITimeline { return _timelines[index]; } private function initialize() : void { var numTimelines : uint = _timelines.length; for (var timelineId : uint = 0; timelineId < numTimelines; ++timelineId) if (_totalTime < _timelines[timelineId].duration) _totalTime = _timelines[timelineId].duration; setPlaybackWindow(0, _totalTime); gotoAndPlay(0); } public function gotoAndPlay(time : Object) : void { var timeValue : uint = getAnimationTime(time); if (timeValue < _loopBeginTime || timeValue > _loopEndTime) throw new Error('Time value is outside of playback window. To reset playback window, call resetPlaybackWindow.'); _currentTime = timeValue; _lastTime = _timeFunction != null ? _timeFunction() : getTimer(); play(); } public function gotoAndStop(time : Object) : void { var timeValue : uint = getAnimationTime(time); if (timeValue < _loopBeginTime || timeValue > _loopEndTime) throw new Error('Time value is outside of playback window. To reset playback window, call resetPlaybackWindow.'); _currentTime = timeValue; _lastTime = _timeFunction != null ? _timeFunction() : getTimer(); stop(); } public function play() : void { _isPlaying = true; _started.execute(this); } public function stop() : void { _isPlaying = false; _stopped.execute(this); } public function setPlaybackWindow(beginTime : Object = null, endTime : Object = null) : void { _loopBeginTime = beginTime != null ? getAnimationTime(beginTime) : 0; _loopEndTime = endTime != null ? getAnimationTime(endTime) : _totalTime; if (_currentTime < _loopBeginTime || _currentTime > _loopEndTime) _currentTime = _loopBeginTime; } public function resetPlaybackWindow() : void { setPlaybackWindow(); } private function getAnimationTime(time : Object) : uint { var timeValue : uint; if (time is uint || time is int || time is Number) { timeValue = uint(time); } else if (time is String) { var labelCount : uint = _labels.length; for (var labelId : uint = 0; labelId < labelCount; ++labelId) if (_labels[labelId].name == time) timeValue = _labels[labelId].time; } else { throw new Error('Invalid argument type. Must be uint or String'); } return timeValue; } override protected function updateOnTime(time : Number) : Boolean { if (_isPlaying) { if (_timeFunction != null) time = _timeFunction(); var deltaT : Number = time - _lastTime; var lastCurrentTime : Number = _currentTime; _currentTime = _loopBeginTime + (_currentTime + deltaT - _loopBeginTime) % (_loopEndTime - _loopBeginTime); if (lastCurrentTime > _currentTime) { if (_looping) _looped.execute(this); else { _currentTime = _totalTime; stop(); return true; } } } _lastTime = time; return _isPlaying; } override protected function updateTarget(target : ISceneNode) : void { var numTimelines : int = _timelines.length; var group : Group = target as Group; for (var i : int = 0; i < numTimelines; ++i) { var timeline : ITimeline = _timelines[i] as ITimeline; timeline.updateAt( _currentTime % (timeline.duration + 1), target ); } } } }
package aerys.minko.scene.controller { import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.Signal; import aerys.minko.type.animation.TimeLabel; import aerys.minko.type.animation.timeline.ITimeline; import flash.utils.getTimer; public class AnimationController extends AbstractController { public function get currentTime():int { return _currentTime; } public function get isPlaying():Boolean { return _isPlaying; } public static var DEFAULT_TIME_FUNCTION : Function = getTimer; private var _timelines : Vector.<ITimeline> = new Vector.<ITimeline>(); private var _isPlaying : Boolean = false; private var _loopBeginTime : int = 0; private var _loopEndTime : int = 0; private var _looping : Boolean = true; private var _currentTime : int = 0; private var _totalTime : int = 0; private var _timeFunction : Function = DEFAULT_TIME_FUNCTION; private var _labels : Vector.<TimeLabel> = null; private var _lastTime : Number = 0; private var _looped : Signal = new Signal(); private var _started : Signal = new Signal(); private var _stopped : Signal = new Signal(); public function get started():Signal { return _started; } public function get stopped() : Signal { return _stopped; } public function get looped():Signal { return _looped; } public function get totalTime() : int { return _totalTime; } public function get looping() : Boolean { return _looping; } public function set looping(value : Boolean) : void { _looping = value; } public function AnimationController(timelines : Vector.<ITimeline>) { super(); _timelines = timelines; initialize(); } public function getTimeline(index : uint = 0) : ITimeline { return _timelines[index]; } private function initialize() : void { var numTimelines : uint = _timelines.length; for (var timelineId : uint = 0; timelineId < numTimelines; ++timelineId) if (_totalTime < _timelines[timelineId].duration) _totalTime = _timelines[timelineId].duration; setPlaybackWindow(0, _totalTime); gotoAndPlay(0); } public function gotoAndPlay(time : Object) : void { var timeValue : uint = getAnimationTime(time); if (timeValue < _loopBeginTime || timeValue > _loopEndTime) throw new Error('Time value is outside of playback window. To reset playback window, call resetPlaybackWindow.'); _currentTime = timeValue; _lastTime = _timeFunction != null ? _timeFunction() : getTimer(); play(); } public function gotoAndStop(time : Object) : void { var timeValue : uint = getAnimationTime(time); if (timeValue < _loopBeginTime || timeValue > _loopEndTime) throw new Error('Time value is outside of playback window. To reset playback window, call resetPlaybackWindow.'); _currentTime = timeValue; _lastTime = _timeFunction != null ? _timeFunction() : getTimer(); stop(); } public function play() : void { _isPlaying = true; _started.execute(this); } public function stop() : void { _isPlaying = false; _stopped.execute(this); } public function setPlaybackWindow(beginTime : Object = null, endTime : Object = null) : void { _loopBeginTime = beginTime != null ? getAnimationTime(beginTime) : 0; _loopEndTime = endTime != null ? getAnimationTime(endTime) : _totalTime; if (_currentTime < _loopBeginTime || _currentTime > _loopEndTime) _currentTime = _loopBeginTime; } public function resetPlaybackWindow() : void { setPlaybackWindow(); } private function getAnimationTime(time : Object) : uint { var timeValue : uint; if (time is uint || time is int || time is Number) { timeValue = uint(time); } else if (time is String) { var labelCount : uint = _labels.length; for (var labelId : uint = 0; labelId < labelCount; ++labelId) if (_labels[labelId].name == time) timeValue = _labels[labelId].time; } else { throw new Error('Invalid argument type. Must be uint or String'); } return timeValue; } override protected function updateOnTime(time : Number) : Boolean { if (_isPlaying) { if (_timeFunction != null) time = _timeFunction(); var deltaT : Number = time - _lastTime; var lastCurrentTime : Number = _currentTime; _currentTime = _loopBeginTime + (_currentTime + deltaT - _loopBeginTime) % (_loopEndTime - _loopBeginTime); if (lastCurrentTime > _currentTime) { if (_looping) _looped.execute(this); else { _currentTime = _totalTime; stop(); return true; } } } _lastTime = time; return _isPlaying; } override protected function updateTarget(target : ISceneNode) : void { var numTimelines : int = _timelines.length; var group : Group = target as Group; for (var i : int = 0; i < numTimelines; ++i) { var timeline : ITimeline = _timelines[i] as ITimeline; timeline.updateAt( _currentTime % (timeline.duration + 1), target ); } } } }
Add getter on totalTime, currentTime and isPlaying properties
Add getter on totalTime, currentTime and isPlaying properties
ActionScript
mit
aerys/minko-as3
35467eee681cd5fa69981df303800d2c2daee6ea
src/aerys/minko/render/shader/part/phong/LightAwareDiffuseShaderPart.as
src/aerys/minko/render/shader/part/phong/LightAwareDiffuseShaderPart.as
package aerys.minko.render.shader.part.phong { import aerys.minko.render.material.basic.BasicProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.type.enum.SamplerFiltering; import aerys.minko.type.enum.SamplerMipMapping; import aerys.minko.type.enum.SamplerWrapping; public class LightAwareDiffuseShaderPart extends LightAwareShaderPart { public function LightAwareDiffuseShaderPart(main:Shader) { super(main); } public function getDiffuseColor() : SFloat { var diffuseColor : SFloat = null; var uv : SFloat = fsUV; if (meshBindings.propertyExists(BasicProperties.DIFFUSE_MAP)) { var diffuseMap : SFloat = meshBindings.getTextureParameter( BasicProperties.DIFFUSE_MAP, meshBindings.getConstant(BasicProperties.DIFFUSE_MAP_FILTERING, SamplerFiltering.LINEAR), meshBindings.getConstant(BasicProperties.DIFFUSE_MAP_MIPMAPPING, SamplerMipMapping.LINEAR), meshBindings.getConstant(BasicProperties.DIFFUSE_MAP_WRAPPING, SamplerWrapping.REPEAT) ); diffuseColor = sampleTexture(diffuseMap, uv); } else if (meshBindings.propertyExists(BasicProperties.DIFFUSE_COLOR)) { diffuseColor = meshBindings.getParameter(BasicProperties.DIFFUSE_COLOR, 4); } else { diffuseColor = float4(0., 0., 0., 1.); } if (meshBindings.propertyExists(BasicProperties.ALPHA_MAP)) { var alphaMap : SFloat = meshBindings.getTextureParameter(BasicProperties.ALPHA_MAP); var alphaSample : SFloat = sampleTexture(alphaMap, uv); diffuseColor = float4(diffuseColor.rgb, alphaSample.r); } if (meshBindings.propertyExists(BasicProperties.DIFFUSE_TRANSFORM)) { diffuseColor = multiply4x4( diffuseColor, meshBindings.getParameter(BasicProperties.DIFFUSE_TRANSFORM, 16) ); } if (meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD)) { var alphaThreshold : SFloat = meshBindings.getParameter( BasicProperties.ALPHA_THRESHOLD, 1 ); kill(subtract(0.5, lessThan(diffuseColor.w, alphaThreshold))); } return diffuseColor; } } }
package aerys.minko.render.shader.part.phong { import aerys.minko.render.material.basic.BasicProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.type.enum.SamplerFiltering; import aerys.minko.type.enum.SamplerFormat; import aerys.minko.type.enum.SamplerMipMapping; import aerys.minko.type.enum.SamplerWrapping; public class LightAwareDiffuseShaderPart extends LightAwareShaderPart { public function LightAwareDiffuseShaderPart(main:Shader) { super(main); } public function getDiffuseColor() : SFloat { var diffuseColor : SFloat = null; var uv : SFloat = fsUV; if (meshBindings.propertyExists(BasicProperties.DIFFUSE_MAP)) { var diffuseMap : SFloat = meshBindings.getTextureParameter( BasicProperties.DIFFUSE_MAP, meshBindings.getConstant(BasicProperties.DIFFUSE_MAP_FILTERING, SamplerFiltering.LINEAR), meshBindings.getConstant(BasicProperties.DIFFUSE_MAP_MIPMAPPING, SamplerMipMapping.LINEAR), meshBindings.getConstant(BasicProperties.DIFFUSE_MAP_WRAPPING, SamplerWrapping.REPEAT), 0, meshBindings.getConstant(BasicProperties.DIFFUSE_MAP_FORMAT, SamplerFormat.RGBA) ); diffuseColor = sampleTexture(diffuseMap, uv); } else if (meshBindings.propertyExists(BasicProperties.DIFFUSE_COLOR)) { diffuseColor = meshBindings.getParameter(BasicProperties.DIFFUSE_COLOR, 4); } else { diffuseColor = float4(0., 0., 0., 1.); } if (meshBindings.propertyExists(BasicProperties.ALPHA_MAP)) { var alphaMap : SFloat = meshBindings.getTextureParameter(BasicProperties.ALPHA_MAP); var alphaSample : SFloat = sampleTexture(alphaMap, uv); diffuseColor = float4(diffuseColor.rgb, alphaSample.r); } if (meshBindings.propertyExists(BasicProperties.DIFFUSE_TRANSFORM)) { diffuseColor = multiply4x4( diffuseColor, meshBindings.getParameter(BasicProperties.DIFFUSE_TRANSFORM, 16) ); } if (meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD)) { var alphaThreshold : SFloat = meshBindings.getParameter( BasicProperties.ALPHA_THRESHOLD, 1 ); kill(subtract(0.5, lessThan(diffuseColor.w, alphaThreshold))); } return diffuseColor; } } }
fix LightAwareDiffuseShaderPart.getDiffuseColor() to use the BasicProperties.DIFFUSE_MAP_FORMAT mesh binding
fix LightAwareDiffuseShaderPart.getDiffuseColor() to use the BasicProperties.DIFFUSE_MAP_FORMAT mesh binding
ActionScript
mit
aerys/minko-as3
6d4b58dd97f2998a2d7c24fb6200bfdf815a4959
src/Player.as
src/Player.as
package { import flash.display.Loader; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.NetStatusEvent; import flash.external.ExternalInterface; import flash.media.SoundTransform; import flash.media.Video; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.URLRequest; import flash.system.Security; [SWF(backgroundColor="0x000000")] public class Player extends Sprite { private var posterUrl: String; private var videoUrl: String; private var loop: Boolean; private var muted: Boolean; private var autoplay: Boolean; private var videoPlaying: Boolean; private var poster: Loader; private var video: Video; private var posterContainer: Sprite; private var connection: NetConnection; private var stream: NetStream; public function Player() { stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; Security.allowDomain("*"); Security.allowInsecureDomain("*"); registerExternalMethods(); posterUrl = loaderInfo.parameters.poster; videoUrl = loaderInfo.parameters.video; loop = loaderInfo.parameters.loop == "true"; muted = loaderInfo.parameters.muted == "true"; autoplay = loaderInfo.parameters.autoplay == "true"; if (posterUrl) { loadPoster(); } loadVideo(); } private function play(): void { videoPlaying = true; stream.resume(); } private function pause(): void { videoPlaying = false; stream.pause(); } private function isPaused(): Boolean { return !videoPlaying; } private function mute(): void { stream.soundTransform = new SoundTransform(0); } private function unmute(): void { stream.soundTransform = new SoundTransform(1); } private function isMuted(): Boolean { return stream.soundTransform.volume == 0; } private function registerExternalMethods(): void { ExternalInterface.addCallback("play", play); ExternalInterface.addCallback("pause", pause); ExternalInterface.addCallback("paused", isPaused); ExternalInterface.addCallback("mute", mute); ExternalInterface.addCallback("unmute", unmute); ExternalInterface.addCallback("muted", isMuted); } private function loadPoster(): void { posterContainer = new Sprite(); posterContainer.width = stage.stageWidth; posterContainer.height = stage.stageHeight; addChildAt(posterContainer, 0); poster = new Loader(); poster.contentLoaderInfo.addEventListener(Event.COMPLETE, function(): void { posterContainer.addChild(poster); }); poster.load(new URLRequest(posterUrl)); } private function loadVideo(): void { connection = new NetConnection(); connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); connection.connect(null); } private function netStatusHandler(event: NetStatusEvent): void { switch (event.info.code) { case "NetConnection.Connect.Success": connectStream(); break; case "NetStream.Play.Stop": if (loop) stream.seek(0); break; } } private function connectStream(): void { video = new Video(stage.stageWidth, stage.stageHeight); addChildAt(video, 1); stream = new NetStream(connection); stream.bufferTime = 0.5; stream.soundTransform = new SoundTransform(muted ? 0 : 1); stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); video.attachNetStream(stream); stream.play(videoUrl); if (!autoplay) pause(); } } }
package { import flash.display.Loader; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.NetStatusEvent; import flash.external.ExternalInterface; import flash.media.SoundTransform; import flash.media.Video; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.URLRequest; import flash.system.Security; [SWF(backgroundColor="0x000000")] public class Player extends Sprite { private var posterUrl: String; private var videoUrl: String; private var loop: Boolean; private var muted: Boolean; private var autoplay: Boolean; private var videoPlaying: Boolean; private var poster: Loader; private var video: Video; private var posterContainer: Sprite; private var connection: NetConnection; private var stream: NetStream; public function Player() { stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; Security.allowDomain("*"); Security.allowInsecureDomain("*"); registerExternalMethods(); posterUrl = loaderInfo.parameters.poster; videoUrl = loaderInfo.parameters.video; loop = loaderInfo.parameters.loop == "true"; muted = loaderInfo.parameters.muted == "true"; autoplay = loaderInfo.parameters.autoplay == "true"; if (posterUrl) { loadPoster(); } loadVideo(); if (loaderInfo.parameters.onReady) { ExternalInterface.call(loaderInfo.parameters.onReady); } } private function play(): void { videoPlaying = true; stream.resume(); } private function pause(): void { videoPlaying = false; stream.pause(); } private function isPaused(): Boolean { return !videoPlaying; } private function mute(): void { stream.soundTransform = new SoundTransform(0); } private function unmute(): void { stream.soundTransform = new SoundTransform(1); } private function isMuted(): Boolean { return stream.soundTransform.volume == 0; } private function registerExternalMethods(): void { ExternalInterface.addCallback("play", play); ExternalInterface.addCallback("pause", pause); ExternalInterface.addCallback("paused", isPaused); ExternalInterface.addCallback("mute", mute); ExternalInterface.addCallback("unmute", unmute); ExternalInterface.addCallback("muted", isMuted); } private function loadPoster(): void { posterContainer = new Sprite(); posterContainer.width = stage.stageWidth; posterContainer.height = stage.stageHeight; addChildAt(posterContainer, 0); poster = new Loader(); poster.contentLoaderInfo.addEventListener(Event.COMPLETE, function(): void { posterContainer.addChild(poster); }); poster.load(new URLRequest(posterUrl)); } private function loadVideo(): void { connection = new NetConnection(); connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); connection.connect(null); } private function netStatusHandler(event: NetStatusEvent): void { switch (event.info.code) { case "NetConnection.Connect.Success": connectStream(); break; case "NetStream.Play.Stop": if (loop) stream.seek(0); break; } } private function connectStream(): void { video = new Video(stage.stageWidth, stage.stageHeight); addChildAt(video, 1); stream = new NetStream(connection); stream.bufferTime = 0.5; stream.soundTransform = new SoundTransform(muted ? 0 : 1); stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); video.attachNetStream(stream); stream.play(videoUrl); if (autoplay) { videoPlaying = true; } else { videoPlaying = false; pause(); } } } }
add onReady callback
add onReady callback
ActionScript
mit
cameronhunter/divine-player