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
|
---|---|---|---|---|---|---|---|---|---|
41be0f56764722d09571d430576f6ba0d8483301
|
lib/src_linux/com/amanitadesign/steam/FRESteamWorks.as
|
lib/src_linux/com/amanitadesign/steam/FRESteamWorks.as
|
/*
* FRESteamWorks.as
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero>
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam {
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.StatusEvent;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.clearInterval;
import flash.utils.setInterval;
public class FRESteamWorks extends EventDispatcher {
[Event(name="steam_response", type="com.amanitadesign.steam.SteamEvent")]
private static const PATH:String = "NativeApps/Linux/APIWrapper";
private var _file:File;
private var _process:NativeProcess;
private var _tm:int;
private var _init:Boolean = false;
private var _error:Boolean = false;
private var _crashHandlerArgs:Array = null;
public var isReady:Boolean = false;
private static const AIRSteam_Init:int = 0;
private static const AIRSteam_RunCallbacks:int = 1;
private static const AIRSteam_RequestStats:int = 2;
private static const AIRSteam_SetAchievement:int = 3;
private static const AIRSteam_ClearAchievement:int = 4;
private static const AIRSteam_IsAchievement:int = 5;
private static const AIRSteam_GetStatInt:int = 6;
private static const AIRSteam_GetStatFloat:int = 7;
private static const AIRSteam_SetStatInt:int = 8;
private static const AIRSteam_SetStatFloat:int = 9;
private static const AIRSteam_StoreStats:int = 10;
private static const AIRSteam_ResetAllStats:int = 11;
private static const AIRSteam_GetFileCount:int = 12;
private static const AIRSteam_GetFileSize:int = 13;
private static const AIRSteam_FileExists:int = 14;
private static const AIRSteam_FileWrite:int = 15;
private static const AIRSteam_FileRead:int = 16;
private static const AIRSteam_FileDelete:int = 17;
private static const AIRSteam_IsCloudEnabledForApp:int = 18;
private static const AIRSteam_SetCloudEnabledForApp:int = 19;
private static const AIRSteam_GetUserID:int = 20;
private static const AIRSteam_GetPersonaName:int = 21;
private static const AIRSteam_UseCrashHandler:int = 22;
public function FRESteamWorks (target:IEventDispatcher = null) {
_file = File.applicationDirectory.resolvePath(PATH);
_process = new NativeProcess();
_process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, eventDispatched);
_process.addEventListener(IOErrorEvent.STANDARD_INPUT_IO_ERROR, errorCallback);
super(target);
}
public function dispose():void {
if(_process.running) {
_process.closeInput();
_process.exit();
}
clearInterval(_tm);
isReady = false;
}
private function startProcess():void {
var startupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
startupInfo.executable = _file;
_process.start(startupInfo);
}
public function init():Boolean {
if(!_file.exists) return false;
try {
startProcess();
} catch(e:Error) {
return false;
}
// try to start the process a second time, but this time ignoring any
// potential errors since we will definitely get one about the process
// already running. this seems to give the runtime enough time to check
// for any stderr output of the initial call to startProcess(), so that we
// now can check if it actually started: in case it couldn't one of the
// libraries it depends on, it prints something like "error while loading
// shared libraries" to stderr, which we're trying to detect here.
// process.running is unreliable, in that it's always set to true,
// even if the process didn't start at all
try {
startProcess();
} catch(e:Error) {
// no-op
}
if(!_process.running) return false;
if(_process.standardError.bytesAvailable > 0) return false;
// initialization seems to be successful
_init = true;
// UseCrashHandler has to be called before Steam_Init
// but we still have to make sure the process is actually running
// so FRESteamWorks#useCrashHandler just sets _crashHandlerArgs
// and the actual call is handled here
if(_crashHandlerArgs) {
if(!callWrapper(AIRSteam_UseCrashHandler, _crashHandlerArgs))
return false;
}
if(!callWrapper(AIRSteam_Init)) return false;
isReady = readBoolResponse();
if(isReady) _tm = setInterval(runCallbacks, 100);
return isReady;
}
private function errorCallback(e:IOErrorEvent):void {
_error = true;
// the process doesn't accept our input anymore, so just stop it
clearInterval(_tm);
if(_process.running) {
try {
_process.closeInput();
} catch(e:*) {
// no-op
}
_process.exit();
}
}
private function callWrapper(funcName:int, params:Array = null):Boolean {
_error = false;
if(!_process.running) return false;
var stdin:IDataOutput = _process.standardInput;
stdin.writeUTFBytes(funcName + "\n");
if (params) {
for(var i:int = 0; i < params.length; ++i) {
if(params[i] is ByteArray) {
var length:uint = params[i].length;
// length + 1 for the added newline
stdin.writeUTFBytes(String(length + 1) + "\n");
stdin.writeBytes(params[i]);
stdin.writeUTFBytes("\n");
} else {
stdin.writeUTFBytes(String(params[i]) + "\n");
}
}
}
return !_error;
}
private function waitForData(output:IDataInput):uint {
while(!output.bytesAvailable) {
// wait
if(!_process.running) return 0;
}
return output.bytesAvailable;
}
private function readBoolResponse():Boolean {
if(!_process.running) return false;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(1);
return (response == "t");
}
private function readIntResponse():int {
if(!_process.running) return 0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail);
return parseInt(response, 10);
}
private function readFloatResponse():Number {
if(!_process.running) return 0.0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail)
return parseFloat(response);
}
private function readStringResponse():String {
if(!_process.running) return "";
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var data:String = stdout.readUTFBytes(avail)
var newline:uint = data.indexOf("\n");
var buf:String = data.substring(newline);
var length:uint = parseInt(data.substring(0, newline), 10);
trace("Waiting for " + length + " bytes");
while(buf.length < length) {
avail = waitForData(stdout);
buf += stdout.readUTFBytes(avail);
}
return buf;
}
private function eventDispatched(e:ProgressEvent):void {
var stderr:IDataInput = _process.standardError;
var avail:uint = stderr.bytesAvailable;
var data:String = stderr.readUTFBytes(avail);
var pattern:RegExp = /__event__<(\d+),(\d+)>/g;
var result:Object;
while((result = pattern.exec(data))) {
var req_type:int = new int(result[1]);
var response:int = new int(result[2]);
var steamEvent:SteamEvent = new SteamEvent(SteamEvent.STEAM_RESPONSE, req_type, response);
dispatchEvent(steamEvent);
}
}
public function requestStats():Boolean {
if(!callWrapper(AIRSteam_RequestStats)) return false;
return readBoolResponse();
}
public function runCallbacks():Boolean {
if(!callWrapper(AIRSteam_RunCallbacks)) return false;
return true;
}
public function getUserID():String {
if(!callWrapper(AIRSteam_GetUserID)) return "";
return readStringResponse();
}
public function getPersonaName():String {
if(!callWrapper(AIRSteam_GetPersonaName)) return "";
return readStringResponse();
}
public function useCrashHandler(appID:uint, version:String, date:String, time:String):Boolean {
// only allow calls before SteamAPI_Init was called
if(_init) return false;
_crashHandlerArgs = [appID, version, date, time];
return true;
}
public function setAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_SetAchievement, [id])) return false;
return readBoolResponse();
}
public function clearAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_ClearAchievement, [id])) return false;
return readBoolResponse();
}
public function isAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_IsAchievement, [id])) return false;
return readBoolResponse();
}
public function getStatInt(id:String):int {
if(!callWrapper(AIRSteam_GetStatInt, [id])) return 0;
return readIntResponse();
}
public function getStatFloat(id:String):Number {
if(!callWrapper(AIRSteam_GetStatFloat, [id])) return 0.0;
return readFloatResponse();
}
public function setStatInt(id:String, value:int):Boolean {
if(!callWrapper(AIRSteam_SetStatInt, [id, value])) return false;
return readBoolResponse();
}
public function setStatFloat(id:String, value:Number):Boolean {
if(!callWrapper(AIRSteam_SetStatFloat, [id, value])) return false;
return readBoolResponse();
}
public function storeStats():Boolean {
if(!callWrapper(AIRSteam_StoreStats)) return false;
return readBoolResponse();
}
public function resetAllStats(bAchievementsToo:Boolean):Boolean {
if(!callWrapper(AIRSteam_ResetAllStats, [bAchievementsToo])) return false;
return readBoolResponse();
}
public function getFileCount():int {
if(!callWrapper(AIRSteam_GetFileCount)) return 0;
return readIntResponse();
}
public function getFileSize(fileName:String):int {
if(!callWrapper(AIRSteam_GetFileSize, [fileName])) return 0;
return readIntResponse();
}
public function fileExists(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileExists, [fileName])) return false;
return readBoolResponse();
}
public function fileWrite(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileWrite, [fileName, data])) return false;
return readBoolResponse();
}
public function fileRead(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileRead, [fileName])) return false;
var success:Boolean = readBoolResponse();
if(success) {
var content:String = readStringResponse();
data.writeUTFBytes(content);
data.position = 0;
}
return success;
}
public function fileDelete(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileDelete, [fileName])) return false;
return readBoolResponse();
}
public function isCloudEnabledForApp():Boolean {
if(!callWrapper(AIRSteam_IsCloudEnabledForApp)) return false;
return readBoolResponse();
}
public function setCloudEnabledForApp(enabled:Boolean):Boolean {
if(!callWrapper(AIRSteam_SetCloudEnabledForApp, [enabled])) return false;
return readBoolResponse();
}
}
}
|
/*
* FRESteamWorks.as
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero>
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam {
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.StatusEvent;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.clearInterval;
import flash.utils.setInterval;
public class FRESteamWorks extends EventDispatcher {
[Event(name="steam_response", type="com.amanitadesign.steam.SteamEvent")]
private static const PATH:String = "NativeApps/Linux/APIWrapper";
private var _file:File;
private var _process:NativeProcess;
private var _tm:int;
private var _init:Boolean = false;
private var _error:Boolean = false;
private var _crashHandlerArgs:Array = null;
public var isReady:Boolean = false;
private static const AIRSteam_Init:int = 0;
private static const AIRSteam_RunCallbacks:int = 1;
private static const AIRSteam_RequestStats:int = 2;
private static const AIRSteam_SetAchievement:int = 3;
private static const AIRSteam_ClearAchievement:int = 4;
private static const AIRSteam_IsAchievement:int = 5;
private static const AIRSteam_GetStatInt:int = 6;
private static const AIRSteam_GetStatFloat:int = 7;
private static const AIRSteam_SetStatInt:int = 8;
private static const AIRSteam_SetStatFloat:int = 9;
private static const AIRSteam_StoreStats:int = 10;
private static const AIRSteam_ResetAllStats:int = 11;
private static const AIRSteam_GetFileCount:int = 12;
private static const AIRSteam_GetFileSize:int = 13;
private static const AIRSteam_FileExists:int = 14;
private static const AIRSteam_FileWrite:int = 15;
private static const AIRSteam_FileRead:int = 16;
private static const AIRSteam_FileDelete:int = 17;
private static const AIRSteam_IsCloudEnabledForApp:int = 18;
private static const AIRSteam_SetCloudEnabledForApp:int = 19;
private static const AIRSteam_GetUserID:int = 20;
private static const AIRSteam_GetPersonaName:int = 21;
private static const AIRSteam_UseCrashHandler:int = 22;
public function FRESteamWorks (target:IEventDispatcher = null) {
_file = File.applicationDirectory.resolvePath(PATH);
_process = new NativeProcess();
_process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, eventDispatched);
_process.addEventListener(IOErrorEvent.STANDARD_INPUT_IO_ERROR, errorCallback);
super(target);
}
public function dispose():void {
if(_process.running) {
_process.closeInput();
_process.exit();
}
clearInterval(_tm);
isReady = false;
}
private function startProcess():void {
var startupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
startupInfo.executable = _file;
_process.start(startupInfo);
}
public function init():Boolean {
if(!_file.exists) return false;
try {
startProcess();
} catch(e:Error) {
return false;
}
// try to start the process a second time, but this time ignoring any
// potential errors since we will definitely get one about the process
// already running. this seems to give the runtime enough time to check
// for any stderr output of the initial call to startProcess(), so that we
// now can check if it actually started: in case it couldn't one of the
// libraries it depends on, it prints something like "error while loading
// shared libraries" to stderr, which we're trying to detect here.
// process.running is unreliable, in that it's always set to true,
// even if the process didn't start at all
try {
startProcess();
} catch(e:Error) {
// no-op
}
if(!_process.running) return false;
if(_process.standardError.bytesAvailable > 0) return false;
// initialization seems to be successful
_init = true;
// UseCrashHandler has to be called before Steam_Init
// but we still have to make sure the process is actually running
// so FRESteamWorks#useCrashHandler just sets _crashHandlerArgs
// and the actual call is handled here
if(_crashHandlerArgs) {
if(!callWrapper(AIRSteam_UseCrashHandler, _crashHandlerArgs))
return false;
}
if(!callWrapper(AIRSteam_Init)) return false;
isReady = readBoolResponse();
if(isReady) _tm = setInterval(runCallbacks, 100);
return isReady;
}
private function errorCallback(e:IOErrorEvent):void {
_error = true;
// the process doesn't accept our input anymore, so just stop it
clearInterval(_tm);
if(_process.running) {
try {
_process.closeInput();
} catch(e:*) {
// no-op
}
_process.exit();
}
}
private function callWrapper(funcName:int, params:Array = null):Boolean {
_error = false;
if(!_process.running) return false;
var stdin:IDataOutput = _process.standardInput;
stdin.writeUTFBytes(funcName + "\n");
if (params) {
for(var i:int = 0; i < params.length; ++i) {
if(params[i] is ByteArray) {
var length:uint = params[i].length;
// length + 1 for the added newline
stdin.writeUTFBytes(String(length + 1) + "\n");
stdin.writeBytes(params[i]);
stdin.writeUTFBytes("\n");
} else {
stdin.writeUTFBytes(String(params[i]) + "\n");
}
}
}
return !_error;
}
private function waitForData(output:IDataInput):uint {
while(!output.bytesAvailable) {
// wait
if(!_process.running) return 0;
}
return output.bytesAvailable;
}
private function readBoolResponse():Boolean {
if(!_process.running) return false;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(1);
return (response == "t");
}
private function readIntResponse():int {
if(!_process.running) return 0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail);
return parseInt(response, 10);
}
private function readFloatResponse():Number {
if(!_process.running) return 0.0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail)
return parseFloat(response);
}
private function readStringResponse():String {
if(!_process.running) return "";
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var data:String = stdout.readUTFBytes(avail)
var newline:uint = data.indexOf("\n");
var buf:String = data.substring(newline);
var length:uint = parseInt(data.substring(0, newline), 10);
while(buf.length < length) {
avail = waitForData(stdout);
buf += stdout.readUTFBytes(avail);
}
return buf;
}
private function eventDispatched(e:ProgressEvent):void {
var stderr:IDataInput = _process.standardError;
var avail:uint = stderr.bytesAvailable;
var data:String = stderr.readUTFBytes(avail);
var pattern:RegExp = /__event__<(\d+),(\d+)>/g;
var result:Object;
while((result = pattern.exec(data))) {
var req_type:int = new int(result[1]);
var response:int = new int(result[2]);
var steamEvent:SteamEvent = new SteamEvent(SteamEvent.STEAM_RESPONSE, req_type, response);
dispatchEvent(steamEvent);
}
}
public function requestStats():Boolean {
if(!callWrapper(AIRSteam_RequestStats)) return false;
return readBoolResponse();
}
public function runCallbacks():Boolean {
if(!callWrapper(AIRSteam_RunCallbacks)) return false;
return true;
}
public function getUserID():String {
if(!callWrapper(AIRSteam_GetUserID)) return "";
return readStringResponse();
}
public function getPersonaName():String {
if(!callWrapper(AIRSteam_GetPersonaName)) return "";
return readStringResponse();
}
public function useCrashHandler(appID:uint, version:String, date:String, time:String):Boolean {
// only allow calls before SteamAPI_Init was called
if(_init) return false;
_crashHandlerArgs = [appID, version, date, time];
return true;
}
public function setAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_SetAchievement, [id])) return false;
return readBoolResponse();
}
public function clearAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_ClearAchievement, [id])) return false;
return readBoolResponse();
}
public function isAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_IsAchievement, [id])) return false;
return readBoolResponse();
}
public function getStatInt(id:String):int {
if(!callWrapper(AIRSteam_GetStatInt, [id])) return 0;
return readIntResponse();
}
public function getStatFloat(id:String):Number {
if(!callWrapper(AIRSteam_GetStatFloat, [id])) return 0.0;
return readFloatResponse();
}
public function setStatInt(id:String, value:int):Boolean {
if(!callWrapper(AIRSteam_SetStatInt, [id, value])) return false;
return readBoolResponse();
}
public function setStatFloat(id:String, value:Number):Boolean {
if(!callWrapper(AIRSteam_SetStatFloat, [id, value])) return false;
return readBoolResponse();
}
public function storeStats():Boolean {
if(!callWrapper(AIRSteam_StoreStats)) return false;
return readBoolResponse();
}
public function resetAllStats(bAchievementsToo:Boolean):Boolean {
if(!callWrapper(AIRSteam_ResetAllStats, [bAchievementsToo])) return false;
return readBoolResponse();
}
public function getFileCount():int {
if(!callWrapper(AIRSteam_GetFileCount)) return 0;
return readIntResponse();
}
public function getFileSize(fileName:String):int {
if(!callWrapper(AIRSteam_GetFileSize, [fileName])) return 0;
return readIntResponse();
}
public function fileExists(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileExists, [fileName])) return false;
return readBoolResponse();
}
public function fileWrite(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileWrite, [fileName, data])) return false;
return readBoolResponse();
}
public function fileRead(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileRead, [fileName])) return false;
var success:Boolean = readBoolResponse();
if(success) {
var content:String = readStringResponse();
data.writeUTFBytes(content);
data.position = 0;
}
return success;
}
public function fileDelete(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileDelete, [fileName])) return false;
return readBoolResponse();
}
public function isCloudEnabledForApp():Boolean {
if(!callWrapper(AIRSteam_IsCloudEnabledForApp)) return false;
return readBoolResponse();
}
public function setCloudEnabledForApp(enabled:Boolean):Boolean {
if(!callWrapper(AIRSteam_SetCloudEnabledForApp, [enabled])) return false;
return readBoolResponse();
}
}
}
|
Remove debug trace
|
[swc] Remove debug trace
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
0bf0b2d322e6b29d31f892b48b25200b8517e369
|
src/aerys/minko/scene/node/Mesh.as
|
src/aerys/minko/scene/node/Mesh.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.scene.controller.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.Ray;
use namespace minko_scene;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractVisibleSceneNode implements ITaggable
{
public static const DEFAULT_MATERIAL : Material = new BasicMaterial();
private var _ctrl : MeshController;
private var _properties : DataProvider;
private var _material : Material;
private var _bindings : DataBindings;
private var _visibility : MeshVisibilityController;
private var _cloned : Signal;
private var _tag : uint = 1;
/**
* 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 <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
var oldMaterial : Material = _material;
_material = value;
if (value)
_bindings.addProvider(value);
}
}
/**
* 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 _ctrl.geometry;
}
public function set geometry(value : Geometry) : void
{
_ctrl.geometry = value;
}
public function get tag() : uint
{
return _tag;
}
public function set tag(value : uint) : void
{
if (_tag != value)
{
_tag = value;
_properties.setProperty('tag', value);
}
}
/**
* Whether the mesh in inside the camera frustum or not.
* @return
*
*/
public function get insideFrustum() : Boolean
{
return _visibility.insideFrustum;
}
override public function get computedVisibility() : Boolean
{
return scene
? super.computedVisibility && _visibility.computedVisibility
: super.computedVisibility;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get frame() : uint
{
return _ctrl.frame;
}
public function set frame(value : uint) : void
{
_ctrl.frame = value;
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
name : String = null,
tag : uint = 1)
{
super();
initializeMesh(geometry, material, name, tag);
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(
properties,
'meshProperties',
DataProviderUsage.EXCLUSIVE
);
super.initialize();
}
override protected function initializeSignals() : void
{
super.initializeSignals();
_cloned = new Signal('Mesh.cloned');
}
override protected function initializeContollers() : void
{
super.initializeContollers();
_ctrl = new MeshController();
addController(_ctrl);
_visibility = new MeshVisibilityController();
_visibility.frustumCulling = FrustumCulling.ENABLED;
addController(_visibility);
}
protected function initializeMesh(geometry : Geometry,
material : Material,
name : String,
tag : uint) : void
{
if (name)
this.name = name;
this.geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
_tag = tag;
}
public function cast(ray : Ray,
maxDistance : Number = Number.POSITIVE_INFINITY,
tag : uint = 1) : Number
{
if (!(_tag & tag))
return -1;
return _ctrl.geometry.boundingBox.testRay(
ray,
getWorldToLocalTransform(),
maxDistance
);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Mesh = new Mesh();
clone.name = name;
clone.geometry = _ctrl.geometry;
clone.properties = DataProvider(_properties.clone());
clone._bindings.copySharedProvidersFrom(_bindings);
clone.transform.copyFrom(transform);
clone.material = _material;
this.cloned.execute(this, clone);
return clone;
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.scene.controller.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.Ray;
use namespace minko_scene;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractVisibleSceneNode implements ITaggable
{
private var _ctrl : MeshController;
private var _properties : DataProvider;
private var _material : Material;
private var _bindings : DataBindings;
private var _visibility : MeshVisibilityController;
private var _cloned : Signal;
private var _tag : uint = 1;
/**
* 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 <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
var oldMaterial : Material = _material;
_material = value;
if (value)
_bindings.addProvider(value);
}
}
/**
* 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 _ctrl.geometry;
}
public function set geometry(value : Geometry) : void
{
_ctrl.geometry = value;
}
public function get tag() : uint
{
return _tag;
}
public function set tag(value : uint) : void
{
if (_tag != value)
{
_tag = value;
_properties.setProperty('tag', value);
}
}
/**
* Whether the mesh in inside the camera frustum or not.
* @return
*
*/
public function get insideFrustum() : Boolean
{
return _visibility.insideFrustum;
}
override public function get computedVisibility() : Boolean
{
return scene
? super.computedVisibility && _visibility.computedVisibility
: super.computedVisibility;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get frame() : uint
{
return _ctrl.frame;
}
public function set frame(value : uint) : void
{
_ctrl.frame = value;
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
name : String = null,
tag : uint = 1)
{
super();
initializeMesh(geometry, material, name, tag);
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(
properties,
'meshProperties',
DataProviderUsage.EXCLUSIVE
);
super.initialize();
}
override protected function initializeSignals() : void
{
super.initializeSignals();
_cloned = new Signal('Mesh.cloned');
}
override protected function initializeContollers() : void
{
super.initializeContollers();
_ctrl = new MeshController();
addController(_ctrl);
_visibility = new MeshVisibilityController();
_visibility.frustumCulling = FrustumCulling.ENABLED;
addController(_visibility);
}
protected function initializeMesh(geometry : Geometry,
material : Material,
name : String,
tag : uint) : void
{
if (name)
this.name = name;
this.geometry = geometry;
this.material = material;
_tag = tag;
}
public function cast(ray : Ray,
maxDistance : Number = Number.POSITIVE_INFINITY,
tag : uint = 1) : Number
{
if (!(_tag & tag))
return -1;
return _ctrl.geometry.boundingBox.testRay(
ray,
getWorldToLocalTransform(),
maxDistance
);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Mesh = new Mesh();
clone.name = name;
clone.geometry = _ctrl.geometry;
clone.properties = DataProvider(_properties.clone());
clone._bindings.copySharedProvidersFrom(_bindings);
clone.transform.copyFrom(transform);
clone.material = _material;
this.cloned.execute(this, clone);
return clone;
}
}
}
|
fix Mesh.initializeMesh() to stop using static reference to a default material to avoid memory leak: by default Mesh will now have a null material if none is provided
|
fix Mesh.initializeMesh() to stop using static reference to a default material to avoid memory leak: by default Mesh will now have a null material if none is provided
|
ActionScript
|
mit
|
aerys/minko-as3
|
35d35bf543fe694c162fb4ae791dfffbd6956bff
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/SimpleCSSStyles.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/SimpleCSSStyles.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import org.apache.flex.events.Event;
import org.apache.flex.events.EventDispatcher;
/**
* The SimpleCSSStyles class contains CSS style
* properties supported by SimpleCSSValuesImpl.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class SimpleCSSStyles
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function SimpleCSSStyles()
{
super();
}
private var _object:IStyleableObject;
/**
* The object to which these styles apply.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get object():IStyleableObject
{
return _object;
}
/**
* @private
*/
public function set object(value:IStyleableObject):void
{
if (_object != value)
{
_object = value;
}
}
public var top:*;
public var bottom:*;
public var left:*;
public var right:*;
public var padding:*;
public var paddingLeft:*;
public var paddingRight:*;
public var paddingTop:*;
public var paddingBottom:*;
public var horizontalCenter:*;
public var verticalCenter:*;
public var horizontalAlign:*;
public var verticalAlign:*;
public var fontFamily:*;
public var fontSize:*;
public var color:*;
public var backgroundColor:*;
public var backgroundImage:*;
public var borderColor:*;
public var borderStyle:*;
public var borderRadius:*;
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import org.apache.flex.events.Event;
import org.apache.flex.events.EventDispatcher;
/**
* The SimpleCSSStyles class contains CSS style
* properties supported by SimpleCSSValuesImpl.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class SimpleCSSStyles
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function SimpleCSSStyles()
{
super();
}
private var _object:IStyleableObject;
/**
* The object to which these styles apply.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get object():IStyleableObject
{
return _object;
}
/**
* @private
*/
public function set object(value:IStyleableObject):void
{
if (_object != value)
{
_object = value;
}
}
public var top:*;
public var bottom:*;
public var left:*;
public var right:*;
public var padding:*;
public var paddingLeft:*;
public var paddingRight:*;
public var paddingTop:*;
public var paddingBottom:*;
public var horizontalCenter:*;
public var verticalCenter:*;
public var horizontalAlign:*;
public var verticalAlign:*;
public var fontFamily:*;
public var fontSize:*;
public var color:*;
public var backgroundAlpha:*;
public var backgroundColor:*;
public var backgroundImage:*;
public var borderColor:*;
public var borderStyle:*;
public var borderRadius:*;
}
}
|
add more style props
|
add more style props
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
f08434ed2125898e0a794813202713f14bab4672
|
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 removeAllCallback() : void
{
for (var callbackIndex : int = _numCallbacks - 1; callbackIndex >= 0; --callbackIndex)
remove(_callbacks[callbackIndex]);
}
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
{
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;
}
}
}
|
Remove 'removeAllCallback' function from signal file
|
Remove 'removeAllCallback' function from signal file
|
ActionScript
|
mit
|
aerys/minko-as3
|
8066aa1927952d437881222ee98a41e7391b2824
|
actionscript/src/com/freshplanet/nativeExtensions/PushNotification.as
|
actionscript/src/com/freshplanet/nativeExtensions/PushNotification.as
|
package com.freshplanet.nativeExtensions
{
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class PushNotification extends EventDispatcher
{
public static const RECURRENCE_NONE:int = 0;
public static const RECURRENCE_DAILY:int = 1;
public static const RECURRENCE_WEEK:int = 2;
public static const RECURRENCE_MONTH:int = 3;
public static const RECURRENCE_YEAR:int = 4;
public static const DEFAULT_LOCAL_NOTIFICATION_ID:int = 0;
private static var extCtx:ExtensionContext = null;
private static var _instance:PushNotification;
public function PushNotification()
{
if (!_instance)
{
if (this.isPushNotificationSupported)
{
extCtx = ExtensionContext.createExtensionContext("com.freshplanet.AirPushNotification", null);
if (extCtx != null)
{
extCtx.addEventListener(StatusEvent.STATUS, onStatus);
} else
{
trace('extCtx is null.');
}
}
_instance = this;
}
else
{
throw Error( 'This is a singleton, use getInstance, do not call the constructor directly');
}
}
public function get isPushNotificationSupported():Boolean
{
var result:Boolean = (Capabilities.manufacturer.search('iOS') > -1 || Capabilities.manufacturer.search('Android') > -1);
return result;
}
/**
* return true if notifs are enabled for this app in device settings
* If iOS < 8 or android < 4.1 this isn't available, so will always return true.
*/
public function get notificationsEnabled():Boolean
{
if(!isPushNotificationSupported) {
return false;
}
return extCtx.call("getNotificationsEnabled");
}
/**
* return true if OS permits sending user to settings (iOS 8, Android
*/
public function get canSendUserToSettings():Boolean
{
if(!isPushNotificationSupported) {
return false;
}
return extCtx.call("getCanSendUserToSettings");
}
public function openDeviceNotificationSettions():void
{
if(isPushNotificationSupported) {
extCtx.call("openDeviceNotificationSettings");
}
}
public static function getInstance() : PushNotification
{
return _instance ? _instance : new PushNotification();
}
/**
* Needs Project id for Android Notifications.
* The project id is the one the developer used to register to gcm.
* @param projectId: project id to use
*/
public function registerForPushNotification(projectId:String = null) : void
{
if (this.isPushNotificationSupported)
{
extCtx.call("registerPush", projectId);
}
}
public function setBadgeNumberValue(value:int):void
{
if (this.isPushNotificationSupported)
{
extCtx.call("setBadgeNb", value);
}
}
/**
* Sends a local notification to the device.
* @param message the local notification text displayed
* @param timestamp when the local notification should appear (in sec)
* @param title (Android Only) Title of the local notification
* @param recurrenceType
*
*/
public function sendLocalNotification(message:String, timestamp:int, title:String, recurrenceType:int = RECURRENCE_NONE, notificationId:int = DEFAULT_LOCAL_NOTIFICATION_ID):void
{
if (this.isPushNotificationSupported)
{
if (notificationId == DEFAULT_LOCAL_NOTIFICATION_ID)
{
extCtx.call("sendLocalNotification", message, timestamp, title, recurrenceType);
} else
{
extCtx.call("sendLocalNotification", message, timestamp, title, recurrenceType, notificationId);
}
}
}
/**
* Not implemented on Android for now.
* @param notificationId
*
*/
public function cancelLocalNotification(notificationId:int = DEFAULT_LOCAL_NOTIFICATION_ID):void
{
if (this.isPushNotificationSupported)
{
if (notificationId == DEFAULT_LOCAL_NOTIFICATION_ID)
{
extCtx.call("cancelLocalNotification");
} else
{
extCtx.call("cancelLocalNotification", notificationId);
}
}
}
public function cancelAllLocalNotifications():void
{
if(this.isPushNotificationSupported)
{
extCtx.call("cancelAllLocalNotifications");
}
}
public function setIsAppInForeground(value:Boolean):void
{
if (this.isPushNotificationSupported)
{
extCtx.call("setIsAppInForeground", value);
}
}
public function addListenerForStarterNotifications(listener:Function):void
{
if (this.isPushNotificationSupported)
{
this.addEventListener(PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT, listener);
extCtx.call("fetchStarterNotification");
}
}
// onStatus()
// Event handler for the event that the native implementation dispatches.
//
private function onStatus(e:StatusEvent):void
{
if (this.isPushNotificationSupported)
{
var event : PushNotificationEvent;
var data:String = e.level;
switch (e.code)
{
case "TOKEN_SUCCESS":
event = new PushNotificationEvent( PushNotificationEvent.PERMISSION_GIVEN_WITH_TOKEN_EVENT );
event.token = e.level;
break;
case "TOKEN_FAIL":
event = new PushNotificationEvent( PushNotificationEvent.PERMISSION_REFUSED_EVENT );
event.errorCode = "NativeCodeError";
event.errorMessage = e.level;
break;
case "COMING_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.COMING_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTING_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTED_IN_BACKGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.APP_STARTED_IN_BACKGROUND_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND":
event = new PushNotificationEvent( PushNotificationEvent.NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_SETTINGS_ENABLED":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_SETTINGS_ENABLED);
break;
case "NOTIFICATION_SETTINGS_DISABLED":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_SETTINGS_DISABLED);
break;
case "LOGGING":
trace(e, e.level);
break;
}
if (event != null)
{
this.dispatchEvent( event );
}
}
}
}
}
|
package com.freshplanet.nativeExtensions
{
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class PushNotification extends EventDispatcher
{
public static const RECURRENCE_NONE:int = 0;
public static const RECURRENCE_DAILY:int = 1;
public static const RECURRENCE_WEEK:int = 2;
public static const RECURRENCE_MONTH:int = 3;
public static const RECURRENCE_YEAR:int = 4;
public static const DEFAULT_LOCAL_NOTIFICATION_ID:int = 0;
private static var extCtx:ExtensionContext = null;
private static var _instance:PushNotification;
public function PushNotification()
{
if (!_instance)
{
if (this.isPushNotificationSupported)
{
extCtx = ExtensionContext.createExtensionContext("com.freshplanet.AirPushNotification", null);
if (extCtx != null)
{
extCtx.addEventListener(StatusEvent.STATUS, onStatus);
} else
{
trace('extCtx is null.');
}
}
_instance = this;
}
else
{
throw Error( 'This is a singleton, use getInstance, do not call the constructor directly');
}
}
public function get isPushNotificationSupported():Boolean
{
var result:Boolean = (Capabilities.manufacturer.search('iOS') > -1 || Capabilities.manufacturer.search('Android') > -1);
return result;
}
/**
* return true if notifs are enabled for this app in device settings
* If iOS < 8 or android < 4.1 this isn't available, so will always return true.
*/
public function get notificationsEnabled():Boolean
{
if(!isPushNotificationSupported) {
return false;
}
return extCtx.call("getNotificationsEnabled");
}
/**
* return true if OS permits sending user to settings (iOS 8, Android
*/
public function get canSendUserToSettings():Boolean
{
if(!isPushNotificationSupported) {
return false;
}
return extCtx.call("getCanSendUserToSettings");
}
public function openDeviceNotificationSettings():void
{
if(isPushNotificationSupported) {
extCtx.call("openDeviceNotificationSettings");
}
}
public static function getInstance() : PushNotification
{
return _instance ? _instance : new PushNotification();
}
/**
* Needs Project id for Android Notifications.
* The project id is the one the developer used to register to gcm.
* @param projectId: project id to use
*/
public function registerForPushNotification(projectId:String = null) : void
{
if (this.isPushNotificationSupported)
{
extCtx.call("registerPush", projectId);
}
}
public function setBadgeNumberValue(value:int):void
{
if (this.isPushNotificationSupported)
{
extCtx.call("setBadgeNb", value);
}
}
/**
* Sends a local notification to the device.
* @param message the local notification text displayed
* @param timestamp when the local notification should appear (in sec)
* @param title (Android Only) Title of the local notification
* @param recurrenceType
*
*/
public function sendLocalNotification(message:String, timestamp:int, title:String, recurrenceType:int = RECURRENCE_NONE, notificationId:int = DEFAULT_LOCAL_NOTIFICATION_ID):void
{
if (this.isPushNotificationSupported)
{
if (notificationId == DEFAULT_LOCAL_NOTIFICATION_ID)
{
extCtx.call("sendLocalNotification", message, timestamp, title, recurrenceType);
} else
{
extCtx.call("sendLocalNotification", message, timestamp, title, recurrenceType, notificationId);
}
}
}
/**
* Not implemented on Android for now.
* @param notificationId
*
*/
public function cancelLocalNotification(notificationId:int = DEFAULT_LOCAL_NOTIFICATION_ID):void
{
if (this.isPushNotificationSupported)
{
if (notificationId == DEFAULT_LOCAL_NOTIFICATION_ID)
{
extCtx.call("cancelLocalNotification");
} else
{
extCtx.call("cancelLocalNotification", notificationId);
}
}
}
public function cancelAllLocalNotifications():void
{
if(this.isPushNotificationSupported)
{
extCtx.call("cancelAllLocalNotifications");
}
}
public function setIsAppInForeground(value:Boolean):void
{
if (this.isPushNotificationSupported)
{
extCtx.call("setIsAppInForeground", value);
}
}
public function addListenerForStarterNotifications(listener:Function):void
{
if (this.isPushNotificationSupported)
{
this.addEventListener(PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT, listener);
extCtx.call("fetchStarterNotification");
}
}
// onStatus()
// Event handler for the event that the native implementation dispatches.
//
private function onStatus(e:StatusEvent):void
{
if (this.isPushNotificationSupported)
{
var event : PushNotificationEvent;
var data:String = e.level;
switch (e.code)
{
case "TOKEN_SUCCESS":
event = new PushNotificationEvent( PushNotificationEvent.PERMISSION_GIVEN_WITH_TOKEN_EVENT );
event.token = e.level;
break;
case "TOKEN_FAIL":
event = new PushNotificationEvent( PushNotificationEvent.PERMISSION_REFUSED_EVENT );
event.errorCode = "NativeCodeError";
event.errorMessage = e.level;
break;
case "COMING_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.COMING_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTING_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.APP_STARTING_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.APP_BROUGHT_TO_FOREGROUND_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "APP_STARTED_IN_BACKGROUND_FROM_NOTIFICATION":
event = new PushNotificationEvent( PushNotificationEvent.APP_STARTED_IN_BACKGROUND_FROM_NOTIFICATION_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND":
event = new PushNotificationEvent( PushNotificationEvent.NOTIFICATION_RECEIVED_WHEN_IN_FOREGROUND_EVENT );
if (data != null)
{
try
{
event.parameters = JSON.parse(data);
} catch (error:Error)
{
trace("[PushNotification Error]", "cannot parse the params string", data);
}
}
break;
case "NOTIFICATION_SETTINGS_ENABLED":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_SETTINGS_ENABLED);
break;
case "NOTIFICATION_SETTINGS_DISABLED":
event = new PushNotificationEvent(PushNotificationEvent.NOTIFICATION_SETTINGS_DISABLED);
break;
case "LOGGING":
trace(e, e.level);
break;
}
if (event != null)
{
this.dispatchEvent( event );
}
}
}
}
}
|
fix typo
|
fix typo
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-Push-Notification,StarIslandGames/ANE-Push-Notification,freshplanet/ANE-Push-Notification,freshplanet/ANE-Push-Notification,StarIslandGames/ANE-Push-Notification
|
0e0157a167b8430a31b711caf6eb9df9da987cd6
|
src/org/mangui/hls/HLSSettings.as
|
src/org/mangui/hls/HLSSettings.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // ///////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // ///////////////////////////////////
/**
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 60.
*/
public static var maxBufferLength : Number = 60;
/**
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3.
*/
public static var lowBufferLength : Number = 3;
/**
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
* HLSSeekMode.SEGMENT_SEEK - segment based seeking (seek to beginning of segment containing requested seek position)
*
* Default is HLSSeekMode.ACCURATE_SEEK.
*/
public static var seekMode : String = HLSSeekMode.ACCURATE_SEEK;
/** max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var keyLoadMaxRetry : int = -1;
/** keyLoadMaxRetryTimeout
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/** max nb of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var fragmentLoadMaxRetry : int = -1;
/** fragmentLoadMaxRetryTimeout
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var fragmentLoadMaxRetryTimeout : Number = 64000;
/**
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/** max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = -1;
/** manifestLoadMaxRetryTimeout
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*/
public static var startFromBitrate : Number = -1;
/** start level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
*/
public static var startFromLevel : Number = -1;
/** seek level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*/
public static var seekFromLevel : Number = -1;
/** use hardware video decoder :
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*/
public static var useHardwareVideoDecoder : Boolean = true;
/**
* Defines whether INFO level log messages will will appear in the console
* Default is true.
*/
public static var logInfo : Boolean = true;
/**
* Defines whether DEBUG level log messages will will appear in the console
* Default is false.
*/
public static var logDebug : Boolean = false;
/**
* Defines whether DEBUG2 level log messages will will appear in the console
* Default is false.
*/
public static var logDebug2 : Boolean = false;
/**
* Defines whether WARN level log messages will will appear in the console
* Default is true.
*/
public static var logWarn : Boolean = true;
/**
* Defines whether ERROR level log messages will will appear in the console
* Default is true.
*/
public static var logError : Boolean = true;
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // ///////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // ///////////////////////////////////
/**
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 60.
*/
public static var maxBufferLength : Number = 60;
/**
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3.
*/
public static var lowBufferLength : Number = 3;
/**
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
* HLSSeekMode.SEGMENT_SEEK - segment based seeking (seek to beginning of segment containing requested seek position)
*
* Default is HLSSeekMode.ACCURATE_SEEK.
*/
public static var seekMode : String = HLSSeekMode.ACCURATE_SEEK;
/** max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var keyLoadMaxRetry : int = -1;
/** keyLoadMaxRetryTimeout
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/** max nb of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var fragmentLoadMaxRetry : int = -1;
/** fragmentLoadMaxRetryTimeout
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var fragmentLoadMaxRetryTimeout : Number = 64000;
/**
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/** max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = -1;
/** manifestLoadMaxRetryTimeout
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*/
public static var startFromBitrate : Number = -1;
/** start level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
*/
public static var startFromLevel : Number = -1;
/** seek level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*/
public static var seekFromLevel : Number = -1;
/** use hardware video decoder :
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*/
public static var useHardwareVideoDecoder : Boolean = false;
/**
* Defines whether INFO level log messages will will appear in the console
* Default is true.
*/
public static var logInfo : Boolean = true;
/**
* Defines whether DEBUG level log messages will will appear in the console
* Default is false.
*/
public static var logDebug : Boolean = false;
/**
* Defines whether DEBUG2 level log messages will will appear in the console
* Default is false.
*/
public static var logDebug2 : Boolean = false;
/**
* Defines whether WARN level log messages will will appear in the console
* Default is true.
*/
public static var logWarn : Boolean = true;
/**
* Defines whether ERROR level log messages will will appear in the console
* Default is true.
*/
public static var logError : Boolean = true;
}
}
|
disable video hardware acceleration by default causing too much trouble :-(
|
disable video hardware acceleration by default
causing too much trouble :-(
|
ActionScript
|
mpl-2.0
|
Peer5/flashls,Corey600/flashls,suuhas/flashls,codex-corp/flashls,viktorot/flashls,aevange/flashls,NicolasSiver/flashls,viktorot/flashls,suuhas/flashls,School-Improvement-Network/flashls,aevange/flashls,Peer5/flashls,mangui/flashls,Boxie5/flashls,jlacivita/flashls,tedconf/flashls,aevange/flashls,Peer5/flashls,aevange/flashls,hola/flashls,viktorot/flashls,fixedmachine/flashls,loungelogic/flashls,School-Improvement-Network/flashls,dighan/flashls,School-Improvement-Network/flashls,fixedmachine/flashls,clappr/flashls,tedconf/flashls,Boxie5/flashls,vidible/vdb-flashls,mangui/flashls,JulianPena/flashls,hola/flashls,thdtjsdn/flashls,jlacivita/flashls,neilrackett/flashls,clappr/flashls,dighan/flashls,codex-corp/flashls,Peer5/flashls,Corey600/flashls,JulianPena/flashls,loungelogic/flashls,NicolasSiver/flashls,suuhas/flashls,suuhas/flashls,vidible/vdb-flashls,neilrackett/flashls,thdtjsdn/flashls
|
3892ffc056246ca46d5f2d7e2c6a9c65278678ed
|
src/aerys/minko/type/data/DataBindings.as
|
src/aerys/minko/type/data/DataBindings.as
|
package aerys.minko.type.data
{
import aerys.minko.type.Signal;
import flash.utils.Dictionary;
public class DataBindings
{
private var _bindingNames : Vector.<String> = new Vector.<String>();
private var _bindingNameToValue : Object = {};
private var _bindingNameToChangedSignal : Object = {};
private var _providerToBindingNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]]
private var _attributeToProviders : Dictionary = new Dictionary(); // dic[Vector.<IDataProvider>[]]
private var _attributeToProvidersAttrNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]]
private var _numProviders : uint = 0;
private var _providers : Vector.<DataProvider> = new <DataProvider>[];
public function get numProviders() : uint
{
return _numProviders;
}
public function get numProperties() : uint
{
return _bindingNames.length;
}
public function DataBindings()
{
}
public function add(provider : IDataProvider) : void
{
if (_providerToBindingNames[provider])
throw new Error('This provider is already binded');
var providerBindingNames : Vector.<String> = new Vector.<String>();
var dataDescriptor : Object = provider.dataDescriptor;
provider.changed.add(onProviderChange);
for (var attrName : String in dataDescriptor)
{
// if this provider attribute is also a dataprovider, let's also bind it
var bindingName : String = dataDescriptor[attrName];
var attribute : Object = provider[attrName]
var dpAttribute : IDataProvider = attribute as IDataProvider;
if (_bindingNames.indexOf(bindingName) != -1)
throw new Error('Another Dataprovider is already declaring "' + bindingName + '". Cannot overwrite.');
if (dpAttribute != null)
{
dpAttribute.changed.add(onProviderAttributeChange);
if (!_attributeToProviders[dpAttribute])
_attributeToProviders[dpAttribute] = new <IDataProvider>[];
if (!_attributeToProvidersAttrNames[dpAttribute])
_attributeToProvidersAttrNames[dpAttribute] = new <String>[];
_attributeToProviders[dpAttribute].push(provider);
_attributeToProvidersAttrNames[dpAttribute].push(attrName);
}
_bindingNameToValue[bindingName] = attribute;
providerBindingNames.push(bindingName);
_bindingNames.push(bindingName);
getPropertyChangedSignal(bindingName).execute(this, bindingName, attribute);
}
_providerToBindingNames[provider] = providerBindingNames;
_providers.push(provider);
++_numProviders;
}
public function remove(provider : IDataProvider) : void
{
var bindingNames : Vector.<String> = _providerToBindingNames[provider];
if (bindingNames == null)
throw new ArgumentError('No such provider was binded');
for each (var bindingName : String in bindingNames)
{
var indexOf : int = _bindingNames.indexOf(bindingName);
_bindingNames.splice(indexOf, 1);
if (_bindingNameToValue[bindingName] is IDataProvider)
IDataProvider(_bindingNameToValue[bindingName]).changed.remove(onProviderAttributeChange);
delete _bindingNameToValue[bindingName];
}
var attributesToDelete : Vector.<Object> = new Vector.<Object>();
for (var attribute : Object in _attributeToProviders)
{
var providers : Vector.<IDataProvider> = _attributeToProviders[attribute];
var attrNames : Vector.<String> = _attributeToProvidersAttrNames[attribute];
var indexOfProvider : int = providers.indexOf(provider);
if (indexOfProvider != -1)
{
providers.splice(indexOfProvider, 1);
attrNames.splice(indexOfProvider, 1);
}
if (providers.length == 0)
attributesToDelete.push(attribute);
}
for (var attributeToDelete : Object in attributesToDelete)
{
delete _attributeToProviders[attributeToDelete];
delete _attributeToProvidersAttrNames[attributeToDelete];
}
provider.changed.remove(onProviderChange);
--_numProviders;
_providers.splice(_providers.indexOf(provider), 1);
delete _providerToBindingNames[provider];
for each (bindingName in bindingNames)
getPropertyChangedSignal(bindingName).execute(this, bindingName, null);
}
public function getDataProviderAt(index : uint) : DataProvider
{
if (index >= _numProviders)
throw new ArgumentError('Index out of bounds.');
return _providers[index];
}
public function getPropertyChangedSignal(bindingName : String) : Signal
{
if (!_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName] = new Signal('DataBindings.changed[' + bindingName + ']');
return _bindingNameToChangedSignal[bindingName];
}
public function propertyExists(bindingName : String) : Boolean
{
return _bindingNameToValue.hasOwnProperty(bindingName);
}
public function getProperty(bindingName : String) : *
{
return _bindingNameToValue[bindingName];
}
public function getPropertyName(bindingIndex : uint) : String
{
if (bindingIndex > numProperties)
throw new ArgumentError('No such binding');
return _bindingNames[bindingIndex];
}
/**
* A provider attribute has changed, and the provider tells us.
* For example, camera.fov has changed, the camera dispatches a 'changed' signal with 'fov' as attributeName.
*
* It could also be that camera.localToWorld has been replaced by another matrix instance.
*/
private function onProviderChange(source : IDataProvider, attributeName : String) : void
{
if (attributeName == null)
{
throw new Error('DataProviders must change one property at a time.');
}
else if (attributeName == 'dataDescriptor')
{
remove(source);
add(source);
}
else
{
var bindingName : String = source.dataDescriptor[attributeName];
var oldDpValue : IDataProvider = _bindingNameToValue[bindingName] as IDataProvider;
var newValue : Object = source[attributeName];
var newDpValue : IDataProvider = newValue as IDataProvider;
// we are replacing a data provider. We must remove listeners and related mapping keys
if (oldDpValue != null)
{
oldDpValue.changed.remove(onProviderAttributeChange);
var providers : Vector.<IDataProvider> = _attributeToProviders[oldDpValue];
var attrNames : Vector.<String> = _attributeToProvidersAttrNames[oldDpValue];
if (providers.length == 1)
{
delete _attributeToProviders[oldDpValue];
delete _attributeToProvidersAttrNames[oldDpValue];
}
else
{
var index : uint = providers.indexOf(source);
providers.splice(index, 1);
attrNames.splice(index, 1);
}
}
// the new value for this key is a dataprovider, we must listen changes.
if (newDpValue != null)
{
newDpValue.changed.add(onProviderAttributeChange);
if (!_attributeToProviders[newDpValue])
_attributeToProviders[newDpValue] = new <IDataProvider>[];
if (!_attributeToProvidersAttrNames[newDpValue])
_attributeToProvidersAttrNames[newDpValue] = new <String>[];
_attributeToProviders[newDpValue].push(source);
_attributeToProvidersAttrNames[newDpValue].push(attributeName);
}
_bindingNameToValue[bindingName] = newValue;
getPropertyChangedSignal(bindingName).execute(this, bindingName, newValue);
}
}
/**
* A provider attribute has changed, and the attribute tells us.
* For example, camera.localToWorld has been updated.
*/
private function onProviderAttributeChange(source : IDataProvider, key : String) : void
{
var providers : Vector.<IDataProvider> = _attributeToProviders[source];
var attrNames : Vector.<String> = _attributeToProvidersAttrNames[source];
var numProviders : uint = providers.length;
for (var providerId : uint = 0; providerId < numProviders; ++providerId)
{
var provider : IDataProvider = providers[providerId];
var attrName : String = attrNames[providerId];
var bindingName : String = provider.dataDescriptor[attrName];
getPropertyChangedSignal(bindingName).execute(this, bindingName, source);
}
}
}
}
|
package aerys.minko.type.data
{
import aerys.minko.type.Signal;
import flash.utils.Dictionary;
public class DataBindings
{
private var _bindingNames : Vector.<String> = new Vector.<String>();
private var _bindingNameToValue : Object = {};
private var _bindingNameToChangedSignal : Object = {};
private var _providerToBindingNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]]
private var _attributeToProviders : Dictionary = new Dictionary(); // dic[Vector.<IDataProvider>[]]
private var _attributeToProvidersAttrNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]]
private var _numProviders : uint = 0;
private var _providers : Vector.<IDataProvider> = new <IDataProvider>[];
public function get numProviders() : uint
{
return _numProviders;
}
public function get numProperties() : uint
{
return _bindingNames.length;
}
public function DataBindings()
{
}
public function add(provider : IDataProvider) : void
{
if (_providerToBindingNames[provider])
throw new Error('This provider is already binded');
var providerBindingNames : Vector.<String> = new Vector.<String>();
var dataDescriptor : Object = provider.dataDescriptor;
provider.changed.add(onProviderChange);
for (var attrName : String in dataDescriptor)
{
// if this provider attribute is also a dataprovider, let's also bind it
var bindingName : String = dataDescriptor[attrName];
var attribute : Object = provider[attrName]
var dpAttribute : IDataProvider = attribute as IDataProvider;
if (_bindingNames.indexOf(bindingName) != -1)
throw new Error('Another Dataprovider is already declaring "' + bindingName + '". Cannot overwrite.');
if (dpAttribute != null)
{
dpAttribute.changed.add(onProviderAttributeChange);
if (!_attributeToProviders[dpAttribute])
_attributeToProviders[dpAttribute] = new <IDataProvider>[];
if (!_attributeToProvidersAttrNames[dpAttribute])
_attributeToProvidersAttrNames[dpAttribute] = new <String>[];
_attributeToProviders[dpAttribute].push(provider);
_attributeToProvidersAttrNames[dpAttribute].push(attrName);
}
_bindingNameToValue[bindingName] = attribute;
providerBindingNames.push(bindingName);
_bindingNames.push(bindingName);
getPropertyChangedSignal(bindingName).execute(this, bindingName, attribute);
}
_providerToBindingNames[provider] = providerBindingNames;
_providers.push(provider);
++_numProviders;
}
public function remove(provider : IDataProvider) : void
{
var bindingNames : Vector.<String> = _providerToBindingNames[provider];
if (bindingNames == null)
throw new ArgumentError('No such provider was binded');
for each (var bindingName : String in bindingNames)
{
var indexOf : int = _bindingNames.indexOf(bindingName);
_bindingNames.splice(indexOf, 1);
if (_bindingNameToValue[bindingName] is IDataProvider)
IDataProvider(_bindingNameToValue[bindingName]).changed.remove(onProviderAttributeChange);
delete _bindingNameToValue[bindingName];
}
var attributesToDelete : Vector.<Object> = new Vector.<Object>();
for (var attribute : Object in _attributeToProviders)
{
var providers : Vector.<IDataProvider> = _attributeToProviders[attribute];
var attrNames : Vector.<String> = _attributeToProvidersAttrNames[attribute];
var indexOfProvider : int = providers.indexOf(provider);
if (indexOfProvider != -1)
{
providers.splice(indexOfProvider, 1);
attrNames.splice(indexOfProvider, 1);
}
if (providers.length == 0)
attributesToDelete.push(attribute);
}
for (var attributeToDelete : Object in attributesToDelete)
{
delete _attributeToProviders[attributeToDelete];
delete _attributeToProvidersAttrNames[attributeToDelete];
}
provider.changed.remove(onProviderChange);
--_numProviders;
_providers.splice(_providers.indexOf(provider), 1);
delete _providerToBindingNames[provider];
for each (bindingName in bindingNames)
getPropertyChangedSignal(bindingName).execute(this, bindingName, null);
}
public function getDataProviderAt(index : uint) : IDataProvider
{
if (index >= _numProviders)
throw new ArgumentError('Index out of bounds.');
return _providers[index];
}
public function getPropertyChangedSignal(bindingName : String) : Signal
{
if (!_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName] = new Signal('DataBindings.changed[' + bindingName + ']');
return _bindingNameToChangedSignal[bindingName];
}
public function propertyExists(bindingName : String) : Boolean
{
return _bindingNameToValue.hasOwnProperty(bindingName);
}
public function getProperty(bindingName : String) : *
{
return _bindingNameToValue[bindingName];
}
public function getPropertyName(bindingIndex : uint) : String
{
if (bindingIndex > numProperties)
throw new ArgumentError('No such binding');
return _bindingNames[bindingIndex];
}
/**
* A provider attribute has changed, and the provider tells us.
* For example, camera.fov has changed, the camera dispatches a 'changed' signal with 'fov' as attributeName.
*
* It could also be that camera.localToWorld has been replaced by another matrix instance.
*/
private function onProviderChange(source : IDataProvider, attributeName : String) : void
{
if (attributeName == null)
{
throw new Error('DataProviders must change one property at a time.');
}
else if (attributeName == 'dataDescriptor')
{
remove(source);
add(source);
}
else
{
var bindingName : String = source.dataDescriptor[attributeName];
var oldDpValue : IDataProvider = _bindingNameToValue[bindingName] as IDataProvider;
var newValue : Object = source[attributeName];
var newDpValue : IDataProvider = newValue as IDataProvider;
// we are replacing a data provider. We must remove listeners and related mapping keys
if (oldDpValue != null)
{
oldDpValue.changed.remove(onProviderAttributeChange);
var providers : Vector.<IDataProvider> = _attributeToProviders[oldDpValue];
var attrNames : Vector.<String> = _attributeToProvidersAttrNames[oldDpValue];
if (providers.length == 1)
{
delete _attributeToProviders[oldDpValue];
delete _attributeToProvidersAttrNames[oldDpValue];
}
else
{
var index : uint = providers.indexOf(source);
providers.splice(index, 1);
attrNames.splice(index, 1);
}
}
// the new value for this key is a dataprovider, we must listen changes.
if (newDpValue != null)
{
newDpValue.changed.add(onProviderAttributeChange);
if (!_attributeToProviders[newDpValue])
_attributeToProviders[newDpValue] = new <IDataProvider>[];
if (!_attributeToProvidersAttrNames[newDpValue])
_attributeToProvidersAttrNames[newDpValue] = new <String>[];
_attributeToProviders[newDpValue].push(source);
_attributeToProvidersAttrNames[newDpValue].push(attributeName);
}
_bindingNameToValue[bindingName] = newValue;
getPropertyChangedSignal(bindingName).execute(this, bindingName, newValue);
}
}
/**
* A provider attribute has changed, and the attribute tells us.
* For example, camera.localToWorld has been updated.
*/
private function onProviderAttributeChange(source : IDataProvider, key : String) : void
{
var providers : Vector.<IDataProvider> = _attributeToProviders[source];
var attrNames : Vector.<String> = _attributeToProvidersAttrNames[source];
var numProviders : uint = providers.length;
for (var providerId : uint = 0; providerId < numProviders; ++providerId)
{
var provider : IDataProvider = providers[providerId];
var attrName : String = attrNames[providerId];
var bindingName : String = provider.dataDescriptor[attrName];
getPropertyChangedSignal(bindingName).execute(this, bindingName, source);
}
}
}
}
|
Fix getDataProviderAt
|
Fix getDataProviderAt
M Change _providers type from vector.<DataProvider> into
vector.<IDataProvider>
|
ActionScript
|
mit
|
aerys/minko-as3
|
a3add8259ba97518f8d0c84653cbd42a48643ac2
|
test/src/FRESteamWorksTest.as
|
test/src/FRESteamWorksTest.as
|
/*
* FRESteamWorks.h
* This file is part of FRESteamWorks.
*
* Created by David ´Oldes´ Oliva on 3/29/12.
* Contributors: Ventero <http://github.com/Ventero>
* Copyright (c) 2012 Amanita Design. All rights reserved.
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package
{
import com.amanitadesign.steam.FRESteamWorks;
import com.amanitadesign.steam.SteamConstants;
import com.amanitadesign.steam.SteamEvent;
import com.amanitadesign.steam.WorkshopConstants;
import flash.desktop.NativeApplication;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.display.StageDisplayState;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.utils.ByteArray;
public class FRESteamWorksTest extends Sprite
{
public var Steamworks:FRESteamWorks = new FRESteamWorks();
public var tf:TextField;
private var _buttonPos:int = 5;
private var _appId:uint;
public function FRESteamWorksTest()
{
tf = new TextField();
tf.x = 160;
tf.width = stage.stageWidth - tf.x;
tf.height = stage.stageHeight;
addChild(tf);
addButton("Check stats/achievements", checkAchievements);
addButton("Toggle achievement", toggleAchievement);
addButton("Toggle cloud enabled", toggleCloudEnabled);
addButton("Toggle file", toggleFile);
addButton("Publish file", publishFile);
addButton("Toggle fullscreen", toggleFullscreen);
addButton("Show Friends overlay", activateOverlay);
addButton("List subscribed files", enumerateSubscribedFiles);
addButton("List shared files", enumerateSharedFiles);
addButton("List workshop files", enumerateWorkshopFiles);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
Steamworks.addOverlayWorkaround(stage, true);
NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit);
try {
//Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20");
if(!Steamworks.init()){
log("STEAMWORKS API is NOT available");
return;
}
log("STEAMWORKS API is available\n");
log("User ID: " + Steamworks.getUserID());
_appId = Steamworks.getAppID();
log("App ID: " + _appId);
log("Persona name: " + Steamworks.getPersonaName());
log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp());
log("getFileCount() == "+Steamworks.getFileCount());
log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt'));
log("getDLCCount() == " + Steamworks.getDLCCount());
Steamworks.resetAllStats(true);
} catch(e:Error) {
log("*** ERROR ***");
log(e.message);
log(e.getStackTrace());
}
}
private function log(value:String):void{
tf.appendText(value+"\n");
tf.scrollV = tf.maxScrollV;
}
public function writeFileToCloud(fileName:String, data:String):Boolean {
var dataOut:ByteArray = new ByteArray();
dataOut.writeUTFBytes(data);
return Steamworks.fileWrite(fileName, dataOut);
}
public function readFileFromCloud(fileName:String):String {
var dataIn:ByteArray = new ByteArray();
var result:String;
dataIn.position = 0;
dataIn.length = Steamworks.getFileSize(fileName);
if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){
result = dataIn.readUTFBytes(dataIn.length);
}
return result;
}
private function checkAchievements(e:Event = null):void {
if(!Steamworks.isReady) return;
// current stats and achievement ids are from steam example app
log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME"));
log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE"));
log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3));
log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2));
Steamworks.storeStats();
log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames'));
log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled'));
}
private function toggleAchievement(e:Event = null):void{
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME");
log("isAchievement('ACH_WIN_ONE_GAME') == " + result);
if(!result) {
log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME"));
} else {
log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME"));
}
}
private function toggleCloudEnabled(e:Event = null):void {
if(!Steamworks.isReady) return;
var enabled:Boolean = Steamworks.isCloudEnabledForApp();
log("isCloudEnabledForApp() == " + enabled);
log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled));
log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp());
}
private function toggleFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.fileExists('test.txt');
log("fileExists('test.txt') == " + result);
if(result){
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt'));
} else {
log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click'));
}
}
private function publishFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId,
"Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private,
["TestTag"], WorkshopConstants.FILETYPE_Community);
log("publishWorkshopFile('test.txt' ...) == " + res);
}
private function toggleFullscreen(e:Event = null):void {
if(stage.displayState == StageDisplayState.NORMAL)
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
else
stage.displayState = StageDisplayState.NORMAL;
}
private function activateOverlay(e:Event = null):void {
if(!Steamworks.isReady) return;
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends"));
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
}
private function enumerateSubscribedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0));
}
private function enumerateSharedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
var userID:String = Steamworks.getUserID();
var res:Boolean = Steamworks.enumerateUserSharedWorkshopFiles(userID, 0, [], []);
log("enumerateSharedFiles(" + userID + ", 0, [], []) == " + res);
}
private function enumerateWorkshopFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.enumeratePublishedWorkshopFiles(
WorkshopConstants.ENUMTYPE_RankedByVote, 0, 10, 0, [], []);
log("enumerateSharedFiles(...) == " + res);
}
private var id:String;
private var handle:String;
private function onSteamResponse(e:SteamEvent):void{
var apiCall:Boolean;
var i:int;
switch(e.req_type){
case SteamConstants.RESPONSE_OnUserStatsStored:
log("RESPONSE_OnUserStatsStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnUserStatsReceived:
log("RESPONSE_OnUserStatsReceived: "+e.response);
break;
case SteamConstants.RESPONSE_OnAchievementStored:
log("RESPONSE_OnAchievementStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnPublishWorkshopFile:
log("RESPONSE_OnPublishWorkshopFile: " + e.response);
var file:String = Steamworks.publishWorkshopFileResult();
log("File published as " + file);
log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file));
break;
case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles:
log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response);
var subRes:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult();
log("User subscribed files: " + subRes.resultsReturned + "/" + subRes.totalResults);
for(i = 0; i < subRes.resultsReturned; i++) {
id = subRes.publishedFileId[i];
apiCall = Steamworks.getPublishedFileDetails(subRes.publishedFileId[i]);
log(i + ": " + subRes.publishedFileId[i] + " (" + subRes.timeSubscribed[i] + ") - " + apiCall);
}
break;
case SteamConstants.RESPONSE_OnEnumerateUserSharedWorkshopFiles:
log("RESPONSE_OnEnumerateUserSharedWorkshopFiles: " + e.response);
var userRes:UserFilesResult = Steamworks.enumerateUserSharedWorkshopFilesResult();
log("User shared files: " + userRes.resultsReturned + "/" + userRes.totalResults);
for(i = 0; i < userRes.resultsReturned; i++) {
log(i + ": " + userRes.publishedFileId[i]);
}
break;
case SteamConstants.RESPONSE_OnEnumeratePublishedWorkshopFiles:
log("RESPONSE_OnEnumeratePublishedWorkshopFiles: " + e.response);
var fileRes:WorkshopFilesResult = Steamworks.enumeratePublishedWorkshopFilesResult();
log("Workshop files: " + fileRes.resultsReturned + "/" + fileRes.totalResults);
for(i = 0; i < fileRes.resultsReturned; i++) {
log(i + ": " + fileRes.publishedFileId[i] + " - " + fileRes.score[i]);
}
break;
case SteamConstants.RESPONSE_OnGetPublishedFileDetails:
log("RESPONSE_OnGetPublishedFileDetails: " + e.response);
var res:FileDetailsResult = Steamworks.getPublishedFileDetailsResult(id);
log("Result for " + id + ": " + res);
if(res) {
log("File: " + res.fileName + ", handle: " + res.fileHandle);
handle = res.fileHandle;
apiCall = Steamworks.UGCDownload(res.fileHandle, 0);
log("UGCDownload(...) == " + apiCall);
}
break;
case SteamConstants.RESPONSE_OnUGCDownload:
log("RESPONSE_OnUGCDownload: " + e.response);
var ugcResult:DownloadUGCResult = Steamworks.getUGCDownloadResult(handle);
log("Result for " + handle + ": " + ugcResult);
if(ugcResult) {
log("File: " + ugcResult.fileName + ", handle: " + ugcResult.fileHandle + ", size: " + ugcResult.size);
var ba:ByteArray = new ByteArray();
ba.length = ugcResult.size;
apiCall = Steamworks.UGCRead(ugcResult.fileHandle, ugcResult.size, 0, ba);
log("UGCRead(...) == " + apiCall);
if(apiCall) {
log("Result length: " + ba.position + "//" + ba.length);
log("Result: " + ba.readUTFBytes(ugcResult.size));
}
}
break;
default:
log("STEAMresponse type:"+e.req_type+" response:"+e.response);
}
}
private function onExit(e:Event):void{
log("Exiting application, cleaning up");
Steamworks.dispose();
}
private function addButton(label:String, callback:Function):void {
var button:Sprite = new Sprite();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
button.buttonMode = true;
button.useHandCursor = true;
button.addEventListener(MouseEvent.CLICK, callback);
button.x = 5;
button.y = _buttonPos;
_buttonPos += button.height + 5;
button.addEventListener(MouseEvent.MOUSE_OVER, function(e:MouseEvent):void {
button.graphics.clear();
button.graphics.beginFill(0xccccccc);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
});
button.addEventListener(MouseEvent.MOUSE_OUT, function(e:MouseEvent):void {
button.graphics.clear();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
});
var text:TextField = new TextField();
text.text = label;
text.width = 140;
text.height = 25;
text.x = 5;
text.y = 5;
text.mouseEnabled = false;
button.addChild(text);
addChild(button);
}
}
}
|
/*
* FRESteamWorks.h
* This file is part of FRESteamWorks.
*
* Created by David ´Oldes´ Oliva on 3/29/12.
* Contributors: Ventero <http://github.com/Ventero>
* Copyright (c) 2012 Amanita Design. All rights reserved.
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package
{
import com.amanitadesign.steam.FRESteamWorks;
import com.amanitadesign.steam.SteamConstants;
import com.amanitadesign.steam.SteamEvent;
import com.amanitadesign.steam.WorkshopConstants;
import flash.desktop.NativeApplication;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.display.StageDisplayState;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.utils.ByteArray;
public class FRESteamWorksTest extends Sprite
{
public var Steamworks:FRESteamWorks = new FRESteamWorks();
public var tf:TextField;
private var _buttonPos:int = 5;
private var _appId:uint;
public function FRESteamWorksTest()
{
tf = new TextField();
tf.x = 160;
tf.width = stage.stageWidth - tf.x;
tf.height = stage.stageHeight;
addChild(tf);
addButton("Check stats/achievements", checkAchievements);
addButton("Toggle achievement", toggleAchievement);
addButton("Toggle cloud enabled", toggleCloudEnabled);
addButton("Toggle file", toggleFile);
addButton("Publish file", publishFile);
addButton("Toggle fullscreen", toggleFullscreen);
addButton("Show Friends overlay", activateOverlay);
addButton("List subscribed files", enumerateSubscribedFiles);
addButton("List shared files", enumerateSharedFiles);
addButton("List workshop files", enumerateWorkshopFiles);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
Steamworks.addOverlayWorkaround(stage, true);
NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit);
try {
//Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20");
if(!Steamworks.init()){
log("STEAMWORKS API is NOT available");
return;
}
log("STEAMWORKS API is available\n");
log("User ID: " + Steamworks.getUserID());
_appId = Steamworks.getAppID();
log("App ID: " + _appId);
log("Persona name: " + Steamworks.getPersonaName());
log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp());
log("getFileCount() == "+Steamworks.getFileCount());
log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt'));
log("getDLCCount() == " + Steamworks.getDLCCount());
Steamworks.resetAllStats(true);
} catch(e:Error) {
log("*** ERROR ***");
log(e.message);
log(e.getStackTrace());
}
}
private function log(value:String):void{
tf.appendText(value+"\n");
tf.scrollV = tf.maxScrollV;
}
public function writeFileToCloud(fileName:String, data:String):Boolean {
var dataOut:ByteArray = new ByteArray();
dataOut.writeUTFBytes(data);
return Steamworks.fileWrite(fileName, dataOut);
}
public function readFileFromCloud(fileName:String):String {
var dataIn:ByteArray = new ByteArray();
var result:String;
dataIn.position = 0;
dataIn.length = Steamworks.getFileSize(fileName);
if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){
result = dataIn.readUTFBytes(dataIn.length);
}
return result;
}
private function checkAchievements(e:Event = null):void {
if(!Steamworks.isReady) return;
// current stats and achievement ids are from steam example app
log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME"));
log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE"));
log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3));
log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2));
Steamworks.storeStats();
log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames'));
log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled'));
}
private function toggleAchievement(e:Event = null):void{
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME");
log("isAchievement('ACH_WIN_ONE_GAME') == " + result);
if(!result) {
log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME"));
} else {
log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME"));
}
}
private function toggleCloudEnabled(e:Event = null):void {
if(!Steamworks.isReady) return;
var enabled:Boolean = Steamworks.isCloudEnabledForApp();
log("isCloudEnabledForApp() == " + enabled);
log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled));
log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp());
}
private function toggleFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.fileExists('test.txt');
log("fileExists('test.txt') == " + result);
if(result){
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt'));
} else {
log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click'));
}
}
private function publishFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId,
"Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private,
["TestTag"], WorkshopConstants.FILETYPE_Community);
log("publishWorkshopFile('test.txt' ...) == " + res);
}
private function toggleFullscreen(e:Event = null):void {
if(stage.displayState == StageDisplayState.NORMAL)
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
else
stage.displayState = StageDisplayState.NORMAL;
}
private function activateOverlay(e:Event = null):void {
if(!Steamworks.isReady) return;
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends"));
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
}
private function enumerateSubscribedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0));
}
private function enumerateSharedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
var userID:String = Steamworks.getUserID();
var res:Boolean = Steamworks.enumerateUserSharedWorkshopFiles(userID, 0, [], []);
log("enumerateSharedFiles(" + userID + ", 0, [], []) == " + res);
}
private function enumerateWorkshopFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.enumeratePublishedWorkshopFiles(
WorkshopConstants.ENUMTYPE_RankedByVote, 0, 10, 0, [], []);
log("enumerateSharedFiles(...) == " + res);
}
private var id:String;
private var handle:String;
private function onSteamResponse(e:SteamEvent):void{
var apiCall:Boolean;
var i:int;
var file:String;
switch(e.req_type){
case SteamConstants.RESPONSE_OnUserStatsStored:
log("RESPONSE_OnUserStatsStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnUserStatsReceived:
log("RESPONSE_OnUserStatsReceived: "+e.response);
break;
case SteamConstants.RESPONSE_OnAchievementStored:
log("RESPONSE_OnAchievementStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnPublishWorkshopFile:
log("RESPONSE_OnPublishWorkshopFile: " + e.response);
file = Steamworks.publishWorkshopFileResult();
log("File published as " + file);
log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file));
break;
case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles:
log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response);
var subRes:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult();
log("User subscribed files: " + subRes.resultsReturned + "/" + subRes.totalResults);
for(i = 0; i < subRes.resultsReturned; i++) {
id = subRes.publishedFileId[i];
apiCall = Steamworks.getPublishedFileDetails(subRes.publishedFileId[i]);
log(i + ": " + subRes.publishedFileId[i] + " (" + subRes.timeSubscribed[i] + ") - " + apiCall);
}
break;
case SteamConstants.RESPONSE_OnEnumerateUserSharedWorkshopFiles:
log("RESPONSE_OnEnumerateUserSharedWorkshopFiles: " + e.response);
var userRes:UserFilesResult = Steamworks.enumerateUserSharedWorkshopFilesResult();
log("User shared files: " + userRes.resultsReturned + "/" + userRes.totalResults);
for(i = 0; i < userRes.resultsReturned; i++) {
log(i + ": " + userRes.publishedFileId[i]);
}
break;
case SteamConstants.RESPONSE_OnEnumeratePublishedWorkshopFiles:
log("RESPONSE_OnEnumeratePublishedWorkshopFiles: " + e.response);
var fileRes:WorkshopFilesResult = Steamworks.enumeratePublishedWorkshopFilesResult();
log("Workshop files: " + fileRes.resultsReturned + "/" + fileRes.totalResults);
for(i = 0; i < fileRes.resultsReturned; i++) {
log(i + ": " + fileRes.publishedFileId[i] + " - " + fileRes.score[i]);
}
if(fileRes.resultsReturned > 0) {
file = fileRes.publishedFileId[0];
log("updateUserPublishedItemVote(" + file + ", true)");
apiCall = Steamworks.updateUserPublishedItemVote(file, true);
log("updateUserPublishedItemVote(" + file + ", true) == " + apiCall);
}
break;
case SteamConstants.RESPONSE_OnGetPublishedFileDetails:
log("RESPONSE_OnGetPublishedFileDetails: " + e.response);
var res:FileDetailsResult = Steamworks.getPublishedFileDetailsResult(id);
log("Result for " + id + ": " + res);
if(res) {
log("File: " + res.fileName + ", handle: " + res.fileHandle);
handle = res.fileHandle;
apiCall = Steamworks.UGCDownload(res.fileHandle, 0);
log("UGCDownload(...) == " + apiCall);
}
break;
case SteamConstants.RESPONSE_OnUGCDownload:
log("RESPONSE_OnUGCDownload: " + e.response);
var ugcResult:DownloadUGCResult = Steamworks.getUGCDownloadResult(handle);
log("Result for " + handle + ": " + ugcResult);
if(ugcResult) {
log("File: " + ugcResult.fileName + ", handle: " + ugcResult.fileHandle + ", size: " + ugcResult.size);
var ba:ByteArray = new ByteArray();
ba.length = ugcResult.size;
apiCall = Steamworks.UGCRead(ugcResult.fileHandle, ugcResult.size, 0, ba);
log("UGCRead(...) == " + apiCall);
if(apiCall) {
log("Result length: " + ba.position + "//" + ba.length);
log("Result: " + ba.readUTFBytes(ugcResult.size));
}
}
break;
default:
log("STEAMresponse type:"+e.req_type+" response:"+e.response);
}
}
private function onExit(e:Event):void{
log("Exiting application, cleaning up");
Steamworks.dispose();
}
private function addButton(label:String, callback:Function):void {
var button:Sprite = new Sprite();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
button.buttonMode = true;
button.useHandCursor = true;
button.addEventListener(MouseEvent.CLICK, callback);
button.x = 5;
button.y = _buttonPos;
_buttonPos += button.height + 5;
button.addEventListener(MouseEvent.MOUSE_OVER, function(e:MouseEvent):void {
button.graphics.clear();
button.graphics.beginFill(0xccccccc);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
});
button.addEventListener(MouseEvent.MOUSE_OUT, function(e:MouseEvent):void {
button.graphics.clear();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
});
var text:TextField = new TextField();
text.text = label;
text.width = 140;
text.height = 25;
text.x = 5;
text.y = 5;
text.mouseEnabled = false;
button.addChild(text);
addChild(button);
}
}
}
|
Add test for updateUserPublishedItemVote
|
Add test for updateUserPublishedItemVote
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
d4252633db7f53bbd5ee11b3b9c8945948f0836c
|
resources/neurosky/FlashToJs/DisplayWindow.as
|
resources/neurosky/FlashToJs/DisplayWindow.as
|
package
{
import flash.display.*;
import flash.events.*;//for event handling
import flash.net.Socket;//Sockets
import flash.utils.*;
import flash.external.ExternalInterface;
import flash.system.*;
import com.adobe.serialization.json.*;//as3corelib JSON support
public class DisplayWindow extends Sprite
{
// Public Properties:
public var attention:uint;
public var meditation:uint;
public var blink:uint;
public var poorSignal:uint;
public var myTimer:Timer;
public var jsTimer:Timer;
public var timeCount:uint;
public var hasStarted:Boolean;
// Private Properties:
private var thinkGearSocket:Socket;
public function DisplayWindow()
{
Security.allowDomain("*");
var self = this;
hasStarted = false;
//To run the ThinkGear software without waiting for the JS, uncomment the line below
//startThinkGearSocket();
//Before the application tries to connect to the ThinkGearSocket, make sure JS is available
waitForJs();
}
private function startThinkGearSocket()
{
if (! hasStarted)
{
hasStarted = true;
log("Preparing ThinkGear...");
thinkGearSocket = new Socket();
thinkGearSocket.addEventListener(ProgressEvent.SOCKET_DATA,dataHandler);
thinkGearSocket.addEventListener(ProgressEvent.PROGRESS,progressHandler);
thinkGearSocket.connect("127.0.0.1",13854);
if (thinkGearSocket.connected)
{
log("ThinkGear connected. Configuring...");
}
else
{
log("ThinkGear not connected. Configuring anyway...");
}
var configuration:Object = new Object();
configuration["enableRawOutput"] = false;
configuration["format"] = "Json";
thinkGearSocket.writeUTFBytes(JSON.encode(configuration));
}
else
{
log("thinkGearSocket has already started");
}
}
// Protected Methods:;
private function progressHandler(e:ProgressEvent)
{
if (thinkGearSocket.connected)
{
log("ThinkGear connected. ProgressEvent occurred.");
}
else
{
log("ThinkGear not connected. ProgressEvent occurred.");
}
}
private function dataHandler(e:ProgressEvent)
{
if (thinkGearSocket.connected)
{
log("ThinkGear connected. Receiving data.");
}
else
{
log("ThinkGear not connected. Receiving data.");
}
var packetString:String = thinkGearSocket.readUTFBytes(thinkGearSocket.bytesAvailable);
if ((packetString == null))
{
log("packetString is NULL");
}
thinkGearSocket.flush();
log("ThinkGearSocket flushed");
var packets:Array = packetString.split(/\r/);
log(("Packets length: " + packets.length));
var data:Object;//temporary data
for each (var packet:String in packets)
{//iterate through each element
if ((packet != ""))
{//sometimes the line is blank so skip the line
try
{
log("Packet: "+packet);
data = JSON.decode(packet);
//decode the data to an array
if (data["poorSignalLevel"] != null)
{//checking to see if the ''poorSignalLevel' key exists
poorSignal = data["poorSignalLevel"];
if ((poorSignal == 0))
{
attention = data["eSense"]["attention"];//assigning data to variables
meditation = data["eSense"]["meditation"];
blink = data["blinkStrength"];
//log("Attention: " + attention);//output attention data to debug
}
else
{
if ((poorSignal == 200))
{
attention = 0;
meditation = 0;
blink = 0;
if (!data["eSense"])
poorSignal = 250;
}
}
}
label1.text = "Attention: " + attention.toString() + "\nMeditation: " + meditation.toString() + "\nPoor Signal: " + poorSignal.toString() + "\nblinkStrength: " + blink.toString();
sendDataToJavaScript(poorSignal,attention,meditation,blink);
}
catch (jError:JSONParseError)
{
log("there was a JSONParseError: " + packet);
// restart a connection at first error :(
hasStarted = false;
thinkGearSocket.close();
startThinkGearSocket();
sendDataToJavaScript(250, 0, 0, 0);
return;
}
} else log("empty packet");
data = null;
}/*for each*/
}/*function dataHandler*/
/**
* iconLevel is the poor signal value
* attentionLevel is the attention value
* meditationLevel is the meditation value
* There may be some need to check the types of these values, because they are not all
* being passed to the Javascript, from what I can tell
*/
public function sendDataToJavaScript(iconLevel:uint,attentionLevel:uint,meditationLevel:uint,blinkStrength:uint)
{
if (ExternalInterface.available)
{
ExternalInterface.call("MindWave.setSignalValue",iconLevel);
ExternalInterface.call("MindWave.setAttentionLevel",attentionLevel);
ExternalInterface.call("MindWave.setMeditationLevel",meditationLevel);
ExternalInterface.call("MindWave.setBlinkStrength",blinkStrength);
}
else
{
log("ExternalInterface is not available to send data to JS");
}
}
public function checkJs(event:TimerEvent)
{
log("Checking javascript...");
if (ExternalInterface.available)
{
var jsReady:Boolean = ExternalInterface.call("isReady");
if (jsReady)
{
jsTimer.stop();
startThinkGearSocket();
}
else
{
log("JS is not Ready");
}
} else {
log("No JS interface...");
}
}
public function checkJsStopped(event:TimerEvent)
{
log("Javascript connection was not established");
}
private function waitForJs()
{
jsTimer = new Timer(1000,100);
jsTimer.addEventListener(TimerEvent.TIMER,checkJs);
jsTimer.addEventListener(TimerEvent.TIMER_COMPLETE,checkJsStopped);
jsTimer.start();
}
private function receivedFromJavaScript(value:String):void
{
log((("JavaScript says: " + value) + "\n"));
}
private function checkJavaScriptReady():Boolean
{
var isReady:Boolean = false;
if (ExternalInterface.available)
{
isReady = ExternalInterface.call("isReady");
}
return isReady;
}
private function log(message:String)
{
trace(message);
label2.text = message;
if (ExternalInterface.available)
{
ExternalInterface.call("console.log",message);
}
}
}
}
|
package
{
import flash.display.*;
import flash.events.*;//for event handling
import flash.net.Socket;//Sockets
import flash.utils.*;
import flash.external.ExternalInterface;
import flash.system.*;
import com.adobe.serialization.json.*;//as3corelib JSON support
public class DisplayWindow extends Sprite
{
// Public Properties:
public var attention:uint;
public var meditation:uint;
public var blink:uint;
public var poorSignal:uint;
public var myTimer:Timer;
public var jsTimer:Timer;
public var timeCount:uint;
public var hasStarted:Boolean;
// Private Properties:
private var thinkGearSocket:Socket;
public function DisplayWindow()
{
Security.allowDomain("*");
var self = this;
hasStarted = false;
//To run the ThinkGear software without waiting for the JS, uncomment the line below
//startThinkGearSocket();
//Before the application tries to connect to the ThinkGearSocket, make sure JS is available
waitForJs();
}
private function startThinkGearSocket()
{
if (! hasStarted)
{
hasStarted = true;
log("Preparing ThinkGear...");
thinkGearSocket = new Socket();
thinkGearSocket.addEventListener(ProgressEvent.SOCKET_DATA,dataHandler);
thinkGearSocket.addEventListener(ProgressEvent.PROGRESS,progressHandler);
thinkGearSocket.connect("127.0.0.1",13854);
if (thinkGearSocket.connected)
{
log("ThinkGear connected. Configuring...");
}
else
{
log("ThinkGear not connected. Configuring anyway...");
}
var configuration:Object = new Object();
configuration["enableRawOutput"] = false;
configuration["format"] = "Json";
thinkGearSocket.writeUTFBytes(JSON.encode(configuration));
}
else
{
log("thinkGearSocket has already started");
}
}
// Protected Methods:;
private function progressHandler(e:ProgressEvent)
{
if (thinkGearSocket.connected)
{
log("ThinkGear connected. ProgressEvent occurred.");
}
else
{
log("ThinkGear not connected. ProgressEvent occurred.");
}
}
private function dataHandler(e:ProgressEvent)
{
if (thinkGearSocket.connected)
{
log("ThinkGear connected. Receiving data.");
}
else
{
log("ThinkGear not connected. Receiving data.");
}
var packetString:String = thinkGearSocket.readUTFBytes(thinkGearSocket.bytesAvailable);
if ((packetString == null))
{
log("packetString is NULL");
}
thinkGearSocket.flush();
log("ThinkGearSocket flushed");
var packets:Array = packetString.split(/\r/);
log(("Packets length: " + packets.length));
var data:Object;//temporary data
for each (var packet:String in packets)
{//iterate through each element
if ((packet != ""))
{//sometimes the line is blank so skip the line
try
{
log("Packet: "+packet);
data = JSON.decode(packet);
//decode the data to an array
if (data["poorSignalLevel"] != null)
{//checking to see if the ''poorSignalLevel' key exists
poorSignal = data["poorSignalLevel"];
if ((poorSignal == 0))
{
attention = data["eSense"]["attention"];//assigning data to variables
meditation = data["eSense"]["meditation"];
blink = data["blinkStrength"];
//log("Attention: " + attention);//output attention data to debug
}
else
{
if ((poorSignal == 200))
{
attention = 0;
meditation = 0;
blink = 0;
if (!data["eSense"])
poorSignal = 250;
}
}
}
label1.text = "Attention: " + attention.toString() + "\nMeditation: " + meditation.toString() + "\nPoor Signal: " + poorSignal.toString() + "\nblinkStrength: " + blink.toString();
sendDataToJavaScript(poorSignal,attention,meditation,blink);
}
catch (jError:JSONParseError)
{
log("there was a JSONParseError: " + packet);
// restart a connection at first error :(
hasStarted = false;
thinkGearSocket.close();
startThinkGearSocket();
sendDataToJavaScript(250, 0, 0, 0);
return;
}
} else log("empty packet");
data = null;
}/*for each*/
}/*function dataHandler*/
/**
* iconLevel is the poor signal value
* attentionLevel is the attention value
* meditationLevel is the meditation value
* There may be some need to check the types of these values, because they are not all
* being passed to the Javascript, from what I can tell
*/
public function sendDataToJavaScript(iconLevel:uint,attentionLevel:uint,meditationLevel:uint,blinkStrength:uint)
{
if (ExternalInterface.available)
{
ExternalInterface.call("MindWave.setSignalValue",iconLevel);
ExternalInterface.call("MindWave.setAttentionLevel",attentionLevel);
ExternalInterface.call("MindWave.setMeditationLevel",meditationLevel);
if (blinkStrength > 0) ExternalInterface.call("MindWave.setBlinkStrength",blinkStrength);
}
else
{
log("ExternalInterface is not available to send data to JS");
}
}
public function checkJs(event:TimerEvent)
{
log("Checking javascript...");
if (ExternalInterface.available)
{
var jsReady:Boolean = ExternalInterface.call("isReady");
if (jsReady)
{
jsTimer.stop();
startThinkGearSocket();
}
else
{
log("JS is not Ready");
}
} else {
log("No JS interface...");
}
}
public function checkJsStopped(event:TimerEvent)
{
log("Javascript connection was not established");
}
private function waitForJs()
{
jsTimer = new Timer(1000,100);
jsTimer.addEventListener(TimerEvent.TIMER,checkJs);
jsTimer.addEventListener(TimerEvent.TIMER_COMPLETE,checkJsStopped);
jsTimer.start();
}
private function receivedFromJavaScript(value:String):void
{
log((("JavaScript says: " + value) + "\n"));
}
private function checkJavaScriptReady():Boolean
{
var isReady:Boolean = false;
if (ExternalInterface.available)
{
isReady = ExternalInterface.call("isReady");
}
return isReady;
}
private function log(message:String)
{
trace(message);
label2.text = message;
if (ExternalInterface.available)
{
ExternalInterface.call("console.log",message);
}
}
}
}
|
send blink if > 0
|
flash: send blink if > 0
|
ActionScript
|
agpl-3.0
|
MLstate/MindChat
|
90123fa07051b8b346b720783a94c2d205457c02
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/Tracker.as
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/Tracker.as
|
/*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker
{
import com.snowplowanalytics.snowplow.tracker.emitter.Emitter;
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import com.snowplowanalytics.snowplow.tracker.payload.TrackerPayload;
import com.snowplowanalytics.snowplow.tracker.util.Preconditions;
import flash.display.Stage;
import flash.external.ExternalInterface;
import flash.net.LocalConnection;
import flash.net.SharedObject;
import flash.system.Capabilities;
public class Tracker
{
private var base64Encoded:Boolean = true;
private var emitter:Emitter;
private var platform:String;
private var appId:String;
private var namespace:String;
private var trackerVersion:String;
private var subject:Subject;
private var stage:Stage;
private var playerType:String;
private var playerVersion:String;
private var isDebugger:Boolean;
private var hasLocalStorage:Boolean;
private var hasScriptAccess:Boolean;
/**
* @param emitter Emitter to which events will be sent
* @param subject Subject to be tracked
* @param namespace Identifier for the Tracker instance
* @param appId Application ID
* @param stage The flash stage object. used for adding stage info to payload.
* @param base64Encoded Whether JSONs in the payload should be base-64 encoded
*/
function Tracker(emitter:Emitter, subject:Subject, namespace:String, appId:String, stage:Stage = null, base64Encoded:Boolean = true) {
this.emitter = emitter;
this.appId = appId;
this.base64Encoded = base64Encoded;
this.namespace = namespace;
this.subject = subject;
this.trackerVersion = Version.TRACKER;
this.platform = DevicePlatform.DESKTOP;
this.stage = stage;
this.playerType = Capabilities.playerType;
this.playerVersion = Capabilities.version;
this.isDebugger = Capabilities.isDebugger;
try
{
SharedObject.getLocal("test");
this.hasLocalStorage = true;
}
catch (e:Error)
{
this.hasLocalStorage = false;
}
this.hasScriptAccess = ExternalInterface.available;
}
/**
* @param payload Payload builder
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
* @return A completed Payload
*/
protected function completePayload(payload:IPayload,
context:Array,
timestamp:Number):IPayload {
payload.add(Parameter.PLATFORM, this.platform);
payload.add(Parameter.APPID, this.appId);
payload.add(Parameter.NAMESPACE, this.namespace);
payload.add(Parameter.TRACKER_VERSION, this.trackerVersion);
payload.add(Parameter.EID, Util.getEventId());
// If timestamp is set to 0, generate one
payload.add(Parameter.TIMESTAMP,
(timestamp == 0 ? Util.getTimestamp() : String(timestamp)));
// Add flash information
if (context == null) {
context = [];
}
var flashData:TrackerPayload = new TrackerPayload();
flashData.add(Parameter.FLASH_PLAYER_TYPE, playerType);
flashData.add(Parameter.FLASH_VERSION, playerVersion);
flashData.add(Parameter.FLASH_IS_DEBUGGER, isDebugger);
flashData.add(Parameter.FLASH_HAS_LOCAL_STORAGE, hasLocalStorage);
flashData.add(Parameter.FLASH_HAS_SCRIPT_ACCESS, hasScriptAccess);
if (stage != null) {
flashData.add(Parameter.FLASH_STAGE_SIZE, stage.stageWidth + "x" + stage.stageHeight);
}
var flashPayload:SchemaPayload = new SchemaPayload();
flashPayload.setSchema(Constants.SCHEMA_FLASH);
flashPayload.setData(flashData.getMap());
context.push(flashPayload);
// Encodes context data
if (context != null && context.length > 0) {
var envelope:SchemaPayload = new SchemaPayload();
envelope.setSchema(Constants.SCHEMA_CONTEXTS);
// We can do better here, rather than re-iterate through the list
var contextDataList:Array = [];
for each(var schemaPayload:SchemaPayload in context) {
contextDataList.push(schemaPayload.getMap());
}
envelope.setData(contextDataList);
payload.addMap(envelope.getMap(), this.base64Encoded, Parameter.CONTEXT_ENCODED, Parameter.CONTEXT);
}
if (this.subject != null) {
payload.addMap(Util.copyObject(subject.getSubject(), true));
}
return payload;
}
public function setPlatform(platform:String):void {
this.platform = platform;
}
public function getPlatform():String {
return this.platform;
}
protected function setTrackerVersion(version:String):void {
this.trackerVersion = version;
}
private function addTrackerPayload(payload:IPayload):void {
this.emitter.addToBuffer(payload);
}
public function setSubject(subject:Subject):void {
this.subject = subject;
}
public function getSubject():Subject {
return this.subject;
}
/**
* @param pageUrl URL of the viewed page
* @param pageTitle Title of the viewed page
* @param referrer Referrer of the page
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackPageView(pageUrl:String, pageTitle:String, referrer:String, context:Array = null, timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(pageUrl);
Preconditions.checkArgument(!Util.isNullOrEmpty(pageUrl), "pageUrl cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(pageTitle), "pageTitle cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(referrer), "referrer cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_PAGE_VIEW);
payload.add(Parameter.PAGE_URL, pageUrl);
payload.add(Parameter.PAGE_TITLE, pageTitle);
payload.add(Parameter.PAGE_REFR, referrer);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* @param category Category of the event
* @param action The event itself
* @param label Refer to the object the action is performed on
* @param property Property associated with either the action or the object
* @param value A value associated with the user action
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackStructuredEvent(category:String,
action:String,
label:String,
property:String,
value:int,
context:Array = null,
timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(label);
Preconditions.checkNotNull(property);
Preconditions.checkArgument(!Util.isNullOrEmpty(label), "label cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(property), "property cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(category), "category cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(action), "action cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_STRUCTURED);
payload.add(Parameter.SE_CATEGORY, category);
payload.add(Parameter.SE_ACTION, action);
payload.add(Parameter.SE_LABEL, label);
payload.add(Parameter.SE_PROPERTY, property);
payload.add(Parameter.SE_VALUE, String(value));
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
*
* @param eventData The properties of the event. Has two field:
* A "data" field containing the event properties and
* A "schema" field identifying the schema against which the data is validated
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackUnstructuredEvent(eventData:SchemaPayload, context:Array = null,
timestamp:Number = 0):void
{
var payload:IPayload = new TrackerPayload();
var envelope:SchemaPayload = new SchemaPayload();
envelope.setSchema(Constants.SCHEMA_UNSTRUCT_EVENT);
envelope.setData(eventData.getMap());
payload.add(Parameter.EVENT, Constants.EVENT_UNSTRUCTURED);
payload.addMap(envelope.getMap());
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* This is an internal method called by track_ecommerce_transaction. It is not for public use.
* @param order_id Order ID
* @param sku Item SKU
* @param price Item price
* @param quantity Item quantity
* @param name Item name
* @param category Item category
* @param currency The currency the price is expressed in
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
protected function trackEcommerceTransactionItem(order_id:String, sku:String, price:Number,
quantity:int, name:String, category:String,
currency:String, context:Array,
timestamp:Number):void
{
// Precondition checks
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(category);
Preconditions.checkNotNull(currency);
Preconditions.checkArgument(!Util.isNullOrEmpty(order_id), "order_id cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(sku), "sku cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(name), "name cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(category), "category cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(currency), "currency cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_ECOMM_ITEM);
payload.add(Parameter.TI_ITEM_ID, order_id);
payload.add(Parameter.TI_ITEM_SKU, sku);
payload.add(Parameter.TI_ITEM_NAME, name);
payload.add(Parameter.TI_ITEM_CATEGORY, category);
payload.add(Parameter.TI_ITEM_PRICE, String(price));
payload.add(Parameter.TI_ITEM_QUANTITY, String(quantity));
payload.add(Parameter.TI_ITEM_CURRENCY, currency);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* @param order_id ID of the eCommerce transaction
* @param total_value Total transaction value
* @param affiliation Transaction affiliation
* @param tax_value Transaction tax value
* @param shipping Delivery cost charged
* @param city Delivery address city
* @param state Delivery address state
* @param country Delivery address country
* @param currency The currency the price is expressed in
* @param items The items in the transaction
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackEcommerceTransaction(order_id:String, total_value:Number, affiliation:String,
tax_value:Number, shipping:Number, city:String,
state:String, country:String, currency:String,
items:Array, context:Array = null,
timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(affiliation);
Preconditions.checkNotNull(city);
Preconditions.checkNotNull(state);
Preconditions.checkNotNull(country);
Preconditions.checkNotNull(currency);
Preconditions.checkArgument(!Util.isNullOrEmpty(order_id), "order_id cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(affiliation), "affiliation cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(city), "city cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(state), "state cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(country), "country cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(currency), "currency cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_ECOMM);
payload.add(Parameter.TR_ID, order_id);
payload.add(Parameter.TR_TOTAL, String(total_value));
payload.add(Parameter.TR_AFFILIATION, affiliation);
payload.add(Parameter.TR_TAX, String(tax_value));
payload.add(Parameter.TR_SHIPPING, String(shipping));
payload.add(Parameter.TR_CITY, city);
payload.add(Parameter.TR_STATE, state);
payload.add(Parameter.TR_COUNTRY, country);
payload.add(Parameter.TR_CURRENCY, currency);
completePayload(payload, context, timestamp);
for each(var item:TransactionItem in items) {
trackEcommerceTransactionItem(
String(item.get(Parameter.TI_ITEM_ID)),
String(item.get(Parameter.TI_ITEM_SKU)),
Number(item.get(Parameter.TI_ITEM_PRICE)),
parseInt(item.get(Parameter.TI_ITEM_QUANTITY)),
String(item.get(Parameter.TI_ITEM_NAME)),
String(item.get(Parameter.TI_ITEM_CATEGORY)),
String(item.get(Parameter.TI_ITEM_CURRENCY)),
item.get(Parameter.CONTEXT),
timestamp);
}
addTrackerPayload(payload);
}
/**
* @param name The name of the screen view event
* @param id Screen view ID
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackScreenView(name:String, id:String, context:Array,
timestamp:Number):void {
Preconditions.checkArgument(name != null || id != null);
var trackerPayload:TrackerPayload = new TrackerPayload();
trackerPayload.add(Parameter.SV_NAME, name);
trackerPayload.add(Parameter.SV_ID, id);
var payload:SchemaPayload = new SchemaPayload();
payload.setSchema(Constants.SCHEMA_SCREEN_VIEW);
payload.setData(trackerPayload);
trackUnstructuredEvent(payload, context, timestamp);
}
}
}
|
/*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker
{
import com.snowplowanalytics.snowplow.tracker.emitter.Emitter;
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import com.snowplowanalytics.snowplow.tracker.payload.TrackerPayload;
import com.snowplowanalytics.snowplow.tracker.util.Preconditions;
import flash.display.Stage;
import flash.external.ExternalInterface;
import flash.net.LocalConnection;
import flash.net.SharedObject;
import flash.system.Capabilities;
public class Tracker
{
private var base64Encoded:Boolean = true;
private var emitter:Emitter;
private var platform:String;
private var appId:String;
private var namespace:String;
private var trackerVersion:String;
private var subject:Subject;
private var stage:Stage;
private var playerType:String;
private var playerVersion:String;
private var isDebugger:Boolean;
private var hasLocalStorage:Boolean;
private var hasScriptAccess:Boolean;
/**
* @param emitter Emitter to which events will be sent
* @param subject Subject to be tracked
* @param namespace Identifier for the Tracker instance
* @param appId Application ID
* @param stage The flash stage object. used for adding stage info to payload.
* @param base64Encoded Whether JSONs in the payload should be base-64 encoded
*/
function Tracker(emitter:Emitter, subject:Subject, namespace:String, appId:String, stage:Stage = null, base64Encoded:Boolean = true) {
this.emitter = emitter;
this.appId = appId;
this.base64Encoded = base64Encoded;
this.namespace = namespace;
this.subject = subject;
this.trackerVersion = Version.TRACKER;
this.platform = DevicePlatform.DESKTOP;
this.stage = stage;
this.playerType = Capabilities.playerType;
this.playerVersion = Capabilities.version;
this.isDebugger = Capabilities.isDebugger;
try
{
SharedObject.getLocal("test");
this.hasLocalStorage = true;
}
catch (e:Error)
{
this.hasLocalStorage = false;
}
this.hasScriptAccess = ExternalInterface.available;
}
/**
* @param payload Payload builder
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
* @return A completed Payload
*/
protected function completePayload(payload:IPayload,
context:Array,
timestamp:Number):IPayload {
payload.add(Parameter.PLATFORM, this.platform);
payload.add(Parameter.APPID, this.appId);
payload.add(Parameter.NAMESPACE, this.namespace);
payload.add(Parameter.TRACKER_VERSION, this.trackerVersion);
payload.add(Parameter.EID, Util.getEventId());
// If timestamp is set to 0, generate one
payload.add(Parameter.TIMESTAMP,
(timestamp == 0 ? Util.getTimestamp() : String(timestamp)));
// Add flash information
if (context == null) {
context = [];
}
var flashData:TrackerPayload = new TrackerPayload();
flashData.add(Parameter.FLASH_PLAYER_TYPE, playerType);
flashData.add(Parameter.FLASH_VERSION, playerVersion);
flashData.add(Parameter.FLASH_IS_DEBUGGER, isDebugger);
flashData.add(Parameter.FLASH_HAS_LOCAL_STORAGE, hasLocalStorage);
flashData.add(Parameter.FLASH_HAS_SCRIPT_ACCESS, hasScriptAccess);
if (stage != null) {
flashData.add(Parameter.FLASH_STAGE_SIZE, { "width": stage.stageWidth, "height": stage.stageHeight});
}
var flashPayload:SchemaPayload = new SchemaPayload();
flashPayload.setSchema(Constants.SCHEMA_FLASH);
flashPayload.setData(flashData.getMap());
context.push(flashPayload);
// Encodes context data
if (context != null && context.length > 0) {
var envelope:SchemaPayload = new SchemaPayload();
envelope.setSchema(Constants.SCHEMA_CONTEXTS);
// We can do better here, rather than re-iterate through the list
var contextDataList:Array = [];
for each(var schemaPayload:SchemaPayload in context) {
contextDataList.push(schemaPayload.getMap());
}
envelope.setData(contextDataList);
payload.addMap(envelope.getMap(), this.base64Encoded, Parameter.CONTEXT_ENCODED, Parameter.CONTEXT);
}
if (this.subject != null) {
payload.addMap(Util.copyObject(subject.getSubject(), true));
}
return payload;
}
public function setPlatform(platform:String):void {
this.platform = platform;
}
public function getPlatform():String {
return this.platform;
}
protected function setTrackerVersion(version:String):void {
this.trackerVersion = version;
}
private function addTrackerPayload(payload:IPayload):void {
this.emitter.addToBuffer(payload);
}
public function setSubject(subject:Subject):void {
this.subject = subject;
}
public function getSubject():Subject {
return this.subject;
}
/**
* @param pageUrl URL of the viewed page
* @param pageTitle Title of the viewed page
* @param referrer Referrer of the page
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackPageView(pageUrl:String, pageTitle:String, referrer:String, context:Array = null, timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(pageUrl);
Preconditions.checkArgument(!Util.isNullOrEmpty(pageUrl), "pageUrl cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(pageTitle), "pageTitle cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(referrer), "referrer cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_PAGE_VIEW);
payload.add(Parameter.PAGE_URL, pageUrl);
payload.add(Parameter.PAGE_TITLE, pageTitle);
payload.add(Parameter.PAGE_REFR, referrer);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* @param category Category of the event
* @param action The event itself
* @param label Refer to the object the action is performed on
* @param property Property associated with either the action or the object
* @param value A value associated with the user action
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackStructuredEvent(category:String,
action:String,
label:String,
property:String,
value:int,
context:Array = null,
timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(label);
Preconditions.checkNotNull(property);
Preconditions.checkArgument(!Util.isNullOrEmpty(label), "label cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(property), "property cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(category), "category cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(action), "action cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_STRUCTURED);
payload.add(Parameter.SE_CATEGORY, category);
payload.add(Parameter.SE_ACTION, action);
payload.add(Parameter.SE_LABEL, label);
payload.add(Parameter.SE_PROPERTY, property);
payload.add(Parameter.SE_VALUE, String(value));
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
*
* @param eventData The properties of the event. Has two field:
* A "data" field containing the event properties and
* A "schema" field identifying the schema against which the data is validated
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackUnstructuredEvent(eventData:SchemaPayload, context:Array = null,
timestamp:Number = 0):void
{
var payload:IPayload = new TrackerPayload();
var envelope:SchemaPayload = new SchemaPayload();
envelope.setSchema(Constants.SCHEMA_UNSTRUCT_EVENT);
envelope.setData(eventData.getMap());
payload.add(Parameter.EVENT, Constants.EVENT_UNSTRUCTURED);
payload.addMap(envelope.getMap());
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* This is an internal method called by track_ecommerce_transaction. It is not for public use.
* @param order_id Order ID
* @param sku Item SKU
* @param price Item price
* @param quantity Item quantity
* @param name Item name
* @param category Item category
* @param currency The currency the price is expressed in
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
protected function trackEcommerceTransactionItem(order_id:String, sku:String, price:Number,
quantity:int, name:String, category:String,
currency:String, context:Array,
timestamp:Number):void
{
// Precondition checks
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(category);
Preconditions.checkNotNull(currency);
Preconditions.checkArgument(!Util.isNullOrEmpty(order_id), "order_id cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(sku), "sku cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(name), "name cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(category), "category cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(currency), "currency cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_ECOMM_ITEM);
payload.add(Parameter.TI_ITEM_ID, order_id);
payload.add(Parameter.TI_ITEM_SKU, sku);
payload.add(Parameter.TI_ITEM_NAME, name);
payload.add(Parameter.TI_ITEM_CATEGORY, category);
payload.add(Parameter.TI_ITEM_PRICE, String(price));
payload.add(Parameter.TI_ITEM_QUANTITY, String(quantity));
payload.add(Parameter.TI_ITEM_CURRENCY, currency);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* @param order_id ID of the eCommerce transaction
* @param total_value Total transaction value
* @param affiliation Transaction affiliation
* @param tax_value Transaction tax value
* @param shipping Delivery cost charged
* @param city Delivery address city
* @param state Delivery address state
* @param country Delivery address country
* @param currency The currency the price is expressed in
* @param items The items in the transaction
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackEcommerceTransaction(order_id:String, total_value:Number, affiliation:String,
tax_value:Number, shipping:Number, city:String,
state:String, country:String, currency:String,
items:Array, context:Array = null,
timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(affiliation);
Preconditions.checkNotNull(city);
Preconditions.checkNotNull(state);
Preconditions.checkNotNull(country);
Preconditions.checkNotNull(currency);
Preconditions.checkArgument(!Util.isNullOrEmpty(order_id), "order_id cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(affiliation), "affiliation cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(city), "city cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(state), "state cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(country), "country cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(currency), "currency cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_ECOMM);
payload.add(Parameter.TR_ID, order_id);
payload.add(Parameter.TR_TOTAL, String(total_value));
payload.add(Parameter.TR_AFFILIATION, affiliation);
payload.add(Parameter.TR_TAX, String(tax_value));
payload.add(Parameter.TR_SHIPPING, String(shipping));
payload.add(Parameter.TR_CITY, city);
payload.add(Parameter.TR_STATE, state);
payload.add(Parameter.TR_COUNTRY, country);
payload.add(Parameter.TR_CURRENCY, currency);
completePayload(payload, context, timestamp);
for each(var item:TransactionItem in items) {
trackEcommerceTransactionItem(
String(item.get(Parameter.TI_ITEM_ID)),
String(item.get(Parameter.TI_ITEM_SKU)),
Number(item.get(Parameter.TI_ITEM_PRICE)),
parseInt(item.get(Parameter.TI_ITEM_QUANTITY)),
String(item.get(Parameter.TI_ITEM_NAME)),
String(item.get(Parameter.TI_ITEM_CATEGORY)),
String(item.get(Parameter.TI_ITEM_CURRENCY)),
item.get(Parameter.CONTEXT),
timestamp);
}
addTrackerPayload(payload);
}
/**
* @param name The name of the screen view event
* @param id Screen view ID
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackScreenView(name:String, id:String, context:Array,
timestamp:Number):void {
Preconditions.checkArgument(name != null || id != null);
var trackerPayload:TrackerPayload = new TrackerPayload();
trackerPayload.add(Parameter.SV_NAME, name);
trackerPayload.add(Parameter.SV_ID, id);
var payload:SchemaPayload = new SchemaPayload();
payload.setSchema(Constants.SCHEMA_SCREEN_VIEW);
payload.setData(trackerPayload);
trackUnstructuredEvent(payload, context, timestamp);
}
}
}
|
fix format of FLASH_STAGE_SIZE parameter
|
fix format of FLASH_STAGE_SIZE parameter
|
ActionScript
|
apache-2.0
|
snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker
|
2bdfa43314325c64a106727c127ba940ced26f8e
|
com/segonquart/menuColourIdiomes.as
|
com/segonquart/menuColourIdiomes.as
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class menuColouridiomes extends MovieClip
{
public var cat, es, en ,fr:MovieClip;
public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function menuColourIdiomes ():Void
{
this.onRollOver = this.mOver;
this.onRollOut = this.mOut;
this.onRelease =this.mOver;
}
private function mOver()
{
var i:Number;
for (var i = 0; i < arrayLang_arr.length; i++)
{
arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc");
]
}
private function mOut()
{
var i:Number;
for (var i = 0; i < arrayLang_arr.length; i++)
{
arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc");
}
}
}
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class menuColouridiomes extends MovieClip
{
public var cat, es, en ,fr:MovieClip;
public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
public function menuColourIdiomes ()
{
this.onRollOver = this.mOver;
this.onRollOut = this.mOut;
this.onRelease =this.mOver;
}
private function mOver()
{
var i:Number;
for (var i = 0; i < arrayLang_arr.length; i++)
{
arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc");
]
}
private function mOut()
{
var i:Number;
for (var i = 0; i < arrayLang_arr.length; i++)
{
arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc");
}
}
}
|
Update menuColourIdiomes.as
|
Update menuColourIdiomes.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
e9945296137102a4894fe9d2544ec56efe94d203
|
frameworks/projects/mobiletheme/src/spark/skins/android4/TransparentNavigationButtonSkin.as
|
frameworks/projects/mobiletheme/src/spark/skins/android4/TransparentNavigationButtonSkin.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.skins.mobile
{
import flash.display.DisplayObject;
import flash.display.Graphics;
import mx.core.DPIClassification;
import mx.core.mx_internal;
import spark.skins.mobile.assets.TransparentNavigationButton_down;
import spark.skins.mobile.assets.TransparentNavigationButton_up;
import spark.skins.mobile.supportClasses.ActionBarButtonSkinBase;
import spark.skins.mobile.supportClasses.MobileSkin;
import spark.skins.mobile320.assets.TransparentNavigationButton_down;
import spark.skins.mobile320.assets.TransparentNavigationButton_up;
import spark.skins.mobile480.assets.TransparentNavigationButton_down;
import spark.skins.mobile480.assets.TransparentNavigationButton_up;
import spark.skins.mobile640.assets.TransparentNavigationButton_down;
import spark.skins.mobile640.assets.TransparentNavigationButton_up;
use namespace mx_internal;
/**
* The default skin class for buttons in the navigation area of the Spark ActionBar component
* in mobile applications.
*
* @langversion 3.0
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class TransparentNavigationButtonSkin extends ActionBarButtonSkinBase
{
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
*/
public function TransparentNavigationButtonSkin()
{
super();
switch (applicationDPI)
{
case DPIClassification.DPI_640:
{
upBorderSkin = spark.skins.mobile640.assets.TransparentActionButton_up;
downBorderSkin = spark.skins.mobile640.assets.TransparentActionButton_down;
break;
}
case DPIClassification.DPI_480:
{
upBorderSkin = spark.skins.mobile480.assets.TransparentActionButton_up;
downBorderSkin = spark.skins.mobile480.assets.TransparentActionButton_down;
break;
}
case DPIClassification.DPI_320:
{
upBorderSkin = spark.skins.mobile320.assets.TransparentNavigationButton_up;
downBorderSkin = spark.skins.mobile320.assets.TransparentNavigationButton_down;
break;
}
default:
{
upBorderSkin = spark.skins.mobile.assets.TransparentNavigationButton_up;
downBorderSkin = spark.skins.mobile.assets.TransparentNavigationButton_down;
break;
}
}
}
override mx_internal function layoutBorder(unscaledWidth:Number, unscaledHeight:Number):void
{
// trailing vertical separator is outside the right bounds of the button
setElementSize(border, unscaledWidth + layoutBorderSize, unscaledHeight);
setElementPosition(border, 0, 0);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.skins.android4
{
import flash.display.DisplayObject;
import flash.display.Graphics;
import mx.core.DPIClassification;
import mx.core.mx_internal;
import spark.skins.mobile.assets.TransparentNavigationButton_down;
import spark.skins.mobile.assets.TransparentNavigationButton_up;
import spark.skins.mobile.supportClasses.ActionBarButtonSkinBase;
import spark.skins.mobile.supportClasses.MobileSkin;
import spark.skins.mobile320.assets.TransparentNavigationButton_down;
import spark.skins.mobile320.assets.TransparentNavigationButton_up;
import spark.skins.mobile480.assets.TransparentNavigationButton_down;
import spark.skins.mobile480.assets.TransparentNavigationButton_up;
import spark.skins.mobile640.assets.TransparentNavigationButton_down;
import spark.skins.mobile640.assets.TransparentNavigationButton_up;
use namespace mx_internal;
/**
* The default skin class for buttons in the navigation area of the Spark ActionBar component
* in mobile applications.
*
* @langversion 3.0
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class TransparentNavigationButtonSkin extends ActionBarButtonSkinBase
{
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
*/
public function TransparentNavigationButtonSkin()
{
super();
switch (applicationDPI)
{
case DPIClassification.DPI_640:
{
upBorderSkin = spark.skins.mobile640.assets.TransparentActionButton_up;
downBorderSkin = spark.skins.mobile640.assets.TransparentActionButton_down;
break;
}
case DPIClassification.DPI_480:
{
upBorderSkin = spark.skins.mobile480.assets.TransparentActionButton_up;
downBorderSkin = spark.skins.mobile480.assets.TransparentActionButton_down;
break;
}
case DPIClassification.DPI_320:
{
upBorderSkin = spark.skins.mobile320.assets.TransparentNavigationButton_up;
downBorderSkin = spark.skins.mobile320.assets.TransparentNavigationButton_down;
break;
}
default:
{
upBorderSkin = spark.skins.mobile.assets.TransparentNavigationButton_up;
downBorderSkin = spark.skins.mobile.assets.TransparentNavigationButton_down;
break;
}
}
}
override mx_internal function layoutBorder(unscaledWidth:Number, unscaledHeight:Number):void
{
// trailing vertical separator is outside the right bounds of the button
setElementSize(border, unscaledWidth + layoutBorderSize, unscaledHeight);
setElementPosition(border, 0, 0);
}
}
}
|
Move to correct package
|
Move to correct package
|
ActionScript
|
apache-2.0
|
danteinforno/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk
|
7340650a2b246eae4cd16ff5db39e9b22d35d0e6
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/effects/PlatformWiper.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/effects/PlatformWiper.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.effects
{
import flash.display.DisplayObject;
import flash.geom.Rectangle;
import org.apache.flex.core.IDocument;
import org.apache.flex.core.IUIBase;
/**
* Helper class for Wipe effects.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class PlatformWiper
{
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function PlatformWiper()
{
super();
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @private
* The target.
*/
private var _target:IUIBase;
/**
* The object that will be clipped.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function set target(value:IUIBase):void
{
_target = value;
if (value == null)
DisplayObject(_target).scrollRect = null;
}
/**
* The visible rectangle.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function set visibleRect(value:Rectangle):void
{
DisplayObject(_target).scrollRect = value;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.effects
{
import flash.display.DisplayObject;
import flash.geom.Rectangle;
import org.apache.flex.core.IDocument;
import org.apache.flex.core.IUIBase;
/**
* Helper class for Wipe effects.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class PlatformWiper
{
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function PlatformWiper()
{
super();
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @private
* The target.
*/
private var _target:IUIBase;
/**
* The object that will be clipped.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function set target(value:IUIBase):void
{
if (value == null)
DisplayObject(_target).scrollRect = null;
_target = value;
}
/**
* The visible rectangle.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function set visibleRect(value:Rectangle):void
{
DisplayObject(_target).scrollRect = value;
}
}
}
|
fix platform wiper
|
fix platform wiper
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
a5a19c72024722c06b91397bfa4b983830f5aede
|
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
|
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
|
package dolly {
import dolly.core.dolly_internal;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
use namespace dolly_internal;
public class ClonerTest {
private var classMarkedAsCloneable:ClassMarkedAsCloneable;
private var classWithSomeCloneableFields:ClassWithSomeCloneableFields;
private var classMarkedAsCloneableType:Type;
private var classWithSomeCloneableFieldsType:Type;
[Before]
public function before():void {
classMarkedAsCloneable = new ClassMarkedAsCloneable();
classMarkedAsCloneable.property1 = "value 1";
classMarkedAsCloneable.property2 = "value 2";
classMarkedAsCloneable.property3 = "value 3";
classMarkedAsCloneable.writableField = "value 4";
classWithSomeCloneableFields = new ClassWithSomeCloneableFields();
classWithSomeCloneableFieldsType = Type.forInstance(classWithSomeCloneableFields);
}
[After]
public function after():void {
classMarkedAsCloneable = null;
classWithSomeCloneableFields = null;
classMarkedAsCloneableType = null;
classWithSomeCloneableFieldsType = null;
}
[Test]
public function testGetCloneableFields():void {
var cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classMarkedAsCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
cloneableFields = Cloner.getCloneableFieldsForType(classWithSomeCloneableFieldsType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
}
[Test]
public function testCloneClassLevelMetadata():void {
const clone1:ClassMarkedAsCloneable = Cloner.clone(classMarkedAsCloneable) as ClassMarkedAsCloneable;
assertNotNull(clone1);
assertNotNull(clone1.property1);
assertEquals(clone1.property1, classMarkedAsCloneable.property1);
assertNotNull(clone1.property2);
assertEquals(clone1.property2, classMarkedAsCloneable.property2);
assertNotNull(clone1.property3);
assertEquals(clone1.property3, classMarkedAsCloneable.property3);
assertNotNull(clone1.writableField);
assertEquals(clone1.writableField, classMarkedAsCloneable.writableField);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class ClonerTest {
private var classMarkedAsCloneable:ClassMarkedAsCloneable;
private var classWithSomeCloneableFields:ClassWithSomeCloneableFields;
private var classMarkedAsCloneableType:Type;
private var classWithSomeCloneableFieldsType:Type;
[Before]
public function before():void {
classMarkedAsCloneable = new ClassMarkedAsCloneable();
classMarkedAsCloneable.property1 = "value 1";
classMarkedAsCloneable.property2 = "value 2";
classMarkedAsCloneable.property3 = "value 3";
classMarkedAsCloneable.writableField = "value 4";
classWithSomeCloneableFields = new ClassWithSomeCloneableFields();
classWithSomeCloneableFields.property1 = "value 1";
classWithSomeCloneableFields.property2 = "value 2";
classWithSomeCloneableFields.property3 = "value 3";
classWithSomeCloneableFields.writableField = "value 4";
classMarkedAsCloneableType = Type.forInstance(classMarkedAsCloneable);
classWithSomeCloneableFieldsType = Type.forInstance(classWithSomeCloneableFields);
}
[After]
public function after():void {
classMarkedAsCloneable = null;
classWithSomeCloneableFields = null;
classMarkedAsCloneableType = null;
classWithSomeCloneableFieldsType = null;
}
[Test]
public function testGetCloneableFields():void {
var cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classMarkedAsCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
cloneableFields = Cloner.getCloneableFieldsForType(classWithSomeCloneableFieldsType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
}
[Test]
public function testCloneWithClassLevelMetadata():void {
const clone1:ClassMarkedAsCloneable = Cloner.clone(classMarkedAsCloneable) as ClassMarkedAsCloneable;
assertNotNull(clone1);
assertNotNull(clone1.property1);
assertEquals(clone1.property1, classMarkedAsCloneable.property1);
assertNotNull(clone1.property2);
assertEquals(clone1.property2, classMarkedAsCloneable.property2);
assertNotNull(clone1.property3);
assertEquals(clone1.property3, classMarkedAsCloneable.property3);
assertNotNull(clone1.writableField);
assertEquals(clone1.writableField, classMarkedAsCloneable.writableField);
}
public function testCloneWithPropertyLevelMetadata():void {
const clone2:ClassWithSomeCloneableFields = Cloner.clone(
classWithSomeCloneableFields
) as ClassWithSomeCloneableFields;
assertNotNull(clone2);
assertNull(clone2.property1);
assertNotNull(clone2.property2);
assertEquals(clone2.property2, classWithSomeCloneableFields.property2);
assertNotNull(clone2.property3);
assertEquals(clone2.property3, classWithSomeCloneableFields.property3);
assertNotNull(clone2.writableField);
assertEquals(clone2.writableField, classWithSomeCloneableFields.writableField);
}
}
}
|
Add test method for cloning by using property-level metadata tags.
|
Add test method for cloning by using property-level metadata tags.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
7a8f197585cd05fdb051038bf4b9aea858458480
|
src/com/esri/builder/controllers/supportClasses/StartupWidgetTypeLoader.as
|
src/com/esri/builder/controllers/supportClasses/StartupWidgetTypeLoader.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.supportClasses
{
import com.esri.builder.model.WidgetType;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.supportClasses.FileUtil;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.views.BuilderAlert;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.utils.Dictionary;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.resources.ResourceManager;
public class StartupWidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(StartupWidgetTypeLoader);
private var widgetTypeArr:Array = [];
private var pendingLoaders:Array;
public function loadWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('Loading modules...');
}
var moduleFiles:Array = getModuleFiles(WellKnownDirectories.getInstance().bundledModules)
.concat(getModuleFiles(WellKnownDirectories.getInstance().customModules));
var swfFileAndXMLFileMaps:Array = mapFilenameToModuleSWFAndXMLFiles(moduleFiles);
var processedFileNames:Array = [];
var loaders:Array = [];
for each (var moduleFile:File in moduleFiles)
{
var fileName:String = FileUtil.getFileName(moduleFile);
if (Log.isDebug())
{
LOG.debug('loading module {0}', fileName);
}
if (processedFileNames.indexOf(fileName) == -1)
{
processedFileNames.push(fileName);
loaders.push(new WidgetTypeLoader(swfFileAndXMLFileMaps[0][fileName],
swfFileAndXMLFileMaps[1][fileName]));
}
}
pendingLoaders = loaders;
for each (var loader:WidgetTypeLoader in loaders)
{
loader.addEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler);
loader.addEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler);
loader.load();
}
checkIfWidgetTypeLoadersComplete();
}
private function mapFilenameToModuleSWFAndXMLFiles(moduleFiles:Array):Array
{
var uniqueFileNameToSWF:Dictionary = new Dictionary();
var uniqueFileNameToXML:Dictionary = new Dictionary();
for each (var file:File in moduleFiles)
{
if (file.extension == "swf")
{
uniqueFileNameToSWF[FileUtil.getFileName(file)] = file;
}
else if (file.extension == "xml")
{
uniqueFileNameToXML[FileUtil.getFileName(file)] = file;
}
}
return [ uniqueFileNameToSWF, uniqueFileNameToXML ];
}
private function getModuleFiles(directory:File):Array
{
var moduleFiles:Array = [];
if (directory.isDirectory)
{
const files:Array = directory.getDirectoryListing();
for each (var file:File in files)
{
if (file.isDirectory)
{
moduleFiles = moduleFiles.concat(getModuleFiles(file));
}
else if (isModuleFile(file))
{
moduleFiles.push(file);
}
}
}
return moduleFiles;
}
private function isModuleFile(file:File):Boolean
{
const moduleFileName:RegExp = /^.*Module\.(swf|xml)$/;
return !file.isDirectory && (moduleFileName.test(file.name));
}
private function checkIfWidgetTypeLoadersComplete():void
{
if (pendingLoaders.length === 0)
{
sortAndAssignWidgetTypes();
}
}
private function markModuleAsLoaded(loader:WidgetTypeLoader):void
{
var loaderIndex:int = pendingLoaders.indexOf(loader);
if (loaderIndex > -1)
{
pendingLoaders.splice(loaderIndex, 1);
}
}
private function sortAndAssignWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('All modules resolved');
}
var widgetTypes:Array = widgetTypeArr.filter(widgetTypeFilter);
for each (var widgetType:WidgetType in widgetTypes)
{
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(widgetType);
}
var layoutWidgetTypes:Array = widgetTypeArr.filter(layoutWidgetTypeFilter);
for each (var layoutWidgetType:WidgetType in layoutWidgetTypes)
{
WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.addWidgetType(layoutWidgetType);
}
function widgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean
{
return item.isManaged;
}
function layoutWidgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean
{
return !item.isManaged;
}
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.sort();
WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.sort();
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_TYPES_COMPLETE));
}
private function loader_loadCompleteHandler(event:WidgetTypeLoaderEvent):void
{
var loader:WidgetTypeLoader = event.currentTarget as WidgetTypeLoader;
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler);
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler);
var widgetType:WidgetType = event.widgetType;
if (Log.isDebug())
{
LOG.debug('Module {0} is resolved', widgetType.name);
}
widgetTypeArr.push(widgetType);
markModuleAsLoaded(loader);
checkIfWidgetTypeLoadersComplete();
}
private function loader_loadErrorHandler(event:WidgetTypeLoaderEvent):void
{
var loader:WidgetTypeLoader = event.currentTarget as WidgetTypeLoader;
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler);
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler);
var errorMessage:String = ResourceManager.getInstance().getString('BuilderStrings',
'importWidgetProcess.couldNotLoadCustomWidgets',
[ loader.name ]);
if (Log.isDebug())
{
LOG.debug(errorMessage);
}
BuilderAlert.show(errorMessage,
ResourceManager.getInstance().getString('BuilderStrings', 'error'));
markModuleAsLoaded(loader);
checkIfWidgetTypeLoadersComplete();
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// 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.supportClasses
{
import com.esri.builder.model.WidgetType;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.supportClasses.FileUtil;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.views.BuilderAlert;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.utils.Dictionary;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.resources.ResourceManager;
public class StartupWidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(StartupWidgetTypeLoader);
private var widgetTypeArr:Array = [];
private var pendingLoaders:Array;
public function loadWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('Loading modules...');
}
var moduleFiles:Array = getModuleFiles(WellKnownDirectories.getInstance().bundledModules)
.concat(getModuleFiles(WellKnownDirectories.getInstance().customModules));
var swfFileAndXMLFileMaps:Array = mapFilenameToModuleSWFAndXMLFiles(moduleFiles);
var processedFileNames:Array = [];
var loaders:Array = [];
for each (var moduleFile:File in moduleFiles)
{
var fileName:String = FileUtil.getFileName(moduleFile);
if (Log.isDebug())
{
LOG.debug('loading module {0}', fileName);
}
if (processedFileNames.indexOf(fileName) == -1)
{
processedFileNames.push(fileName);
loaders.push(new WidgetTypeLoader(swfFileAndXMLFileMaps[0][fileName],
swfFileAndXMLFileMaps[1][fileName]));
}
}
pendingLoaders = loaders;
for each (var loader:WidgetTypeLoader in loaders)
{
loader.addEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler);
loader.addEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler);
loader.load();
}
checkIfWidgetTypeLoadersComplete();
}
private function mapFilenameToModuleSWFAndXMLFiles(moduleFiles:Array):Array
{
var uniqueFileNameToSWF:Dictionary = new Dictionary();
var uniqueFileNameToXML:Dictionary = new Dictionary();
for each (var file:File in moduleFiles)
{
if (file.extension == "swf")
{
uniqueFileNameToSWF[FileUtil.getFileName(file)] = file;
}
else if (file.extension == "xml")
{
uniqueFileNameToXML[FileUtil.getFileName(file)] = file;
}
}
return [ uniqueFileNameToSWF, uniqueFileNameToXML ];
}
private function getModuleFiles(directory:File):Array
{
var moduleFiles:Array = [];
if (directory.isDirectory)
{
const files:Array = directory.getDirectoryListing();
for each (var file:File in files)
{
if (file.isDirectory)
{
moduleFiles = moduleFiles.concat(getModuleFiles(file));
}
else if (isModuleFile(file))
{
moduleFiles.push(file);
}
}
}
return moduleFiles;
}
private function isModuleFile(file:File):Boolean
{
const moduleFileName:RegExp = /^.*Module\.(swf|xml)$/;
return !file.isDirectory && (moduleFileName.test(file.name));
}
private function checkIfWidgetTypeLoadersComplete():void
{
if (pendingLoaders.length === 0)
{
sortAndAssignWidgetTypes();
}
}
private function markModuleAsLoaded(loader:WidgetTypeLoader):void
{
var loaderIndex:int = pendingLoaders.indexOf(loader);
if (loaderIndex > -1)
{
pendingLoaders.splice(loaderIndex, 1);
}
}
private function sortAndAssignWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('All modules resolved');
}
for each (var widgetType:WidgetType in widgetTypeArr)
{
if (widgetType.isManaged)
{
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(widgetType);
}
else
{
WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.addWidgetType(widgetType);
}
}
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.sort();
WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.sort();
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_TYPES_COMPLETE));
}
private function loader_loadCompleteHandler(event:WidgetTypeLoaderEvent):void
{
var loader:WidgetTypeLoader = event.currentTarget as WidgetTypeLoader;
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler);
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler);
var widgetType:WidgetType = event.widgetType;
if (Log.isDebug())
{
LOG.debug('Module {0} is resolved', widgetType.name);
}
widgetTypeArr.push(widgetType);
markModuleAsLoaded(loader);
checkIfWidgetTypeLoadersComplete();
}
private function loader_loadErrorHandler(event:WidgetTypeLoaderEvent):void
{
var loader:WidgetTypeLoader = event.currentTarget as WidgetTypeLoader;
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler);
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler);
var errorMessage:String = ResourceManager.getInstance().getString('BuilderStrings',
'importWidgetProcess.couldNotLoadCustomWidgets',
[ loader.name ]);
if (Log.isDebug())
{
LOG.debug(errorMessage);
}
BuilderAlert.show(errorMessage,
ResourceManager.getInstance().getString('BuilderStrings', 'error'));
markModuleAsLoaded(loader);
checkIfWidgetTypeLoadersComplete();
}
}
}
|
Clean code for registering widgets at startup.
|
Clean code for registering widgets at startup.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
4c418ec6aab3f054b156081675bb440133bbe852
|
runtime/src/main/as/flump/display/Movie.as
|
runtime/src/main/as/flump/display/Movie.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.display {
import flump.mold.MovieMold;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
public class Movie extends Sprite
{
public static const FRAMERATE :Number = 30;
public function Movie (src :MovieMold, idToDisplayObject :Function) {
name = src.libraryItem;
_ticker = new Ticker(advanceTime);
var frames :int = 0;
const flipbook :Boolean = src.flipbook;
if (src.flipbook) {
_layers = new Vector.<Layer>(1, true);
_layers[0] = new Layer(this, src.layers[0], idToDisplayObject, /*flipbook=*/true);
frames = src.layers[0].frames;
} else {
_layers = new Vector.<Layer>(src.layers.length, true);
for (var ii :int = 0; ii < _layers.length; ii++) {
_layers[ii] = new Layer(this, src.layers[ii], idToDisplayObject, /*flipbook=*/false);
frames = Math.max(src.layers[ii].frames, frames);
}
}
_duration = frames / FRAMERATE;
goto(0, true, false);
addEventListener(Event.ADDED_TO_STAGE, addedToStage);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
}
protected function advanceTime (dt :Number) :void {
if (!_playing) return;
_playTime += dt;
if (_playTime > _duration) _playTime = _playTime % _duration;
var newFrame :int = int(_playTime * FRAMERATE);
const overDuration :Boolean = dt >= _duration;
// If the update crosses or goes to the stopFrame, go to the stop frame, stop the movie and
// clear it
if (_stopFrame != NO_FRAME &&
((newFrame >= _stopFrame && (_frame < _stopFrame || newFrame < _frame)) || overDuration)) {
_playing = false
newFrame = _stopFrame;
_stopFrame = NO_FRAME;
}
goto(newFrame, false, overDuration);
}
protected function goto (newFrame :int, fromSkip :Boolean, overDuration :Boolean) :void {
if (_goingToFrame) {
_pendingFrame = newFrame;
return;
}
_goingToFrame = true;
const differentFrame :Boolean = newFrame != _frame;
const wrapped :Boolean = newFrame < _frame;
if (differentFrame) {
if (wrapped) {
for each (var layer :Layer in _layers) {
layer.changedKeyframe = true;
layer.keyframeIdx = 0;
}
}
for each (layer in _layers) layer.drawFrame(newFrame);
}
// Update the frame before firing, so if firing changes the frame, it sticks.
const oldFrame :int = _frame;
_frame = newFrame;
if (fromSkip) {
// TODO [self fireLabelsFrom:newFrame to:newFrame];
_playTime = newFrame/FRAMERATE;
} else if (overDuration) {
//[self fireLabelsFrom:oldFrame + 1 to:[_labels count] - 1];
//[self fireLabelsFrom:0 to:_frame];
} else if (differentFrame) {
if (wrapped) {
//[self fireLabelsFrom:oldFrame + 1 to:[_labels count] - 1];
//[self fireLabelsFrom:0 to:_frame];
} else {
//[self fireLabelsFrom:oldFrame + 1 to:_frame];
}
}
_goingToFrame = false;
if (_pendingFrame != NO_FRAME) {
newFrame = _pendingFrame;
_pendingFrame = NO_FRAME;
goto(newFrame, true, false);
}
}
protected function addedToStage (..._) :void { Starling.juggler.add(_ticker); }
protected function removedFromStage (..._) :void { Starling.juggler.add(_ticker); }
protected var _goingToFrame :Boolean;
protected var _pendingFrame :int = NO_FRAME;
protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME;
protected var _playing :Boolean = true;
protected var _playTime :Number, _duration :Number;
protected var _layers :Vector.<Layer>;
protected var _ticker :Ticker;
private static const NO_FRAME :int = -1;
}
}
import flump.display.Movie;
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
import starling.display.DisplayObject;
import starling.display.Sprite;
class Layer {
public var keyframeIdx :int ;// The index of the last keyframe drawn in drawFrame
public var layerIdx :int;// This layer's index in the movie
public var keyframes :Vector.<KeyframeMold>;
// Only created if there are multiple items on this layer. If it does exist, the appropriate display is swapped in at keyframe changes. If it doesn't, the display is only added to the parent on layer creation
public var displays :Vector.<DisplayObject>;// <SPDisplayObject*>
public var movie :Movie; // The movie this layer belongs to
// If the keyframe has changed since the last drawFrame
public var changedKeyframe :Boolean;
public function Layer (movie :Movie, src :LayerMold, idToDisplayObject :Function,
flipbook :Boolean) {
keyframes = src.keyframes;
this.movie = movie;
var lastItem :String;
for (var ii :int = 0; ii < keyframes.length && lastItem == null; ii++) {
lastItem = keyframes[ii].libraryItem;
}
if (!flipbook && lastItem == null) movie.addChild(new Sprite());// Label only layer
else {
var multipleItems :Boolean = flipbook;
for (ii = 0; ii < keyframes.length && !multipleItems; ii++) {
multipleItems = keyframes[ii].libraryItem != lastItem;
}
if (!multipleItems) movie.addChild(idToDisplayObject(lastItem));
else {
displays = new Vector.<DisplayObject>();
for each (var kf :KeyframeMold in keyframes) {
var display :DisplayObject = kf.id == null ? new Sprite() : idToDisplayObject(kf.id);
displays.push(display);
display.name = src.name;
}
movie.addChild(displays[0]);
}
}
layerIdx = movie.numChildren - 1;
movie.getChildAt(layerIdx).name = src.name;
}
public function drawFrame (frame :int) :void {
while (keyframeIdx < keyframes.length - 1 && keyframes[keyframeIdx + 1].index <= frame) {
keyframeIdx++;
changedKeyframe = true;
}
// We've got multiple items. Swap in the one for this kf
if (changedKeyframe && displays != null) {
movie.removeChildAt(layerIdx);
movie.addChildAt(displays[keyframeIdx], layerIdx);
}
changedKeyframe = false;
const kf :KeyframeMold = keyframes[keyframeIdx];
const layer :DisplayObject = movie.getChildAt(layerIdx);
if (keyframeIdx == keyframes.length - 1 || kf.index == frame) {
layer.x = kf.x;
layer.y = kf.y;
layer.scaleX = kf.scaleX;
layer.scaleY = kf.scaleY;
layer.rotation = kf.rotation;
layer.alpha = kf.alpha;
} else {
var interped :Number = (frame - kf.index)/kf.duration;
var ease :Number = kf.ease;
if (ease != 0) {
var t :Number;
if (ease < 0) {
// Ease in
var inv :Number = 1 - interped;
t = 1 - inv*inv;
ease = -ease;
} else {
// Ease out
t = interped*interped;
}
interped = ease*t + (1 - ease)*interped;
}
const nextKf :KeyframeMold = keyframes[keyframeIdx + 1];
layer.x = kf.x + (nextKf.x - kf.x) * interped;
layer.y = kf.y + (nextKf.y - kf.y) * interped;
layer.scaleX = kf.scaleX + (nextKf.scaleX - kf.scaleX) * interped;
layer.scaleY = kf.scaleY + (nextKf.scaleY - kf.scaleY) * interped;
layer.rotation = kf.rotation + (nextKf.rotation - kf.rotation) * interped;
layer.alpha = kf.alpha + (nextKf.alpha - kf.alpha) * interped;
}
layer.pivotX = kf.pivotX;
layer.pivotY = kf.pivotY;
layer.visible = kf.visible;
}
}
import starling.animation.IAnimatable;
class Ticker implements IAnimatable {
public function Ticker (callback :Function) {
_callback = callback;
}
public function get isComplete () :Boolean { return false; }
public function advanceTime (time :Number) :void { _callback(time); }
protected var _callback :Function;
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.display {
import flump.mold.MovieMold;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
public class Movie extends Sprite
{
public static const FRAMERATE :Number = 30;
public function Movie (src :MovieMold, idToDisplayObject :Function) {
name = src.libraryItem;
_ticker = new Ticker(advanceTime);
const flipbook :Boolean = src.flipbook;
if (src.flipbook) {
_layers = new Vector.<Layer>(1, true);
_layers[0] = new Layer(this, src.layers[0], idToDisplayObject, /*flipbook=*/true);
_frames = src.layers[0].frames;
} else {
_layers = new Vector.<Layer>(src.layers.length, true);
for (var ii :int = 0; ii < _layers.length; ii++) {
_layers[ii] = new Layer(this, src.layers[ii], idToDisplayObject, /*flipbook=*/false);
_frames = Math.max(src.layers[ii].frames, _frames);
}
}
_duration = _frames / FRAMERATE;
goto(0, true, false);
addEventListener(Event.ADDED_TO_STAGE, addedToStage);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
}
public function frames () :int {
return _frames;
}
protected function advanceTime (dt :Number) :void {
if (!_playing) return;
_playTime += dt;
var actualPlaytime :Number = _playTime;
if (_playTime > _duration) _playTime = _playTime % _duration;
var newFrame :int = int(_playTime * FRAMERATE);
const overDuration :Boolean = dt >= _duration;
// If the update crosses or goes to the stopFrame, go to the stop frame, stop the movie and
// clear it
if (_stopFrame != NO_FRAME) {
// how many frames remain to the stopframe?
var framesRemaining :int =
(_frame <= _stopFrame ? _stopFrame - _frame : _frames - _frame + _stopFrame);
var framesElapsed :int = int(actualPlaytime * FRAMERATE) - _frame;
if (framesElapsed >= framesRemaining) {
_playing = false;
newFrame = _stopFrame;
_stopFrame = NO_FRAME;
}
}
goto(newFrame, false, overDuration);
}
protected function goto (newFrame :int, fromSkip :Boolean, overDuration :Boolean) :void {
if (_goingToFrame) {
_pendingFrame = newFrame;
return;
}
_goingToFrame = true;
const differentFrame :Boolean = newFrame != _frame;
const wrapped :Boolean = newFrame < _frame;
if (differentFrame) {
if (wrapped) {
for each (var layer :Layer in _layers) {
layer.changedKeyframe = true;
layer.keyframeIdx = 0;
}
}
for each (layer in _layers) layer.drawFrame(newFrame);
}
// Update the frame before firing, so if firing changes the frame, it sticks.
const oldFrame :int = _frame;
_frame = newFrame;
if (fromSkip) {
// TODO [self fireLabelsFrom:newFrame to:newFrame];
_playTime = newFrame/FRAMERATE;
} else if (overDuration) {
//[self fireLabelsFrom:oldFrame + 1 to:[_labels count] - 1];
//[self fireLabelsFrom:0 to:_frame];
} else if (differentFrame) {
if (wrapped) {
//[self fireLabelsFrom:oldFrame + 1 to:[_labels count] - 1];
//[self fireLabelsFrom:0 to:_frame];
} else {
//[self fireLabelsFrom:oldFrame + 1 to:_frame];
}
}
_goingToFrame = false;
if (_pendingFrame != NO_FRAME) {
newFrame = _pendingFrame;
_pendingFrame = NO_FRAME;
goto(newFrame, true, false);
}
}
protected function addedToStage (..._) :void { Starling.juggler.add(_ticker); }
protected function removedFromStage (..._) :void { Starling.juggler.add(_ticker); }
protected var _goingToFrame :Boolean;
protected var _pendingFrame :int = NO_FRAME;
protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME;
protected var _playing :Boolean = true;
protected var _playTime :Number, _duration :Number;
protected var _layers :Vector.<Layer>;
protected var _ticker :Ticker;
protected var _frames :int;
private static const NO_FRAME :int = -1;
}
}
import flump.display.Movie;
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
import starling.display.DisplayObject;
import starling.display.Sprite;
class Layer {
public var keyframeIdx :int ;// The index of the last keyframe drawn in drawFrame
public var layerIdx :int;// This layer's index in the movie
public var keyframes :Vector.<KeyframeMold>;
// Only created if there are multiple items on this layer. If it does exist, the appropriate display is swapped in at keyframe changes. If it doesn't, the display is only added to the parent on layer creation
public var displays :Vector.<DisplayObject>;// <SPDisplayObject*>
public var movie :Movie; // The movie this layer belongs to
// If the keyframe has changed since the last drawFrame
public var changedKeyframe :Boolean;
public function Layer (movie :Movie, src :LayerMold, idToDisplayObject :Function,
flipbook :Boolean) {
keyframes = src.keyframes;
this.movie = movie;
var lastItem :String;
for (var ii :int = 0; ii < keyframes.length && lastItem == null; ii++) {
lastItem = keyframes[ii].libraryItem;
}
if (!flipbook && lastItem == null) movie.addChild(new Sprite());// Label only layer
else {
var multipleItems :Boolean = flipbook;
for (ii = 0; ii < keyframes.length && !multipleItems; ii++) {
multipleItems = keyframes[ii].libraryItem != lastItem;
}
if (!multipleItems) movie.addChild(idToDisplayObject(lastItem));
else {
displays = new Vector.<DisplayObject>();
for each (var kf :KeyframeMold in keyframes) {
var display :DisplayObject = kf.id == null ? new Sprite() : idToDisplayObject(kf.id);
displays.push(display);
display.name = src.name;
}
movie.addChild(displays[0]);
}
}
layerIdx = movie.numChildren - 1;
movie.getChildAt(layerIdx).name = src.name;
}
public function drawFrame (frame :int) :void {
while (keyframeIdx < keyframes.length - 1 && keyframes[keyframeIdx + 1].index <= frame) {
keyframeIdx++;
changedKeyframe = true;
}
// We've got multiple items. Swap in the one for this kf
if (changedKeyframe && displays != null) {
movie.removeChildAt(layerIdx);
movie.addChildAt(displays[keyframeIdx], layerIdx);
}
changedKeyframe = false;
const kf :KeyframeMold = keyframes[keyframeIdx];
const layer :DisplayObject = movie.getChildAt(layerIdx);
if (keyframeIdx == keyframes.length - 1 || kf.index == frame) {
layer.x = kf.x;
layer.y = kf.y;
layer.scaleX = kf.scaleX;
layer.scaleY = kf.scaleY;
layer.rotation = kf.rotation;
layer.alpha = kf.alpha;
} else {
var interped :Number = (frame - kf.index)/kf.duration;
var ease :Number = kf.ease;
if (ease != 0) {
var t :Number;
if (ease < 0) {
// Ease in
var inv :Number = 1 - interped;
t = 1 - inv*inv;
ease = -ease;
} else {
// Ease out
t = interped*interped;
}
interped = ease*t + (1 - ease)*interped;
}
const nextKf :KeyframeMold = keyframes[keyframeIdx + 1];
layer.x = kf.x + (nextKf.x - kf.x) * interped;
layer.y = kf.y + (nextKf.y - kf.y) * interped;
layer.scaleX = kf.scaleX + (nextKf.scaleX - kf.scaleX) * interped;
layer.scaleY = kf.scaleY + (nextKf.scaleY - kf.scaleY) * interped;
layer.rotation = kf.rotation + (nextKf.rotation - kf.rotation) * interped;
layer.alpha = kf.alpha + (nextKf.alpha - kf.alpha) * interped;
}
layer.pivotX = kf.pivotX;
layer.pivotY = kf.pivotY;
layer.visible = kf.visible;
}
}
import starling.animation.IAnimatable;
class Ticker implements IAnimatable {
public function Ticker (callback :Function) {
_callback = callback;
}
public function get isComplete () :Boolean { return false; }
public function advanceTime (time :Number) :void { _callback(time); }
protected var _callback :Function;
}
|
Fix _stopFrame logic
|
Fix _stopFrame logic
|
ActionScript
|
mit
|
tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,funkypandagame/flump,mathieuanthoine/flump
|
67f2726d7a6e75e9bfb0d3c5facc536a1fe37a33
|
frameworks/projects/HTML/asjs/src/org/apache/flex/html/beads/layouts/OneFlexibleChildHorizontalLayout.as
|
frameworks/projects/HTML/asjs/src/org/apache/flex/html/beads/layouts/OneFlexibleChildHorizontalLayout.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.IDocument;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.geom.Rectangle;
import org.apache.flex.utils.CSSUtils;
import org.apache.flex.utils.CSSContainerUtils;
/**
* The OneFlexibleChildHorizontalLayout 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 one 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 OneFlexibleChildHorizontalLayout implements IBeadLayout, IDocument
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function OneFlexibleChildHorizontalLayout()
{
}
/**
* The id of the flexible child
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var flexibleChild:String;
private var actualChild:ILayoutChild;
// the strand/host container is also an ILayoutChild because
// can have its size dictated by the host's parent which is
// important to know for layout optimization
private var host:ILayoutChild;
/**
* @private
* The document.
*/
private var document:Object;
/**
* @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
{
host = value as ILayoutChild;
}
private var _maxWidth:Number;
/**
* @copy org.apache.flex.core.IBead#maxWidth
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxWidth():Number
{
return _maxWidth;
}
/**
* @private
*/
public function set maxWidth(value:Number):void
{
_maxWidth = value;
}
private var _maxHeight:Number;
/**
* @copy org.apache.flex.core.IBead#maxHeight
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxHeight():Number
{
return _maxHeight;
}
/**
* @private
*/
public function set maxHeight(value:Number):void
{
_maxHeight = value;
}
/**
* @copy org.apache.flex.core.IBeadLayout#layout
*/
public function layout():Boolean
{
var layoutParent:ILayoutParent = host.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent ? layoutParent.contentView : IParentIUIBase(host);
var padding:Rectangle = CSSContainerUtils.getPaddingMetrics(host);
actualChild = document[flexibleChild];
var ilc:ILayoutChild;
var n:int = contentView.numElements;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
maxHeight = 0;
var verticalMargins:Array = new Array(n);
var ww:Number = contentView.width - padding.right;
var hh:Number = contentView.height;
var xx:int = padding.left;
var flexChildIndex:int;
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var lastmr:Number;
var lastml:Number;
var valign:Object;
var hostSizedToContent:Boolean = host.isHeightSizedToContent();
for (var i:int = 0; i < n; i++)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
if (child == actualChild)
{
flexChildIndex = i;
break;
}
margin = ValuesManager.valuesImpl.getValue(child, "margin");
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");
mt = CSSUtils.getTopValue(marginTop, margin, hh);
mb = CSSUtils.getBottomValue(marginBottom, margin, hh);
mr = CSSUtils.getRightValue(marginRight, margin, ww);
ml = CSSUtils.getLeftValue(marginLeft, margin, ww);
child.y = mt + padding.top;
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, true);
}
maxHeight = Math.max(maxHeight, mt + child.height + mb);
child.x = xx + ml;
xx += child.width + ml + mr;
lastmr = mr;
valign = ValuesManager.valuesImpl.getValue(child, "vertical-align");
verticalMargins[i] = { marginTop: mt, marginBottom: mb, valign: valign };
}
if (n > 0 && n > flexChildIndex)
{
for (i = n - 1; i > flexChildIndex; i--)
{
child = contentView.getElementAt(i) as IUIBase;
margin = ValuesManager.valuesImpl.getValue(child, "margin");
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");
mt = CSSUtils.getTopValue(marginTop, margin, hh);
mb = CSSUtils.getTopValue(marginBottom, margin, hh);
mr = CSSUtils.getRightValue(marginRight, margin, ww);
ml = CSSUtils.getLeftValue(marginLeft, margin, ww);
child.y = mt + padding.top;
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, true);
}
maxHeight = Math.max(maxHeight, mt + child.height + mb);
child.x = ww - child.width - mr;
ww -= child.width + ml + mr;
lastml = ml;
valign = ValuesManager.valuesImpl.getValue(child, "vertical-align");
verticalMargins[i] = { marginTop: mt, marginBottom: mb, valign: valign };
}
child = contentView.getElementAt(flexChildIndex) as IUIBase;
margin = ValuesManager.valuesImpl.getValue(child, "margin");
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");
mt = CSSUtils.getTopValue(marginTop, margin, hh);
mb = CSSUtils.getTopValue(marginBottom, margin, hh);
mr = CSSUtils.getRightValue(marginRight, margin, ww);
ml = CSSUtils.getLeftValue(marginLeft, margin, ww);
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, true);
}
maxHeight = Math.max(maxHeight, mt + child.height + mb);
child.x = xx + ml;
child.width = ww - xx - child.x;
valign = ValuesManager.valuesImpl.getValue(child, "vertical-align");
verticalMargins[flexChildIndex] = { marginTop: mt, marginBottom: mb, valign: valign };
}
if (hostSizedToContent)
ILayoutChild(contentView).setHeight(maxHeight + padding.top + padding.bottom, true);
for (i = 0; i < n; i++)
{
var obj:Object = verticalMargins[i]
child = contentView.getElementAt(i) as IUIBase;
setPositionAndHeight(child, obj.top, obj.marginTop, padding.top,
obj.bottom, obj.marginBottom, padding.bottom, maxHeight, obj.valign);
}
return true;
}
private function setPositionAndHeight(child:IUIBase, top:Number, mt:Number, pt:Number,
bottom:Number, mb:Number, pb:Number, h:Number, valign:String):void
{
var heightSet:Boolean = false; // if we've set the height in a way that gens a change event
var ySet:Boolean = false; // if we've set the y yet.
var hh:Number = h;
var ilc:ILayoutChild = child as ILayoutChild;
if (!isNaN(top))
{
child.y = top + mt;
ySet = true;
hh -= top + mt;
}
else
{
hh -= mt;
}
if (!isNaN(bottom))
{
if (!isNaN(top))
{
if (ilc)
ilc.setHeight(hh - bottom - mb, true);
else
{
child.height = hh - bottom - mb;
heightSet = true;
}
}
else
{
child.y = h - bottom - mb - child.height - 1; // some browsers don't like going to the edge
ySet = true;
}
}
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(h * ilc.percentHeight / 100, true);
}
if (valign == "center")
child.y = (h - child.height) / 2;
else if (valign == "bottom")
child.y = h - child.height - mb;
else
child.y = mt + pt;
if (!heightSet)
child.dispatchEvent(new Event("sizeChanged"));
}
public function setDocument(document:Object, id:String = null):void
{
this.document = document;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.IDocument;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.geom.Rectangle;
import org.apache.flex.utils.CSSUtils;
import org.apache.flex.utils.CSSContainerUtils;
/**
* The OneFlexibleChildHorizontalLayout 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 one 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 OneFlexibleChildHorizontalLayout implements IBeadLayout, IDocument
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function OneFlexibleChildHorizontalLayout()
{
}
/**
* The id of the flexible child
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var flexibleChild:String;
private var actualChild:ILayoutChild;
// the strand/host container is also an ILayoutChild because
// can have its size dictated by the host's parent which is
// important to know for layout optimization
private var host:ILayoutChild;
/**
* @private
* The document.
*/
private var document:Object;
/**
* @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
{
host = value as ILayoutChild;
}
private var _maxWidth:Number;
/**
* @copy org.apache.flex.core.IBead#maxWidth
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxWidth():Number
{
return _maxWidth;
}
/**
* @private
*/
public function set maxWidth(value:Number):void
{
_maxWidth = value;
}
private var _maxHeight:Number;
/**
* @copy org.apache.flex.core.IBead#maxHeight
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxHeight():Number
{
return _maxHeight;
}
/**
* @private
*/
public function set maxHeight(value:Number):void
{
_maxHeight = value;
}
/**
* @copy org.apache.flex.core.IBeadLayout#layout
*/
public function layout():Boolean
{
var layoutParent:ILayoutParent = host.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent ? layoutParent.contentView : IParentIUIBase(host);
var padding:Rectangle = CSSContainerUtils.getPaddingMetrics(host);
actualChild = document[flexibleChild];
var ilc:ILayoutChild;
var n:int = contentView.numElements;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
maxHeight = 0;
var verticalMargins:Array = new Array(n);
var ww:Number = contentView.width - padding.right;
var hh:Number = contentView.height;
var xx:int = padding.left;
var flexChildIndex:int;
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var lastmr:Number;
var lastml:Number;
var valign:Object;
var hostSizedToContent:Boolean = host.isHeightSizedToContent();
for (var i:int = 0; i < n; i++)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
if (child == actualChild)
{
flexChildIndex = i;
break;
}
margin = ValuesManager.valuesImpl.getValue(child, "margin");
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");
mt = CSSUtils.getTopValue(marginTop, margin, hh);
mb = CSSUtils.getBottomValue(marginBottom, margin, hh);
mr = CSSUtils.getRightValue(marginRight, margin, ww);
ml = CSSUtils.getLeftValue(marginLeft, margin, ww);
child.y = mt + padding.top;
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, true);
}
maxHeight = Math.max(maxHeight, mt + child.height + mb);
child.x = xx + ml;
xx += child.width + ml + mr;
lastmr = mr;
valign = ValuesManager.valuesImpl.getValue(child, "vertical-align");
verticalMargins[i] = { marginTop: mt, marginBottom: mb, valign: valign };
}
if (n > 0 && n > flexChildIndex)
{
for (i = n - 1; i > flexChildIndex; i--)
{
child = contentView.getElementAt(i) as IUIBase;
margin = ValuesManager.valuesImpl.getValue(child, "margin");
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");
mt = CSSUtils.getTopValue(marginTop, margin, hh);
mb = CSSUtils.getTopValue(marginBottom, margin, hh);
mr = CSSUtils.getRightValue(marginRight, margin, ww);
ml = CSSUtils.getLeftValue(marginLeft, margin, ww);
child.y = mt + padding.top;
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, true);
}
maxHeight = Math.max(maxHeight, mt + child.height + mb);
child.x = ww - child.width - mr;
ww -= child.width + ml + mr;
lastml = ml;
valign = ValuesManager.valuesImpl.getValue(child, "vertical-align");
verticalMargins[i] = { marginTop: mt, marginBottom: mb, valign: valign };
}
child = contentView.getElementAt(flexChildIndex) as IUIBase;
margin = ValuesManager.valuesImpl.getValue(child, "margin");
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");
mt = CSSUtils.getTopValue(marginTop, margin, hh);
mb = CSSUtils.getTopValue(marginBottom, margin, hh);
mr = CSSUtils.getRightValue(marginRight, margin, ww);
ml = CSSUtils.getLeftValue(marginLeft, margin, ww);
if (child is ILayoutChild)
{
ilc = child as ILayoutChild;
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, true);
}
child.x = xx + ml;
child.width = ww - child.x;
maxHeight = Math.max(maxHeight, mt + child.height + mb);
valign = ValuesManager.valuesImpl.getValue(child, "vertical-align");
verticalMargins[flexChildIndex] = { marginTop: mt, marginBottom: mb, valign: valign };
}
if (hostSizedToContent)
ILayoutChild(contentView).setHeight(maxHeight + padding.top + padding.bottom, true);
for (i = 0; i < n; i++)
{
var obj:Object = verticalMargins[i]
child = contentView.getElementAt(i) as IUIBase;
setPositionAndHeight(child, obj.top, obj.marginTop, padding.top,
obj.bottom, obj.marginBottom, padding.bottom, maxHeight, obj.valign);
}
return true;
}
private function setPositionAndHeight(child:IUIBase, top:Number, mt:Number, pt:Number,
bottom:Number, mb:Number, pb:Number, h:Number, valign:String):void
{
var heightSet:Boolean = false; // if we've set the height in a way that gens a change event
var ySet:Boolean = false; // if we've set the y yet.
var hh:Number = h;
var ilc:ILayoutChild = child as ILayoutChild;
if (!isNaN(top))
{
child.y = top + mt;
ySet = true;
hh -= top + mt;
}
else
{
hh -= mt;
}
if (!isNaN(bottom))
{
if (!isNaN(top))
{
if (ilc)
ilc.setHeight(hh - bottom - mb, true);
else
{
child.height = hh - bottom - mb;
heightSet = true;
}
}
else
{
child.y = h - bottom - mb - child.height - 1; // some browsers don't like going to the edge
ySet = true;
}
}
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(h * ilc.percentHeight / 100, true);
}
if (valign == "center")
child.y = (h - child.height) / 2;
else if (valign == "bottom")
child.y = h - child.height - mb;
else
child.y = mt + pt;
if (!heightSet)
child.dispatchEvent(new Event("sizeChanged"));
}
public function setDocument(document:Object, id:String = null):void
{
this.document = document;
}
}
}
|
fix the calculation
|
fix the calculation
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
b3601158e825ad6289c9fc7bf4e0fef97658400c
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/layouts/VerticalLayout.as
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/layouts/VerticalLayout.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.IBeadModel;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.utils.dbg.DOMPathUtil;
/**
* The VerticalLayout class is a simple layout
* bead. It takes the set of children and lays them out
* vertically in one column, separating them according to
* CSS layout rules for margin and horizontal-align styles.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class VerticalLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function VerticalLayout()
{
}
// the strand/host container is also an ILayoutChild because
// can have its size dictated by the host's parent which is
// important to know for layout optimization
private var host:ILayoutChild;
/**
* @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
{
host = value as ILayoutChild;
}
public function layout():Boolean
{
var layoutParent:ILayoutParent = host.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent ? layoutParent.contentView : IParentIUIBase(host);
var n:int = contentView.numElements;
var hasHorizontalFlex:Boolean;
var hostSizedToContent:Boolean = host.isWidthSizedToContent();
var flexibleHorizontalMargins:Array = [];
var ilc:ILayoutChild;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var maxWidth:Number = 0;
// asking for contentView.width can result in infinite loop if host isn't sized already
var w:Number = hostSizedToContent ? 0 : contentView.width;
for (var i:int = 0; i < n; i++)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
ilc = child as ILayoutChild;
var left:Number = ValuesManager.valuesImpl.getValue(child, "left");
var right:Number = ValuesManager.valuesImpl.getValue(child, "right");
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 lastmb:Number;
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
var yy:Number;
if (i == 0)
{
if (ilc)
ilc.setY(mt);
else
child.y = mt;
}
else
{
if (ilc)
ilc.setY(yy + Math.max(mt, lastmb));
else
child.y = yy + Math.max(mt, lastmb);
}
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, !isNaN(ilc.percentWidth));
}
lastmb = mb;
var marginObject:Object = {};
flexibleHorizontalMargins[i] = marginObject;
if (marginLeft == "auto")
{
ml = 0;
marginObject.marginLeft = marginLeft;
hasHorizontalFlex = true;
}
else
{
ml = Number(marginLeft);
if (isNaN(ml))
{
ml = 0;
marginObject.marginLeft = marginLeft;
}
else
marginObject.marginLeft = ml;
}
if (marginRight == "auto")
{
mr = 0;
marginObject.marginRight = marginRight;
hasHorizontalFlex = true;
}
else
{
mr = Number(marginRight);
if (isNaN(mr))
{
mr = 0;
marginObject.marginRight = marginRight;
}
else
marginObject.marginRight = mr;
}
if (!hostSizedToContent)
{
// if host is sized by parent,
// we can position and size children horizontally now
setPositionAndWidth(child, left, ml, right, mr, w);
}
else
{
if (!isNaN(left))
{
ml = left;
marginObject.left = ml;
}
if (!isNaN(right))
{
mr = right;
marginObject.right = mr;
}
maxWidth = Math.max(maxWidth, ml + child.width + mr);
}
yy = child.y + child.height;
}
if (hostSizedToContent)
{
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
var obj:Object = flexibleHorizontalMargins[i];
setPositionAndWidth(child, obj.left, obj.marginLeft,
obj.right, obj.marginRight, maxWidth);
}
}
if (hasHorizontalFlex)
{
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
ilc = child as ILayoutChild;
obj = flexibleHorizontalMargins[i];
if (hasHorizontalFlex)
{
if (ilc)
{
if (obj.marginLeft == "auto" && obj.marginRight == "auto")
ilc.setX(maxWidth - child.width / 2);
else if (obj.marginLeft == "auto")
ilc.setX(maxWidth - child.width - obj.marginRight);
}
else
{
if (obj.marginLeft == "auto" && obj.marginRight == "auto")
child.x = maxWidth - child.width / 2;
else if (obj.marginLeft == "auto")
child.x = maxWidth - child.width - obj.marginRight;
}
}
}
}
// Only return true if the contentView needs to be larger; that new
// size is stored in the model.
var sizeChanged:Boolean = true;
host.dispatchEvent( new Event("layoutComplete") );
return sizeChanged;
}
private function setPositionAndWidth(child:IUIBase, left:Number, ml:Number,
right:Number, mr:Number, w:Number):void
{
var widthSet:Boolean = false;
var ww:Number = w;
var ilc:ILayoutChild = child as ILayoutChild;
if (!isNaN(left))
{
if (ilc)
ilc.setX(left + ml);
else
child.x = left + ml;
ww -= left + ml;
}
else
{
if (ilc)
ilc.setX(ml);
else
child.x = ml;
ww -= ml;
}
if (!isNaN(right))
{
if (!isNaN(left))
{
if (ilc)
ilc.setWidth(ww - right - mr, true);
else
{
child.width = ww - right - mr;
widthSet = true;
}
}
else
{
if (ilc)
ilc.setX(w - right - mr - child.width);
else
child.x = w - right - mr - child.width;
}
}
if (ilc)
{
if (!isNaN(ilc.percentWidth))
ilc.setWidth(w * ilc.percentWidth / 100, true);
}
if (!widthSet)
child.dispatchEvent(new Event("sizeChanged"));
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.IBeadModel;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.utils.dbg.DOMPathUtil;
import org.apache.flex.utils.CSSUtils;
/**
* The VerticalLayout class is a simple layout
* bead. It takes the set of children and lays them out
* vertically in one column, separating them according to
* CSS layout rules for margin and horizontal-align styles.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class VerticalLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function VerticalLayout()
{
}
// the strand/host container is also an ILayoutChild because
// can have its size dictated by the host's parent which is
// important to know for layout optimization
private var host:ILayoutChild;
/**
* @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
{
host = value as ILayoutChild;
}
public function layout():Boolean
{
var layoutParent:ILayoutParent = host.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent ? layoutParent.contentView : IParentIUIBase(host);
var n:int = contentView.numElements;
var hasHorizontalFlex:Boolean;
var hostSizedToContent:Boolean = host.isWidthSizedToContent();
var flexibleHorizontalMargins:Array = [];
var ilc:ILayoutChild;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var maxWidth:Number = 0;
// asking for contentView.width can result in infinite loop if host isn't sized already
var w:Number = hostSizedToContent ? 0 : contentView.width;
var h = contentView.height;
for (var i:int = 0; i < n; i++)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
ilc = child as ILayoutChild;
var left:Number = ValuesManager.valuesImpl.getValue(child, "left");
var right:Number = ValuesManager.valuesImpl.getValue(child, "right");
margin = ValuesManager.valuesImpl.getValue(child, "margin");
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");
var ml:Number = CSSUtils.getLeftValue(marginLeft, margin, w);
var mr:Number = CSSUtils.getRightValue(marginRight, margin, w);
var mt:Number = CSSUtils.getTopValue(marginTop, margin, h);
var mb:Number = CSSUtils.getBottomValue(marginBottom, margin, h);
var lastmb:Number;
var yy:Number;
if (i == 0)
{
if (ilc)
ilc.setY(mt);
else
child.y = mt;
}
else
{
if (ilc)
ilc.setY(yy + Math.max(mt, lastmb));
else
child.y = yy + Math.max(mt, lastmb);
}
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, !isNaN(ilc.percentWidth));
}
lastmb = mb;
var marginObject:Object = {};
flexibleHorizontalMargins[i] = marginObject;
if (marginLeft == "auto")
{
ml = 0;
marginObject.marginLeft = marginLeft;
hasHorizontalFlex = true;
}
else
{
ml = Number(marginLeft);
if (isNaN(ml))
{
ml = 0;
marginObject.marginLeft = marginLeft;
}
else
marginObject.marginLeft = ml;
}
if (marginRight == "auto")
{
mr = 0;
marginObject.marginRight = marginRight;
hasHorizontalFlex = true;
}
else
{
mr = Number(marginRight);
if (isNaN(mr))
{
mr = 0;
marginObject.marginRight = marginRight;
}
else
marginObject.marginRight = mr;
}
if (!hostSizedToContent)
{
// if host is sized by parent,
// we can position and size children horizontally now
setPositionAndWidth(child, left, ml, right, mr, w);
}
else
{
if (!isNaN(left))
{
ml = left;
marginObject.left = ml;
}
if (!isNaN(right))
{
mr = right;
marginObject.right = mr;
}
maxWidth = Math.max(maxWidth, ml + child.width + mr);
}
yy = child.y + child.height;
}
if (hostSizedToContent)
{
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
var obj:Object = flexibleHorizontalMargins[i];
setPositionAndWidth(child, obj.left, obj.marginLeft,
obj.right, obj.marginRight, maxWidth);
}
}
if (hasHorizontalFlex)
{
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
ilc = child as ILayoutChild;
obj = flexibleHorizontalMargins[i];
if (hasHorizontalFlex)
{
if (ilc)
{
if (obj.marginLeft == "auto" && obj.marginRight == "auto")
ilc.setX(maxWidth - child.width / 2);
else if (obj.marginLeft == "auto")
ilc.setX(maxWidth - child.width - obj.marginRight);
}
else
{
if (obj.marginLeft == "auto" && obj.marginRight == "auto")
child.x = maxWidth - child.width / 2;
else if (obj.marginLeft == "auto")
child.x = maxWidth - child.width - obj.marginRight;
}
}
}
}
// Only return true if the contentView needs to be larger; that new
// size is stored in the model.
var sizeChanged:Boolean = true;
host.dispatchEvent( new Event("layoutComplete") );
return sizeChanged;
}
private function setPositionAndWidth(child:IUIBase, left:Number, ml:Number,
right:Number, mr:Number, w:Number):void
{
var widthSet:Boolean = false;
var ww:Number = w;
var ilc:ILayoutChild = child as ILayoutChild;
if (!isNaN(left))
{
if (ilc)
ilc.setX(left + ml);
else
child.x = left + ml;
ww -= left + ml;
}
else
{
if (ilc)
ilc.setX(ml);
else
child.x = ml;
ww -= ml;
}
if (!isNaN(right))
{
if (!isNaN(left))
{
if (ilc)
ilc.setWidth(ww - right - mr, true);
else
{
child.width = ww - right - mr;
widthSet = true;
}
}
else
{
if (ilc)
ilc.setX(w - right - mr - child.width);
else
child.x = w - right - mr - child.width;
}
}
if (ilc)
{
if (!isNaN(ilc.percentWidth))
ilc.setWidth(w * ilc.percentWidth / 100, true);
}
if (!widthSet)
child.dispatchEvent(new Event("sizeChanged"));
}
}
}
|
fix margin handling
|
fix margin handling
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
a11b338156b7319cbb73b0a1c346137a739ced31
|
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 ()
{
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, dispatchEvent);
_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, dispatchEvent);
}
/**
* 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 = 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;
}
}
|
//
// $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 ()
{
_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 = 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;
}
}
|
Document something that doesn't work.
|
Document something that doesn't work.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4605 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
1083490e735abf3989b56d9cca49110e3ccf7dbf
|
src/as/com/threerings/util/StreamableHashMap.as
|
src/as/com/threerings/util/StreamableHashMap.as
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2009 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 com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
import com.threerings.util.Log;
import com.threerings.util.Maps;
import com.threerings.util.maps.ForwardingMap;
/**
* A {@link HashMap} that can be sent over the wire, bearing in mind that all keys and values must
* be primitives or implement {@link Streamable}.
*/
public class StreamableHashMap extends ForwardingMap
implements Streamable
{
public function StreamableHashMap (keyClazz :Class = null)
{
if (keyClazz != null) {
super(Maps.newMapOf(keyClazz));
}
}
// documentation inherited from interface Streamable
public function writeObject (out :ObjectOutputStream) :void
{
out.writeInt(size());
forEach(function (key :Object, value :Object) :void {
out.writeObject(key);
out.writeObject(value);
});
}
// documentation inherited from interface Streamable
public function readObject (ins :ObjectInputStream) :void
{
var ecount :int = ins.readInt();
if (ecount > 0) {
// guess the type of map based on the first key
var key :Object = ins.readObject();
_source = Maps.newMapOf(ClassUtil.getClass(key));
put(key, ins.readObject());
// now read the rest
for (var ii :int = 1; ii < ecount; ii++) {
put(ins.readObject(), ins.readObject());
}
} else {
// shit!
Log.getLog(this).warning("Empty StreamableHashMap read, guessing DictionaryMap.");
_source = Maps.newDictionaryMap();
}
}
}
}
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2009 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 com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
import com.threerings.util.Log;
import com.threerings.util.Maps;
import com.threerings.util.maps.ForwardingMap;
/**
* A {@link HashMap} that can be sent over the wire, bearing in mind that all keys and values must
* be primitives or implement {@link Streamable}.
*/
public class StreamableHashMap extends ForwardingMap
implements Streamable
{
public function StreamableHashMap (keyClazz :Class = null)
{
if (keyClazz != null) {
super(Maps.newMapOf(keyClazz));
}
}
// documentation inherited from interface Streamable
public function writeObject (out :ObjectOutputStream) :void
{
out.writeInt(size());
forEach(function (key :Object, value :Object) :void {
out.writeObject(key);
out.writeObject(value);
});
}
// documentation inherited from interface Streamable
public function readObject (ins :ObjectInputStream) :void
{
var ecount :int = ins.readInt();
if (ecount > 0) {
// guess the type of map based on the first key
var key :Object = ins.readObject();
_source = Maps.newMapOf(ClassUtil.getClass(key));
put(key, ins.readObject());
// now read the rest
for (var ii :int = 1; ii < ecount; ii++) {
put(ins.readObject(), ins.readObject());
}
} else {
// shit!
Log.getLog(this).warning("Empty StreamableHashMap read, guessing DictionaryMap.");
_source = Maps.newMapOf(Object);
}
}
}
}
|
Use newMapOf().
|
Use newMapOf().
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5929 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
cb0d947f3476e4f393543c380a7c36cb75f6c3ee
|
frameworks/projects/Graphics/as/src/org/apache/flex/core/graphics/LinearGradient.as
|
frameworks/projects/Graphics/as/src/org/apache/flex/core/graphics/LinearGradient.as
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flex.core.graphics
{
COMPILE::AS3
{
import flash.display.GradientType;
import flash.display.InterpolationMethod;
import flash.display.SpreadMethod;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
}
public class LinearGradient extends GradientBase implements IFill
{
COMPILE::AS3
private static var commonMatrix:Matrix = new Matrix();
private var _scaleX:Number;
/**
* The horizontal scale of the gradient transform, which defines the width of the (unrotated) gradient
*/
public function get scaleX():Number
{
return _scaleX;
}
public function set scaleX(value:Number):void
{
_scaleX = value;
}
COMPILE::AS3
public function begin(s:GraphicShape,targetBounds:Rectangle, targetOrigin:Point):void
{
commonMatrix.identity();
commonMatrix.createGradientBox(targetBounds.width,targetBounds.height,toRad(this.rotation),targetOrigin.x, targetOrigin.y);
s.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios,
commonMatrix, SpreadMethod.PAD, InterpolationMethod.RGB);
}
COMPILE::AS3
public function end(s:GraphicShape):void
{
s.graphics.endFill();
}
/**
* addFillAttrib()
*
* @param value The GraphicShape object on which the fill must be added.
* @return {string}
* @flexjsignorecoercion Node
*/
COMPILE::JS
public function addFillAttrib(value:GraphicShape):String
{
//Create and add a linear gradient def
var svgNS:String = value.element.namespaceURI;
var grad:HTMLElement = document.createElementNS(svgNS, 'linearGradient') as HTMLElement;
var gradientId:String = this.newId;
grad.setAttribute('id', gradientId);
//Set x1, y1, x2, y2 of gradient
grad.setAttribute('x1', '0%');
grad.setAttribute('y1', '0%');
grad.setAttribute('x2', '100%');
grad.setAttribute('y2', '0%');
//Apply rotation to the gradient if rotation is a number
if (rotation)
{
grad.setAttribute('gradientTransform', 'rotate(' + rotation + ' 0.5 0.5)');
}
//Process gradient entries and create a stop for each entry
var entries:Array = entries;
for (var i:int = 0; i < entries.length; i++)
{
var gradientEntry:GradientEntry = entries[i];
var stop:HTMLElement = document.createElementNS(svgNS, 'stop') as HTMLElement;
//Set Offset
stop.setAttribute('offset', String(gradientEntry.ratio * 100) + '%');
//Set Color
var color:String = Number(gradientEntry.color).toString(16);
if (color.length == 1) color = '00' + color;
if (color.length == 2) color = '00' + color;
if (color.length == 4) color = '00' + color;
stop.setAttribute('stop-color', '#' + String(color));
//Set Alpha
stop.setAttribute('stop-opacity', String(gradientEntry.alpha));
grad.appendChild(stop);
}
//Add defs element if not available already
//Add newly created gradient to defs element
var defs:Node = value.element.querySelector('defs') ||
value.element.insertBefore(document.createElementNS(svgNS, 'defs'), value.element.firstChild);
defs.appendChild(grad);
//Return the fill attribute
return 'fill:url(#' + gradientId + ')';
}
}
}
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flex.core.graphics
{
COMPILE::AS3
{
import flash.display.GradientType;
import flash.display.InterpolationMethod;
import flash.display.SpreadMethod;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
}
public class LinearGradient extends GradientBase implements IFill
{
COMPILE::AS3
private static var commonMatrix:Matrix = new Matrix();
private var _scaleX:Number;
/**
* The horizontal scale of the gradient transform, which defines the width of the (unrotated) gradient
*/
public function get scaleX():Number
{
return _scaleX;
}
public function set scaleX(value:Number):void
{
_scaleX = value;
}
COMPILE::AS3
public function begin(s:GraphicShape,targetBounds:Rectangle, targetOrigin:Point):void
{
commonMatrix.identity();
commonMatrix.createGradientBox(targetBounds.width,targetBounds.height,toRad(this.rotation),targetOrigin.x, targetOrigin.y);
s.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios,
commonMatrix, SpreadMethod.PAD, InterpolationMethod.RGB);
}
COMPILE::AS3
public function end(s:GraphicShape):void
{
s.graphics.endFill();
}
/**
* addFillAttrib()
*
* @param value The GraphicShape object on which the fill must be added.
* @return {string}
* @flexjsignorecoercion Node
*/
COMPILE::JS
public function addFillAttrib(value:GraphicShape):String
{
//Create and add a linear gradient def
var svgNS:String = value.element.namespaceURI;
var grad:HTMLElement = document.createElementNS(svgNS, 'linearGradient') as HTMLElement;
var gradientId:String = this.newId;
grad.setAttribute('id', gradientId);
//Set x1, y1, x2, y2 of gradient
grad.setAttribute('x1', '0%');
grad.setAttribute('y1', '0%');
grad.setAttribute('x2', '100%');
grad.setAttribute('y2', '0%');
//Apply rotation to the gradient if rotation is a number
if (rotation)
{
grad.setAttribute('gradientTransform', 'rotate(' + rotation + ' 0.5 0.5)');
}
//Process gradient entries and create a stop for each entry
var entries:Array = this.entries;
for (var i:int = 0; i < entries.length; i++)
{
var gradientEntry:GradientEntry = entries[i];
var stop:HTMLElement = document.createElementNS(svgNS, 'stop') as HTMLElement;
//Set Offset
stop.setAttribute('offset', String(gradientEntry.ratio * 100) + '%');
//Set Color
var color:String = Number(gradientEntry.color).toString(16);
if (color.length == 1) color = '00' + color;
if (color.length == 2) color = '00' + color;
if (color.length == 4) color = '00' + color;
stop.setAttribute('stop-color', '#' + String(color));
//Set Alpha
stop.setAttribute('stop-opacity', String(gradientEntry.alpha));
grad.appendChild(stop);
}
//Add defs element if not available already
//Add newly created gradient to defs element
var defs:Node = value.element.querySelector('defs') ||
value.element.insertBefore(document.createElementNS(svgNS, 'defs'), value.element.firstChild);
defs.appendChild(grad);
//Return the fill attribute
return 'fill:url(#' + gradientId + ')';
}
}
}
|
fix error
|
fix error
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
4d3708c1db17c0d4b9c9a2718db069e5a14643b0
|
asunit-4.0/src/asunit/runners/TestRunner.as
|
asunit-4.0/src/asunit/runners/TestRunner.as
|
package asunit.runners {
import asunit.events.TimeoutCommandEvent;
import asunit.framework.Assert;
import asunit.framework.Async;
import asunit.framework.IResult;
import asunit.framework.Result;
import asunit.framework.IAsync;
import asunit.framework.IRunner;
import asunit.framework.IRunnerFactory;
import asunit.framework.Method;
import asunit.framework.TestFailure;
import asunit.framework.TestIterator;
import asunit.framework.TestSuccess;
import asunit.framework.TestWarning;
import asunit.util.ArrayIterator;
import asunit.util.Iterator;
import flash.display.Sprite;
import org.swiftsuspenders.Injector;
import p2.reflect.Reflection;
import p2.reflect.ReflectionMetaData;
import p2.reflect.ReflectionVariable;
import flash.display.DisplayObjectContainer;
import flash.errors.IllegalOperationError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
import flash.utils.getTimer;
public class TestRunner extends EventDispatcher implements IRunner {
/**
*
*/
//TODO: perhaps add a getter for this to IRunner
public var result:IResult;
// partially exposed for unit testing
internal var currentTest:Object;
internal var async:IAsync;
/** Supplies dependencies to tests, e.g. IAsync, context Sprite. */
internal var testInjector:Injector;
protected var currentMethod:Method;
protected var currentTestReflection:Reflection;
protected var methodIsExecuting:Boolean = false;
protected var methodPassed:Boolean = true;
protected var methodTimeoutID:Number;
protected var methodsToRun:TestIterator;
protected var startTime:Number;
protected var testMethodNameReceived:Boolean;
protected var timer:Timer;
protected var visualContext:DisplayObjectContainer;
protected var visualInstances:Array;
public function TestRunner(result:IResult = null) {
async = new Async();
this.result = result ||= new Result();
testInjector = new Injector();
testInjector.mapValue(IAsync, async);
testInjector.mapValue(Async, async);
timer = new Timer(0, 1);
timer.addEventListener(TimerEvent.TIMER, runNextMethod);
visualInstances = [];
}
public function run(testOrSuite:Class, methodName:String=null, visualContext:DisplayObjectContainer=null):void {
runMethodByName(testOrSuite, methodName, visualContext);
}
public function runMethodByName(test:Class, methodName:String=null, visualContext:DisplayObjectContainer=null):void {
currentTestReflection = Reflection.create(test);
this.visualContext = visualContext;
testInjector.mapValue(Sprite, visualContext);
currentMethod = null;
testMethodNameReceived = (methodName != null);
try {
currentTest = testInjector.instantiate(test);
}
catch(e:VerifyError) {
warn("Unable to instantiate provided test case with: " + currentTestReflection.name);
return;
}
async.addEventListener(TimeoutCommandEvent.CALLED, onAsyncMethodCalled);
async.addEventListener(TimeoutCommandEvent.TIMED_OUT, onAsyncMethodTimedOut);
startTime = getTimer();
result.onTestStarted(currentTest);
methodsToRun = createTestIterator(currentTest, methodName);
if(methodsToRun.length == 0) {
warn(">> We were unable to find any test methods in " + currentTestReflection.name + ". Did you set the --keep-as3-metadata flag?");
}
runNextMethod();
}
protected function createTestIterator(test:*, testMethodName:String):TestIterator {
return new TestIterator(test, testMethodName);
}
protected function runNextMethod(e:TimerEvent = null):void {
if (testCompleted) {
onTestCompleted();
return;
}
runMethod(methodsToRun.next());
}
protected function runMethod(method:Method):void {
if (!method) return;
currentMethod = method;
methodPassed = true; // innocent until proven guilty by recordFailure()
if (currentMethod.ignore) {
result.onTestIgnored(currentMethod);
onMethodCompleted();
return;
}
// This is used to prevent async callbacks from triggering onMethodCompleted too early.
methodIsExecuting = true;
if (currentMethod.expects) {
try {
var errorClass:Class = getDefinitionByName(currentMethod.expects) as Class;
Assert.assertThrows(errorClass, currentMethod.value);
}
catch(definitionError:ReferenceError) {
// NOTE: [luke] Added ReferenceError catch here b/c I had a bad class name in my expects.
// Does this look right?
recordFailure(new Error('Could not find Reference for: ' + currentMethod.expects));
}
catch (error:Error) {
recordFailure(error);
}
}
else {
try {
currentMethod.execute();
}
catch (error:Error) {
recordFailure(error);
}
}
methodIsExecuting = false;
if (async.hasPending) return;
onMethodCompleted();
}
protected function onMethodCompleted():void {
async.cancelPending();
if (currentMethod.isTest && methodPassed && !currentMethod.ignore) {
result.onTestSuccess(new TestSuccess(currentTest, currentMethod.name));
}
// Calling synchronously is faster but keeps adding to the call stack.
runNextMethod();
// green thread for runNextMethod()
// This runs much slower in Flash Player 10.1.
//timer.reset();
//timer.start();
}
protected function onAsyncMethodCalled(event:TimeoutCommandEvent):void {
try {
event.command.execute();
}
catch (error:Error) {
recordFailure(error);
}
onAsyncMethodCompleted(event);
}
protected function onAsyncMethodTimedOut(event:TimeoutCommandEvent):void {
var error:IllegalOperationError = new IllegalOperationError("Timeout (" + event.command.duration + "ms) exceeded on an asynchronous operation.");
recordFailure(error);
onAsyncMethodCompleted(event);
}
protected function recordFailure(error:Error):void {
methodPassed = false;
result.onTestFailure(new TestFailure(currentTest, currentMethod.name, error));
}
protected function onAsyncMethodCompleted(event:Event = null):void {
if (!methodIsExecuting && !async.hasPending) {
onMethodCompleted();
}
}
protected function onTestCompleted():void {
async.removeEventListener(TimeoutCommandEvent.CALLED, onAsyncMethodCalled);
async.removeEventListener(TimeoutCommandEvent.TIMED_OUT, onAsyncMethodTimedOut);
async.cancelPending();
result.onTestCompleted(currentTest);
dispatchEvent(new Event(Event.COMPLETE));
}
protected function get testCompleted():Boolean {
return (!methodsToRun.hasNext() && !async.hasPending);
}
protected function warn(message:String, method:Method=null):void {
result.onWarning(new TestWarning(message, method));
}
}
}
|
package asunit.runners {
import asunit.events.TimeoutCommandEvent;
import asunit.framework.Assert;
import asunit.framework.Async;
import asunit.framework.IResult;
import asunit.framework.Result;
import asunit.framework.IAsync;
import asunit.framework.IRunner;
import asunit.framework.IRunnerFactory;
import asunit.framework.Method;
import asunit.framework.TestFailure;
import asunit.framework.TestIterator;
import asunit.framework.TestSuccess;
import asunit.framework.TestWarning;
import asunit.util.ArrayIterator;
import asunit.util.Iterator;
import flash.display.Sprite;
import org.swiftsuspenders.Injector;
import p2.reflect.Reflection;
import p2.reflect.ReflectionMetaData;
import p2.reflect.ReflectionVariable;
import flash.display.DisplayObjectContainer;
import flash.errors.IllegalOperationError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
import flash.utils.getTimer;
public class TestRunner extends EventDispatcher implements IRunner {
/**
*
*/
//TODO: perhaps add a getter for this to IRunner
public var result:IResult;
// partially exposed for unit testing
internal var currentTest:Object;
internal var async:IAsync;
/** Supplies dependencies to tests, e.g. IAsync, context Sprite. */
internal var testInjector:Injector;
protected var currentMethod:Method;
protected var currentTestReflection:Reflection;
protected var methodIsExecuting:Boolean = false;
protected var methodPassed:Boolean = true;
protected var methodTimeoutID:Number;
protected var methodsToRun:TestIterator;
protected var startTime:Number;
protected var testMethodNameReceived:Boolean;
protected var timer:Timer;
protected var visualContext:DisplayObjectContainer;
protected var visualInstances:Array;
public function TestRunner(result:IResult = null) {
async = new Async();
this.result = result ||= new Result();
testInjector = new Injector();
testInjector.mapValue(IAsync, async);
testInjector.mapValue(Async, async);
timer = new Timer(0, 1);
timer.addEventListener(TimerEvent.TIMER, runNextMethods);
visualInstances = [];
}
public function runMethodByName(testOrSuite:Class, methodName:String=null, visualContext:DisplayObjectContainer=null):void {
run(testOrSuite, methodName, visualContext);
}
public function run(test:Class, methodName:String=null, visualContext:DisplayObjectContainer=null):void {
currentTestReflection = Reflection.create(test);
this.visualContext = visualContext;
testInjector.mapValue(Sprite, visualContext);
currentMethod = null;
testMethodNameReceived = (methodName != null);
try {
currentTest = testInjector.instantiate(test);
}
catch(e:VerifyError) {
warn("Unable to instantiate provided test case with: " + currentTestReflection.name);
return;
}
async.addEventListener(TimeoutCommandEvent.CALLED, onAsyncMethodCalled);
async.addEventListener(TimeoutCommandEvent.TIMED_OUT, onAsyncMethodTimedOut);
startTime = getTimer();
result.onTestStarted(currentTest);
methodsToRun = createTestIterator(currentTest, methodName);
if(methodsToRun.length == 0) {
warn(">> We were unable to find any test methods in " + currentTestReflection.name + ". Did you set the --keep-as3-metadata flag?");
}
runNextMethods();
}
protected function createTestIterator(test:*, testMethodName:String):TestIterator {
return new TestIterator(test, testMethodName);
}
protected function runNextMethods(e:TimerEvent = null):void {
// Loop through as many as possible without hitting asynchronous tests.
// This keeps the call stack small.
while (methodsToRun.hasNext()) {
var hasAsyncPending:Boolean = runMethod(methodsToRun.next());
if (hasAsyncPending) return;
}
onTestCompleted();
}
/**
*
* @param method
* @return true if asynchronous calls are pending after calling the test method.
*/
protected function runMethod(method:Method):Boolean {
if (!method) return false;
currentMethod = method;
methodPassed = true; // innocent until proven guilty by recordFailure()
if (currentMethod.ignore) {
result.onTestIgnored(currentMethod);
onMethodCompleted();
return false;
}
// This is used to prevent async callbacks from triggering onMethodCompleted too early.
methodIsExecuting = true;
if (currentMethod.expects) {
try {
var errorClass:Class = getDefinitionByName(currentMethod.expects) as Class;
Assert.assertThrows(errorClass, currentMethod.value);
}
catch(definitionError:ReferenceError) {
// NOTE: [luke] Added ReferenceError catch here b/c I had a bad class name in my expects.
// Does this look right?
recordFailure(new Error('Could not find Reference for: ' + currentMethod.expects));
}
catch (error:Error) {
recordFailure(error);
}
}
else {
try {
currentMethod.execute();
}
catch (error:Error) {
recordFailure(error);
}
}
methodIsExecuting = false;
if (async.hasPending) return true;
onMethodCompleted();
return false;
}
protected function onMethodCompleted(wasAsync:Boolean = false):void {
async.cancelPending();
if (currentMethod.isTest && methodPassed && !currentMethod.ignore) {
result.onTestSuccess(new TestSuccess(currentTest, currentMethod.name));
}
if (wasAsync)
runNextMethods();
// green thread for runNextMethods()
// This runs much slower in Flash Player 10.1.
//timer.reset();
//timer.start();
}
protected function onAsyncMethodCalled(event:TimeoutCommandEvent):void {
try {
event.command.execute();
}
catch (error:Error) {
recordFailure(error);
}
onAsyncMethodCompleted(event);
}
protected function onAsyncMethodTimedOut(event:TimeoutCommandEvent):void {
var error:IllegalOperationError = new IllegalOperationError("Timeout (" + event.command.duration + "ms) exceeded on an asynchronous operation.");
recordFailure(error);
onAsyncMethodCompleted(event);
}
protected function recordFailure(error:Error):void {
methodPassed = false;
result.onTestFailure(new TestFailure(currentTest, currentMethod.name, error));
}
protected function onAsyncMethodCompleted(event:Event = null):void {
if (!methodIsExecuting && !async.hasPending) {
onMethodCompleted(true);
}
}
protected function onTestCompleted():void {
async.removeEventListener(TimeoutCommandEvent.CALLED, onAsyncMethodCalled);
async.removeEventListener(TimeoutCommandEvent.TIMED_OUT, onAsyncMethodTimedOut);
async.cancelPending();
result.onTestCompleted(currentTest);
dispatchEvent(new Event(Event.COMPLETE));
}
protected function get testCompleted():Boolean {
return (!methodsToRun.hasNext() && !async.hasPending);
}
protected function warn(message:String, method:Method=null):void {
result.onWarning(new TestWarning(message, method));
}
}
}
|
Call stacks for failures are now much shorter. Now using a while loop to iterate as far as possible before hitting async methods.
|
Call stacks for failures are now much shorter. Now using a while loop to iterate as far as possible before hitting async methods.
|
ActionScript
|
mit
|
patternpark/asunit,robertpenner/asunit
|
95d7bcb9951858c34a55ce7cea6b3d01c9d79a3a
|
src/aerys/minko/scene/node/Mesh.as
|
src/aerys/minko/scene/node/Mesh.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.scene.controller.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.Ray;
use namespace minko_scene;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractVisibleSceneNode implements ITaggable
{
public static const DEFAULT_MATERIAL : Material = new BasicMaterial();
private var _ctrl : MeshController;
private var _properties : DataProvider;
private var _material : Material;
private var _bindings : DataBindings;
private var _visibility : MeshVisibilityController;
private var _cloned : Signal;
private var _tag : uint = 1;
/**
* 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 <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
var oldMaterial : Material = _material;
_material = value;
if (value)
_bindings.addProvider(value);
}
}
/**
* 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 _ctrl.geometry;
}
public function set geometry(value : Geometry) : void
{
_ctrl.geometry = value;
}
public function get tag() : uint
{
return _tag;
}
public function set tag(value : uint) : void
{
if (_tag != value)
{
_tag = value;
_properties.setProperty('tag', value);
}
}
/**
* Whether the mesh in inside the camera frustum or not.
* @return
*
*/
public function get insideFrustum() : Boolean
{
return _visibility.insideFrustum;
}
override public function get computedVisibility() : Boolean
{
return scene
? super.computedVisibility && _visibility.computedVisibility
: super.computedVisibility;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get frame() : uint
{
return _ctrl.frame;
}
public function set frame(value : uint) : void
{
_ctrl.frame = value;
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
name : String = null,
tag : uint = 1)
{
super();
initializeMesh(geometry, material, name, tag);
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(
properties,
'meshProperties',
DataProviderUsage.EXCLUSIVE
);
super.initialize();
}
override protected function initializeSignals() : void
{
super.initializeSignals();
_cloned = new Signal('Mesh.cloned');
}
override protected function initializeContollers() : void
{
super.initializeContollers();
_ctrl = new MeshController();
addController(_ctrl);
_visibility = new MeshVisibilityController();
_visibility.frustumCulling = FrustumCulling.ENABLED;
addController(_visibility);
}
protected function initializeMesh(geometry : Geometry,
material : Material,
name : String,
tag : uint) : void
{
if (name)
this.name = name;
this.geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
_tag = tag;
}
public function cast(ray : Ray,
maxDistance : Number = Number.POSITIVE_INFINITY,
tag : uint = 1) : Number
{
if (!(_tag & tag))
return -1;
return _ctrl.geometry.boundingBox.testRay(
ray,
getWorldToLocalTransform(),
maxDistance
);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Mesh = new Mesh();
clone.name = name;
clone.geometry = _ctrl.geometry;
clone.properties = DataProvider(_properties.clone());
clone._bindings.copySharedProvidersFrom(_bindings);
clone.transform.copyFrom(transform);
clone.material = _material;
this.cloned.execute(this, clone);
return clone;
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.scene.controller.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.Ray;
use namespace minko_scene;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractVisibleSceneNode implements ITaggable
{
private var _ctrl : MeshController;
private var _properties : DataProvider;
private var _material : Material;
private var _bindings : DataBindings;
private var _visibility : MeshVisibilityController;
private var _cloned : Signal;
private var _tag : uint = 1;
/**
* 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 <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
var oldMaterial : Material = _material;
_material = value;
if (value)
_bindings.addProvider(value);
}
}
/**
* 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 _ctrl.geometry;
}
public function set geometry(value : Geometry) : void
{
_ctrl.geometry = value;
}
public function get tag() : uint
{
return _tag;
}
public function set tag(value : uint) : void
{
if (_tag != value)
{
_tag = value;
_properties.setProperty('tag', value);
}
}
/**
* Whether the mesh in inside the camera frustum or not.
* @return
*
*/
public function get insideFrustum() : Boolean
{
return _visibility.insideFrustum;
}
override public function get computedVisibility() : Boolean
{
return scene
? super.computedVisibility && _visibility.computedVisibility
: super.computedVisibility;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get frame() : uint
{
return _ctrl.frame;
}
public function set frame(value : uint) : void
{
_ctrl.frame = value;
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
name : String = null,
tag : uint = 1)
{
super();
initializeMesh(geometry, material, name, tag);
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(
properties,
'meshProperties',
DataProviderUsage.EXCLUSIVE
);
super.initialize();
}
override protected function initializeSignals() : void
{
super.initializeSignals();
_cloned = new Signal('Mesh.cloned');
}
override protected function initializeContollers() : void
{
super.initializeContollers();
_ctrl = new MeshController();
addController(_ctrl);
_visibility = new MeshVisibilityController();
_visibility.frustumCulling = FrustumCulling.ENABLED;
addController(_visibility);
}
protected function initializeMesh(geometry : Geometry,
material : Material,
name : String,
tag : uint) : void
{
if (name)
this.name = name;
this.geometry = geometry;
this.material = material;
_tag = tag;
}
public function cast(ray : Ray,
maxDistance : Number = Number.POSITIVE_INFINITY,
tag : uint = 1) : Number
{
if (!(_tag & tag))
return -1;
return _ctrl.geometry.boundingBox.testRay(
ray,
getWorldToLocalTransform(),
maxDistance
);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Mesh = new Mesh();
clone.name = name;
clone.geometry = _ctrl.geometry;
clone.properties = DataProvider(_properties.clone());
clone._bindings.copySharedProvidersFrom(_bindings);
clone.transform.copyFrom(transform);
clone.material = _material;
this.cloned.execute(this, clone);
return clone;
}
}
}
|
fix Mesh.initializeMesh() to stop using static reference to a default material to avoid memory leak: by default Mesh will now have a null material if none is provided
|
fix Mesh.initializeMesh() to stop using static reference to a default material to avoid memory leak: by default Mesh will now have a null material if none is provided
|
ActionScript
|
mit
|
aerys/minko-as3
|
88e782fda3d6fcfa72adce0b5c43638e9b7e12b9
|
src/org/mangui/basic/Player.as
|
src/org/mangui/basic/Player.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.basic {
import org.mangui.hls.HLS;
import org.mangui.hls.event.HLSEvent;
import flash.display.Sprite;
import flash.media.Video;
public class Player extends Sprite {
private var hls : HLS = null;
private var video : Video = null;
public function Player() {
hls = new HLS();
video = new Video(640, 480);
addChild(video);
video.x = 0;
video.y = 0;
video.smoothing = true;
video.attachNetStream(hls.stream);
hls.addEventListener(HLSEvent.MANIFEST_LOADED, manifestHandler);
hls.load("http://domain.com/hls/m1.m3u8");
}
public function manifestHandler(event : HLSEvent) : void {
hls.stream.play();
};
}
}
|
/* 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.basic {
import org.mangui.hls.HLS;
import org.mangui.hls.event.HLSEvent;
import flash.display.Sprite;
import flash.media.Video;
public class Player extends Sprite {
private var hls : HLS = null;
private var video : Video = null;
public function Player() {
hls = new HLS();
hls.stage = this.stage;
video = new Video(640, 480);
addChild(video);
video.x = 0;
video.y = 0;
video.smoothing = true;
video.attachNetStream(hls.stream);
hls.addEventListener(HLSEvent.MANIFEST_LOADED, manifestHandler);
hls.load("http://domain.com/hls/m1.m3u8");
}
public function manifestHandler(event : HLSEvent) : void {
hls.stream.play(null, -1);
};
}
}
|
update basic/Player.as and set stage
|
update basic/Player.as and set stage
|
ActionScript
|
mpl-2.0
|
viktorot/flashls,tedconf/flashls,suuhas/flashls,Peer5/flashls,Peer5/flashls,Peer5/flashls,Corey600/flashls,hola/flashls,vidible/vdb-flashls,aevange/flashls,codex-corp/flashls,viktorot/flashls,aevange/flashls,jlacivita/flashls,Boxie5/flashls,suuhas/flashls,mangui/flashls,jlacivita/flashls,JulianPena/flashls,suuhas/flashls,School-Improvement-Network/flashls,codex-corp/flashls,dighan/flashls,Boxie5/flashls,thdtjsdn/flashls,loungelogic/flashls,suuhas/flashls,JulianPena/flashls,School-Improvement-Network/flashls,Peer5/flashls,aevange/flashls,mangui/flashls,vidible/vdb-flashls,dighan/flashls,aevange/flashls,fixedmachine/flashls,fixedmachine/flashls,neilrackett/flashls,viktorot/flashls,neilrackett/flashls,clappr/flashls,NicolasSiver/flashls,thdtjsdn/flashls,loungelogic/flashls,hola/flashls,NicolasSiver/flashls,Corey600/flashls,clappr/flashls,School-Improvement-Network/flashls,tedconf/flashls
|
6a26246146ce90d7d9f5fbd2616796bca7241dd6
|
assets/scripts/test.as
|
assets/scripts/test.as
|
#include "../assets/scripts/entities/camera.as"
#include "../assets/scripts/entities/dummy.as"
#include "../assets/scripts/entities/directional_light.as"
#include "../assets/scripts/entities/light.as"
#include "../assets/scripts/entities/player.as"
#include "../assets/scripts/entities/plane.as"
void main() {
camera c(glm::vec3(-10, 4, 0), glm::quat(glm::radians(-15), glm::vec3(1, 0, 0)));
c.activate();
plane pl(glm::vec3(0, 1, 0), glm::quat(glm::radians(0), glm::vec3(1, 0, 0)), glm::vec3(1));
dummy d(glm::vec3(4, 4, 0), glm::quat(glm::radians(45), glm::vec3(0, 1, 0)), glm::vec3(1.f), "meshes/dummy.msh");
light l(glm::vec3(-4.f, 4.f, 2.f), glm::vec3(1), 20);
light l2(glm::vec3(10.f, 2.f, -2.f), glm::vec3(0.f, 0.3f, 1.0f), 20);
player p(glm::vec3(-3.f, 2.f, -14.f), glm::quat(glm::radians(90), glm::vec3(0, 1, 0)), glm::vec3(1), "meshes/human.msh", "anims/human.skl");
p.impl().get_state_component().change_state("run");
directional_light dl(glm::vec3(1, 0.3, 1), glm::vec3(1), 1, true);
c.follow(p.id());
c.impl().get_camera_follow_component().initial_position(glm::vec3(0,0,0));
//d.impl().get_physics_component().apply_central_impulse(glm::vec3(5, 5, 0));
}
|
#include "../assets/scripts/entities/camera.as"
#include "../assets/scripts/entities/dummy.as"
#include "../assets/scripts/entities/directional_light.as"
#include "../assets/scripts/entities/light.as"
#include "../assets/scripts/entities/player.as"
#include "../assets/scripts/entities/plane.as"
void main() {
camera c(glm::vec3(-10, 4, 0), glm::quat(glm::radians(-15), glm::vec3(1, 0, 0)));
c.activate();
plane pl(glm::vec3(0, 1, 0), glm::quat(glm::radians(0), glm::vec3(1, 0, 0)), glm::vec3(1));
dummy d(glm::vec3(4, 4, 0), glm::quat(glm::radians(45), glm::vec3(0, 1, 0)), glm::vec3(1.f), "meshes/dummy.msh");
light l(glm::vec3(-4.f, 4.f, 2.f), glm::vec3(1), 20);
light l2(glm::vec3(10.f, 2.f, -2.f), glm::vec3(0.f, 0.3f, 1.0f), 20);
player p(glm::vec3(-3.f, 2.f, -14.f), glm::quat(glm::radians(90), glm::vec3(0, 1, 0)), glm::vec3(1), "meshes/human.msh", "anims/human.skl");
player_id = p.id();
directional_light dl(glm::vec3(1, 0.3, 1), glm::vec3(1), 1, true);
c.follow(p.id());
c.impl().get_camera_follow_component().initial_position(glm::vec3(0,0,0));
//d.impl().get_physics_component().apply_central_impulse(glm::vec3(5, 5, 0));
}
|
set player id in test.as
|
set player id in test.as
|
ActionScript
|
mit
|
kasoki/project-zombye,kasoki/project-zombye,kasoki/project-zombye
|
c7f8a2dda1f37498b1c644248a22553bd21b6ae9
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/beads/layouts/LayoutChangeNotifier.as
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/beads/layouts/LayoutChangeNotifier.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.IBead;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The LayoutChangeNotifier notifies layouts when a property
* it is watching changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class LayoutChangeNotifier implements IBead
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function LayoutChangeNotifier()
{
}
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;
}
private var _value:* = undefined;
/**
* The number of tiles to fit horizontally into the layout.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set watchedProperty(value:Object):void
{
if (_value !== value)
{
_value = value;
IBeadView(_strand).host.dispatchEvent(new Event("layoutNeeded"));
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBead;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The LayoutChangeNotifier notifies layouts when a property
* it is watching changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class LayoutChangeNotifier implements IBead
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function LayoutChangeNotifier()
{
}
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;
}
private var _value:* = undefined;
/**
* The number of tiles to fit horizontally into the layout.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set watchedProperty(value:Object):void
{
if (_value !== value)
{
_value = value;
if (_strand is IBeadView)
IBeadView(_strand).host.dispatchEvent(new Event("layoutNeeded"));
else
IEventDispatcher(_strand).dispatchEvent(new Event("layoutNeeded"));
}
}
}
}
|
handle being a bead on a component as well as a view
|
handle being a bead on a component as well as a view
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
a9871ce84d6488175a26b9c0352f05ec6074b536
|
frameworks/projects/mobiletheme/src/spark/skins/mobile/supportClasses/ActionBarButtonSkinBase.as
|
frameworks/projects/mobiletheme/src/spark/skins/mobile/supportClasses/ActionBarButtonSkinBase.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.skins.mobile.supportClasses
{
import flash.display.DisplayObject;
import flash.display.GradientType;
import flash.display.Graphics;
import flash.geom.Matrix;
import mx.core.DPIClassification;
import mx.core.mx_internal;
import mx.utils.ColorUtil;
import spark.skins.mobile.ActionBarSkin;
import spark.skins.mobile.ButtonSkin;
use namespace mx_internal;
/**
* Base skin class for ActionBar buttons in mobile applications. To support
* overlay modes in ViewNavigator, this base skin is transparent in all states
* except for the down state.
*
* @see spark.components.ActionBar
* @see spark.components.supportClasses.ViewNavigatorBase#overlayControls
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class ActionBarButtonSkinBase extends ButtonSkin
{
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
private static var matrix:Matrix = new Matrix();
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
*/
public function ActionBarButtonSkinBase()
{
super();
switch (applicationDPI)
{
case DPIClassification.DPI_640:
{
// Note provisional may need changes
layoutBorderSize = 2;
layoutPaddingTop = 24;
layoutPaddingBottom = 20;
layoutPaddingLeft = 40;
layoutPaddingRight = 40;
measuredDefaultWidth = 2012;
measuredDefaultHeight = 172;
break;
}
case DPIClassification.DPI_480:
{
// Note provisional may need changes
layoutBorderSize = 1;
layoutPaddingTop = 18;
layoutPaddingBottom = 16;
layoutPaddingLeft = 32;
layoutPaddingRight = 32;
measuredDefaultWidth = 162;
measuredDefaultHeight = 130;
break;
}
case DPIClassification.DPI_320:
{
layoutBorderSize = 1;
layoutPaddingTop = 12;
layoutPaddingBottom = 10;
layoutPaddingLeft = 20;
layoutPaddingRight = 20;
measuredDefaultWidth = 106;
measuredDefaultHeight = 86;
break;
}
case DPIClassification.DPI_240:
{
layoutBorderSize = 1;
layoutPaddingTop = 9;
layoutPaddingBottom = 8;
layoutPaddingLeft = 16;
layoutPaddingRight = 16;
measuredDefaultWidth = 81;
measuredDefaultHeight = 65;
break;
}
case DPIClassification.DPI_120:
{
// Note provisional may need changes
layoutBorderSize = 1;
layoutPaddingTop = 4;
layoutPaddingBottom = 4;
layoutPaddingLeft = 8;
layoutPaddingRight = 8;
measuredDefaultWidth = 40;
measuredDefaultHeight = 33;
break;
}
default:
{
// default DPI_160
layoutBorderSize = 1;
layoutPaddingTop = 6;
layoutPaddingBottom = 5;
layoutPaddingLeft = 10;
layoutPaddingRight = 10;
measuredDefaultWidth = 53;
measuredDefaultHeight = 43;
break;
}
}
}
/**
* @private
* Disabled state for ActionBar buttons only applies to label and icon
*/
override protected function commitDisabled():void
{
var alphaValue:Number = (hostComponent.enabled) ? 1 : 0.5
labelDisplay.alpha = alphaValue;
labelDisplayShadow.alpha = alphaValue;
var icon:DisplayObject = getIconDisplay();
if (icon != null)
icon.alpha = alphaValue;
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function drawBackground(unscaledWidth:Number, unscaledHeight:Number):void
{
// omit super.drawBackground() to drawRect instead
// only draw chromeColor in down state (transparent hit zone otherwise)
var isDown:Boolean = (currentState == "down");
var chromeColor:uint = isDown ? getStyle(fillColorStyleName) : 0;
var chromeAlpha:Number = isDown ? 1 : 0;
graphics.beginFill(chromeColor, chromeAlpha);
graphics.drawRect(0, 0, unscaledWidth, unscaledHeight);
graphics.endFill();
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.skins.mobile.supportClasses
{
import flash.display.DisplayObject;
import flash.display.GradientType;
import flash.display.Graphics;
import flash.geom.Matrix;
import mx.core.DPIClassification;
import mx.core.mx_internal;
import mx.utils.ColorUtil;
import spark.skins.mobile.ActionBarSkin;
import spark.skins.mobile.ButtonSkin;
use namespace mx_internal;
/**
* Base skin class for ActionBar buttons in mobile applications. To support
* overlay modes in ViewNavigator, this base skin is transparent in all states
* except for the down state.
*
* @see spark.components.ActionBar
* @see spark.components.supportClasses.ViewNavigatorBase#overlayControls
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class ActionBarButtonSkinBase extends ButtonSkin
{
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
private static var matrix:Matrix = new Matrix();
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
*/
public function ActionBarButtonSkinBase()
{
super();
switch (applicationDPI)
{
case DPIClassification.DPI_640:
{
// Note provisional may need changes
layoutBorderSize = 2;
layoutPaddingTop = 24;
layoutPaddingBottom = 20;
layoutPaddingLeft = 40;
layoutPaddingRight = 40;
measuredDefaultWidth = 212;
measuredDefaultHeight = 172;
break;
}
case DPIClassification.DPI_480:
{
// Note provisional may need changes
layoutBorderSize = 1;
layoutPaddingTop = 18;
layoutPaddingBottom = 16;
layoutPaddingLeft = 32;
layoutPaddingRight = 32;
measuredDefaultWidth = 162;
measuredDefaultHeight = 130;
break;
}
case DPIClassification.DPI_320:
{
layoutBorderSize = 1;
layoutPaddingTop = 12;
layoutPaddingBottom = 10;
layoutPaddingLeft = 20;
layoutPaddingRight = 20;
measuredDefaultWidth = 106;
measuredDefaultHeight = 86;
break;
}
case DPIClassification.DPI_240:
{
layoutBorderSize = 1;
layoutPaddingTop = 9;
layoutPaddingBottom = 8;
layoutPaddingLeft = 16;
layoutPaddingRight = 16;
measuredDefaultWidth = 81;
measuredDefaultHeight = 65;
break;
}
case DPIClassification.DPI_120:
{
// Note provisional may need changes
layoutBorderSize = 1;
layoutPaddingTop = 4;
layoutPaddingBottom = 4;
layoutPaddingLeft = 8;
layoutPaddingRight = 8;
measuredDefaultWidth = 40;
measuredDefaultHeight = 33;
break;
}
default:
{
// default DPI_160
layoutBorderSize = 1;
layoutPaddingTop = 6;
layoutPaddingBottom = 5;
layoutPaddingLeft = 10;
layoutPaddingRight = 10;
measuredDefaultWidth = 53;
measuredDefaultHeight = 43;
break;
}
}
}
/**
* @private
* Disabled state for ActionBar buttons only applies to label and icon
*/
override protected function commitDisabled():void
{
var alphaValue:Number = (hostComponent.enabled) ? 1 : 0.5
labelDisplay.alpha = alphaValue;
labelDisplayShadow.alpha = alphaValue;
var icon:DisplayObject = getIconDisplay();
if (icon != null)
icon.alpha = alphaValue;
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function drawBackground(unscaledWidth:Number, unscaledHeight:Number):void
{
// omit super.drawBackground() to drawRect instead
// only draw chromeColor in down state (transparent hit zone otherwise)
var isDown:Boolean = (currentState == "down");
var chromeColor:uint = isDown ? getStyle(fillColorStyleName) : 0;
var chromeAlpha:Number = isDown ? 1 : 0;
graphics.beginFill(chromeColor, chromeAlpha);
graphics.drawRect(0, 0, unscaledWidth, unscaledHeight);
graphics.endFill();
}
}
}
|
Fix for https://issues.apache.org/jira/browse/FLEX-34189
|
Fix for https://issues.apache.org/jira/browse/FLEX-34189
|
ActionScript
|
apache-2.0
|
danteinforno/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk
|
5db2c020ad380f7d0aa644e41b430ae0ba8aeab1
|
as25/src/asunit/framework/TestCase.as
|
as25/src/asunit/framework/TestCase.as
|
import asunit.flash.utils.Timer;
import asunit.errors.ClassNameUndefinedError;
import asunit.util.ArrayUtil;
import asunit.framework.AsyncOperation;
import asunit.framework.TestResult;
import asunit.framework.TestListener;
import asunit.framework.Test;
import asunit.framework.Assert;
import asunit.flash.errors.IllegalOperationError;
import asunit.flash.events.Event;
import asunit.errors.AssertionFailedError;
import asunit.util.ArrayIterator;
import asunit.util.Iterator;
/**
* A test case defines the fixture to run multiple tests. To define a test case<br>
* 1) implement a subclass of TestCase<br>
* 2) define instance variables that store the state of the fixture<br>
* 3) initialize the fixture state by overriding <code>setUp</code><br>
* 4) clean-up after a test by overriding <code>tearDown</code>.<br>
* Each test runs in its own fixture so there
* can be no side effects among test runs.
* Here is an example:
* <pre>
* public class MathTest extends TestCase {
* protected double fValue1;
* protected double fValue2;
*
* protected void setUp() {
* fValue1= 2.0;
* fValue2= 3.0;
* }
* }
* </pre>
*
* For each test implement a method which interacts
* with the fixture. Verify the expected results with assertions specified
* by calling <code>assertTrue</code> with a boolean.
* <pre>
* public void testAdd() {
* double result= fValue1 + fValue2;
* assertTrue(result == 5.0);
* }
* </pre>
* Once the methods are defined you can run them. The framework supports
* both a static type safe and more dynamic way to run a test.
* In the static way you override the runTest method and define the method to
* be invoked. A convenient way to do so is with an anonymous inner class.
* <pre>
* TestCase test= new MathTest("add") {
* public void runTest() {
* testAdd();
* }
* };
* test.run();
* </pre>
* The dynamic way uses reflection to implement <code>runTest</code>. It dynamically finds
* and invokes a method.
* In this case the name of the test case has to correspond to the test method
* to be run.
* <pre>
* TestCase= new MathTest("testAdd");
* test.run();
* </pre>
* The tests to be run can be collected into a TestSuite. JUnit provides
* different <i>test runners</i> which can run a test suite and collect the results.
* A test runner either expects a static method <code>suite</code> as the entry
* point to get a test to run or it will extract the suite automatically.
* <pre>
* public static Test suite() {
* suite.addTest(new MathTest("testAdd"));
* suite.addTest(new MathTest("testDivideByZero"));
* return suite;
* }
* </pre>
* @see TestResult
* @see TestSuite
*/
class asunit.framework.TestCase extends Assert implements Test {
private static var PRE_SET_UP:Number = 0;
private static var SET_UP:Number = 1;
private static var RUN_METHOD:Number = 2;
private static var TEAR_DOWN:Number = 3;
private static var DEFAULT_TIMEOUT:Number = 1000;
private var className:String;
private var fName:String;
private var result : TestListener;
private var testMethods:Array;
private var isComplete:Boolean;
private var context : MovieClip;
private var asyncQueue:Array;
private var currentMethod:String;
private var runSingle:Boolean;
private var methodIterator:Iterator;
private var layoutManager:Object;
private var currentState:Number;
private static var lastDepth:Number = 10;
/**
* Constructs a test case with the given name.
*/
public function TestCase(testMethod:String) {
if(testMethod==undefined) testMethod=null;
if(testMethod != null) {
testMethods = testMethod.split(", ").join(",").split(",");
if(testMethods.length == 1) {
runSingle = true;
}
} else {
setTestMethods(this);
}
setName(this.className);
// I don't think this is necessary for as2
// resolveLayoutManager();
asyncQueue = [];
}
/* private function resolveLayoutManager():Void {
// Avoid creating import dependencies on flex framework
// If you have the framework.swc in your classpath,
// the layout manager will be found, if not, a mcok
// will be used.
try {
var manager:Class = getDefinitionByName("mx.managers.LayoutManager") as Class;
layoutManager = manager["getInstance"]();
if(!layoutManager.hasOwnProperty("resetAll")) {
throw new Error("TestCase :: mx.managers.LayoutManager missing resetAll method");
}
}
catch(e:Error) {
layoutManager = new Object();
layoutManager.resetAll = function():Void {
};
}
}
*/
/**
* Sets the name of a TestCase
* @param name The name to set
*/
public function setName(name:String):Void {
if(name==undefined || name==null){
throw new ClassNameUndefinedError("You must assign a ClassName for your TestCase subclass.")
}
fName = name;
}
private function setTestMethods(obj:Object):Void {
testMethods = [];
_global.ASSetPropFlags(obj.__proto__, null, 6, true);
for(var prop:String in obj) {
// look for functions starting with "test"
if((prop.indexOf("test")==0) && (obj[prop] instanceof Function)){
testMethods.push(prop);
}
}
_global.ASSetPropFlags(this.__proto__, null, 1, true);
testMethods.reverse();
}
public function getTestMethods():Array {
return testMethods;
}
/**
* Counts the number of test cases executed by run(TestResult result).
*/
public function countTestCases():Number {
return testMethods.length;
}
/**
* Creates a default TestResult object
*
* @see TestResult
*/
private function createResult():TestResult {
return new TestResult();
}
/**
* A convenience method to run this test, collecting the results with
* either the TestResult provided or a default, new TestResult object.
* Expects either:
* run():Void // will return the newly created TestResult
* run(result:TestResult):TestResult // will use the TestResult
* that was passed in.
*
* @see TestResult
*/
public function run():Void {
getResult().run(this);
}
public function setResult(result:TestListener):Void {
this.result = result;
}
public function getResult():TestListener {
return (result == null) ? createResult() : result;
}
/**
* Runs the bare test sequence.
* @exception Error if any exception is thrown
* throws Error
*/
public function runBare():Void {
if(isComplete) {
return;
}
var name:String;
var itr:Iterator = getMethodIterator();
if(itr.hasNext()) {
name = String(itr.next());
currentState = PRE_SET_UP;
runMethod(name);
}
else {
cleanUp();
getResult().endTest(this);
isComplete = true;
dispatchEvent(new Event(Event.COMPLETE));
}
}
private function getMethodIterator():Iterator {
if(methodIterator == null) {
methodIterator = new ArrayIterator(testMethods);
}
return methodIterator;
}
// Override this method in Asynchronous test cases
// or any other time you want to perform additional
// member cleanup after all test methods have run
private function cleanUp():Void {
}
private function runMethod(methodName:String):Void {
try {
if(currentState == PRE_SET_UP) {
currentState = SET_UP;
getResult().startTestMethod(this, methodName);
setUp(); // setUp may be async and change the state of methodIsAsynchronous
}
currentMethod = methodName;
if(!waitForAsync()) {
currentState = RUN_METHOD;
this[methodName]();
}
}
catch(assertionFailedError:AssertionFailedError) {
getResult().addFailure(this, assertionFailedError);
}
catch(unknownError:Error) {
getResult().addError(this, unknownError);
}
finally {
if(!waitForAsync()) {
runTearDown();
}
}
}
/**
* Sets up the fixture, for example, instantiate a mock object.
* This method is called before each test is executed.
* throws Exception on error
*/
private function setUp():Void {
}
/**
* Tears down the fixture, for example, delete mock object.
* This method is called after a test is executed.
* throws Exception on error
*/
private function tearDown():Void {
}
/**
* Returns a string representation of the test case
*/
public function toString():String {
if(getCurrentMethod()) {
return getName() + "." + getCurrentMethod() + "()";
}
else {
return getName();
}
}
/**
* Gets the name of a TestCase
* @return returns a String
*/
public function getName():String {
return fName;
}
public function getCurrentMethod():String {
return currentMethod;
}
public function getIsComplete():Boolean {
return isComplete;
}
public function setContext(context:MovieClip):Void {
this.context = context;
}
public function getContext():MovieClip {
return context;
}
private function addAsync(handler:Function, duration:Number):Function {
if(handler == undefined) {
handler = function():Void{};
}
if(duration == undefined) {
duration = DEFAULT_TIMEOUT;
}
var async:AsyncOperation = new AsyncOperation(this, handler, duration);
asyncQueue.push(async);
return async.getCallback();
}
public function asyncOperationTimeout(async:AsyncOperation, duration:Number):Void{
getResult().addError(this, new IllegalOperationError("TestCase.timeout (" + duration + "ms) exceeded on an asynchronous operation."));
asyncOperationComplete(async);
}
public function asyncOperationComplete(async:AsyncOperation):Void{
// remove operation from queue
var i:Number = ArrayUtil.indexOf(asyncQueue, async);
asyncQueue.splice(i,1);
// if we still need to wait, return
if(waitForAsync()) return;
if(currentState == SET_UP) {
runMethod(currentMethod);
}
else if(currentState == RUN_METHOD) {
runTearDown();
}
}
private function waitForAsync():Boolean{
return asyncQueue.length > 0;
}
private function runTearDown():Void {
currentState = TEAR_DOWN;
if(isComplete) {
return;
}
if(!runSingle) {
getResult().endTestMethod(this, currentMethod);
tearDown();
}
Timer.setTimeout(this, runBare, 5);
}
/**
* begin asunit25 specific methods
*/
private function createEmptyMovieClip(name:String, depth:Number):MovieClip {
if(depth==undefined || depth===null) depth = getNextHighestDepth();
return getContext().createEmptyMovieClip(name, depth);
}
private function createTextField(name:String, depth:Number, x:Number, y:Number, width:Number, height:Number):TextField {
getContext().createTextField(name, depth, x, y, width, height);
return TextField(getContext()[name]);
}
private function getNextHighestDepth():Number {
return getContext().getNextHighestDepth();
}
/*
* This helper method will support the following method signatures:
*
* attachMovie(linkageId:String):MovieClip;
* attachMovie(linkageId:String, initObject:Object):MovieClip;
* attachMovie(linkageId:String, name:String, depth:Number):MovieClip;
* attachMovie(linkageId:String, name:String, depth:Number, initObject:Object):MovieClip;
*
* @return
* MovieClip
*/
private function attachMovie():MovieClip {
var linkageId:String = arguments[0];
var name:String;
var depth:Number;
var initObj:Object = new Object();
switch(arguments.length) {
case 1 :
case 2 :
name = getValidName(getContext(), name);
depth = getValidDepth(getContext());
initObj = arguments[1];
break;
case 3 :
case 4 :
name = arguments[1];
depth = arguments[2];
initObj = arguments[3];
break;
}
return getContext().attachMovie(linkageId, name, depth, initObj);
}
public function getUpperEmptyDepth(parent:MovieClip, depth:Number):Number {
if(depth == undefined || !isValidDepth(parent, depth)) {
var high:Number = (depth == undefined) ? 1 : depth;
for(var i:String in parent) {
if(parent[i] instanceof MovieClip && parent[i].getDepth() != undefined) {
high = Math.max(parent[i].getDepth()+1, high);
}
}
return high;
}
return depth;
}
private function getValidName(parent:MovieClip, nm:Object):String {
var incr:Number = 1;
var name:String = (nm == undefined || nm instanceof Object) ? "item" : nm.toString();
var ref:MovieClip = parent[name];
var name2:String = name;
while(ref != undefined && incr < 100) {
name2 = name + "-" + (incr++);
ref = parent[name2];
}
return name2;
}
private function isValidDepth(parent:MovieClip, depth:Number):Boolean {
var item:MovieClip = getItemByDepth(parent, depth);
return (item == null) ? true : false;
}
private function getItemByDepth(parent:MovieClip, depth:Number):MovieClip {
for(var i:String in parent) {
if(parent[i].getDepth() == depth) {
return parent[i];
}
}
return null;
}
/**
* Returns the next available depth for attaching a MovieClip.
*
* @return
* Number of next available depth.
*/
public static function nextDepth():Number {
return lastDepth++;
}
private function getValidDepth(mc:MovieClip):Number {
var mcDepth:Number;
var dp:Number = nextDepth();
for(var i:String in mc) {
mcDepth = mc[i].getDepth();
if(mc[i] instanceof MovieClip && mcDepth < 10000) {
dp = Math.max(mcDepth, dp);
}
}
return ++dp;
}
}
|
import asunit.flash.utils.Timer;
import asunit.errors.ClassNameUndefinedError;
import asunit.util.ArrayUtil;
import asunit.framework.AsyncOperation;
import asunit.framework.TestResult;
import asunit.framework.TestListener;
import asunit.framework.Test;
import asunit.framework.Assert;
import asunit.flash.errors.IllegalOperationError;
import asunit.flash.events.Event;
import asunit.errors.AssertionFailedError;
import asunit.util.ArrayIterator;
import asunit.util.Iterator;
/**
* A test case defines the fixture to run multiple tests. To define a test case<br>
* 1) implement a subclass of TestCase<br>
* 2) define instance variables that store the state of the fixture<br>
* 3) initialize the fixture state by overriding <code>setUp</code><br>
* 4) clean-up after a test by overriding <code>tearDown</code>.<br>
* Each test runs in its own fixture so there
* can be no side effects among test runs.
* Here is an example:
* <pre>
* public class MathTest extends TestCase {
* protected double fValue1;
* protected double fValue2;
*
* protected void setUp() {
* fValue1= 2.0;
* fValue2= 3.0;
* }
* }
* </pre>
*
* For each test implement a method which interacts
* with the fixture. Verify the expected results with assertions specified
* by calling <code>assertTrue</code> with a boolean.
* <pre>
* public void testAdd() {
* double result= fValue1 + fValue2;
* assertTrue(result == 5.0);
* }
* </pre>
* Once the methods are defined you can run them. The framework supports
* both a static type safe and more dynamic way to run a test.
* In the static way you override the runTest method and define the method to
* be invoked. A convenient way to do so is with an anonymous inner class.
* <pre>
* TestCase test= new MathTest("add") {
* public void runTest() {
* testAdd();
* }
* };
* test.run();
* </pre>
* The dynamic way uses reflection to implement <code>runTest</code>. It dynamically finds
* and invokes a method.
* In this case the name of the test case has to correspond to the test method
* to be run.
* <pre>
* TestCase= new MathTest("testAdd");
* test.run();
* </pre>
* The tests to be run can be collected into a TestSuite. JUnit provides
* different <i>test runners</i> which can run a test suite and collect the results.
* A test runner either expects a static method <code>suite</code> as the entry
* point to get a test to run or it will extract the suite automatically.
* <pre>
* public static Test suite() {
* suite.addTest(new MathTest("testAdd"));
* suite.addTest(new MathTest("testDivideByZero"));
* return suite;
* }
* </pre>
* @see TestResult
* @see TestSuite
*/
class asunit.framework.TestCase extends Assert implements Test {
private static var PRE_SET_UP:Number = 0;
private static var SET_UP:Number = 1;
private static var RUN_METHOD:Number = 2;
private static var TEAR_DOWN:Number = 3;
private static var DEFAULT_TIMEOUT:Number = 1000;
private var className:String;
private var fName:String;
private var result : TestListener;
private var testMethods:Array;
private var isComplete:Boolean;
private var context : MovieClip;
private var asyncQueue:Array;
private var currentMethod:String;
private var runSingle:Boolean;
private var methodIterator:Iterator;
private var layoutManager:Object;
private var currentState:Number;
private static var lastDepth:Number = 10;
/**
* Constructs a test case with the given name.
*/
public function TestCase(testMethod:String) {
if(testMethod==undefined) testMethod=null;
if(testMethod != null) {
testMethods = testMethod.split(", ").join(",").split(",");
if(testMethods.length == 1) {
runSingle = true;
}
} else {
setTestMethods(this);
}
try {
setName(this.className);
}
catch(e:ClassNameUndefinedError) {
trace(">> WARNING: Concrete TestCase classes must have a 'className' parameter with the fully qualified class name in order for AsUnit to provide useful failures.");
}
// resolveLayoutManager();
asyncQueue = [];
}
/* private function resolveLayoutManager():Void {
// Avoid creating import dependencies on flex framework
// If you have the framework.swc in your classpath,
// the layout manager will be found, if not, a mcok
// will be used.
try {
var manager:Class = getDefinitionByName("mx.managers.LayoutManager") as Class;
layoutManager = manager["getInstance"]();
if(!layoutManager.hasOwnProperty("resetAll")) {
throw new Error("TestCase :: mx.managers.LayoutManager missing resetAll method");
}
}
catch(e:Error) {
layoutManager = new Object();
layoutManager.resetAll = function():Void {
};
}
}
*/
/**
* Sets the name of a TestCase
* @param name The name to set
*/
public function setName(name:String):Void {
if(name==undefined || name==null){
throw new ClassNameUndefinedError("You must assign a ClassName for your TestCase subclass.")
}
fName = name;
}
private function setTestMethods(obj:Object):Void {
testMethods = [];
_global.ASSetPropFlags(obj.__proto__, null, 6, true);
for(var prop:String in obj) {
// look for functions starting with "test"
if((prop.indexOf("test")==0) && (obj[prop] instanceof Function)){
testMethods.push(prop);
}
}
_global.ASSetPropFlags(this.__proto__, null, 1, true);
testMethods.reverse();
}
public function getTestMethods():Array {
return testMethods;
}
/**
* Counts the number of test cases executed by run(TestResult result).
*/
public function countTestCases():Number {
return testMethods.length;
}
/**
* Creates a default TestResult object
*
* @see TestResult
*/
private function createResult():TestResult {
return new TestResult();
}
/**
* A convenience method to run this test, collecting the results with
* either the TestResult provided or a default, new TestResult object.
* Expects either:
* run():Void // will return the newly created TestResult
* run(result:TestResult):TestResult // will use the TestResult
* that was passed in.
*
* @see TestResult
*/
public function run():Void {
getResult().run(this);
}
public function setResult(result:TestListener):Void {
this.result = result;
}
public function getResult():TestListener {
return (result == null) ? createResult() : result;
}
/**
* Runs the bare test sequence.
* @exception Error if any exception is thrown
* throws Error
*/
public function runBare():Void {
if(isComplete) {
return;
}
var name:String;
var itr:Iterator = getMethodIterator();
if(itr.hasNext()) {
name = String(itr.next());
currentState = PRE_SET_UP;
runMethod(name);
}
else {
cleanUp();
getResult().endTest(this);
isComplete = true;
dispatchEvent(new Event(Event.COMPLETE));
}
}
private function getMethodIterator():Iterator {
if(methodIterator == null) {
methodIterator = new ArrayIterator(testMethods);
}
return methodIterator;
}
// Override this method in Asynchronous test cases
// or any other time you want to perform additional
// member cleanup after all test methods have run
private function cleanUp():Void {
}
private function runMethod(methodName:String):Void {
try {
if(currentState == PRE_SET_UP) {
currentState = SET_UP;
getResult().startTestMethod(this, methodName);
setUp(); // setUp may be async and change the state of methodIsAsynchronous
}
currentMethod = methodName;
if(!waitForAsync()) {
currentState = RUN_METHOD;
this[methodName]();
}
}
catch(assertionFailedError:AssertionFailedError) {
getResult().addFailure(this, assertionFailedError);
}
catch(unknownError:Error) {
getResult().addError(this, unknownError);
}
finally {
if(!waitForAsync()) {
runTearDown();
}
}
}
/**
* Sets up the fixture, for example, instantiate a mock object.
* This method is called before each test is executed.
* throws Exception on error
*/
private function setUp():Void {
}
/**
* Tears down the fixture, for example, delete mock object.
* This method is called after a test is executed.
* throws Exception on error
*/
private function tearDown():Void {
}
/**
* Returns a string representation of the test case
*/
public function toString():String {
if(getCurrentMethod()) {
return getName() + "." + getCurrentMethod() + "()";
}
else {
return getName();
}
}
/**
* Gets the name of a TestCase
* @return returns a String
*/
public function getName():String {
return fName;
}
public function getCurrentMethod():String {
return currentMethod;
}
public function getIsComplete():Boolean {
return isComplete;
}
public function setContext(context:MovieClip):Void {
this.context = context;
}
public function getContext():MovieClip {
return context;
}
private function addAsync(handler:Function, duration:Number):Function {
if(handler == undefined) {
handler = function():Void{};
}
if(duration == undefined) {
duration = DEFAULT_TIMEOUT;
}
var async:AsyncOperation = new AsyncOperation(this, handler, duration);
asyncQueue.push(async);
return async.getCallback();
}
public function asyncOperationTimeout(async:AsyncOperation, duration:Number):Void{
getResult().addError(this, new IllegalOperationError("TestCase.timeout (" + duration + "ms) exceeded on an asynchronous operation."));
asyncOperationComplete(async);
}
public function asyncOperationComplete(async:AsyncOperation):Void{
// remove operation from queue
var i:Number = ArrayUtil.indexOf(asyncQueue, async);
asyncQueue.splice(i,1);
// if we still need to wait, return
if(waitForAsync()) return;
if(currentState == SET_UP) {
runMethod(currentMethod);
}
else if(currentState == RUN_METHOD) {
runTearDown();
}
}
private function waitForAsync():Boolean{
return asyncQueue.length > 0;
}
private function runTearDown():Void {
currentState = TEAR_DOWN;
if(isComplete) {
return;
}
if(!runSingle) {
getResult().endTestMethod(this, currentMethod);
tearDown();
}
Timer.setTimeout(this, runBare, 5);
}
/**
* begin asunit25 specific methods
*/
private function createEmptyMovieClip(name:String, depth:Number):MovieClip {
if(depth==undefined || depth===null) depth = getNextHighestDepth();
return getContext().createEmptyMovieClip(name, depth);
}
private function createTextField(name:String, depth:Number, x:Number, y:Number, width:Number, height:Number):TextField {
getContext().createTextField(name, depth, x, y, width, height);
return TextField(getContext()[name]);
}
private function getNextHighestDepth():Number {
return getContext().getNextHighestDepth();
}
/*
* This helper method will support the following method signatures:
*
* attachMovie(linkageId:String):MovieClip;
* attachMovie(linkageId:String, initObject:Object):MovieClip;
* attachMovie(linkageId:String, name:String, depth:Number):MovieClip;
* attachMovie(linkageId:String, name:String, depth:Number, initObject:Object):MovieClip;
*
* @return
* MovieClip
*/
private function attachMovie():MovieClip {
var linkageId:String = arguments[0];
var name:String;
var depth:Number;
var initObj:Object = new Object();
switch(arguments.length) {
case 1 :
case 2 :
name = getValidName(getContext(), name);
depth = getValidDepth(getContext());
initObj = arguments[1];
break;
case 3 :
case 4 :
name = arguments[1];
depth = arguments[2];
initObj = arguments[3];
break;
}
return getContext().attachMovie(linkageId, name, depth, initObj);
}
public function getUpperEmptyDepth(parent:MovieClip, depth:Number):Number {
if(depth == undefined || !isValidDepth(parent, depth)) {
var high:Number = (depth == undefined) ? 1 : depth;
for(var i:String in parent) {
if(parent[i] instanceof MovieClip && parent[i].getDepth() != undefined) {
high = Math.max(parent[i].getDepth()+1, high);
}
}
return high;
}
return depth;
}
private function getValidName(parent:MovieClip, nm:Object):String {
var incr:Number = 1;
var name:String = (nm == undefined || nm instanceof Object) ? "item" : nm.toString();
var ref:MovieClip = parent[name];
var name2:String = name;
while(ref != undefined && incr < 100) {
name2 = name + "-" + (incr++);
ref = parent[name2];
}
return name2;
}
private function isValidDepth(parent:MovieClip, depth:Number):Boolean {
var item:MovieClip = getItemByDepth(parent, depth);
return (item == null) ? true : false;
}
private function getItemByDepth(parent:MovieClip, depth:Number):MovieClip {
for(var i:String in parent) {
if(parent[i].getDepth() == depth) {
return parent[i];
}
}
return null;
}
/**
* Returns the next available depth for attaching a MovieClip.
*
* @return
* Number of next available depth.
*/
public static function nextDepth():Number {
return lastDepth++;
}
private function getValidDepth(mc:MovieClip):Number {
var mcDepth:Number;
var dp:Number = nextDepth();
for(var i:String in mc) {
mcDepth = mc[i].getDepth();
if(mc[i] instanceof MovieClip && mcDepth < 10000) {
dp = Math.max(mcDepth, dp);
}
}
return ++dp;
}
}
|
Change failure to add 'className' to a test case from a sielent error to a traced warning
|
Change failure to add 'className' to a test case from a sielent error to a traced warning
|
ActionScript
|
mit
|
patternpark/asunit,lukebayes/asunit,robertpenner/asunit
|
616f18546c777108dd2b7b39d2e4f524bbfd42c1
|
src/as/com/threerings/util/NetUtil.as
|
src/as/com/threerings/util/NetUtil.as
|
package com.threerings.util {
import flash.net.URLRequest;
//import flash.net.navigateToURL; // function import
public class NetUtil
{
/**
* Convenience method to load a web page in the browser window without
* having to worry about SecurityErrors in various conditions.
*/
public static function navigateToURL (
url :String, preferSameWindowOrTab :Boolean = true) :void
{
var ureq :URLRequest = new URLRequest(url);
if (preferSameWindowOrTab) {
try {
flash.net.navigateToURL(ureq, "_self");
return;
} catch (err :SecurityError) {
// ignore; fall back to using a blank window, below...
}
}
// open in a blank window
try {
flash.net.navigateToURL(ureq);
} catch (err :SecurityError) {
Log.getLog(NetUtil).warning(
"Unable to navigate to URL [e=" + err + "].");
}
}
}
}
|
package com.threerings.util {
import flash.net.URLRequest;
//import flash.net.navigateToURL; // function import
public class NetUtil
{
/**
* Convenience method to load a web page in the browser window without
* having to worry about SecurityErrors in various conditions.
*
* @return true if the url was unable to be loaded.
*/
public static function navigateToURL (
url :String, preferSameWindowOrTab :Boolean = true) :Boolean
{
var ureq :URLRequest = new URLRequest(url);
if (preferSameWindowOrTab) {
try {
flash.net.navigateToURL(ureq, "_self");
return true;
} catch (err :SecurityError) {
// ignore; fall back to using a blank window, below...
}
}
// open in a blank window
try {
flash.net.navigateToURL(ureq);
return true;
} catch (err :SecurityError) {
Log.getLog(NetUtil).warning(
"Unable to navigate to URL [e=" + err + "].");
}
return false; // failure!
}
}
}
|
Return true if we succeeded.
|
Return true if we succeeded.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4462 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
347ea4b58b3aef60c59e074375a40aa421b7efe8
|
FlexUnit4CIListener/src/org/flexunit/listeners/CIListener.as
|
FlexUnit4CIListener/src/org/flexunit/listeners/CIListener.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 Jeff Tapper
* @version
**/
package org.flexunit.listeners
{
import flash.events.DataEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.XMLSocket;
import flash.utils.Timer;
import org.flexunit.listeners.closer.ApplicationCloser;
import org.flexunit.listeners.closer.StandAloneFlashPlayerCloser;
import org.flexunit.reporting.FailureFormatter;
import org.flexunit.runner.Descriptor;
import org.flexunit.runner.IDescription;
import org.flexunit.runner.Result;
import org.flexunit.runner.notification.Failure;
import org.flexunit.runner.notification.IAsyncStartupRunListener;
import org.flexunit.runner.notification.ITemporalRunListener;
import org.flexunit.runner.notification.async.AsyncListenerWatcher;
public class CIListener extends EventDispatcher implements IAsyncStartupRunListener, ITemporalRunListener
{
protected static const DEFAULT_PORT : uint = 1024;
protected static const DEFAULT_SERVER : String = "127.0.0.1";
private static const SUCCESS:String = "success";
private static const ERROR:String = "error";
private static const FAILURE:String = "failure";
private static const IGNORE:String = "ignore";
private var successes:Array = new Array();
private var ignores:Array = new Array();
private var _ready:Boolean = false;
private static const END_OF_TEST_ACK : String ="<endOfTestRunAck/>";
private static const END_OF_TEST_RUN : String = "<endOfTestRun/>";
private static const START_OF_TEST_RUN_ACK : String = "<startOfTestRunAck/>";
private var socket:XMLSocket;
[Inspectable]
public var port : uint;
[Inspectable]
public var server : String; //this is local host. same machine
public var closer : ApplicationCloser;
private var lastFailedTest:IDescription;
private var timeOut:Timer;
private var lastTestTime:Number;
public function CIListener(port : uint = DEFAULT_PORT, server : String = DEFAULT_SERVER)
{
this.port = port;
this.server = server;
this.closer = new StandAloneFlashPlayerCloser(); //default application closer
socket = new XMLSocket ();
socket.addEventListener( DataEvent.DATA, dataHandler );
socket.addEventListener( Event.CONNECT, handleConnect );
socket.addEventListener( IOErrorEvent.IO_ERROR, errorHandler);
socket.addEventListener( SecurityErrorEvent.SECURITY_ERROR,errorHandler);
socket.addEventListener( Event.CLOSE,errorHandler);
timeOut = new Timer( 2000, 1 );
timeOut.addEventListener(TimerEvent.TIMER_COMPLETE, declareBroken, false, 0, true );
timeOut.start();
try
{
socket.connect( server, port );
timeOut.stop();
} catch (e:Error) {
//This needs to be more than a trace
trace (e.message);
}
}
private function declareBroken( event:TimerEvent ):void {
errorHandler( new Event( "broken") );
}
[Bindable(event="listenerReady")]
public function get ready():Boolean
{
return _ready;
}
private function setStatusReady():void {
_ready = true;
dispatchEvent( new Event( AsyncListenerWatcher.LISTENER_READY ) );
}
private function getTestCount( description:IDescription ):int
{
return description.testCount;
}
private function testTimeString( time:Number ):String {
var timeShifted:Number = time * 1000;
var timeFloor:Number = Math.floor( timeShifted );
var timeStr:String = String( ( timeFloor/1000 ) );
return timeStr;
}
public function testTimed( description:IDescription, runTime:Number ):void {
lastTestTime = runTime;
//trace( description.displayName + " took " + runTime + " ms " );
}
public function testRunStarted( description:IDescription ):void
{
//Since description tells us nothing about failure, error, and skip counts, this is
//computed by the Ant task as the process executes and no work is needed to signify
//the start of a test run.
}
public function testRunFinished( result:Result ):void
{
sendResults(END_OF_TEST_RUN);
}
public function testStarted( description:IDescription ):void
{
// called before each test
}
public function testFinished( description:IDescription ):void
{
// called after each test
if(!lastFailedTest || description.displayName != lastFailedTest.displayName){
var desc:Descriptor = getDescriptorFromDescription(description);
sendResults("<testcase classname='"+desc.suite+"' name='"+desc.method+"' time='" + testTimeString( lastTestTime ) +"' status='"+SUCCESS+"'/>");
}
}
public function testAssumptionFailure( failure:Failure ):void
{
// called on assumptionFail
}
public function testIgnored( description:IDescription ):void
{
// called on ignored test if we want to send ignore to ant.
var descriptor:Descriptor = getDescriptorFromDescription(description);
var xml:String =
"<testcase classname='"+descriptor.suite+"' name='"+descriptor.method+"' time='" + testTimeString( lastTestTime ) + "' status='"+IGNORE+"'>"
+ "<skipped />"
+ "</testcase>";
sendResults( xml );
}
public function testFailure( failure:Failure ):void
{
// called on a test failure
lastFailedTest = failure.description;
var descriptor:Descriptor =
getDescriptorFromDescription(failure.description);
var type : String = failure.description.displayName
var message : String = failure.message;
var stackTrace : String = failure.stackTrace;
var methodName : String = descriptor.method;
if ( stackTrace != null ) stackTrace = stackTrace.toString();
stackTrace = FailureFormatter.xmlEscapeMessage( stackTrace );
message = FailureFormatter.xmlEscapeMessage( message );
var xml : String = null;
if(FailureFormatter.isError(failure.exception))
{
xml =
"<testcase classname='"+descriptor.suite+"' name='"+descriptor.method+"' time='" + testTimeString( lastTestTime ) +"' status='"+ERROR+"'>"
+ "<error message='" + message + "' type='"+ type +"' >"
+ "<![CDATA[" + stackTrace + "]]>"
+ "</error>"
+ "</testcase>";
}
else
{
xml =
"<testcase classname='"+descriptor.suite+"' name='"+descriptor.method+"' time='" + testTimeString( lastTestTime ) +"' status='"+FAILURE+"'>"
+ "<failure message='" + message + "' type='"+ type +"' >"
+ "<![CDATA[" + stackTrace + "]]>"
+ "</failure>"
+ "</testcase>";
}
sendResults(xml);
}
/*
* Internal methods
*/
private function getDescriptorFromDescription( description:IDescription ):Descriptor
{
// reads relavent data from descriptor
/**
* JAdkins - 7/27/07 - FXU-53 - Listener was returning a null value for the test class
* causing no data to be returned. If length of array is greater than 1, then class is
* not in the default package. If array length is 1, then test class is default package
* and formats accordingly.
**/
var descriptor:Descriptor = new Descriptor();
var descriptionArray:Array = description.displayName.split("::");
var classMethod:String;
if ( descriptionArray.length > 1 )
{
descriptor.path = descriptionArray[0];
classMethod = descriptionArray[1];
}
else
{
classMethod = descriptionArray[0];
}
var classMethodArray:Array = classMethod.split(".");
descriptor.suite = ( descriptor.path == "" ) ? classMethodArray[0] :
descriptor.path + "::" + classMethodArray[0];
descriptor.method = classMethodArray[1];
return descriptor;
}
protected function sendResults(msg:String):void
{
if(socket.connected)
{
socket.send( msg );
}
trace(msg);
}
private function handleConnect(event:Event):void
{
//This is a good start, but we are no longer considering this a valid
//time to begin sending results
//We are going to wait until we get some data first
//_ready = true;
//dispatchEvent( new Event( AsyncListenerWatcher.LISTENER_READY ) );
}
private function errorHandler(event:Event):void
{
if ( !ready ) {
//If we are not yet ready and received this, just inform the core so it can move on
dispatchEvent( new Event( AsyncListenerWatcher.LISTENER_FAILED ) );
} else {
//If on the other hand we were ready once, then the core is counting on us... so, if something goes
//wrong now, we are likely hung up. For now we are simply going to bail out of this process
exit();
}
}
private function dataHandler( event : DataEvent ) : void
{
var data : String = event.data;
// If we received an acknowledgement on startup, the java server is read and we can start sending.
if ( data == START_OF_TEST_RUN_ACK ) {
setStatusReady();
} else if ( data == END_OF_TEST_ACK ) {
// If we received an acknowledgement finish-up.
// Close the socket.
socket.close();
exit();
}
}
/**
* Exit the test runner by calling the ApplicationCloser.
*/
protected function exit() : void
{
this.closer.close();
}
}
}
|
/**
* 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 Jeff Tapper
* @version
**/
package org.flexunit.listeners
{
import flash.events.DataEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.XMLSocket;
import flash.utils.Timer;
import org.flexunit.listeners.closer.ApplicationCloser;
import org.flexunit.listeners.closer.StandAloneFlashPlayerCloser;
import org.flexunit.reporting.FailureFormatter;
import org.flexunit.runner.Descriptor;
import org.flexunit.runner.IDescription;
import org.flexunit.runner.Result;
import org.flexunit.runner.notification.Failure;
import org.flexunit.runner.notification.IAsyncStartupRunListener;
import org.flexunit.runner.notification.ITemporalRunListener;
import org.flexunit.runner.notification.async.AsyncListenerWatcher;
public class CIListener extends EventDispatcher implements IAsyncStartupRunListener, ITemporalRunListener
{
protected static const DEFAULT_PORT : uint = 1024;
protected static const DEFAULT_SERVER : String = "127.0.0.1";
private static const SUCCESS:String = "success";
private static const ERROR:String = "error";
private static const FAILURE:String = "failure";
private static const IGNORE:String = "ignore";
private var successes:Array = new Array();
private var ignores:Array = new Array();
private var _ready:Boolean = false;
private static const END_OF_TEST_ACK : String ="<endOfTestRunAck/>";
private static const END_OF_TEST_RUN : String = "<endOfTestRun/>";
private static const START_OF_TEST_RUN_ACK : String = "<startOfTestRunAck/>";
private var socket:XMLSocket;
[Inspectable]
public var port : uint;
[Inspectable]
public var server : String; //this is local host. same machine
public var closer : ApplicationCloser;
private var lastFailedTest:IDescription;
private var timeOut:Timer;
private var lastTestTime:Number;
public function CIListener(port : uint = DEFAULT_PORT, server : String = DEFAULT_SERVER)
{
this.port = port;
this.server = server;
this.closer = new StandAloneFlashPlayerCloser(); //default application closer
socket = new XMLSocket ();
socket.addEventListener( DataEvent.DATA, dataHandler );
socket.addEventListener( Event.CONNECT, handleConnect );
socket.addEventListener( IOErrorEvent.IO_ERROR, errorHandler);
socket.addEventListener( SecurityErrorEvent.SECURITY_ERROR,errorHandler);
socket.addEventListener( Event.CLOSE,errorHandler);
timeOut = new Timer( 2000, 1 );
timeOut.addEventListener(TimerEvent.TIMER_COMPLETE, declareBroken, false, 0, true );
timeOut.start();
try
{
socket.connect( server, port );
timeOut.stop();
} catch (e:Error) {
//This needs to be more than a trace
trace (e.message);
}
}
private function declareBroken( event:TimerEvent ):void {
errorHandler( new Event( "broken") );
}
[Bindable(event="listenerReady")]
public function get ready():Boolean
{
return _ready;
}
private function setStatusReady():void {
_ready = true;
dispatchEvent( new Event( AsyncListenerWatcher.LISTENER_READY ) );
}
private function getTestCount( description:IDescription ):int
{
return description.testCount;
}
private function testTimeString( time:Number ):String {
var timeShifted:Number = time * 1000;
var timeFloor:Number = Math.floor( timeShifted );
var timeStr:String = String( ( timeFloor/1000 ) );
return timeStr;
}
public function testTimed( description:IDescription, runTime:Number ):void {
lastTestTime = runTime;
//trace( description.displayName + " took " + runTime + " ms " );
}
public function testRunStarted( description:IDescription ):void
{
//Since description tells us nothing about failure, error, and skip counts, this is
//computed by the Ant task as the process executes and no work is needed to signify
//the start of a test run.
}
public function testRunFinished( result:Result ):void
{
sendResults(END_OF_TEST_RUN);
}
public function testStarted( description:IDescription ):void
{
// called before each test
}
public function testFinished( description:IDescription ):void
{
// called after each test
if(!lastFailedTest || description.displayName != lastFailedTest.displayName){
var desc:Descriptor = getDescriptorFromDescription(description);
sendResults("<testcase classname=\""+desc.suite+"\" name=\""+desc.method+"\" time=\"" + testTimeString( lastTestTime ) +"\" status=\""+SUCCESS+"\" />");
}
}
public function testAssumptionFailure( failure:Failure ):void
{
// called on assumptionFail
}
public function testIgnored( description:IDescription ):void
{
// called on ignored test if we want to send ignore to ant.
var descriptor:Descriptor = getDescriptorFromDescription(description);
var xml:String =
"<testcase classname=\""+descriptor.suite+"\" name=\""+descriptor.method+"\" time=\"" + testTimeString( lastTestTime ) + "\" status=\""+IGNORE+"\">"
+ "<skipped />"
+ "</testcase>";
sendResults( xml );
}
public function testFailure( failure:Failure ):void
{
// called on a test failure
lastFailedTest = failure.description;
var descriptor:Descriptor =
getDescriptorFromDescription(failure.description);
var type : String = failure.description.displayName
var message : String = failure.message;
var stackTrace : String = failure.stackTrace;
var methodName : String = descriptor.method;
if ( stackTrace != null ) stackTrace = stackTrace.toString();
stackTrace = FailureFormatter.xmlEscapeMessage( stackTrace );
message = FailureFormatter.xmlEscapeMessage( message );
var xml : String = null;
if(FailureFormatter.isError(failure.exception))
{
xml =
"<testcase classname=\""+descriptor.suite+"\" name=\""+descriptor.method+"\" time=\"" + testTimeString( lastTestTime ) +"\" status=\""+ERROR+"\">"
+ "<error message=\"" + message + "\" type=\""+ type +"\">"
+ "<![CDATA[" + stackTrace + "]]>"
+ "</error>"
+ "</testcase>";
}
else
{
xml =
"<testcase classname=\""+descriptor.suite+"\" name=\""+descriptor.method+"\" time=\"" + testTimeString( lastTestTime ) +"\" status=\""+FAILURE+"\">"
+ "<failure message=\"" + message + "\" type=\""+ type +"\" >"
+ "<![CDATA[" + stackTrace + "]]>"
+ "</failure>"
+ "</testcase>";
}
sendResults(xml);
}
/*
* Internal methods
*/
private function getDescriptorFromDescription( description:IDescription ):Descriptor
{
// reads relavent data from descriptor
/**
* JAdkins - 7/27/07 - FXU-53 - Listener was returning a null value for the test class
* causing no data to be returned. If length of array is greater than 1, then class is
* not in the default package. If array length is 1, then test class is default package
* and formats accordingly.
**/
var descriptor:Descriptor = new Descriptor();
var descriptionArray:Array = description.displayName.split("::");
var classMethod:String;
if ( descriptionArray.length > 1 )
{
descriptor.path = descriptionArray[0];
classMethod = descriptionArray[1];
}
else
{
classMethod = descriptionArray[0];
}
var classMethodArray:Array = classMethod.split(".");
descriptor.suite = ( descriptor.path == "" ) ? classMethodArray[0] :
descriptor.path + "::" + classMethodArray[0];
descriptor.method = classMethodArray[1];
return descriptor;
}
protected function sendResults(msg:String):void
{
if(socket.connected)
{
socket.send( msg );
}
trace(msg);
}
private function handleConnect(event:Event):void
{
//This is a good start, but we are no longer considering this a valid
//time to begin sending results
//We are going to wait until we get some data first
//_ready = true;
//dispatchEvent( new Event( AsyncListenerWatcher.LISTENER_READY ) );
}
private function errorHandler(event:Event):void
{
if ( !ready ) {
//If we are not yet ready and received this, just inform the core so it can move on
dispatchEvent( new Event( AsyncListenerWatcher.LISTENER_FAILED ) );
} else {
//If on the other hand we were ready once, then the core is counting on us... so, if something goes
//wrong now, we are likely hung up. For now we are simply going to bail out of this process
exit();
}
}
private function dataHandler( event : DataEvent ) : void
{
var data : String = event.data;
// If we received an acknowledgement on startup, the java server is read and we can start sending.
if ( data == START_OF_TEST_RUN_ACK ) {
setStatusReady();
} else if ( data == END_OF_TEST_ACK ) {
// If we received an acknowledgement finish-up.
// Close the socket.
socket.close();
exit();
}
}
/**
* Exit the test runner by calling the ApplicationCloser.
*/
protected function exit() : void
{
this.closer.close();
}
}
}
|
Fix to CIListener to use double quotes and correct spacing for result XML. Re-fixed from the pull from mlabriola.
|
Fix to CIListener to use double quotes and correct spacing for result XML. Re-fixed from the pull from mlabriola.
|
ActionScript
|
apache-2.0
|
SlavaRa/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit
|
a47e3c32b9e0f3f555be533f0594814bc7a3e69f
|
src/flash/events/EventDispatcher.as
|
src/flash/events/EventDispatcher.as
|
/*
* Copyright 2014 Mozilla Foundation
*
* 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 flash.events {
[native(cls='EventDispatcherClass')]
public class EventDispatcher implements IEventDispatcher {
public function EventDispatcher(target:IEventDispatcher = null) {
ctor(target);
}
public function toString():String {
return '[object EventDispatcher]';
}
public native function addEventListener(type:String, listener:Function,
useCapture:Boolean = false, priority:int = 0,
useWeakReference:Boolean = false):void;
public native function removeEventListener(type:String, listener:Function,
useCapture:Boolean = false):void;
public native function hasEventListener(type:String):Boolean;
public native function willTrigger(type:String):Boolean;
public function dispatchEvent(event:Event):Boolean {
return dispatchEventFunction(event.target ? event.clone() : event);
}
private native function ctor(target: IEventDispatcher): void;
private native function dispatchEventFunction(event: Event): Boolean;
}
}
|
/*
* Copyright 2014 Mozilla Foundation
*
* 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 flash.events {
[native(cls='EventDispatcherClass')]
public class EventDispatcher implements IEventDispatcher {
public function EventDispatcher(target:IEventDispatcher = null) {
ctor(target);
}
public function toString():String {
return Object.prototype.toString.call(this);
}
public native function addEventListener(type:String, listener:Function,
useCapture:Boolean = false, priority:int = 0,
useWeakReference:Boolean = false):void;
public native function removeEventListener(type:String, listener:Function,
useCapture:Boolean = false):void;
public native function hasEventListener(type:String):Boolean;
public native function willTrigger(type:String):Boolean;
public function dispatchEvent(event:Event):Boolean {
return dispatchEventFunction(event.target ? event.clone() : event);
}
private native function ctor(target: IEventDispatcher): void;
private native function dispatchEventFunction(event: Event): Boolean;
}
}
|
Fix EventDispatcher#toString
|
Fix EventDispatcher#toString
|
ActionScript
|
apache-2.0
|
yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,mozilla/shumway,tschneidereit/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway
|
57ca0a32a04070175613a7b78a9ac5c91345e852
|
src/com/axis/rtspclient/BitArray.as
|
src/com/axis/rtspclient/BitArray.as
|
package com.axis.rtspclient {
import com.axis.ErrorManager;
import flash.utils.ByteArray;
public class BitArray extends ByteArray {
private var src:ByteArray;
private var byte:uint;
private var bitpos:uint;
public function BitArray(src:ByteArray) {
this.src = src;
this.bitpos = 0;
this.byte = 0; /* This should really be undefined, uint wont allow it though */
}
public function readBits(length:uint):uint {
if (32 < length || 0 === length) {
/* To big for an uint */
ErrorManager.dispatchError(819, null, true);
}
var result:uint = 0;
for (var i:uint = 1; i <= length; ++i) {
if (0 === bitpos) {
/* Previous byte all read out. Get a new one. */
byte = src.readUnsignedByte();
}
/* Shift result one left to make room for another bit,
then add the next bit on the stream. */
result = (result << 1) | ((byte >> (8 - (++bitpos))) & 0x01);
bitpos %= 8;
}
return result;
}
public function readUnsignedExpGolomb():uint {
var bitsToRead:uint = 0;
while (readBits(1) !== 1) bitsToRead++;
if (bitsToRead == 0) return 0; /* Easy peasy, just a single 1. This is 0 in exp golomb */
if (bitsToRead >= 31) ErrorManager.dispatchError(820, null, true);
var n:uint = readBits(bitsToRead); /* Read all bits part of this number */
n |= (0x1 << (bitsToRead)); /* Move in the 1 read by while-statement above */
return n - 1; /* Because result in exp golomb is one larger */
}
public function readSignedExpGolomb():uint {
var r:uint = this.readUnsignedExpGolomb();
if (r & 0x01) {
r = (r+1) >> 1;
} else {
r = -(r >> 1);
}
return r;
}
}
}
|
package com.axis.rtspclient {
import com.axis.ErrorManager;
import flash.utils.ByteArray;
public class BitArray extends ByteArray {
private var src:ByteArray;
private var byte:uint;
private var bitpos:uint;
public function BitArray(src:ByteArray) {
this.src = clone(src);
this.bitpos = 0;
this.byte = 0; /* This should really be undefined, uint wont allow it though */
}
public function readBits(length:uint):uint {
if (32 < length || 0 === length) {
/* To big for an uint */
ErrorManager.dispatchError(819, null, true);
}
var result:uint = 0;
for (var i:uint = 1; i <= length; ++i) {
if (0 === bitpos) {
/* Previous byte all read out. Get a new one. */
byte = src.readUnsignedByte();
}
/* Shift result one left to make room for another bit,
then add the next bit on the stream. */
result = (result << 1) | ((byte >> (8 - (++bitpos))) & 0x01);
bitpos %= 8;
}
return result;
}
public function readUnsignedExpGolomb():uint {
var bitsToRead:uint = 0;
while (readBits(1) !== 1) bitsToRead++;
if (bitsToRead == 0) return 0; /* Easy peasy, just a single 1. This is 0 in exp golomb */
if (bitsToRead >= 31) ErrorManager.dispatchError(820, null, true);
var n:uint = readBits(bitsToRead); /* Read all bits part of this number */
n |= (0x1 << (bitsToRead)); /* Move in the 1 read by while-statement above */
return n - 1; /* Because result in exp golomb is one larger */
}
public function readSignedExpGolomb():uint {
var r:uint = this.readUnsignedExpGolomb();
if (r & 0x01) {
r = (r+1) >> 1;
} else {
r = -(r >> 1);
}
return r;
}
public function clone(source:ByteArray):* {
var temp:ByteArray = new ByteArray();
temp.writeObject(source);
temp.position = 0;
return(temp.readObject());
}
}
}
|
Clone ByteArray in BitArray class to avoid side effects
|
Clone ByteArray in BitArray class to avoid side effects
|
ActionScript
|
bsd-3-clause
|
gaetancollaud/locomote-video-player,AxisCommunications/locomote-video-player
|
7edeabe9031dd4a6ef09236be2917b8adfb28dd9
|
src/swf2png.as
|
src/swf2png.as
|
package
{
import com.adobe.images.PNGEncoder;
import com.bit101.components.ScrollPane;
import flash.desktop.NativeApplication;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.geom.Rectangle;
import flash.geom.Matrix;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.utils.ByteArray;
import flash.utils.Timer;
public class swf2png extends Sprite
{
public var outputWidth:int;
public var outputHeight:int;
public var loadedSwf:MovieClip;
public var loader:Loader;
private var counter:int = 0;
private var timer:Timer;
private var totalFrames:int;
private var inputFileName:String;
private var inputFilePath:String;
private var prefix:String;
private var separator:String = "_";
private var outfield:TextField;
private var outputDirPath:String;
private var offsetMatrix:Matrix;
private var bBox:Rectangle;
private var scaleFactor:Number;
private var pane:ScrollPane;
public function swf2png() {
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
stage.align = 'TL';
stage.scaleMode = 'noScale';
outfield = new TextField();
outfield.autoSize = TextFieldAutoSize.LEFT;
pane = new ScrollPane(stage);
pane.width = stage.stageWidth;
pane.height = stage.stageHeight;
pane.addChild(outfield);
pane.update();
stage.addEventListener(Event.RESIZE, onResize, false, 0, true);
}
//Loads in file
private function loadSwf():void {
loader = new Loader();
log("Loading " + inputFilePath);
loader.load(new URLRequest("file://" + inputFilePath));
loader.contentLoaderInfo.addEventListener(Event.INIT, startLoop);
}
//Event handler called when the swf is loaded. Sets it up and starts the export loop
private function startLoop(ev:Event):void {
try {
loadedSwf = MovieClip(ev.target.content);
}
catch(err:Error) {
//AVM1 Movie not supported
exit(5);
return;
}
outputWidth = Math.ceil(ev.target.width);
outputHeight = Math.ceil(ev.target.height);
log("Loaded!");
totalFrames = loadedSwf.totalFrames;
log("Frame count: " + totalFrames);
calculateBBox();
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
timer = new Timer(1);
timer.addEventListener(TimerEvent.TIMER, step);
timer.start();
}
private function padNumber(input:int, target:int):String {
var out:String = input.toString();
var targetCount:int = target.toString().length;
while(out.length < targetCount) {
out = '0' + out;
}
return out;
}
private function calculateBBox():void {
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
var boundsArray:Object = {
"x" : new Array(),
"y" : new Array(),
"w" : new Array(),
"h" : new Array()
}
var r:Rectangle;
for(var currentFrame:int = 0; currentFrame < totalFrames; currentFrame++) {
goToFrame(loadedSwf, currentFrame);
r = loader.content.getRect(stage);
boundsArray.x.push(r.x);
boundsArray.y.push(r.y);
boundsArray.w.push(r.width);
boundsArray.h.push(r.height);
}
boundsArray.x.sort(Array.NUMERIC);
boundsArray.y.sort(Array.NUMERIC);
boundsArray.w.sort(Array.NUMERIC | Array.DESCENDING);
boundsArray.h.sort(Array.NUMERIC | Array.DESCENDING);
bBox = new Rectangle(
Math.floor(boundsArray.x[0]),
Math.floor(boundsArray.y[0]),
Math.ceil(boundsArray.w[0]),
Math.ceil(boundsArray.h[0])
);
log("Bounding box: " + bBox)
outputWidth = bBox.width * scaleFactor;
outputHeight = bBox.height * scaleFactor;
offsetMatrix = new Matrix();
offsetMatrix.translate(bBox.x * -1, bBox.y * -1);
offsetMatrix.scale(scaleFactor, scaleFactor);
return;
}
//Called for every frame
private function step(ev:TimerEvent):void {
counter++;
if(counter <= totalFrames) {
goToFrame(loadedSwf, counter);
saveFrame();
}
else {
timer.stop();
log("Done!");
exit(0);
return;
}
}
//Saves the current frame of the loader object to a png
private function saveFrame():void {
var bitmapData:BitmapData = new BitmapData(outputWidth, outputHeight, true, 0x0);
bitmapData.draw(loader.content, offsetMatrix);
var bytearr:ByteArray = PNGEncoder.encode(bitmapData);
var increment:String = '';
if(totalFrames > 1) {
increment = separator + padNumber(counter, totalFrames);
}
var outfileName:String = outputDirPath + File.separator + prefix + increment + ".png"
var file:File = new File(outfileName);
log("Writing: " + outfileName);
var stream:FileStream = new FileStream();
stream.open(file, "write");
stream.writeBytes(bytearr);
stream.close();
}
//Stops the movie clip and all its subclips.
private function stopClip(inMc:MovieClip):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.stop();
if(mc.numChildren > 0) {
stopClip(mc);
}
}
}
inMc.stop();
}
//Traverses the movie clip and sets the current frame for all subclips too, looping them where needed.
private function goToFrame(inMc:MovieClip, frameNo:int):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.gotoAndStop(frameNo % inMc.totalFrames);
if(mc.numChildren > 0) {
goToFrame(mc, frameNo);
}
}
}
inMc.gotoAndStop(frameNo % inMc.totalFrames);
}
//Finds and checks for existance of input file
private function getInputFile(ev:InvokeEvent):String {
if(ev.arguments && ev.arguments.length) {
inputFileName = ev.arguments[0];
var matchNameRegExStr:String = '([^\\' + File.separator + ']+)$';
var matchNameRegEx:RegExp = new RegExp(matchNameRegExStr);
var matches:Array = inputFileName.match(matchNameRegEx);
if(!matches) {
// File inputFileName not valid
exit(2);
return "";
}
prefix = matches[1].split('.')[0];
log("Prefix: " + prefix);
var f:File = new File(ev.currentDirectory.nativePath);
f = f.resolvePath(inputFileName);
if(!f.exists) {
log("Input file not found!");
//Input file not found
exit(3);
return "";
}
return f.nativePath;
}
else {
//App opened without input data
exit(1);
return "";
}
}
//Finds and checks for existance of output directory
private function getOutputDir(ev:InvokeEvent):String {
var d:File;
if(ev.arguments.length > 1) {
outputDirPath = ev.arguments[1];
d = new File(ev.currentDirectory.nativePath);
d = d.resolvePath(outputDirPath);
if(!d.isDirectory) {
//outdir not a directory
exit(4);
return "";
}
return d.nativePath;
}
else if(inputFilePath) {
d = new File(inputFilePath);
if(!d.isDirectory) {
d = d.resolvePath('..');
}
return d.nativePath;
}
else {
if(ev.currentDirectory.nativePath === '/') {
return File.desktopDirectory.nativePath;
}
else {
return ev.currentDirectory.nativePath;
}
}
return "";
}
private function getScaleFactor(ev:InvokeEvent):Number {
if(ev.arguments.length > 2) {
log("scale factor set to " + parseFloat(ev.arguments[2]));
return parseFloat(ev.arguments[2]);
}
return 1;
}
private function log(message:String="", add_new_line:Boolean=true):void {
outfield.appendText((add_new_line ? "\n" : "") + message);
pane.update();
}
//Invoke handler called when started
private function onInvoke(ev:InvokeEvent):void {
inputFilePath = getInputFile(ev);
outputDirPath = getOutputDir(ev);
scaleFactor = getScaleFactor(ev);
log("Input file: " + inputFilePath);
log("Output directory: " + outputDirPath);
loadSwf();
}
private function onResize(ev:Event):void {
pane.width = stage.stageWidth;
pane.height = stage.stageHeight;
pane.update();
}
private function exit(code:int=0):void {
log("Exit: " + code);
NativeApplication.nativeApplication.exit(code);
}
}
}
|
package
{
import com.adobe.images.PNGEncoder;
import com.bit101.components.ScrollPane;
import flash.desktop.NativeApplication;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.geom.Rectangle;
import flash.geom.Matrix;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.utils.ByteArray;
import flash.utils.Timer;
public class swf2png extends Sprite
{
public var outputWidth:int;
public var outputHeight:int;
public var loadedSwf:MovieClip;
public var loader:Loader;
private var counter:int = 0;
private var timer:Timer;
private var totalFrames:int;
private var inputFileName:String;
private var inputFilePath:String;
private var prefix:String;
private var separator:String = "_";
private var outfield:TextField;
private var outputDirPath:String;
private var offsetMatrix:Matrix = new Matrix();
private var bBox:Rectangle;
private var scaleFactor:Number;
private var pane:ScrollPane;
public function swf2png() {
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
stage.align = 'TL';
stage.scaleMode = 'noScale';
stage.frameRate = 12;
outfield = new TextField();
outfield.autoSize = TextFieldAutoSize.LEFT;
pane = new ScrollPane(stage);
pane.width = stage.stageWidth;
pane.height = stage.stageHeight;
pane.addChild(outfield);
pane.update();
stage.addEventListener(Event.RESIZE, onResize, false, 0, true);
}
//Loads in file
private function loadSwf():void {
loader = new Loader();
log("Loading " + inputFilePath);
loader.load(new URLRequest("file://" + inputFilePath));
loader.contentLoaderInfo.addEventListener(Event.INIT, startLoop);
}
//Event handler called when the swf is loaded. Sets it up and starts the export loop
private function startLoop(ev:Event):void {
try {
loadedSwf = MovieClip(ev.target.content);
}
catch(err:Error) {
//AVM1 Movie not supported
exit(5);
return;
}
outputWidth = Math.ceil(ev.target.width);
outputHeight = Math.ceil(ev.target.height);
log("Loaded!");
totalFrames = loadedSwf.totalFrames;
log("Frame count: " + totalFrames);
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
timer = new Timer(1);
timer.addEventListener(TimerEvent.TIMER, step);
timer.start();
}
private function padNumber(input:int, target:int):String {
var out:String = input.toString();
var targetCount:int = target.toString().length;
while(out.length < targetCount) {
out = '0' + out;
}
return out;
}
//Called for every frame
private function step(ev:TimerEvent):void {
counter++;
if(counter <= totalFrames) {
goToFrame(loadedSwf, counter);
saveFrame();
}
else {
timer.stop();
log("Done!");
exit(0);
return;
}
}
//Saves the current frame of the loader object to a png
private function saveFrame():void {
var bitmapData:BitmapData = new BitmapData(outputWidth, outputHeight, true, 0x0);
offsetMatrix.scale(scaleFactor, scaleFactor);
bitmapData.draw(loader.content, offsetMatrix);
var bytearr:ByteArray = PNGEncoder.encode(bitmapData);
var increment:String = '';
if(totalFrames > 1) {
increment = separator + padNumber(counter, totalFrames);
}
var outfileName:String = outputDirPath + File.separator + prefix + increment + ".png"
var file:File = new File(outfileName);
log("Writing: " + outfileName);
var stream:FileStream = new FileStream();
stream.open(file, "write");
stream.writeBytes(bytearr);
stream.close();
}
//Stops the movie clip and all its subclips.
private function stopClip(inMc:MovieClip):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.stop();
if(mc.numChildren > 0) {
stopClip(mc);
}
}
}
inMc.stop();
}
//Traverses the movie clip and sets the current frame for all subclips too, looping them where needed.
private function goToFrame(inMc:MovieClip, frameNo:int):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.gotoAndStop(frameNo % inMc.totalFrames);
if(mc.numChildren > 0) {
goToFrame(mc, frameNo);
}
}
}
inMc.gotoAndStop(frameNo % inMc.totalFrames);
}
//Finds and checks for existance of input file
private function getInputFile(ev:InvokeEvent):String {
if(ev.arguments && ev.arguments.length) {
inputFileName = ev.arguments[0];
var matchNameRegExStr:String = '([^\\' + File.separator + ']+)$';
var matchNameRegEx:RegExp = new RegExp(matchNameRegExStr);
var matches:Array = inputFileName.match(matchNameRegEx);
if(!matches) {
// File inputFileName not valid
exit(2);
return "";
}
prefix = matches[1].split('.')[0];
log("Prefix: " + prefix);
var f:File = new File(ev.currentDirectory.nativePath);
f = f.resolvePath(inputFileName);
if(!f.exists) {
log("Input file not found!");
//Input file not found
exit(3);
return "";
}
return f.nativePath;
}
else {
//App opened without input data
exit(1);
return "";
}
}
//Finds and checks for existance of output directory
private function getOutputDir(ev:InvokeEvent):String {
var d:File;
if(ev.arguments.length > 1) {
outputDirPath = ev.arguments[1];
d = new File(ev.currentDirectory.nativePath);
d = d.resolvePath(outputDirPath);
if(!d.isDirectory) {
//outdir not a directory
exit(4);
return "";
}
return d.nativePath;
}
else if(inputFilePath) {
d = new File(inputFilePath);
if(!d.isDirectory) {
d = d.resolvePath('..');
}
return d.nativePath;
}
else {
if(ev.currentDirectory.nativePath === '/') {
return File.desktopDirectory.nativePath;
}
else {
return ev.currentDirectory.nativePath;
}
}
return "";
}
private function getScaleFactor(ev:InvokeEvent):Number {
if(ev.arguments.length > 2) {
log("scale factor set to " + parseFloat(ev.arguments[2]));
return parseFloat(ev.arguments[2]);
}
outputWidth *= scaleFactor;
outputHeight *= scaleFactor;
return 1;
}
private function log(message:String="", add_new_line:Boolean=true):void {
outfield.appendText((add_new_line ? "\n" : "") + message);
pane.update();
}
//Invoke handler called when started
private function onInvoke(ev:InvokeEvent):void {
inputFilePath = getInputFile(ev);
outputDirPath = getOutputDir(ev);
scaleFactor = getScaleFactor(ev);
log("Input file: " + inputFilePath);
log("Output directory: " + outputDirPath);
loadSwf();
}
private function onResize(ev:Event):void {
pane.width = stage.stageWidth;
pane.height = stage.stageHeight;
pane.update();
}
private function exit(code:int=0):void {
log("Exit: " + code);
NativeApplication.nativeApplication.exit(code);
}
}
}
|
Remove support for bounding box detection.
|
Remove support for bounding box detection.
|
ActionScript
|
mit
|
mdahlstrand/swf2png
|
d04ae24b2dc2ac1cdc27edeabd50af74c182cadf
|
doc/tutorials/examples/actionscript/guestbook/flex/src/org/pyamf/examples/guestbook/GuestbookExample.as
|
doc/tutorials/examples/actionscript/guestbook/flex/src/org/pyamf/examples/guestbook/GuestbookExample.as
|
package org.pyamf.examples.guestbook
{
/**
* Copyright (c) 2007-2009 The PyAMF Project.
* See LICENSE.txt for details.
*/
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.net.NetConnection;
import flash.net.Responder;
import mx.collections.ArrayCollection;
import mx.core.Application;
import mx.events.FlexEvent;
import org.pyamf.examples.guestbook.components.SubmitBox;
import org.pyamf.examples.guestbook.events.SubmitEvent;
import org.pyamf.examples.guestbook.vo.Message;
/**
* Simple guestbook using PyAMF, Twisted and Flash.
*
* @since 0.3.0
*/
public class GuestbookExample extends Application
{
private var _gateway : NetConnection;
[Bindable]
public var messages : ArrayCollection;
[Bindable]
public var totalMessages : String = "Loading...";
[Bindable]
public var loading : Boolean = true;
public var submit : SubmitBox;
public function GuestbookExample()
{
super();
addEventListener( FlexEvent.APPLICATION_COMPLETE, onInitApp );
}
private function onInitApp( event:FlexEvent ): void
{
// setup connection
_gateway = new NetConnection();
_gateway.addEventListener( NetStatusEvent.NET_STATUS, onStatus );
_gateway.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onError );
// Connect to gateway
_gateway.connect( "http://localhost:8080/gateway" );
// Set responder property to the object and methods that will receive the
// result or fault condition that the service returns.
var responder:Responder = new Responder( onLoadResult, onFault );
// Call remote service to fetch data
_gateway.call( "guestbook.getMessages", responder);
}
public function addMessage( event:SubmitEvent ): void
{
var message:Message = event.message;
loading = true;
// set responder property to the object and methods that will receive the
// result or fault condition that the service returns.
var responder:Responder = new Responder( onSaveResult, onFault );
// call remote service to save guestbook message.
_gateway.call( "guestbook.addMessage", responder, new ObjectProxy(event.message) );
// wait for result.
totalMessages = "Saving message...";
}
private function onLoadResult( result:* ): void
{
loading = false;
// update list
messages = result;
totalMessages = "Loaded " + messages.length + " message(s).";
}
private function onSaveResult( result:* ): void
{
var message:Message = result;
loading = false;
// add message to list
messages.addItemAt( message, 0 );
totalMessages = "Loaded " + messages.length + " message(s).";
}
private function onStatus( event:NetStatusEvent ): void
{
submit.status = event.info.description + "!";
}
private function onError( event:* ): void
{
submit.status = event.error + "!";
}
private function onFault( error:* ): void
{
// notify the user of the problem
//trace("Remoting error:");
for ( var d:String in error ) {
//trace(" " + d + ": " + error[d]);
}
totalMessages = "Loaded " + messages.length + " message(s).";
if ( error.fault.description != null ) {
submit.status = error.fault.description + "!";
} else {
submit.status = error + "!";
}
}
}
}
|
package org.pyamf.examples.guestbook
{
/**
* Copyright (c) 2007-2009 The PyAMF Project.
* See LICENSE.txt for details.
*/
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.net.NetConnection;
import flash.net.Responder;
import mx.collections.ArrayCollection;
import mx.core.Application;
import mx.events.FlexEvent;
import mx.utils.ObjectProxy;
import org.pyamf.examples.guestbook.components.SubmitBox;
import org.pyamf.examples.guestbook.events.SubmitEvent;
import org.pyamf.examples.guestbook.vo.Message;
/**
* Simple guestbook using PyAMF, Twisted and Flash.
*
* @since 0.3.0
*/
public class GuestbookExample extends Application
{
private var _gateway : NetConnection;
[Bindable]
public var messages : ArrayCollection;
[Bindable]
public var totalMessages : String = "Loading...";
[Bindable]
public var loading : Boolean = true;
public var submit : SubmitBox;
public function GuestbookExample()
{
super();
addEventListener( FlexEvent.APPLICATION_COMPLETE, onInitApp );
}
private function onInitApp( event:FlexEvent ): void
{
// setup connection
_gateway = new NetConnection();
_gateway.addEventListener( NetStatusEvent.NET_STATUS, onStatus );
_gateway.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onError );
// Connect to gateway
_gateway.connect( "http://localhost:8080/gateway" );
// Set responder property to the object and methods that will receive the
// result or fault condition that the service returns.
var responder:Responder = new Responder( onLoadResult, onFault );
// Call remote service to fetch data
_gateway.call( "guestbook.getMessages", responder);
}
public function addMessage( event:SubmitEvent ): void
{
var message:Message = event.message;
loading = true;
// set responder property to the object and methods that will receive the
// result or fault condition that the service returns.
var responder:Responder = new Responder( onSaveResult, onFault );
// call remote service to save guestbook message.
_gateway.call( "guestbook.addMessage", responder, new ObjectProxy(event.message) );
// wait for result.
totalMessages = "Saving message...";
}
private function onLoadResult( result:* ): void
{
loading = false;
// update list
messages = result;
totalMessages = "Loaded " + messages.length + " message(s).";
}
private function onSaveResult( result:* ): void
{
var message:Message = result;
loading = false;
// add message to list
messages.addItemAt( message, 0 );
totalMessages = "Loaded " + messages.length + " message(s).";
}
private function onStatus( event:NetStatusEvent ): void
{
submit.status = event.info.description + "!";
}
private function onError( event:* ): void
{
submit.status = event.error + "!";
}
private function onFault( error:* ): void
{
// notify the user of the problem
//trace("Remoting error:");
for ( var d:String in error ) {
//trace(" " + d + ": " + error[d]);
}
totalMessages = "Loaded " + messages.length + " message(s).";
if ( error.fault.description != null ) {
submit.status = error.fault.description + "!";
} else {
submit.status = error + "!";
}
}
}
}
|
fix compile error for missing import
|
fix compile error for missing import
|
ActionScript
|
mit
|
njoyce/pyamf,njoyce/pyamf,thijstriemstra/pyamf,hydralabs/pyamf,thijstriemstra/pyamf,hydralabs/pyamf
|
b9cdb00e100c1cd2dad55f0c199946eaf1ca5a0c
|
src/flash/display/DisplayObject.as
|
src/flash/display/DisplayObject.as
|
package flash.display {
import flash.events.EventDispatcher;
import flash.display.IBitmapDrawable;
import String;
import flash.accessibility.AccessibilityProperties;
import flash.geom.Point;
import Object;
import flash.display.LoaderInfo;
import flash.geom.Rectangle;
import Array;
import flash.display.Shader;
import Boolean;
import flash.geom.Vector3D;
import Number;
import flash.display.DisplayObjectContainer;
import flash.display.Stage;
import flash.geom.Transform;
import flash.events.Event;
public class DisplayObject extends EventDispatcher implements IBitmapDrawable {
public function DisplayObject() {}
public native function get root():DisplayObject;
public native function get stage():Stage;
public native function get name():String;
public native function set name(value:String):void;
public native function get parent():DisplayObjectContainer;
public native function get mask():DisplayObject;
public native function set mask(value:DisplayObject):void;
public native function get visible():Boolean;
public native function set visible(value:Boolean):void;
public native function get x():Number;
public native function set x(value:Number):void;
public native function get y():Number;
public native function set y(value:Number):void;
public native function get z():Number;
public native function set z(value:Number):void;
public native function get scaleX():Number;
public native function set scaleX(value:Number):void;
public native function get scaleY():Number;
public native function set scaleY(value:Number):void;
public native function get scaleZ():Number;
public native function set scaleZ(value:Number):void;
public native function get mouseX():Number;
public native function get mouseY():Number;
public native function get rotation():Number;
public native function set rotation(value:Number):void;
public native function get rotationX():Number;
public native function set rotationX(value:Number):void;
public native function get rotationY():Number;
public native function set rotationY(value:Number):void;
public native function get rotationZ():Number;
public native function set rotationZ(value:Number):void;
public native function get alpha():Number;
public native function set alpha(value:Number):void;
public native function get width():Number;
public native function set width(value:Number):void;
public native function get height():Number;
public native function set height(value:Number):void;
public native function get cacheAsBitmap():Boolean;
public native function set cacheAsBitmap(value:Boolean):void;
public native function get opaqueBackground():Object;
public native function set opaqueBackground(value:Object):void;
public native function get scrollRect():Rectangle;
public native function set scrollRect(value:Rectangle):void;
public native function get filters():Array;
public native function set filters(value:Array):void;
public native function get blendMode():String;
public native function set blendMode(value:String):void;
public native function get transform():Transform;
public native function set transform(value:Transform):void;
public native function get scale9Grid():Rectangle;
public native function set scale9Grid(innerRectangle:Rectangle):void;
public native function globalToLocal(point:Point):Point;
public native function localToGlobal(point:Point):Point;
public native function getBounds(targetCoordinateSpace:DisplayObject):Rectangle;
public native function getRect(targetCoordinateSpace:DisplayObject):Rectangle;
public native function get loaderInfo():LoaderInfo;
public function hitTestObject(obj:DisplayObject):Boolean { notImplemented("hitTestObject"); }
public function hitTestPoint(x:Number, y:Number, shapeFlag:Boolean = false):Boolean { notImplemented("hitTestPoint"); }
public native function get accessibilityProperties():AccessibilityProperties;
public native function set accessibilityProperties(value:AccessibilityProperties):void;
public native function globalToLocal3D(point:Point):Vector3D;
public native function local3DToGlobal(point3d:Vector3D):Point;
public native function set blendShader(value:Shader):void;
}
}
|
/*
* Copyright 2014 Mozilla Foundation
*
* 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 flash.display {
import flash.accessibility.AccessibilityProperties;
import flash.events.EventDispatcher;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.geom.Transform;
import flash.geom.Vector3D;
[native(cls='DisplayObjectClass')]
public class DisplayObject extends EventDispatcher implements IBitmapDrawable {
public function DisplayObject() {}
public native function get root():DisplayObject;
public native function get stage():Stage;
public native function get name():String;
public native function set name(value:String):void;
public native function get parent():DisplayObjectContainer;
public native function get mask():DisplayObject;
public native function set mask(value:DisplayObject):void;
public native function get visible():Boolean;
public native function set visible(value:Boolean):void;
public native function get x():Number;
public native function set x(value:Number):void;
public native function get y():Number;
public native function set y(value:Number):void;
public native function get z():Number;
public native function set z(value:Number):void;
public native function get scaleX():Number;
public native function set scaleX(value:Number):void;
public native function get scaleY():Number;
public native function set scaleY(value:Number):void;
public native function get scaleZ():Number;
public native function set scaleZ(value:Number):void;
public native function get mouseX():Number;
public native function get mouseY():Number;
public native function get rotation():Number;
public native function set rotation(value:Number):void;
public native function get rotationX():Number;
public native function set rotationX(value:Number):void;
public native function get rotationY():Number;
public native function set rotationY(value:Number):void;
public native function get rotationZ():Number;
public native function set rotationZ(value:Number):void;
public native function get alpha():Number;
public native function set alpha(value:Number):void;
public native function get width():Number;
public native function set width(value:Number):void;
public native function get height():Number;
public native function set height(value:Number):void;
public native function get cacheAsBitmap():Boolean;
public native function set cacheAsBitmap(value:Boolean):void;
public native function get opaqueBackground():Object;
public native function set opaqueBackground(value:Object):void;
public native function get scrollRect():Rectangle;
public native function set scrollRect(value:Rectangle):void;
public native function get filters():Array;
public native function set filters(value:Array):void;
public native function get blendMode():String;
public native function set blendMode(value:String):void;
public native function get transform():Transform;
public native function set transform(value:Transform):void;
public native function get scale9Grid():Rectangle;
public native function set scale9Grid(innerRectangle:Rectangle):void;
public native function get loaderInfo():LoaderInfo;
public native function get accessibilityProperties():AccessibilityProperties;
public native function set accessibilityProperties(value:AccessibilityProperties):void;
public native function set blendShader(value:Shader):void;
public native function globalToLocal(point:Point):Point;
public native function localToGlobal(point:Point):Point;
public native function getBounds(targetCoordinateSpace:DisplayObject):Rectangle;
public native function getRect(targetCoordinateSpace:DisplayObject):Rectangle;
public function hitTestObject(obj:DisplayObject):Boolean {
return _hitTest(false, 0, 0, false, obj);
}
public function hitTestPoint(x:Number, y:Number, shapeFlag:Boolean = false):Boolean {
return _hitTest(true, x, y, shapeFlag, null);
}
public native function globalToLocal3D(point:Point):Vector3D;
public native function local3DToGlobal(point3d:Vector3D):Point;
private native function _hitTest(use_xy: Boolean, x: Number, y: Number, useShape: Boolean,
hitTestObject: DisplayObject): Boolean;
}
}
|
Implement as3 part of DisplayObject
|
Implement as3 part of DisplayObject
|
ActionScript
|
apache-2.0
|
tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway
|
97a6e7db18fbbeae2e794b42544bd02be3664315
|
runtime/src/main/as/flump/display/LibraryLoader.as
|
runtime/src/main/as/flump/display/LibraryLoader.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.display {
import flash.utils.ByteArray;
import flump.executor.Executor;
import flump.executor.Future;
import starling.core.Starling;
/**
* Loads zip files created by the flump exporter and parses them into Library instances.
*/
public class LibraryLoader
{
/**
* Loads a Library from the zip in the given bytes.
*
* @param bytes The bytes containing the zip
*
* @param executor The executor on which the loading should run. If not specified, it'll run on
* a new single-use executor.
*
* @param scaleFactor the desired scale factor of the textures to load. If the Library contains
* textures with multiple scale factors, loader will load the textures with the scale factor
* closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be
* used.
*
* @return a Future to use to track the success or failure of loading the resources out of the
* bytes. If the loading succeeds, the Future's onSuccess will fire with an instance of
* Library. If it fails, the Future's onFail will fire with the Error that caused the
* loading failure.
*/
public static function loadBytes (bytes :ByteArray, executor :Executor=null, scaleFactor :Number=-1) :Future {
return (executor || new Executor(1)).submit(new Loader(bytes, scaleFactor).load);
}
/**
* Loads a Library from the zip at the given url.
*
* @param bytes The url where the zip can be found
*
* @param executor The executor on which the loading should run. If not specified, it'll run on
* a new single-use executor.
*
* @param scaleFactor the desired scale factor of the textures to load. If the Library contains
* textures with multiple scale factors, loader will load the textures with the scale factor
* closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be
* used.
*
* @return a Future to use to track the success or failure of loading the resources from the
* url. If the loading succeeds, the Future's onSuccess will fire with an instance of
* Library. If it fails, the Future's onFail will fire with the Error that caused the
* loading failure.
*/
public static function loadURL (url :String, executor :Executor=null, scaleFactor :Number=-1) :Future {
return (executor || new Executor(1)).submit(new Loader(url, scaleFactor).load);
}
/** @private */
public static const LIBRARY_LOCATION :String = "library.json";
/** @private */
public static const MD5_LOCATION :String = "md5";
/** @private */
public static const VERSION_LOCATION :String = "version";
/**
* @private
* The version produced and parsable by this version of the code. The version in a resources
* zip must equal the version compiled into the parsing code for parsing to succeed.
*/
public static const VERSION :String = "0";
}
}
import flash.events.Event;
import flash.geom.Point;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import deng.fzip.FZip;
import deng.fzip.FZipErrorEvent;
import deng.fzip.FZipEvent;
import deng.fzip.FZipFile;
import flump.display.Library;
import flump.display.LibraryLoader;
import flump.display.Movie;
import flump.executor.Executor;
import flump.executor.Future;
import flump.executor.FutureTask;
import flump.executor.load.ImageLoader;
import flump.executor.load.LoadedImage;
import flump.mold.AtlasMold;
import flump.mold.AtlasTextureMold;
import flump.mold.LibraryMold;
import flump.mold.MovieMold;
import flump.mold.TextureGroupMold;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Image;
import starling.display.Sprite;
import starling.textures.Texture;
interface SymbolCreator
{
function create (library :Library) :DisplayObject;
}
class LibraryImpl
implements Library
{
public function LibraryImpl (creators :Dictionary) {
_creators = creators;
}
public function createMovie (symbol :String) :Movie {
return Movie(createDisplayObject(symbol));
}
public function createImage (symbol :String) :DisplayObject {
const disp :DisplayObject = createDisplayObject(symbol);
if (disp is Movie) throw new Error(symbol + " is a movie, not a texture");
return disp;
}
public function get movieSymbols () :Vector.<String> {
const names :Vector.<String> = new Vector.<String>();
for (var creatorName :String in _creators) {
if (_creators[creatorName] is MovieCreator) names.push(creatorName);
}
return names;
}
public function get imageSymbols () :Vector.<String> {
const names :Vector.<String> = new Vector.<String>();
for (var creatorName :String in _creators) {
if (_creators[creatorName] is ImageCreator) names.push(creatorName);
}
return names;
}
public function createDisplayObject (name :String) :DisplayObject {
var creator :SymbolCreator = _creators[name];
if (creator == null) throw new Error("No such id '" + name + "'");
return creator.create(this);
}
protected var _creators :Dictionary;
}
class Loader
{
public function Loader (toLoad :Object, scaleFactor :Number) {
_scaleFactor = (scaleFactor > 0 ? scaleFactor : Starling.contentScaleFactor);
_toLoad = toLoad;
}
public function load (future :FutureTask) :void {
_future = future;
_zip.addEventListener(Event.COMPLETE, _future.monitoredCallback(onZipLoadingComplete));
_zip.addEventListener(FZipErrorEvent.PARSE_ERROR, _future.fail);
_zip.addEventListener(FZipEvent.FILE_LOADED, _future.monitoredCallback(onFileLoaded));
if (_toLoad is String) _zip.load(new URLRequest(String(_toLoad)));
else _zip.loadBytes(ByteArray(_toLoad));
}
protected function onFileLoaded (e :FZipEvent) :void {
const loaded :FZipFile = _zip.removeFileAt(_zip.getFileCount() - 1);
const name :String = loaded.filename;
if (name == LibraryLoader.LIBRARY_LOCATION) {
const jsonString :String = loaded.content.readUTFBytes(loaded.content.length);
_lib = LibraryMold.fromJSON(JSON.parse(jsonString));
} else if (name.indexOf(PNG, name.length - PNG.length) != -1) {
_pngBytes[name] = loaded.content;
} else if (name == LibraryLoader.VERSION_LOCATION) {
const zipVersion :String = loaded.content.readUTFBytes(loaded.content.length)
if (zipVersion != LibraryLoader.VERSION) {
throw new Error("Zip is version " + zipVersion + " but the code needs " + LibraryLoader.VERSION);
}
_versionChecked = true;
} else if (name == LibraryLoader.MD5_LOCATION ) { // Nothing to verify
} else {} // ignore unknown files
}
protected function onZipLoadingComplete (..._) :void {
_zip = null;
if (_lib == null) throw new Error(LibraryLoader.LIBRARY_LOCATION + " missing from zip");
if (!_versionChecked) throw new Error(LibraryLoader.VERSION_LOCATION + " missing from zip");
const loader :ImageLoader = new ImageLoader();
_pngLoaders.terminated.add(_future.monitoredCallback(onPngLoadingComplete));
// Determine the scale factor we want to use
var textureGroup :TextureGroupMold = _lib.bestTextureGroupForScaleFactor(_scaleFactor);
if (textureGroup != null) {
for each (var atlas :AtlasMold in textureGroup.atlases) {
loadAtlas(loader, atlas);
}
}
_pngLoaders.shutdown();
}
protected function loadAtlas (loader :ImageLoader, atlas :AtlasMold) :void {
const pngBytes :* = _pngBytes[atlas.file];
if (pngBytes === undefined) {
throw new Error("Expected an atlas '" + atlas.file + "', but it wasn't in the zip");
}
const atlasFuture :Future = loader.loadFromBytes(pngBytes, _pngLoaders);
atlasFuture.failed.add(onPngLoadingFailed);
atlasFuture.succeeded.add(function (img :LoadedImage) :void {
const baseTexture :Texture = Texture.fromBitmapData(
img.bitmapData,
true, // generateMipMaps - do we want this?
false, // optimizeForRenderToTexture
atlas.scaleFactor);
for each (var atlasTexture :AtlasTextureMold in atlas.textures) {
_creators[atlasTexture.symbol] = new ImageCreator(
Texture.fromTexture(baseTexture, atlasTexture.bounds),
atlasTexture.offset,
atlasTexture.symbol);
}
});
}
protected function onPngLoadingComplete (..._) :void {
for each (var movie :MovieMold in _lib.movies) {
movie.fillLabels();
_creators[movie.id] = new MovieCreator(movie, _lib.frameRate);
}
_future.succeed(new LibraryImpl(_creators));
}
protected function onPngLoadingFailed (e :*) :void {
if (_future.isComplete) return;
_future.fail(e);
_pngLoaders.shutdownNow();
}
protected var _toLoad :Object;
protected var _scaleFactor :Number;
protected var _future :FutureTask;
protected var _versionChecked :Boolean;
protected var _zip :FZip = new FZip();
protected var _lib :LibraryMold;
protected const _creators :Dictionary = new Dictionary();//<name, ImageCreator/MovieCreator>
protected const _pngBytes :Dictionary = new Dictionary();//<String name, ByteArray>
protected const _pngLoaders :Executor = new Executor(1);
protected static const PNG :String = ".png";
}
class ImageCreator
implements SymbolCreator
{
public var texture :Texture;
public var offset :Point;
public var symbol :String;
public function ImageCreator (texture :Texture, offset :Point, symbol :String) {
this.texture = texture;
this.offset = offset;
this.symbol = symbol;
}
public function create (library :Library) :DisplayObject {
const image :Image = new Image(texture);
image.x = offset.x;
image.y = offset.y;
const holder :Sprite = new Sprite();
holder.addChild(image);
holder.name = symbol;
return holder;
}
}
class MovieCreator
implements SymbolCreator
{
public var mold :MovieMold;
public var frameRate :Number;
public function MovieCreator (mold :MovieMold, frameRate :Number) {
this.mold = mold;
this.frameRate = frameRate;
}
public function create (library :Library) :DisplayObject {
return new Movie(mold, frameRate, library);
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.display {
import flash.utils.ByteArray;
import flump.executor.Executor;
import flump.executor.Future;
import starling.core.Starling;
/**
* Loads zip files created by the flump exporter and parses them into Library instances.
*/
public class LibraryLoader
{
/**
* Loads a Library from the zip in the given bytes.
*
* @param bytes The bytes containing the zip
*
* @param executor The executor on which the loading should run. If not specified, it'll run on
* a new single-use executor.
*
* @param scaleFactor the desired scale factor of the textures to load. If the Library contains
* textures with multiple scale factors, loader will load the textures with the scale factor
* closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be
* used.
*
* @return a Future to use to track the success or failure of loading the resources out of the
* bytes. If the loading succeeds, the Future's onSuccess will fire with an instance of
* Library. If it fails, the Future's onFail will fire with the Error that caused the
* loading failure.
*/
public static function loadBytes (bytes :ByteArray, executor :Executor=null, scaleFactor :Number=-1) :Future {
return (executor || new Executor(1)).submit(new Loader(bytes, scaleFactor).load);
}
/**
* Loads a Library from the zip at the given url.
*
* @param bytes The url where the zip can be found
*
* @param executor The executor on which the loading should run. If not specified, it'll run on
* a new single-use executor.
*
* @param scaleFactor the desired scale factor of the textures to load. If the Library contains
* textures with multiple scale factors, loader will load the textures with the scale factor
* closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be
* used.
*
* @return a Future to use to track the success or failure of loading the resources from the
* url. If the loading succeeds, the Future's onSuccess will fire with an instance of
* Library. If it fails, the Future's onFail will fire with the Error that caused the
* loading failure.
*/
public static function loadURL (url :String, executor :Executor=null, scaleFactor :Number=-1) :Future {
return (executor || new Executor(1)).submit(new Loader(url, scaleFactor).load);
}
/** @private */
public static const LIBRARY_LOCATION :String = "library.json";
/** @private */
public static const MD5_LOCATION :String = "md5";
/** @private */
public static const VERSION_LOCATION :String = "version";
/**
* @private
* The version produced and parsable by this version of the code. The version in a resources
* zip must equal the version compiled into the parsing code for parsing to succeed.
*/
public static const VERSION :String = "1";
}
}
import flash.events.Event;
import flash.geom.Point;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import deng.fzip.FZip;
import deng.fzip.FZipErrorEvent;
import deng.fzip.FZipEvent;
import deng.fzip.FZipFile;
import flump.display.Library;
import flump.display.LibraryLoader;
import flump.display.Movie;
import flump.executor.Executor;
import flump.executor.Future;
import flump.executor.FutureTask;
import flump.executor.load.ImageLoader;
import flump.executor.load.LoadedImage;
import flump.mold.AtlasMold;
import flump.mold.AtlasTextureMold;
import flump.mold.LibraryMold;
import flump.mold.MovieMold;
import flump.mold.TextureGroupMold;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Image;
import starling.display.Sprite;
import starling.textures.Texture;
interface SymbolCreator
{
function create (library :Library) :DisplayObject;
}
class LibraryImpl
implements Library
{
public function LibraryImpl (creators :Dictionary) {
_creators = creators;
}
public function createMovie (symbol :String) :Movie {
return Movie(createDisplayObject(symbol));
}
public function createImage (symbol :String) :DisplayObject {
const disp :DisplayObject = createDisplayObject(symbol);
if (disp is Movie) throw new Error(symbol + " is a movie, not a texture");
return disp;
}
public function get movieSymbols () :Vector.<String> {
const names :Vector.<String> = new Vector.<String>();
for (var creatorName :String in _creators) {
if (_creators[creatorName] is MovieCreator) names.push(creatorName);
}
return names;
}
public function get imageSymbols () :Vector.<String> {
const names :Vector.<String> = new Vector.<String>();
for (var creatorName :String in _creators) {
if (_creators[creatorName] is ImageCreator) names.push(creatorName);
}
return names;
}
public function createDisplayObject (name :String) :DisplayObject {
var creator :SymbolCreator = _creators[name];
if (creator == null) throw new Error("No such id '" + name + "'");
return creator.create(this);
}
protected var _creators :Dictionary;
}
class Loader
{
public function Loader (toLoad :Object, scaleFactor :Number) {
_scaleFactor = (scaleFactor > 0 ? scaleFactor : Starling.contentScaleFactor);
_toLoad = toLoad;
}
public function load (future :FutureTask) :void {
_future = future;
_zip.addEventListener(Event.COMPLETE, _future.monitoredCallback(onZipLoadingComplete));
_zip.addEventListener(FZipErrorEvent.PARSE_ERROR, _future.fail);
_zip.addEventListener(FZipEvent.FILE_LOADED, _future.monitoredCallback(onFileLoaded));
if (_toLoad is String) _zip.load(new URLRequest(String(_toLoad)));
else _zip.loadBytes(ByteArray(_toLoad));
}
protected function onFileLoaded (e :FZipEvent) :void {
const loaded :FZipFile = _zip.removeFileAt(_zip.getFileCount() - 1);
const name :String = loaded.filename;
if (name == LibraryLoader.LIBRARY_LOCATION) {
const jsonString :String = loaded.content.readUTFBytes(loaded.content.length);
_lib = LibraryMold.fromJSON(JSON.parse(jsonString));
} else if (name.indexOf(PNG, name.length - PNG.length) != -1) {
_pngBytes[name] = loaded.content;
} else if (name == LibraryLoader.VERSION_LOCATION) {
const zipVersion :String = loaded.content.readUTFBytes(loaded.content.length)
if (zipVersion != LibraryLoader.VERSION) {
throw new Error("Zip is version " + zipVersion + " but the code needs " + LibraryLoader.VERSION);
}
_versionChecked = true;
} else if (name == LibraryLoader.MD5_LOCATION ) { // Nothing to verify
} else {} // ignore unknown files
}
protected function onZipLoadingComplete (..._) :void {
_zip = null;
if (_lib == null) throw new Error(LibraryLoader.LIBRARY_LOCATION + " missing from zip");
if (!_versionChecked) throw new Error(LibraryLoader.VERSION_LOCATION + " missing from zip");
const loader :ImageLoader = new ImageLoader();
_pngLoaders.terminated.add(_future.monitoredCallback(onPngLoadingComplete));
// Determine the scale factor we want to use
var textureGroup :TextureGroupMold = _lib.bestTextureGroupForScaleFactor(_scaleFactor);
if (textureGroup != null) {
for each (var atlas :AtlasMold in textureGroup.atlases) {
loadAtlas(loader, atlas);
}
}
_pngLoaders.shutdown();
}
protected function loadAtlas (loader :ImageLoader, atlas :AtlasMold) :void {
const pngBytes :* = _pngBytes[atlas.file];
if (pngBytes === undefined) {
throw new Error("Expected an atlas '" + atlas.file + "', but it wasn't in the zip");
}
const atlasFuture :Future = loader.loadFromBytes(pngBytes, _pngLoaders);
atlasFuture.failed.add(onPngLoadingFailed);
atlasFuture.succeeded.add(function (img :LoadedImage) :void {
const baseTexture :Texture = Texture.fromBitmapData(
img.bitmapData,
true, // generateMipMaps - do we want this?
false, // optimizeForRenderToTexture
atlas.scaleFactor);
for each (var atlasTexture :AtlasTextureMold in atlas.textures) {
_creators[atlasTexture.symbol] = new ImageCreator(
Texture.fromTexture(baseTexture, atlasTexture.bounds),
atlasTexture.offset,
atlasTexture.symbol);
}
});
}
protected function onPngLoadingComplete (..._) :void {
for each (var movie :MovieMold in _lib.movies) {
movie.fillLabels();
_creators[movie.id] = new MovieCreator(movie, _lib.frameRate);
}
_future.succeed(new LibraryImpl(_creators));
}
protected function onPngLoadingFailed (e :*) :void {
if (_future.isComplete) return;
_future.fail(e);
_pngLoaders.shutdownNow();
}
protected var _toLoad :Object;
protected var _scaleFactor :Number;
protected var _future :FutureTask;
protected var _versionChecked :Boolean;
protected var _zip :FZip = new FZip();
protected var _lib :LibraryMold;
protected const _creators :Dictionary = new Dictionary();//<name, ImageCreator/MovieCreator>
protected const _pngBytes :Dictionary = new Dictionary();//<String name, ByteArray>
protected const _pngLoaders :Executor = new Executor(1);
protected static const PNG :String = ".png";
}
class ImageCreator
implements SymbolCreator
{
public var texture :Texture;
public var offset :Point;
public var symbol :String;
public function ImageCreator (texture :Texture, offset :Point, symbol :String) {
this.texture = texture;
this.offset = offset;
this.symbol = symbol;
}
public function create (library :Library) :DisplayObject {
const image :Image = new Image(texture);
image.x = offset.x;
image.y = offset.y;
const holder :Sprite = new Sprite();
holder.addChild(image);
holder.name = symbol;
return holder;
}
}
class MovieCreator
implements SymbolCreator
{
public var mold :MovieMold;
public var frameRate :Number;
public function MovieCreator (mold :MovieMold, frameRate :Number) {
this.mold = mold;
this.frameRate = frameRate;
}
public function create (library :Library) :DisplayObject {
return new Movie(mold, frameRate, library);
}
}
|
Bump our data format version
|
Bump our data format version
|
ActionScript
|
mit
|
mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump
|
ece6a697b600638293b1ce90053ede693e1e0475
|
src/com/google/analytics/GATracker.as
|
src/com/google/analytics/GATracker.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics
{
import com.google.analytics.core.Buffer;
import com.google.analytics.core.Ecommerce;
import com.google.analytics.core.EventTracker;
import com.google.analytics.core.GIFRequest;
import com.google.analytics.core.IdleTimer;
import com.google.analytics.core.ServerOperationMode;
import com.google.analytics.core.TrackerCache;
import com.google.analytics.core.TrackerMode;
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.Layout;
import com.google.analytics.events.AnalyticsEvent;
import com.google.analytics.external.AdSenseGlobals;
import com.google.analytics.external.HTMLDOM;
import com.google.analytics.external.JavascriptProxy;
import com.google.analytics.utils.Environment;
import com.google.analytics.v4.Bridge;
import com.google.analytics.v4.Configuration;
import com.google.analytics.v4.GoogleAnalyticsAPI;
import com.google.analytics.v4.Tracker;
import core.version;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.EventDispatcher;
EventTracker;
ServerOperationMode;
/**
* Dispatched after the factory has built the tracker object.
* @eventType com.google.analytics.events.AnalyticsEvent.READY
*/
[Event(name="ready", type="com.google.analytics.events.AnalyticsEvent")]
/**
* Google Analytic Tracker Code (GATC)'s code-only component.
*/
public class GATracker implements AnalyticsTracker
{
private var _ready:Boolean = false;
private var _display:DisplayObject;
private var _eventDispatcher:EventDispatcher;
private var _tracker:GoogleAnalyticsAPI;
//factory
private var _config:Configuration;
private var _debug:DebugConfiguration;
private var _env:Environment;
private var _buffer:Buffer;
private var _gifRequest:GIFRequest;
private var _jsproxy:JavascriptProxy;
private var _dom:HTMLDOM;
private var _adSense:AdSenseGlobals;
private var _idleTimer:IdleTimer;
private var _ecom:Ecommerce;
//object properties
private var _account:String;
private var _mode:String;
private var _visualDebug:Boolean;
/**
* Indicates if the tracker is automatically build.
*/
public static var autobuild:Boolean = true;
/**
* The version of the tracker.
*/
public static var version:core.version = API.version;
/**
* Creates a new GATracker instance.
* <p><b>Note:</b> the GATracker need to be instancied and added to the Stage or at least
* being placed in a display list.</p>
*/
public function GATracker( display:DisplayObject, account:String,
mode:String = "AS3", visualDebug:Boolean = false,
config:Configuration = null, debug:DebugConfiguration = null )
{
_display = display;
_eventDispatcher = new EventDispatcher( this ) ;
_tracker = new TrackerCache();
this.account = account;
this.mode = mode;
this.visualDebug = visualDebug;
if( !debug )
{
this.debug = new DebugConfiguration();
}
if( !config )
{
this.config = new Configuration( debug );
}
else
{
this.config = config;
}
if( autobuild )
{
_factory();
}
}
/**
* @private
* Factory to build the different trackers
*/
private function _factory():void
{
_jsproxy = new JavascriptProxy( debug );
if( visualDebug )
{
debug.layout = new Layout( debug, _display );
debug.active = visualDebug;
}
var activeTracker:GoogleAnalyticsAPI;
var cache:TrackerCache = _tracker as TrackerCache;
switch( mode )
{
case TrackerMode.BRIDGE :
{
activeTracker = _bridgeFactory();
break;
}
case TrackerMode.AS3 :
default:
{
activeTracker = _trackerFactory();
}
}
if( !cache.isEmpty() )
{
cache.tracker = activeTracker;
cache.flush();
}
_tracker = activeTracker;
_ready = true;
dispatchEvent( new AnalyticsEvent( AnalyticsEvent.READY, this ) );
}
/**
* @private
* Factory method for returning a Tracker object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _trackerFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (AS3) v" + version +"\naccount: " + account );
/* note:
for unit testing and to avoid 2 different branches AIR/Flash
here we will detect if we are in the Flash Player or AIR
and pass the infos to the LocalInfo
By default we will define "Flash" for our local tests
*/
_adSense = new AdSenseGlobals( debug );
_dom = new HTMLDOM( debug );
_dom.cacheProperties();
_env = new Environment( "", "", "", debug, _dom );
_buffer = new Buffer( config, debug, false );
_gifRequest = new GIFRequest( config, debug, _buffer, _env );
_idleTimer = new IdleTimer( config, debug, _display, _buffer );
_ecom = new Ecommerce ( _debug );
/* note:
To be able to obtain the URL of the main SWF containing the GA API
we need to be able to access the stage property of a DisplayObject,
here we open the internal namespace to be able to set that reference
at instanciation-time.
We keep the implementation internal to be able to change it if required later.
*/
use namespace ga_internal;
_env.url = _display.stage.loaderInfo.url;
return new Tracker( account, config, debug, _env, _buffer, _gifRequest, _adSense, _ecom );
}
/**
* @private
* Factory method for returning a Bridge object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _bridgeFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (Bridge) v" + version +"\naccount: " + account );
return new Bridge( account, _debug, _jsproxy );
}
/**
* Indicates the account value of the tracking.
*/
public function get account():String
{
return _account;
}
/**
* @private
*/
public function set account( value:String ):void
{
_account = value;
}
/**
* Determinates the Configuration object of the tracker.
*/
public function get config():Configuration
{
return _config;
}
/**
* @private
*/
public function set config( value:Configuration ):void
{
_config = value;
}
/**
* Determinates the DebugConfiguration of the tracker.
*/
public function get debug():DebugConfiguration
{
return _debug;
}
/**
* @private
*/
public function set debug( value:DebugConfiguration ):void
{
_debug = value;
}
/**
* Indicates if the tracker is ready to use.
*/
public function isReady():Boolean
{
return _ready;
}
/**
* Indicates the mode of the tracking "AS3" or "Bridge".
*/
public function get mode():String
{
return _mode;
}
/**
* @private
*/
public function set mode( value:String ):void
{
_mode = value ;
}
/**
* Indicates if the tracker use a visual debug.
*/
public function get visualDebug():Boolean
{
return _visualDebug;
}
/**
* @private
*/
public function set visualDebug( value:Boolean ):void
{
_visualDebug = value;
}
/**
* Builds the tracker.
*/
public function build():void
{
if( !isReady() )
{
_factory();
}
}
// IEventDispatcher implementation
/**
* Allows the registration of event listeners on the event target.
* @param type A string representing the event type to listen for. If eventName value is "ALL" addEventListener use addGlobalListener
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
* @param priority Determines the priority level of the event listener.
* @param useWeakReference Indicates if the listener is a weak reference.
*/
public function addEventListener( type:String, listener:Function, useCapture:Boolean = false, priority:int = 0,
useWeakReference:Boolean = false):void
{
_eventDispatcher.addEventListener( type, listener, useCapture, priority, useWeakReference );
}
/**
* Dispatches an event into the event flow.
* @param event The Event object that is dispatched into the event flow.
* @return <code class="prettyprint">true</code> if the Event is dispatched.
*/
public function dispatchEvent( event:Event ):Boolean
{
return _eventDispatcher.dispatchEvent( event );
}
/**
* Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
* This allows you to determine where altered handling of an event type has been introduced in the event flow heirarchy by an EventDispatcher object.
*/
public function hasEventListener( type:String ):Boolean
{
return _eventDispatcher.hasEventListener( type );
}
/**
* Removes a listener from the EventDispatcher object.
* If there is no matching listener registered with the <code class="prettyprint">EventDispatcher</code> object, then calling this method has no effect.
* @param type Specifies the type of event.
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
*/
public function removeEventListener( type:String, listener:Function, useCapture:Boolean = false ):void
{
_eventDispatcher.removeEventListener( type, listener, useCapture );
}
/**
* Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
* This method returns <code class="prettyprint">true</code> if an event listener is triggered during any phase of the event flow when an event of the specified type is dispatched to this EventDispatcher object or any of its descendants.
* @return A value of <code class="prettyprint">true</code> if a listener of the specified type will be triggered; <code class="prettyprint">false</code> otherwise.
*/
public function willTrigger( type:String ):Boolean
{
return _eventDispatcher.willTrigger( type );
}
include "common.txt"
}
}
|
/*
* 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
{
import com.google.analytics.core.Buffer;
import com.google.analytics.core.Ecommerce;
import com.google.analytics.core.EventTracker;
import com.google.analytics.core.GIFRequest;
import com.google.analytics.core.ServerOperationMode;
import com.google.analytics.core.TrackerCache;
import com.google.analytics.core.TrackerMode;
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.Layout;
import com.google.analytics.events.AnalyticsEvent;
import com.google.analytics.external.AdSenseGlobals;
import com.google.analytics.external.HTMLDOM;
import com.google.analytics.external.JavascriptProxy;
import com.google.analytics.utils.Environment;
import com.google.analytics.v4.Bridge;
import com.google.analytics.v4.Configuration;
import com.google.analytics.v4.GoogleAnalyticsAPI;
import com.google.analytics.v4.Tracker;
import core.version;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.EventDispatcher;
EventTracker;
ServerOperationMode;
/**
* Dispatched after the factory has built the tracker object.
* @eventType com.google.analytics.events.AnalyticsEvent.READY
*/
[Event(name="ready", type="com.google.analytics.events.AnalyticsEvent")]
/**
* Google Analytic Tracker Code (GATC)'s code-only component.
*/
public class GATracker implements AnalyticsTracker
{
private var _ready:Boolean = false;
private var _display:DisplayObject;
private var _eventDispatcher:EventDispatcher;
private var _tracker:GoogleAnalyticsAPI;
//factory
private var _config:Configuration;
private var _debug:DebugConfiguration;
private var _env:Environment;
private var _buffer:Buffer;
private var _gifRequest:GIFRequest;
private var _jsproxy:JavascriptProxy;
private var _dom:HTMLDOM;
private var _adSense:AdSenseGlobals;
private var _ecom:Ecommerce;
//object properties
private var _account:String;
private var _mode:String;
private var _visualDebug:Boolean;
/**
* Indicates if the tracker is automatically build.
*/
public static var autobuild:Boolean = true;
/**
* The version of the tracker.
*/
public static var version:core.version = API.version;
/**
* Creates a new GATracker instance.
* <p><b>Note:</b> the GATracker need to be instancied and added to the Stage or at least
* being placed in a display list.</p>
*/
public function GATracker( display:DisplayObject, account:String,
mode:String = "AS3", visualDebug:Boolean = false,
config:Configuration = null, debug:DebugConfiguration = null )
{
_display = display;
_eventDispatcher = new EventDispatcher( this ) ;
_tracker = new TrackerCache();
this.account = account;
this.mode = mode;
this.visualDebug = visualDebug;
if( !debug )
{
this.debug = new DebugConfiguration();
}
if( !config )
{
this.config = new Configuration( debug );
}
else
{
this.config = config;
}
if( autobuild )
{
_factory();
}
}
/**
* @private
* Factory to build the different trackers
*/
private function _factory():void
{
_jsproxy = new JavascriptProxy( debug );
if( visualDebug )
{
debug.layout = new Layout( debug, _display );
debug.active = visualDebug;
}
var activeTracker:GoogleAnalyticsAPI;
var cache:TrackerCache = _tracker as TrackerCache;
switch( mode )
{
case TrackerMode.BRIDGE :
{
activeTracker = _bridgeFactory();
break;
}
case TrackerMode.AS3 :
default:
{
activeTracker = _trackerFactory();
}
}
if( !cache.isEmpty() )
{
cache.tracker = activeTracker;
cache.flush();
}
_tracker = activeTracker;
_ready = true;
dispatchEvent( new AnalyticsEvent( AnalyticsEvent.READY, this ) );
}
/**
* @private
* Factory method for returning a Tracker object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _trackerFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (AS3) v" + version +"\naccount: " + account );
/* note:
for unit testing and to avoid 2 different branches AIR/Flash
here we will detect if we are in the Flash Player or AIR
and pass the infos to the LocalInfo
By default we will define "Flash" for our local tests
*/
_adSense = new AdSenseGlobals( debug );
_dom = new HTMLDOM( debug );
_dom.cacheProperties();
_env = new Environment( "", "", "", debug, _dom );
_buffer = new Buffer( config, debug, false );
_gifRequest = new GIFRequest( config, debug, _buffer, _env );
_ecom = new Ecommerce ( _debug );
/* note:
To be able to obtain the URL of the main SWF containing the GA API
we need to be able to access the stage property of a DisplayObject,
here we open the internal namespace to be able to set that reference
at instanciation-time.
We keep the implementation internal to be able to change it if required later.
*/
use namespace ga_internal;
_env.url = _display.stage.loaderInfo.url;
return new Tracker( account, config, debug, _env, _buffer, _gifRequest, _adSense, _ecom );
}
/**
* @private
* Factory method for returning a Bridge object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _bridgeFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (Bridge) v" + version +"\naccount: " + account );
return new Bridge( account, _debug, _jsproxy );
}
/**
* Indicates the account value of the tracking.
*/
public function get account():String
{
return _account;
}
/**
* @private
*/
public function set account( value:String ):void
{
_account = value;
}
/**
* Determinates the Configuration object of the tracker.
*/
public function get config():Configuration
{
return _config;
}
/**
* @private
*/
public function set config( value:Configuration ):void
{
_config = value;
}
/**
* Determinates the DebugConfiguration of the tracker.
*/
public function get debug():DebugConfiguration
{
return _debug;
}
/**
* @private
*/
public function set debug( value:DebugConfiguration ):void
{
_debug = value;
}
/**
* Indicates if the tracker is ready to use.
*/
public function isReady():Boolean
{
return _ready;
}
/**
* Indicates the mode of the tracking "AS3" or "Bridge".
*/
public function get mode():String
{
return _mode;
}
/**
* @private
*/
public function set mode( value:String ):void
{
_mode = value ;
}
/**
* Indicates if the tracker use a visual debug.
*/
public function get visualDebug():Boolean
{
return _visualDebug;
}
/**
* @private
*/
public function set visualDebug( value:Boolean ):void
{
_visualDebug = value;
}
/**
* Builds the tracker.
*/
public function build():void
{
if( !isReady() )
{
_factory();
}
}
// IEventDispatcher implementation
/**
* Allows the registration of event listeners on the event target.
* @param type A string representing the event type to listen for. If eventName value is "ALL" addEventListener use addGlobalListener
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
* @param priority Determines the priority level of the event listener.
* @param useWeakReference Indicates if the listener is a weak reference.
*/
public function addEventListener( type:String, listener:Function, useCapture:Boolean = false, priority:int = 0,
useWeakReference:Boolean = false):void
{
_eventDispatcher.addEventListener( type, listener, useCapture, priority, useWeakReference );
}
/**
* Dispatches an event into the event flow.
* @param event The Event object that is dispatched into the event flow.
* @return <code class="prettyprint">true</code> if the Event is dispatched.
*/
public function dispatchEvent( event:Event ):Boolean
{
return _eventDispatcher.dispatchEvent( event );
}
/**
* Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
* This allows you to determine where altered handling of an event type has been introduced in the event flow heirarchy by an EventDispatcher object.
*/
public function hasEventListener( type:String ):Boolean
{
return _eventDispatcher.hasEventListener( type );
}
/**
* Removes a listener from the EventDispatcher object.
* If there is no matching listener registered with the <code class="prettyprint">EventDispatcher</code> object, then calling this method has no effect.
* @param type Specifies the type of event.
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
*/
public function removeEventListener( type:String, listener:Function, useCapture:Boolean = false ):void
{
_eventDispatcher.removeEventListener( type, listener, useCapture );
}
/**
* Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
* This method returns <code class="prettyprint">true</code> if an event listener is triggered during any phase of the event flow when an event of the specified type is dispatched to this EventDispatcher object or any of its descendants.
* @return A value of <code class="prettyprint">true</code> if a listener of the specified type will be triggered; <code class="prettyprint">false</code> otherwise.
*/
public function willTrigger( type:String ):Boolean
{
return _eventDispatcher.willTrigger( type );
}
include "common.txt"
}
}
|
remove idle timer instanciation
|
remove idle timer instanciation
|
ActionScript
|
apache-2.0
|
jeremy-wischusen/gaforflash,dli-iclinic/gaforflash,dli-iclinic/gaforflash,jisobkim/gaforflash,soumavachakraborty/gaforflash,soumavachakraborty/gaforflash,drflash/gaforflash,DimaBaliakin/gaforflash,DimaBaliakin/gaforflash,Vigmar/gaforflash,jisobkim/gaforflash,Miyaru/gaforflash,Miyaru/gaforflash,jeremy-wischusen/gaforflash,Vigmar/gaforflash,mrthuanvn/gaforflash,drflash/gaforflash,mrthuanvn/gaforflash
|
9128a0ccca591e26d1f215a0e893375872b6520d
|
src/battlecode/client/viewer/render/DrawRobot.as
|
src/battlecode/client/viewer/render/DrawRobot.as
|
package battlecode.client.viewer.render {
import battlecode.common.ActionType;
import battlecode.common.Direction;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.RobotType;
import battlecode.common.Team;
import battlecode.events.RobotEvent;
import mx.containers.Canvas;
import mx.controls.Image;
import mx.core.UIComponent;
[Event(name="indicatorStringChange", type="battlecode.events.RobotEvent")]
public class DrawRobot extends Canvas implements DrawObject {
private var actions:Vector.<DrawAction>;
private var broadcastAnimation:BroadcastAnimation;
private var explosionAnimation:ExplosionAnimation;
private var overlayCanvas:UIComponent;
private var imageCanvas:UIComponent;
private var hatCanvas:UIComponent;
private var image:Image;
// size
private var overrideSize:Number;
// indicator strings
private var indicatorStrings:Vector.<String> = new Vector.<String>(3, true);
// movement animation
private var drawX:Number, drawY:Number;
private var movementDelay:uint;
// attack animation
private var targetLocation:MapLocation;
private var selected:Boolean = false;
private var robotID:uint;
private var type:String;
private var team:String;
private var location:MapLocation;
private var direction:String;
private var energon:Number = 0;
private var maxEnergon:Number = 0;
private var alive:Boolean = true;
private var hats:Array;
private var hatImages:Array;
public function DrawRobot(robotID:uint, type:String, team:String, overrideSize:Number = 0) {
this.robotID = robotID;
this.type = type;
this.team = team;
this.maxEnergon = RobotType.maxEnergon(type);
this.movementDelay = 0;
this.hats = new Array();
this.hatImages = new Array();
this.actions = new Vector.<DrawAction>();
this.overrideSize = overrideSize;
// set the unit avatar image
var avatarClass:Class = ImageAssets.getRobotAvatar(type, team);
this.imageCanvas = new UIComponent();
this.image = new Image();
this.image.source = avatarClass;
this.image.width = getImageSize(true);
this.image.height = getImageSize(true);
this.image.x = -this.image.width / 2;
this.image.y = -this.image.height / 2;
this.imageCanvas.addChild(image);
this.addChild(imageCanvas);
this.width = this.image.width;
this.height = this.image.height;
this.overlayCanvas = new UIComponent();
this.addChild(overlayCanvas);
this.hatCanvas = new UIComponent();
this.addChild(hatCanvas);
// set the hit area for click selection
this.hitArea = imageCanvas;
// animations
this.broadcastAnimation = new BroadcastAnimation(0, team);
this.addChild(broadcastAnimation);
this.explosionAnimation = new ExplosionAnimation();
this.addChild(explosionAnimation);
}
public function clone():DrawObject {
var d:DrawRobot = new DrawRobot(robotID, type, team, overrideSize);
d.location = location;
d.energon = energon;
d.movementDelay = movementDelay;
d.targetLocation = targetLocation;
d.alive = alive;
d.hats = hats.concat();
d.hatImages = new Array();
d.actions = new Vector.<DrawAction>(actions.length);
for each (var o:DrawAction in actions) {
d.actions.push(o.clone());
}
d.removeChild(d.broadcastAnimation);
d.removeChild(d.explosionAnimation);
d.broadcastAnimation = broadcastAnimation.clone() as BroadcastAnimation;
d.explosionAnimation = explosionAnimation.clone() as ExplosionAnimation;
d.addChild(d.broadcastAnimation);
d.addChild(d.explosionAnimation);
return d;
}
private function addAction(d:DrawAction):void {
actions.push(d);
}
public function getRobotID():uint {
return robotID;
}
public function getType():String {
return type;
}
public function getTeam():String {
return team;
}
public function getLocation():MapLocation {
return location;
}
public function getSelected():Boolean {
return selected;
}
public function getIndicatorString(index:uint):String {
return indicatorStrings[index];
}
public function setLocation(location:MapLocation):void {
this.location = location;
}
public function setEnergon(amt:Number):void {
this.energon = Math.min(Math.max(0, amt), maxEnergon);
}
public function setSelected(val:Boolean):void {
this.selected = val;
}
public function setIndicatorString(str:String, index:uint):void {
indicatorStrings[index] = str;
dispatchEvent(new RobotEvent(RobotEvent.INDICATOR_STRING_CHANGE, false, false, this));
}
public function setOverrideSize(overrideSize:Number):void {
this.overrideSize = overrideSize;
this.draw(true);
}
public function capture():void {
this.addAction(new DrawAction(ActionType.CAPTURING, GameConstants.CAPTURE_DELAY));
}
public function layMine():void {
this.addAction(new DrawAction(ActionType.MINING, GameConstants.MINE_LAY_DELAY));
}
public function stopLayingMine():void {
this.addAction(new DrawAction(ActionType.MINING_STOPPING, GameConstants.MINE_LAY_STOP_DELAY));
}
public function diffuseMine(hasUpgrade:Boolean):void {
this.addAction(new DrawAction(ActionType.DEFUSING, hasUpgrade ? GameConstants.MINE_DIFFUSE_UPGRADE_DELAY: GameConstants.MINE_DIFFUSE_DELAY))
}
public function attack(targetLocation:MapLocation):void {
this.targetLocation = targetLocation;
this.addAction(new DrawAction(ActionType.ATTACKING, RobotType.attackDelay(type)));
}
public function broadcast():void {
this.broadcastAnimation.broadcast();
}
public function destroyUnit():void {
this.explosionAnimation.explode();
this.alive = false;
}
public function moveToLocation(location:MapLocation):void {
this.direction = this.location.directionTo(location);
this.movementDelay = Direction.isDiagonal(direction) ?
RobotType.movementDelayDiagonal(type) :
RobotType.movementDelay(type);
this.location = location;
this.addAction(new DrawAction(ActionType.MOVING, movementDelay));
}
public function wearHat(hat:int):void {
hats.push(hat);
}
public function isAlive():Boolean {
return alive || explosionAnimation.isAlive();
}
public function updateRound():void {
// update actions
for (var i:uint = 0; i < actions.length; i++) {
var o:DrawAction = actions[i];
o.decreaseRound();
if (o.getRounds() <= 0) {
actions.splice(i, 1);
i--;
}
}
// update animations
broadcastAnimation.updateRound();
explosionAnimation.updateRound();
// update tooltip
this.toolTip = "Robot " + getRobotID() + " " + getType() + " Energon: " + energon + " Loc: " + getLocation().toString();
}
public function draw(force:Boolean = false):void {
if (explosionAnimation.isExploding()) {
this.imageCanvas.visible = false;
this.overlayCanvas.visible = false;
this.graphics.clear();
explosionAnimation.draw(force);
return;
}
// draw direction
this.imageCanvas.rotation = directionToRotation(direction);
if (force) {
this.image.width = getImageSize(true);
this.image.height = getImageSize(true);
this.image.x = -this.image.width / 2;
this.image.y = -this.image.height / 2;
}
// clear the graphics object once
this.graphics.clear();
this.overlayCanvas.graphics.clear();
var o:DrawAction;
var movementRounds:uint = 0;
for each (o in actions) {
if (o.getType() == ActionType.MOVING) {
movementRounds = o.getRounds();
break;
}
}
drawX = calculateDrawX(movementRounds);
drawY = calculateDrawY(movementRounds);
for each (o in actions) {
switch (o.getType()) {
case ActionType.ATTACKING:
drawAttack();
break;
case ActionType.MOVING:
drawMovement();
break;
case ActionType.CAPTURING:
case ActionType.MINING:
case ActionType.MINING_STOPPING:
case ActionType.DEFUSING:
drawActionBar(o);
break;
}
}
drawEnergonBar();
drawSelected();
drawHats();
// draw animations
broadcastAnimation.draw(force);
}
///////////////////////////////////////////////////////
////////////// DRAWING HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function drawEnergonBar():void {
if (!RenderConfiguration.showEnergon() && getType() != RobotType.HQ)
return;
var ratio:Number = energon / maxEnergon;
var size:Number = getImageSize(true);
this.graphics.lineStyle();
this.graphics.beginFill(0x00FF00, 0.8);
this.graphics.drawRect(-size / 2, size / 2, ratio * size, 5 * getImageScale());
this.graphics.endFill();
this.graphics.beginFill(0x000000, 0.8);
this.graphics.drawRect(-size / 2 + ratio * size, size / 2, (1 - ratio) * size, 5 * getImageScale());
this.graphics.endFill();
}
private function drawActionBar(action:DrawAction):void {
var yOffset:Number = RenderConfiguration.showEnergon() ? 5 * getImageScale() : 0;
var color:uint;
switch (action.getType()) {
case ActionType.CAPTURING:
color = 0x4C4CFF;
break;
case ActionType.MINING:
color = 0xFF00CC;
break;
case ActionType.MINING_STOPPING:
color = 0xFF0000;
break;
case ActionType.DEFUSING:
color = 0x00FFFF;
break;
default:
color = 0x000000;
break;
}
var ratio:Number;
switch (action.getType()) {
case ActionType.MINING_STOPPING:
ratio = action.getRounds() / action.getMaxRounds();
break;
default:
ratio = (action.getMaxRounds() - action.getRounds()) / action.getMaxRounds();
break;
}
var size:Number = getImageSize(true);
this.graphics.lineStyle();
this.graphics.beginFill(color, 0.8);
this.graphics.drawRect(-size / 2, size / 2 + yOffset, ratio * size, 5 * getImageScale());
this.graphics.endFill();
this.graphics.beginFill(0x000000, 0.8);
this.graphics.drawRect(-size / 2 + ratio * size, size / 2 + yOffset, (1 - ratio) * size, 5 * getImageScale());
this.graphics.endFill();
}
private function drawAttack():void {
var targetOffsetX:Number = (targetLocation.getX() - location.getX()) * getImageSize();
var targetOffsetY:Number = (targetLocation.getY() - location.getY()) * getImageSize();
this.graphics.lineStyle(2, team == Team.A ? 0xFF0000 : 0x0000FF);
this.graphics.moveTo(0, 0);
this.graphics.lineTo(targetOffsetX - drawX, targetOffsetY - drawY);
this.graphics.drawCircle(targetOffsetX - drawX, targetOffsetY - drawY, getImageSize() / 2 * .6);
}
private function drawMovement():void {
if (RenderConfiguration.showDiscrete()) return;
this.x += drawX;
this.y += drawY;
}
private function drawSelected():void {
var size:Number = getImageSize(true);
if (selected) {
this.graphics.lineStyle(2, 0xFFFFFF);
this.graphics.moveTo(-size / 2, -size / 4);
this.graphics.lineTo(-size / 2, -size / 2);
this.graphics.lineTo(-size / 4, -size / 2);
this.graphics.moveTo(size / 2, -size / 4);
this.graphics.lineTo(size / 2, -size / 2);
this.graphics.lineTo(size / 4, -size / 2);
this.graphics.moveTo(size / 2, size / 4);
this.graphics.lineTo(size / 2, size / 2);
this.graphics.lineTo(size / 4, size / 2);
this.graphics.moveTo(-size / 2, size / 4);
this.graphics.lineTo(-size / 2, size / 2);
this.graphics.lineTo(-size / 4, size / 2);
}
}
private function drawHats():void {
if (!RenderConfiguration.showHats()) {
hatCanvas.visible = false;
return;
}
hatCanvas.visible = true;
while (hatImages.length < hats.length) {
var hatImage:Image = new Image();
var hatSource:Class = ImageAssets.getHatAvatar(hats[hatImages.length]);
hatImage.source = new hatSource();
hatImage.width = RenderConfiguration.getGridSize();
hatImage.height = RenderConfiguration.getGridSize();
hatImage.x = -RenderConfiguration.getGridSize() / 2;
hatImage.y = -RenderConfiguration.getGridSize() - hatImage.height * hatImages.length;
hatCanvas.addChild(hatImage);
hatImages.push(hatImage);
}
}
///////////////////////////////////////////////////////
////////////// PRIVATE HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function getImageSize(scale:Boolean = false):Number {
if (overrideSize)
return overrideSize;
return RenderConfiguration.getGridSize() * (scale ? getUnitScale(type) : 1.0);
}
private function getImageScale():Number {
if (overrideSize)
return 1.0;
return RenderConfiguration.getScalingFactor();
}
private function getUnitScale(type:String):Number {
switch (type) {
case RobotType.HQ:
return 2.0;
case RobotType.TOWER:
return 1.5;
default:
return 1.0;
}
}
private function getUnitOffset(type:String):Number {
return 0;
}
private function directionToRotation(dir:String):int {
switch (dir) {
case Direction.NORTH:
return -90;
case Direction.NORTH_EAST:
return -45;
case Direction.EAST:
return 0;
case Direction.SOUTH_EAST:
return 45;
case Direction.SOUTH:
return 90;
case Direction.SOUTH_WEST:
return 135;
case Direction.WEST:
return 180;
case Direction.NORTH_WEST:
return -135;
default:
return 0;
}
}
private function directionOffsetX(dir:String):int {
switch (dir) {
case Direction.NORTH_EAST:
return +1;
case Direction.NORTH_WEST:
return -1;
case Direction.SOUTH_EAST:
return +1;
case Direction.SOUTH_WEST:
return -1;
case Direction.NORTH:
return 0;
case Direction.SOUTH:
return 0;
case Direction.EAST:
return +1;
case Direction.WEST:
return -1;
default:
return 0;
}
}
private function directionOffsetY(dir:String):int {
switch (dir) {
case Direction.NORTH_EAST:
return -1;
case Direction.NORTH_WEST:
return -1;
case Direction.SOUTH_EAST:
return +1;
case Direction.SOUTH_WEST:
return +1;
case Direction.NORTH:
return -1;
case Direction.SOUTH:
return +1;
case Direction.EAST:
return 0;
case Direction.WEST:
return 0;
default:
return 0;
}
}
private function calculateDrawX(rounds:uint):Number {
if (RenderConfiguration.showDiscrete()) return 0;
return -1 * getImageSize() * directionOffsetX(direction) * (rounds / movementDelay);
}
private function calculateDrawY(rounds:uint):Number {
if (RenderConfiguration.showDiscrete()) return 0;
return -1 * getImageSize() * directionOffsetY(direction) * (rounds / movementDelay);
}
}
}
|
package battlecode.client.viewer.render {
import battlecode.common.ActionType;
import battlecode.common.Direction;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.RobotType;
import battlecode.common.Team;
import battlecode.events.RobotEvent;
import mx.containers.Canvas;
import mx.controls.Image;
import mx.core.UIComponent;
[Event(name="indicatorStringChange", type="battlecode.events.RobotEvent")]
public class DrawRobot extends Canvas implements DrawObject {
private var actions:Vector.<DrawAction>;
private var broadcastAnimation:BroadcastAnimation;
private var explosionAnimation:ExplosionAnimation;
private var overlayCanvas:UIComponent;
private var imageCanvas:UIComponent;
private var hatCanvas:UIComponent;
private var image:Image;
// size
private var overrideSize:Number;
// indicator strings
private var indicatorStrings:Vector.<String> = new Vector.<String>(3, true);
// movement animation
private var drawX:Number, drawY:Number;
private var movementDelay:uint;
// attack animation
private var targetLocation:MapLocation;
private var selected:Boolean = false;
private var robotID:uint;
private var type:String;
private var team:String;
private var location:MapLocation;
private var direction:String;
private var energon:Number = 0;
private var maxEnergon:Number = 0;
private var alive:Boolean = true;
private var hats:Array;
private var hatImages:Array;
public function DrawRobot(robotID:uint, type:String, team:String, overrideSize:Number = 0) {
this.robotID = robotID;
this.type = type;
this.team = team;
this.maxEnergon = RobotType.maxEnergon(type);
this.movementDelay = 1;
this.hats = new Array();
this.hatImages = new Array();
this.actions = new Vector.<DrawAction>();
this.overrideSize = overrideSize;
// set the unit avatar image
var avatarClass:Class = ImageAssets.getRobotAvatar(type, team);
this.imageCanvas = new UIComponent();
this.image = new Image();
this.image.source = avatarClass;
this.image.width = getImageSize(true);
this.image.height = getImageSize(true);
this.image.x = -this.image.width / 2;
this.image.y = -this.image.height / 2;
this.imageCanvas.addChild(image);
this.addChild(imageCanvas);
this.width = this.image.width;
this.height = this.image.height;
this.overlayCanvas = new UIComponent();
this.addChild(overlayCanvas);
this.hatCanvas = new UIComponent();
this.addChild(hatCanvas);
// set the hit area for click selection
this.hitArea = imageCanvas;
// animations
this.broadcastAnimation = new BroadcastAnimation(0, team);
this.addChild(broadcastAnimation);
this.explosionAnimation = new ExplosionAnimation();
this.addChild(explosionAnimation);
}
public function clone():DrawObject {
var d:DrawRobot = new DrawRobot(robotID, type, team, overrideSize);
d.location = location;
d.energon = energon;
d.movementDelay = movementDelay;
d.targetLocation = targetLocation;
d.alive = alive;
d.hats = hats.concat();
d.hatImages = new Array();
d.actions = new Vector.<DrawAction>(actions.length);
for each (var o:DrawAction in actions) {
d.actions.push(o.clone());
}
d.removeChild(d.broadcastAnimation);
d.removeChild(d.explosionAnimation);
d.broadcastAnimation = broadcastAnimation.clone() as BroadcastAnimation;
d.explosionAnimation = explosionAnimation.clone() as ExplosionAnimation;
d.addChild(d.broadcastAnimation);
d.addChild(d.explosionAnimation);
return d;
}
private function addAction(d:DrawAction):void {
actions.push(d);
}
public function getRobotID():uint {
return robotID;
}
public function getType():String {
return type;
}
public function getTeam():String {
return team;
}
public function getLocation():MapLocation {
return location;
}
public function getSelected():Boolean {
return selected;
}
public function getIndicatorString(index:uint):String {
return indicatorStrings[index];
}
public function setLocation(location:MapLocation):void {
this.location = location;
}
public function setEnergon(amt:Number):void {
this.energon = Math.min(Math.max(0, amt), maxEnergon);
}
public function setSelected(val:Boolean):void {
this.selected = val;
}
public function setIndicatorString(str:String, index:uint):void {
indicatorStrings[index] = str;
dispatchEvent(new RobotEvent(RobotEvent.INDICATOR_STRING_CHANGE, false, false, this));
}
public function setOverrideSize(overrideSize:Number):void {
this.overrideSize = overrideSize;
this.draw(true);
}
public function capture():void {
this.addAction(new DrawAction(ActionType.CAPTURING, GameConstants.CAPTURE_DELAY));
}
public function layMine():void {
this.addAction(new DrawAction(ActionType.MINING, GameConstants.MINE_LAY_DELAY));
}
public function stopLayingMine():void {
this.addAction(new DrawAction(ActionType.MINING_STOPPING, GameConstants.MINE_LAY_STOP_DELAY));
}
public function diffuseMine(hasUpgrade:Boolean):void {
this.addAction(new DrawAction(ActionType.DEFUSING, hasUpgrade ? GameConstants.MINE_DIFFUSE_UPGRADE_DELAY: GameConstants.MINE_DIFFUSE_DELAY))
}
public function attack(targetLocation:MapLocation):void {
this.targetLocation = targetLocation;
this.addAction(new DrawAction(ActionType.ATTACKING, RobotType.attackDelay(type)));
}
public function broadcast():void {
this.broadcastAnimation.broadcast();
}
public function destroyUnit():void {
this.explosionAnimation.explode();
this.alive = false;
}
public function moveToLocation(location:MapLocation):void {
this.direction = this.location.directionTo(location);
this.movementDelay = Direction.isDiagonal(direction) ?
RobotType.movementDelayDiagonal(type) :
RobotType.movementDelay(type);
this.location = location;
this.addAction(new DrawAction(ActionType.MOVING, movementDelay));
}
public function wearHat(hat:int):void {
hats.push(hat);
}
public function isAlive():Boolean {
return alive || explosionAnimation.isAlive();
}
public function updateRound():void {
// update actions
for (var i:uint = 0; i < actions.length; i++) {
var o:DrawAction = actions[i];
o.decreaseRound();
if (o.getRounds() <= 0) {
actions.splice(i, 1);
i--;
}
}
// update animations
broadcastAnimation.updateRound();
explosionAnimation.updateRound();
// update tooltip
this.toolTip = "Robot " + getRobotID() + " " + getType() + " Energon: " + energon + " Loc: " + getLocation().toString();
}
public function draw(force:Boolean = false):void {
if (explosionAnimation.isExploding()) {
this.imageCanvas.visible = false;
this.overlayCanvas.visible = false;
this.graphics.clear();
explosionAnimation.draw(force);
return;
}
// draw direction
this.imageCanvas.rotation = directionToRotation(direction);
if (force) {
this.image.width = getImageSize(true);
this.image.height = getImageSize(true);
this.image.x = -this.image.width / 2;
this.image.y = -this.image.height / 2;
}
// clear the graphics object once
this.graphics.clear();
this.overlayCanvas.graphics.clear();
var o:DrawAction;
var movementRounds:uint = 0;
for each (o in actions) {
if (o.getType() == ActionType.MOVING) {
movementRounds = o.getRounds();
break;
}
}
drawX = calculateDrawX(movementRounds);
drawY = calculateDrawY(movementRounds);
for each (o in actions) {
switch (o.getType()) {
case ActionType.ATTACKING:
drawAttack();
break;
case ActionType.MOVING:
drawMovement();
break;
case ActionType.CAPTURING:
case ActionType.MINING:
case ActionType.MINING_STOPPING:
case ActionType.DEFUSING:
drawActionBar(o);
break;
}
}
drawEnergonBar();
drawSelected();
drawHats();
// draw animations
broadcastAnimation.draw(force);
}
///////////////////////////////////////////////////////
////////////// DRAWING HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function drawEnergonBar():void {
if (!RenderConfiguration.showEnergon() && getType() != RobotType.HQ)
return;
var ratio:Number = energon / maxEnergon;
var size:Number = getImageSize(true);
this.graphics.lineStyle();
this.graphics.beginFill(0x00FF00, 0.8);
this.graphics.drawRect(-size / 2, size / 2, ratio * size, 5 * getImageScale());
this.graphics.endFill();
this.graphics.beginFill(0x000000, 0.8);
this.graphics.drawRect(-size / 2 + ratio * size, size / 2, (1 - ratio) * size, 5 * getImageScale());
this.graphics.endFill();
}
private function drawActionBar(action:DrawAction):void {
var yOffset:Number = RenderConfiguration.showEnergon() ? 5 * getImageScale() : 0;
var color:uint;
switch (action.getType()) {
case ActionType.CAPTURING:
color = 0x4C4CFF;
break;
case ActionType.MINING:
color = 0xFF00CC;
break;
case ActionType.MINING_STOPPING:
color = 0xFF0000;
break;
case ActionType.DEFUSING:
color = 0x00FFFF;
break;
default:
color = 0x000000;
break;
}
var ratio:Number;
switch (action.getType()) {
case ActionType.MINING_STOPPING:
ratio = action.getRounds() / action.getMaxRounds();
break;
default:
ratio = (action.getMaxRounds() - action.getRounds()) / action.getMaxRounds();
break;
}
var size:Number = getImageSize(true);
this.graphics.lineStyle();
this.graphics.beginFill(color, 0.8);
this.graphics.drawRect(-size / 2, size / 2 + yOffset, ratio * size, 5 * getImageScale());
this.graphics.endFill();
this.graphics.beginFill(0x000000, 0.8);
this.graphics.drawRect(-size / 2 + ratio * size, size / 2 + yOffset, (1 - ratio) * size, 5 * getImageScale());
this.graphics.endFill();
}
private function drawAttack():void {
var targetOffsetX:Number = (targetLocation.getX() - location.getX()) * getImageSize();
var targetOffsetY:Number = (targetLocation.getY() - location.getY()) * getImageSize();
this.graphics.lineStyle(2, team == Team.A ? 0xFF0000 : 0x0000FF);
this.graphics.moveTo(0, 0);
this.graphics.lineTo(targetOffsetX - drawX, targetOffsetY - drawY);
this.graphics.drawCircle(targetOffsetX - drawX, targetOffsetY - drawY, getImageSize() / 2 * .6);
}
private function drawMovement():void {
if (RenderConfiguration.showDiscrete()) return;
this.x += drawX;
this.y += drawY;
}
private function drawSelected():void {
var size:Number = getImageSize(true);
if (selected) {
this.graphics.lineStyle(2, 0xFFFFFF);
this.graphics.moveTo(-size / 2, -size / 4);
this.graphics.lineTo(-size / 2, -size / 2);
this.graphics.lineTo(-size / 4, -size / 2);
this.graphics.moveTo(size / 2, -size / 4);
this.graphics.lineTo(size / 2, -size / 2);
this.graphics.lineTo(size / 4, -size / 2);
this.graphics.moveTo(size / 2, size / 4);
this.graphics.lineTo(size / 2, size / 2);
this.graphics.lineTo(size / 4, size / 2);
this.graphics.moveTo(-size / 2, size / 4);
this.graphics.lineTo(-size / 2, size / 2);
this.graphics.lineTo(-size / 4, size / 2);
}
}
private function drawHats():void {
if (!RenderConfiguration.showHats()) {
hatCanvas.visible = false;
return;
}
hatCanvas.visible = true;
while (hatImages.length < hats.length) {
var hatImage:Image = new Image();
var hatSource:Class = ImageAssets.getHatAvatar(hats[hatImages.length]);
hatImage.source = new hatSource();
hatImage.width = RenderConfiguration.getGridSize();
hatImage.height = RenderConfiguration.getGridSize();
hatImage.x = -RenderConfiguration.getGridSize() / 2;
hatImage.y = -RenderConfiguration.getGridSize() - hatImage.height * hatImages.length;
hatCanvas.addChild(hatImage);
hatImages.push(hatImage);
}
}
///////////////////////////////////////////////////////
////////////// PRIVATE HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function getImageSize(scale:Boolean = false):Number {
if (overrideSize)
return overrideSize;
return RenderConfiguration.getGridSize() * (scale ? getUnitScale(type) : 1.0);
}
private function getImageScale():Number {
if (overrideSize)
return 1.0;
return RenderConfiguration.getScalingFactor();
}
private function getUnitScale(type:String):Number {
switch (type) {
case RobotType.HQ:
return 2.0;
case RobotType.TOWER:
return 1.5;
default:
return 1.0;
}
}
private function getUnitOffset(type:String):Number {
return 0;
}
private function directionToRotation(dir:String):int {
switch (dir) {
case Direction.NORTH:
return -90;
case Direction.NORTH_EAST:
return -45;
case Direction.EAST:
return 0;
case Direction.SOUTH_EAST:
return 45;
case Direction.SOUTH:
return 90;
case Direction.SOUTH_WEST:
return 135;
case Direction.WEST:
return 180;
case Direction.NORTH_WEST:
return -135;
default:
return 0;
}
}
private function directionOffsetX(dir:String):int {
switch (dir) {
case Direction.NORTH_EAST:
return +1;
case Direction.NORTH_WEST:
return -1;
case Direction.SOUTH_EAST:
return +1;
case Direction.SOUTH_WEST:
return -1;
case Direction.NORTH:
return 0;
case Direction.SOUTH:
return 0;
case Direction.EAST:
return +1;
case Direction.WEST:
return -1;
default:
return 0;
}
}
private function directionOffsetY(dir:String):int {
switch (dir) {
case Direction.NORTH_EAST:
return -1;
case Direction.NORTH_WEST:
return -1;
case Direction.SOUTH_EAST:
return +1;
case Direction.SOUTH_WEST:
return +1;
case Direction.NORTH:
return -1;
case Direction.SOUTH:
return +1;
case Direction.EAST:
return 0;
case Direction.WEST:
return 0;
default:
return 0;
}
}
private function calculateDrawX(rounds:uint):Number {
if (RenderConfiguration.showDiscrete()) return 0;
return -1 * getImageSize() * directionOffsetX(direction) * (rounds / movementDelay);
}
private function calculateDrawY(rounds:uint):Number {
if (RenderConfiguration.showDiscrete()) return 0;
return -1 * getImageSize() * directionOffsetY(direction) * (rounds / movementDelay);
}
}
}
|
fix attack animation for non-moving units
|
fix attack animation for non-moving units
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
10e7a405b912d5ea3977986afc361b37f95f3a38
|
src/NetConnectionPolyfill.as
|
src/NetConnectionPolyfill.as
|
package {
import flash.display.Sprite;
import flash.system.Security;
import flash.net.NetConnection;
import flash.external.ExternalInterface;
import flash.events.Event;
import flash.events.AsyncErrorEvent
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.events.IOErrorEvent
public class NetConnectionPolyfill extends Sprite {
public const VERSION:String = CONFIG::version;
private var _nc:NetConnection;
private var _jsLogProxyName: String = "NetConnection.onFlashLog";
private var _jsReadyProxyName: String = "NetConnection.onReady";
private var _jsAsyncErrorEventProxyName: String = "NetConnection.onAsyncErrorEvent";
private var _jsIOErrorEventProxyName: String = "NetConnection.onIOErrorEvent";
private var _jsNetStatusEventProxyName: String = "NetConnection.onNetStatusEvent";
private var _jsSecurityErrorEventProxyName: String = "NetConnection.onSecurityErrorEvent";
private var _jsClientCallProxyName: String = "NetConnection.onClientCall";
public function NetConnectionPolyfill() {
log('info', 'New NetConnection instance');
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function init():void {
Security.allowDomain("*");
Security.allowInsecureDomain("*");
if(ExternalInterface.available) {
registerExternalMethods();
}
_nc = new NetConnection();
_nc.addEventListener(NetStatusEvent.NET_STATUS, onNetStatusEvent);
_nc.addEventListener(IOErrorEvent.IO_ERROR, onIOErrorEvent);
_nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityErrorEvent);
_nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, onAyncErrorEvent);
callExternalInterface(_jsReadyProxyName);
}
private function registerExternalMethods():void {
try {
ExternalInterface.addCallback("nc_addHeader", onAddHeaderCalled);
ExternalInterface.addCallback("nc_call", onCallCalled);
ExternalInterface.addCallback("nc_close", onCloseCalled);
ExternalInterface.addCallback("nc_connect", onConnectCalled);
ExternalInterface.addCallback("nc_getProperty", onGetPropertyCalled);
ExternalInterface.addCallback("nc_setProperty", onSetPropertyCalled);
ExternalInterface.addCallback("nc_setClient", onSetClientCalled);
} catch (e:Error) {
log("error", e.message);
} finally {}
}
private function onAddedToStage(event: Event):void {
init();
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAyncErrorEvent(event: AsyncErrorEvent): void {
callExternalInterface(_jsAsyncErrorEventProxyName, event.type, event.error);
}
private function onIOErrorEvent(event:IOErrorEvent): void {
callExternalInterface(_jsIOErrorEventProxyName, event.type, event.text);
}
private function onSecurityErrorEvent(event: SecurityErrorEvent): void {
callExternalInterface(_jsSecurityErrorEventProxyName, event.type, event.text);
}
private function onNetStatusEvent(event: NetStatusEvent): void {
callExternalInterface(_jsNetStatusEventProxyName, event.type, event.info);
}
private function onAddHeaderCalled(opeartion: String, mustUnderstand: Boolean = false, param: Object = null):void {
this._nc.addHeader(opeartion, mustUnderstand, param);
}
private function onCallCalled(command: String, ... args):void {
try {
log('info', 'Calling '+command);
var __incomingArgs:* = args as Array;
var __newArgs:Array = [command, null].concat(__incomingArgs);
var __sanitizedArgs:Array = cleanObject(__newArgs);
this._nc.call.apply(this._nc, __sanitizedArgs);
} catch (e: Error) {
log('error', e.message);
}
}
private function onCloseCalled():void {
this._nc.close();
}
private function onConnectCalled(command:*, ...args):void {
log('info', 'Connecting to '+command);
var __incomingArgs:* = args as Array;
var __newArgs:Array = [command].concat(__incomingArgs);
var __sanitizedArgs:Array = cleanObject(__newArgs);
this._nc.connect.apply(this._nc, __sanitizedArgs);
}
private function onSetClientCalled(methods: Array):void {
this._nc.client = new Object();
try {
for (var i = 0; i < methods.length; i++) {
var method = methods[i];
this._nc.client[method] = function(... args) {
callExternalInterface(_jsClientCallProxyName, method, args);
}
}
} catch (e: Error) {
log('error', e.message);
}
}
private function onGetPropertyCalled(pPropertyName:String = ""):* {
if (this._nc.hasOwnProperty(pPropertyName)) {
if (this._nc[pPropertyName] is Function) {
log('warning', 'It is not possible to get a function as a property');
return null;
}
return this._nc[pPropertyName];
}
return null;
}
private function onSetPropertyCalled(pPropertyName: String, value: *):void {
switch(pPropertyName) {
case "objectEncoding":
this._nc.objectEncoding = value as uint;
break;
case "proxyType":
this._nc.proxyType = value as String;
break;
case "maxPeerConnections":
this._nc.maxPeerConnections = value as uint;
break;
default:
log('warning', 'Property '+pPropertyName+ ' cannot be set.');
}
}
private function log(level: String, message: *):void {
if (loaderInfo.parameters.debug != undefined && loaderInfo.parameters.debug == "true") {
this.callExternalInterface(_jsLogProxyName, level, cleanObject(message));
}
}
private function callExternalInterface(proxyName: String, ...args):void {
if (ExternalInterface.available) {
var __incomingArgs:* = args as Array;
var __newArgs:Array = [proxyName, ExternalInterface.objectID].concat(__incomingArgs);
var __sanitizedArgs:Array = cleanObject(__newArgs);
ExternalInterface.call.apply(null, __sanitizedArgs);
}
}
private function cleanObject(o:*):* {
if (o == null) {
return null;
}
if (o is String) {
return o.split("\\").join("\\\\");
} else if (o is Array) {
var __sanitizedArray:Array = new Array();
for each (var __item in o){
__sanitizedArray.push(cleanObject(__item));
}
return __sanitizedArray;
} else if (typeof(o) == 'object') {
var __sanitizedObject:Object = new Object();
for (var __i in o){
__sanitizedObject[__i] = cleanObject(o[__i]);
}
return __sanitizedObject;
} else {
return o;
}
}
}
}
|
package {
import flash.display.Sprite;
import flash.system.Security;
import flash.net.NetConnection;
import flash.net.Responder;
import flash.external.ExternalInterface;
import flash.events.Event;
import flash.events.AsyncErrorEvent
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.events.IOErrorEvent
public class NetConnectionPolyfill extends Sprite {
public const VERSION:String = CONFIG::version;
private var _nc:NetConnection;
private var _jsLogProxyName: String = "NetConnection.onFlashLog";
private var _jsReadyProxyName: String = "NetConnection.onReady";
private var _jsAsyncErrorEventProxyName: String = "NetConnection.onAsyncErrorEvent";
private var _jsIOErrorEventProxyName: String = "NetConnection.onIOErrorEvent";
private var _jsNetStatusEventProxyName: String = "NetConnection.onNetStatusEvent";
private var _jsSecurityErrorEventProxyName: String = "NetConnection.onSecurityErrorEvent";
private var _jsClientCallProxyName: String = "NetConnection.onClientCall";
private var _jsClientCallResultProxyName: String = "NetConnection.onClientCallResult";
public function NetConnectionPolyfill() {
log('info', 'New NetConnection instance');
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function init():void {
Security.allowDomain("*");
Security.allowInsecureDomain("*");
if(ExternalInterface.available) {
registerExternalMethods();
}
_nc = new NetConnection();
_nc.addEventListener(NetStatusEvent.NET_STATUS, onNetStatusEvent);
_nc.addEventListener(IOErrorEvent.IO_ERROR, onIOErrorEvent);
_nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityErrorEvent);
_nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, onAyncErrorEvent);
callExternalInterface(_jsReadyProxyName);
}
private function registerExternalMethods():void {
try {
ExternalInterface.addCallback("nc_addHeader", onAddHeaderCalled);
ExternalInterface.addCallback("nc_call", onCallCalled);
ExternalInterface.addCallback("nc_close", onCloseCalled);
ExternalInterface.addCallback("nc_connect", onConnectCalled);
ExternalInterface.addCallback("nc_getProperty", onGetPropertyCalled);
ExternalInterface.addCallback("nc_setProperty", onSetPropertyCalled);
ExternalInterface.addCallback("nc_setClient", onSetClientCalled);
} catch (e:Error) {
log("error", e.message);
} finally {}
}
private function onAddedToStage(event: Event):void {
init();
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAyncErrorEvent(event: AsyncErrorEvent): void {
callExternalInterface(_jsAsyncErrorEventProxyName, event.type, event.error);
}
private function onIOErrorEvent(event:IOErrorEvent): void {
callExternalInterface(_jsIOErrorEventProxyName, event.type, event.text);
}
private function onSecurityErrorEvent(event: SecurityErrorEvent): void {
callExternalInterface(_jsSecurityErrorEventProxyName, event.type, event.text);
}
private function onNetStatusEvent(event: NetStatusEvent): void {
callExternalInterface(_jsNetStatusEventProxyName, event.type, event.info);
}
private function onAddHeaderCalled(opeartion: String, mustUnderstand: Boolean = false, param: Object = null):void {
this._nc.addHeader(opeartion, mustUnderstand, param);
}
private function onCallCalled(command: String, handlerId: String, ... args):void {
try {
log('info', 'Calling command: '+command);
var responder: Responder = new Responder(function(result: Object) {
callExternalInterface(_jsClientCallResultProxyName, handlerId, null, cleanObject(result));
}, function(error: Object) {
callExternalInterface(_jsClientCallResultProxyName, handlerId, cleanObject(error));
});
var __incomingArgs:* = args as Array;
var __newArgs:Array = [command, responder].concat(cleanObject(__incomingArgs));
this._nc.call.apply(this._nc, __newArgs);
} catch (e: Error) {
log('error', e.message);
}
}
private function onCloseCalled():void {
this._nc.close();
}
private function onConnectCalled(command:*, ...args):void {
log('info', 'Connecting to '+command);
var __incomingArgs:* = args as Array;
var __newArgs:Array = [command].concat(__incomingArgs);
var __sanitizedArgs:Array = cleanObject(__newArgs);
this._nc.connect.apply(this._nc, __sanitizedArgs);
}
private function onSetClientCalled(methods: Array):void {
var self = this;
this._nc.client = new Object();
try {
for (var i = 0; i < methods.length; i++) {
var method = methods[i];
log('info', 'Creating method '+method);
var createMethod = function(method) {
var m = method;
return function(... args) {
var _incomingArgs:* = args as Array;
callExternalInterface.apply(self, [_jsClientCallProxyName, m].concat(_incomingArgs));
}
}
this._nc.client[method] = createMethod(method);
}
} catch (e: Error) {
log('error', e.message);
}
}
private function onGetPropertyCalled(pPropertyName:String = ""):* {
if (this._nc.hasOwnProperty(pPropertyName)) {
if (this._nc[pPropertyName] is Function) {
log('warning', 'It is not possible to get a function as a property');
return null;
}
return this._nc[pPropertyName];
}
return null;
}
private function onSetPropertyCalled(pPropertyName: String, value: *):void {
switch(pPropertyName) {
case "objectEncoding":
this._nc.objectEncoding = value as uint;
break;
case "proxyType":
this._nc.proxyType = value as String;
break;
case "maxPeerConnections":
this._nc.maxPeerConnections = value as uint;
break;
default:
log('warning', 'Property '+pPropertyName+ ' cannot be set.');
}
}
private function log(level: String, message: *):void {
if (loaderInfo.parameters.debug != undefined && loaderInfo.parameters.debug == "true") {
this.callExternalInterface(_jsLogProxyName, level, cleanObject(message));
}
}
private function callExternalInterface(proxyName: String, ...args):void {
if (ExternalInterface.available) {
var __incomingArgs:* = args as Array;
var __newArgs:Array = [proxyName, ExternalInterface.objectID].concat(__incomingArgs);
var __sanitizedArgs:Array = cleanObject(__newArgs);
ExternalInterface.call.apply(null, __sanitizedArgs);
}
}
private function cleanObject(o:*):* {
if (o == null) {
return null;
}
if (o is String) {
return o.split("\\").join("\\\\");
} else if (o is Array) {
var __sanitizedArray:Array = new Array();
for each (var __item in o){
__sanitizedArray.push(cleanObject(__item));
}
return __sanitizedArray;
} else if (typeof(o) == 'object') {
var __sanitizedObject:Object = new Object();
for (var __i in o){
__sanitizedObject[__i] = cleanObject(o[__i]);
}
return __sanitizedObject;
} else {
return o;
}
}
}
}
|
Implement call responder
|
feat(call): Implement call responder
Create a new Responder when call method is invoked. The responder will call external interface with either the result or an error.
NetConnection-polyfill should implement the static method "onClientCallResult" which will receive the result of a call invoke.
|
ActionScript
|
mit
|
cladera/netconnection-polyfill-swf
|
894adaeac00bc31c847d85f279d872886a32751e
|
test/trace/values.as
|
test/trace/values.as
|
// This ActionScript file defines a list of values that are considered
// important for checking various ActionScript operations.
// It defines 2 variables:
// - "values": The array of values to be checked
// - "names": The array of corresponding string representations for values.
// It's suggested to use these instead of using values directly to
// avoid spurious toString and valueOf calls.
printall = new Object ();
printall.valueOf = function () {
trace ("valueOf called");
return this;
};
printall.toString = function () {
trace ("toString called");
return this;
};
tostring = new Object ();
tostring.toString = function () {
trace ("toString called with " + arguments);
return this;
};
valueof = new Object ();
valueof.valueOf = function () {
trace ("valueOf called with " + arguments);
return this;
};
nothing = new Object ();
nothing.__proto__ = undefined;
values = [
undefined,
null,
true, false,
0, 1, 0.5, -1, -0.5, Infinity, -Infinity, NaN,
"", "0", "-0", "0.0", "1", "Hello World!", "true", "_level0",
this, new Object (), Function, printall, tostring, valueof, nothing ];
var l = values.length;
var v = function () {
trace (this.nr + ": valueOf!");
return this.v;
};
var s = function () {
trace (this.nr + ": toString!");
return this.v;
};
for (i = 0; i < l; i++) {
var o = new Object ();
o.nr = i;
o.valueOf = v;
o.toString = s;
o.v = values[i];
values.push (o);
};
names = [];
for (i = 0; i < values.length; i++) {
names[i] = "(" + i + ") " + values[i] + " (" + typeof (values[i]) + ")";
};
|
// This ActionScript file defines a list of values that are considered
// important for checking various ActionScript operations.
// It defines 2 variables:
// - "values": The array of values to be checked
// - "names": The array of corresponding string representations for values.
// It's suggested to use these instead of using values directly to
// avoid spurious toString and valueOf calls.
printall = new Object ();
printall.valueOf = function () {
trace ("valueOf called");
return this;
};
printall.toString = function () {
trace ("toString called");
return this;
};
printtostring = new Object ();
printtostring.toString = function () {
trace ("toString called with " + arguments);
return this;
};
printvalueof = new Object ();
printvalueof.valueOf = function () {
trace ("valueOf called with " + arguments);
return this;
};
nothing = new Object ();
nothing.__proto__ = undefined;
values = [
undefined,
null,
true, false,
0, 1, 0.5, -1, -0.5, Infinity, -Infinity, NaN,
"", "0", "-0", "0.0", "1", "Hello World!", "true", "_level0",
this, new Object (), Function, printall, printtostring, printvalueof, nothing ];
var l = values.length;
var v = function () {
trace (this.nr + ": valueOf!");
return this.v;
};
var s = function () {
trace (this.nr + ": toString!");
return this.v;
};
for (i = 0; i < l; i++) {
var o = new Object ();
o.nr = i;
o.valueOf = v;
o.toString = s;
o.v = values[i];
values.push (o);
};
names = [];
for (i = 0; i < values.length; i++) {
names[i] = "(" + i + ") " + values[i] + " (" + typeof (values[i]) + ")";
};
|
Rename valueof and tostring to printvalueof and printtostring in values.as
|
Rename valueof and tostring to printvalueof and printtostring in values.as
To avoid non-determinism with having multiple variables using different case
|
ActionScript
|
lgpl-2.1
|
mltframework/swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec
|
a57cf57ca5dc801f8509c0643ae510af3d560237
|
kdp3Lib/src/com/kaltura/kdpfl/ApplicationFacade.as
|
kdp3Lib/src/com/kaltura/kdpfl/ApplicationFacade.as
|
package com.kaltura.kdpfl
{
import com.kaltura.kdpfl.controller.InitMacroCommand;
import com.kaltura.kdpfl.controller.LayoutReadyCommand;
import com.kaltura.kdpfl.controller.PlaybackCompleteCommand;
import com.kaltura.kdpfl.controller.SequenceItemPlayEndCommand;
import com.kaltura.kdpfl.controller.SequenceSkipNextCommand;
import com.kaltura.kdpfl.controller.StartupCommand;
import com.kaltura.kdpfl.controller.media.InitChangeMediaMacroCommand;
import com.kaltura.kdpfl.controller.media.LiveStreamCommand;
import com.kaltura.kdpfl.controller.media.MediaReadyCommand;
import com.kaltura.kdpfl.events.DynamicEvent;
import com.kaltura.kdpfl.model.ExternalInterfaceProxy;
import com.kaltura.kdpfl.model.type.DebugLevel;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import com.kaltura.puremvc.as3.core.KView;
import flash.display.DisplayObject;
import mx.utils.ObjectProxy;
import org.osmf.media.MediaPlayerState;
import org.puremvc.as3.interfaces.IFacade;
import org.puremvc.as3.interfaces.IMediator;
import org.puremvc.as3.interfaces.IProxy;
import org.puremvc.as3.patterns.facade.Facade;
public class ApplicationFacade extends Facade implements IFacade
{
/**
* The current version of the KDP.
*/
public var kdpVersion : String = "v3.6.17";
/**
* save any mediator name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _mediatorNameArray : Array = new Array();
/**
* save any proxy name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _proxyNameArray : Array = new Array();
/**
* save any notification that create a command name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _commandNameArray : Array = new Array();
/**
* The bindObject create dynamicly all attributes that need to be binded on it
*/
public var bindObject:ObjectProxy = new ObjectProxy();
/**
* a reference to KDP3 main application
*/
private var _app : DisplayObject;
/**
* the url of the kdp
*/
public var appFolder : String;
public var debugMode : Boolean = false;
/**
*
* will affect the traces that will be sent. See DebugLevel enum
*/
public var debugLevel:int;
private var externalInterface : ExternalInterfaceProxy;
/**
* return the one and only instance of the ApplicationFacade,
* if not exist it will be created.
* @return
*
*/
public static function getInstance() : ApplicationFacade
{
if (instance == null) instance = new ApplicationFacade();
return instance as ApplicationFacade;
}
/**
* All this simply does is fire a notification which is routed to
* "StartupCommand" via the "registerCommand" handlers
* @param app
*
*/
public function start(app:DisplayObject):void
{
CONFIG::isSDK46 {
kdpVersion += ".sdk46";
}
_app = app;
appFolder = app.root.loaderInfo.url;
appFolder = appFolder.substr(0, appFolder.lastIndexOf('/') + 1);
sendNotification(NotificationType.STARTUP, app);
externalInterface = retrieveProxy(ExternalInterfaceProxy.NAME) as ExternalInterfaceProxy;
}
/**
* Created to trace all notifications for debug
* @param notificationName
* @param body
* @param type
*
*/
override public function sendNotification(notificationName:String, body:Object = null, type:String = null):void {
if (debugMode) {
var s:String;
if ((notificationName == NotificationType.BYTES_DOWNLOADED_CHANGE && debugLevel == DebugLevel.HIGH) ||
(notificationName == NotificationType.PLAYER_UPDATE_PLAYHEAD && (debugLevel == DebugLevel.HIGH || debugLevel == DebugLevel.MEDIUM)) ||
(notificationName != NotificationType.PLAYER_UPDATE_PLAYHEAD && notificationName != NotificationType.BYTES_DOWNLOADED_CHANGE))
{
if (notificationName == NotificationType.PLAYER_STATE_CHANGE)
s = 'Sent ' + notificationName + ' ==> ' + body.toString();
else {
s = 'Sent ' + notificationName;
if (body) {
var found:Boolean = false;
for (var o:* in body) {
s += ", " + o + ":" + body[o];
found = true;
}
if (!found) {
s += ", " + body.toString();
}
}
}
}
if (s && s != "null") {
var curTime:Number = 0;
var kmediaPlayerMediator:KMediaPlayerMediator = retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator;
if (kmediaPlayerMediator &&
kmediaPlayerMediator.player &&
kmediaPlayerMediator.player.state!=MediaPlayerState.LOADING &&
kmediaPlayerMediator.player.state!=MediaPlayerState.UNINITIALIZED &&
kmediaPlayerMediator.player.state!=MediaPlayerState.PLAYBACK_ERROR)
{
curTime = kmediaPlayerMediator.getCurrentTime();
}
var date:Date = new Date();
KTrace.getInstance().log(date.toTimeString(), ":", s, ", playhead position:", curTime);
}
}
super.sendNotification(notificationName, body, type);
//For external Flash/Flex application application listening to the KDP events
_app.dispatchEvent(new DynamicEvent(notificationName, body));
//For external Javascript application listening to the KDP events
if (externalInterface)
externalInterface.notifyJs(notificationName, body);
}
/**
* controls the routing of notifications to our controllers,
* we all know them as commands
*
*/
override protected function initializeController():void
{
super.initializeController();
registerCommand(NotificationType.STARTUP, StartupCommand);
// we do both init start KDP life cycle, and start to load the entry simultaneously
registerCommand(NotificationType.INITIATE_APP, InitMacroCommand);
//There are several things that need to be done as soon as the layout of the kdp is ready.
registerCommand(NotificationType.LAYOUT_READY, LayoutReadyCommand );
//when one call change media we fire the load media command again
registerCommand(NotificationType.CHANGE_MEDIA, InitChangeMediaMacroCommand);
registerCommand (NotificationType.LIVE_ENTRY, LiveStreamCommand );
registerCommand (NotificationType.MEDIA_LOADED, MediaReadyCommand );
registerCommand (NotificationType.PLAYBACK_COMPLETE, PlaybackCompleteCommand);
registerCommand(NotificationType.SEQUENCE_ITEM_PLAY_END, SequenceItemPlayEndCommand);
registerCommand(NotificationType.SEQUENCE_SKIP_NEXT, SequenceSkipNextCommand);
}
override protected function initializeView():void
{
if ( view != null ) return;
view = KView.getInstance();
}
override protected function initializeFacade():void
{
initializeView();
initializeModel();
initializeController();
}
/**
* Help to remove all commands, mediator, proxies from the facade
*
*/
public function dispose() : void
{
var i:int =0;
for(i=0; i<_commandNameArray.length; i++)
this.removeCommand( _commandNameArray[i] );
for(i=0; i<_mediatorNameArray.length; i++)
this.removeMediator( _mediatorNameArray[i] );
for(i=0; i<_proxyNameArray.length; i++)
this.removeProxy( _proxyNameArray[i] );
_commandNameArray = new Array();
_mediatorNameArray = new Array();
_proxyNameArray = new Array();
}
/**
* after registartion add the notification name to a
* @param notificationName
* @param commandClassRef
*
*/
override public function registerCommand(notificationName:String, commandClassRef:Class):void
{
super.registerCommand(notificationName, commandClassRef);
//save the notification name so we can delete it later
_commandNameArray.push( notificationName );
}
override public function registerMediator(mediator:IMediator):void
{
super.registerMediator(mediator);
//save the mediator name so we can delete it later
_mediatorNameArray.push( mediator.getMediatorName() );
}
override public function registerProxy(proxy:IProxy):void
{
bindObject[proxy.getProxyName()] = proxy.getData();
super.registerProxy(proxy);
//save the proxy name so we can delete it later
_proxyNameArray.push( proxy.getProxyName() );
}
/**
* add notification observer for a given mediator
* @param notification the notification to listen for
* @param notificationHandler handler to be called
* @param mediator
*
*/
public function addNotificationInterest(notification:String, notificationHandler:Function, mediator:IMediator):void {
(view as KView).addNotificationInterest(notification, notificationHandler, mediator);
}
public function get app () : DisplayObject
{
return _app;
}
public function set app (disObj : DisplayObject) : void
{
_app = disObj;
}
}
}
|
package com.kaltura.kdpfl
{
import com.kaltura.kdpfl.controller.InitMacroCommand;
import com.kaltura.kdpfl.controller.LayoutReadyCommand;
import com.kaltura.kdpfl.controller.PlaybackCompleteCommand;
import com.kaltura.kdpfl.controller.SequenceItemPlayEndCommand;
import com.kaltura.kdpfl.controller.SequenceSkipNextCommand;
import com.kaltura.kdpfl.controller.StartupCommand;
import com.kaltura.kdpfl.controller.media.InitChangeMediaMacroCommand;
import com.kaltura.kdpfl.controller.media.LiveStreamCommand;
import com.kaltura.kdpfl.controller.media.MediaReadyCommand;
import com.kaltura.kdpfl.events.DynamicEvent;
import com.kaltura.kdpfl.model.ExternalInterfaceProxy;
import com.kaltura.kdpfl.model.type.DebugLevel;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import com.kaltura.puremvc.as3.core.KView;
import flash.display.DisplayObject;
import mx.utils.ObjectProxy;
import org.osmf.media.MediaPlayerState;
import org.puremvc.as3.interfaces.IFacade;
import org.puremvc.as3.interfaces.IMediator;
import org.puremvc.as3.interfaces.IProxy;
import org.puremvc.as3.patterns.facade.Facade;
public class ApplicationFacade extends Facade implements IFacade
{
/**
* The current version of the KDP.
*/
public var kdpVersion : String = "v3.6.18";
/**
* save any mediator name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _mediatorNameArray : Array = new Array();
/**
* save any proxy name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _proxyNameArray : Array = new Array();
/**
* save any notification that create a command name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _commandNameArray : Array = new Array();
/**
* The bindObject create dynamicly all attributes that need to be binded on it
*/
public var bindObject:ObjectProxy = new ObjectProxy();
/**
* a reference to KDP3 main application
*/
private var _app : DisplayObject;
/**
* the url of the kdp
*/
public var appFolder : String;
public var debugMode : Boolean = false;
/**
*
* will affect the traces that will be sent. See DebugLevel enum
*/
public var debugLevel:int;
private var externalInterface : ExternalInterfaceProxy;
/**
* return the one and only instance of the ApplicationFacade,
* if not exist it will be created.
* @return
*
*/
public static function getInstance() : ApplicationFacade
{
if (instance == null) instance = new ApplicationFacade();
return instance as ApplicationFacade;
}
/**
* All this simply does is fire a notification which is routed to
* "StartupCommand" via the "registerCommand" handlers
* @param app
*
*/
public function start(app:DisplayObject):void
{
CONFIG::isSDK46 {
kdpVersion += ".sdk46";
}
_app = app;
appFolder = app.root.loaderInfo.url;
appFolder = appFolder.substr(0, appFolder.lastIndexOf('/') + 1);
sendNotification(NotificationType.STARTUP, app);
externalInterface = retrieveProxy(ExternalInterfaceProxy.NAME) as ExternalInterfaceProxy;
}
/**
* Created to trace all notifications for debug
* @param notificationName
* @param body
* @param type
*
*/
override public function sendNotification(notificationName:String, body:Object = null, type:String = null):void {
if (debugMode) {
var s:String;
if ((notificationName == NotificationType.BYTES_DOWNLOADED_CHANGE && debugLevel == DebugLevel.HIGH) ||
(notificationName == NotificationType.PLAYER_UPDATE_PLAYHEAD && (debugLevel == DebugLevel.HIGH || debugLevel == DebugLevel.MEDIUM)) ||
(notificationName != NotificationType.PLAYER_UPDATE_PLAYHEAD && notificationName != NotificationType.BYTES_DOWNLOADED_CHANGE))
{
if (notificationName == NotificationType.PLAYER_STATE_CHANGE)
s = 'Sent ' + notificationName + ' ==> ' + body.toString();
else {
s = 'Sent ' + notificationName;
if (body) {
var found:Boolean = false;
for (var o:* in body) {
s += ", " + o + ":" + body[o];
found = true;
}
if (!found) {
s += ", " + body.toString();
}
}
}
}
if (s && s != "null") {
var curTime:Number = 0;
var kmediaPlayerMediator:KMediaPlayerMediator = retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator;
if (kmediaPlayerMediator &&
kmediaPlayerMediator.player &&
kmediaPlayerMediator.player.state!=MediaPlayerState.LOADING &&
kmediaPlayerMediator.player.state!=MediaPlayerState.UNINITIALIZED &&
kmediaPlayerMediator.player.state!=MediaPlayerState.PLAYBACK_ERROR)
{
curTime = kmediaPlayerMediator.getCurrentTime();
}
var date:Date = new Date();
KTrace.getInstance().log(date.toTimeString(), ":", s, ", playhead position:", curTime);
}
}
super.sendNotification(notificationName, body, type);
//For external Flash/Flex application application listening to the KDP events
_app.dispatchEvent(new DynamicEvent(notificationName, body));
//For external Javascript application listening to the KDP events
if (externalInterface)
externalInterface.notifyJs(notificationName, body);
}
/**
* controls the routing of notifications to our controllers,
* we all know them as commands
*
*/
override protected function initializeController():void
{
super.initializeController();
registerCommand(NotificationType.STARTUP, StartupCommand);
// we do both init start KDP life cycle, and start to load the entry simultaneously
registerCommand(NotificationType.INITIATE_APP, InitMacroCommand);
//There are several things that need to be done as soon as the layout of the kdp is ready.
registerCommand(NotificationType.LAYOUT_READY, LayoutReadyCommand );
//when one call change media we fire the load media command again
registerCommand(NotificationType.CHANGE_MEDIA, InitChangeMediaMacroCommand);
registerCommand (NotificationType.LIVE_ENTRY, LiveStreamCommand );
registerCommand (NotificationType.MEDIA_LOADED, MediaReadyCommand );
registerCommand (NotificationType.PLAYBACK_COMPLETE, PlaybackCompleteCommand);
registerCommand(NotificationType.SEQUENCE_ITEM_PLAY_END, SequenceItemPlayEndCommand);
registerCommand(NotificationType.SEQUENCE_SKIP_NEXT, SequenceSkipNextCommand);
}
override protected function initializeView():void
{
if ( view != null ) return;
view = KView.getInstance();
}
override protected function initializeFacade():void
{
initializeView();
initializeModel();
initializeController();
}
/**
* Help to remove all commands, mediator, proxies from the facade
*
*/
public function dispose() : void
{
var i:int =0;
for(i=0; i<_commandNameArray.length; i++)
this.removeCommand( _commandNameArray[i] );
for(i=0; i<_mediatorNameArray.length; i++)
this.removeMediator( _mediatorNameArray[i] );
for(i=0; i<_proxyNameArray.length; i++)
this.removeProxy( _proxyNameArray[i] );
_commandNameArray = new Array();
_mediatorNameArray = new Array();
_proxyNameArray = new Array();
}
/**
* after registartion add the notification name to a
* @param notificationName
* @param commandClassRef
*
*/
override public function registerCommand(notificationName:String, commandClassRef:Class):void
{
super.registerCommand(notificationName, commandClassRef);
//save the notification name so we can delete it later
_commandNameArray.push( notificationName );
}
override public function registerMediator(mediator:IMediator):void
{
super.registerMediator(mediator);
//save the mediator name so we can delete it later
_mediatorNameArray.push( mediator.getMediatorName() );
}
override public function registerProxy(proxy:IProxy):void
{
bindObject[proxy.getProxyName()] = proxy.getData();
super.registerProxy(proxy);
//save the proxy name so we can delete it later
_proxyNameArray.push( proxy.getProxyName() );
}
/**
* add notification observer for a given mediator
* @param notification the notification to listen for
* @param notificationHandler handler to be called
* @param mediator
*
*/
public function addNotificationInterest(notification:String, notificationHandler:Function, mediator:IMediator):void {
(view as KView).addNotificationInterest(notification, notificationHandler, mediator);
}
public function get app () : DisplayObject
{
return _app;
}
public function set app (disObj : DisplayObject) : void
{
_app = disObj;
}
}
}
|
update kdp version to v3.6.18
|
update kdp version to v3.6.18
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,kaltura/kdp
|
a3ae11ba88aec10c901f817e40744396950006b3
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/CSSTextField.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/CSSTextField.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import flash.text.TextField;
import flash.text.TextFormat;
import org.apache.flex.core.ValuesManager;
/**
* The CSSTextField class implements CSS text styles in a TextField.
* Not every CSS text style is currently supported.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class CSSTextField extends TextField
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function CSSTextField()
{
super();
}
/**
* @private
* The styleParent property is set if the CSSTextField
* is used in a SimpleButton-based instance because
* the parent property is null, defeating CSS lookup.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var styleParent:Object;
/**
* @private
*/
override public function set text(value:String):void
{
var sp:Object = parent;
if (!sp)
sp = styleParent;
var tf: TextFormat = new TextFormat();
tf.font = ValuesManager.valuesImpl.getValue(sp, "fontFamily") as String;
tf.size = ValuesManager.valuesImpl.getValue(sp, "fontSize");
tf.bold = ValuesManager.valuesImpl.getValue(sp, "fontWeight") == "bold";
tf.color = ValuesManager.valuesImpl.getValue(sp, "color");
var padding:Object = ValuesManager.valuesImpl.getValue(sp, "padding");
if (padding == null) padding = 0;
var paddingLeft:Object = ValuesManager.valuesImpl.getValue(sp,"padding-left");
if (paddingLeft == null) paddingLeft = padding;
var paddingRight:Object = ValuesManager.valuesImpl.getValue(sp,"padding-right");
if (paddingRight == null) paddingRight = padding;
tf.leftMargin = paddingLeft;
tf.rightMargin = paddingRight;
defaultTextFormat = tf;
super.text = value;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import flash.text.TextField;
import flash.text.TextFormat;
import org.apache.flex.core.ValuesManager;
/**
* The CSSTextField class implements CSS text styles in a TextField.
* Not every CSS text style is currently supported.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class CSSTextField extends TextField
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function CSSTextField()
{
super();
}
/**
* @private
* The styleParent property is set if the CSSTextField
* is used in a SimpleButton-based instance because
* the parent property is null, defeating CSS lookup.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var styleParent:Object;
/**
* @private
*/
override public function set text(value:String):void
{
var sp:Object = parent;
if (!sp)
sp = styleParent;
var tf: TextFormat = new TextFormat();
tf.font = ValuesManager.valuesImpl.getValue(sp, "fontFamily") as String;
tf.size = ValuesManager.valuesImpl.getValue(sp, "fontSize");
tf.bold = ValuesManager.valuesImpl.getValue(sp, "fontWeight") == "bold";
tf.color = ValuesManager.valuesImpl.getValue(sp, "color");
var padding:Object = ValuesManager.valuesImpl.getValue(sp, "padding");
if (padding == null) padding = 0;
var paddingLeft:Object = ValuesManager.valuesImpl.getValue(sp,"padding-left");
if (paddingLeft == null) paddingLeft = padding;
var paddingRight:Object = ValuesManager.valuesImpl.getValue(sp,"padding-right");
if (paddingRight == null) paddingRight = padding;
tf.leftMargin = paddingLeft;
tf.rightMargin = paddingRight;
var align:Object = ValuesManager.valuesImpl.getValue(sp, "text-align");
if (align == "center")
tf.align = "center";
else if (align == "right")
tf.align = "right";
defaultTextFormat = tf;
super.text = value;
}
}
}
|
handle text-align
|
handle text-align
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
be2d398d73fe1d6245324cbc23c1ed6d9dadcbf2
|
src/com/esri/builder/controllers/LocaleController.as
|
src/com/esri/builder/controllers/LocaleController.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers
{
import com.esri.builder.eventbus.AppEvent;
import com.esri.builder.model.LocaleModel;
import com.esri.builder.model.Model;
import com.esri.builder.supportClasses.LogUtil;
import mx.core.FlexGlobals;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.resources.ResourceManager;
import mx.styles.CSSStyleDeclaration;
import mx.styles.IStyleManager2;
import mx.styles.StyleManager;
public class LocaleController
{
private static const LOG:ILogger = LogUtil.createLogger(LocaleController);
public function LocaleController()
{
AppEvent.addListener(AppEvent.SETTINGS_SAVED, settingsChangeHandler, false, 500); //high priority to prevent app using outdated locale settings
}
private function settingsChangeHandler(event:AppEvent):void
{
updateApplicationLocale();
}
private function updateApplicationLocale():void
{
var selectedLocale:String = Model.instance.locale;
var localeChain:Array = ResourceManager.getInstance().localeChain;
var selectedLocaleIndex:int = localeChain.indexOf(selectedLocale);
localeChain.splice(selectedLocaleIndex, 1);
localeChain.unshift(selectedLocale);
if (Log.isDebug())
{
LOG.debug("Updating application locale: {0}", selectedLocale);
}
ResourceManager.getInstance().update();
applyLocaleLayoutDirection(selectedLocale);
setPreferredLocaleFonts(selectedLocale);
setEmphasisText(selectedLocale);
}
private function applyLocaleLayoutDirection(selectedLocale:String):void
{
var currentLayoutDirection:String = FlexGlobals.topLevelApplication.getStyle('layoutDirection');
var localeLayoutDirection:String = LocaleModel.getInstance().getLocaleLayoutDirection(selectedLocale);
if (localeLayoutDirection != currentLayoutDirection)
{
FlexGlobals.topLevelApplication.setStyle('direction', localeLayoutDirection);
FlexGlobals.topLevelApplication.setStyle('layoutDirection', localeLayoutDirection);
}
var currentLocale:String = FlexGlobals.topLevelApplication.getStyle('locale');
if (selectedLocale != currentLocale)
{
FlexGlobals.topLevelApplication.setStyle('locale', selectedLocale);
}
}
private function setPreferredLocaleFonts(selectedLocale:String):void
{
if (selectedLocale == 'ar')
{
FlexGlobals.topLevelApplication.setStyle('fontFamily', LocaleModel.ARABIC_FONT_FAMILY);
}
else if (selectedLocale == 'ja_JP')
{
FlexGlobals.topLevelApplication.setStyle('fontFamily', LocaleModel.JAPANESE_FONT_FAMILY);
}
else if (selectedLocale == 'ko_KR')
{
FlexGlobals.topLevelApplication.setStyle('fontFamily', LocaleModel.KOREAN_FONT_FAMILY);
}
else if (selectedLocale == 'zh_CN')
{
FlexGlobals.topLevelApplication.setStyle('fontFamily', LocaleModel.CHINESE_FONT_FAMILY);
}
else
{
FlexGlobals.topLevelApplication.setStyle('fontFamily', undefined);
}
}
private function setEmphasisText(locale:String):void
{
var topLevelStyleManager:IStyleManager2 = StyleManager.getStyleManager(null);
var emphasisStyle:CSSStyleDeclaration = topLevelStyleManager.getStyleDeclaration(".emphasisText");
var isItalicInappropriateLocale:Boolean =
locale == 'ja_JP' || locale == 'ko_KR' || locale == 'zh_CN'
|| locale == 'ar' || locale == 'he_IL';
var emphasisFontStyle:String = isItalicInappropriateLocale ? "normal" : "italic";
emphasisStyle.setStyle("fontStyle", emphasisFontStyle);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers
{
import com.esri.builder.eventbus.AppEvent;
import com.esri.builder.model.LocaleModel;
import com.esri.builder.model.Model;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.supportClasses.LogUtil;
import mx.core.FlexGlobals;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.resources.ResourceManager;
import mx.styles.CSSStyleDeclaration;
import mx.styles.IStyleManager2;
import mx.styles.StyleManager;
public class LocaleController
{
private static const LOG:ILogger = LogUtil.createLogger(LocaleController);
public function LocaleController()
{
AppEvent.addListener(AppEvent.SETTINGS_SAVED, settingsChangeHandler, false, 500); //high priority to prevent app using outdated locale settings
}
private function settingsChangeHandler(event:AppEvent):void
{
updateApplicationLocale();
}
private function updateApplicationLocale():void
{
var selectedLocale:String = Model.instance.locale;
var localeChain:Array = ResourceManager.getInstance().localeChain;
var selectedLocaleIndex:int = localeChain.indexOf(selectedLocale);
localeChain.splice(selectedLocaleIndex, 1);
localeChain.unshift(selectedLocale);
if (Log.isDebug())
{
LOG.debug("Updating application locale: {0}", selectedLocale);
}
ResourceManager.getInstance().update();
applyLocaleLayoutDirection(selectedLocale);
setPreferredLocaleFonts(selectedLocale);
setEmphasisText(selectedLocale);
}
private function applyLocaleLayoutDirection(selectedLocale:String):void
{
var currentLayoutDirection:String = FlexGlobals.topLevelApplication.getStyle('layoutDirection');
var localeLayoutDirection:String = LocaleModel.getInstance().getLocaleLayoutDirection(selectedLocale);
if (localeLayoutDirection != currentLayoutDirection)
{
FlexGlobals.topLevelApplication.setStyle('direction', localeLayoutDirection);
FlexGlobals.topLevelApplication.setStyle('layoutDirection', localeLayoutDirection);
}
var currentLocale:String = FlexGlobals.topLevelApplication.getStyle('locale');
if (selectedLocale != currentLocale)
{
FlexGlobals.topLevelApplication.setStyle('locale', selectedLocale);
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.sort();
}
}
private function setPreferredLocaleFonts(selectedLocale:String):void
{
if (selectedLocale == 'ar')
{
FlexGlobals.topLevelApplication.setStyle('fontFamily', LocaleModel.ARABIC_FONT_FAMILY);
}
else if (selectedLocale == 'ja_JP')
{
FlexGlobals.topLevelApplication.setStyle('fontFamily', LocaleModel.JAPANESE_FONT_FAMILY);
}
else if (selectedLocale == 'ko_KR')
{
FlexGlobals.topLevelApplication.setStyle('fontFamily', LocaleModel.KOREAN_FONT_FAMILY);
}
else if (selectedLocale == 'zh_CN')
{
FlexGlobals.topLevelApplication.setStyle('fontFamily', LocaleModel.CHINESE_FONT_FAMILY);
}
else
{
FlexGlobals.topLevelApplication.setStyle('fontFamily', undefined);
}
}
private function setEmphasisText(locale:String):void
{
var topLevelStyleManager:IStyleManager2 = StyleManager.getStyleManager(null);
var emphasisStyle:CSSStyleDeclaration = topLevelStyleManager.getStyleDeclaration(".emphasisText");
var isItalicInappropriateLocale:Boolean =
locale == 'ja_JP' || locale == 'ko_KR' || locale == 'zh_CN'
|| locale == 'ar' || locale == 'he_IL';
var emphasisFontStyle:String = isItalicInappropriateLocale ? "normal" : "italic";
emphasisStyle.setStyle("fontStyle", emphasisFontStyle);
}
}
}
|
Sort widget modules on locale change.
|
Sort widget modules on locale change.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
a998df04a91cca823d6377d1b7f1eb7e3422a05b
|
as3/com/netease/protobuf/WriteUtils.as
|
as3/com/netease/protobuf/WriteUtils.as
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved.
//
// [email protected]
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.utils.*
public final class WriteUtils {
public static function writeTag(output:IDataOutput,
wireType:uint, number:uint):void {
const varint:VarintWriter = new VarintWriter;
varint.write(wireType, 3);
varint.write(number, 32);
varint.end()
output.writeBytes(varint)
}
public static function write_TYPE_DOUBLE(output:IDataOutput, value:Number):void {
output.writeDouble(value)
}
public static function write_TYPE_FLOAT(output:IDataOutput, value:Number):void {
output.writeFloat(value)
}
public static function write_TYPE_INT64(output:IDataOutput, value:Int64):void {
const varint:VarintWriter = new VarintWriter;
varint.write(value.low, 32);
varint.write(value.high, 32);
varint.end()
output.writeBytes(varint)
}
public static function write_TYPE_UINT64(output:IDataOutput, value:UInt64):void {
const varint:VarintWriter = new VarintWriter;
varint.write(value.low, 32);
varint.write(value.high, 32);
varint.end()
output.writeBytes(varint)
}
public static function write_TYPE_INT32(output:IDataOutput, value:int):void {
write_TYPE_UINT32(output, value)
}
public static function write_TYPE_FIXED64(output:IDataOutput, value:Int64):void {
output.endian = Endian.LITTLE_ENDIAN
output.writeUnsignedInt(value.low)
output.writeInt(value.high)
}
public static function write_TYPE_FIXED32(output:IDataOutput, value:int):void {
output.endian = Endian.LITTLE_ENDIAN
output.writeInt(value)
}
public static function write_TYPE_BOOL(output:IDataOutput, value:Boolean):void {
output.writeByte(value ? 1 : 0)
}
public static function write_TYPE_STRING(output:IDataOutput, value:String):void {
var plb:PostposeLengthBuffer = output as PostposeLengthBuffer
if (plb == null) {
plb = new PostposeLengthBuffer
}
const i:uint = plb.beginBlock()
plb.writeUTF(value)
plb.endBlock(i)
if (plb != output) {
plb.toNormal(output)
}
}
public static function write_TYPE_BYTES(output:IDataOutput, value:ByteArray):void {
write_TYPE_UINT32(output, value.length)
output.writeBytes(value)
}
public static function write_TYPE_UINT32(output:IDataOutput, value:uint):void {
const varint:VarintWriter = new VarintWriter;
varint.write(value, 32);
varint.end()
output.writeBytes(varint)
}
public static function write_TYPE_ENUM(output:IDataOutput, value:int):void {
write_TYPE_INT32(output, value)
}
public static function write_TYPE_SFIXED32(output:IDataOutput, value:int):void {
write_TYPE_FIXED32(output, (value >>> 31) ^ (value << 1))
}
public static function write_TYPE_SFIXED64(output:IDataOutput, value:Int64):void {
output.endian = Endian.LITTLE_ENDIAN
output.writeUnsignedInt((value.high >>> 31) ^ (value.low << 1))
output.writeUnsignedInt((value.low >>> 31) ^ (value.high << 1))
}
public static function write_TYPE_SINT32(output:IDataOutput, value:int):void {
write_TYPE_UINT32(output, (value >>> 31) ^ (value << 1))
}
public static function write_TYPE_SINT64(output:IDataOutput, value:Int64):void {
const varint:VarintWriter = new VarintWriter;
varint.write((value.high >>> 31) ^ (value.low << 1), 32);
varint.write((value.low >>> 31) ^ (value.high << 1), 32);
varint.end()
output.writeBytes(varint)
}
public static function write_TYPE_MESSAGE(output:IDataOutput, value:IExternalizable):void {
var plb:PostposeLengthBuffer = output as PostposeLengthBuffer
if (plb == null) {
plb = new PostposeLengthBuffer
}
const i:uint = plb.beginBlock()
value.writeExternal(plb)
plb.endBlock(i)
if (plb != output) {
plb.toNormal(output)
}
}
public static function writePackedRepeated(output:IDataOutput,
writeFunction:Function, value:Array):void {
var plb:PostposeLengthBuffer = output as PostposeLengthBuffer
if (plb == null) {
plb = new PostposeLengthBuffer
}
const i:uint = plb.beginBlock()
for each (var element:* in value) {
writeFunction(plb, element)
}
plb.endBlock(i)
if (plb != output) {
plb.toNormal(output)
}
}
}
}
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved.
//
// [email protected]
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.utils.*
public final class WriteUtils {
public static function writeTag(output:IDataOutput,
wireType:uint, number:uint):void {
const varint:VarintWriter = new VarintWriter;
varint.write(wireType, 3);
varint.write(number, 32);
varint.end()
output.writeBytes(varint)
}
public static function write_TYPE_DOUBLE(output:IDataOutput, value:Number):void {
output.writeDouble(value)
}
public static function write_TYPE_FLOAT(output:IDataOutput, value:Number):void {
output.writeFloat(value)
}
public static function write_TYPE_INT64(output:IDataOutput, value:Int64):void {
const varint:VarintWriter = new VarintWriter;
varint.write(value.low, 32);
varint.write(value.high, 32);
varint.end()
output.writeBytes(varint)
}
public static function write_TYPE_UINT64(output:IDataOutput, value:UInt64):void {
const varint:VarintWriter = new VarintWriter;
varint.write(value.low, 32);
varint.write(value.high, 32);
varint.end()
output.writeBytes(varint)
}
public static function write_TYPE_INT32(output:IDataOutput, value:int):void {
write_TYPE_UINT32(output, value)
}
public static function write_TYPE_FIXED64(output:IDataOutput, value:Int64):void {
output.endian = Endian.LITTLE_ENDIAN
output.writeUnsignedInt(value.low)
output.writeInt(value.high)
}
public static function write_TYPE_FIXED32(output:IDataOutput, value:int):void {
output.endian = Endian.LITTLE_ENDIAN
output.writeInt(value)
}
public static function write_TYPE_BOOL(output:IDataOutput, value:Boolean):void {
output.writeByte(value ? 1 : 0)
}
public static function write_TYPE_STRING(output:IDataOutput, value:String):void {
var plb:PostposeLengthBuffer = output as PostposeLengthBuffer
if (plb == null) {
plb = new PostposeLengthBuffer
}
const i:uint = plb.beginBlock()
plb.writeUTFBytes(value)
plb.endBlock(i)
if (plb != output) {
plb.toNormal(output)
}
}
public static function write_TYPE_BYTES(output:IDataOutput, value:ByteArray):void {
write_TYPE_UINT32(output, value.length)
output.writeBytes(value)
}
public static function write_TYPE_UINT32(output:IDataOutput, value:uint):void {
const varint:VarintWriter = new VarintWriter;
varint.write(value, 32);
varint.end()
output.writeBytes(varint)
}
public static function write_TYPE_ENUM(output:IDataOutput, value:int):void {
write_TYPE_INT32(output, value)
}
public static function write_TYPE_SFIXED32(output:IDataOutput, value:int):void {
write_TYPE_FIXED32(output, (value >>> 31) ^ (value << 1))
}
public static function write_TYPE_SFIXED64(output:IDataOutput, value:Int64):void {
output.endian = Endian.LITTLE_ENDIAN
output.writeUnsignedInt((value.high >>> 31) ^ (value.low << 1))
output.writeUnsignedInt((value.low >>> 31) ^ (value.high << 1))
}
public static function write_TYPE_SINT32(output:IDataOutput, value:int):void {
write_TYPE_UINT32(output, (value >>> 31) ^ (value << 1))
}
public static function write_TYPE_SINT64(output:IDataOutput, value:Int64):void {
const varint:VarintWriter = new VarintWriter;
varint.write((value.high >>> 31) ^ (value.low << 1), 32);
varint.write((value.low >>> 31) ^ (value.high << 1), 32);
varint.end()
output.writeBytes(varint)
}
public static function write_TYPE_MESSAGE(output:IDataOutput, value:IExternalizable):void {
var plb:PostposeLengthBuffer = output as PostposeLengthBuffer
if (plb == null) {
plb = new PostposeLengthBuffer
}
const i:uint = plb.beginBlock()
value.writeExternal(plb)
plb.endBlock(i)
if (plb != output) {
plb.toNormal(output)
}
}
public static function writePackedRepeated(output:IDataOutput,
writeFunction:Function, value:Array):void {
var plb:PostposeLengthBuffer = output as PostposeLengthBuffer
if (plb == null) {
plb = new PostposeLengthBuffer
}
const i:uint = plb.beginBlock()
for each (var element:* in value) {
writeFunction(plb, element)
}
plb.endBlock(i)
if (plb != output) {
plb.toNormal(output)
}
}
}
}
|
修复发送字符串时多发了前缀的 bug
|
修复发送字符串时多发了前缀的 bug
|
ActionScript
|
bsd-2-clause
|
tconkling/protoc-gen-as3
|
586ebae57e6e1e63bf677dc531de78eaa85b34b2
|
src/aerys/minko/render/resource/Context3DResource.as
|
src/aerys/minko/render/resource/Context3DResource.as
|
package aerys.minko.render.resource
{
import flash.display.BitmapData;
import flash.display3D.Context3D;
import flash.display3D.IndexBuffer3D;
import flash.display3D.Program3D;
import flash.display3D.VertexBuffer3D;
import flash.display3D.textures.CubeTexture;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Rectangle;
public final class Context3DResource
{
private var _context : Context3D = null;
private var _enableErrorChecking : Boolean = false;
private var _rttTarget : TextureBase = null;
private var _rttDepthAndStencil : Boolean = false;
private var _rttAntiAliasing : int = 0;
private var _rttSurfaceSelector : int = 0;
private var _rectangle : Rectangle = null;
private var _depthMask : Boolean = false;
private var _passCompareMode : String = null;
private var _program : Program3D = null;
private var _blendingSource : String = null;
private var _blendingDestination : String = null;
private var _triangleCulling : String = null;
private var _vertexBuffers : Vector.<VertexBuffer3D> = new Vector.<VertexBuffer3D>(8, true);
private var _vertexBuffersOffsets : Vector.<int> = new Vector.<int>(8, true);
private var _vertexBuffersFormats : Vector.<String> = new Vector.<String>(8, true);
private var _textures : Vector.<TextureBase> = new Vector.<TextureBase>(8, true);
private var _colorMaskRed : Boolean = false;
private var _colorMaskGreen : Boolean = false;
private var _colorMaskBlue : Boolean = false;
private var _colorMaskAlpha : Boolean = false;
public function get enabledErrorChecking() : Boolean
{
return _enableErrorChecking;
}
public function set enableErrorChecking(value : Boolean) : void
{
if (value != _enableErrorChecking)
{
_enableErrorChecking = value;
_context.enableErrorChecking = value;
}
}
public function Context3DResource(context : Context3D)
{
_context = context;
}
public function clear(red : Number = 0.0,
green : Number = 0.0,
blue : Number = 0.0,
alpha : Number = 1.0,
depth : Number = 1.0,
stencil : uint = 0,
mask : uint = 0xffffffff) : void
{
_context.clear(red, green, blue, alpha, depth, stencil, mask);
}
public function configureBackBuffer(width : int,
height : int,
antiAlias : int,
enabledDepthAndStencil : Boolean) : Context3DResource
{
_context.configureBackBuffer(width, height, antiAlias, enabledDepthAndStencil);
return this;
}
public function createCubeTexture(size : int,
format : String,
optimizeForRenderToTexture : Boolean) : CubeTexture
{
return _context.createCubeTexture(size, format, optimizeForRenderToTexture);
}
public function createIndexBuffer(numIndices : int) : IndexBuffer3D
{
return _context.createIndexBuffer(numIndices);
}
public function createProgram() : Program3D
{
return _context.createProgram();
}
public function createTexture(width : int,
height : int,
format : String,
optimizeForRenderToTexture : Boolean) : Texture
{
return _context.createTexture(width, height, format, optimizeForRenderToTexture);
}
public function createVertexBuffer(numVertices : int, data32PerVertex : int) : VertexBuffer3D
{
return _context.createVertexBuffer(numVertices, data32PerVertex);
}
public function dispose() : void
{
_context.dispose();
}
public function drawToBitmapData(destination : BitmapData) : Context3DResource
{
_context.drawToBitmapData(destination);
return this;
}
public function drawTriangles(indexBuffer : IndexBuffer3D,
firstIndex : int = 0,
numTriangles : int = -1) : Context3DResource
{
_context.drawTriangles(indexBuffer, firstIndex, numTriangles);
return this;
}
public function present() : Context3DResource
{
_context.present();
return this;
}
public function setBlendFactors(source : String, destination : String) : Context3DResource
{
if (source != _blendingSource || destination != _blendingDestination)
{
_blendingSource = source;
_blendingDestination = destination;
_context.setBlendFactors(_blendingSource, _blendingDestination);
}
return this;
}
public function setColorMask(red : Boolean,
green : Boolean,
blue : Boolean,
alpha : Boolean) : Context3DResource
{
if (red != _colorMaskRed || green != _colorMaskGreen
|| blue != _colorMaskBlue || alpha != _colorMaskAlpha)
{
_colorMaskRed = red;
_colorMaskGreen = green;
_colorMaskBlue = blue;
_colorMaskAlpha = alpha;
_context.setColorMask(
_colorMaskRed,
_colorMaskGreen,
_colorMaskBlue,
_colorMaskAlpha
);
}
return this;
}
public function setCulling(triangleCulling : String) : Context3DResource
{
if (triangleCulling != _triangleCulling)
{
_triangleCulling = triangleCulling;
_context.setCulling(triangleCulling);
}
return this;
}
public function setDepthTest(depthMask : Boolean, passCompareMode : String) : Context3DResource
{
if (depthMask != _depthMask || passCompareMode != _passCompareMode)
{
_depthMask = depthMask;
_passCompareMode = passCompareMode;
_context.setDepthTest(_depthMask, _passCompareMode);
}
return this;
}
public function setProgram(program : Program3D) : Context3DResource
{
if (_program != program)
{
_program = program;
_context.setProgram(program);
}
return this;
}
public function setProgramConstantsFromVector(programeType : String,
offset : uint,
values : Vector.<Number>,
numRegisters : int = -1) : Context3DResource
{
_context.setProgramConstantsFromVector(programeType, offset, values, numRegisters);
return this;
}
public function setRenderToBackBuffer() : Context3DResource
{
if (_rttTarget != null)
{
_rttTarget = null;
_context.setRenderToBackBuffer();
}
return this;
}
public function setRenderToTexture(texture : TextureBase,
enableDepthAndStencil : Boolean = false,
antiAlias : int = 0,
surfaceSelector : int = 0) : Context3DResource
{
if (texture != _rttTarget || enableDepthAndStencil != _rttDepthAndStencil
|| antiAlias != _rttAntiAliasing || surfaceSelector != _rttSurfaceSelector)
{
_rttTarget = texture;
_rttDepthAndStencil = enableDepthAndStencil;
_rttAntiAliasing = antiAlias;
_rttSurfaceSelector = surfaceSelector;
_context.setRenderToTexture(
texture,
enableDepthAndStencil,
antiAlias,
surfaceSelector
);
}
return this;
}
public function setScissorRectangle(rectangle : Rectangle) : Context3DResource
{
if (_rectangle != rectangle)
{
_rectangle = rectangle;
_context.setScissorRectangle(_rectangle);
}
return this;
}
public function setTextureAt(sampler : uint,
texture : TextureBase) : Context3DResource
{
if (_textures[sampler] != texture)
{
_textures[sampler] = texture;
_context.setTextureAt(sampler, texture);
}
return this;
}
public function setVertexBufferAt(index : int,
vertexBuffer : VertexBuffer3D,
bufferOffset : int = 0,
format : String = 'float4') : Context3DResource
{
if (_vertexBuffers[index] != vertexBuffer
|| _vertexBuffersOffsets[index] != bufferOffset
|| _vertexBuffersFormats[index] != format)
{
_vertexBuffers[index] = vertexBuffer;
_vertexBuffersOffsets[index] = bufferOffset;
_vertexBuffersFormats[index] = format;
_context.setVertexBufferAt(
index,
vertexBuffer,
bufferOffset,
format
);
}
return this;
}
public function setStencilReferenceValue(refNum : uint = 0,
readMask : uint = 255,
writeMask : uint = 255) : Context3DResource
{
_context.setStencilReferenceValue(refNum, readMask, writeMask);
return this;
}
public function setStencilActions(triangleFace : String = 'frontAndBack',
compareMode : String = 'always',
actionOnBothPass : String = 'keep',
actionOnDepthFail : String = 'keep',
actionOnDepthPassStencilFail : String = 'keep') : Context3DResource
{
_context.setStencilActions(
triangleFace,
compareMode,
actionOnBothPass,
actionOnDepthFail,
actionOnDepthPassStencilFail
);
return this;
}
}
}
|
package aerys.minko.render.resource
{
import flash.display.BitmapData;
import flash.display3D.Context3D;
import flash.display3D.IndexBuffer3D;
import flash.display3D.Program3D;
import flash.display3D.VertexBuffer3D;
import flash.display3D.textures.CubeTexture;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Rectangle;
public final class Context3DResource
{
private var _context : Context3D;
private var _enableErrorChecking : Boolean;
private var _rttTarget : TextureBase;
private var _rttDepthAndStencil : Boolean;
private var _rttAntiAliasing : int;
private var _rttSurfaceSelector : int;
private var _rectangle : Rectangle;
private var _depthMask : Boolean;
private var _passCompareMode : String;
private var _program : Program3D;
private var _blendingSource : String;
private var _blendingDestination : String;
private var _triangleCulling : String;
private var _vertexBuffers : Vector.<VertexBuffer3D>;
private var _vertexBuffersOffsets : Vector.<int>;
private var _vertexBuffersFormats : Vector.<String>;
private var _textures : Vector.<TextureBase>;
private var _colorMaskRed : Boolean;
private var _colorMaskGreen : Boolean;
private var _colorMaskBlue : Boolean;
private var _colorMaskAlpha : Boolean;
private var _stencilRefNum : uint;
private var _stencilReadMask : uint;
private var _stencilWriteMask : uint;
private var _stencilTriangleFace : String;
private var _stencilCompareMode : String;
private var _stencilActionOnBothPass : String;
private var _stencilActionOnDepthFail : String;
private var _stencilActionOnDepthPassStencilFail : String;
public function get enabledErrorChecking() : Boolean
{
return _enableErrorChecking;
}
public function set enableErrorChecking(value : Boolean) : void
{
if (value != _enableErrorChecking)
{
_enableErrorChecking = value;
_context.enableErrorChecking = value;
}
}
public function Context3DResource(context : Context3D)
{
_context = context;
initialize();
}
private function initialize() : void
{
_vertexBuffers = new Vector.<VertexBuffer3D>(8, true);
_vertexBuffersOffsets = new Vector.<int>(8, true);
_vertexBuffersFormats = new Vector.<String>(8, true);
_textures = new Vector.<TextureBase>(8, true);
}
public function clear(red : Number = 0.0,
green : Number = 0.0,
blue : Number = 0.0,
alpha : Number = 1.0,
depth : Number = 1.0,
stencil : uint = 0,
mask : uint = 0xffffffff) : void
{
_context.clear(red, green, blue, alpha, depth, stencil, mask);
}
public function configureBackBuffer(width : int,
height : int,
antiAlias : int,
enabledDepthAndStencil : Boolean) : Context3DResource
{
_context.configureBackBuffer(width, height, antiAlias, enabledDepthAndStencil);
return this;
}
public function createCubeTexture(size : int,
format : String,
optimizeForRenderToTexture : Boolean) : CubeTexture
{
return _context.createCubeTexture(size, format, optimizeForRenderToTexture);
}
public function createIndexBuffer(numIndices : int) : IndexBuffer3D
{
return _context.createIndexBuffer(numIndices);
}
public function createProgram() : Program3D
{
return _context.createProgram();
}
public function createTexture(width : int,
height : int,
format : String,
optimizeForRenderToTexture : Boolean) : Texture
{
return _context.createTexture(width, height, format, optimizeForRenderToTexture);
}
public function createVertexBuffer(numVertices : int, data32PerVertex : int) : VertexBuffer3D
{
return _context.createVertexBuffer(numVertices, data32PerVertex);
}
public function dispose() : void
{
_context.dispose();
}
public function drawToBitmapData(destination : BitmapData) : Context3DResource
{
_context.drawToBitmapData(destination);
return this;
}
public function drawTriangles(indexBuffer : IndexBuffer3D,
firstIndex : int = 0,
numTriangles : int = -1) : Context3DResource
{
_context.drawTriangles(indexBuffer, firstIndex, numTriangles);
return this;
}
public function present() : Context3DResource
{
_context.present();
return this;
}
public function setBlendFactors(source : String, destination : String) : Context3DResource
{
if (source != _blendingSource || destination != _blendingDestination)
{
_blendingSource = source;
_blendingDestination = destination;
_context.setBlendFactors(_blendingSource, _blendingDestination);
}
return this;
}
public function setColorMask(red : Boolean,
green : Boolean,
blue : Boolean,
alpha : Boolean) : Context3DResource
{
if (red != _colorMaskRed || green != _colorMaskGreen
|| blue != _colorMaskBlue || alpha != _colorMaskAlpha)
{
_colorMaskRed = red;
_colorMaskGreen = green;
_colorMaskBlue = blue;
_colorMaskAlpha = alpha;
_context.setColorMask(
_colorMaskRed,
_colorMaskGreen,
_colorMaskBlue,
_colorMaskAlpha
);
}
return this;
}
public function setCulling(triangleCulling : String) : Context3DResource
{
if (triangleCulling != _triangleCulling)
{
_triangleCulling = triangleCulling;
_context.setCulling(triangleCulling);
}
return this;
}
public function setDepthTest(depthMask : Boolean, passCompareMode : String) : Context3DResource
{
if (depthMask != _depthMask || passCompareMode != _passCompareMode)
{
_depthMask = depthMask;
_passCompareMode = passCompareMode;
_context.setDepthTest(_depthMask, _passCompareMode);
}
return this;
}
public function setProgram(program : Program3D) : Context3DResource
{
if (_program != program)
{
_program = program;
_context.setProgram(program);
}
return this;
}
public function setProgramConstantsFromVector(programeType : String,
offset : uint,
values : Vector.<Number>,
numRegisters : int = -1) : Context3DResource
{
_context.setProgramConstantsFromVector(programeType, offset, values, numRegisters);
return this;
}
public function setRenderToBackBuffer() : Context3DResource
{
if (_rttTarget != null)
{
_rttTarget = null;
_context.setRenderToBackBuffer();
}
return this;
}
public function setRenderToTexture(texture : TextureBase,
enableDepthAndStencil : Boolean = false,
antiAlias : int = 0,
surfaceSelector : int = 0) : Context3DResource
{
if (texture != _rttTarget || enableDepthAndStencil != _rttDepthAndStencil
|| antiAlias != _rttAntiAliasing || surfaceSelector != _rttSurfaceSelector)
{
_rttTarget = texture;
_rttDepthAndStencil = enableDepthAndStencil;
_rttAntiAliasing = antiAlias;
_rttSurfaceSelector = surfaceSelector;
_context.setRenderToTexture(
texture,
enableDepthAndStencil,
antiAlias,
surfaceSelector
);
}
return this;
}
public function setScissorRectangle(rectangle : Rectangle) : Context3DResource
{
if (_rectangle != rectangle)
{
_rectangle = rectangle;
_context.setScissorRectangle(_rectangle);
}
return this;
}
public function setTextureAt(sampler : uint,
texture : TextureBase) : Context3DResource
{
if (_textures[sampler] != texture)
{
_textures[sampler] = texture;
_context.setTextureAt(sampler, texture);
}
return this;
}
public function setVertexBufferAt(index : int,
vertexBuffer : VertexBuffer3D,
bufferOffset : int = 0,
format : String = 'float4') : Context3DResource
{
if (_vertexBuffers[index] != vertexBuffer
|| _vertexBuffersOffsets[index] != bufferOffset
|| _vertexBuffersFormats[index] != format)
{
_vertexBuffers[index] = vertexBuffer;
_vertexBuffersOffsets[index] = bufferOffset;
_vertexBuffersFormats[index] = format;
_context.setVertexBufferAt(
index,
vertexBuffer,
bufferOffset,
format
);
}
return this;
}
public function setStencilReferenceValue(refNum : uint = 0,
readMask : uint = 255,
writeMask : uint = 255) : Context3DResource
{
if (refNum != _stencilRefNum
|| readMask != _stencilReadMask
|| writeMask != _stencilWriteMask
)
{
_context.setStencilReferenceValue(refNum, readMask, writeMask);
_stencilRefNum = refNum;
_stencilReadMask = readMask;
_stencilWriteMask = writeMask;
}
return this;
}
public function setStencilActions(triangleFace : String = 'frontAndBack',
compareMode : String = 'always',
actionOnBothPass : String = 'keep',
actionOnDepthFail : String = 'keep',
actionOnDepthPassStencilFail : String = 'keep') : Context3DResource
{
if (triangleFace != _stencilTriangleFace
|| compareMode != _stencilCompareMode
|| actionOnBothPass != _stencilActionOnBothPass
|| actionOnDepthFail != _stencilActionOnDepthFail
|| actionOnDepthPassStencilFail != _stencilActionOnDepthPassStencilFail
)
{
_context.setStencilActions(
triangleFace,
compareMode,
actionOnBothPass,
actionOnDepthFail,
actionOnDepthPassStencilFail
);
_stencilTriangleFace = triangleFace;
_stencilCompareMode = compareMode;
_stencilActionOnBothPass = actionOnBothPass;
_stencilActionOnDepthFail = actionOnDepthFail;
_stencilActionOnDepthPassStencilFail = actionOnDepthPassStencilFail;
}
return this;
}
}
}
|
handle stencil related GPU render states properly
|
handle stencil related GPU render states properly
|
ActionScript
|
mit
|
aerys/minko-as3
|
bc2a09042d3cb8fc016144675ae518e91e34f7f8
|
src/aerys/minko/type/xpath/XPathEvaluator.as
|
src/aerys/minko/type/xpath/XPathEvaluator.as
|
package aerys.minko.type.xpath
{
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.binding.DataBindings;
import flash.utils.getQualifiedClassName;
public final class XPathEvaluator
{
private var _path : String;
private var _selection : Vector.<ISceneNode> = null;
private var _modifier : String = null;
private var _lexer : XPathLexer = null;
public function get selection() : Vector.<ISceneNode>
{
return _selection;
}
public function XPathEvaluator(path : String,
selection : Vector.<ISceneNode>,
modifier : String = null)
{
_modifier = modifier;
initialize(path, selection);
}
private function initialize(path : String, selection : Vector.<ISceneNode>) : void
{
_path = path;
_lexer = new XPathLexer(_path);
// update root
var token : String = _lexer.getToken();
_selection = selection.slice();
if (token == "/")
{
selectRoots();
_lexer.nextToken(token);
}
// parse
while ((token = _lexer.getToken()) != null)
{
switch (token)
{
case '//' :
_lexer.nextToken(token);
selectDescendants();
break ;
case '/' :
_lexer.nextToken(token);
selectChildren();
break ;
default :
_lexer.nextToken(token);
parseNodeType(token);
break ;
}
}
}
private function selectChildren(typeName : String = null) : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
if (typeName != null)
typeName = typeName.toLowerCase();
_selection.length = 0;
for each (var node : ISceneNode in selection)
{
if (node is Group)
{
var group : Group = node as Group;
var numChildren : uint = group.numChildren;
for (var i : uint = 0; i < numChildren; ++i)
{
var child : ISceneNode = group.getChildAt(i);
var className : String = getQualifiedClassName(child)
var childType : String = className.substr(className.lastIndexOf(':') + 1);
if (typeName == null || childType.toLowerCase() == typeName)
_selection.push(child);
}
}
}
}
private function selectRoots() : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
_selection.length = 0;
for each (var node : ISceneNode in selection)
if (_selection.indexOf(node.root) < 0)
_selection.push(node);
}
private function selectDescendants() : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
_selection.length = 0;
for each (var node : ISceneNode in selection)
{
_selection.push(node);
if (node is Group)
(node as Group).getDescendantsByType(ISceneNode, _selection);
}
}
private function selectParents() : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
_selection.length = 0;
for each (var node : ISceneNode in selection)
{
if (node.parent)
_selection.push(node.parent);
else
_selection.push(node);
}
}
private function parseNodeType(nodeType : String) : void
{
if (nodeType == '.')
{
// nothing
}
if (nodeType == '..')
selectParents();
else if (nodeType == '*')
selectChildren();
else
selectChildren(nodeType);
// apply predicates
var token : String = _lexer.getToken();
while (token == '[')
{
_lexer.nextToken(token);
parsePredicate();
token = _lexer.getToken();
}
}
private function parsePredicate() : void
{
var propertyName : String = _lexer.getToken(true);
var isBinding : Boolean = propertyName == '@';
if (isBinding)
propertyName = _lexer.getToken(true);
var index : int = parseInt(propertyName);
filterProperty(_lexer, propertyName, _selection);
_lexer.checkNextToken(']');
}
private function getValueObject(source : Object, chunks : Array) : Object
{
if (chunks)
for each (var chunk : String in chunks)
source = source[chunk];
return source;
}
private function removeFromSelection(index : uint) : void
{
var numNodes : uint = _selection.length - 1;
_selection[index] = _selection[numNodes];
_selection.length = numNodes;
}
private function filterProperty(lexer : XPathLexer, propertyName : String, selection : Vector.<ISceneNode>) : void
{
var isBinding : Boolean = propertyName == '@';
var index : int = parseInt(propertyName);
if (propertyName == 'hasController')
filterOnController(lexer, selection);
else if (propertyName == 'hasProperty')
filterOnProperty(lexer, selection);
else if (propertyName == 'position')
filterOnPosition(lexer, selection);
else if (propertyName == 'last')
filterLast(lexer, selection);
else if (propertyName == 'first')
filterFirst(lexer, selection);
else if (index.toString() == propertyName)
{
if (index < selection.length)
{
selection[0] = selection[index];
selection.length = 1;
}
else
selection.length = 0;
}
else
filterOnValue(lexer, selection, propertyName, isBinding);
}
private function filterOnValue(lexer : XPathLexer,
selection : Vector.<ISceneNode>,
propertyName : String,
isBinding : Boolean = false) : void
{
var operator : String = lexer.getToken(true);
var chunks : Array = [propertyName];
while (operator == '.')
{
chunks.push(lexer.getToken(true));
operator = lexer.getToken(true);
}
var value : Object = lexer.getValueToken();
var numNodes : uint = selection.length;
for (var i : int = numNodes - 1; i >= 0; --i)
{
var node : ISceneNode = selection[i];
var nodeValue : Object = null;
if (isBinding && (node['bindings'] is DataBindings))
nodeValue = (node['bindings'] as DataBindings).getProperty(propertyName);
else
{
try
{
nodeValue = getValueObject(node, chunks);
if (!compare(operator, nodeValue, value))
removeFromSelection(i);
}
catch (e : Error)
{
removeFromSelection(i);
}
}
}
}
private function filterLast(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void
{
lexer.checkNextToken('(');
lexer.checkNextToken(')');
if (selection.length)
{
selection[0] = selection[uint(selection.length - 1)];
selection.length = 1;
}
}
private function filterFirst(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void
{
lexer.checkNextToken('(');
lexer.checkNextToken(')');
selection.length = 1;
}
private function filterOnController(lexer : XPathLexer, selection : Vector.<ISceneNode>) : Object
{
lexer.checkNextToken('(');
var controllerName : String = lexer.getToken(true);
lexer.checkNextToken(')');
var numNodes : uint = selection.length;
for (var i : int = numNodes - 1; i >= 0; --i)
{
var node : ISceneNode = selection[i];
var numControllers : uint = node.numControllers;
var keepSceneNode : Boolean = false;
for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId)
{
var controllerType : String = getQualifiedClassName(node.getController(controllerId));
controllerType = controllerType.substr(controllerType.lastIndexOf(':') + 1);
if (controllerType == controllerName)
{
keepSceneNode = true;
break;
}
}
if (!keepSceneNode)
removeFromSelection(i);
}
return null;
}
private function filterOnPosition(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void
{
lexer.checkNextToken('(');
lexer.checkNextToken(')');
var operator : String = lexer.getToken(true);
var value : uint = uint(parseInt(lexer.getToken(true)));
switch (operator)
{
case '>':
++value;
case '>=':
selection = selection.slice(value);
break;
case '<':
--value;
case '<=':
selection = selection.slice(0, value);
break;
case '=':
case '==':
selection[0] = selection[value];
selection.length = 1;
default:
throw new Error('Unknown comparison operator \'' + operator + '\'');
}
}
private function filterOnProperty(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void
{
lexer.checkNextToken('(');
var chunks : Array = [lexer.getToken(true)];
var operator : String = lexer.getToken(true);
while (operator == '.')
{
chunks.push(operator);
operator = lexer.getToken(true);
}
if (operator != ')')
lexer.throwParseError(')', operator);
var numNodes : uint = selection.length;
for (var i : int = numNodes - 1; i >= 0; --i)
{
try
{
getValueObject(selection[i], chunks);
}
catch (e : Error)
{
removeFromSelection(i);
}
}
}
private function compare(operator : String, a : Object, b : Object) : Boolean
{
switch (operator)
{
case '>' :
return a > b;
case '>=' :
return a >= b;
case '<' :
return a >= b;
case '<=' :
return a <= b;
case '=' :
case '==' :
return a == b;
case '~=' :
var matches : Array = String(a).match(b);
return matches && matches.length != 0;
default:
throw new Error('Unknown comparison operator \'' + operator + '\'');
}
}
}
}
|
package aerys.minko.type.xpath
{
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.binding.DataBindings;
import flash.utils.getQualifiedClassName;
public final class XPathEvaluator
{
private var _path : String;
private var _selection : Vector.<ISceneNode> = null;
private var _modifier : String = null;
private var _lexer : XPathLexer = null;
public function get selection() : Vector.<ISceneNode>
{
return _selection;
}
public function XPathEvaluator(path : String,
selection : Vector.<ISceneNode>,
modifier : String = null)
{
_modifier = modifier;
initialize(path, selection);
}
private function initialize(path : String, selection : Vector.<ISceneNode>) : void
{
_path = path;
_lexer = new XPathLexer(_path);
// update root
var token : String = _lexer.getToken();
_selection = selection.slice();
if (token == "/")
{
selectRoots();
_lexer.nextToken(token);
}
// parse
while ((token = _lexer.getToken()) != null)
{
switch (token)
{
case '//' :
_lexer.nextToken(token);
selectDescendants();
break ;
case '/' :
_lexer.nextToken(token);
selectChildren();
break ;
default :
_lexer.nextToken(token);
parseNodeType(token);
break ;
}
}
}
private function selectChildren(typeName : String = null) : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
if (typeName != null)
typeName = typeName.toLowerCase();
_selection.length = 0;
for each (var node : ISceneNode in selection)
{
if (node is Group)
{
var group : Group = node as Group;
var numChildren : uint = group.numChildren;
for (var i : uint = 0; i < numChildren; ++i)
{
var child : ISceneNode = group.getChildAt(i);
var className : String = getQualifiedClassName(child)
var childType : String = className.substr(className.lastIndexOf(':') + 1);
if (typeName == null || childType.toLowerCase() == typeName)
_selection.push(child);
}
}
}
}
private function selectRoots() : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
_selection.length = 0;
for each (var node : ISceneNode in selection)
if (_selection.indexOf(node.root) < 0)
_selection.push(node);
}
private function selectDescendants() : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
_selection.length = 0;
for each (var node : ISceneNode in selection)
{
_selection.push(node);
if (node is Group)
(node as Group).getDescendantsByType(ISceneNode, _selection);
}
}
private function selectParents() : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
_selection.length = 0;
for each (var node : ISceneNode in selection)
{
if (node.parent)
_selection.push(node.parent);
else
_selection.push(node);
}
}
private function parseNodeType(nodeType : String) : void
{
if (nodeType == '.')
{
// nothing
}
if (nodeType == '..')
selectParents();
else if (nodeType == '*')
selectChildren();
else
selectChildren(nodeType);
// apply predicates
var token : String = _lexer.getToken();
while (token == '[')
{
_lexer.nextToken(token);
parsePredicate();
token = _lexer.getToken();
}
}
private function parsePredicate() : void
{
var propertyName : String = _lexer.getToken(true);
var isBinding : Boolean = propertyName == '@';
if (isBinding)
propertyName = _lexer.getToken(true);
var index : int = parseInt(propertyName);
filterProperty(_lexer, propertyName, _selection);
_lexer.checkNextToken(']');
}
private function getValueObject(source : Object, chunks : Array) : Object
{
if (chunks)
for each (var chunk : String in chunks)
source = source[chunk];
return source;
}
private function removeFromSelection(index : uint) : void
{
var numNodes : uint = _selection.length - 1;
_selection[index] = _selection[numNodes];
_selection.length = numNodes;
}
private function filterProperty(lexer : XPathLexer, propertyName : String, selection : Vector.<ISceneNode>) : void
{
var isBinding : Boolean = propertyName == '@';
var index : int = parseInt(propertyName);
if (propertyName == 'hasController')
filterOnController(lexer, selection);
else if (propertyName == 'hasProperty')
filterOnProperty(lexer, selection);
else if (propertyName == 'position')
filterOnPosition(lexer, selection);
else if (propertyName == 'last')
filterLast(lexer, selection);
else if (propertyName == 'first')
filterFirst(lexer, selection);
else if (index.toString() == propertyName)
{
if (index < selection.length)
{
selection[0] = selection[index];
selection.length = 1;
}
else
selection.length = 0;
}
else
filterOnValue(lexer, selection, propertyName, isBinding);
}
private function filterOnValue(lexer : XPathLexer,
selection : Vector.<ISceneNode>,
propertyName : String,
isBinding : Boolean = false) : void
{
var operator : String = lexer.getToken(true);
var chunks : Array = [propertyName];
while (operator == '.')
{
chunks.push(lexer.getToken(true));
operator = lexer.getToken(true);
}
var value : Object = lexer.getValueToken();
var numNodes : uint = selection.length;
for (var i : int = numNodes - 1; i >= 0; --i)
{
var node : ISceneNode = selection[i];
var nodeValue : Object = null;
if (isBinding && (node['bindings'] is DataBindings))
nodeValue = (node['bindings'] as DataBindings).getProperty(propertyName);
else
{
try
{
nodeValue = getValueObject(node, chunks);
if (!compare(operator, nodeValue, value))
removeFromSelection(i);
}
catch (e : Error)
{
removeFromSelection(i);
}
}
}
}
private function filterLast(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void
{
lexer.checkNextToken('(');
lexer.checkNextToken(')');
if (selection.length)
{
selection[0] = selection[uint(selection.length - 1)];
selection.length = 1;
}
}
private function filterFirst(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void
{
lexer.checkNextToken('(');
lexer.checkNextToken(')');
selection.length = 1;
}
private function filterOnController(lexer : XPathLexer, selection : Vector.<ISceneNode>) : Object
{
lexer.checkNextToken('(');
var controllerName : String = lexer.getToken(true);
lexer.checkNextToken(')');
var numNodes : uint = selection.length;
for (var i : int = numNodes - 1; i >= 0; --i)
{
var node : ISceneNode = selection[i];
var numControllers : uint = node.numControllers;
var keepSceneNode : Boolean = false;
for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId)
{
var controllerType : String = getQualifiedClassName(node.getController(controllerId));
controllerType = controllerType.substr(controllerType.lastIndexOf(':') + 1);
if (controllerType == controllerName)
{
keepSceneNode = true;
break;
}
}
if (!keepSceneNode)
removeFromSelection(i);
}
return null;
}
private function filterOnPosition(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void
{
lexer.checkNextToken('(');
lexer.checkNextToken(')');
var operator : String = lexer.getToken(true);
var value : uint = uint(parseInt(lexer.getToken(true)));
switch (operator)
{
case '>':
++value;
case '>=':
selection = selection.slice(value);
break;
case '<':
--value;
case '<=':
selection = selection.slice(0, value);
break;
case '=':
case '==':
selection[0] = selection[value];
selection.length = 1;
default:
throw new Error('Unknown comparison operator \'' + operator + '\'');
}
}
private function filterOnProperty(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void
{
lexer.checkNextToken('(');
var chunks : Array = [lexer.getToken(true)];
var operator : String = lexer.getToken(true);
while (operator == '.')
{
//chunks.push(operator);
chunks.push(lexer.getToken(true));
operator = lexer.getToken(true);
}
if (operator != ')')
lexer.throwParseError(')', operator);
var numNodes : uint = selection.length;
for (var i : int = numNodes - 1; i >= 0; --i)
{
try
{
if (getValueObject(selection[i], chunks) == null)
removeFromSelection(i);
}
catch (e : Error)
{
removeFromSelection(i);
}
}
}
private function compare(operator : String, a : Object, b : Object) : Boolean
{
switch (operator)
{
case '>' :
return a > b;
case '>=' :
return a >= b;
case '<' :
return a >= b;
case '<=' :
return a <= b;
case '=' :
case '==' :
return a == b;
case '~=' :
var matches : Array = String(a).match(b);
return matches && matches.length != 0;
default:
throw new Error('Unknown comparison operator \'' + operator + '\'');
}
}
}
}
|
Fix xpath for hasProperty command
|
Fix xpath for hasProperty command
|
ActionScript
|
mit
|
aerys/minko-as3
|
e14212f5b4ba164d5301aba93b7f64e4e9142aad
|
src/as/com/threerings/flex/FlexUtil.as
|
src/as/com/threerings/flex/FlexUtil.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 mx.controls.Label;
import mx.controls.Spacer;
import mx.controls.Text;
import mx.core.Container;
import mx.core.UIComponent;
/**
* Flex-related utility methods.
*/
public class FlexUtil
{
/**
* Creates a label with the supplied text and tooltip, and optionally applies a style class to
* it.
*/
public static function createTipLabel (
text :String, toolTip :String, style :String = null) :Label
{
var label :Label = new Label();
label.text = text;
if (toolTip != null) {
label.toolTip = toolTip;
}
if (style != null) {
label.styleName = style;
}
return label;
}
/**
* Creates a label with the supplied text, and optionally applies a style class to it.
*/
public static function createLabel (text :String, style :String = null) :Label
{
return createTipLabel(text, null, style);
}
/**
* Create an uneditable/unselectable multiline Text widget with the specified text and width.
*/
public static function createText (text :String, width :int, style :String = null) :Text
{
var t :Text = new Text();
t.styleName = style;
t.width = width;
t.selectable = false;
t.text = text;
return t;
}
/**
* How hard would it have been for them make Spacer accept two optional arguments?
*/
public static function createSpacer (width :int = 0, height :int = 0) :Spacer
{
var spacer :Spacer = new Spacer();
spacer.width = width;
spacer.height = height;
return spacer;
}
/**
* Return a count of how many visible (includeInLayout=true) children
* are in the specified container.
*/
public static function countLayoutChildren (container :Container) :int
{
var layoutChildren :int = container.numChildren;
for each (var child :Object in container.getChildren()) {
if ((child is UIComponent) && !UIComponent(child).includeInLayout) {
layoutChildren--;
}
}
return layoutChildren;
}
/**
* In flex the 'visible' property controls visibility separate from whether
* the component takes up space in the layout, which is controlled by 'includeInLayout'.
* We usually want to set them together, so this does that for us.
* @return the new visible setting.
*/
public static function setVisible (component :UIComponent, visible :Boolean) :Boolean
{
component.visible = visible;
component.includeInLayout = visible;
return visible;
}
}
}
|
//
// $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 mx.controls.Label;
import mx.controls.Spacer;
import mx.controls.Text;
import mx.core.Container;
import mx.core.UIComponent;
/**
* Flex-related utility methods.
*/
public class FlexUtil
{
/**
* Creates a label with the supplied text and tooltip, and optionally applies a style class to
* it.
*/
public static function createTipLabel (
text :String, toolTip :String, style :String = null) :Label
{
var label :Label = new Label();
label.text = text;
if (toolTip != null) {
label.toolTip = toolTip;
}
if (style != null) {
label.styleName = style;
}
return label;
}
/**
* Creates a label with the supplied text, and optionally applies a style class to it.
*/
public static function createLabel (text :String, style :String = null) :Label
{
return createTipLabel(text, null, style);
}
/**
* Create an uneditable/unselectable multiline Text widget with the specified text and width.
*/
public static function createText (
text :String, width :int, style :String = null, html :Boolean = false) :Text
{
var t :Text = new Text();
t.styleName = style;
t.width = width;
if (html) {
// I want selectable = false here too, but that makes links not work. They still
// have a hand cursor, you can still click the fucking things, but they don't
// work. WHY ADOBE WHY YOU RANCID PIEFUCKERS?
t.htmlText = text;
} else {
t.selectable = false;
t.text = text;
}
return t;
}
/**
* How hard would it have been for them make Spacer accept two optional arguments?
*/
public static function createSpacer (width :int = 0, height :int = 0) :Spacer
{
var spacer :Spacer = new Spacer();
spacer.width = width;
spacer.height = height;
return spacer;
}
/**
* Return a count of how many visible (includeInLayout=true) children
* are in the specified container.
*/
public static function countLayoutChildren (container :Container) :int
{
var layoutChildren :int = container.numChildren;
for each (var child :Object in container.getChildren()) {
if ((child is UIComponent) && !UIComponent(child).includeInLayout) {
layoutChildren--;
}
}
return layoutChildren;
}
/**
* In flex the 'visible' property controls visibility separate from whether
* the component takes up space in the layout, which is controlled by 'includeInLayout'.
* We usually want to set them together, so this does that for us.
* @return the new visible setting.
*/
public static function setVisible (component :UIComponent, visible :Boolean) :Boolean
{
component.visible = visible;
component.includeInLayout = visible;
return visible;
}
}
}
|
Add a way to set the HTML text. Oh yeah, links don't work unless the field is selectable. WHY? Carbomb adobe.
|
Add a way to set the HTML text.
Oh yeah, links don't work unless the field is selectable. WHY?
Carbomb adobe.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@691 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
f3390bb91b942f4f23646d0f4453161795306f02
|
fp10/src/as3isolib/display/IsoGroup.as
|
fp10/src/as3isolib/display/IsoGroup.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 - 3000 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
{
import as3isolib.bounds.IBounds;
import as3isolib.bounds.PrimitiveBounds;
import as3isolib.bounds.SceneBounds;
import as3isolib.core.IIsoDisplayObject;
import as3isolib.core.IsoDisplayObject;
import as3isolib.core.as3isolib_internal;
import as3isolib.display.renderers.ISceneLayoutRenderer;
import as3isolib.display.renderers.SimpleSceneLayoutRenderer;
import as3isolib.display.scene.IIsoScene;
import flash.display.DisplayObjectContainer;
use namespace as3isolib_internal;
public class IsoGroup extends IsoDisplayObject implements IIsoScene
{
///////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
///////////////////////////////////////////////////////////////////////
/**
* Constructor
*/
public function IsoGroup (descriptor:Object = null)
{
super(descriptor);
}
///////////////////////////////////////////////////////////////////////
// I ISO SCENE
///////////////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
public function get hostContainer ():DisplayObjectContainer
{
return null;
}
/**
* @private
*/
public function set hostContainer (value:DisplayObjectContainer):void
{
//do nothing
}
/**
* @inheritDoc
*/
public function get invalidatedChildren ():Array
{
var a:Array;
var child:IIsoDisplayObject;
for each (child in children)
{
if (child.isInvalidated)
a.push(child);
}
return a;
}
/**
* @inheritDoc
*/
override public function get isoBounds ():IBounds
{
return bSizeSetExplicitly ? new PrimitiveBounds(this) : new SceneBounds(this);
}
///////////////////////////////////////////////////////////////////////
// WIDTH LENGTH HEIGHT
///////////////////////////////////////////////////////////////////////
private var bSizeSetExplicitly:Boolean;
/**
* @inheritDoc
*/
override public function set width (value:Number):void
{
super.width = value;
bSizeSetExplicitly = !isNaN(value);
}
/**
* @inheritDoc
*/
override public function set length (value:Number):void
{
super.length = value;
bSizeSetExplicitly = !isNaN(value);
}
/**
* @inheritDoc
*/
override public function set height (value:Number):void
{
super.height = value;
bSizeSetExplicitly = !isNaN(value);
}
///////////////////////////////////////////////////////////////////////
// ISO GROUP
///////////////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
override protected function renderLogic (recursive:Boolean = true):void
{
super.renderLogic(recursive);
if (bIsInvalidated)
{
if (!bSizeSetExplicitly)
calculateSizeFromChildren();
var renderer:ISceneLayoutRenderer = new SimpleSceneLayoutRenderer();
renderer.renderScene(this);
bIsInvalidated = false;
}
}
/**
* @private
*/
protected function calculateSizeFromChildren ():void
{
var b:IBounds = new SceneBounds(this);
isoWidth = b.width;
isoLength = b.length;
isoHeight = b.height;
}
}
}
|
/*
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 - 3000 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
{
import as3isolib.bounds.IBounds;
import as3isolib.bounds.PrimitiveBounds;
import as3isolib.bounds.SceneBounds;
import as3isolib.core.IIsoDisplayObject;
import as3isolib.core.IsoDisplayObject;
import as3isolib.core.as3isolib_internal;
import as3isolib.display.renderers.ISceneLayoutRenderer;
import as3isolib.display.renderers.SimpleSceneLayoutRenderer;
import as3isolib.display.scene.IIsoScene;
import flash.display.DisplayObjectContainer;
use namespace as3isolib_internal;
public class IsoGroup extends IsoDisplayObject implements IIsoScene
{
///////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
///////////////////////////////////////////////////////////////////////
/**
* Constructor
*/
public function IsoGroup (descriptor:Object = null)
{
super(descriptor);
}
///////////////////////////////////////////////////////////////////////
// I ISO SCENE
///////////////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
public function get hostContainer ():DisplayObjectContainer
{
return null;
}
/**
* @private
*/
public function set hostContainer (value:DisplayObjectContainer):void
{
//do nothing
}
/**
* @inheritDoc
*/
public function get invalidatedChildren ():Array
{
var a:Array;
var child:IIsoDisplayObject;
for each (child in children)
{
if (child.isInvalidated)
a.push(child);
}
return a;
}
/**
* @inheritDoc
*/
override public function get isoBounds ():IBounds
{
return bSizeSetExplicitly ? new PrimitiveBounds(this) : new SceneBounds(this);
}
///////////////////////////////////////////////////////////////////////
// WIDTH LENGTH HEIGHT
///////////////////////////////////////////////////////////////////////
private var bSizeSetExplicitly:Boolean;
/**
* @inheritDoc
*/
override public function set width (value:Number):void
{
super.width = value;
bSizeSetExplicitly = !isNaN(value);
}
/**
* @inheritDoc
*/
override public function set length (value:Number):void
{
super.length = value;
bSizeSetExplicitly = !isNaN(value);
}
/**
* @inheritDoc
*/
override public function set height (value:Number):void
{
super.height = value;
bSizeSetExplicitly = !isNaN(value);
}
///////////////////////////////////////////////////////////////////////
// ISO GROUP
///////////////////////////////////////////////////////////////////////
public var renderer:ISceneLayoutRenderer = new SimpleSceneLayoutRenderer();
/**
* @inheritDoc
*/
override protected function renderLogic (recursive:Boolean = true):void
{
super.renderLogic(recursive);
if (bIsInvalidated)
{
if (!bSizeSetExplicitly)
calculateSizeFromChildren();
if (!renderer)
renderer = new SimpleSceneLayoutRenderer();
renderer.renderScene(this);
bIsInvalidated = false;
}
}
/**
* @private
*/
protected function calculateSizeFromChildren ():void
{
var b:IBounds = new SceneBounds(this);
isoWidth = b.width;
isoLength = b.length;
isoHeight = b.height;
}
}
}
|
fix for IsoGroup
|
fix for IsoGroup
|
ActionScript
|
mit
|
liuju/as3isolib.v1,liuju/as3isolib.v1,dreamsxin/as3isolib.v1,as3isolib/as3isolib.v1,dreamsxin/as3isolib.v1,as3isolib/as3isolib.v1
|
35c75eeb005b15e218d8d7da82263fbaae6c94b9
|
src/org/mangui/hls/stream/TagBuffer.as
|
src/org/mangui/hls/stream/TagBuffer.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.stream {
import flash.events.TimerEvent;
import flash.events.Event;
import flash.utils.Timer;
import flash.utils.Dictionary;
import org.mangui.hls.event.HLSMediatime;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.constant.HLSSeekStates;
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.utils.Log;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
/*
* intermediate FLV Tag Buffer
* input : FLV tags retrieved from different fragment loaders (video/alt-audio...)
* output : provide muxed FLV tags to HLSNetStream
*/
public class TagBuffer {
private var _hls : HLS;
/** Timer used to process FLV tags. **/
private var _timer : Timer;
private var _audioTags : Vector.<FLVData>;
private var _videoTags : Vector.<FLVData>;
private var _metaTags : Vector.<FLVData>;
/** playlist duration **/
private var _playlist_duration : Number = 0;
/** requested start position **/
private var _seek_position_requested : Number;
/** real start position , retrieved from first fragment **/
private var _seek_position_real : Number;
/** start position of first injected tag **/
private var _first_start_position : Number;
private var _seek_pos_reached : Boolean;
/** Current play position (relative position from beginning of sliding window) **/
private var _playback_current_position : Number;
/** playlist sliding (non null for live playlist) **/
private var _playlist_sliding_duration : Number;
/** buffer PTS (indexed by continuity counter) */
private var _buffer_pts : Dictionary;
public function TagBuffer(hls : HLS) {
_hls = hls;
flushAll();
_timer = new Timer(100, 0);
_timer.addEventListener(TimerEvent.TIMER, _checkBuffer);
_hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED, _playlistDurationUpdated);
}
public function dispose() : void {
flushAll();
_hls.removeEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED, _playlistDurationUpdated);
_timer.stop();
_hls = null;
_timer = null;
}
public function stop() : void {
flushAll();
}
public function seek(position : Number) : void {
_seek_position_requested = position;
flushAll();
_timer.start();
}
public function flushAll() : void {
_audioTags = new Vector.<FLVData>();
_videoTags = new Vector.<FLVData>();
_metaTags = new Vector.<FLVData>();
_buffer_pts = new Dictionary();
_seek_pos_reached = false;
_playlist_sliding_duration = 0;
_first_start_position = -1;
}
public function flushAudio() : void {
_audioTags = new Vector.<FLVData>();
}
public function appendTags(tags : Vector.<FLVTag>, min_pts : Number, max_pts : Number, continuity : int, start_position : Number) : void {
for each (var tag : FLVTag in tags) {
var position : Number = start_position + (tag.pts - min_pts) / 1000;
var tagData : FLVData = new FLVData(tag, position, continuity);
switch(tag.type) {
case FLVTag.AAC_HEADER:
case FLVTag.AAC_RAW:
case FLVTag.MP3_RAW:
_audioTags.push(tagData);
break;
case FLVTag.AVC_HEADER:
case FLVTag.AVC_NALU:
_videoTags.push(tagData);
break;
case FLVTag.DISCONTINUITY:
case FLVTag.METADATA:
_metaTags.push(tagData);
break;
default:
}
}
/* check live playlist sliding here :
_seek_position_real + getTotalBufferedDuration() should be the start_position
* /of the new fragment if the playlist was not sliding
=> live playlist sliding is the difference between the new start position and this previous value */
if (_hls.seekState == HLSSeekStates.SEEKED) {
// Log.info("seek pos/getTotalBufferedDuration/start pos:" + _seek_position_requested + "/" + getTotalBufferedDuration() + "/" + start_position);
_playlist_sliding_duration = (_first_start_position + getTotalBufferedDuration()) - start_position;
} else {
if (_first_start_position == -1) {
// remember position of first tag injected after seek. it will be used for playlist sliding computation
_first_start_position = start_position;
}
}
// update buffer min/max table indexed with continuity counter
if (_buffer_pts[continuity] == undefined) {
_buffer_pts[continuity] = new BufferPTS(min_pts, max_pts);
} else {
(_buffer_pts[continuity] as BufferPTS).max = max_pts;
}
_timer.start();
}
/** Return current media position **/
public function get position() : Number {
switch(_hls.seekState) {
case HLSSeekStates.SEEKING:
return _seek_position_requested;
case HLSSeekStates.SEEKED:
/** Relative playback position = (Absolute Position(seek position + play time) - playlist sliding, non null for Live Playlist) **/
return _seek_position_real + _hls.stream.time - _playlist_sliding_duration;
case HLSSeekStates.IDLE:
default:
return 0;
}
};
public function get audioBufferLength() : Number {
return getbuflen(_audioTags);
}
public function get videoBufferLength() : Number {
return getbuflen(_videoTags);
}
public function get bufferLength() : Number {
return Math.max(audioBufferLength, videoBufferLength);
}
/** Timer **/
private function _checkBuffer(e : Event) : void {
// dispatch media time event
_hls.dispatchEvent(new HLSEvent(HLSEvent.MEDIA_TIME, new HLSMediatime(position, _playlist_duration, _hls.stream.bufferLength, _playlist_sliding_duration)));
/* only append tags if seek position has been reached, otherwise wait for more tags to come
* this is to ensure that accurate seeking will work appropriately
*/
if (_seek_pos_reached || max_pos >= _seek_position_requested) {
var flvdata : FLVData;
var data : Vector.<FLVData> = new Vector.<FLVData>();
while ((flvdata = shift()) != null) {
data.push(flvdata);
}
if (!_seek_pos_reached) {
data = seekFilterTags(data);
_seek_pos_reached = true;
}
var tags : Vector.<FLVTag> = new Vector.<FLVTag>();
for each (flvdata in data) {
tags.push(flvdata.tag);
}
if (tags.length) {
(_hls.stream as HLSNetStream).appendTags(tags);
Log.debug("appending " + tags.length + " tags");
}
}
}
/* filter/tweak tags to seek accurately into the stream */
private function seekFilterTags(tags : Vector.<FLVData>) : Vector.<FLVData> {
var filteredTags : Vector.<FLVData>= new Vector.<FLVData>();
/* PTS of first tag that will be pushed into FLV tag buffer */
var first_pts : Number;
/* PTS of last video keyframe before requested seek position */
var keyframe_pts : Number;
/* */
var min_offset : Number = tags[0].position;
var min_pts : Number = tags[0].tag.pts;
/*
*
* real seek requested seek Frag
* position position End
* *------------------*-------------------------
* <------------------>
* seek_offset
*
* real seek position is the start offset of the first received fragment after seek command. (= fragment start offset).
* seek offset is the diff between the requested seek position and the real seek position
*/
/* if requested seek position is out of this segment bounds
* all the segments will be pushed, first pts should be thus be min_pts
*/
if (_seek_position_requested < min_offset) {
_seek_position_real = min_offset;
first_pts = min_pts;
} else {
/* if requested position is within segment bounds, determine real seek position depending on seek mode setting */
if (HLSSettings.seekMode == HLSSeekMode.SEGMENT_SEEK) {
_seek_position_real = min_offset;
first_pts = min_pts;
} else {
/* accurate or keyframe seeking */
/* seek_pts is the requested PTS seek position */
var seek_pts : Number = min_pts + 1000 * (_seek_position_requested - min_offset);
/* analyze fragment tags and look for PTS of last keyframe before seek position.*/
keyframe_pts = min_pts;
for each (var flvData : FLVData in tags) {
var tag : FLVTag = flvData.tag;
// look for last keyframe with pts <= seek_pts
if (tag.keyframe == true && tag.pts <= seek_pts && (tag.type == FLVTag.AVC_HEADER || tag.type == FLVTag.AVC_NALU)) {
keyframe_pts = tag.pts;
}
}
if (HLSSettings.seekMode == HLSSeekMode.KEYFRAME_SEEK) {
_seek_position_real = min_offset + (keyframe_pts - min_pts) / 1000;
first_pts = keyframe_pts;
} else {
// accurate seek, to exact requested position
_seek_position_real = _seek_position_requested;
first_pts = seek_pts;
}
}
}
/* if in segment seeking mode : push all FLV tags */
if (HLSSettings.seekMode == HLSSeekMode.SEGMENT_SEEK) {
filteredTags = tags;
} else {
/* keyframe / accurate seeking, we need to filter out some FLV tags */
for each (flvData in tags) {
tag = flvData.tag;
if (tag.pts >= first_pts) {
filteredTags.push(flvData);
} else {
switch(tag.type) {
case FLVTag.AAC_HEADER:
case FLVTag.AVC_HEADER:
case FLVTag.METADATA:
case FLVTag.DISCONTINUITY:
tag.pts = tag.dts = first_pts;
filteredTags.push(flvData);
break;
case FLVTag.AVC_NALU:
/* only append video tags starting from last keyframe before seek position to avoid playback artifacts
* rationale of this is that there can be multiple keyframes per segment. if we append all keyframes
* in NetStream, all of them will be displayed in a row and this will introduce some playback artifacts
* */
if (tag.pts >= keyframe_pts) {
tag.pts = tag.dts = first_pts;
filteredTags.push(flvData);
}
break;
default:
break;
}
}
}
}
return filteredTags;
}
private function _playlistDurationUpdated(event : HLSEvent) : void {
_playlist_duration = event.duration;
}
private function getbuflen(tags : Vector.<FLVData>) : Number {
var min_pts : Number = 0;
var max_pts : Number = 0;
var continuity : int = -1;
var len : Number = 0;
for each (var data : FLVData in tags) {
if (data.continuity != continuity) {
len += (max_pts - min_pts);
min_pts = data.tag.pts;
continuity = data.continuity;
} else {
max_pts = data.tag.pts;
}
}
len += (max_pts - min_pts);
return len / 1000;
}
/** return total buffered duration since seek() call, needed to compute live playlist sliding */
private function getTotalBufferedDuration() : Number {
var len : Number = 0;
for each (var entry : BufferPTS in _buffer_pts) {
len += (entry.max - entry.min);
}
return len / 1000;
}
/*
*
* return next tag from queue, using the following priority :
* smallest continuity
* then smallest pts
* then metadata then video then audio tags
*/
private function shift() : FLVData {
if (_videoTags.length == 0 && _audioTags.length == 0 && _metaTags.length == 0)
return null;
var continuity : int = int.MAX_VALUE;
// find smallest continuity counter
if (_metaTags.length) continuity = Math.min(continuity, _metaTags[0].continuity);
if (_videoTags.length) continuity = Math.min(continuity, _videoTags[0].continuity);
if (_audioTags.length) continuity = Math.min(continuity, _audioTags[0].continuity);
var pts : Number = Number.MAX_VALUE;
// for this continuity counter, find smallest PTS
if (_metaTags.length && _metaTags[0].continuity == continuity) pts = Math.min(pts, _metaTags[0].tag.pts);
if (_videoTags.length && _videoTags[0].continuity == continuity) pts = Math.min(pts, _videoTags[0].tag.pts);
if (_audioTags.length && _audioTags[0].continuity == continuity) pts = Math.min(pts, _audioTags[0].tag.pts);
// for this continuity counter, this PTS, prioritize tags with the following order : metadata/video/audio
if (_metaTags.length && _metaTags[0].continuity == continuity && _metaTags[0].tag.pts == pts) return _metaTags.shift();
if (_videoTags.length && _videoTags[0].continuity == continuity && _videoTags[0].tag.pts == pts) return _videoTags.shift();
else return _audioTags.shift();
}
/*
private function get min_pos() : Number {
var min_pos_ : Number = Number.POSITIVE_INFINITY;
if (_metaTags.length) min_pos_ = Math.min(min_pos_, _metaTags[0].position);
if (_videoTags.length) min_pos_ = Math.min(min_pos_, _videoTags[0].position);
if (_audioTags.length) min_pos_ = Math.min(min_pos_, _audioTags[0].position);
return min_pos_;
}
*/
private function get max_pos() : Number {
var max_pos_ : Number = Number.NEGATIVE_INFINITY;
if (_metaTags.length) max_pos_ = Math.max(max_pos_, _metaTags[_metaTags.length - 1].position);
if (_videoTags.length) max_pos_ = Math.max(max_pos_, _videoTags[_videoTags.length - 1].position);
if (_audioTags.length) max_pos_ = Math.max(max_pos_, _audioTags[_audioTags.length - 1].position);
return max_pos_;
}
}
}
import org.mangui.hls.flv.FLVTag;
class FLVData {
public var tag : FLVTag;
public var position : Number;
public var continuity : int;
public function FLVData(tag : FLVTag, position : Number, continuity : int) {
this.tag = tag;
this.position = position;
this.continuity = continuity;
}
}
class BufferPTS {
public var min : Number;
public var max : Number;
public function BufferPTS(min : Number, max : Number) {
this.min = min;
this.max = max;
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.stream {
import flash.events.TimerEvent;
import flash.events.Event;
import flash.utils.Timer;
import flash.utils.Dictionary;
import org.mangui.hls.event.HLSMediatime;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.constant.HLSSeekStates;
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.utils.Log;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
/*
* intermediate FLV Tag Buffer
* input : FLV tags retrieved from different fragment loaders (video/alt-audio...)
* output : provide muxed FLV tags to HLSNetStream
*/
public class TagBuffer {
private var _hls : HLS;
/** Timer used to process FLV tags. **/
private var _timer : Timer;
private var _audioTags : Vector.<FLVData>;
private var _videoTags : Vector.<FLVData>;
private var _metaTags : Vector.<FLVData>;
/** playlist duration **/
private var _playlist_duration : Number = 0;
/** requested start position **/
private var _seek_position_requested : Number;
/** real start position , retrieved from first fragment **/
private var _seek_position_real : Number;
/** start position of first injected tag **/
private var _first_start_position : Number;
private var _seek_pos_reached : Boolean;
/** playlist sliding (non null for live playlist) **/
private var _playlist_sliding_duration : Number;
/** buffer PTS (indexed by continuity counter) */
private var _buffer_pts : Dictionary;
public function TagBuffer(hls : HLS) {
_hls = hls;
flushAll();
_timer = new Timer(100, 0);
_timer.addEventListener(TimerEvent.TIMER, _checkBuffer);
_hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED, _playlistDurationUpdated);
}
public function dispose() : void {
flushAll();
_hls.removeEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED, _playlistDurationUpdated);
_timer.stop();
_hls = null;
_timer = null;
}
public function stop() : void {
flushAll();
}
public function seek(position : Number) : void {
_seek_position_requested = position;
flushAll();
_timer.start();
}
public function flushAll() : void {
_audioTags = new Vector.<FLVData>();
_videoTags = new Vector.<FLVData>();
_metaTags = new Vector.<FLVData>();
_buffer_pts = new Dictionary();
_seek_pos_reached = false;
_playlist_sliding_duration = 0;
_first_start_position = -1;
}
public function flushAudio() : void {
_audioTags = new Vector.<FLVData>();
}
public function appendTags(tags : Vector.<FLVTag>, min_pts : Number, max_pts : Number, continuity : int, start_position : Number) : void {
for each (var tag : FLVTag in tags) {
var position : Number = start_position + (tag.pts - min_pts) / 1000;
var tagData : FLVData = new FLVData(tag, position, continuity);
switch(tag.type) {
case FLVTag.AAC_HEADER:
case FLVTag.AAC_RAW:
case FLVTag.MP3_RAW:
_audioTags.push(tagData);
break;
case FLVTag.AVC_HEADER:
case FLVTag.AVC_NALU:
_videoTags.push(tagData);
break;
case FLVTag.DISCONTINUITY:
case FLVTag.METADATA:
_metaTags.push(tagData);
break;
default:
}
}
/* check live playlist sliding here :
_seek_position_real + getTotalBufferedDuration() should be the start_position
* /of the new fragment if the playlist was not sliding
=> live playlist sliding is the difference between the new start position and this previous value */
if (_hls.seekState == HLSSeekStates.SEEKED) {
// Log.info("seek pos/getTotalBufferedDuration/start pos:" + _seek_position_requested + "/" + getTotalBufferedDuration() + "/" + start_position);
_playlist_sliding_duration = (_first_start_position + getTotalBufferedDuration()) - start_position;
} else {
if (_first_start_position == -1) {
// remember position of first tag injected after seek. it will be used for playlist sliding computation
_first_start_position = start_position;
}
}
// update buffer min/max table indexed with continuity counter
if (_buffer_pts[continuity] == undefined) {
_buffer_pts[continuity] = new BufferPTS(min_pts, max_pts);
} else {
(_buffer_pts[continuity] as BufferPTS).max = max_pts;
}
_timer.start();
}
/** Return current media position **/
public function get position() : Number {
switch(_hls.seekState) {
case HLSSeekStates.SEEKING:
return _seek_position_requested;
case HLSSeekStates.SEEKED:
/** Relative playback position = (Absolute Position(seek position + play time) - playlist sliding, non null for Live Playlist) **/
return _seek_position_real + _hls.stream.time - _playlist_sliding_duration;
case HLSSeekStates.IDLE:
default:
return 0;
}
};
public function get audioBufferLength() : Number {
return getbuflen(_audioTags);
}
public function get videoBufferLength() : Number {
return getbuflen(_videoTags);
}
public function get bufferLength() : Number {
return Math.max(audioBufferLength, videoBufferLength);
}
/** Timer **/
private function _checkBuffer(e : Event) : void {
// dispatch media time event
_hls.dispatchEvent(new HLSEvent(HLSEvent.MEDIA_TIME, new HLSMediatime(position, _playlist_duration, _hls.stream.bufferLength, _playlist_sliding_duration)));
/* only append tags if seek position has been reached, otherwise wait for more tags to come
* this is to ensure that accurate seeking will work appropriately
*/
if (_seek_pos_reached || max_pos >= _seek_position_requested) {
var flvdata : FLVData;
var data : Vector.<FLVData> = new Vector.<FLVData>();
while ((flvdata = shift()) != null) {
data.push(flvdata);
}
if (!_seek_pos_reached) {
data = seekFilterTags(data);
_seek_pos_reached = true;
}
var tags : Vector.<FLVTag> = new Vector.<FLVTag>();
for each (flvdata in data) {
tags.push(flvdata.tag);
}
if (tags.length) {
(_hls.stream as HLSNetStream).appendTags(tags);
Log.debug("appending " + tags.length + " tags");
}
}
}
/* filter/tweak tags to seek accurately into the stream */
private function seekFilterTags(tags : Vector.<FLVData>) : Vector.<FLVData> {
var filteredTags : Vector.<FLVData>= new Vector.<FLVData>();
/* PTS of first tag that will be pushed into FLV tag buffer */
var first_pts : Number;
/* PTS of last video keyframe before requested seek position */
var keyframe_pts : Number;
/* */
var min_offset : Number = tags[0].position;
var min_pts : Number = tags[0].tag.pts;
/*
*
* real seek requested seek Frag
* position position End
* *------------------*-------------------------
* <------------------>
* seek_offset
*
* real seek position is the start offset of the first received fragment after seek command. (= fragment start offset).
* seek offset is the diff between the requested seek position and the real seek position
*/
/* if requested seek position is out of this segment bounds
* all the segments will be pushed, first pts should be thus be min_pts
*/
if (_seek_position_requested < min_offset) {
_seek_position_real = min_offset;
first_pts = min_pts;
} else {
/* if requested position is within segment bounds, determine real seek position depending on seek mode setting */
if (HLSSettings.seekMode == HLSSeekMode.SEGMENT_SEEK) {
_seek_position_real = min_offset;
first_pts = min_pts;
} else {
/* accurate or keyframe seeking */
/* seek_pts is the requested PTS seek position */
var seek_pts : Number = min_pts + 1000 * (_seek_position_requested - min_offset);
/* analyze fragment tags and look for PTS of last keyframe before seek position.*/
keyframe_pts = min_pts;
for each (var flvData : FLVData in tags) {
var tag : FLVTag = flvData.tag;
// look for last keyframe with pts <= seek_pts
if (tag.keyframe == true && tag.pts <= seek_pts && (tag.type == FLVTag.AVC_HEADER || tag.type == FLVTag.AVC_NALU)) {
keyframe_pts = tag.pts;
}
}
if (HLSSettings.seekMode == HLSSeekMode.KEYFRAME_SEEK) {
_seek_position_real = min_offset + (keyframe_pts - min_pts) / 1000;
first_pts = keyframe_pts;
} else {
// accurate seek, to exact requested position
_seek_position_real = _seek_position_requested;
first_pts = seek_pts;
}
}
}
/* if in segment seeking mode : push all FLV tags */
if (HLSSettings.seekMode == HLSSeekMode.SEGMENT_SEEK) {
filteredTags = tags;
} else {
/* keyframe / accurate seeking, we need to filter out some FLV tags */
for each (flvData in tags) {
tag = flvData.tag;
if (tag.pts >= first_pts) {
filteredTags.push(flvData);
} else {
switch(tag.type) {
case FLVTag.AAC_HEADER:
case FLVTag.AVC_HEADER:
case FLVTag.METADATA:
case FLVTag.DISCONTINUITY:
tag.pts = tag.dts = first_pts;
filteredTags.push(flvData);
break;
case FLVTag.AVC_NALU:
/* only append video tags starting from last keyframe before seek position to avoid playback artifacts
* rationale of this is that there can be multiple keyframes per segment. if we append all keyframes
* in NetStream, all of them will be displayed in a row and this will introduce some playback artifacts
* */
if (tag.pts >= keyframe_pts) {
tag.pts = tag.dts = first_pts;
filteredTags.push(flvData);
}
break;
default:
break;
}
}
}
}
return filteredTags;
}
private function _playlistDurationUpdated(event : HLSEvent) : void {
_playlist_duration = event.duration;
}
private function getbuflen(tags : Vector.<FLVData>) : Number {
var min_pts : Number = 0;
var max_pts : Number = 0;
var continuity : int = -1;
var len : Number = 0;
for each (var data : FLVData in tags) {
if (data.continuity != continuity) {
len += (max_pts - min_pts);
min_pts = data.tag.pts;
continuity = data.continuity;
} else {
max_pts = data.tag.pts;
}
}
len += (max_pts - min_pts);
return len / 1000;
}
/** return total buffered duration since seek() call, needed to compute live playlist sliding */
private function getTotalBufferedDuration() : Number {
var len : Number = 0;
for each (var entry : BufferPTS in _buffer_pts) {
len += (entry.max - entry.min);
}
return len / 1000;
}
/*
*
* return next tag from queue, using the following priority :
* smallest continuity
* then smallest pts
* then metadata then video then audio tags
*/
private function shift() : FLVData {
if (_videoTags.length == 0 && _audioTags.length == 0 && _metaTags.length == 0)
return null;
var continuity : int = int.MAX_VALUE;
// find smallest continuity counter
if (_metaTags.length) continuity = Math.min(continuity, _metaTags[0].continuity);
if (_videoTags.length) continuity = Math.min(continuity, _videoTags[0].continuity);
if (_audioTags.length) continuity = Math.min(continuity, _audioTags[0].continuity);
var pts : Number = Number.MAX_VALUE;
// for this continuity counter, find smallest PTS
if (_metaTags.length && _metaTags[0].continuity == continuity) pts = Math.min(pts, _metaTags[0].tag.pts);
if (_videoTags.length && _videoTags[0].continuity == continuity) pts = Math.min(pts, _videoTags[0].tag.pts);
if (_audioTags.length && _audioTags[0].continuity == continuity) pts = Math.min(pts, _audioTags[0].tag.pts);
// for this continuity counter, this PTS, prioritize tags with the following order : metadata/video/audio
if (_metaTags.length && _metaTags[0].continuity == continuity && _metaTags[0].tag.pts == pts) return _metaTags.shift();
if (_videoTags.length && _videoTags[0].continuity == continuity && _videoTags[0].tag.pts == pts) return _videoTags.shift();
else return _audioTags.shift();
}
/*
private function get min_pos() : Number {
var min_pos_ : Number = Number.POSITIVE_INFINITY;
if (_metaTags.length) min_pos_ = Math.min(min_pos_, _metaTags[0].position);
if (_videoTags.length) min_pos_ = Math.min(min_pos_, _videoTags[0].position);
if (_audioTags.length) min_pos_ = Math.min(min_pos_, _audioTags[0].position);
return min_pos_;
}
*/
private function get max_pos() : Number {
var max_pos_ : Number = Number.NEGATIVE_INFINITY;
if (_metaTags.length) max_pos_ = Math.max(max_pos_, _metaTags[_metaTags.length - 1].position);
if (_videoTags.length) max_pos_ = Math.max(max_pos_, _videoTags[_videoTags.length - 1].position);
if (_audioTags.length) max_pos_ = Math.max(max_pos_, _audioTags[_audioTags.length - 1].position);
return max_pos_;
}
}
}
import org.mangui.hls.flv.FLVTag;
class FLVData {
public var tag : FLVTag;
public var position : Number;
public var continuity : int;
public function FLVData(tag : FLVTag, position : Number, continuity : int) {
this.tag = tag;
this.position = position;
this.continuity = continuity;
}
}
class BufferPTS {
public var min : Number;
public var max : Number;
public function BufferPTS(min : Number, max : Number) {
this.min = min;
this.max = max;
}
}
|
remove unused var
|
remove unused var
|
ActionScript
|
mpl-2.0
|
School-Improvement-Network/flashls,Boxie5/flashls,suuhas/flashls,aevange/flashls,loungelogic/flashls,suuhas/flashls,Peer5/flashls,codex-corp/flashls,aevange/flashls,clappr/flashls,Boxie5/flashls,jlacivita/flashls,Peer5/flashls,Peer5/flashls,Corey600/flashls,vidible/vdb-flashls,neilrackett/flashls,dighan/flashls,aevange/flashls,viktorot/flashls,aevange/flashls,suuhas/flashls,Peer5/flashls,tedconf/flashls,jlacivita/flashls,codex-corp/flashls,School-Improvement-Network/flashls,mangui/flashls,fixedmachine/flashls,loungelogic/flashls,hola/flashls,NicolasSiver/flashls,neilrackett/flashls,fixedmachine/flashls,hola/flashls,thdtjsdn/flashls,JulianPena/flashls,School-Improvement-Network/flashls,tedconf/flashls,mangui/flashls,viktorot/flashls,viktorot/flashls,JulianPena/flashls,vidible/vdb-flashls,clappr/flashls,Corey600/flashls,suuhas/flashls,NicolasSiver/flashls,dighan/flashls,thdtjsdn/flashls
|
1378eafe69ff38d86314b1c4c6eae8fa71cd50b9
|
Arguments/src/classes/Language.as
|
Arguments/src/classes/Language.as
|
package classes
{
/**
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 flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import mx.controls.Alert;
import org.osmf.layout.AbsoluteLayoutFacet;
public class Language
{
//I will set the language to either GERMAN, RUSSIAN or ENGLISH
//based on this, you could read the values into the variables
//by default, the language is EN-US
public static const GERMAN:String = "GER";
public static const ENGLISH:String = "EN-US";
public static const RUSSIAN:String = "RUS";
public static var language:String = "EN-US";
public static var xml:XML;
private static var ready:Boolean=false;
public static function init():void
{
[Embed(source="../../../translation.xml", mimeType="application/octet-stream")]
const MyData:Class;
var byteArray:ByteArray = new MyData() as ByteArray;
var x:XML = new XML(byteArray.readUTFBytes(byteArray.length));
xml = x;
ready=true;
}
/**The key function. Use this to look up a label from the translation document according to the set language.*/
public static function lookup(label:String):String{
if(!ready){
init();
}
trace("Now looking up:" + label);
var lbl:XMLList = xml.descendants(label);
var lang:XMLList = lbl.descendants(language);
var output:String = lang.attribute("text");
if(!output){
output = "error | ошибка | fehler --- There was a problem getting the text for this item. The label was: " + label;
}
trace("Output is: " + output);
return output;
}
}
}
|
package classes
{
/**
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 flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import mx.controls.Alert;
import org.osmf.layout.AbsoluteLayoutFacet;
public class Language
{
//I will set the language to either GERMAN, RUSSIAN or ENGLISH
//based on this, you could read the values into the variables
//by default, the language is EN-US
public static const GERMAN:String = "GER";
public static const ENGLISH:String = "EN-US";
public static const RUSSIAN:String = "RUS";
public static var language:String = GERMAN;
public static var xml:XML;
private static var ready:Boolean=false;
public static function init():void
{
[Embed(source="../../../translation.xml", mimeType="application/octet-stream")]
const MyData:Class;
var byteArray:ByteArray = new MyData() as ByteArray;
var x:XML = new XML(byteArray.readUTFBytes(byteArray.length));
xml = x;
ready=true;
}
/**The key function. Use this to look up a label from the translation document according to the set language.*/
public static function lookup(label:String):String{
if(!ready){
init();
}
trace("Now looking up:" + label);
var lbl:XMLList = xml.descendants(label);
var lang:XMLList = lbl.descendants(language);
var output:String = lang.attribute("text");
if(!output){
output = "error | ошибка | fehler --- There was a problem getting the text for this item. The label was: " + label;
}
trace("Output is: " + output);
return output;
}
}
}
|
Change current language to German
|
Change current language to German
|
ActionScript
|
agpl-3.0
|
mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA,MichaelHoffmann/AGORA
|
57c300b2df3ed3d11d23f1adef1931f7b61984da
|
src/MultipartTest.as
|
src/MultipartTest.as
|
package
{
import com.jonas.net.Multipart;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.utils.ByteArray;
[SWF(width="600", height="400", frameRate="30", backgroundColor="#CCCCCC")]
public class MultipartTest extends Sprite
{
[Embed(source="icon480.png")]
public var c:Class;
public var b:Bitmap;
public var t:TextField;
private var url:String = "http://labs.positronic.fr/flash/multipart/upload.php";
public function MultipartTest()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
var s:Sprite = new Sprite();
s.addEventListener(MouseEvent.CLICK, onClick);
s.buttonMode = true;
s.y = 20;
addChild(s);
b = new c() as Bitmap;
b.scaleX = b.scaleY = 0.5;
s.addChild(b);
t = new TextField();
t.width = 400;
t.multiline = t.wordWrap = true;
t.autoSize = TextFieldAutoSize.LEFT;
t.x = s.width+20;
t.y = s.y;
addChild(t);
t.text = "Click to upload";
if(loaderInfo.parameters["url"] != null){
url = loaderInfo.parameters["url"];
}
}
protected function onClick(event:Event):void
{
t.text = "loading...";
var jpg:JPEGEncoder = new JPEGEncoder(80);
var test:ByteArray = new ByteArray();
test.writeMultiByte("Hello", "ascii");
var form:Multipart = new Multipart(url);
// add fields
form.addField("field1", "hello");
form.addField("field2", "world");
// add files
form.addFile("file1", test, "text/plain", "test.txt");
form.addFile("file2", jpg.encode(b.bitmapData), "application/octet-stream", "test.jpg");
//navigateToURL(form.request);
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onComplete);
try {
loader.load(form.request);
} catch (error: Error) {
t.text = "Unable to load requested document : "+error.message;
}
}
protected function onComplete (e: Event):void {
t.text = e.target["data"];
}
}
}
|
package
{
import com.jonas.net.Multipart;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.utils.ByteArray;
[SWF(width="600", height="400", frameRate="30", backgroundColor="#CCCCCC")]
public class MultipartTest extends Sprite
{
[Embed(source="icon480.png")]
public var c:Class;
public var b:Bitmap;
public var t:TextField;
private var url:String = "http://labs.positronic.fr/flash/multipart/upload.php";
public function MultipartTest()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
var s:Sprite = new Sprite();
s.addEventListener(MouseEvent.CLICK, onClick);
s.buttonMode = true;
s.y = 20;
addChild(s);
b = new c() as Bitmap;
b.scaleX = b.scaleY = 0.5;
s.addChild(b);
t = new TextField();
t.width = 400;
t.multiline = t.wordWrap = true;
t.autoSize = TextFieldAutoSize.LEFT;
t.x = s.width+20;
t.y = s.y;
addChild(t);
t.text = "Click to upload";
if(loaderInfo.parameters["url"] != null){
url = loaderInfo.parameters["url"];
}
}
protected function onClick(event:Event):void
{
t.text = "loading...";
var jpg:JPEGEncoder = new JPEGEncoder(80);
var test:ByteArray = new ByteArray();
test.writeMultiByte("Hello", "ascii");
var form:Multipart = new Multipart(url);
// add fields
form.addField("field1", "hello");
form.addField("field2", "world");
// add files
form.addFile("file1", test, "text/plain", "test.txt");
form.addFile("file2", jpg.encode(b.bitmapData), "image/jpeg", "test.jpg");
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onComplete);
try {
loader.load(form.request);
} catch (error: Error) {
t.text = "Unable to load requested document : "+error.message;
}
}
protected function onComplete (e: Event):void {
t.text = e.target["data"];
}
}
}
|
change mime type
|
change mime type
|
ActionScript
|
apache-2.0
|
jimojon/Multipart.as
|
3695510904e7cc3ff42aeb3ba96d2379d6b02f5c
|
utils/gcClasses.as
|
utils/gcClasses.as
|
/* -*- indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// Input is a bunch of file names and/or names of files from which to read file names.
//
// Output is a tree of classes derived from a root class (default GCFinalizedObject),
// with an annotation about whether it has an explicit destructor or not (line
// prefixed with "*"). Each class is printed with the file and line on which the
// definition starts.
//
// Assumes names are globally unique (namespaces don't matter). Is tricked by macro
// definitions like in the Error objects, and by the use of the bitwise not operator
// in some cases: "exception->flags &= ~Exception::SEEN_BY_DEBUGGER;"
//
// Furtermore there will be generated destructors for classes that have substructures,
// and those destructors won't be visible here.
//
// Usage:
//
// avmshell gcClasses.abc -- [options] file ...
//
// Options:
//
// --base classname Specify the base class name, default GCFinalizedObject.
// Useful values are GCObject, GCTraceableObject, and RCObject.
//
// Example:
//
// find . -name '*.cpp' -o -name '*.h' > allfiles.txt
// avmshell gcClasses.abc -- @allfiles.txt
//
// Example: (for TR, though not the player)
//
// avmshell utils/gcClasses.abc -- $(find . -name '*.h' -o -name '*.cpp')
//
// Note the list of "excluded" paths below; those could be command line arguments but
// that's for later.
import avmplus.*;
// The root class could be a command line argument.
var rootclass = "GCFinalizedObject";
// Classes defined in files whose names match these regexes will not
// be printed, but will participate in the computation.
const ignorePaths =
[ new RegExp("^.*/shell/.*$"),
new RegExp("^.*/extensions/ST_.*$"),
new RegExp("^.*/extensions/JavaGlue.*$"),
new RegExp("^.*/MMgc/GCTests.*$")];
class LineInfo
{
function LineInfo(_derived, _base, _filename, _lineno) {
derived = _derived;
base = _base;
filename = _filename;
lineno = _lineno;
}
var derived; // name of the class being defined
var base; // name of its base class
var filename; // file where we found the definition of 'derived'
var lineno; // line where we found the definition of 'derived'
var baseref = null; // reference to the LineInfo for the base class
var subrefs = []; // list of known subclasses
var destructor = false; // true if we believe this has a destructor
}
main(System.argv);
function main(args) {
if (args.length > 0 && args[0] == "--base") {
if (args.length > 1) {
rootclass = args[1];
args.shift();
args.shift();
}
else
throw new Error("Missing class name to --base");
}
printClasses(processQueue(readFiles(args)));
}
function readFiles(argv) {
var filenames_dict = {};
var probable_destructors = {};
var all_lines = [];
var re1 = new RegExp("class\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*:.*(?:public|private|virtual)\\s*([A-Za-z0-9_:]+)");
var re2 = new RegExp("class\\s+GC_(?:AS3|CPP)_EXACT(?:[A-Z_]+)?\\(([^,\\)]+)\\s*,\\s*([^,\\)]+)");
var red = new RegExp("~\s*([A-Za-z_][A-Za-z0-9_]*)");
compute(argv,false);
annotateDestructors();
return all_lines;
function annotateDestructors() {
for ( var i=0 ; i < all_lines.length ; i++ ) {
var ln = all_lines[i];
ln.destructor = probable_destructors.hasOwnProperty(ln.derived);
}
}
function compute(argv) {
for ( var i=0 ; i < argv.length ; i++ ) {
var arg=argv[i];
if (arg.charAt(0) == '@')
compute(readFile(arg.substring(1)));
else if (newFile(arg))
filterFile(arg);
}
}
function newFile(fn) {
return File.exists(fn) && !filenames_dict.hasOwnProperty(fn);
}
function filterFile(fn) {
var lines = readFile(fn);
var ignore = false;
var ignorelevel = 0;
for ( var i=0 ; i < lines.length ; i++ ) {
var l = lines[i];
var result;
// Faster to filter by indexOf and then do regex matching than just regex matching.
if (l.indexOf("#") != -1) {
// Preprocessor macro?
// We need to know the regions commented out by #ifdef DRC_TRIVIAL_DESTRUCTOR .. #endif
// but we must track nested regions too.
if (l.match(/^\s*#\s*(?:ifdef|ifndef|if|elif)/)) {
if (l.match(/^\s*#\s*ifdef\s+DRC_TRIVIAL_DESTRUCTOR/))
ignore = true;
if (ignore)
ignorelevel++;
}
else if (l.match(/^\s*#\s*endif/)) {
if (ignore) {
--ignorelevel;
if (ignorelevel == 0)
ignore = false;
}
}
}
if (l.indexOf("class") != -1) {
if ((result = l.match(re1)) || (result = l.match(re2))) {
var derived = result[1];
var base = stripNamespaces(result[2]);
all_lines.push(new LineInfo(derived,base,fn,i+1));
}
}
else if (!ignore && l.indexOf("~") != -1) {
if (result = l.match(red)) {
probable_destructors[result[1]] = true;
}
}
}
filenames_dict[fn] = true;
}
function stripNamespaces(name) {
var x = name.lastIndexOf(":");
return (x >= 0) ? name.substring(x+1) : name;
}
}
function readFile(fn) {
try {
return File.read(fn).split("\n");
}
catch (e) {
print("Can't open file \"" + "\"\n" + e);
return [];
}
}
function processQueue(lines) {
var queue = []; // Queue of classes to process
var classes = {}; // Map of classes processed or in queue to their LineInfo
queue.push(rootclass);
classes[rootclass] = new LineInfo(rootclass, "", "(internal)", 0); // synthetic
while (queue.length > 0) {
var cls = queue.shift();
for ( var l=0 ; l < lines.length ; l++ ) {
var ln = lines[l];
if (classes.hasOwnProperty(ln.base) && !classes.hasOwnProperty(ln.derived)) {
var basecls = classes[ln.base];
ln.baseref = basecls;
basecls.subrefs.push(ln);
classes[ln.derived] = ln;
queue.push(ln.derived);
}
}
}
return classes;
}
function printClasses(classes) {
printCls(classes[rootclass], 0);
function printCls(cls, indent) {
if (!ignoreIt(cls)) {
var d = cls.destructor ? " * " : " ";
print(d + padTo50(spaces(indent) + cls.derived) + " " + cls.filename + ":" + cls.lineno);
}
cls.subrefs.sort(function (a,b) { return strcmp(a.derived, b.derived); })
for ( var i=0 ; i < cls.subrefs.length ; i++ ) {
var c = cls.subrefs[i];
printCls(c, indent+2);
}
}
function ignoreIt(cls) {
for ( var i=0 ; i < ignorePaths.length ; i++ ) {
if (cls.filename.match(ignorePaths[i]))
return true;
}
return false;
}
function padTo50(s) {
return (s.length >= 50) ? s : padTo50(s + " ");
}
function spaces(n) {
return (n == 0) ? "" : " " + spaces(n-1);
}
function strcmp(a,b) {
if (a < b) return -1;
if (b < a) return 1;
return 0;
}
}
|
/* -*- indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// Input is a bunch of file names and/or names of files from which to read file names.
//
// Output is a tree of classes derived from a root class (default GCFinalizedObject),
// with per-class annotations:
//
// - a "D" if the class has an explicit Destructor
// - a "E" if the class is Exactly traced
//
// Each class is printed with the file and line on which the definition starts.
//
// At the end some statistics are printed.
//
// Assumes names are globally unique (namespaces don't matter). Is tricked by macro
// definitions like in the Error objects, and by the use of the bitwise not operator
// in some cases: "exception->flags &= ~Exception::SEEN_BY_DEBUGGER;"
//
// Furtermore there will be generated destructors for classes that have substructures,
// and those destructors won't be visible here.
//
// Usage:
//
// avmshell gcClasses.abc -- [options] file ...
//
// Options:
//
// --base classname Specify the base class name, default GCFinalizedObject.
// Useful values are GCObject, GCTraceableObject, and RCObject.
//
// Example:
//
// find . -name '*.cpp' -o -name '*.h' > allfiles.txt
// avmshell gcClasses.abc -- @allfiles.txt
//
// Example: (for TR, though not the player)
//
// avmshell utils/gcClasses.abc -- $(find . -name '*.h' -o -name '*.cpp')
//
// Note the list of "excluded" paths below; those could be command line arguments but
// that's for later.
import avmplus.*;
// The root class could be a command line argument.
var rootclass = "GCFinalizedObject";
// Classes defined in files whose names match these regexes will not
// be printed, but will participate in the computation.
const ignorePaths =
[ new RegExp("^.*/shell/.*$"),
new RegExp("^.*/extensions/ST_.*$"),
new RegExp("^.*/extensions/JavaGlue.*$"),
new RegExp("^.*/eval/.*$"),
new RegExp("^.*/MMgc/GCTests.*$")];
class LineInfo
{
function LineInfo(_derived, _base, _isExact, _filename, _lineno) {
derived = _derived;
base = _base;
isExact = _isExact;
filename = _filename;
lineno = _lineno;
}
public function toString() {
return "derived=" + derived + ", base=" + base + ", filename=" + filename + ", lineno=" + lineno + ", defcount=" + defcount;
}
var derived; // name of the class being defined
var base; // name of its base class
var isExact; // true iff the class is exactly traced
var filename; // file where we found the definition of 'derived'
var lineno; // line where we found the definition of 'derived'
var baseref = null; // reference to the LineInfo for the base class
var subrefs = []; // list of known subclasses
var destructor = false; // true if we believe this has a destructor
var defcount = 0; // number of definitions
var otherlines = []; // for in-tree lines beyond the first: locations of definition: { filename:x, lineno:n }
var exolines = []; // for out-of-tree lines: locations of definition: { filename:x, lineno:n }
var external = false; // true if there are definitions of the 'derived' name not within the tree
}
main(System.argv);
function main(args) {
if (args.length > 0 && args[0] == "--base") {
if (args.length > 1) {
rootclass = args[1];
args.shift();
args.shift();
}
else
throw new Error("Missing class name to --base");
}
printClasses(processQueue(readFiles(args)));
}
function readFiles(argv) {
var filenames_dict = {};
var probable_destructors = {};
var probable_tracers = {};
var all_lines = [];
// Hack, hack, hack
var re1 = new RegExp("class\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*:.*(?:public|private|virtual)\\s*(?:MMgc\\s*::\\s*)?([A-Za-z0-9_:]+)");
var re2 = new RegExp("class\\s+GC_(?:MANUAL|AS3|CPP)_EXACT(?:[A-Z_]+)?\\(([^,\\)]+)\\s*,\\s*([^,\\)]+)");
var red = new RegExp("~\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*\\(");
var red2 = new RegExp("virtual\\s*~\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*\\(.*\\)\\s*{\\s*}");
var rtrace = new RegExp("([A-Za-z0-9_]+)\\s*::\\s*gcTrace");
compute(argv,false);
annotateDestructors();
annotateTracers();
return all_lines;
function annotateDestructors() {
for ( var i=0 ; i < all_lines.length ; i++ ) {
var ln = all_lines[i];
ln.destructor = probable_destructors.hasOwnProperty(ln.derived);
}
}
function annotateTracers() {
for ( var i=0 ; i < all_lines.length ; i++ ) {
var ln = all_lines[i];
ln.isExact = ln.isExact || probable_tracers.hasOwnProperty(ln.derived);
}
}
function compute(argv) {
for ( var i=0 ; i < argv.length ; i++ ) {
var arg=argv[i];
if (arg.charAt(0) == '@')
compute(readFile(arg.substring(1)));
else if (newFile(arg))
filterFile(arg);
}
}
function newFile(fn) {
return File.exists(fn) && !filenames_dict.hasOwnProperty(fn);
}
function filterFile(fn) {
var lines = readFile(fn);
var ignore = false;
var ignorelevel = 0;
for ( var i=0 ; i < lines.length ; i++ ) {
var l = lines[i];
var result;
// Faster to filter by indexOf and then do regex matching than just regex matching.
if (l.indexOf("#") != -1) {
// Preprocessor macro?
// We need to know the regions commented out by #ifdef DRC_TRIVIAL_DESTRUCTOR .. #endif
// but we must track nested regions too.
if (l.match(/^\s*#\s*(?:ifdef|ifndef|if|elif)/)) {
if (l.match(/^\s*#\s*ifdef\s+DRC_TRIVIAL_DESTRUCTOR/))
ignore = true;
if (ignore)
ignorelevel++;
}
else if (l.match(/^\s*#\s*endif/)) {
if (ignore) {
--ignorelevel;
if (ignorelevel == 0)
ignore = false;
}
}
}
if (l.indexOf("class") != -1) {
var found = 0;
// Order matters because we want commented-out "class GC_MANUAL_EXACT( ..." to take precedence
// over the actual definition when we build the class tree.
if ((result = l.match(re2)) != null)
found = 2;
else if ((result = l.match(re1)) != null)
found = 1;
if (found) {
var derived = result[1];
var base = stripNamespaces(result[2]);
all_lines.push(new LineInfo(derived,base,found==2,fn,i+1));
}
}
else if (!ignore && l.indexOf("~") != -1) {
if (result = l.match(red)) {
if (!l.match(red2)) // filter out trivial destructors
probable_destructors[result[1]] = true;
}
}
else if (!ignore && l.indexOf("gcTrace") != -1) {
if (result = l.match(rtrace)) {
probable_tracers[result[1]] = true;
}
}
}
filenames_dict[fn] = true;
}
function stripNamespaces(name) {
var x = name.lastIndexOf(":");
return (x >= 0) ? name.substring(x+1) : name;
}
}
function readFile(fn) {
try {
return File.read(fn).split("\n");
}
catch (e) {
print("Can't open file \"" + "\"\n" + e);
return [];
}
}
function processQueue(lines) {
var queue = []; // Queue of classes to process
var classes = {}; // Map of classes processed or in queue to their LineInfo
queue.push(rootclass);
classes[rootclass] = new LineInfo(rootclass, "", false, "(internal)", 0); // synthetic
while (queue.length > 0) {
var cls = queue.shift();
for ( var l=0 ; l < lines.length ; l++ ) {
var ln = lines[l];
if (classes.hasOwnProperty(ln.base)) {
if (!classes.hasOwnProperty(ln.derived)) {
var basecls = classes[ln.base];
ln.baseref = basecls;
basecls.subrefs.push(ln);
classes[ln.derived] = ln;
ln.defcount = 1;
queue.push(ln.derived);
}
else {
// Flag it as used, but it's not canonical because
// it's not in the classes table.
ln.defcount = 1;
}
}
}
}
// Compute lines for multiple in-tree definitions, and attributes for not-within-tree definitions
for ( var l=0 ; l < lines.length ; l++ ) {
var ln = lines[l];
if (ln.defcount > 0 && classes.hasOwnProperty(ln.derived)) {
var c = classes[ln.derived];
if (c !== ln) {
c.defcount++;
c.otherlines.push({filename: ln.filename, lineno: ln.lineno});
}
}
if (ln.defcount == 0 && classes.hasOwnProperty(ln.derived)) {
var c = classes[ln.derived];
c.external = true;
c.exolines.push({filename: ln.filename, lineno: ln.lineno});
}
}
return classes;
}
function printClasses(classes) {
var destructors = 0;
var exacts = 0;
var classcount = 0;
print("Legend:");
print(" D - at least one of the definitions has an explicit destructor");
print(" E - at least one of the definitions is exactly traced");
print(" M - multiple definitions in the tree (in different namespaces or nested within classes)");
print(" # - continuation line for M with additional locations");
print(" X - definitions of the same name exist outside the tree");
print(" @ - continuation line for @ with locations");
print("");
printCls(classes[rootclass], 0);
print("");
print("Classes: " + classcount);
print("Explicit destructors: " + destructors);
print("Exactly traced: " + exacts + " (" + Math.round(exacts/classcount*100) + "%)");
function printCls(cls, indent) {
if (!ignoreIt(cls)) {
classcount++;
if (cls.destructor) destructors++;
if (cls.isExact) exacts++;
var d = " " + (cls.destructor ? "D" : " ") + (cls.isExact ? "E" : " ") + (cls.defcount > 1 ? "M" : " ") + (cls.external ? "X" : " ") + " ";
print(d + padTo50(spaces(indent) + cls.derived) + " " + cls.filename + ":" + cls.lineno);
if (cls.defcount > 1) {
var locs = cls.otherlines;
for ( var l=0 ; l < locs.length ; l++ )
print(" # " + padTo50("") + locs[l].filename + ":" + locs[l].lineno);
}
if (cls.external) {
var locs = cls.exolines;
for ( var l=0 ; l < locs.length ; l++ )
print(" @ " + padTo50("") + locs[l].filename + ":" + locs[l].lineno);
}
}
cls.subrefs.sort(function (a,b) { return strcmp(a.derived, b.derived); })
for ( var i=0 ; i < cls.subrefs.length ; i++ ) {
var c = cls.subrefs[i];
printCls(c, indent+2);
}
}
function ignoreIt(cls) {
for ( var i=0 ; i < ignorePaths.length ; i++ ) {
if (cls.filename.match(ignorePaths[i]))
return true;
}
return false;
}
function padTo50(s) {
return (s.length >= 50) ? s : padTo50(s + " ");
}
function spaces(n) {
return (n == 0) ? "" : " " + spaces(n-1);
}
function strcmp(a,b) {
if (a < b) return -1;
if (b < a) return 1;
return 0;
}
}
|
Update the gcClasses script to handle multiple definitions, out-of-tree definitions, and to filter trivial destructors and non-destructors (r=lhansen)
|
Update the gcClasses script to handle multiple definitions, out-of-tree definitions, and to filter trivial destructors and non-destructors (r=lhansen)
|
ActionScript
|
mpl-2.0
|
pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux
|
9ac5f652dbf2c7aa3828eb5ad9f15a11fef4cb25
|
src/com/google/analytics/GATracker.as
|
src/com/google/analytics/GATracker.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics
{
import com.google.analytics.core.Buffer;
import com.google.analytics.core.EventTracker;
import com.google.analytics.core.GIFRequest;
import com.google.analytics.core.IdleTimer;
import com.google.analytics.core.ServerOperationMode;
import com.google.analytics.core.TrackerCache;
import com.google.analytics.core.TrackerMode;
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.Layout;
import com.google.analytics.events.AnalyticsEvent;
import com.google.analytics.external.AdSenseGlobals;
import com.google.analytics.external.HTMLDOM;
import com.google.analytics.external.JavascriptProxy;
import com.google.analytics.utils.Environment;
import com.google.analytics.utils.Version;
import com.google.analytics.v4.Bridge;
import com.google.analytics.v4.Configuration;
import com.google.analytics.v4.GoogleAnalyticsAPI;
import com.google.analytics.v4.Tracker;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.EventDispatcher;
/* force import for type in the includes */
EventTracker;
ServerOperationMode;
/**
* Dispatched after the factory has built the tracker object.
* @eventType com.google.analytics.events.AnalyticsEvent.READY
*/
[Event(name="ready", type="com.google.analytics.events.AnalyticsEvent")]
/**
* Google Analytic Tracker Code (GATC)'s code-only component.
*/
public class GATracker implements AnalyticsTracker
{
private var _ready:Boolean = false;
private var _display:DisplayObject;
private var _eventDispatcher:EventDispatcher;
private var _tracker:GoogleAnalyticsAPI;
//factory
private var _config:Configuration;
private var _debug:DebugConfiguration;
private var _env:Environment;
private var _buffer:Buffer;
private var _gifRequest:GIFRequest;
private var _jsproxy:JavascriptProxy;
private var _dom:HTMLDOM;
private var _adSense:AdSenseGlobals;
//object properties
private var _account:String;
private var _mode:String;
private var _visualDebug:Boolean;
/**
* Indicates if the tracker is automatically build.
*/
public static var autobuild:Boolean = true;
/**
* The version of the tracker.
*/
public static var version:Version = API.version;
/**
* Creates a new GATracker instance.
* <p><b>Note:</b> the GATracker need to be instancied and added to the Stage or at least
* being placed in a display list.</p>
*/
public function GATracker( display:DisplayObject, account:String,
mode:String = "AS3", visualDebug:Boolean = false,
config:Configuration = null, debug:DebugConfiguration = null )
{
_display = display;
_eventDispatcher = new EventDispatcher( this ) ;
_tracker = new TrackerCache();
this.account = account;
this.mode = mode;
this.visualDebug = visualDebug;
if( !debug )
{
this.debug = new DebugConfiguration();
}
if( !config )
{
this.config = new Configuration( debug );
}
if( autobuild )
{
_factory();
}
}
/**
* @private
* Factory to build the different trackers
*/
private function _factory():void
{
_jsproxy = new JavascriptProxy( debug );
if( visualDebug )
{
debug.layout = new Layout( debug, _display );
debug.active = visualDebug;
}
var activeTracker:GoogleAnalyticsAPI;
var cache:TrackerCache = _tracker as TrackerCache;
switch( mode )
{
case TrackerMode.BRIDGE :
{
activeTracker = _bridgeFactory();
break;
}
case TrackerMode.AS3 :
default:
{
activeTracker = _trackerFactory();
}
}
if( !cache.isEmpty() )
{
cache.tracker = activeTracker;
cache.flush();
}
_tracker = activeTracker;
_ready = true;
dispatchEvent( new AnalyticsEvent( AnalyticsEvent.READY, this ) );
}
/**
* @private
* Factory method for returning a Tracker object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _trackerFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (AS3) v" + version +"\naccount: " + account );
/* note:
for unit testing and to avoid 2 different branches AIR/Flash
here we will detect if we are in the Flash Player or AIR
and pass the infos to the LocalInfo
By default we will define "Flash" for our local tests
*/
_adSense = new AdSenseGlobals( debug );
_dom = new HTMLDOM( debug );
_dom.cacheProperties();
_env = new Environment( "", "", "", debug, _dom );
_buffer = null;
_gifRequest = null;
/* note:
To be able to obtain the URL of the main SWF containing the GA API
we need to be able to access the stage property of a DisplayObject,
here we open the internal namespace to be able to set that reference
at instanciation-time.
We keep the implementation internal to be able to change it if required later.
*/
use namespace ga_internal;
_env.url = _display.stage.loaderInfo.url;
return new Tracker( account, config, debug, _env, _buffer, _gifRequest, _adSense, _display );
}
/**
* @private
* Factory method for returning a Bridge object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _bridgeFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (Bridge) v" + version +"\naccount: " + account );
return new Bridge( account, _debug, _jsproxy );
}
/**
* Indicates the account value of the tracking.
*/
public function get account():String
{
return _account;
}
/**
* @private
*/
public function set account( value:String ):void
{
_account = value;
}
/**
* Determinates the Configuration object of the tracker.
*/
public function get config():Configuration
{
return _config;
}
/**
* @private
*/
public function set config( value:Configuration ):void
{
_config = value;
}
/**
* Determinates the DebugConfiguration of the tracker.
*/
public function get debug():DebugConfiguration
{
return _debug;
}
/**
* @private
*/
public function set debug( value:DebugConfiguration ):void
{
_debug = value;
}
/**
* Indicates if the tracker is ready to use.
*/
public function isReady():Boolean
{
return _ready;
}
/**
* Indicates the mode of the tracking "AS3" or "Bridge".
*/
public function get mode():String
{
return _mode;
}
/**
* @private
*/
public function set mode( value:String ):void
{
_mode = value ;
}
/**
* Indicates if the tracker use a visual debug.
*/
public function get visualDebug():Boolean
{
return _visualDebug;
}
/**
* @private
*/
public function set visualDebug( value:Boolean ):void
{
_visualDebug = value;
}
/**
* Builds the tracker.
*/
public function build():void
{
if( !isReady() )
{
_factory();
}
}
// IEventDispatcher implementation
/**
* Allows the registration of event listeners on the event target.
* @param type A string representing the event type to listen for. If eventName value is "ALL" addEventListener use addGlobalListener
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
* @param priority Determines the priority level of the event listener.
* @param useWeakReference Indicates if the listener is a weak reference.
*/
public function addEventListener( type:String, listener:Function, useCapture:Boolean = false, priority:int = 0,
useWeakReference:Boolean = false):void
{
_eventDispatcher.addEventListener( type, listener, useCapture, priority, useWeakReference );
}
/**
* Dispatches an event into the event flow.
* @param event The Event object that is dispatched into the event flow.
* @return <code class="prettyprint">true</code> if the Event is dispatched.
*/
public function dispatchEvent( event:Event ):Boolean
{
return _eventDispatcher.dispatchEvent( event );
}
/**
* Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
* This allows you to determine where altered handling of an event type has been introduced in the event flow heirarchy by an EventDispatcher object.
*/
public function hasEventListener( type:String ):Boolean
{
return _eventDispatcher.hasEventListener( type );
}
/**
* Removes a listener from the EventDispatcher object.
* If there is no matching listener registered with the <code class="prettyprint">EventDispatcher</code> object, then calling this method has no effect.
* @param type Specifies the type of event.
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
*/
public function removeEventListener( type:String, listener:Function, useCapture:Boolean = false ):void
{
_eventDispatcher.removeEventListener( type, listener, useCapture );
}
/**
* Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
* This method returns <code class="prettyprint">true</code> if an event listener is triggered during any phase of the event flow when an event of the specified type is dispatched to this EventDispatcher object or any of its descendants.
* @return A value of <code class="prettyprint">true</code> if a listener of the specified type will be triggered; <code class="prettyprint">false</code> otherwise.
*/
public function willTrigger( type:String ):Boolean
{
return _eventDispatcher.willTrigger( type );
}
include "common.txt"
}
}
|
/*
* 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
{
import com.google.analytics.core.Buffer;
import com.google.analytics.core.EventTracker;
import com.google.analytics.core.GIFRequest;
import com.google.analytics.core.ServerOperationMode;
import com.google.analytics.core.TrackerCache;
import com.google.analytics.core.TrackerMode;
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.Layout;
import com.google.analytics.events.AnalyticsEvent;
import com.google.analytics.external.AdSenseGlobals;
import com.google.analytics.external.HTMLDOM;
import com.google.analytics.external.JavascriptProxy;
import com.google.analytics.utils.Environment;
import com.google.analytics.utils.Version;
import com.google.analytics.v4.Bridge;
import com.google.analytics.v4.Configuration;
import com.google.analytics.v4.GoogleAnalyticsAPI;
import com.google.analytics.v4.Tracker;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.EventDispatcher;
/* force import for type in the includes */
EventTracker;
ServerOperationMode;
/**
* Dispatched after the factory has built the tracker object.
* @eventType com.google.analytics.events.AnalyticsEvent.READY
*/
[Event(name="ready", type="com.google.analytics.events.AnalyticsEvent")]
/**
* Google Analytic Tracker Code (GATC)'s code-only component.
*/
public class GATracker implements AnalyticsTracker
{
private var _ready:Boolean = false;
private var _display:DisplayObject;
private var _eventDispatcher:EventDispatcher;
private var _tracker:GoogleAnalyticsAPI;
//factory
private var _config:Configuration;
private var _debug:DebugConfiguration;
private var _env:Environment;
private var _buffer:Buffer;
private var _gifRequest:GIFRequest;
private var _jsproxy:JavascriptProxy;
private var _dom:HTMLDOM;
private var _adSense:AdSenseGlobals;
//object properties
private var _account:String;
private var _mode:String;
private var _visualDebug:Boolean;
/**
* Indicates if the tracker is automatically build.
*/
public static var autobuild:Boolean = true;
/**
* The version of the tracker.
*/
public static var version:Version = API.version;
/**
* Creates a new GATracker instance.
* <p><b>Note:</b> the GATracker need to be instancied and added to the Stage or at least
* being placed in a display list.</p>
*/
public function GATracker( display:DisplayObject, account:String,
mode:String = "AS3", visualDebug:Boolean = false,
config:Configuration = null, debug:DebugConfiguration = null )
{
_display = display;
_eventDispatcher = new EventDispatcher( this ) ;
_tracker = new TrackerCache();
this.account = account;
this.mode = mode;
this.visualDebug = visualDebug;
if( !debug )
{
this.debug = new DebugConfiguration();
}
if( !config )
{
this.config = new Configuration( debug );
}
if( autobuild )
{
_factory();
}
}
/**
* @private
* Factory to build the different trackers
*/
private function _factory():void
{
_jsproxy = new JavascriptProxy( debug );
if( visualDebug )
{
debug.layout = new Layout( debug, _display );
debug.active = visualDebug;
}
var activeTracker:GoogleAnalyticsAPI;
var cache:TrackerCache = _tracker as TrackerCache;
switch( mode )
{
case TrackerMode.BRIDGE :
{
activeTracker = _bridgeFactory();
break;
}
case TrackerMode.AS3 :
default:
{
activeTracker = _trackerFactory();
}
}
if( !cache.isEmpty() )
{
cache.tracker = activeTracker;
cache.flush();
}
_tracker = activeTracker;
_ready = true;
dispatchEvent( new AnalyticsEvent( AnalyticsEvent.READY, this ) );
}
/**
* @private
* Factory method for returning a Tracker object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _trackerFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (AS3) v" + version +"\naccount: " + account );
/* note:
for unit testing and to avoid 2 different branches AIR/Flash
here we will detect if we are in the Flash Player or AIR
and pass the infos to the LocalInfo
By default we will define "Flash" for our local tests
*/
_adSense = new AdSenseGlobals( debug );
_dom = new HTMLDOM( debug );
_dom.cacheProperties();
_env = new Environment( "", "", "", debug, _dom );
_buffer = null;
_gifRequest = null;
/* note:
To be able to obtain the URL of the main SWF containing the GA API
we need to be able to access the stage property of a DisplayObject,
here we open the internal namespace to be able to set that reference
at instanciation-time.
We keep the implementation internal to be able to change it if required later.
*/
use namespace ga_internal;
_env.url = _display.stage.loaderInfo.url;
return new Tracker( account, config, debug, _env, _buffer, _gifRequest, _adSense, _display );
}
/**
* @private
* Factory method for returning a Bridge object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _bridgeFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (Bridge) v" + version +"\naccount: " + account );
return new Bridge( account, _debug, _jsproxy );
}
/**
* Indicates the account value of the tracking.
*/
public function get account():String
{
return _account;
}
/**
* @private
*/
public function set account( value:String ):void
{
_account = value;
}
/**
* Determinates the Configuration object of the tracker.
*/
public function get config():Configuration
{
return _config;
}
/**
* @private
*/
public function set config( value:Configuration ):void
{
_config = value;
}
/**
* Determinates the DebugConfiguration of the tracker.
*/
public function get debug():DebugConfiguration
{
return _debug;
}
/**
* @private
*/
public function set debug( value:DebugConfiguration ):void
{
_debug = value;
}
/**
* Indicates if the tracker is ready to use.
*/
public function isReady():Boolean
{
return _ready;
}
/**
* Indicates the mode of the tracking "AS3" or "Bridge".
*/
public function get mode():String
{
return _mode;
}
/**
* @private
*/
public function set mode( value:String ):void
{
_mode = value ;
}
/**
* Indicates if the tracker use a visual debug.
*/
public function get visualDebug():Boolean
{
return _visualDebug;
}
/**
* @private
*/
public function set visualDebug( value:Boolean ):void
{
_visualDebug = value;
}
/**
* Builds the tracker.
*/
public function build():void
{
if( !isReady() )
{
_factory();
}
}
// IEventDispatcher implementation
/**
* Allows the registration of event listeners on the event target.
* @param type A string representing the event type to listen for. If eventName value is "ALL" addEventListener use addGlobalListener
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
* @param priority Determines the priority level of the event listener.
* @param useWeakReference Indicates if the listener is a weak reference.
*/
public function addEventListener( type:String, listener:Function, useCapture:Boolean = false, priority:int = 0,
useWeakReference:Boolean = false):void
{
_eventDispatcher.addEventListener( type, listener, useCapture, priority, useWeakReference );
}
/**
* Dispatches an event into the event flow.
* @param event The Event object that is dispatched into the event flow.
* @return <code class="prettyprint">true</code> if the Event is dispatched.
*/
public function dispatchEvent( event:Event ):Boolean
{
return _eventDispatcher.dispatchEvent( event );
}
/**
* Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
* This allows you to determine where altered handling of an event type has been introduced in the event flow heirarchy by an EventDispatcher object.
*/
public function hasEventListener( type:String ):Boolean
{
return _eventDispatcher.hasEventListener( type );
}
/**
* Removes a listener from the EventDispatcher object.
* If there is no matching listener registered with the <code class="prettyprint">EventDispatcher</code> object, then calling this method has no effect.
* @param type Specifies the type of event.
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
*/
public function removeEventListener( type:String, listener:Function, useCapture:Boolean = false ):void
{
_eventDispatcher.removeEventListener( type, listener, useCapture );
}
/**
* Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
* This method returns <code class="prettyprint">true</code> if an event listener is triggered during any phase of the event flow when an event of the specified type is dispatched to this EventDispatcher object or any of its descendants.
* @return A value of <code class="prettyprint">true</code> if a listener of the specified type will be triggered; <code class="prettyprint">false</code> otherwise.
*/
public function willTrigger( type:String ):Boolean
{
return _eventDispatcher.willTrigger( type );
}
include "common.txt"
}
}
|
Fix GATracker import
|
Fix GATracker import
|
ActionScript
|
apache-2.0
|
minimedj/gaforflash,soumavachakraborty/gaforflash,DimaBaliakin/gaforflash,jeremy-wischusen/gaforflash,drflash/gaforflash,mrthuanvn/gaforflash,dli-iclinic/gaforflash,soumavachakraborty/gaforflash,Vigmar/gaforflash,mrthuanvn/gaforflash,Miyaru/gaforflash,drflash/gaforflash,Miyaru/gaforflash,jeremy-wischusen/gaforflash,minimedj/gaforflash,Vigmar/gaforflash,nsdevaraj/gaforflash,nsdevaraj/gaforflash,dli-iclinic/gaforflash,jisobkim/gaforflash,jisobkim/gaforflash,DimaBaliakin/gaforflash
|
46e54f2e89bcf81b9137cdba219d7322ee7055ad
|
vivified/core/vivi_initialize.as
|
vivified/core/vivi_initialize.as
|
/* Vivified
* Copyright (C) 2007 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
/*** general objects ***/
Wrap = function () {};
Wrap.prototype = {};
Wrap.prototype.toString = Native.wrap_toString;
Frame = function () extends Wrap {};
Frame.prototype = new Wrap ();
Frame.prototype.addProperty ("code", Native.frame_code_get, null);
Frame.prototype.addProperty ("name", Native.frame_name_get, null);
Frame.prototype.addProperty ("next", Native.frame_next_get, null);
/*** breakpoints ***/
Breakpoint = function () extends Native.Breakpoint {
super ();
Breakpoint.list.push (this);
};
Breakpoint.list = new Array ();
Breakpoint.prototype.addProperty ("active", Native.breakpoint_active_get, Native.breakpoint_active_set);
/*** information about the player ***/
Player = {};
Player.addProperty ("frame", Native.player_frame_get, null);
/*** commands available for debugging ***/
Commands = new Object ();
Commands.print = Native.print;
Commands.error = Native.error;
Commands.r = Native.run;
Commands.run = Native.run;
Commands.halt = Native.stop;
Commands.stop = Native.stop;
Commands.s = Native.step;
Commands.step = Native.step;
Commands.reset = Native.reset;
Commands.restart = function () {
Commands.reset ();
Commands.run ();
};
Commands.quit = Native.quit;
/* can't use "break" as a function name, it's a keyword in JS */
Commands.add = function (name) {
if (name == undefined) {
Commands.error ("add command requires a function name");
return undefined;
}
var ret = new Breakpoint ();
ret.onStartFrame = function (frame) {
if (frame.name != name)
return false;
Commands.print ("Breakpoint: function " + name + " called");
Commands.print (" " + frame);
return true;
};
ret.toString = function () {
return "function call " + name;
};
return ret;
};
Commands.list = function () {
var a = Breakpoint.list;
var i;
for (i = 0; i < a.length; i++) {
Commands.print (i + ": " + a[i]);
}
};
Commands.del = function (id) {
var a = Breakpoint.list;
if (id == undefined) {
while (a[0])
Commands.del (0);
}
var b = a[id];
a.splice (id, 1);
b.active = false;
};
Commands.delete = Commands.del;
|
/* Vivified
* Copyright (C) 2007 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
/*** general objects ***/
Wrap = function () {};
Wrap.prototype = {};
Wrap.prototype.toString = Native.wrap_toString;
Frame = function () extends Wrap {};
Frame.prototype = new Wrap ();
Frame.prototype.addProperty ("code", Native.frame_code_get, null);
Frame.prototype.addProperty ("name", Native.frame_name_get, null);
Frame.prototype.addProperty ("next", Native.frame_next_get, null);
/*** breakpoints ***/
Breakpoint = function () extends Native.Breakpoint {
super ();
Breakpoint.list.push (this);
};
Breakpoint.list = new Array ();
Breakpoint.prototype.addProperty ("active", Native.breakpoint_active_get, Native.breakpoint_active_set);
/*** information about the player ***/
Player = {};
Player.addProperty ("frame", Native.player_frame_get, null);
/*** commands available for debugging ***/
Commands = new Object ();
Commands.print = Native.print;
Commands.error = Native.error;
Commands.r = Native.run;
Commands.run = Native.run;
Commands.halt = Native.stop;
Commands.stop = Native.stop;
Commands.s = Native.step;
Commands.step = Native.step;
Commands.reset = Native.reset;
Commands.restart = function () {
Commands.reset ();
Commands.run ();
};
Commands.quit = Native.quit;
/* can't use "break" as a function name, it's a keyword in JS */
Commands.add = function (name) {
if (name == undefined) {
Commands.error ("add command requires a function name");
return undefined;
}
var ret = new Breakpoint ();
ret.onStartFrame = function (frame) {
if (frame.name != name)
return false;
Commands.print ("Breakpoint: function " + name + " called");
Commands.print (" " + frame);
return true;
};
ret.toString = function () {
return "function call " + name;
};
return ret;
};
Commands.list = function () {
var a = Breakpoint.list;
var i;
for (i = 0; i < a.length; i++) {
Commands.print (i + ": " + a[i]);
}
};
Commands.del = function (id) {
var a = Breakpoint.list;
if (id == undefined) {
while (a[0])
Commands.del (0);
}
var b = a[id];
a.splice (id, 1);
b.active = false;
};
Commands.delete = Commands.del;
Commands.where = function () {
var frame = Player.frame;
if (frame == undefined) {
print ("---");
return;
}
while (frame) {
print (frame);
frame = frame.next;
}
};
Commands.backtrace = Commands.where;
Commands.bt = Commands.where;
|
add backtrace function
|
add backtrace function
|
ActionScript
|
lgpl-2.1
|
mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec
|
49c88f498aeafb0dac7cd90a7aff1b91a157b87b
|
example/ExampleApp.as
|
example/ExampleApp.as
|
/*
* An exmaple app for Twitter for AS3
*
* copyright (c) 2015 Susisu
*/
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.net.navigateToURL;
import flash.net.URLRequest;
import isle.susisu.twitter.Twitter;
import isle.susisu.twitter.TwitterRequest;
import isle.susisu.twitter.events.TwitterRequestEvent;
import isle.susisu.twitter.events.TwitterErrorEvent;
[SWF(width="480", height="360", backgroundColor="0x000000", frameRate="60")]
public class ExampleApp extends Sprite
{
private var outputConsole:TextField;
private var openBrowserButton:Sprite;
private var pinInputField:TextField;
private var getAccessTokenButton:Sprite;
private var tweetInputField:TextField;
private var tweetButton:Sprite;
private var twitter:Twitter;
public function ExampleApp()
{
// Replace <consumer key> and <consumer key secret> with your app's
this.twitter = new Twitter("<consumer key>","<consumer key secret>");
// Create UI
// Output console
this.outputConsole = new TextField();
this.outputConsole.width = 480;
this.outputConsole.height = 180;
this.outputConsole.border = true;
this.outputConsole.background = true;
this.outputConsole.backgroundColor = 0xffffff;
this.outputConsole.text = "";
this.addChild(this.outputConsole);
// "Open browser" button
this.openBrowserButton = new Sprite();
var openBrowserButtonText:TextField = new TextField();
openBrowserButtonText.width = 80;
openBrowserButtonText.height = 20;
openBrowserButtonText.background = true;
openBrowserButtonText.backgroundColor = 0xc0c0c0;
openBrowserButtonText.border = true;
openBrowserButtonText.text = "Open browser";
this.openBrowserButton.addChild(openBrowserButtonText);
this.openBrowserButton.y = 180;
this.openBrowserButton.buttonMode = true;
this.openBrowserButton.mouseChildren = false;
this.addChild(this.openBrowserButton);
this.openBrowserButton.addEventListener(MouseEvent.CLICK, onOpenBrowserButtonClick);
// PIN input field
this.pinInputField = new TextField();
this.pinInputField.x = 80;
this.pinInputField.y = 180;
this.pinInputField.width = 200;
this.pinInputField.height = 20;
this.pinInputField.background = true;
this.pinInputField.backgroundColor = 0xffffff;
this.pinInputField.border = true;
this.pinInputField.type = TextFieldType.INPUT;
this.pinInputField.text = "Input PIN here";
this.addChild(this.pinInputField);
// "Get access token" button
this.getAccessTokenButton = new Sprite();
var getAccessTokenButtonText:TextField = new TextField();
getAccessTokenButtonText.width = 200;
getAccessTokenButtonText.height = 20;
getAccessTokenButtonText.background = true;
getAccessTokenButtonText.backgroundColor = 0xc0c0c0;
getAccessTokenButtonText.border = true;
getAccessTokenButtonText.text = "Get access tokens";
this.getAccessTokenButton.addChild(getAccessTokenButtonText);
this.getAccessTokenButton.x = 280;
this.getAccessTokenButton.y = 180;
this.getAccessTokenButton.buttonMode = true;
this.getAccessTokenButton.mouseChildren = false;
this.addChild(this.getAccessTokenButton);
this.getAccessTokenButton.addEventListener(MouseEvent.CLICK, onGetAccessTokenButtonClick);
// Tweet input field
this.tweetInputField = new TextField();
this.tweetInputField.y = 200;
this.tweetInputField.width = 480;
this.tweetInputField.height = 140;
this.tweetInputField.background = true;
this.tweetInputField.backgroundColor = 0xffffff;
this.tweetInputField.border = true;
this.tweetInputField.type = TextFieldType.INPUT;
this.tweetInputField.text = "Input your tweet here"
this.addChild(this.tweetInputField);
// Tweet button
this.tweetButton = new Sprite();
var tweetButtonText:TextField = new TextField();
tweetButtonText.width = 480;
tweetButtonText.height = 20;
tweetButtonText.background = true;
tweetButtonText.backgroundColor = 0xc0c0c0;
tweetButtonText.border = true;
tweetButtonText.text = "Tweet";
this.tweetButton.addChild(tweetButtonText);
this.tweetButton.y = 340;
this.tweetButton.buttonMode = true;
this.tweetButton.mouseChildren = false;
this.addChild(this.tweetButton);
this.tweetButton.addEventListener(MouseEvent.CLICK, onTweetButtonClick);
this.outputConsole.appendText("1. Click \"open browser\" button\n2. Authorize the app and get PIN\n3. Input PIN\n4. Get access tokens\n5. Tweet!\n");
}
// When the "open browser" button is clicked
private function onOpenBrowserButtonClick(event:MouseEvent):void
{
var request:TwitterRequest = this.twitter.oauth_requestToken();
request.addEventListener(TwitterRequestEvent.COMPLETE, onOAuthRequestTokenComplete);
request.addEventListener(TwitterErrorEvent.CLIENT_ERROR, onOAuthRequestTokenError);
request.addEventListener(TwitterErrorEvent.SERVER_ERROR, onOAuthRequestTokenError);
this.outputConsole.appendText("Please wait...\n");
}
// When oauth/request_token is complete
private function onOAuthRequestTokenComplete(event:TwitterRequestEvent):void
{
(event.target as TwitterRequest).removeEventListener(TwitterRequestEvent.COMPLETE, onOAuthRequestTokenComplete);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.CLIENT_ERROR, onOAuthRequestTokenError);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.SERVER_ERROR, onOAuthRequestTokenError);
// Open the authorization page in browser
navigateToURL(new URLRequest(this.twitter.getOAuthAuthorizeURL()));
this.outputConsole.appendText("Borwser opened: " + this.twitter.getOAuthAuthorizeURL() + "\n");
}
// When oauth/request_token failed
private function onOAuthRequestTokenError(event:TwitterErrorEvent):void
{
(event.target as TwitterRequest).removeEventListener(TwitterRequestEvent.COMPLETE, onOAuthRequestTokenComplete);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.CLIENT_ERROR, onOAuthRequestTokenError);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.SERVER_ERROR, onOAuthRequestTokenError);
this.outputConsole.appendText("Error: " + event.statusCode.toString() + "\n");
}
// When the "access token" button is clicked
private function onGetAccessTokenButtonClick(event:MouseEvent):void
{
// Send PIN
var request:TwitterRequest = this.twitter.oauth_accessToken(this.pinInputField.text);
request.addEventListener(TwitterRequestEvent.COMPLETE, onOAuthAccessTokenComplete);
request.addEventListener(TwitterErrorEvent.CLIENT_ERROR, onOAuthAccessTokenError);
request.addEventListener(TwitterErrorEvent.SERVER_ERROR, onOAuthAccessTokenError);
this.outputConsole.appendText("Please wait...\n");
}
// When oauth/access_token is complete
private function onOAuthAccessTokenComplete(event:TwitterRequestEvent):void
{
(event.target as TwitterRequest).removeEventListener(TwitterRequestEvent.COMPLETE, onOAuthAccessTokenComplete);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.CLIENT_ERROR, onOAuthAccessTokenError);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.SERVER_ERROR, onOAuthAccessTokenError);
this.pinInputField.text = "";
// Output the access token to the console
this.outputConsole.appendText("Access token: " + this.twitter.accessToken + "\n");
this.outputConsole.appendText("Access token secret: " + this.twitter.accessTokenSecret + "\n");
}
// When oauth/access_token failed
private function onOAuthAccessTokenError(event:TwitterErrorEvent):void
{
(event.target as TwitterRequest).removeEventListener(TwitterRequestEvent.COMPLETE, onOAuthAccessTokenComplete);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.CLIENT_ERROR, onOAuthAccessTokenError);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.SERVER_ERROR, onOAuthAccessTokenError);
this.outputConsole.appendText("Error: " + event.statusCode.toString() + "\n");
}
// When the tweet button is clicked
private function onTweetButtonClick(event:MouseEvent):void
{
// Send tweet
var request:TwitterRequest = this.twitter.statuses_update(this.tweetInputField.text);
request.addEventListener(TwitterRequestEvent.COMPLETE, onStatusesUpdateComplete);
request.addEventListener(TwitterErrorEvent.CLIENT_ERROR, onStatusesUpdateError);
request.addEventListener(TwitterErrorEvent.SERVER_ERROR, onStatusesUpdateError);
this.outputConsole.appendText("Please wait...\n");
}
// When tweet succeeded
private function onStatusesUpdateComplete(event:TwitterRequestEvent):void
{
(event.target as TwitterRequest).removeEventListener(TwitterRequestEvent.COMPLETE, onStatusesUpdateComplete);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.CLIENT_ERROR, onStatusesUpdateError);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.SERVER_ERROR, onStatusesUpdateError);
this.tweetInputField.text = "";
this.outputConsole.appendText("Tweeted!\n");
}
// When tweet failed
private function onStatusesUpdateError(event:TwitterErrorEvent):void
{
(event.target as TwitterRequest).removeEventListener(TwitterRequestEvent.COMPLETE, onStatusesUpdateComplete);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.CLIENT_ERROR, onStatusesUpdateError);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.SERVER_ERROR, onStatusesUpdateError);
this.outputConsole.appendText("Error: " + event.statusCode.toString() + "\n");
}
}
}
|
/*
* An exmaple app for Twitter for AS3
*
* copyright (c) 2015 Susisu
*/
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.net.navigateToURL;
import flash.net.URLRequest;
import isle.susisu.twitter.Twitter;
import isle.susisu.twitter.TwitterRequest;
import isle.susisu.twitter.events.TwitterRequestEvent;
import isle.susisu.twitter.events.TwitterErrorEvent;
[SWF(width="480", height="360", backgroundColor="0x000000", frameRate="60")]
public class ExampleApp extends Sprite
{
private var outputConsole:TextField;
private var openBrowserButton:Sprite;
private var pinInputField:TextField;
private var getAccessTokenButton:Sprite;
private var tweetInputField:TextField;
private var tweetButton:Sprite;
private var twitter:Twitter;
public function ExampleApp()
{
// Replace <consumer key> and <consumer key secret> with your app's
this.twitter = new Twitter("<consumer key>","<consumer key secret>");
// Create UI
// Output console
this.outputConsole = new TextField();
this.outputConsole.width = 480;
this.outputConsole.height = 180;
this.outputConsole.border = true;
this.outputConsole.background = true;
this.outputConsole.backgroundColor = 0xffffff;
this.outputConsole.text = "";
this.addChild(this.outputConsole);
// "Open browser" button
this.openBrowserButton = new Sprite();
var openBrowserButtonText:TextField = new TextField();
openBrowserButtonText.width = 80;
openBrowserButtonText.height = 20;
openBrowserButtonText.background = true;
openBrowserButtonText.backgroundColor = 0xc0c0c0;
openBrowserButtonText.border = true;
openBrowserButtonText.text = "Open browser";
this.openBrowserButton.addChild(openBrowserButtonText);
this.openBrowserButton.y = 180;
this.openBrowserButton.buttonMode = true;
this.openBrowserButton.mouseChildren = false;
this.addChild(this.openBrowserButton);
this.openBrowserButton.addEventListener(MouseEvent.CLICK, onOpenBrowserButtonClick);
// PIN input field
this.pinInputField = new TextField();
this.pinInputField.x = 80;
this.pinInputField.y = 180;
this.pinInputField.width = 200;
this.pinInputField.height = 20;
this.pinInputField.background = true;
this.pinInputField.backgroundColor = 0xffffff;
this.pinInputField.border = true;
this.pinInputField.type = TextFieldType.INPUT;
this.pinInputField.text = "Input PIN here";
this.addChild(this.pinInputField);
// "Get access token" button
this.getAccessTokenButton = new Sprite();
var getAccessTokenButtonText:TextField = new TextField();
getAccessTokenButtonText.width = 200;
getAccessTokenButtonText.height = 20;
getAccessTokenButtonText.background = true;
getAccessTokenButtonText.backgroundColor = 0xc0c0c0;
getAccessTokenButtonText.border = true;
getAccessTokenButtonText.text = "Get access tokens";
this.getAccessTokenButton.addChild(getAccessTokenButtonText);
this.getAccessTokenButton.x = 280;
this.getAccessTokenButton.y = 180;
this.getAccessTokenButton.buttonMode = true;
this.getAccessTokenButton.mouseChildren = false;
this.addChild(this.getAccessTokenButton);
this.getAccessTokenButton.addEventListener(MouseEvent.CLICK, onGetAccessTokenButtonClick);
// Tweet input field
this.tweetInputField = new TextField();
this.tweetInputField.y = 200;
this.tweetInputField.width = 480;
this.tweetInputField.height = 140;
this.tweetInputField.background = true;
this.tweetInputField.backgroundColor = 0xffffff;
this.tweetInputField.border = true;
this.tweetInputField.type = TextFieldType.INPUT;
this.tweetInputField.text = "Input your tweet here"
this.addChild(this.tweetInputField);
// Tweet button
this.tweetButton = new Sprite();
var tweetButtonText:TextField = new TextField();
tweetButtonText.width = 480;
tweetButtonText.height = 20;
tweetButtonText.background = true;
tweetButtonText.backgroundColor = 0xc0c0c0;
tweetButtonText.border = true;
tweetButtonText.text = "Tweet";
this.tweetButton.addChild(tweetButtonText);
this.tweetButton.y = 340;
this.tweetButton.buttonMode = true;
this.tweetButton.mouseChildren = false;
this.addChild(this.tweetButton);
this.tweetButton.addEventListener(MouseEvent.CLICK, onTweetButtonClick);
this.outputConsole.appendText("1. Click \"open browser\" button\n2. Authorize the app and get PIN\n3. Input PIN\n4. Get access tokens\n5. Tweet!\n");
}
// When the "open browser" button is clicked
private function onOpenBrowserButtonClick(event:MouseEvent):void
{
var request:TwitterRequest = this.twitter.oauth_requestToken();
request.addEventListener(TwitterRequestEvent.COMPLETE, onOAuthRequestTokenComplete);
request.addEventListener(TwitterErrorEvent.CLIENT_ERROR, onOAuthRequestTokenError);
request.addEventListener(TwitterErrorEvent.SERVER_ERROR, onOAuthRequestTokenError);
this.outputConsole.appendText("Please wait...\n");
}
// When oauth/request_token is complete
private function onOAuthRequestTokenComplete(event:TwitterRequestEvent):void
{
(event.target as TwitterRequest).removeEventListener(TwitterRequestEvent.COMPLETE, onOAuthRequestTokenComplete);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.CLIENT_ERROR, onOAuthRequestTokenError);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.SERVER_ERROR, onOAuthRequestTokenError);
// Open the authorization page in browser
navigateToURL(new URLRequest(this.twitter.getOAuthAuthorizeURL()));
this.outputConsole.appendText("Borwser opened: " + this.twitter.getOAuthAuthorizeURL() + "\n");
}
// When oauth/request_token failed
private function onOAuthRequestTokenError(event:TwitterErrorEvent):void
{
(event.target as TwitterRequest).removeEventListener(TwitterRequestEvent.COMPLETE, onOAuthRequestTokenComplete);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.CLIENT_ERROR, onOAuthRequestTokenError);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.SERVER_ERROR, onOAuthRequestTokenError);
this.outputConsole.appendText("Error: " + event.statusCode.toString() + "\n");
event.preventDefault();
}
// When the "access token" button is clicked
private function onGetAccessTokenButtonClick(event:MouseEvent):void
{
// Send PIN
var request:TwitterRequest = this.twitter.oauth_accessToken(this.pinInputField.text);
request.addEventListener(TwitterRequestEvent.COMPLETE, onOAuthAccessTokenComplete);
request.addEventListener(TwitterErrorEvent.CLIENT_ERROR, onOAuthAccessTokenError);
request.addEventListener(TwitterErrorEvent.SERVER_ERROR, onOAuthAccessTokenError);
this.outputConsole.appendText("Please wait...\n");
}
// When oauth/access_token is complete
private function onOAuthAccessTokenComplete(event:TwitterRequestEvent):void
{
(event.target as TwitterRequest).removeEventListener(TwitterRequestEvent.COMPLETE, onOAuthAccessTokenComplete);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.CLIENT_ERROR, onOAuthAccessTokenError);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.SERVER_ERROR, onOAuthAccessTokenError);
this.pinInputField.text = "";
// Output the access token to the console
this.outputConsole.appendText("Access token: " + this.twitter.accessToken + "\n");
this.outputConsole.appendText("Access token secret: " + this.twitter.accessTokenSecret + "\n");
}
// When oauth/access_token failed
private function onOAuthAccessTokenError(event:TwitterErrorEvent):void
{
(event.target as TwitterRequest).removeEventListener(TwitterRequestEvent.COMPLETE, onOAuthAccessTokenComplete);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.CLIENT_ERROR, onOAuthAccessTokenError);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.SERVER_ERROR, onOAuthAccessTokenError);
this.outputConsole.appendText("Error: " + event.statusCode.toString() + "\n");
event.preventDefault();
}
// When the tweet button is clicked
private function onTweetButtonClick(event:MouseEvent):void
{
// Send tweet
var request:TwitterRequest = this.twitter.statuses_update(this.tweetInputField.text);
request.addEventListener(TwitterRequestEvent.COMPLETE, onStatusesUpdateComplete);
request.addEventListener(TwitterErrorEvent.CLIENT_ERROR, onStatusesUpdateError);
request.addEventListener(TwitterErrorEvent.SERVER_ERROR, onStatusesUpdateError);
this.outputConsole.appendText("Please wait...\n");
}
// When tweet succeeded
private function onStatusesUpdateComplete(event:TwitterRequestEvent):void
{
(event.target as TwitterRequest).removeEventListener(TwitterRequestEvent.COMPLETE, onStatusesUpdateComplete);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.CLIENT_ERROR, onStatusesUpdateError);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.SERVER_ERROR, onStatusesUpdateError);
this.tweetInputField.text = "";
this.outputConsole.appendText("Tweeted!\n");
}
// When tweet failed
private function onStatusesUpdateError(event:TwitterErrorEvent):void
{
(event.target as TwitterRequest).removeEventListener(TwitterRequestEvent.COMPLETE, onStatusesUpdateComplete);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.CLIENT_ERROR, onStatusesUpdateError);
(event.target as TwitterRequest).removeEventListener(TwitterErrorEvent.SERVER_ERROR, onStatusesUpdateError);
this.outputConsole.appendText("Error: " + event.statusCode.toString() + "\n");
event.preventDefault();
}
}
}
|
Fix missing preventDefault() for error events
|
Fix missing preventDefault() for error events
|
ActionScript
|
mit
|
susisu/Twitter-for-AS3
|
7db39eb9957bc3f2e071c1c03c764bdf8ad46350
|
src/goplayer/SkinPlayerView.as
|
src/goplayer/SkinPlayerView.as
|
package goplayer
{
import flash.display.DisplayObject
import flash.display.DisplayObjectContainer
import flash.display.Sprite
import flash.text.TextField
import flash.events.MouseEvent
import flash.utils.getQualifiedClassName
import flash.utils.describeType
public class SkinPlayerView extends ResizableSprite
implements PlayerVideoUpdateListener
{
private const overlay : Background
= new Background(0x000000, 0.5)
private const bufferingIndicator : BufferingIndicator
= new BufferingIndicator
private var skin : WrappedSkin
private var video : PlayerVideo
private var player : Player
public function SkinPlayerView
(skin : WrappedSkin, video : PlayerVideo, player : Player)
{
this.skin = skin
this.video = video
this.player = player
onclick(skin.playButton, handlePlayButtonClicked)
onclick(skin.pauseButton, handlePauseButtonClicked)
onclick(skin.enableFullscreenButton, handleEnableFullscreenButtonClicked)
onclick(skin.muteButton, handleMuteButtonClicked)
onclick(skin.unmuteButton, handleUnmuteButtonClicked)
addChild(video)
addChild(overlay)
addChild(bufferingIndicator)
addChild(skin.root)
video.addUpdateListener(this)
}
private function handlePlayButtonClicked() : void
{
if (player.started)
player.paused = false
else
player.start()
}
private function handlePauseButtonClicked() : void
{ player.paused = true }
private function handleMuteButtonClicked() : void
{ player.mute() }
private function handleUnmuteButtonClicked() : void
{ player.unmute() }
private function handleEnableFullscreenButtonClicked() : void
{ video.toggleFullscreen() }
override public function set dimensions(value : Dimensions) : void
{ video.normalDimensions = value }
public function handlePlayerVideoUpdated() : void
{
setDimensions(skin.root, video.dimensions)
skin.bufferRatio = player.bufferRatio
skin.playheadRatio = player.playheadRatio
video.visible = !player.finished
skin.playButton.visible = playButtonVisible
skin.pauseButton.visible = !playButtonVisible
skin.muteButton.visible = !player.muted
skin.unmuteButton.visible = player.muted
skin.leftTimeField.text = leftTimeLabel
skin.rightTimeField.text = rightTimeLabel
setBounds(overlay, video.videoPosition, video.videoDimensions)
overlay.visible = player.buffering
setPosition(bufferingIndicator, video.videoDimensions.halved.asPosition)
bufferingIndicator.size = video.videoDimensions.innerSquare.width / 3
bufferingIndicator.ratio = player.bufferFillRatio
bufferingIndicator.visible = player.buffering
if (bufferingIndicator.visible)
bufferingIndicator.update()
}
private function get leftTimeLabel() : String
{ return player.playheadPosition.mss }
private function get rightTimeLabel() : String
{ return player.streamLength.minus(player.playheadPosition).mss }
private function get playButtonVisible() : Boolean
{ return !player.started || player.paused || player.finished }
private function get videoWidth() : Number
{ return video.videoDimensions.width }
private function get videoLeft() : Number
{ return video.videoPosition.x }
private function get videoBottom() : Number
{ return video.videoPosition.plus(video.videoDimensions).y }
}
}
|
package goplayer
{
import flash.display.DisplayObject
import flash.display.DisplayObjectContainer
import flash.display.Sprite
import flash.text.TextField
import flash.events.MouseEvent
import flash.utils.getQualifiedClassName
import flash.utils.describeType
public class SkinPlayerView extends ResizableSprite
implements PlayerVideoUpdateListener
{
private const overlay : Background
= new Background(0x000000, 0.5)
private const bufferingIndicator : BufferingIndicator
= new BufferingIndicator
private var skin : WrappedSkin
private var video : PlayerVideo
private var player : Player
public function SkinPlayerView
(skin : WrappedSkin, video : PlayerVideo, player : Player)
{
this.skin = skin
this.video = video
this.player = player
onclick(skin.playButton, handlePlayButtonClicked)
onclick(skin.pauseButton, handlePauseButtonClicked)
onclick(skin.enableFullscreenButton, handleEnableFullscreenButtonClicked)
onclick(skin.muteButton, handleMuteButtonClicked)
onclick(skin.unmuteButton, handleUnmuteButtonClicked)
addChild(video)
addChild(overlay)
addChild(bufferingIndicator)
addChild(skin.root)
skin.root.visible = false
video.addUpdateListener(this)
}
private function handlePlayButtonClicked() : void
{
if (player.started)
player.paused = false
else
player.start()
}
private function handlePauseButtonClicked() : void
{ player.paused = true }
private function handleMuteButtonClicked() : void
{ player.mute() }
private function handleUnmuteButtonClicked() : void
{ player.unmute() }
private function handleEnableFullscreenButtonClicked() : void
{ video.toggleFullscreen() }
override public function set dimensions(value : Dimensions) : void
{ video.normalDimensions = value }
public function handlePlayerVideoUpdated() : void
{
setDimensions(skin.root, video.dimensions)
skin.root.visible = true
skin.bufferRatio = player.bufferRatio
skin.playheadRatio = player.playheadRatio
video.visible = !player.finished
skin.playButton.visible = playButtonVisible
skin.pauseButton.visible = !playButtonVisible
skin.muteButton.visible = !player.muted
skin.unmuteButton.visible = player.muted
skin.leftTimeField.text = leftTimeLabel
skin.rightTimeField.text = rightTimeLabel
setBounds(overlay, video.videoPosition, video.videoDimensions)
overlay.visible = player.buffering
setPosition(bufferingIndicator, video.videoDimensions.halved.asPosition)
bufferingIndicator.size = video.videoDimensions.innerSquare.width / 3
bufferingIndicator.ratio = player.bufferFillRatio
bufferingIndicator.visible = player.buffering
if (bufferingIndicator.visible)
bufferingIndicator.update()
}
private function get leftTimeLabel() : String
{ return player.playheadPosition.mss }
private function get rightTimeLabel() : String
{ return player.streamLength.minus(player.playheadPosition).mss }
private function get playButtonVisible() : Boolean
{ return !player.started || player.paused || player.finished }
private function get videoWidth() : Number
{ return video.videoDimensions.width }
private function get videoLeft() : Number
{ return video.videoPosition.x }
private function get videoBottom() : Number
{ return video.videoPosition.plus(video.videoDimensions).y }
}
}
|
Hide the skin while it is being initialized.
|
Hide the skin while it is being initialized.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
97640c9700d4e3272e1d13de67f02f72e0f22a2c
|
src/org/igniterealtime/xiff/core/XMPPBOSHConnection.as
|
src/org/igniterealtime/xiff/core/XMPPBOSHConnection.as
|
/*
* License
*/
package org.igniterealtime.xiff.core
{
import flash.events.TimerEvent;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.logging.ILogger;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import org.igniterealtime.xiff.events.*;
import org.igniterealtime.xiff.logging.LoggerFactory;
import org.igniterealtime.xiff.util.Callback;
/**
* Bidirectional-streams Over Synchronous HTTP (BOSH)
* @see http://xmpp.org/extensions/xep-0206.html
*/
public class XMPPBOSHConnection extends XMPPConnection
{
private static const BOSH_VERSION:String = "1.6";
private static const HTTPS_PORT:int = 7443;
private static const HTTP_PORT:int = 7070;
private static const headers:Object = {
"post": [],
"get": [ 'Cache-Control',
'no-store',
'Cache-Control',
'no-cache',
'Pragma', 'no-cache' ]
};
private static const logger:ILogger = LoggerFactory.getLogger( "org.igniterealtime.xiff.core.XMPPBOSHConnection" );
private var _boshPath:String = "http-bind/";
private var _hold:uint = 1;
private var _maxConcurrentRequests:uint = 2;
private var _port:Number;
private var _secure:Boolean;
private var _wait:uint = 20;
private var boshPollingInterval:uint = 10000;
private var inactivity:uint;
private var isDisconnecting:Boolean = false;
private var lastPollTime:Date = null;
private var maxPause:uint;
private var pauseEnabled:Boolean = false;
private var pauseTimer:Timer;
private var pollingEnabled:Boolean = false;
private var requestCount:int = 0;
private var requestQueue:Array = [];
private var responseQueue:Array = [];
private const responseTimer:Timer = new Timer( 0.0, 1 );
private var rid:Number;
private var sid:String;
private var streamRestarted:Boolean;
/**
*
* @param secure
*/
public function XMPPBOSHConnection( secure:Boolean = false ):void
{
super();
this.secure = secure;
}
override public function connect( streamType:String = null ):Boolean
{
logger.debug( "BOSH connect()" );
var attrs:Object = {
"xml:lang": "en",
"xmlns": "http://jabber.org/protocol/httpbind",
"xmlns:xmpp": "urn:xmpp:xbosh",
"xmpp:version": "1.0",
"hold": hold,
"rid": nextRID,
"secure": secure,
"wait": wait,
"ver": BOSH_VERSION,
"to": domain
};
var result:XMLNode = new XMLNode( 1, "body" );
result.attributes = attrs;
sendRequests( result );
return true;
}
override public function disconnect():void
{
if ( active )
{
var data:XMLNode = createRequest();
data.attributes.type = "terminate";
sendRequests( data );
active = false;
loggedIn = false;
dispatchEvent( new DisconnectionEvent());
}
}
/**
* @return true if pause request is sent
*/
public function pauseSession( seconds:uint ):Boolean
{
logger.debug( "Pausing session for {0} seconds", seconds );
var pauseDuration:uint = seconds * 1000;
if ( !pauseEnabled || pauseDuration > maxPause || pauseDuration <= boshPollingInterval )
return false;
pollingEnabled = false;
var data:XMLNode = createRequest();
data.attributes[ "pause" ] = seconds;
sendRequests( data );
pauseTimer = new Timer( pauseDuration - 2000, 1 );
pauseTimer.addEventListener( TimerEvent.TIMER, handlePauseTimeout );
pauseTimer.start();
return true;
}
public function processConnectionResponse( responseBody:XMLNode ):void
{
dispatchEvent( new ConnectionSuccessEvent());
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
wait = attributes.wait;
if ( attributes.polling )
{
boshPollingInterval = attributes.polling * 1000;
}
if ( attributes.inactivity )
{
inactivity = attributes.inactivity * 1000;
}
if ( attributes.maxpause )
{
maxPause = attributes.maxpause * 1000;
pauseEnabled = true;
}
if ( attributes.requests )
{
maxConcurrentRequests = attributes.requests;
}
logger.debug( "Polling interval: {0}", boshPollingInterval );
logger.debug( "Inactivity timeout: {0}", inactivity );
logger.debug( "Max requests: {0}", maxConcurrentRequests );
logger.debug( "Max pause: {0}", maxPause );
active = true;
addEventListener( LoginEvent.LOGIN, handleLogin );
responseTimer.addEventListener( TimerEvent.TIMER_COMPLETE, processResponse );
}
//do nothing, we use polling instead
override public function sendKeepAlive():void
{
}
override protected function restartStream():void
{
var data:XMLNode = createRequest();
data.attributes[ "xmpp:restart" ] = "true";
data.attributes[ "xmlns:xmpp" ] = "urn:xmpp:xbosh";
data.attributes[ "xml:lang" ] = "en";
data.attributes[ "to" ] = domain;
sendRequests( data );
streamRestarted = true;
}
override protected function sendXML( body:* ):void
{
sendQueuedRequests( body );
}
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 handleLogin( e:LoginEvent ):void
{
pollingEnabled = true;
pollServer();
}
private function handlePauseTimeout( event:TimerEvent ):void
{
logger.debug( "handlePauseTimeout" );
pollingEnabled = true;
pollServer();
}
private function httpError( req:XMLNode, isPollResponse:Boolean, event:FaultEvent ):void
{
disconnect();
dispatchError( "Unknown HTTP Error", event.fault.rootCause.text, "",
-1 );
}
private function httpResponse( req:XMLNode, isPollResponse:Boolean, event:ResultEvent ):void
{
requestCount--;
var rawXML:String = event.result as String;
logger.info( "INCOMING {0}", rawXML );
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
xmlData.parseXML( rawXML );
var bodyNode:XMLNode = xmlData.firstChild;
var byteData:ByteArray = new ByteArray();
byteData.writeUTFBytes(xmlData.toString());
var incomingEvent:IncomingDataEvent = new IncomingDataEvent();
incomingEvent.data = byteData;
dispatchEvent( incomingEvent );
if ( streamRestarted && !bodyNode.hasChildNodes())
{
streamRestarted = false;
bindConnection();
}
if ( bodyNode.attributes[ "type" ] == "terminate" )
{
dispatchError( "BOSH Error", bodyNode.attributes[ "condition" ],
"", -1 );
active = false;
}
if ( bodyNode.attributes[ "sid" ] && !loggedIn )
{
processConnectionResponse( bodyNode );
var featuresFound:Boolean = false;
for each ( var child:XMLNode in bodyNode.childNodes )
{
if ( child.nodeName == "stream:features" )
featuresFound = true;
}
if ( !featuresFound )
{
pollingEnabled = true;
pollServer();
}
}
for each ( var childNode:XMLNode in bodyNode.childNodes )
{
responseQueue.push( childNode );
}
resetResponseProcessor();
//if we have no outstanding requests, then we're free to send a poll at the next opportunity
if ( requestCount == 0 && !sendQueuedRequests())
pollServer();
}
private function pollServer():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() || !pollingEnabled || sendQueuedRequests() || requestCount >
0 )
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()
sendRequests( null, true );
}
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":
handleStreamFeatures( currentNode );
streamRestarted = false; //avoid triggering the old server workaround
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;
case "failure":
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 sendQueuedRequests( body:* = null ):Boolean
{
if ( body )
{
requestQueue.push( body );
}
else if ( requestQueue.length == 0 )
{
return false;
}
return sendRequests();
}
//returns true if any requests were sent
private function sendRequests( data:XMLNode = null, isPoll:Boolean = false ):Boolean
{
if ( requestCount >= maxConcurrentRequests )
{
return false;
}
requestCount++;
if ( !data )
{
if ( isPoll )
{
data = createRequest();
}
else
{
var temp:Array = [];
for ( var i:uint = 0; i < 10 && requestQueue.length > 0; ++i )
{
temp.push( requestQueue.shift());
}
data = createRequest( temp );
}
}
// TODO: Could this be replaced with URLLoader ?
//build the http request
var request:HTTPService = new HTTPService();
request.method = "post";
request.headers = headers[ request.method ];
request.url = httpServer;
request.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
request.contentType = "text/xml";
var responseCallback:Callback = new Callback( this, httpResponse, data,
isPoll );
var errorCallback:Callback = new Callback( this, httpError, data, isPoll );
request.addEventListener( ResultEvent.RESULT, responseCallback.call,
false );
request.addEventListener( FaultEvent.FAULT, errorCallback.call, false );
request.send( data );
var byteData:ByteArray = new ByteArray();
byteData.writeUTFBytes(data.toString());
var event:OutgoingDataEvent = new OutgoingDataEvent();
event.data = byteData;
dispatchEvent( event );
if ( isPoll )
{
lastPollTime = new Date();
logger.info( "Polling" );
}
logger.info( "OUTGOING {0}", data );
return true;
}
public function get boshPath():String
{
return _boshPath;
}
public function set boshPath( value:String ):void
{
_boshPath = value;
}
private function get nextRID():Number
{
if ( !rid )
rid = Math.floor( Math.random() * 1000000 );
return ++rid;
}
public function get wait():uint
{
return _wait;
}
public function set wait( value:uint ):void
{
_wait = value;
}
public function get secure():Boolean
{
return _secure;
}
public function set secure( flag:Boolean ):void
{
logger.debug( "set secure: {0}", flag );
_secure = flag;
port = _secure ? HTTPS_PORT : HTTP_PORT;
}
override public function get port():Number
{
return _port;
}
override public function set port( portnum:Number ):void
{
logger.debug( "set port: {0}", portnum );
_port = portnum;
}
public function get hold():uint
{
return _hold;
}
public function set hold( value:uint ):void
{
_hold = value;
}
public function get httpServer():String
{
return ( secure ? "https" : "http" ) + "://" + server + ":" + port +
"/" + boshPath;
}
public function get maxConcurrentRequests():uint
{
return _maxConcurrentRequests;
}
public function set maxConcurrentRequests( value:uint ):void
{
_maxConcurrentRequests = value;
}
}
}
|
/*
* License
*/
package org.igniterealtime.xiff.core
{
import flash.events.*;
import flash.net.*;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.logging.ILogger;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import org.igniterealtime.xiff.events.*;
import org.igniterealtime.xiff.logging.LoggerFactory;
import org.igniterealtime.xiff.util.Callback;
/**
* Bidirectional-streams Over Synchronous HTTP (BOSH)
* @see http://xmpp.org/extensions/xep-0206.html
*/
public class XMPPBOSHConnection extends XMPPConnection
{
private static const BOSH_VERSION:String = "1.6";
private static const HTTPS_PORT:int = 7443;
private static const HTTP_PORT:int = 7070;
/**
* Keys should match URLRequestMethod constants.
*/
private static const headers:Object = {
"post": [],
"get": [ 'Cache-Control',
'no-store',
'Cache-Control',
'no-cache',
'Pragma', 'no-cache' ]
};
private static const logger:ILogger = LoggerFactory.getLogger( "org.igniterealtime.xiff.core.XMPPBOSHConnection" );
private var _boshPath:String = "http-bind/";
private var _hold:uint = 1;
private var _maxConcurrentRequests:uint = 2;
private var _port:Number;
private var _secure:Boolean;
private var _wait:uint = 20;
private var boshPollingInterval:uint = 10000;
private var inactivity:uint;
private var isDisconnecting:Boolean = false;
private var lastPollTime:Date = null;
private var maxPause:uint;
private var pauseEnabled:Boolean = false;
private var pauseTimer:Timer;
private var pollingEnabled:Boolean = false;
private var requestCount:int = 0;
private var requestQueue:Array = [];
private var responseQueue:Array = [];
private var responseTimer:Timer;
private var rid:Number;
private var sid:String;
private var streamRestarted:Boolean;
/**
*
* @param secure
*/
public function XMPPBOSHConnection( secure:Boolean = false ):void
{
super();
this.secure = secure;
responseTimer = new Timer( 0.0, 1 );
}
override public function connect( streamType:String = null ):Boolean
{
logger.debug( "BOSH connect()" );
var attrs:Object = {
"xml:lang": "en",
"xmlns": "http://jabber.org/protocol/httpbind",
"xmlns:xmpp": "urn:xmpp:xbosh",
"xmpp:version": "1.0",
"hold": hold,
"rid": nextRID,
"secure": secure,
"wait": wait,
"ver": BOSH_VERSION,
"to": domain
};
var result:XMLNode = new XMLNode( 1, "body" );
result.attributes = attrs;
sendRequests( result );
return true;
}
override public function disconnect():void
{
if ( active )
{
var data:XMLNode = createRequest();
data.attributes.type = "terminate";
sendRequests( data );
active = false;
loggedIn = false;
dispatchEvent( new DisconnectionEvent());
}
}
/**
* @return true if pause request is sent
*/
public function pauseSession( seconds:uint ):Boolean
{
logger.debug( "Pausing session for {0} seconds", seconds );
var pauseDuration:uint = seconds * 1000;
if ( !pauseEnabled || pauseDuration > maxPause || pauseDuration <= boshPollingInterval )
return false;
pollingEnabled = false;
var data:XMLNode = createRequest();
data.attributes[ "pause" ] = seconds;
sendRequests( data );
pauseTimer = new Timer( pauseDuration - 2000, 1 );
pauseTimer.addEventListener( TimerEvent.TIMER, handlePauseTimeout );
pauseTimer.start();
return true;
}
public function processConnectionResponse( responseBody:XMLNode ):void
{
dispatchEvent( new ConnectionSuccessEvent());
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
wait = attributes.wait;
if ( attributes.polling )
{
boshPollingInterval = attributes.polling * 1000;
}
if ( attributes.inactivity )
{
inactivity = attributes.inactivity * 1000;
}
if ( attributes.maxpause )
{
maxPause = attributes.maxpause * 1000;
pauseEnabled = true;
}
if ( attributes.requests )
{
maxConcurrentRequests = attributes.requests;
}
logger.debug( "Polling interval: {0}", boshPollingInterval );
logger.debug( "Inactivity timeout: {0}", inactivity );
logger.debug( "Max requests: {0}", maxConcurrentRequests );
logger.debug( "Max pause: {0}", maxPause );
active = true;
addEventListener( LoginEvent.LOGIN, handleLogin );
responseTimer.addEventListener( TimerEvent.TIMER_COMPLETE, processResponse );
}
//do nothing, we use polling instead
override public function sendKeepAlive():void
{
}
override protected function restartStream():void
{
var data:XMLNode = createRequest();
data.attributes[ "xmpp:restart" ] = "true";
data.attributes[ "xmlns:xmpp" ] = "urn:xmpp:xbosh";
data.attributes[ "xml:lang" ] = "en";
data.attributes[ "to" ] = domain;
sendRequests( data );
streamRestarted = true;
}
override protected function sendXML( body:* ):void
{
sendQueuedRequests( body );
}
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 handleLogin( e:LoginEvent ):void
{
pollingEnabled = true;
pollServer();
}
private function handlePauseTimeout( event:TimerEvent ):void
{
logger.debug( "handlePauseTimeout" );
pollingEnabled = true;
pollServer();
}
private function httpError( req:XMLNode, isPollResponse:Boolean, event:FaultEvent ):void
{
disconnect();
dispatchError( "Unknown HTTP Error", event.fault.rootCause.text, "",
-1 );
}
private function httpResponse( req:XMLNode, isPollResponse:Boolean, event:ResultEvent ):void
{
requestCount--;
var rawXML:String = event.result as String;
logger.info( "INCOMING {0}", rawXML );
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
xmlData.parseXML( rawXML );
var bodyNode:XMLNode = xmlData.firstChild;
var byteData:ByteArray = new ByteArray();
byteData.writeUTFBytes(xmlData.toString());
var incomingEvent:IncomingDataEvent = new IncomingDataEvent();
incomingEvent.data = byteData;
dispatchEvent( incomingEvent );
if ( streamRestarted && !bodyNode.hasChildNodes())
{
streamRestarted = false;
bindConnection();
}
if ( bodyNode.attributes[ "type" ] == "terminate" )
{
dispatchError( "BOSH Error", bodyNode.attributes[ "condition" ],
"", -1 );
active = false;
}
if ( bodyNode.attributes[ "sid" ] && !loggedIn )
{
processConnectionResponse( bodyNode );
var featuresFound:Boolean = false;
for each ( var child:XMLNode in bodyNode.childNodes )
{
if ( child.nodeName == "stream:features" )
featuresFound = true;
}
if ( !featuresFound )
{
pollingEnabled = true;
pollServer();
}
}
for each ( var childNode:XMLNode in bodyNode.childNodes )
{
responseQueue.push( childNode );
}
resetResponseProcessor();
//if we have no outstanding requests, then we're free to send a poll at the next opportunity
if ( requestCount == 0 && !sendQueuedRequests())
pollServer();
}
private function pollServer():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() || !pollingEnabled || sendQueuedRequests() || requestCount >
0 )
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()
sendRequests( null, true );
}
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":
handleStreamFeatures( currentNode );
streamRestarted = false; //avoid triggering the old server workaround
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;
case "failure":
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 sendQueuedRequests( body:* = null ):Boolean
{
if ( body )
{
requestQueue.push( body );
}
else if ( requestQueue.length == 0 )
{
return false;
}
return sendRequests();
}
//returns true if any requests were sent
private function sendRequests( data:XMLNode = null, isPoll:Boolean = false ):Boolean
{
if ( requestCount >= maxConcurrentRequests )
{
return false;
}
requestCount++;
if ( !data )
{
if ( isPoll )
{
data = createRequest();
}
else
{
var temp:Array = [];
for ( var i:uint = 0; i < 10 && requestQueue.length > 0; ++i )
{
temp.push( requestQueue.shift());
}
data = createRequest( temp );
}
}
/*
var req:URLRequest = new URLRequest(httpServer);
req.method = URLRequestMethod.POST;
req.contentType = "text/xml";
req.requestHeaders = headers[ req.method ];
req.data = data;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, onRequestComplete);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, socketSecurityError);
loader.addEventListener(IOErrorEvent.IO_ERROR, socketIOError);
loader.load(req);
*/
// TODO: Could this be replaced with URLLoader ?
//build the http request
var request:HTTPService = new HTTPService();
request.method = "post";
request.headers = headers[ request.method ];
request.url = httpServer;
request.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
request.contentType = "text/xml";
var responseCallback:Callback = new Callback( this, httpResponse, data,
isPoll );
var errorCallback:Callback = new Callback( this, httpError, data, isPoll );
request.addEventListener( ResultEvent.RESULT, responseCallback.call,
false );
request.addEventListener( FaultEvent.FAULT, errorCallback.call, false );
request.send( data );
var byteData:ByteArray = new ByteArray();
byteData.writeUTFBytes(data.toString());
var event:OutgoingDataEvent = new OutgoingDataEvent();
event.data = byteData;
dispatchEvent( event );
if ( isPoll )
{
lastPollTime = new Date();
logger.info( "Polling" );
}
logger.info( "OUTGOING {0}", data );
return true;
}
public function get boshPath():String
{
return _boshPath;
}
public function set boshPath( value:String ):void
{
_boshPath = value;
}
private function get nextRID():Number
{
if ( !rid )
rid = Math.floor( Math.random() * 1000000 );
return ++rid;
}
public function get wait():uint
{
return _wait;
}
public function set wait( value:uint ):void
{
_wait = value;
}
public function get secure():Boolean
{
return _secure;
}
public function set secure( flag:Boolean ):void
{
logger.debug( "set secure: {0}", flag );
_secure = flag;
port = _secure ? HTTPS_PORT : HTTP_PORT;
}
override public function get port():Number
{
return _port;
}
override public function set port( portnum:Number ):void
{
logger.debug( "set port: {0}", portnum );
_port = portnum;
}
public function get hold():uint
{
return _hold;
}
public function set hold( value:uint ):void
{
_hold = value;
}
public function get httpServer():String
{
return ( secure ? "https" : "http" ) + "://" + server + ":" + port +
"/" + boshPath;
}
public function get maxConcurrentRequests():uint
{
return _maxConcurrentRequests;
}
public function set maxConcurrentRequests( value:uint ):void
{
_maxConcurrentRequests = value;
}
}
}
|
Rewrite work in progress...
|
Rewrite work in progress...
|
ActionScript
|
apache-2.0
|
igniterealtime/XIFF
|
7f382df453b084eeb581b21e78385101c84f2513
|
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 com.adobe.crypto.MD5;
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;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
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;
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;
const numMovieFrames :int = movie.frames;
for each (var layer :LayerMold in movie.layers) {
for each (var kf :KeyframeMold in layer.keyframes) {
var swfTexture :SwfTexture = null;
if (movie.flipbook) {
try {
swfTexture = SwfTexture.fromFlipbook(this, movie, kf.index)
} catch (e :Error) {
addTopLevelError(ParseError.CRIT, "Error creating flipbook texture from '" + movie.id + "'");
swfTexture = null;
}
} 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) {
const tex :XflTexture = XflTexture(item);
try {
swfTexture = SwfTexture.fromTexture(this.swf, tex);
} catch (e :Error) {
addTopLevelError(ParseError.CRIT, "Error creating texture '" + tex.symbol + "'");
swfTexture = null;
}
}
}
if (swfTexture != null) {
// Texture symbols have origins. For texture layer keyframes,
// we combine the texture's origin with the keyframe's pivot point.
kf.pivotX += swfTexture.origin.x;
kf.pivotY += swfTexture.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.connect(function (data :ByteArray) :void {
md5 = MD5.hashBytes(data);
const loadSwf :Future = new SwfLoader().loadFromBytes(data);
loadSwf.succeeded.connect(function (loadedSwf :LoadedSwf) :void {
swf = loadedSwf;
});
loadSwf.failed.connect(function (error :Error) :void {
addTopLevelError(ParseError.CRIT, error.message, error);
});
loadSwf.completed.connect(onComplete.succeed);
});
loadSwfFile.failed.connect(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 com.adobe.crypto.MD5;
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;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
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;
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) {
var swfTexture :SwfTexture = null;
if (movie.flipbook) {
try {
swfTexture = SwfTexture.fromFlipbook(this, movie, kf.index)
} catch (e :Error) {
addTopLevelError(ParseError.CRIT, "Error creating flipbook texture from '" + movie.id + "'");
swfTexture = null;
}
} 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) {
const tex :XflTexture = XflTexture(item);
try {
swfTexture = SwfTexture.fromTexture(this.swf, tex);
} catch (e :Error) {
addTopLevelError(ParseError.CRIT, "Error creating texture '" + tex.symbol + "'");
swfTexture = null;
}
}
}
if (swfTexture != null) {
// Texture symbols have origins. For texture layer keyframes,
// we combine the texture's origin with the keyframe's pivot point.
kf.pivotX += swfTexture.origin.x;
kf.pivotY += swfTexture.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.connect(function (data :ByteArray) :void {
md5 = MD5.hashBytes(data);
const loadSwf :Future = new SwfLoader().loadFromBytes(data);
loadSwf.succeeded.connect(function (loadedSwf :LoadedSwf) :void {
swf = loadedSwf;
});
loadSwf.failed.connect(function (error :Error) :void {
addTopLevelError(ParseError.CRIT, error.message, error);
});
loadSwf.completed.connect(onComplete.succeed);
});
loadSwfFile.failed.connect(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);
}
}
|
remove unused variable
|
remove unused variable
|
ActionScript
|
mit
|
mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,funkypandagame/flump,tconkling/flump
|
7a589c14d68d97d31591193f099e28f1ad3cc6e8
|
src/org/jivesoftware/xiff/core/XMPPSocketConnection.as
|
src/org/jivesoftware/xiff/core/XMPPSocketConnection.as
|
/*
* Copyright (C) 2003-2007
* Nick Velloff <[email protected]>
* Derrick Grigg <[email protected]>
* Sean Voisen <[email protected]>
* Sean Treadway <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jivesoftware.xiff.core
{
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.logging.ILogger;
import org.jivesoftware.xiff.events.*;
import org.jivesoftware.xiff.logging.LoggerFactory;
import org.jivesoftware.xiff.util.SocketConn;
import org.jivesoftware.xiff.util.SocketDataEvent;
/**
* A child of <code>XMPPConnection</code>, this class makes use of the
* Flash AVM2 binary socket instead of the older <code>XMLSocket</code>.
* This gets rid of issues related to the <code>XMLSocket</code>'s appending
* of a null-byte to all outgoing data.
*
* @see org.jivesoftware.xiff.core.XMPPConnection
*/
public class XMPPSocketConnection extends XMPPConnection
{
private static const logger:ILogger = LoggerFactory.getLogger("org.jivesoftware.xiff.core.XMPPSocketConnection");
private var _incompleteRawXML: String = '';
protected var binarySocket:SocketConn;
public function XMPPSocketConnection()
{
super();
configureSocket();
}
private function configureSocket():void {
binarySocket = new SocketConn();
binarySocket.addEventListener(Event.CLOSE, socketClosed);
binarySocket.addEventListener(Event.CONNECT, socketConnected);
binarySocket.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
binarySocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
binarySocket.addEventListener(SocketDataEvent.SOCKET_DATA_RECEIVED, bSocketReceivedData);
}
override protected function sendXML( someData:* ):void
{
logger.info("OUTGOING: {0}", someData);
// Data is untyped because it could be a string or XML
binarySocket.sendString(someData);
var event:OutgoingDataEvent = new OutgoingDataEvent();
event.data = someData;
dispatchEvent( event );
}
override public function disconnect():void
{
if( isActive() ) {
sendXML( closingStreamTag );
binarySocket.close();
active = false;
loggedIn = false;
var event:DisconnectionEvent = new DisconnectionEvent();
dispatchEvent(event);
}
}
override public function connect( streamType:String = "terminatedStandard" ):Boolean
{
active = false;
loggedIn = false;
// Stream type lets user set opening/closing tag - some servers (jadc2s) prefer <stream:flash> to the standard
// <stream:stream>
switch( streamType ) {
case "flash":
openingStreamTag = "<?xml version=\"1.0\"?><flash:stream to=\"" + domain + "\" xmlns=\"jabber:client\" xmlns:flash=\"http://www.jabber.com/streams/flash\" version=\"1.0\">";
closingStreamTag = "</flash:stream>";
break;
case "terminatedFlash":
openingStreamTag = "<?xml version=\"1.0\"?><flash:stream to=\"" + domain + "\" xmlns=\"jabber:client\" xmlns:flash=\"http://www.jabber.com/streams/flash\" version=\"1.0\" />";
closingStreamTag = "</flash:stream>";
break;
case "standard":
openingStreamTag = "<?xml version=\"1.0\"?><stream:stream to=\"" + domain + "\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">";
closingStreamTag = "</stream:stream>";
break;
case "terminatedStandard":
default:
openingStreamTag = "<?xml version=\"1.0\"?><stream:stream to=\"" + domain + "\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\" />";
closingStreamTag = "</stream:stream>";
break;
}
binarySocket.connect( server, port );
return true;
}
protected function bSocketReceivedData( ev:SocketDataEvent ):void
{
var rawXML:String = _incompleteRawXML + ev.data as String;
logger.info("INCOMING: {0}", rawXML);
// parseXML is more strict in AS3 so we must check for the presence of flash:stream
// the unterminated tag should be in the first string of xml data retured from the server
if (!_expireTagSearch)
{
var pattern:RegExp = new RegExp("<flash:stream");
var resultObj:Object = pattern.exec(rawXML);
if (resultObj != null) // stop searching for unterminated node
{
rawXML = rawXML.concat("</flash:stream>");
_expireTagSearch = true;
}
}
if (!_expireTagSearch)
{
var pattern2:RegExp = new RegExp("<stream:stream");
var resultObj2:Object = pattern2.exec(rawXML);
if (resultObj2 != null) // stop searching for unterminated node
{
rawXML = rawXML.concat("</stream:stream>");
_expireTagSearch = true;
}
}
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
//error handling to catch incomplete xml strings that have
//been truncated by the socket
try{
var isComplete: Boolean = true;
xmlData.parseXML( rawXML );
_incompleteRawXML = '';
}
catch(err:Error){
isComplete = false;
_incompleteRawXML += ev.data as String;//concatenate the raw xml to the previous xml
}
if (isComplete){
var event:IncomingDataEvent = new IncomingDataEvent();
event.data = xmlData;
dispatchEvent( event );
for (var i:int = 0; i<xmlData.childNodes.length; i++)
{
// Read the data and send it to the appropriate parser
var currentNode:XMLNode = xmlData.childNodes[i];
var nodeName:String = currentNode.nodeName.toLowerCase();
switch( nodeName )
{
case "stream:stream":
_expireTagSearch = false;
handleStream( currentNode );
break;
case "flash:stream":
_expireTagSearch = false;
handleStream( currentNode );
break;
case "stream:error":
handleStreamError( currentNode );
break;
case "iq":
handleIQ( currentNode );
break;
case "message":
handleMessage( currentNode );
break;
case "presence":
handlePresence( currentNode );
break;
default:
dispatchError( "undefined-condition", "Unknown Error", "modify", 500 );
break;
}
}
}
}
}
}
|
/*
* Copyright (C) 2003-2007
* Nick Velloff <[email protected]>
* Derrick Grigg <[email protected]>
* Sean Voisen <[email protected]>
* Sean Treadway <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jivesoftware.xiff.core
{
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.logging.ILogger;
import org.jivesoftware.xiff.events.*;
import org.jivesoftware.xiff.logging.LoggerFactory;
import org.jivesoftware.xiff.util.SocketConn;
import org.jivesoftware.xiff.util.SocketDataEvent;
/**
* A child of <code>XMPPConnection</code>, this class makes use of the
* Flash AVM2 binary socket instead of the older <code>XMLSocket</code>.
* This gets rid of issues related to the <code>XMLSocket</code>'s appending
* of a null-byte to all outgoing data.
*
* @see org.jivesoftware.xiff.core.XMPPConnection
*/
public class XMPPSocketConnection extends XMPPConnection
{
private static const logger:ILogger = LoggerFactory.getLogger("org.jivesoftware.xiff.core.XMPPSocketConnection");
private var _incompleteRawXML: String = '';
protected var binarySocket:SocketConn;
public function XMPPSocketConnection()
{
super();
configureSocket();
}
private function configureSocket():void {
binarySocket = new SocketConn();
binarySocket.addEventListener(Event.CLOSE, socketClosed);
binarySocket.addEventListener(Event.CONNECT, socketConnected);
binarySocket.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
binarySocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
binarySocket.addEventListener(SocketDataEvent.SOCKET_DATA_RECEIVED, bSocketReceivedData);
}
override protected function sendXML( someData:* ):void
{
logger.info("OUTGOING: {0}", someData);
// Data is untyped because it could be a string or XML
binarySocket.sendString(someData);
var event:OutgoingDataEvent = new OutgoingDataEvent();
event.data = someData;
dispatchEvent( event );
}
override public function disconnect():void
{
if( isActive() ) {
sendXML( closingStreamTag );
binarySocket.close();
active = false;
loggedIn = false;
var event:DisconnectionEvent = new DisconnectionEvent();
dispatchEvent(event);
}
}
override public function connect( streamType:String = "terminatedStandard" ):Boolean
{
active = false;
loggedIn = false;
// Stream type lets user set opening/closing tag - some servers (jadc2s) prefer <stream:flash> to the standard
// <stream:stream>
switch( streamType ) {
case "flash":
openingStreamTag = "<?xml version=\"1.0\"?><flash:stream to=\"" + domain + "\" xmlns=\"jabber:client\" xmlns:flash=\"http://www.jabber.com/streams/flash\" version=\"1.0\">";
closingStreamTag = "</flash:stream>";
break;
case "terminatedFlash":
openingStreamTag = "<?xml version=\"1.0\"?><flash:stream to=\"" + domain + "\" xmlns=\"jabber:client\" xmlns:flash=\"http://www.jabber.com/streams/flash\" version=\"1.0\" />";
closingStreamTag = "</flash:stream>";
break;
case "standard":
openingStreamTag = "<?xml version=\"1.0\"?><stream:stream to=\"" + domain + "\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">";
closingStreamTag = "</stream:stream>";
break;
case "terminatedStandard":
default:
openingStreamTag = "<?xml version=\"1.0\"?><stream:stream to=\"" + domain + "\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\" />";
closingStreamTag = "</stream:stream>";
break;
}
binarySocket.connect( server, port );
return true;
}
protected function bSocketReceivedData( ev:SocketDataEvent ):void
{
var rawXML:String = _incompleteRawXML + ev.data as String;
logger.info("INCOMING: {0}", rawXML);
// parseXML is more strict in AS3 so we must check for the presence of flash:stream
// the unterminated tag should be in the first string of xml data retured from the server
if (!_expireTagSearch)
{
var pattern:RegExp = new RegExp("<flash:stream");
var resultObj:Object = pattern.exec(rawXML);
if (resultObj != null) // stop searching for unterminated node
{
rawXML = rawXML.concat("</flash:stream>");
_expireTagSearch = true;
}
}
if (!_expireTagSearch)
{
var pattern2:RegExp = new RegExp("<stream:stream");
var resultObj2:Object = pattern2.exec(rawXML);
if (resultObj2 != null) // stop searching for unterminated node
{
rawXML = rawXML.concat("</stream:stream>");
_expireTagSearch = true;
}
}
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
//error handling to catch incomplete xml strings that have
//been truncated by the socket
try{
var isComplete: Boolean = true;
xmlData.parseXML( rawXML );
_incompleteRawXML = '';
}
catch(err:Error){
isComplete = false;
_incompleteRawXML += ev.data as String;//concatenate the raw xml to the previous xml
}
if (isComplete){
var event:IncomingDataEvent = new IncomingDataEvent();
event.data = xmlData;
dispatchEvent( event );
for (var i:int = 0; i<xmlData.childNodes.length; i++)
{
// Read the data and send it to the appropriate parser
var currentNode:XMLNode = xmlData.childNodes[i];
var nodeName:String = currentNode.nodeName.toLowerCase();
switch( nodeName )
{
case "stream:stream":
_expireTagSearch = false;
handleStream( currentNode );
break;
case "flash:stream":
_expireTagSearch = false;
handleStream( currentNode );
break;
case "stream:error":
handleStreamError( currentNode );
break;
case "iq":
handleIQ( currentNode );
break;
case "message":
handleMessage( currentNode );
break;
case "presence":
handlePresence( currentNode );
break;
case "stream:features":
handleStreamFeatures( currentNode );
break;
case "success":
handleAuthentication( currentNode );
break;
case "failure":
handleAuthentication( currentNode );
break;
default:
dispatchError( "undefined-condition", "Unknown Error", "modify", 500 );
break;
}
}
}
}
}
}
|
Allow XMPPSocketConnection to handle the stream:features packet.
|
Allow XMPPSocketConnection to handle the stream:features packet.
git-svn-id: c197267f952b24206666de142881703007ca05d5@10749 b35dd754-fafc-0310-a699-88a17e54d16e
|
ActionScript
|
apache-2.0
|
nazoking/xiff
|
57b77ce01ce29567005e2a05490f9faaf25d02c3
|
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;
// 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));
});
s_r.addEventListener(ProgressEvent.SOCKET_DATA, relay_to_client);
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));
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, client_to_relay);
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.");
}
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
{
if (flush_id)
clearTimeout(flush_id);
flush_id = undefined;
if (!(s_r.connected && s_c.connected))
/* Can't do anything until both sockets are connected. */
return;
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");
}
/* Call again when safe, if necessary. */
if (r2c_schedule.length > 0 || c2r_schedule.length > 0)
flush_id = setTimeout(flush, ui.rate_limit.when() * 1000);
}
}
|
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. Set to undefined to disable limit.
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();
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY);
else
rate_limit = new RateUnlimit();
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
{
public function RateLimit()
{
}
public function update(n:Number):Boolean
{
return true;
}
public function when():Number
{
return 0.0;
}
public function is_limited():Boolean
{
return false;
}
}
class RateUnlimit extends RateLimit
{
public function RateUnlimit()
{
}
public override function update(n:Number):Boolean
{
return true;
}
public override function when():Number
{
return 0.0;
}
public override function is_limited():Boolean
{
return false;
}
}
class BucketRateLimit extends RateLimit
{
private var amount:Number;
private var capacity:Number;
private var time:Number;
private var last_update:uint;
public function BucketRateLimit(capacity:Number, time:Number)
{
this.amount = 0.0;
/* capacity / time is the rate we are aiming for. */
this.capacity = capacity;
this.time = time;
this.last_update = getTimer();
}
private function age():void
{
var now:uint;
var delta:Number;
now = getTimer();
delta = (now - last_update) / 1000.0;
last_update = now;
amount -= delta * capacity / time;
if (amount < 0.0)
amount = 0.0;
}
public override function update(n:Number):Boolean
{
age();
amount += n;
return amount <= capacity;
}
public override function when():Number
{
age();
return (amount - capacity) / (capacity / time);
}
public override function is_limited():Boolean
{
age();
return amount > capacity;
}
}
/* 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));
});
s_r.addEventListener(ProgressEvent.SOCKET_DATA, relay_to_client);
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));
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, client_to_relay);
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.");
}
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
{
if (flush_id)
clearTimeout(flush_id);
flush_id = undefined;
if (!(s_r.connected && s_c.connected))
/* Can't do anything until both sockets are connected. */
return;
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");
}
/* 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 RateUnlimit implementation of RateLimit.
|
Add a RateUnlimit implementation of RateLimit.
|
ActionScript
|
mit
|
glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy
|
a28e541d4d824c1650f1a2d374b543dd9fa7ba0d
|
src/org/mangui/hls/stream/HLSNetStream.as
|
src/org/mangui/hls/stream/HLSNetStream.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.stream {
import org.mangui.hls.controller.BufferThresholdController;
import org.mangui.hls.event.HLSPlayMetrics;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.constant.HLSSeekStates;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
import org.mangui.hls.utils.Hex;
import flash.events.Event;
import flash.events.NetStatusEvent;
import flash.events.TimerEvent;
import flash.net.*;
import flash.utils.*;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that overrides standard flash.net.NetStream class, keeps the buffer filled, handles seek and play state
*
* play state transition :
* FROM TO condition
* HLSPlayStates.IDLE HLSPlayStates.PLAYING_BUFFERING play()/play2()/seek() called
* HLSPlayStates.PLAYING_BUFFERING HLSPlayStates.PLAYING buflen > minBufferLength
* HLSPlayStates.PAUSED_BUFFERING HLSPlayStates.PAUSED buflen > minBufferLength
* HLSPlayStates.PLAYING HLSPlayStates.PLAYING_BUFFERING buflen < lowBufferLength
* HLSPlayStates.PAUSED HLSPlayStates.PAUSED_BUFFERING buflen < lowBufferLength
*/
public class HLSNetStream extends NetStream {
/** Reference to the framework controller. **/
private var _hls : HLS;
/** reference to buffer threshold controller */
private var _bufferThresholdController : BufferThresholdController;
/** FLV Tag Buffer . **/
private var _streamBuffer : StreamBuffer;
/** Timer used to check buffer and position. **/
private var _timer : Timer;
/** Current playback state. **/
private var _playbackState : String;
/** Current seek state. **/
private var _seekState : String;
/** current playback level **/
private var _playbackLevel : int;
/** Netstream client proxy */
private var _client : HLSNetStreamClient;
/** Create the buffer. **/
public function HLSNetStream(connection : NetConnection, hls : HLS, streamBuffer : StreamBuffer) : void {
super(connection);
super.bufferTime = 0.1;
_hls = hls;
_bufferThresholdController = new BufferThresholdController(hls);
_streamBuffer = streamBuffer;
_playbackState = HLSPlayStates.IDLE;
_seekState = HLSSeekStates.IDLE;
_timer = new Timer(100, 0);
_timer.addEventListener(TimerEvent.TIMER, _checkBuffer);
_client = new HLSNetStreamClient();
_client.registerCallback("onHLSFragmentChange", onHLSFragmentChange);
_client.registerCallback("onID3Data", onID3Data);
super.client = _client;
};
public function onHLSFragmentChange(level : int, seqnum : int, cc : int, audio_only : Boolean, program_date : Number, width : int, height : int, ... tags) : void {
CONFIG::LOGGING {
Log.debug("playing fragment(level/sn/cc):" + level + "/" + seqnum + "/" + cc);
}
_playbackLevel = level;
var tag_list : Array = new Array();
for (var i : uint = 0; i < tags.length; i++) {
tag_list.push(tags[i]);
CONFIG::LOGGING {
Log.debug("custom tag:" + tags[i]);
}
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.FRAGMENT_PLAYING, new HLSPlayMetrics(level, seqnum, cc, audio_only, program_date, width, height, tag_list)));
}
// function is called by SCRIPT in FLV
public function onID3Data(data : ByteArray) : void {
var dump : String = "unset";
// we dump the content as hex to get it to the Javascript in the browser.
// from lots of searching, we could use base64, but even then, the decode would
// not be native, so hex actually seems more efficient
dump = Hex.fromArray(data);
CONFIG::LOGGING {
Log.debug("id3:" + dump);
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.ID3_UPDATED, dump));
}
/** timer function, check/update NetStream state, and append tags if needed **/
private function _checkBuffer(e : Event) : void {
var buffer : Number = this.bufferLength;
// Log.info("netstream/total:" + super.bufferLength + "/" + this.bufferLength);
// Set playback state. no need to check buffer status if seeking
if (_seekState != HLSSeekStates.SEEKING) {
// check low buffer condition
if (buffer <= 0.1) {
if (_streamBuffer.reachedEnd) {
// Last tag done? Then append sequence end.
super.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE);
super.appendBytes(new ByteArray());
// reach end of playlist + playback complete (as buffer is empty).
// stop timer, report event and switch to IDLE mode.
_timer.stop();
CONFIG::LOGGING {
Log.debug("reached end of VOD playlist, notify playback complete");
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_COMPLETE));
_setPlaybackState(HLSPlayStates.IDLE);
_setSeekState(HLSSeekStates.IDLE);
return;
} else {
// buffer <= 0.1 and not EOS, pause playback
super.pause();
}
}
// if buffer len is below lowBufferLength, get into buffering state
if (!_streamBuffer.reachedEnd && buffer < _bufferThresholdController.lowBufferLength) {
if (_playbackState == HLSPlayStates.PLAYING) {
// low buffer condition and play state. switch to play buffering state
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
} else if (_playbackState == HLSPlayStates.PAUSED) {
// low buffer condition and pause state. switch to paused buffering state
_setPlaybackState(HLSPlayStates.PAUSED_BUFFERING);
}
}
// if buffer len is above minBufferLength, get out of buffering state
if (buffer >= _bufferThresholdController.minBufferLength || _streamBuffer.reachedEnd) {
if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) {
CONFIG::LOGGING {
Log.debug("resume playback");
}
// resume playback in case it was paused, this can happen if buffer was in really low condition (less than 0.1s)
super.resume();
_setPlaybackState(HLSPlayStates.PLAYING);
} else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) {
_setPlaybackState(HLSPlayStates.PAUSED);
}
}
}
};
/** Return the current playback state. **/
public function get playbackState() : String {
return _playbackState;
};
/** Return the current seek state. **/
public function get seekState() : String {
return _seekState;
};
/** Return the current playback quality level **/
public function get playbackLevel() : int {
return _playbackLevel;
};
/** append tags to NetStream **/
public function appendTags(tags : Vector.<FLVTag>) : void {
if (_seekState == HLSSeekStates.SEEKING) {
/* this is our first injection after seek(),
let's flush netstream now
this is to avoid black screen during seek command */
super.close();
CONFIG::FLASH_11_1 {
try {
super.useHardwareDecoder = HLSSettings.useHardwareVideoDecoder;
} catch(e : Error) {
}
}
super.play(null);
super.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK);
// immediatly pause NetStream, it will be resumed when enough data will be buffered in the NetStream
super.pause();
// for each (var tag : FLVTag in tags) {
// CONFIG::LOGGING {
// Log.debug2('inject type/dts/pts:' + tag.typeString + '/' + tag.dts + '/' + tag.pts);
// }
// }
}
// append all tags
for each (var tagBuffer : FLVTag in tags) {
try {
if (tagBuffer.type == FLVTag.DISCONTINUITY) {
super.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
super.appendBytes(FLVTag.getHeader());
}
super.appendBytes(tagBuffer.data);
} catch (error : Error) {
var hlsError : HLSError = new HLSError(HLSError.TAG_APPENDING_ERROR, null, tagBuffer.type + ": " + error.message);
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
}
}
if (_seekState == HLSSeekStates.SEEKING) {
// dispatch event to mimic NetStream behaviour
dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, {code:"NetStream.Seek.Notify", level:"status"}));
_setSeekState(HLSSeekStates.SEEKED);
}
};
/** Change playback state. **/
private function _setPlaybackState(state : String) : void {
if (state != _playbackState) {
CONFIG::LOGGING {
Log.debug('[PLAYBACK_STATE] from ' + _playbackState + ' to ' + state);
}
_playbackState = state;
_hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_STATE, _playbackState));
}
};
/** Change seeking state. **/
private function _setSeekState(state : String) : void {
if (state != _seekState) {
CONFIG::LOGGING {
Log.debug('[SEEK_STATE] from ' + _seekState + ' to ' + state);
}
_seekState = state;
_hls.dispatchEvent(new HLSEvent(HLSEvent.SEEK_STATE, _seekState));
}
};
override public function play(...args) : void {
var _playStart : Number;
if (args.length >= 2) {
_playStart = Number(args[1]);
} else {
_playStart = -1;
}
CONFIG::LOGGING {
Log.info("HLSNetStream:play(" + _playStart + ")");
}
seek(_playStart);
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
}
override public function play2(param : NetStreamPlayOptions) : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:play2(" + param.start + ")");
}
seek(param.start);
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
}
/** Pause playback. **/
override public function pause() : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:pause");
}
if (_playbackState == HLSPlayStates.PLAYING) {
super.pause();
_setPlaybackState(HLSPlayStates.PAUSED);
} else if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) {
super.pause();
_setPlaybackState(HLSPlayStates.PAUSED_BUFFERING);
}
};
/** Resume playback. **/
override public function resume() : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:resume");
}
if (_playbackState == HLSPlayStates.PAUSED) {
super.resume();
_setPlaybackState(HLSPlayStates.PLAYING);
} else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) {
// dont resume NetStream here, it will be resumed by Timer. this avoids resuming playback while seeking is in progress
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
}
};
/** get Buffer Length **/
override public function get bufferLength() : Number {
return netStreamBufferLength + _streamBuffer.bufferLength;
};
/** get Back Buffer Length **/
override public function get backBufferLength() : Number {
return _streamBuffer.backBufferLength;
};
public function get netStreamBufferLength() : Number {
if (_seekState == HLSSeekStates.SEEKING) {
return 0;
} else {
return super.bufferLength;
}
};
/** Start playing data in the buffer. **/
override public function seek(position : Number) : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:seek(" + position + ")");
}
_streamBuffer.seek(position);
_setSeekState(HLSSeekStates.SEEKING);
/* if HLS was in paused state before seeking,
* switch to paused buffering state
* otherwise, switch to playing buffering state
*/
switch(_playbackState) {
case HLSPlayStates.PAUSED:
case HLSPlayStates.PAUSED_BUFFERING:
_setPlaybackState(HLSPlayStates.PAUSED_BUFFERING);
break;
case HLSPlayStates.IDLE:
case HLSPlayStates.PLAYING:
case HLSPlayStates.PLAYING_BUFFERING:
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
break;
default:
break;
}
/* always pause NetStream while seeking, even if we are in play state
* in that case, NetStream will be resumed during next call to appendTags()
*/
super.pause();
_timer.start();
};
public override function set client(client : Object) : void {
_client.delegate = client;
};
public override function get client() : Object {
return _client.delegate;
}
/** Stop playback. **/
override public function close() : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:close");
}
super.close();
_streamBuffer.stop();
_timer.stop();
_setPlaybackState(HLSPlayStates.IDLE);
_setSeekState(HLSSeekStates.IDLE);
};
public function dispose_() : void {
close();
_bufferThresholdController.dispose();
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.stream {
import org.mangui.hls.controller.BufferThresholdController;
import org.mangui.hls.event.HLSPlayMetrics;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.constant.HLSSeekStates;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
import org.mangui.hls.utils.Hex;
import flash.events.Event;
import flash.events.NetStatusEvent;
import flash.events.TimerEvent;
import flash.net.*;
import flash.utils.*;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that overrides standard flash.net.NetStream class, keeps the buffer filled, handles seek and play state
*
* play state transition :
* FROM TO condition
* HLSPlayStates.IDLE HLSPlayStates.PLAYING_BUFFERING play()/play2()/seek() called
* HLSPlayStates.PLAYING_BUFFERING HLSPlayStates.PLAYING buflen > minBufferLength
* HLSPlayStates.PAUSED_BUFFERING HLSPlayStates.PAUSED buflen > minBufferLength
* HLSPlayStates.PLAYING HLSPlayStates.PLAYING_BUFFERING buflen < lowBufferLength
* HLSPlayStates.PAUSED HLSPlayStates.PAUSED_BUFFERING buflen < lowBufferLength
*/
public class HLSNetStream extends NetStream {
/** Reference to the framework controller. **/
private var _hls : HLS;
/** reference to buffer threshold controller */
private var _bufferThresholdController : BufferThresholdController;
/** FLV Tag Buffer . **/
private var _streamBuffer : StreamBuffer;
/** Timer used to check buffer and position. **/
private var _timer : Timer;
/** Current playback state. **/
private var _playbackState : String;
/** Current seek state. **/
private var _seekState : String;
/** current playback level **/
private var _playbackLevel : int;
/** Netstream client proxy */
private var _client : HLSNetStreamClient;
/** Create the buffer. **/
public function HLSNetStream(connection : NetConnection, hls : HLS, streamBuffer : StreamBuffer) : void {
super(connection);
super.bufferTime = 0.1;
_hls = hls;
_bufferThresholdController = new BufferThresholdController(hls);
_streamBuffer = streamBuffer;
_playbackState = HLSPlayStates.IDLE;
_seekState = HLSSeekStates.IDLE;
_timer = new Timer(100, 0);
_timer.addEventListener(TimerEvent.TIMER, _checkBuffer);
_client = new HLSNetStreamClient();
_client.registerCallback("onHLSFragmentChange", onHLSFragmentChange);
_client.registerCallback("onID3Data", onID3Data);
super.client = _client;
};
public function onHLSFragmentChange(level : int, seqnum : int, cc : int, audio_only : Boolean, program_date : Number, width : int, height : int, ... tags) : void {
CONFIG::LOGGING {
Log.debug("playing fragment(level/sn/cc):" + level + "/" + seqnum + "/" + cc);
}
_playbackLevel = level;
var tag_list : Array = new Array();
for (var i : uint = 0; i < tags.length; i++) {
tag_list.push(tags[i]);
CONFIG::LOGGING {
Log.debug("custom tag:" + tags[i]);
}
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.FRAGMENT_PLAYING, new HLSPlayMetrics(level, seqnum, cc, audio_only, program_date, width, height, tag_list)));
}
// function is called by SCRIPT in FLV
public function onID3Data(data : ByteArray) : void {
// we dump the content as hex to get it to the Javascript in the browser.
// from lots of searching, we could use base64, but even then, the decode would
// not be native, so hex actually seems more efficient
var dump : String = Hex.fromArray(data);
CONFIG::LOGGING {
Log.debug("id3:" + dump);
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.ID3_UPDATED, dump));
}
/** timer function, check/update NetStream state, and append tags if needed **/
private function _checkBuffer(e : Event) : void {
var buffer : Number = this.bufferLength;
// Log.info("netstream/total:" + super.bufferLength + "/" + this.bufferLength);
// Set playback state. no need to check buffer status if seeking
if (_seekState != HLSSeekStates.SEEKING) {
// check low buffer condition
if (buffer <= 0.1) {
if (_streamBuffer.reachedEnd) {
// Last tag done? Then append sequence end.
super.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE);
super.appendBytes(new ByteArray());
// reach end of playlist + playback complete (as buffer is empty).
// stop timer, report event and switch to IDLE mode.
_timer.stop();
CONFIG::LOGGING {
Log.debug("reached end of VOD playlist, notify playback complete");
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_COMPLETE));
_setPlaybackState(HLSPlayStates.IDLE);
_setSeekState(HLSSeekStates.IDLE);
return;
} else {
// buffer <= 0.1 and not EOS, pause playback
super.pause();
}
}
// if buffer len is below lowBufferLength, get into buffering state
if (!_streamBuffer.reachedEnd && buffer < _bufferThresholdController.lowBufferLength) {
if (_playbackState == HLSPlayStates.PLAYING) {
// low buffer condition and play state. switch to play buffering state
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
} else if (_playbackState == HLSPlayStates.PAUSED) {
// low buffer condition and pause state. switch to paused buffering state
_setPlaybackState(HLSPlayStates.PAUSED_BUFFERING);
}
}
// if buffer len is above minBufferLength, get out of buffering state
if (buffer >= _bufferThresholdController.minBufferLength || _streamBuffer.reachedEnd) {
if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) {
CONFIG::LOGGING {
Log.debug("resume playback");
}
// resume playback in case it was paused, this can happen if buffer was in really low condition (less than 0.1s)
super.resume();
_setPlaybackState(HLSPlayStates.PLAYING);
} else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) {
_setPlaybackState(HLSPlayStates.PAUSED);
}
}
}
};
/** Return the current playback state. **/
public function get playbackState() : String {
return _playbackState;
};
/** Return the current seek state. **/
public function get seekState() : String {
return _seekState;
};
/** Return the current playback quality level **/
public function get playbackLevel() : int {
return _playbackLevel;
};
/** append tags to NetStream **/
public function appendTags(tags : Vector.<FLVTag>) : void {
if (_seekState == HLSSeekStates.SEEKING) {
/* this is our first injection after seek(),
let's flush netstream now
this is to avoid black screen during seek command */
super.close();
CONFIG::FLASH_11_1 {
try {
super.useHardwareDecoder = HLSSettings.useHardwareVideoDecoder;
} catch(e : Error) {
}
}
super.play(null);
super.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK);
// immediatly pause NetStream, it will be resumed when enough data will be buffered in the NetStream
super.pause();
// for each (var tag : FLVTag in tags) {
// CONFIG::LOGGING {
// Log.debug2('inject type/dts/pts:' + tag.typeString + '/' + tag.dts + '/' + tag.pts);
// }
// }
}
// append all tags
for each (var tagBuffer : FLVTag in tags) {
try {
if (tagBuffer.type == FLVTag.DISCONTINUITY) {
super.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
super.appendBytes(FLVTag.getHeader());
}
super.appendBytes(tagBuffer.data);
} catch (error : Error) {
var hlsError : HLSError = new HLSError(HLSError.TAG_APPENDING_ERROR, null, tagBuffer.type + ": " + error.message);
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
}
}
if (_seekState == HLSSeekStates.SEEKING) {
// dispatch event to mimic NetStream behaviour
dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, {code:"NetStream.Seek.Notify", level:"status"}));
_setSeekState(HLSSeekStates.SEEKED);
}
};
/** Change playback state. **/
private function _setPlaybackState(state : String) : void {
if (state != _playbackState) {
CONFIG::LOGGING {
Log.debug('[PLAYBACK_STATE] from ' + _playbackState + ' to ' + state);
}
_playbackState = state;
_hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_STATE, _playbackState));
}
};
/** Change seeking state. **/
private function _setSeekState(state : String) : void {
if (state != _seekState) {
CONFIG::LOGGING {
Log.debug('[SEEK_STATE] from ' + _seekState + ' to ' + state);
}
_seekState = state;
_hls.dispatchEvent(new HLSEvent(HLSEvent.SEEK_STATE, _seekState));
}
};
override public function play(...args) : void {
var _playStart : Number;
if (args.length >= 2) {
_playStart = Number(args[1]);
} else {
_playStart = -1;
}
CONFIG::LOGGING {
Log.info("HLSNetStream:play(" + _playStart + ")");
}
seek(_playStart);
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
}
override public function play2(param : NetStreamPlayOptions) : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:play2(" + param.start + ")");
}
seek(param.start);
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
}
/** Pause playback. **/
override public function pause() : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:pause");
}
if (_playbackState == HLSPlayStates.PLAYING) {
super.pause();
_setPlaybackState(HLSPlayStates.PAUSED);
} else if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) {
super.pause();
_setPlaybackState(HLSPlayStates.PAUSED_BUFFERING);
}
};
/** Resume playback. **/
override public function resume() : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:resume");
}
if (_playbackState == HLSPlayStates.PAUSED) {
super.resume();
_setPlaybackState(HLSPlayStates.PLAYING);
} else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) {
// dont resume NetStream here, it will be resumed by Timer. this avoids resuming playback while seeking is in progress
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
}
};
/** get Buffer Length **/
override public function get bufferLength() : Number {
return netStreamBufferLength + _streamBuffer.bufferLength;
};
/** get Back Buffer Length **/
override public function get backBufferLength() : Number {
return _streamBuffer.backBufferLength;
};
public function get netStreamBufferLength() : Number {
if (_seekState == HLSSeekStates.SEEKING) {
return 0;
} else {
return super.bufferLength;
}
};
/** Start playing data in the buffer. **/
override public function seek(position : Number) : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:seek(" + position + ")");
}
_streamBuffer.seek(position);
_setSeekState(HLSSeekStates.SEEKING);
/* if HLS was in paused state before seeking,
* switch to paused buffering state
* otherwise, switch to playing buffering state
*/
switch(_playbackState) {
case HLSPlayStates.PAUSED:
case HLSPlayStates.PAUSED_BUFFERING:
_setPlaybackState(HLSPlayStates.PAUSED_BUFFERING);
break;
case HLSPlayStates.IDLE:
case HLSPlayStates.PLAYING:
case HLSPlayStates.PLAYING_BUFFERING:
_setPlaybackState(HLSPlayStates.PLAYING_BUFFERING);
break;
default:
break;
}
/* always pause NetStream while seeking, even if we are in play state
* in that case, NetStream will be resumed during next call to appendTags()
*/
super.pause();
_timer.start();
};
public override function set client(client : Object) : void {
_client.delegate = client;
};
public override function get client() : Object {
return _client.delegate;
}
/** Stop playback. **/
override public function close() : void {
CONFIG::LOGGING {
Log.info("HLSNetStream:close");
}
super.close();
_streamBuffer.stop();
_timer.stop();
_setPlaybackState(HLSPlayStates.IDLE);
_setSeekState(HLSSeekStates.IDLE);
};
public function dispose_() : void {
close();
_bufferThresholdController.dispose();
}
}
}
|
remove useless assignement
|
remove useless assignement
|
ActionScript
|
mpl-2.0
|
aevange/flashls,neilrackett/flashls,aevange/flashls,JulianPena/flashls,dighan/flashls,aevange/flashls,Boxie5/flashls,dighan/flashls,suuhas/flashls,thdtjsdn/flashls,vidible/vdb-flashls,neilrackett/flashls,Peer5/flashls,suuhas/flashls,jlacivita/flashls,Corey600/flashls,Corey600/flashls,aevange/flashls,loungelogic/flashls,hola/flashls,fixedmachine/flashls,vidible/vdb-flashls,Peer5/flashls,tedconf/flashls,clappr/flashls,fixedmachine/flashls,hola/flashls,NicolasSiver/flashls,NicolasSiver/flashls,Boxie5/flashls,mangui/flashls,suuhas/flashls,suuhas/flashls,tedconf/flashls,mangui/flashls,codex-corp/flashls,Peer5/flashls,JulianPena/flashls,clappr/flashls,thdtjsdn/flashls,codex-corp/flashls,jlacivita/flashls,Peer5/flashls,loungelogic/flashls
|
19e372c1f2d8d867155c125d6386c7ce825181ef
|
src/com/merlinds/miracle_tool/views/alerts/AlertView.as
|
src/com/merlinds/miracle_tool/views/alerts/AlertView.as
|
/**
* User: MerlinDS
* Date: 12.07.2014
* Time: 21:38
*/
package com.merlinds.miracle_tool.views.alerts {
import com.merlinds.miracle_tool.view.interfaces.IResizable;
import com.merlinds.miracle_tool.views.components.containers.DialogWindow;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.setTimeout;
public class AlertView extends Sprite implements IResizable{
private var _dialogs:Sprite;
private var _modalBlocker:Shape;
//==============================================================================
//{region PUBLIC METHODS
public function AlertView(parent:DisplayObjectContainer = null) {
super();
_modalBlocker = super.addChild(new Shape()) as Shape;
_dialogs = super.addChild(new Sprite()) as Sprite;
parent.addChild(this);
}
public function setSize(w:Number, h:Number):void {
this.visible = false;
_modalBlocker.graphics.clear();
_modalBlocker.graphics.beginFill(0x000000, 0.3);
_modalBlocker.graphics.drawRect(0, 0, w, h);
_modalBlocker.graphics.endFill();
_modalBlocker.visible = false;
if(_dialogs.numChildren > 0){
for(var i:int = 0; i < _dialogs.numChildren; i++){
var child:DisplayObject = _dialogs.getChildAt(i);
child.x = this.width - child.width >> 1;
child.y = this.height - child.height >> 1;
}
_dialogs.visible = true;
}
}
override public function addChild(child:DisplayObject):DisplayObject {
child.addEventListener(Event.ADDED_TO_STAGE, this.childAddedHandler);
return _dialogs.addChild(child);
}
override public function removeChild(child:DisplayObject):DisplayObject {
// when super.removeChild will be executed numChildren will be equals 0
if(_dialogs.numChildren == 1){
this.visible = false;
}
return _dialogs.removeChild(child);
}
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function childAddedHandler(event:Event):void {
var child:DisplayObject = event.target as DisplayObject;
child.removeEventListener(Event.ADDED_TO_STAGE, this.childAddedHandler);
//only on next frame//Hack for minimal comps
setTimeout(function():void{
child.x = width - child.width >> 1;
child.y = height - child.height >> 1;
visible = true;
_modalBlocker.visible = (child as DialogWindow).modal;
}, 0);
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
/**
* User: MerlinDS
* Date: 12.07.2014
* Time: 21:38
*/
package com.merlinds.miracle_tool.views.alerts {
import com.merlinds.miracle_tool.view.interfaces.IResizable;
import com.merlinds.miracle_tool.views.components.containers.DialogWindow;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.setTimeout;
public class AlertView extends Sprite implements IResizable{
private var _dialogs:Sprite;
private var _modalBlocker:Shape;
//==============================================================================
//{region PUBLIC METHODS
public function AlertView(parent:DisplayObjectContainer = null) {
super();
_modalBlocker = super.addChild(new Shape()) as Shape;
_dialogs = super.addChild(new Sprite()) as Sprite;
parent.addChild(this);
}
public function setSize(w:Number, h:Number):void {
this.visible = false;
_modalBlocker.graphics.clear();
_modalBlocker.graphics.beginFill(0x000000, 0.3);
_modalBlocker.graphics.drawRect(0, 0, w, h);
_modalBlocker.graphics.endFill();
_modalBlocker.visible = false;
if(_dialogs.numChildren > 0){
for(var i:int = 0; i < _dialogs.numChildren; i++){
var child:DisplayObject = _dialogs.getChildAt(i);
child.x = this.width - child.width >> 1;
child.y = this.height - child.height >> 1;
_modalBlocker.visible = (child as DialogWindow).modal;
}
this.visible = true;
}
}
override public function addChild(child:DisplayObject):DisplayObject {
child.addEventListener(Event.ADDED_TO_STAGE, this.childAddedHandler);
return _dialogs.addChild(child);
}
override public function removeChild(child:DisplayObject):DisplayObject {
// when super.removeChild will be executed numChildren will be equals 0
if(_dialogs.numChildren == 1){
this.visible = false;
}
return _dialogs.removeChild(child);
}
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function childAddedHandler(event:Event):void {
var child:DisplayObject = event.target as DisplayObject;
child.removeEventListener(Event.ADDED_TO_STAGE, this.childAddedHandler);
//only on next frame//Hack for minimal comps
setTimeout(function():void{
child.x = width - child.width >> 1;
child.y = height - child.height >> 1;
visible = true;
_modalBlocker.visible = (child as DialogWindow).modal;
}, 0);
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
Create dialog fix
|
Create dialog fix
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
0ef4b6cf190d01f9f3fd450d9bb4468492fcef74
|
driver/src/main/flex/org/postgresql/febe/MessageStream.as
|
driver/src/main/flex/org/postgresql/febe/MessageStream.as
|
package org.postgresql.febe {
import flash.events.EventDispatcher;
import org.postgresql.febe.message.AuthenticationRequest;
import org.postgresql.febe.message.BackendKeyData;
import org.postgresql.febe.message.Bind;
import org.postgresql.febe.message.BindComplete;
import org.postgresql.febe.message.CloseComplete;
import org.postgresql.febe.message.CommandComplete;
import org.postgresql.febe.message.DataRow;
import org.postgresql.febe.message.EmptyQueryResponse;
import org.postgresql.febe.message.ErrorResponse;
import org.postgresql.febe.message.IBEMessage;
import org.postgresql.febe.message.IFEMessage;
import org.postgresql.febe.message.NoData;
import org.postgresql.febe.message.NoticeResponse;
import org.postgresql.febe.message.ParameterDescription;
import org.postgresql.febe.message.ParameterStatus;
import org.postgresql.febe.message.ParseComplete;
import org.postgresql.febe.message.PortalSuspended;
import org.postgresql.febe.message.ReadyForQuery;
import org.postgresql.febe.message.RowDescription;
import org.postgresql.io.ByteDataStream;
import org.postgresql.io.DataStreamErrorEvent;
import org.postgresql.io.DataStreamEvent;
import org.postgresql.io.IDataStream;
import org.postgresql.log.ILogger;
import org.postgresql.log.Log;
import org.postgresql.util.format;
public class MessageStream extends EventDispatcher implements IMessageStream {
private static const LOGGER:ILogger = Log.getLogger(MessageStream);
// Commented-out messages are part of the protocol but unimplemented. COPY
// will probably be implemented at some point; the function call (fastpath)
// subprotocol probably will not be
public static const backendMessageTypes:Object = {
'R': AuthenticationRequest,
'K': BackendKeyData,
'B': Bind,
'C': CommandComplete,
/*'d': CopyData,
'c': CopyDone,
'G': CopyInResponse,
'H': CopyOutResponse */
'3': CloseComplete,
'D': DataRow,
'I': EmptyQueryResponse,
'E': ErrorResponse,
/*'V': FunctionCallResponse */
'n': NoData,
'N': NoticeResponse,
't': ParameterDescription,
'S': ParameterStatus,
'1': ParseComplete,
'2': BindComplete,
's': PortalSuspended,
'Z': ReadyForQuery,
'T': RowDescription
};
private var _dataStream:IDataStream;
private var _onDisconnected:Function;
private var _nextMessageType:int;
private var _nextMessageLen:int;
public function MessageStream(stream:IDataStream) {
_dataStream = stream;
_dataStream.addEventListener(DataStreamEvent.PROGRESS, handleStreamData);
_dataStream.addEventListener(DataStreamErrorEvent.ERROR, handleError);
_nextMessageType = -1;
_nextMessageLen = -1;
}
private function handleStreamData(e:DataStreamEvent):void {
while (_dataStream.connected &&
(_nextMessageLen == -1 && _dataStream.bytesAvailable >= 5 /* len + type */) ||
(_nextMessageLen != -1 && _dataStream.bytesAvailable >= _nextMessageLen)) {
if (_nextMessageLen == -1) {
_nextMessageType = _dataStream.readByte();
// FEBE encodes the message length as including the size
// of the length field itself. This does not work well for
// our purposes (it would make a number of things more confusing
// than necessary), so we subtract the size of the length field.
_nextMessageLen = _dataStream.readInt() - 4;
} else {
// TODO: We should not have to copy the message to its own array: we
// should wrap the stream in something that sets an arbitrary hard limit
// to the number of bytes this particular message can read.
var messageBytes:ByteDataStream = new ByteDataStream();
_dataStream.readBytes(messageBytes, 0, _nextMessageLen);
var nextTypeCode:String = String.fromCharCode(_nextMessageType);
var nextMessageClass:Class = backendMessageTypes[nextTypeCode];
if (!nextMessageClass) {
var msg:String = format("No message class found for message type {0}", nextTypeCode);
dispatchEvent(new MessageStreamErrorEvent(MessageStreamErrorEvent.ERROR, msg));
} else {
try {
var nextMessage:IBEMessage = new nextMessageClass();
nextMessage.read(messageBytes);
LOGGER.debug('<= {0}', nextMessage);
dispatchEvent(new MessageEvent(MessageEvent.RECEIVED, nextMessage));
} catch (e:Error) {
dispatchEvent(new MessageStreamErrorEvent(MessageStreamErrorEvent.ERROR, e.message));
} finally {
// TODO: we should probably try sync in the catch or something: it's rather
// optimistic to assume that this finally clause will work for the failure case
_nextMessageType = -1;
_nextMessageLen = -1;
}
}
}
}
dispatchEvent(new MessageStreamEvent(MessageStreamEvent.BATCH_COMPLETE));
}
private function handleError(e:DataStreamErrorEvent):void {
dispatchEvent(new MessageStreamErrorEvent(MessageStreamErrorEvent.ERROR, e.text));
}
public function send(message:IFEMessage):void {
LOGGER.debug('=> {0}', message);
message.write(_dataStream);
// TODO: we can eventually expose flush() in the IMessageBroker interface
// to support flushing a batch of message instead of each individual message.
// For now, we just keep this simple.
_dataStream.flush();
dispatchEvent(new MessageEvent(MessageEvent.SENT, message));
}
public function get connected():Boolean {
return _dataStream.connected;
}
public function close():void {
_dataStream.close();
}
}
}
|
package org.postgresql.febe {
import flash.events.EventDispatcher;
import org.postgresql.febe.message.AuthenticationRequest;
import org.postgresql.febe.message.BackendKeyData;
import org.postgresql.febe.message.Bind;
import org.postgresql.febe.message.BindComplete;
import org.postgresql.febe.message.CloseComplete;
import org.postgresql.febe.message.CommandComplete;
import org.postgresql.febe.message.DataRow;
import org.postgresql.febe.message.EmptyQueryResponse;
import org.postgresql.febe.message.ErrorResponse;
import org.postgresql.febe.message.IBEMessage;
import org.postgresql.febe.message.IFEMessage;
import org.postgresql.febe.message.NoData;
import org.postgresql.febe.message.NoticeResponse;
import org.postgresql.febe.message.ParameterDescription;
import org.postgresql.febe.message.ParameterStatus;
import org.postgresql.febe.message.ParseComplete;
import org.postgresql.febe.message.PortalSuspended;
import org.postgresql.febe.message.ReadyForQuery;
import org.postgresql.febe.message.RowDescription;
import org.postgresql.io.ByteDataStream;
import org.postgresql.io.DataStreamErrorEvent;
import org.postgresql.io.DataStreamEvent;
import org.postgresql.io.IDataStream;
import org.postgresql.log.ILogger;
import org.postgresql.log.Log;
import org.postgresql.util.assert;
import org.postgresql.util.format;
public class MessageStream extends EventDispatcher implements IMessageStream {
private static const LOGGER:ILogger = Log.getLogger(MessageStream);
// Commented-out messages are part of the protocol but unimplemented. COPY
// will probably be implemented at some point; the function call (fastpath)
// subprotocol probably will not be
public static const backendMessageTypes:Object = {
'R': AuthenticationRequest,
'K': BackendKeyData,
'B': Bind,
'C': CommandComplete,
/*'d': CopyData,
'c': CopyDone,
'G': CopyInResponse,
'H': CopyOutResponse */
'3': CloseComplete,
'D': DataRow,
'I': EmptyQueryResponse,
'E': ErrorResponse,
/*'V': FunctionCallResponse */
'n': NoData,
'N': NoticeResponse,
't': ParameterDescription,
'S': ParameterStatus,
'1': ParseComplete,
'2': BindComplete,
's': PortalSuspended,
'Z': ReadyForQuery,
'T': RowDescription
};
private var _dataStream:IDataStream;
private var _onDisconnected:Function;
private var _nextMessageType:int;
private var _nextMessageLen:int;
public function MessageStream(stream:IDataStream) {
_dataStream = stream;
_dataStream.addEventListener(DataStreamEvent.PROGRESS, handleStreamData);
_dataStream.addEventListener(DataStreamErrorEvent.ERROR, handleError);
_nextMessageType = -1;
_nextMessageLen = -1;
}
private function handleStreamData(e:DataStreamEvent):void {
while (_dataStream.connected &&
(_nextMessageLen == -1 && _dataStream.bytesAvailable >= 5 /* len + type */) ||
(_nextMessageLen != -1 && _dataStream.bytesAvailable >= _nextMessageLen)) {
if (_nextMessageLen == -1) {
_nextMessageType = _dataStream.readByte();
// FEBE encodes the message length as including the size
// of the length field itself. This does not work well for
// our purposes (it would make a number of things more confusing
// than necessary), so we subtract the size of the length field.
_nextMessageLen = _dataStream.readInt() - 4;
LOGGER.debug("Waiting for {0} more bytes ({1} available)", _nextMessageLen, _dataStream.bytesAvailable);
} else {
LOGGER.debug("Reading message of {0} bytes ({1} available)", _nextMessageLen, _dataStream.bytesAvailable);
// TODO: We should not have to copy the message to its own array: we
// should wrap the stream in something that sets an arbitrary hard limit
// to the number of bytes this particular message can read.
var messageBytes:ByteDataStream = new ByteDataStream();
if (_nextMessageLen > 0) {
// N.B.: If
_dataStream.readBytes(messageBytes, 0, _nextMessageLen);
}
assert("Unexpected amount of data was read off the stream", messageBytes.length == _nextMessageLen);
var nextTypeCode:String = String.fromCharCode(_nextMessageType);
var nextMessageClass:Class = backendMessageTypes[nextTypeCode];
if (!nextMessageClass) {
var msg:String = format("No message class found for message type {0}", nextTypeCode);
dispatchEvent(new MessageStreamErrorEvent(MessageStreamErrorEvent.ERROR, msg));
} else {
try {
var nextMessage:IBEMessage = new nextMessageClass();
nextMessage.read(messageBytes);
LOGGER.debug('<= {0}', nextMessage);
dispatchEvent(new MessageEvent(MessageEvent.RECEIVED, nextMessage));
} catch (e:Error) {
dispatchEvent(new MessageStreamErrorEvent(MessageStreamErrorEvent.ERROR, e.message));
} finally {
// TODO: we should probably try sync in the catch or something: it's rather
// optimistic to assume that this finally clause will work for the failure case
_nextMessageType = -1;
_nextMessageLen = -1;
}
}
}
}
dispatchEvent(new MessageStreamEvent(MessageStreamEvent.BATCH_COMPLETE));
}
private function handleError(e:DataStreamErrorEvent):void {
dispatchEvent(new MessageStreamErrorEvent(MessageStreamErrorEvent.ERROR, e.text));
}
public function send(message:IFEMessage):void {
LOGGER.debug('=> {0}', message);
message.write(_dataStream);
// TODO: we can eventually expose flush() in the IMessageBroker interface
// to support flushing a batch of message instead of each individual message.
// For now, we just keep this simple.
_dataStream.flush();
dispatchEvent(new MessageEvent(MessageEvent.SENT, message));
}
public function get connected():Boolean {
return _dataStream.connected;
}
public function close():void {
_dataStream.close();
}
}
}
|
Fix reading of 0-payload-length backend messages; additional debugging.
|
Fix reading of 0-payload-length backend messages; additional debugging.
|
ActionScript
|
bsd-3-clause
|
uhoh-itsmaciek/pegasus
|
cc08295071fcdde27a97c28937398176503baf2b
|
Arguments/src/Controller/logic/ModusTollens.as
|
Arguments/src/Controller/logic/ModusTollens.as
|
package Controller.logic
{
import Controller.ArgumentController;
import Model.AGORAModel;
import Model.ArgumentTypeModel;
import Model.StatementModel;
import ValueObjects.AGORAParameters;
import components.ArgSelector;
import components.ArgumentPanel;
import components.MenuPanel;
import classes.Language;
import mx.controls.Alert;
import mx.core.FlexGlobals;
public class ModusTollens extends ParentArg
{
public var andOr:String;
private var _isExp:Boolean;
private static var instance:ModusTollens;
public function ModusTollens()
{
langTypes = ["If-then","Implies","Whenever","Only if","Provided that","Sufficient condition","Necessary condition"];
//dbLangTypeNames = ["ifthen","implies","whenever","onlyif","providedthat","sufficient","necessary"];
expLangTypes = ["Only if"]; // Expandable with both And and Or
label = AGORAParameters.getInstance().MOD_TOL;
}
public static function getInstance():ModusTollens{
if(instance == null){
instance = new ModusTollens;
}
return instance;
}
override public function getLabel():String{
return label;
}
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;
switch(argumentTypeModel.language){
case langTypes[0]:
reasonText = reasonModels[0].statement.positiveText;
output = Language.lookup("ArgIf") + claimModel.statement.positiveText +
Language.lookup("ArgThen") + reasonText;
break;
case langTypes[1]:
output = claimModel.statement.positiveText + Language.lookup("ArgImplies") + reasonModels[0].statement.positiveText;
break;
case langTypes[2]:
reasonText = reasonModels[0].statement.positiveText;
output = Language.lookup("ArgWhenever") + claimModel.statement.positiveText + ", " + reasonText;
break;
case langTypes[3]:
//if many reasons
var params:AGORAParameters = AGORAParameters.getInstance();
if(argumentTypeModel.reasonModels.length > 1 && argumentTypeModel.lSubOption == null){
output = "Select how you want to connect the reasons"; //TODO: Translate
argSelector.andor.x = argSelector.typeSelector.x + argSelector.typeSelector.width;
argSelector.andor.dataProvider = [params.AND, params.OR];
argSelector.andor.visible = argSelector.typeSelector.visible;
//if one reason
}else if(argumentTypeModel.reasonModels.length == 1){
reasonText = reasonModels[0].statement.positiveText;
output = claimModel.statement.positiveText + Language.lookup("ArgOnlyIf");
output = output + reasonText;
}else{
output = claimModel.statement.positiveText + Language.lookup("ArgOnlyIf");
for(i=0; i<reasonModels.length - 1; i++){
reasonText = reasonText + reasonModels[i].statement.positiveText + " " + argumentTypeModel.lSubOption + " ";
}
reasonText = reasonText + reasonModels[reasonModels.length - 1].statement.positiveText;
output = output + reasonText;
argSelector.andor.x = argSelector.typeSelector.x + argSelector.typeSelector.width;
argSelector.andor.dataProvider = [params.AND, params.OR];
argSelector.andor.visible = argSelector.typeSelector.visible;
}
break;
case langTypes[4]:
//provided that
reasonText = reasonModels[0].statement.positiveText ;
output = reasonText + Language.lookup("ArgProvidedThat") + claimModel.statement.positiveText;
break;
case langTypes[5]:
//sufficient condition
reasonText = reasonModels[0].statement.positiveText;
output = claimModel.statement.positiveText + Language.lookup("ArgSufficientCond") + reasonText;
break;
case langTypes[6]:
//necessary condition
reasonText = reasonModels[0].statement.positiveText
output = reasonText + Language.lookup("ArgNecessaryCond") + claimModel.statement.positiveText;
break;
}
argumentTypeModel.inferenceModel.statements[0].text = claimModel.statement.text;
argumentTypeModel.inferenceModel.statements[1].text = reasonText;
argumentTypeModel.inferenceModel.statement.text = output;
}
override public function formTextWithSubOption(argumentTypeModel:ArgumentTypeModel):void{
//must be only if:
var output: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;
if(argumentTypeModel.language == langTypes[4]){
output = claimModel.statement.positiveText + Language.lookup("ArgOnlyIf") + reasonModels[0].statement.positiveText;
for(i=1; i < reasonModels.length; i++){
output = " " + argumentTypeModel.lSubOption + " " + reasonModels[i].statement.positiveText;
}
}
else{
trace("ModusTollens::formTextWithSubOption: Should not be any other language type other than only if");
}
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;
//if first claim's argument, then make it non-negative
if(claimModel.firstClaim){
claimModel.negated = false;
//the first inference statement is the one to be removed
}
removeDependence(claimModel.statement, argumentTypeModel.inferenceModel.statements[0]);
//make reason models non-negative
for each(var reason:StatementModel in reasonModels){
reason.negated = false;
removeDependence(reason.statement, argumentTypeModel.inferenceModel.statements[1]);
}
}
override public function link(argumentTypeModel:ArgumentTypeModel):void{
var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels;
var claimModel:StatementModel = argumentTypeModel.claimModel;
var inferenceModel:StatementModel = argumentTypeModel.inferenceModel;
if(claimModel.firstClaim){
claimModel.negated = true;
}
inferenceModel.connectingString = StatementModel.IMPLICATION;
//claimModel.statement.forwardList.push(inferenceModel.statements[0]);
claimModel.statement.addDependentStatement(inferenceModel.statements[0]);
for each(var reason:StatementModel in reasonModels){
reason.negated = true;
//reason.statement.forwardList.push(inferenceModel.statements[1]);
reason.statement.addDependentStatement(inferenceModel.statements[1]);
}
}
}
}
|
package Controller.logic
{
import Controller.ArgumentController;
import Model.AGORAModel;
import Model.ArgumentTypeModel;
import Model.StatementModel;
import ValueObjects.AGORAParameters;
import components.ArgSelector;
import components.ArgumentPanel;
import components.MenuPanel;
import classes.Language;
import mx.controls.Alert;
import mx.core.FlexGlobals;
public class ModusTollens extends ParentArg
{
public var andOr:String;
private var _isExp:Boolean;
private static var instance:ModusTollens;
public function ModusTollens()
{
langTypes = ["If-then","Implies","Whenever","Only if","Provided that","Sufficient condition","Necessary condition"];
//dbLangTypeNames = ["ifthen","implies","whenever","onlyif","providedthat","sufficient","necessary"];
expLangTypes = ["Only if"]; // Expandable with both And and Or
label = AGORAParameters.getInstance().MOD_TOL;
}
public static function getInstance():ModusTollens{
if(instance == null){
instance = new ModusTollens;
}
return instance;
}
override public function getLabel():String{
return label;
}
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;
switch(argumentTypeModel.language){
case langTypes[0]:
reasonText = reasonModels[0].statement.positiveText;
output = Language.lookup("ArgIf") + claimModel.statement.positiveText +
Language.lookup("ArgThen") + reasonText;
break;
case langTypes[1]:
output = claimModel.statement.positiveText + Language.lookup("ArgImplies") + reasonModels[0].statement.positiveText;
break;
case langTypes[2]:
reasonText = reasonModels[0].statement.positiveText;
output = Language.lookup("ArgWhenever") + claimModel.statement.positiveText + ", " + reasonText;
break;
case langTypes[3]:
//if many reasons
var params:AGORAParameters = AGORAParameters.getInstance();
if(argumentTypeModel.reasonModels.length > 1 && argumentTypeModel.lSubOption == null){
output = Language.lookup("SelectLanguageType");
argSelector.andor.x = argSelector.typeSelector.x + argSelector.typeSelector.width;
argSelector.andor.dataProvider = [params.AND, params.OR];
argSelector.andor.visible = argSelector.typeSelector.visible;
//if one reason
}else if(argumentTypeModel.reasonModels.length == 1){
reasonText = reasonModels[0].statement.positiveText;
output = claimModel.statement.positiveText + Language.lookup("ArgOnlyIf");
output = output + reasonText;
}else{
output = claimModel.statement.positiveText + Language.lookup("ArgOnlyIf");
for(i=0; i<reasonModels.length - 1; i++){
reasonText = reasonText + reasonModels[i].statement.positiveText + " " + argumentTypeModel.lSubOption + " ";
}
reasonText = reasonText + reasonModels[reasonModels.length - 1].statement.positiveText;
output = output + reasonText;
argSelector.andor.x = argSelector.typeSelector.x + argSelector.typeSelector.width;
argSelector.andor.dataProvider = [params.AND, params.OR];
argSelector.andor.visible = argSelector.typeSelector.visible;
}
break;
case langTypes[4]:
//provided that
reasonText = reasonModels[0].statement.positiveText ;
output = reasonText + Language.lookup("ArgProvidedThat") + claimModel.statement.positiveText;
break;
case langTypes[5]:
//sufficient condition
reasonText = reasonModels[0].statement.positiveText;
output = claimModel.statement.positiveText + Language.lookup("ArgSufficientCond") + reasonText;
break;
case langTypes[6]:
//necessary condition
reasonText = reasonModels[0].statement.positiveText
output = reasonText + Language.lookup("ArgNecessaryCond") + claimModel.statement.positiveText;
break;
}
argumentTypeModel.inferenceModel.statements[0].text = claimModel.statement.text;
argumentTypeModel.inferenceModel.statements[1].text = reasonText;
argumentTypeModel.inferenceModel.statement.text = output;
}
override public function formTextWithSubOption(argumentTypeModel:ArgumentTypeModel):void{
//must be only if:
var output: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;
if(argumentTypeModel.language == langTypes[4]){
output = claimModel.statement.positiveText + Language.lookup("ArgOnlyIf") + reasonModels[0].statement.positiveText;
for(i=1; i < reasonModels.length; i++){
output = " " + argumentTypeModel.lSubOption + " " + reasonModels[i].statement.positiveText;
}
}
else{
trace("ModusTollens::formTextWithSubOption: Should not be any other language type other than only if");
}
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;
//if first claim's argument, then make it non-negative
if(claimModel.firstClaim){
claimModel.negated = false;
//the first inference statement is the one to be removed
}
removeDependence(claimModel.statement, argumentTypeModel.inferenceModel.statements[0]);
//make reason models non-negative
for each(var reason:StatementModel in reasonModels){
reason.negated = false;
removeDependence(reason.statement, argumentTypeModel.inferenceModel.statements[1]);
}
}
override public function link(argumentTypeModel:ArgumentTypeModel):void{
var reasonModels:Vector.<StatementModel> = argumentTypeModel.reasonModels;
var claimModel:StatementModel = argumentTypeModel.claimModel;
var inferenceModel:StatementModel = argumentTypeModel.inferenceModel;
if(claimModel.firstClaim){
claimModel.negated = true;
}
inferenceModel.connectingString = StatementModel.IMPLICATION;
//claimModel.statement.forwardList.push(inferenceModel.statements[0]);
claimModel.statement.addDependentStatement(inferenceModel.statements[0]);
for each(var reason:StatementModel in reasonModels){
reason.negated = true;
//reason.statement.forwardList.push(inferenceModel.statements[1]);
reason.statement.addDependentStatement(inferenceModel.statements[1]);
}
}
}
}
|
Add help text to MT
|
Add help text to MT
|
ActionScript
|
agpl-3.0
|
mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA
|
825b869f69764db52959cdf544dd72c032139edd
|
src/org/mangui/hls/controller/BufferThresholdController.as
|
src/org/mangui/hls/controller/BufferThresholdController.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.controller {
import org.mangui.hls.constant.HLSLoaderTypes;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.event.HLSLoadMetrics;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that manages buffer threshold values (minBufferLength/lowBufferLength)
*/
public class BufferThresholdController {
/** Reference to the HLS controller. **/
private var _hls : HLS;
// max nb of samples used for bw checking. the bigger it is, the more conservative it is.
private static const MAX_SAMPLES : int = 30;
private var _bw : Vector.<Number>;
private var _nbSamples : uint;
private var _targetduration : Number;
private var _minBufferLength : Number;
/** Create the loader. **/
public function BufferThresholdController(hls : HLS) : void {
_hls = hls;
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler);
_hls.addEventListener(HLSEvent.TAGS_LOADED, _fragmentLoadedHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler);
};
public function dispose() : void {
_hls.removeEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler);
_hls.removeEventListener(HLSEvent.TAGS_LOADED, _fragmentLoadedHandler);
_hls.removeEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler);
}
public function get minBufferLength() : Number {
if (HLSSettings.minBufferLength == -1) {
return _minBufferLength;
} else {
return HLSSettings.minBufferLength;
}
}
public function get lowBufferLength() : Number {
if (HLSSettings.minBufferLength == -1) {
// in automode, low buffer threshold should be less than min auto buffer
return Math.min(minBufferLength / 2, HLSSettings.lowBufferLength);
} else {
return HLSSettings.lowBufferLength;
}
}
private function _manifestLoadedHandler(event : HLSEvent) : void {
_nbSamples = 0;
_targetduration = event.levels[_hls.startLevel].targetduration;
_bw = new Vector.<Number>(MAX_SAMPLES);
_minBufferLength = _targetduration;
};
private function _fragmentLoadedHandler(event : HLSEvent) : void {
var metrics : HLSLoadMetrics = event.loadMetrics;
// only monitor main fragment metrics for buffer threshold computing
if(metrics.type == HLSLoaderTypes.FRAGMENT_MAIN) {
var cur_bw : Number = metrics.bandwidth;
_bw[_nbSamples % MAX_SAMPLES] = cur_bw;
_nbSamples++;
// compute min bw on MAX_SAMPLES
var minBw : Number = Number.POSITIVE_INFINITY;
var samples_max : int = Math.min(_nbSamples, MAX_SAMPLES);
for (var i : int = 0; i < samples_max; i++) {
minBw = Math.min(minBw, _bw[i]);
}
// give more weight to current bandwidth
var bw_ratio : Number = 2 * cur_bw / (minBw + cur_bw);
/* predict time to dl next segment using a conservative approach.
*
* heuristic is as follow :
*
* time to dl next segment = time to dl current segment * (playlist target duration / current segment duration) * bw_ratio
* \---------------------------------------------------------------------------------/
* this part is a simple rule by 3, assuming we keep same dl bandwidth
* bw ratio is the conservative factor, assuming that next segment will be downloaded with min bandwidth
*/
_minBufferLength = metrics.processing_duration * (_targetduration / metrics.duration) * bw_ratio;
// avoid min > max
if (HLSSettings.maxBufferLength) {
_minBufferLength = Math.min(HLSSettings.maxBufferLength, _minBufferLength);
}
CONFIG::LOGGING {
Log.debug2("AutoBufferController:minBufferLength:" + _minBufferLength);
}
};
}
}
}
|
/* 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.controller {
import org.mangui.hls.constant.HLSLoaderTypes;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.event.HLSLoadMetrics;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that manages buffer threshold values (minBufferLength/lowBufferLength)
*/
public class BufferThresholdController {
/** Reference to the HLS controller. **/
private var _hls : HLS;
// max nb of samples used for bw checking. the bigger it is, the more conservative it is.
private static const MAX_SAMPLES : int = 30;
private var _bw : Vector.<Number>;
private var _nbSamples : uint;
private var _targetduration : Number;
private var _minBufferLength : Number;
/** Create the loader. **/
public function BufferThresholdController(hls : HLS) : void {
_hls = hls;
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler);
_hls.addEventListener(HLSEvent.TAGS_LOADED, _fragmentLoadedHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler);
};
public function dispose() : void {
_hls.removeEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler);
_hls.removeEventListener(HLSEvent.TAGS_LOADED, _fragmentLoadedHandler);
_hls.removeEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler);
}
public function get minBufferLength() : Number {
if (HLSSettings.minBufferLength == -1) {
return _minBufferLength;
} else {
return HLSSettings.minBufferLength;
}
}
public function get lowBufferLength() : Number {
if (HLSSettings.minBufferLength == -1) {
// in automode, low buffer threshold should be less than min auto buffer
return Math.min(minBufferLength / 2, HLSSettings.lowBufferLength);
} else {
return HLSSettings.lowBufferLength;
}
}
private function _manifestLoadedHandler(event : HLSEvent) : void {
_nbSamples = 0;
_targetduration = event.levels[_hls.startLevel].targetduration;
_bw = new Vector.<Number>(MAX_SAMPLES,true);
_minBufferLength = _targetduration;
};
private function _fragmentLoadedHandler(event : HLSEvent) : void {
var metrics : HLSLoadMetrics = event.loadMetrics;
// only monitor main fragment metrics for buffer threshold computing
if(metrics.type == HLSLoaderTypes.FRAGMENT_MAIN) {
var cur_bw : Number = metrics.bandwidth;
_bw[_nbSamples % MAX_SAMPLES] = cur_bw;
_nbSamples++;
// compute min bw on MAX_SAMPLES
var minBw : Number = Number.POSITIVE_INFINITY;
var samples_max : int = Math.min(_nbSamples, MAX_SAMPLES);
for (var i : int = 0; i < samples_max; i++) {
minBw = Math.min(minBw, _bw[i]);
}
// give more weight to current bandwidth
var bw_ratio : Number = 2 * cur_bw / (minBw + cur_bw);
/* predict time to dl next segment using a conservative approach.
*
* heuristic is as follow :
*
* time to dl next segment = time to dl current segment * (playlist target duration / current segment duration) * bw_ratio
* \---------------------------------------------------------------------------------/
* this part is a simple rule by 3, assuming we keep same dl bandwidth
* bw ratio is the conservative factor, assuming that next segment will be downloaded with min bandwidth
*/
_minBufferLength = metrics.processing_duration * (_targetduration / metrics.duration) * bw_ratio;
// avoid min > max
if (HLSSettings.maxBufferLength) {
_minBufferLength = Math.min(HLSSettings.maxBufferLength, _minBufferLength);
}
CONFIG::LOGGING {
Log.debug2("AutoBufferController:minBufferLength:" + _minBufferLength);
}
};
}
}
}
|
optimize fixed length vector instantiation
|
optimize fixed length vector instantiation
|
ActionScript
|
mpl-2.0
|
Boxie5/flashls,NicolasSiver/flashls,vidible/vdb-flashls,hola/flashls,Peer5/flashls,loungelogic/flashls,tedconf/flashls,mangui/flashls,jlacivita/flashls,Peer5/flashls,loungelogic/flashls,fixedmachine/flashls,codex-corp/flashls,thdtjsdn/flashls,fixedmachine/flashls,neilrackett/flashls,mangui/flashls,dighan/flashls,Peer5/flashls,neilrackett/flashls,vidible/vdb-flashls,JulianPena/flashls,dighan/flashls,codex-corp/flashls,Peer5/flashls,tedconf/flashls,clappr/flashls,jlacivita/flashls,Corey600/flashls,thdtjsdn/flashls,NicolasSiver/flashls,clappr/flashls,hola/flashls,Boxie5/flashls,JulianPena/flashls,Corey600/flashls
|
f18bacccf5e9c5a9f1b495e6cddc822eb1866d9e
|
tamarin-central/thane/as3src/flash/utils/typeFunctions.as
|
tamarin-central/thane/as3src/flash/utils/typeFunctions.as
|
//
// $Id$
//
// Thane - an enhancement of Mozilla/Adobe's Tamarin project with partial Flash Player compatibility
// Copyright (C) 2008-2009 Three Rings Design, Inc.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package flash.utils {
import avmplus.Domain;
public function describeType (c :Object) :XML
{
throw new Error("describeType() Not implemented");
}
public function getDefinitionByName (name :String) :Class
{
return Domain.currentDomain.getClass(name.replace("::", "."));
}
public function getQualifiedClassName (c :*) :String
{
return Domain.currentDomain.getClassName(c);
}
public function getQualifiedSuperclassName (c :*) :String
{
throw new Error("getQualifiedSuperclassName() not implemented");
}
}
|
//
// $Id$
//
// Thane - an enhancement of Mozilla/Adobe's Tamarin project with partial Flash Player compatibility
// Copyright (C) 2008-2009 Three Rings Design, Inc.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package flash.utils {
import avmplus.describeType;
import avmplus.FLASH10_FLAGS;
import avmplus.Domain;
public function describeType (c :Object) :XML
{
return avmplus.describeType(c, FLASH10_FLAGS);
}
public function describeTypeWithFlags (value :*, flags :uint) :XML
{
return avmplus.describeType(value, flags);
}
public function getDefinitionByName (name :String) :Class
{
return avmplus.Domain.currentDomain.getClass(name.replace("::", "."));
}
public function getQualifiedClassName (c :*) :String
{
// TODO: This function now exists in avmplus.*, see core/DescribeType.as
return avmplus.Domain.currentDomain.getClassName(c);
}
public function getQualifiedSuperclassName (c :*) :String
{
// TODO: This function now exists in avmplus.*, see core/DescribeType.as
throw new Error("getQualifiedSuperclassName() not implemented");
}
}
|
Use the new fancy describeType() implementation in Tamarin. It's hopefully functionally identical to the one in the client. This probably obsoletes the Thane/Client environment fiddling we do in Narya.
|
Use the new fancy describeType() implementation in Tamarin. It's hopefully functionally identical to the one in the client. This probably obsoletes the Thane/Client environment fiddling we do in Narya.
|
ActionScript
|
bsd-2-clause
|
greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane
|
ff8315900e3e9a4748cf5430556fc4c894adbe84
|
src/flash/net/NetStreamMulticastInfo.as
|
src/flash/net/NetStreamMulticastInfo.as
|
/*
* Copyright 2014 Mozilla Foundation
*
* 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 flash.net {
public final class NetStreamMulticastInfo {
public function NetStreamMulticastInfo(sendDataBytesPerSecond:Number, sendControlBytesPerSecond:Number, receiveDataBytesPerSecond:Number, receiveControlBytesPerSecond:Number, bytesPushedToPeers:Number, fragmentsPushedToPeers:Number, bytesRequestedByPeers:Number, fragmentsRequestedByPeers:Number, bytesPushedFromPeers:Number, fragmentsPushedFromPeers:Number, bytesRequestedFromPeers:Number, fragmentsRequestedFromPeers:Number, sendControlBytesPerSecondToServer:Number, receiveDataBytesPerSecondFromServer:Number, bytesReceivedFromServer:Number, fragmentsReceivedFromServer:Number, receiveDataBytesPerSecondFromIPMulticast:Number, bytesReceivedFromIPMulticast:Number, fragmentsReceivedFromIPMulticast:Number) {
this._sendDataBytesPerSecond = sendDataBytesPerSecond;
this._sendControlBytesPerSecond = sendControlBytesPerSecond;
this._receiveDataBytesPerSecond = receiveDataBytesPerSecond;
this._receiveControlBytesPerSecond = receiveControlBytesPerSecond;
this._bytesPushedToPeers = bytesPushedToPeers;
this._fragmentsPushedToPeers = fragmentsPushedToPeers;
this._bytesRequestedByPeers = bytesRequestedByPeers;
this._fragmentsRequestedByPeers = fragmentsRequestedByPeers;
this._bytesPushedFromPeers = bytesPushedFromPeers;
this._fragmentsPushedFromPeers = fragmentsPushedFromPeers;
this._bytesRequestedFromPeers = bytesRequestedFromPeers;
this._fragmentsRequestedFromPeers = fragmentsRequestedFromPeers;
this._sendControlBytesPerSecondToServer = sendControlBytesPerSecondToServer;
this._receiveDataBytesPerSecondFromServer = receiveDataBytesPerSecondFromServer;
this._bytesReceivedFromServer = bytesReceivedFromServer;
this._fragmentsReceivedFromServer = fragmentsReceivedFromServer;
this._receiveDataBytesPerSecondFromIPMulticast = receiveDataBytesPerSecondFromIPMulticast;
this._bytesReceivedFromIPMulticast = bytesReceivedFromIPMulticast;
this._fragmentsReceivedFromIPMulticast = fragmentsReceivedFromIPMulticast;
}
public function get sendDataBytesPerSecond():Number {
return _sendDataBytesPerSecond;
}
public function get sendControlBytesPerSecond():Number {
return _sendControlBytesPerSecond;
}
public function get receiveDataBytesPerSecond():Number {
return _receiveDataBytesPerSecond;
}
public function get receiveControlBytesPerSecond():Number {
return _receiveControlBytesPerSecond;
}
public function get bytesPushedToPeers():Number {
return _bytesPushedToPeers;
}
public function get fragmentsPushedToPeers():Number {
return _fragmentsPushedToPeers;
}
public function get bytesRequestedByPeers():Number {
return _bytesRequestedByPeers;
}
public function get fragmentsRequestedByPeers():Number {
return _fragmentsRequestedByPeers;
}
public function get bytesPushedFromPeers():Number {
return _bytesPushedFromPeers;
}
public function get fragmentsPushedFromPeers():Number {
return _fragmentsPushedFromPeers;
}
public function get bytesRequestedFromPeers():Number {
return _bytesRequestedFromPeers;
}
public function get fragmentsRequestedFromPeers():Number {
return _fragmentsRequestedFromPeers;
}
public function get sendControlBytesPerSecondToServer():Number {
return _sendControlBytesPerSecondToServer;
}
public function get receiveDataBytesPerSecondFromServer():Number {
return _receiveDataBytesPerSecondFromServer;
}
public function get bytesReceivedFromServer():Number {
return _bytesReceivedFromServer;
}
public function get fragmentsReceivedFromServer():Number {
return _fragmentsReceivedFromServer;
}
public function get receiveDataBytesPerSecondFromIPMulticast():Number {
return _receiveDataBytesPerSecondFromIPMulticast;
}
public function get bytesReceivedFromIPMulticast():Number {
return _bytesReceivedFromIPMulticast;
}
public function get fragmentsReceivedFromIPMulticast():Number {
return _fragmentsReceivedFromIPMulticast;
}
public function toString():String {
notImplemented("toString");
return "";
}
private var _sendDataBytesPerSecond:Number;
private var _sendControlBytesPerSecond:Number;
private var _receiveDataBytesPerSecond:Number;
private var _receiveControlBytesPerSecond:Number;
private var _bytesPushedToPeers:Number;
private var _fragmentsPushedToPeers:Number;
private var _bytesRequestedByPeers:Number;
private var _fragmentsRequestedByPeers:Number;
private var _bytesPushedFromPeers:Number;
private var _fragmentsPushedFromPeers:Number;
private var _bytesRequestedFromPeers:Number;
private var _fragmentsRequestedFromPeers:Number;
private var _sendControlBytesPerSecondToServer:Number;
private var _receiveDataBytesPerSecondFromServer:Number;
private var _bytesReceivedFromServer:Number;
private var _fragmentsReceivedFromServer:Number;
private var _receiveDataBytesPerSecondFromIPMulticast:Number;
private var _bytesReceivedFromIPMulticast:Number;
private var _fragmentsReceivedFromIPMulticast:Number;
}
}
|
/*
* Copyright 2014 Mozilla Foundation
*
* 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 flash.net {
public final class NetStreamMulticastInfo {
public function NetStreamMulticastInfo(sendDataBytesPerSecond: Number,
sendControlBytesPerSecond: Number,
receiveDataBytesPerSecond: Number,
receiveControlBytesPerSecond: Number,
bytesPushedToPeers: Number, fragmentsPushedToPeers: Number,
bytesRequestedByPeers: Number,
fragmentsRequestedByPeers: Number,
bytesPushedFromPeers: Number,
fragmentsPushedFromPeers: Number,
bytesRequestedFromPeers: Number,
fragmentsRequestedFromPeers: Number,
sendControlBytesPerSecondToServer: Number,
receiveDataBytesPerSecondFromServer: Number,
bytesReceivedFromServer: Number,
fragmentsReceivedFromServer: Number,
receiveDataBytesPerSecondFromIPMulticast: Number,
bytesReceivedFromIPMulticast: Number,
fragmentsReceivedFromIPMulticast: Number)
{
this._sendDataBytesPerSecond = sendDataBytesPerSecond;
this._sendControlBytesPerSecond = sendControlBytesPerSecond;
this._receiveDataBytesPerSecond = receiveDataBytesPerSecond;
this._receiveControlBytesPerSecond = receiveControlBytesPerSecond;
this._bytesPushedToPeers = bytesPushedToPeers;
this._fragmentsPushedToPeers = fragmentsPushedToPeers;
this._bytesRequestedByPeers = bytesRequestedByPeers;
this._fragmentsRequestedByPeers = fragmentsRequestedByPeers;
this._bytesPushedFromPeers = bytesPushedFromPeers;
this._fragmentsPushedFromPeers = fragmentsPushedFromPeers;
this._bytesRequestedFromPeers = bytesRequestedFromPeers;
this._fragmentsRequestedFromPeers = fragmentsRequestedFromPeers;
this._sendControlBytesPerSecondToServer = sendControlBytesPerSecondToServer;
this._receiveDataBytesPerSecondFromServer = receiveDataBytesPerSecondFromServer;
this._bytesReceivedFromServer = bytesReceivedFromServer;
this._fragmentsReceivedFromServer = fragmentsReceivedFromServer;
this._receiveDataBytesPerSecondFromIPMulticast = receiveDataBytesPerSecondFromIPMulticast;
this._bytesReceivedFromIPMulticast = bytesReceivedFromIPMulticast;
this._fragmentsReceivedFromIPMulticast = fragmentsReceivedFromIPMulticast;
}
private var _sendDataBytesPerSecond: Number;
private var _sendControlBytesPerSecond: Number;
private var _receiveDataBytesPerSecond: Number;
private var _receiveControlBytesPerSecond: Number;
private var _bytesPushedToPeers: Number;
private var _fragmentsPushedToPeers: Number;
private var _bytesRequestedByPeers: Number;
private var _fragmentsRequestedByPeers: Number;
private var _bytesPushedFromPeers: Number;
private var _fragmentsPushedFromPeers: Number;
private var _bytesRequestedFromPeers: Number;
private var _fragmentsRequestedFromPeers: Number;
private var _sendControlBytesPerSecondToServer: Number;
private var _receiveDataBytesPerSecondFromServer: Number;
private var _bytesReceivedFromServer: Number;
private var _fragmentsReceivedFromServer: Number;
private var _receiveDataBytesPerSecondFromIPMulticast: Number;
private var _bytesReceivedFromIPMulticast: Number;
private var _fragmentsReceivedFromIPMulticast: Number;
public function get sendDataBytesPerSecond(): Number {
return _sendDataBytesPerSecond;
}
public function get sendControlBytesPerSecond(): Number {
return _sendControlBytesPerSecond;
}
public function get receiveDataBytesPerSecond(): Number {
return _receiveDataBytesPerSecond;
}
public function get receiveControlBytesPerSecond(): Number {
return _receiveControlBytesPerSecond;
}
public function get bytesPushedToPeers(): Number {
return _bytesPushedToPeers;
}
public function get fragmentsPushedToPeers(): Number {
return _fragmentsPushedToPeers;
}
public function get bytesRequestedByPeers(): Number {
return _bytesRequestedByPeers;
}
public function get fragmentsRequestedByPeers(): Number {
return _fragmentsRequestedByPeers;
}
public function get bytesPushedFromPeers(): Number {
return _bytesPushedFromPeers;
}
public function get fragmentsPushedFromPeers(): Number {
return _fragmentsPushedFromPeers;
}
public function get bytesRequestedFromPeers(): Number {
return _bytesRequestedFromPeers;
}
public function get fragmentsRequestedFromPeers(): Number {
return _fragmentsRequestedFromPeers;
}
public function get sendControlBytesPerSecondToServer(): Number {
return _sendControlBytesPerSecondToServer;
}
public function get receiveDataBytesPerSecondFromServer(): Number {
return _receiveDataBytesPerSecondFromServer;
}
public function get bytesReceivedFromServer(): Number {
return _bytesReceivedFromServer;
}
public function get fragmentsReceivedFromServer(): Number {
return _fragmentsReceivedFromServer;
}
public function get receiveDataBytesPerSecondFromIPMulticast(): Number {
return _receiveDataBytesPerSecondFromIPMulticast;
}
public function get bytesReceivedFromIPMulticast(): Number {
return _bytesReceivedFromIPMulticast;
}
public function get fragmentsReceivedFromIPMulticast(): Number {
return _fragmentsReceivedFromIPMulticast;
}
public function toString(): String {
return 'sendDataBytesPerSecond=' + _sendDataBytesPerSecond +
' sendControlBytesPerSecond=' + _sendControlBytesPerSecond +
' receiveDataBytesPerSecond=' + _receiveDataBytesPerSecond +
' receiveControlBytesPerSecond=' + _receiveControlBytesPerSecond +
' bytesPushedToPeers=' + _bytesPushedToPeers +
' fragmentsPushedToPeers=' + _fragmentsPushedToPeers +
' bytesRequestedByPeers=' + _bytesRequestedByPeers +
' fragmentsRequestedByPeers=' + _fragmentsRequestedByPeers +
' bytesPushedFromPeers=' + _bytesPushedFromPeers +
' fragmentsPushedFromPeers=' + _fragmentsPushedFromPeers +
' bytesRequestedFromPeers=' + _bytesRequestedFromPeers +
' fragmentsRequestedFromPeers=' + _fragmentsRequestedFromPeers +
' sendControlBytesPerSecondToServer=' + _sendControlBytesPerSecondToServer +
' receiveDataBytesPerSecondFromServer=' + _receiveDataBytesPerSecondFromServer +
' bytesReceivedFromServer=' + _bytesReceivedFromServer +
' fragmentsReceivedFromServer=' + _fragmentsReceivedFromServer +
' receiveDataBytesPerSecondFromIPMulticast=' + _receiveDataBytesPerSecondFromIPMulticast +
' bytesReceivedFromIPMulticast=' + _bytesReceivedFromIPMulticast +
' fragmentsReceivedFromIPMulticast=' + _fragmentsReceivedFromIPMulticast;
}
}
}
|
Implement NetStreamMulticastInfo#toString
|
Implement NetStreamMulticastInfo#toString
And reformat the file
|
ActionScript
|
apache-2.0
|
yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway
|
6229d429b513a5f6ff83e2b9f3aca3ee9a9a710d
|
src/org/mangui/flowplayer/HLSProvider.as
|
src/org/mangui/flowplayer/HLSProvider.as
|
package org.mangui.flowplayer {
import flash.display.DisplayObject;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.Dictionary;
import flash.media.Video;
import org.mangui.HLS.HLS;
import org.mangui.HLS.HLSEvent;
import org.mangui.HLS.HLSStates;
import org.mangui.HLS.HLSTypes;
import org.mangui.HLS.utils.Log;
import org.flowplayer.model.Plugin;
import org.flowplayer.model.PluginModel;
import org.flowplayer.view.Flowplayer;
import org.flowplayer.controller.StreamProvider;
import org.flowplayer.controller.TimeProvider;
import org.flowplayer.controller.VolumeController;
import org.flowplayer.model.Clip;
import org.flowplayer.model.ClipType;
import org.flowplayer.model.ClipEvent;
import org.flowplayer.model.ClipEventType;
import org.flowplayer.model.Playlist;
import org.flowplayer.view.StageVideoWrapper;
public class HLSProvider implements StreamProvider,Plugin {
private var _volumecontroller : VolumeController;
private var _playlist : Playlist;
private var _timeProvider : TimeProvider;
private var _model : PluginModel;
private var _player : Flowplayer;
private var _clip : Clip;
private var _video : Video;
/** reference to the framework. **/
private var _hls : HLS;
private var _hlsState : String = HLSStates.IDLE;
// event values
private var _position : Number = 0;
private var _duration : Number = 0;
private var _bufferedTime : Number = 0;
private var _videoWidth : Number = -1;
private var _videoHeight : Number = -1;
private var _isManifestLoaded : Boolean = false;
private var _pauseAfterStart : Boolean;
private var _seekable : Boolean = false;
public function getDefaultConfig() : Object {
return null;
}
public function onConfig(model : PluginModel) : void {
Log.info("onConfig()");
_model = model;
}
public function onLoad(player : Flowplayer) : void {
Log.info("onLoad()");
_player = player;
_hls = new HLS();
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler);
_hls.addEventListener(HLSEvent.ERROR, _errorHandler);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler);
_hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler);
_hls.addEventListener(HLSEvent.STATE, _stateHandler);
var cfg:Object = _model.config;
var value : Object;
// parse configuration parameters
value = cfg.hls_debug;
if (value != null) {
Log.info("hls_debug:" + value);
Log.LOG_DEBUG_ENABLED = value as Boolean;
}
value = cfg.hls_debug2;
if (value != null) {
Log.info("hls_debug2:" + value);
Log.LOG_DEBUG2_ENABLED = value as Boolean;
}
value = cfg.hls_minbufferlength;
if (value != null) {
Log.info("hls_minbufferlength:" + value);
_hls.minBufferLength = value as Number;
}
value = cfg.hls_maxbufferlength;
if (value != null) {
Log.info("hls_maxbufferlength:" + value);
_hls.maxBufferLength = value as Number;
}
value = cfg.hls_startfromlowestlevel;
if (value != null) {
Log.info("hls_startfromlowestlevel:" + value);
_hls.startFromLowestLevel = value as Boolean;
}
value = cfg.hls_seekfromlowestlevel;
if (value != null) {
Log.info("hls_seekfromlowestlevel:" + value);
_hls.seekFromLowestLevel = value as Boolean;
}
value = cfg.hls_live_flushurlcache;
if (value != null) {
Log.info("hls_live_flushurlcache:" + value);
_hls.flushLiveURLCache = value as Boolean;
}
_model.dispatchOnLoad();
}
private function _completeHandler(event : HLSEvent) : void {
_clip.dispatch(ClipEventType.FINISH);
};
private function _errorHandler(event : HLSEvent) : void {
};
private function _manifestHandler(event : HLSEvent) : void {
_duration = event.levels[0].duration;
_isManifestLoaded = true;
_clip.duration = _duration;
_clip.dispatch(ClipEventType.METADATA);
_seekable = true;
//if (_hls.type == HLSTypes.LIVE) {
// _seekable = false;
//} else {
// _seekable = true;
//}
if (_pauseAfterStart == false) {
_hls.stream.play();
}
};
private function _mediaTimeHandler(event : HLSEvent) : void {
_position = Math.max(0, event.mediatime.position);
_duration = event.mediatime.duration;
_clip.duration = _duration;
_bufferedTime = event.mediatime.buffer + event.mediatime.position;
var videoWidth : Number = _video.videoWidth;
var videoHeight : Number = _video.videoHeight;
if (videoWidth && videoHeight) {
var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight;
if (changed) {
Log.info("video size changed to " + videoWidth + "/" + videoHeight);
_videoWidth = videoWidth;
_videoHeight = videoHeight;
_clip.originalWidth = videoWidth;
_clip.originalHeight = videoHeight;
_clip.dispatch(ClipEventType.START);
_clip.dispatch(ClipEventType.METADATA_CHANGED);
}
}
};
private function _stateHandler(event : HLSEvent) : void {
_hlsState = event.state;
// Log.txt("state:"+ _hlsState);
switch(event.state) {
case HLSStates.IDLE:
case HLSStates.PLAYING:
_clip.dispatch(ClipEventType.BUFFER_FULL);
break;
case HLSStates.PLAYING_BUFFERING:
_clip.dispatch(ClipEventType.BUFFER_EMPTY);
break;
case HLSStates.PAUSED_BUFFERING:
_clip.dispatch(ClipEventType.BUFFER_EMPTY);
_clip.dispatch(ClipEventType.PAUSE);
break;
case HLSStates.PAUSED:
_clip.dispatch(ClipEventType.BUFFER_FULL);
_clip.dispatch(ClipEventType.PAUSE);
break;
}
};
/**
* Starts loading the specivied clip. Once video data is available the provider
* must set it to the clip using <code>clip.setContent()</code>. Typically the video
* object passed to the clip is an instance of <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html">flash.media.Video</a>.
*
* @param event the event that this provider should dispatch once loading has successfully started,
* once dispatched the player will call <code>getVideo()</code>
* @param clip the clip to load
* @param pauseAfterStart if <code>true</code> the playback is paused on first frame and
* buffering is continued
* @see Clip#setContent()
* @see #getVideo()
*/
public function load(event : ClipEvent, clip : Clip, pauseAfterStart : Boolean = true) : void {
_clip = clip;
Log.info("load()" + clip.completeUrl);
_hls.load(clip.completeUrl);
_pauseAfterStart = pauseAfterStart;
clip.type = ClipType.VIDEO;
clip.dispatch(ClipEventType.BEGIN);
return;
}
/**
* Gets the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html">Video</a> object.
* A stream will be attached to the returned video object using <code>attachStream()</code>.
* @param clip the clip for which the Video object is queried for
* @see #attachStream()
*/
public function getVideo(clip : Clip) : DisplayObject {
Log.debug("getVideo()");
if (clip.useStageVideo) {
Log.debug("useStageVideo");
_video = new StageVideoWrapper(clip);
} else {
_video = new Video();
_video.smoothing = clip.smoothing;
}
return _video;
}
/**
* Attaches a stream to the specified display object.
* @param video the video object that was originally retrieved using <code>getVideo()</code>.
* @see #getVideo()
*/
public function attachStream(video : DisplayObject) : void {
Log.debug("attachStream()");
Video(video).attachNetStream(_hls.stream);
return;
}
/**
* Pauses playback.
* @param event the event that this provider should dispatch once loading has been successfully paused
*/
public function pause(event : ClipEvent) : void {
Log.info("pause()");
_hls.stream.pause();
return;
}
/**
* Resumes playback.
* @param event the event that this provider should dispatch once loading has been successfully resumed
*/
public function resume(event : ClipEvent) : void {
Log.info("resume()");
_hls.stream.resume();
_clip.dispatch(ClipEventType.RESUME);
return;
}
/**
* Stops and rewinds to the beginning of current clip.
* @param event the event that this provider should dispatch once loading has been successfully stopped
*/
public function stop(event : ClipEvent, closeStream : Boolean = false) : void {
Log.info("stop()");
_hls.stream.close();
return;
}
/**
* Seeks to the specified point in the timeline.
* @param event the event that this provider should dispatch once the seek is in target
* @param seconds the target point in the timeline
*/
public function seek(event : ClipEvent, seconds : Number) : void {
Log.info("seek()");
_hls.stream.seek(seconds);
_position = seconds;
_bufferedTime = seconds;
_clip.dispatch(ClipEventType.SEEK);
return;
}
/**
* File size in bytes.
*/
public function get fileSize() : Number {
return 0;
}
/**
* Current playhead time in seconds.
*/
public function get time() : Number {
return _position;
}
/**
* The point in timeline where the buffered data region begins, in seconds.
*/
public function get bufferStart() : Number {
return 0;
}
/**
* The point in timeline where the buffered data region ends, in seconds.
*/
public function get bufferEnd() : Number {
return _bufferedTime;
}
/**
* Does this provider support random seeking to unbuffered areas in the timeline?
*/
public function get allowRandomSeek() : Boolean {
// Log.info("allowRandomSeek()");
return _seekable;
}
/**
* Volume controller used to control the video volume.
*/
public function set volumeController(controller : VolumeController) : void {
_volumecontroller = controller;
_volumecontroller.netStream = _hls.stream;
return;
}
/**
* Is this provider in the process of stopping the stream?
* When stopped the provider should not dispatch any events resulting from events that
* might get triggered by the underlying streaming implementation.
*/
public function get stopping() : Boolean {
Log.info("stopping()");
return false;
}
/**
* The playlist instance.
*/
public function set playlist(playlist : Playlist) : void {
// Log.debug("set playlist()");
_playlist = playlist;
return;
}
public function get playlist() : Playlist {
Log.debug("get playlist()");
return _playlist;
}
/**
* Adds a callback public function to the NetConnection instance. This public function will fire ClipEvents whenever
* the callback is invoked in the connection.
* @param name
* @param listener
* @return
* @see ClipEventType#CONNECTION_EVENT
*/
public function addConnectionCallback(name : String, listener : Function) : void {
Log.debug("addConnectionCallback()");
return;
}
/**
* Adds a callback public function to the NetStream object. This public function will fire a ClipEvent of type StreamEvent whenever
* the callback has been invoked on the stream. The invokations typically come from a server-side app running
* on RTMP server.
* @param name
* @param listener
* @return
* @see ClipEventType.NETSTREAM_EVENT
*/
public function addStreamCallback(name : String, listener : Function) : void {
Log.debug("addStreamCallback()");
return;
}
/**
* Get the current stream callbacks.
* @return a dictionary of callbacks, keyed using callback names and values being the callback functions
*/
public function get streamCallbacks() : Dictionary {
Log.debug("get streamCallbacks()");
return null;
}
/**
* Gets the underlying NetStream object.
* @return the netStream currently in use, or null if this provider has not started streaming yet
*/
public function get netStream() : NetStream {
Log.debug("get netStream()");
return _hls.stream;
}
/**
* Gets the underlying netConnection object.
* @return the netConnection currently in use, or null if this provider has not started streaming yet
*/
public function get netConnection() : NetConnection {
Log.debug("get netConnection()");
return null;
}
/**
* Sets a time provider to be used by this StreamProvider. Normally the playhead time is queried from
* the NetStream.time property.
*
* @param timeProvider
*/
public function set timeProvider(timeProvider : TimeProvider) : void {
Log.debug("set timeProvider()");
_timeProvider = timeProvider;
return;
}
/**
* Gets the type of StreamProvider either http, rtmp, psuedo.
*/
public function get type() : String {
return "httpstreaming";
}
/**
* Switch the stream in realtime with / without dynamic stream switching support
*
* @param event ClipEvent the clip event
* @param clip Clip the clip to switch to
* @param netStreamPlayOptions Object the NetStreamPlayOptions object to enable dynamic stream switching
*/
public function switchStream(event : ClipEvent, clip : Clip, netStreamPlayOptions : Object = null) : void {
Log.info("switchStream()");
return;
}
}
}
|
package org.mangui.flowplayer {
import flash.display.DisplayObject;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.Dictionary;
import flash.media.Video;
import org.mangui.HLS.HLS;
import org.mangui.HLS.HLSEvent;
import org.mangui.HLS.HLSStates;
import org.mangui.HLS.utils.Log;
import org.flowplayer.model.Plugin;
import org.flowplayer.model.PluginModel;
import org.flowplayer.view.Flowplayer;
import org.flowplayer.controller.StreamProvider;
import org.flowplayer.controller.TimeProvider;
import org.flowplayer.controller.VolumeController;
import org.flowplayer.model.Clip;
import org.flowplayer.model.ClipType;
import org.flowplayer.model.ClipEvent;
import org.flowplayer.model.ClipEventType;
import org.flowplayer.model.Playlist;
import org.flowplayer.view.StageVideoWrapper;
public class HLSProvider implements StreamProvider,Plugin {
private var _volumecontroller : VolumeController;
private var _playlist : Playlist;
private var _timeProvider : TimeProvider;
private var _model : PluginModel;
private var _player : Flowplayer;
private var _clip : Clip;
private var _video : Video;
/** reference to the framework. **/
private var _hls : HLS;
private var _hlsState : String = HLSStates.IDLE;
// event values
private var _position : Number = 0;
private var _duration : Number = 0;
private var _bufferedTime : Number = 0;
private var _videoWidth : Number = -1;
private var _videoHeight : Number = -1;
private var _isManifestLoaded : Boolean = false;
private var _pauseAfterStart : Boolean;
private var _seekable : Boolean = false;
public function getDefaultConfig() : Object {
return null;
}
public function onConfig(model : PluginModel) : void {
Log.info("onConfig()");
_model = model;
}
public function onLoad(player : Flowplayer) : void {
Log.info("onLoad()");
_player = player;
_hls = new HLS();
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler);
_hls.addEventListener(HLSEvent.ERROR, _errorHandler);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler);
_hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler);
_hls.addEventListener(HLSEvent.STATE, _stateHandler);
var cfg:Object = _model.config;
var value : Object;
// parse configuration parameters
value = cfg.hls_debug;
if (value != null) {
Log.info("hls_debug:" + value);
Log.LOG_DEBUG_ENABLED = value as Boolean;
}
value = cfg.hls_debug2;
if (value != null) {
Log.info("hls_debug2:" + value);
Log.LOG_DEBUG2_ENABLED = value as Boolean;
}
value = cfg.hls_minbufferlength;
if (value != null) {
Log.info("hls_minbufferlength:" + value);
_hls.minBufferLength = value as Number;
}
value = cfg.hls_maxbufferlength;
if (value != null) {
Log.info("hls_maxbufferlength:" + value);
_hls.maxBufferLength = value as Number;
}
value = cfg.hls_startfromlowestlevel;
if (value != null) {
Log.info("hls_startfromlowestlevel:" + value);
_hls.startFromLowestLevel = value as Boolean;
}
value = cfg.hls_seekfromlowestlevel;
if (value != null) {
Log.info("hls_seekfromlowestlevel:" + value);
_hls.seekFromLowestLevel = value as Boolean;
}
value = cfg.hls_live_flushurlcache;
if (value != null) {
Log.info("hls_live_flushurlcache:" + value);
_hls.flushLiveURLCache = value as Boolean;
}
_model.dispatchOnLoad();
}
private function _completeHandler(event : HLSEvent) : void {
_clip.dispatch(ClipEventType.FINISH);
};
private function _errorHandler(event : HLSEvent) : void {
};
private function _manifestHandler(event : HLSEvent) : void {
_duration = event.levels[0].duration;
_isManifestLoaded = true;
_clip.duration = _duration;
_clip.dispatch(ClipEventType.METADATA);
_seekable = true;
//if (_hls.type == HLSTypes.LIVE) {
// _seekable = false;
//} else {
// _seekable = true;
//}
if (_pauseAfterStart == false) {
_hls.stream.play();
}
};
private function _mediaTimeHandler(event : HLSEvent) : void {
_position = Math.max(0, event.mediatime.position);
_duration = event.mediatime.duration;
_clip.duration = _duration;
_bufferedTime = event.mediatime.buffer + event.mediatime.position;
var videoWidth : Number = _video.videoWidth;
var videoHeight : Number = _video.videoHeight;
if (videoWidth && videoHeight) {
var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight;
if (changed) {
Log.info("video size changed to " + videoWidth + "/" + videoHeight);
_videoWidth = videoWidth;
_videoHeight = videoHeight;
_clip.originalWidth = videoWidth;
_clip.originalHeight = videoHeight;
_clip.dispatch(ClipEventType.START);
_clip.dispatch(ClipEventType.METADATA_CHANGED);
}
}
};
private function _stateHandler(event : HLSEvent) : void {
_hlsState = event.state;
// Log.txt("state:"+ _hlsState);
switch(event.state) {
case HLSStates.IDLE:
case HLSStates.PLAYING:
_clip.dispatch(ClipEventType.BUFFER_FULL);
break;
case HLSStates.PLAYING_BUFFERING:
_clip.dispatch(ClipEventType.BUFFER_EMPTY);
break;
case HLSStates.PAUSED_BUFFERING:
_clip.dispatch(ClipEventType.BUFFER_EMPTY);
_clip.dispatch(ClipEventType.PAUSE);
break;
case HLSStates.PAUSED:
_clip.dispatch(ClipEventType.BUFFER_FULL);
_clip.dispatch(ClipEventType.PAUSE);
break;
}
};
/**
* Starts loading the specivied clip. Once video data is available the provider
* must set it to the clip using <code>clip.setContent()</code>. Typically the video
* object passed to the clip is an instance of <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html">flash.media.Video</a>.
*
* @param event the event that this provider should dispatch once loading has successfully started,
* once dispatched the player will call <code>getVideo()</code>
* @param clip the clip to load
* @param pauseAfterStart if <code>true</code> the playback is paused on first frame and
* buffering is continued
* @see Clip#setContent()
* @see #getVideo()
*/
public function load(event : ClipEvent, clip : Clip, pauseAfterStart : Boolean = true) : void {
_clip = clip;
Log.info("load()" + clip.completeUrl);
_hls.load(clip.completeUrl);
_pauseAfterStart = pauseAfterStart;
clip.type = ClipType.VIDEO;
clip.dispatch(ClipEventType.BEGIN);
return;
}
/**
* Gets the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html">Video</a> object.
* A stream will be attached to the returned video object using <code>attachStream()</code>.
* @param clip the clip for which the Video object is queried for
* @see #attachStream()
*/
public function getVideo(clip : Clip) : DisplayObject {
Log.debug("getVideo()");
if (clip.useStageVideo) {
Log.debug("useStageVideo");
_video = new StageVideoWrapper(clip);
} else {
_video = new Video();
_video.smoothing = clip.smoothing;
}
return _video;
}
/**
* Attaches a stream to the specified display object.
* @param video the video object that was originally retrieved using <code>getVideo()</code>.
* @see #getVideo()
*/
public function attachStream(video : DisplayObject) : void {
Log.debug("attachStream()");
Video(video).attachNetStream(_hls.stream);
return;
}
/**
* Pauses playback.
* @param event the event that this provider should dispatch once loading has been successfully paused
*/
public function pause(event : ClipEvent) : void {
Log.info("pause()");
_hls.stream.pause();
return;
}
/**
* Resumes playback.
* @param event the event that this provider should dispatch once loading has been successfully resumed
*/
public function resume(event : ClipEvent) : void {
Log.info("resume()");
_hls.stream.resume();
_clip.dispatch(ClipEventType.RESUME);
return;
}
/**
* Stops and rewinds to the beginning of current clip.
* @param event the event that this provider should dispatch once loading has been successfully stopped
*/
public function stop(event : ClipEvent, closeStream : Boolean = false) : void {
Log.info("stop()");
_hls.stream.close();
return;
}
/**
* Seeks to the specified point in the timeline.
* @param event the event that this provider should dispatch once the seek is in target
* @param seconds the target point in the timeline
*/
public function seek(event : ClipEvent, seconds : Number) : void {
Log.info("seek()");
_hls.stream.seek(seconds);
_position = seconds;
_bufferedTime = seconds;
_clip.dispatch(ClipEventType.SEEK);
return;
}
/**
* File size in bytes.
*/
public function get fileSize() : Number {
return 0;
}
/**
* Current playhead time in seconds.
*/
public function get time() : Number {
return _position;
}
/**
* The point in timeline where the buffered data region begins, in seconds.
*/
public function get bufferStart() : Number {
return 0;
}
/**
* The point in timeline where the buffered data region ends, in seconds.
*/
public function get bufferEnd() : Number {
return _bufferedTime;
}
/**
* Does this provider support random seeking to unbuffered areas in the timeline?
*/
public function get allowRandomSeek() : Boolean {
// Log.info("allowRandomSeek()");
return _seekable;
}
/**
* Volume controller used to control the video volume.
*/
public function set volumeController(controller : VolumeController) : void {
_volumecontroller = controller;
_volumecontroller.netStream = _hls.stream;
return;
}
/**
* Is this provider in the process of stopping the stream?
* When stopped the provider should not dispatch any events resulting from events that
* might get triggered by the underlying streaming implementation.
*/
public function get stopping() : Boolean {
Log.info("stopping()");
return false;
}
/**
* The playlist instance.
*/
public function set playlist(playlist : Playlist) : void {
// Log.debug("set playlist()");
_playlist = playlist;
return;
}
public function get playlist() : Playlist {
Log.debug("get playlist()");
return _playlist;
}
/**
* Adds a callback public function to the NetConnection instance. This public function will fire ClipEvents whenever
* the callback is invoked in the connection.
* @param name
* @param listener
* @return
* @see ClipEventType#CONNECTION_EVENT
*/
public function addConnectionCallback(name : String, listener : Function) : void {
Log.debug("addConnectionCallback()");
return;
}
/**
* Adds a callback public function to the NetStream object. This public function will fire a ClipEvent of type StreamEvent whenever
* the callback has been invoked on the stream. The invokations typically come from a server-side app running
* on RTMP server.
* @param name
* @param listener
* @return
* @see ClipEventType.NETSTREAM_EVENT
*/
public function addStreamCallback(name : String, listener : Function) : void {
Log.debug("addStreamCallback()");
return;
}
/**
* Get the current stream callbacks.
* @return a dictionary of callbacks, keyed using callback names and values being the callback functions
*/
public function get streamCallbacks() : Dictionary {
Log.debug("get streamCallbacks()");
return null;
}
/**
* Gets the underlying NetStream object.
* @return the netStream currently in use, or null if this provider has not started streaming yet
*/
public function get netStream() : NetStream {
Log.debug("get netStream()");
return _hls.stream;
}
/**
* Gets the underlying netConnection object.
* @return the netConnection currently in use, or null if this provider has not started streaming yet
*/
public function get netConnection() : NetConnection {
Log.debug("get netConnection()");
return null;
}
/**
* Sets a time provider to be used by this StreamProvider. Normally the playhead time is queried from
* the NetStream.time property.
*
* @param timeProvider
*/
public function set timeProvider(timeProvider : TimeProvider) : void {
Log.debug("set timeProvider()");
_timeProvider = timeProvider;
return;
}
/**
* Gets the type of StreamProvider either http, rtmp, psuedo.
*/
public function get type() : String {
return "httpstreaming";
}
/**
* Switch the stream in realtime with / without dynamic stream switching support
*
* @param event ClipEvent the clip event
* @param clip Clip the clip to switch to
* @param netStreamPlayOptions Object the NetStreamPlayOptions object to enable dynamic stream switching
*/
public function switchStream(event : ClipEvent, clip : Clip, netStreamPlayOptions : Object = null) : void {
Log.info("switchStream()");
return;
}
}
}
|
remove unused import
|
remove unused import
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
a7d413fa70a55a8050ba5ca6c98938c2d5533c0b
|
src/laml/display/Skin.as
|
src/laml/display/Skin.as
|
package laml.display {
import flash.display.DisplayObject;
import flash.display.Sprite;
public class Skin extends Sprite implements ISkin {
public function getBitmapByName(alias:String):DisplayObject {
if(hasOwnProperty(alias)) {
return new this[alias]() as DisplayObject;
}
return null;
}
}
}
|
package laml.display {
import flash.display.DisplayObject;
import flash.display.Sprite;
import mx.core.BitmapAsset;
import mx.core.FontAsset;
import mx.core.IFlexAsset;
import mx.core.IFlexDisplayObject;
import mx.core.SpriteAsset;
public class Skin extends Sprite implements ISkin {
private var bitmapAsset:BitmapAsset;
private var fontAsset:FontAsset;
private var iFlexAsset:IFlexAsset;
private var iFlexDisplayObject:IFlexDisplayObject;
private var spriteAsset:SpriteAsset;
public function getBitmapByName(alias:String):DisplayObject {
if(hasOwnProperty(alias)) {
return new this[alias]() as DisplayObject;
}
return null;
}
}
}
|
Put MX dependencies in skin
|
Put MX dependencies in skin
git-svn-id: 02605e11d3a461bc7e12f3f3880edf4b0c8dcfd0@4281 3e7533ad-8678-4d30-8e38-00a379d3f0d0
|
ActionScript
|
mit
|
lukebayes/laml
|
cebd5948b8721d3f147f0c751db5df88a2d1c7be
|
WEB-INF/lps/lfc/kernel/swf9/LzMouseKernel.as
|
WEB-INF/lps/lfc/kernel/swf9/LzMouseKernel.as
|
/**
* LzMouseKernel.as
*
* @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
// Receives mouse events from the runtime
class LzMouseKernel {
#passthrough (toplevel:true) {
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.ui.*;
}#
// sends mouse events to the callback
static function __sendEvent(view, eventname) {
if (LzMouseKernel.__callback) LzMouseKernel.__scope[LzMouseKernel.__callback](eventname, view);
//Debug.write('LzMouseKernel event', eventname);
}
static var __callback = null;
static var __scope = null;
static var __lastMouseDown = null;
static var __listeneradded:Boolean = false ;
/**
* Shows or hides the hand cursor for all clickable views.
*/
static var showhandcursor:Boolean = true;
static function setCallback (scope, funcname) {
LzMouseKernel.__scope = scope;
LzMouseKernel.__callback = funcname;
if (LzMouseKernel.__listeneradded == false) {
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mouseHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_UP, __mouseHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_DOWN, __mouseHandler);
LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, __mouseLeavesHandler);
LzMouseKernel.__listeneradded = true;
}
}
// Handles global mouse events
static function __mouseHandler(event:MouseEvent):void {
var eventname = 'on' + event.type.toLowerCase();
if (eventname == 'onmouseup' && __lastMouseDown != null) {
// call mouseup on the sprite that got the last mouse down
LzMouseKernel.__lastMouseDown.__globalmouseup(event);
__lastMouseDown = null;
} else {
LzMouseKernel.__sendEvent(null, eventname);
}
}
// handles MOUSE_LEAVES event
static function __mouseLeavesHandler(event:Event):void {
var eventname = 'on' + event.type.toLowerCase();
LzMouseKernel.__sendEvent(null, eventname);
}
/**
* Shows or hides the hand cursor for all clickable views.
* @param Boolean show: true shows the hand cursor for buttons, false hides it
*/
static function showHandCursor (show) {
LzMouseKernel.showhandcursor = show;
}
static var __amLocked:Boolean = false;
static var cursorSprite:Sprite = null;
static var globalCursorResource:String = null;
static var lastCursorResource:String = null;
/**
* Sets the cursor to a resource
* @param String what: The resource to use as the cursor.
*/
static function setCursorGlobal ( what:String ){
globalCursorResource = what;
setCursorLocal(what);
}
static function setCursorLocal ( what:String ) {
if ( LzMouseKernel.__amLocked ) { return; }
Mouse.hide();
cursorSprite.x = LFCApplication.stage.mouseX;
cursorSprite.y = LFCApplication.stage.mouseY;
LFCApplication.setChildIndex(cursorSprite, LFCApplication._sprite.numChildren-1);
if (lastCursorResource != what) {
if (cursorSprite.numChildren > 0) {
cursorSprite.removeChildAt(0);
}
var resourceSprite = getCursorResource(what);
cursorSprite.addChild( resourceSprite );
lastCursorResource = what;
}
// respond to mouse move events
cursorSprite.startDrag();
LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
cursorSprite.visible = true;
}
static function mouseLeaveHandler(evt:Event):void {
cursorSprite.visible = false;
}
static function getCursorResource (resource:String):Sprite {
var resinfo = LzResourceLibrary[resource];
var assetclass;
var frames = resinfo.frames;
var asset:Sprite;
// single frame resources get an entry in LzResourceLibrary which has
// 'assetclass' pointing to the resource Class object.
if (resinfo.assetclass is Class) {
assetclass = resinfo.assetclass;
} else {
// Multiframe resources have an array of Class objects in frames[]
assetclass = frames[0];
}
if (! assetclass) return null;
asset = new assetclass();
asset.scaleX = 1.0;
asset.scaleY = 1.0;
//Debug.write('cursor asset', asset);
return asset;
}
/**
* This function restores the default cursor if there is no locked cursor on
* the screen.
*
* @access private
*/
static function restoreCursor ( ){
if ( LzMouseKernel.__amLocked ) { return; }
cursorSprite.stopDrag();
cursorSprite.visible = false;
globalCursorResource = null;
Mouse.show();
}
/** Called by LzSprite to restore cursor to global value.
*/
static function restoreCursorLocal ( ){
if ( LzMouseKernel.__amLocked ) { return; }
if (globalCursorResource == null) {
// Restore to system default pointer
restoreCursor();
} else {
// Restore to the last value set by setCursorGlobal
setCursorLocal(globalCursorResource);
}
}
/**
* Prevents the cursor from being changed until unlock is called.
*
*/
static function lock (){
LzMouseKernel.__amLocked = true;
}
/**
* Restores the default cursor.
*
*/
static function unlock (){
LzMouseKernel.__amLocked = false;
LzMouseKernel.restoreCursor();
}
static function initCursor () {
cursorSprite = new Sprite();
cursorSprite.mouseChildren = false;
cursorSprite.mouseEnabled = false;
// Add the cursor DisplayObject to the root sprite
LFCApplication.addChild(cursorSprite);
cursorSprite.x = -10000;
cursorSprite.y = -10000;
}
}
|
/**
* LzMouseKernel.as
*
* @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
// Receives mouse events from the runtime
class LzMouseKernel {
#passthrough (toplevel:true) {
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.ui.*;
}#
// sends mouse events to the callback
static function __sendEvent(view, eventname) {
if (LzMouseKernel.__callback) LzMouseKernel.__scope[LzMouseKernel.__callback](eventname, view);
//Debug.write('LzMouseKernel event', eventname);
}
static var __callback = null;
static var __scope = null;
static var __lastMouseDown = null;
static var __mouseLeft:Boolean = false;
static var __listeneradded:Boolean = false ;
/**
* Shows or hides the hand cursor for all clickable views.
*/
static var showhandcursor:Boolean = true;
static function setCallback (scope, funcname) {
LzMouseKernel.__scope = scope;
LzMouseKernel.__callback = funcname;
if (LzMouseKernel.__listeneradded == false) {
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mouseHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_UP, __mouseHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_DOWN, __mouseHandler);
LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, __mouseLeavesHandler);
LzMouseKernel.__listeneradded = true;
}
}
// Handles global mouse events
static function __mouseHandler(event:MouseEvent):void {
var eventname = 'on' + event.type.toLowerCase();
if (eventname == 'onmouseup' && __lastMouseDown != null) {
// call mouseup on the sprite that got the last mouse down
LzMouseKernel.__lastMouseDown.__globalmouseup(event);
__lastMouseDown = null;
} else {
if (__mouseLeft && event.buttonDown && LzMouseKernel.__lastMouseDown != null) {
__mouseLeft = false;
//Debug.write(eventname, event.buttonDown, LzMouseKernel.__lastMouseDown);
var ev = new MouseEvent('mouseup');
LzMouseKernel.__lastMouseDown.__globalmouseup(ev);
LzMouseKernel.__lastMouseDown = null;
}
LzMouseKernel.__sendEvent(null, eventname);
}
}
// handles MOUSE_LEAVES event
static function __mouseLeavesHandler(event:Event):void {
var eventname = 'on' + event.type.toLowerCase();
LzMouseKernel.__mouseLeft = true;
LzMouseKernel.__sendEvent(null, eventname);
}
/**
* Shows or hides the hand cursor for all clickable views.
* @param Boolean show: true shows the hand cursor for buttons, false hides it
*/
static function showHandCursor (show) {
LzMouseKernel.showhandcursor = show;
}
static var __amLocked:Boolean = false;
static var cursorSprite:Sprite = null;
static var globalCursorResource:String = null;
static var lastCursorResource:String = null;
/**
* Sets the cursor to a resource
* @param String what: The resource to use as the cursor.
*/
static function setCursorGlobal ( what:String ){
globalCursorResource = what;
setCursorLocal(what);
}
static function setCursorLocal ( what:String ) {
if ( LzMouseKernel.__amLocked ) { return; }
Mouse.hide();
cursorSprite.x = LFCApplication.stage.mouseX;
cursorSprite.y = LFCApplication.stage.mouseY;
LFCApplication.setChildIndex(cursorSprite, LFCApplication._sprite.numChildren-1);
if (lastCursorResource != what) {
if (cursorSprite.numChildren > 0) {
cursorSprite.removeChildAt(0);
}
var resourceSprite = getCursorResource(what);
cursorSprite.addChild( resourceSprite );
lastCursorResource = what;
}
// respond to mouse move events
cursorSprite.startDrag();
LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
cursorSprite.visible = true;
}
static function mouseLeaveHandler(evt:Event):void {
cursorSprite.visible = false;
}
static function getCursorResource (resource:String):Sprite {
var resinfo = LzResourceLibrary[resource];
var assetclass;
var frames = resinfo.frames;
var asset:Sprite;
// single frame resources get an entry in LzResourceLibrary which has
// 'assetclass' pointing to the resource Class object.
if (resinfo.assetclass is Class) {
assetclass = resinfo.assetclass;
} else {
// Multiframe resources have an array of Class objects in frames[]
assetclass = frames[0];
}
if (! assetclass) return null;
asset = new assetclass();
asset.scaleX = 1.0;
asset.scaleY = 1.0;
//Debug.write('cursor asset', asset);
return asset;
}
/**
* This function restores the default cursor if there is no locked cursor on
* the screen.
*
* @access private
*/
static function restoreCursor ( ){
if ( LzMouseKernel.__amLocked ) { return; }
cursorSprite.stopDrag();
cursorSprite.visible = false;
globalCursorResource = null;
Mouse.show();
}
/** Called by LzSprite to restore cursor to global value.
*/
static function restoreCursorLocal ( ){
if ( LzMouseKernel.__amLocked ) { return; }
if (globalCursorResource == null) {
// Restore to system default pointer
restoreCursor();
} else {
// Restore to the last value set by setCursorGlobal
setCursorLocal(globalCursorResource);
}
}
/**
* Prevents the cursor from being changed until unlock is called.
*
*/
static function lock (){
LzMouseKernel.__amLocked = true;
}
/**
* Restores the default cursor.
*
*/
static function unlock (){
LzMouseKernel.__amLocked = false;
LzMouseKernel.restoreCursor();
}
static function initCursor () {
cursorSprite = new Sprite();
cursorSprite.mouseChildren = false;
cursorSprite.mouseEnabled = false;
// Add the cursor DisplayObject to the root sprite
LFCApplication.addChild(cursorSprite);
cursorSprite.x = -10000;
cursorSprite.y = -10000;
}
}
|
Change 20090206-maxcarlson-y by [email protected] on 2009-02-06 19:03:11 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20090206-maxcarlson-y by [email protected] on 2009-02-06 19:03:11 PST
in /Users/maxcarlson/openlaszlo/trunk-clean
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: Send mouseup events when mouse goes up outside the app in swf9
Bugs Fixed: LPP-7724 - Mouse events behave wrong in opaque mode (FireFox)
Technical Reviewer: [email protected]
QA Reviewer: hminsky
Details: Add mouseLeft flag to track whether the mouse left the app. Send a mouseup event if the mouse left the app, the button is still down and there is a view to receive the event (lastMouseDown)
Tests: See LPP-7724.
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@12771 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
aeb78a402d31c40aa301925ff009c884513b3a8d
|
src/goplayer/Player.as
|
src/goplayer/Player.as
|
package goplayer
{
public class Player
implements FlashNetConnectionListener, FlashNetStreamListener
{
private const DEFAULT_VOLUME : Number = .8
private const START_BUFFER : Duration = Duration.seconds(.1)
private const SMALL_BUFFER : Duration = Duration.seconds(3)
private const LARGE_BUFFER : Duration = Duration.seconds(60)
private const finishingListeners : Array = []
private var _movie : Movie
private var connection : FlashNetConnection
private var triedConnectingUsingDefaultPorts : Boolean = false
private var stream : FlashNetStream = null
private var metadata : Object = null
private var _volume : Number = DEFAULT_VOLUME
private var _paused : Boolean = false
private var _buffering : Boolean = false
public function Player
(movie : Movie, connection : FlashNetConnection)
{
_movie = movie, this.connection = connection
connection.listener = this
}
public function get movie() : Movie
{ return _movie }
public function addFinishingListener
(value : PlayerFinishingListener) : void
{ finishingListeners.push(value) }
// -----------------------------------------------------
public function start() : void
{ connection.connect(movie.rtmpURL) }
public function handleConnectionFailed() : void
{
if (movie.rtmpURL.hasPort && !triedConnectingUsingDefaultPorts)
connectUsingDefaultPorts()
else
debug("Could not connect using RTMP; giving up.")
}
private function connectUsingDefaultPorts() : void
{
debug("Trying to connect using default RTMP ports.")
triedConnectingUsingDefaultPorts = true
connection.connect(movie.rtmpURL.withoutPort)
}
public function handleConnectionClosed() : void
{}
// -----------------------------------------------------
public function handleConnectionEstablished() : void
{
stream = connection.getNetStream()
stream.listener = this
stream.bufferTime = START_BUFFER
stream.volume = volume
stream.play(movie.rtmpStreams)
_buffering = true
if (paused)
stream.paused = true
}
public function handleNetStreamMetadata(data : Object) : void
{ metadata = data }
public function handleBufferFilled() : void
{ handleBufferingFinished() }
private function handleBufferingFinished() : void
{
useLargeBuffer()
_buffering = false
}
public function handleBufferEmptied() : void
{
if (finishedPlaying)
handleFinishedPlaying()
else
handleBufferingStarted()
}
private function handleBufferingStarted() : void
{
useSmallBuffer()
_buffering = true
}
private function useSmallBuffer() : void
{ stream.bufferTime = SMALL_BUFFER }
private function useLargeBuffer() : void
{ stream.bufferTime = LARGE_BUFFER }
public function get buffering() : Boolean
{ return _buffering }
public function handleStreamingStopped() : void
{
if (finishedPlaying)
handleFinishedPlaying()
}
private function handleFinishedPlaying() : void
{
debug("Finished playing.")
for each (var listener : PlayerFinishingListener in finishingListeners)
listener.handleMovieFinishedPlaying()
}
private function get finishedPlaying() : Boolean
{ return timeRemaining.seconds < 1 }
private function get timeRemaining() : Duration
{ return streamLength.minus(playheadPosition) }
// -----------------------------------------------------
public function get paused() : Boolean
{ return _paused }
public function set paused(value : Boolean) : void
{
_paused = value
if (stream)
stream.paused = value
}
public function togglePaused() : void
{ paused = !paused }
// -----------------------------------------------------
public function get playheadPosition() : Duration
{ return stream ? stream.playheadPosition : Duration.ZERO }
public function set playheadPosition(value : Duration) : void
{ stream.playheadPosition = value }
public function seekBy(delta : Duration) : void
{ playheadPosition = playheadPosition.plus(delta) }
public function rewind() : void
{ playheadPosition = Duration.ZERO }
// -----------------------------------------------------
public function get volume() : Number
{ return _volume }
public function set volume(value : Number) : void
{
_volume = value
if (stream)
stream.volume = value
}
public function changeVolumeBy(delta : Number) : void
{ volume = volume + delta }
// -----------------------------------------------------
public function get aspectRatio() : Number
{ return movie.aspectRatio }
public function get bufferTime() : Duration
{ return stream ? stream.bufferTime : Duration.ZERO }
public function get bufferLength() : Duration
{ return stream ? stream.bufferLength : Duration.ZERO }
public function get bufferFillRatio() : Number
{ return Math.min(1, bufferLength.seconds / bufferTime.seconds) }
public function get streamLength() : Duration
{
return metadata
? Duration.seconds(metadata.duration)
: movie.duration
}
public function get bitrate() : Bitrate
{ return stream ? stream.bitrate : Bitrate.ZERO }
public function get bandwidth() : Bitrate
{ return stream ? stream.bandwidth : Bitrate.ZERO }
public function get highQualityDimensions() : Dimensions
{
var result : Dimensions = Dimensions.ZERO
for each (var stream : RTMPStream in movie.rtmpStreams)
if (stream.dimensions.isGreaterThan(result))
result = stream.dimensions
return result
}
}
}
|
package goplayer
{
public class Player
implements FlashNetConnectionListener, FlashNetStreamListener
{
private const DEFAULT_VOLUME : Number = .8
private const START_BUFFER : Duration = Duration.seconds(.1)
private const SMALL_BUFFER : Duration = Duration.seconds(3)
private const LARGE_BUFFER : Duration = Duration.seconds(60)
private const finishingListeners : Array = []
private var _movie : Movie
private var connection : FlashNetConnection
private var triedConnectingUsingDefaultPorts : Boolean = false
private var stream : FlashNetStream = null
private var metadata : Object = null
private var _volume : Number = DEFAULT_VOLUME
private var _paused : Boolean = false
private var _buffering : Boolean = false
public function Player
(movie : Movie, connection : FlashNetConnection)
{
_movie = movie, this.connection = connection
connection.listener = this
}
public function get movie() : Movie
{ return _movie }
public function addFinishingListener
(value : PlayerFinishingListener) : void
{ finishingListeners.push(value) }
// -----------------------------------------------------
public function start() : void
{ connection.connect(movie.rtmpURL) }
public function handleConnectionFailed() : void
{
if (movie.rtmpURL.hasPort && !triedConnectingUsingDefaultPorts)
connectUsingDefaultPorts()
else
debug("Could not connect using RTMP; giving up.")
}
private function connectUsingDefaultPorts() : void
{
debug("Trying to connect using default RTMP ports.")
triedConnectingUsingDefaultPorts = true
connection.connect(movie.rtmpURL.withoutPort)
}
public function handleConnectionClosed() : void
{}
// -----------------------------------------------------
public function handleConnectionEstablished() : void
{
stream = connection.getNetStream()
stream.listener = this
stream.bufferTime = START_BUFFER
stream.volume = volume
stream.play(movie.rtmpStreams)
_buffering = true
if (paused)
stream.paused = true
}
public function handleNetStreamMetadata(data : Object) : void
{ metadata = data }
public function handleBufferFilled() : void
{ handleBufferingFinished() }
private function handleBufferingFinished() : void
{
_buffering = false
// Make sure to let playback resume first.
later(useLargeBuffer)
}
public function handleBufferEmptied() : void
{
if (finishedPlaying)
handleFinishedPlaying()
else
handleBufferingStarted()
}
private function handleBufferingStarted() : void
{
useSmallBuffer()
_buffering = true
}
private function useStartBuffer() : void
{ stream.bufferTime = START_BUFFER }
private function useSmallBuffer() : void
{ stream.bufferTime = SMALL_BUFFER }
private function useLargeBuffer() : void
{ stream.bufferTime = LARGE_BUFFER }
public function get buffering() : Boolean
{ return _buffering }
public function handleStreamingStopped() : void
{
if (finishedPlaying)
handleFinishedPlaying()
}
private function handleFinishedPlaying() : void
{
debug("Finished playing.")
for each (var listener : PlayerFinishingListener in finishingListeners)
listener.handleMovieFinishedPlaying()
}
private function get finishedPlaying() : Boolean
{ return timeRemaining.seconds < 1 }
private function get timeRemaining() : Duration
{ return streamLength.minus(playheadPosition) }
// -----------------------------------------------------
public function get paused() : Boolean
{ return _paused }
public function set paused(value : Boolean) : void
{
_paused = value
if (stream)
stream.paused = value
}
public function togglePaused() : void
{ paused = !paused }
// -----------------------------------------------------
public function get playheadPosition() : Duration
{ return stream ? stream.playheadPosition : Duration.ZERO }
public function set playheadPosition(value : Duration) : void
{
useStartBuffer()
stream.playheadPosition = value
}
public function seekBy(delta : Duration) : void
{ playheadPosition = playheadPosition.plus(delta) }
public function rewind() : void
{ playheadPosition = Duration.ZERO }
// -----------------------------------------------------
public function get volume() : Number
{ return _volume }
public function set volume(value : Number) : void
{
_volume = value
if (stream)
stream.volume = value
}
public function changeVolumeBy(delta : Number) : void
{ volume = volume + delta }
// -----------------------------------------------------
public function get aspectRatio() : Number
{ return movie.aspectRatio }
public function get bufferTime() : Duration
{ return stream ? stream.bufferTime : Duration.ZERO }
public function get bufferLength() : Duration
{ return stream ? stream.bufferLength : Duration.ZERO }
public function get bufferFillRatio() : Number
{ return Math.min(1, bufferLength.seconds / bufferTime.seconds) }
public function get streamLength() : Duration
{
return metadata
? Duration.seconds(metadata.duration)
: movie.duration
}
public function get bitrate() : Bitrate
{ return stream ? stream.bitrate : Bitrate.ZERO }
public function get bandwidth() : Bitrate
{ return stream ? stream.bandwidth : Bitrate.ZERO }
public function get highQualityDimensions() : Dimensions
{
var result : Dimensions = Dimensions.ZERO
for each (var stream : RTMPStream in movie.rtmpStreams)
if (stream.dimensions.isGreaterThan(result))
result = stream.dimensions
return result
}
}
}
|
Tweak buffering strategy.
|
Tweak buffering strategy.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
f107cd1e6b00a80bfb26cb50e37041a1763a4e67
|
src/aerys/minko/scene/node/camera/Camera.as
|
src/aerys/minko/scene/node/camera/Camera.as
|
package aerys.minko.scene.node.camera
{
import aerys.minko.ns.minko_scene;
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;
import aerys.minko.type.math.Vector4;
import flash.geom.Point;
use namespace minko_scene;
public class Camera extends AbstractCamera
{
public static const DEFAULT_FOV : Number = Math.PI * .25;
private var _tmpVector:Vector4 = new Vector4();
public function get fieldOfView() : Number
{
return _cameraData.fieldOfView;
}
public function set fieldOfView(value : Number) : void
{
_cameraData.fieldOfView = value;
}
public function Camera(fieldOfView : Number = DEFAULT_FOV,
zNear : Number = AbstractCamera.DEFAULT_ZNEAR,
zFar : Number = AbstractCamera.DEFAULT_ZFAR)
{
super(zNear, zFar);
_cameraData.fieldOfView = fieldOfView;
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Camera = new Camera(fieldOfView, zNear, zFar);
clone.transform.copyFrom(this.transform);
return clone as AbstractSceneNode;
}
override public function unproject(x : Number, y : Number, out : Ray = null) : Ray
{
if (!(root is Scene))
throw new Error('Camera must be in the scene to unproject vectors.');
out ||= new Ray();
var sceneBindings : DataBindings = (root as Scene).bindings;
var zNear : Number = _cameraData.zNear;
var zFar : Number = _cameraData.zFar;
var fovDiv2 : Number = _cameraData.fieldOfView * 0.5;
var width : Number = sceneBindings.getProperty('viewportWidth');
var height : Number = sceneBindings.getProperty('viewportHeight');
var xPercent : Number = 2.0 * (x / width - 0.5);
var yPercent : Number = 2.0 * (y / height - 0.5);
var dx : Number = Math.tan(fovDiv2) * xPercent * (width / height);
var dy : Number = -Math.tan(fovDiv2) * yPercent;
out.origin.set(dx * zNear, dy * zNear, zNear);
out.direction.set(dx * zNear, dy * zNear, zNear).normalize();
localToWorld(out.origin, out.origin);
localToWorld(out.direction, out.direction, true);
return out;
}
override public function project(localToWorld : Matrix4x4, output : Point = null) : Point
{
output ||= new Point();
var sceneBindings : DataBindings = (root as Scene).bindings;
var width : Number = sceneBindings.getProperty('viewportWidth');
var height : Number = sceneBindings.getProperty('viewportHeight');
var translation : Vector4 = localToWorld.getTranslation();
var screenPosition : Vector4 = _cameraData.worldToScreen.projectVector(translation, _tmpVector);
output.x = width * ((screenPosition.x + 1.0) * .5);
output.y = height * ((1.0 - ((screenPosition.y + 1.0) * .5)));
return output;
}
public function projectPoint(point : Vector4, output : Point = null) : Point
{
output ||= new Point();
var sceneBindings : DataBindings = (root as Scene).bindings;
var width : Number = sceneBindings.getProperty('viewportWidth');
var height : Number = sceneBindings.getProperty('viewportHeight');
var screenPosition : Vector4 = _cameraData.worldToScreen.projectVector(point, _tmpVector);
output.x = width * ((screenPosition.x + 1.0) * .5);
output.y = height * ((1.0 - ((screenPosition.y + 1.0) * .5)));
return output;
}
}
}
|
package aerys.minko.scene.node.camera
{
import aerys.minko.ns.minko_scene;
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;
import aerys.minko.type.math.Vector4;
import flash.geom.Point;
use namespace minko_scene;
public class Camera extends AbstractCamera
{
public static const DEFAULT_FOV : Number = Math.PI * .25;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
public function get fieldOfView() : Number
{
return _cameraData.fieldOfView;
}
public function set fieldOfView(value : Number) : void
{
_cameraData.fieldOfView = value;
}
public function Camera(fieldOfView : Number = DEFAULT_FOV,
zNear : Number = AbstractCamera.DEFAULT_ZNEAR,
zFar : Number = AbstractCamera.DEFAULT_ZFAR)
{
super(zNear, zFar);
_cameraData.fieldOfView = fieldOfView;
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Camera = new Camera(fieldOfView, zNear, zFar);
clone.transform.copyFrom(this.transform);
return clone as AbstractSceneNode;
}
override public function unproject(x : Number, y : Number, out : Ray = null) : Ray
{
if (!(root is Scene))
throw new Error('Camera must be in the scene to unproject vectors.');
out ||= new Ray();
var sceneBindings : DataBindings = (root as Scene).bindings;
var zNear : Number = _cameraData.zNear;
var zFar : Number = _cameraData.zFar;
var fovDiv2 : Number = _cameraData.fieldOfView * 0.5;
var width : Number = sceneBindings.getProperty('viewportWidth');
var height : Number = sceneBindings.getProperty('viewportHeight');
var xPercent : Number = 2.0 * (x / width - 0.5);
var yPercent : Number = 2.0 * (y / height - 0.5);
var dx : Number = Math.tan(fovDiv2) * xPercent * (width / height);
var dy : Number = -Math.tan(fovDiv2) * yPercent;
out.origin.set(dx * zNear, dy * zNear, zNear);
out.direction.set(dx * zNear, dy * zNear, zNear).normalize();
localToWorld(out.origin, out.origin);
localToWorld(out.direction, out.direction, true);
return out;
}
override public function project(localToWorld : Matrix4x4, output : Point = null) : Point
{
output ||= new Point();
var sceneBindings : DataBindings = (root as Scene).bindings;
var width : Number = sceneBindings.getProperty('viewportWidth');
var height : Number = sceneBindings.getProperty('viewportHeight');
var translation : Vector4 = localToWorld.getTranslation();
var screenPosition : Vector4 = _cameraData.worldToScreen.projectVector(
translation, TMP_VECTOR4
);
output.x = width * ((screenPosition.x + 1.0) * .5);
output.y = height * ((1.0 - ((screenPosition.y + 1.0) * .5)));
return output;
}
}
}
|
remove duplicate definition of Camera.project() and set the tmp Vector4 as a private static const
|
remove duplicate definition of Camera.project() and set the tmp Vector4 as a private static const
|
ActionScript
|
mit
|
aerys/minko-as3
|
719e38204519a15fb4e18341f87aad393b1957d0
|
krew-framework/krewfw/builtin_actor/system/KrewScenarioPlayer.as
|
krew-framework/krewfw/builtin_actor/system/KrewScenarioPlayer.as
|
package krewfw.builtin_actor.system {
import krewfw.core.KrewActor;
/**
* Base class for event-driven command player.
*/
//------------------------------------------------------------
public class KrewScenarioPlayer extends KrewActor {
private var _eventList:Array;
private var _eventsByTrigger:Object;
private var _triggers:Object = {};
private var _methods:Object = {};
//------------------------------------------------------------
public function KrewScenarioPlayer() {
displayable = false;
}
protected override function onDispose():void {
_eventList = null;
_eventsByTrigger = null;
_triggers = null;
_methods = null;
}
//------------------------------------------------------------
// public
//------------------------------------------------------------
/**
* @params eventList Example:
* <pre>
* [
* {
* "trigger_key" : "start_turn",
* "trigger_params": {"turn": 1},
* "method": "dialog",
* "params": {
* "messages": [ ... ]
* },
* "next": [
* {
* "method": "overlay",
* "params": { ... }
* }
* ]
* },
* ...
* ]
* </pre>
*/
public function setData(eventList:Array):void {
_eventList = eventList;
_eventsByTrigger = {};
for each (var eventData:Object in _eventList) {
var triggerKey:String = eventData.trigger_key;
if (!triggerKey) { continue; }
if (!_eventsByTrigger[triggerKey]) {
_eventsByTrigger[triggerKey] = [];
}
_eventsByTrigger[triggerKey].push(eventData);
}
}
/**
* @param checker Schema: function(eventArgs;Object, triggerParams:Object):Boolean
*/
public function addTrigger(triggerKey:String, eventName:String, checker:Function):void {
_triggers[triggerKey] = new TriggerInfo(eventName, checker);
}
/**
* @param triggerInfoList Example:
* <pre>
* [
* ["triggerKey", "eventName", checkerFunc],
* ...
* ]
* </pre>
*/
public function addTriggers(triggerInfoList:Array):void {
for each (var info:Array in triggerInfoList) {
addTrigger(info[0], info[1], info[2]);
}
}
/**
* @param handler Schema: function(params:Object, onComplete:Function):void
*/
public function addMethod(methodName:String, handler:Function):void {
_methods[methodName] = handler;
}
/**
* @param triggerInfoList Example:
* <pre>
* [
* ["methodName", methodFunc],
* ...
* ]
* </pre>
*/
public function addMethods(methodList:Array):void {
for each (var info:Array in methodList) {
addMethod(info[0], info[1]);
}
}
/**
* Activate player.
* Please call this after setData(), addTriggers(), addMethods(), and init().
*/
public function activate():void {
for (var triggerKey:String in _eventsByTrigger) {
_listenEvent(triggerKey);
}
}
//------------------------------------------------------------
// private
//------------------------------------------------------------
private function _listenEvent(triggerKey:String):void {
var info:TriggerInfo = _triggers[triggerKey];
if (!info) {
throw new Error('[KrewEventPlayer] trigger not registered: ' + triggerKey);
return;
}
listen(info.eventName, function(eventArgs:Object):void {
for each (var eventData:Object in _eventsByTrigger[triggerKey]) {
var triggerParams:Object = eventData.trigger_params;
if (!info.checker(eventArgs, triggerParams)) { continue; }
_callMethod(eventData);
}
});
}
private function _callMethod(eventData:Object):void {
var methodName:String = eventData.method;
if (!methodName) {
throw new Error('[KrewEventPlayer] method name not found. (trigger: '
+ eventData.trigger_key + ')');
return;
}
var method:Function = _methods[methodName];
if (method == null) {
throw new Error('[KrewEventPlayer] method not registered: ' + methodName);
return;
}
method(eventData.params, function():void {
_callNextMethod(eventData);
});
}
private function _callNextMethod(parentEventData:Object):void {
if (!parentEventData.next) { return; }
for each (var nextEventData:Object in parentEventData.next) {
_callMethod(nextEventData);
}
}
}
}
class TriggerInfo {
public var eventName:String;
public var checker:Function;
public function TriggerInfo(eventName:String, checker:Function) {
this.eventName = eventName;
this.checker = checker;
}
}
|
package krewfw.builtin_actor.system {
import krewfw.core.KrewActor;
/**
* Base class for event-driven command player.
*/
//------------------------------------------------------------
public class KrewScenarioPlayer extends KrewActor {
// You can customize object keys.
public var TRIGGER_KEY :String = "trigger_key";
public var TRIGGER_PARAMS :String = "trigger_params";
public var METHOD :String = "method";
public var PARAMS :String = "params";
public var NEXT :String = "next";
private var _eventList:Array;
private var _eventsByTrigger:Object;
private var _triggers:Object = {};
private var _methods:Object = {};
//------------------------------------------------------------
public function KrewScenarioPlayer() {
displayable = false;
}
protected override function onDispose():void {
_eventList = null;
_eventsByTrigger = null;
_triggers = null;
_methods = null;
}
//------------------------------------------------------------
// public
//------------------------------------------------------------
/**
* @params eventList Example:
* <pre>
* [
* {
* "trigger_key" : "start_turn",
* "trigger_params": {"turn": 1},
* "method": "dialog",
* "params": {
* "messages": [ ... ]
* },
* "next": [
* {
* "method": "overlay",
* "params": { ... }
* }
* ]
* },
* ...
* ]
* </pre>
*/
public function setData(eventList:Array):void {
_eventList = eventList;
_eventsByTrigger = {};
for each (var eventData:Object in _eventList) {
var triggerKey:String = eventData[TRIGGER_KEY];
if (!triggerKey) { continue; }
if (!_eventsByTrigger[triggerKey]) {
_eventsByTrigger[triggerKey] = [];
}
_eventsByTrigger[triggerKey].push(eventData);
}
}
/**
* @param checker Schema: function(eventArgs;Object, triggerParams:Object):Boolean
*/
public function addTrigger(triggerKey:String, eventName:String, checker:Function):void {
_triggers[triggerKey] = new TriggerInfo(eventName, checker);
}
/**
* @param triggerInfoList Example:
* <pre>
* [
* ["triggerKey", "eventName", checkerFunc],
* ...
* ]
* </pre>
*/
public function addTriggers(triggerInfoList:Array):void {
for each (var info:Array in triggerInfoList) {
addTrigger(info[0], info[1], info[2]);
}
}
/**
* @param handler Schema: function(params:Object, onComplete:Function):void
*/
public function addMethod(methodName:String, handler:Function):void {
_methods[methodName] = handler;
}
/**
* @param triggerInfoList Example:
* <pre>
* [
* ["methodName", methodFunc],
* ...
* ]
* </pre>
*/
public function addMethods(methodList:Array):void {
for each (var info:Array in methodList) {
addMethod(info[0], info[1]);
}
}
/**
* Activate player.
* Please call this after setData(), addTriggers(), addMethods(), and init().
*/
public function activate():void {
for (var triggerKey:String in _eventsByTrigger) {
_listenEvent(triggerKey);
}
}
//------------------------------------------------------------
// private
//------------------------------------------------------------
private function _listenEvent(triggerKey:String):void {
var info:TriggerInfo = _triggers[triggerKey];
if (!info) {
throw new Error('[KrewEventPlayer] trigger not registered: ' + triggerKey);
return;
}
listen(info.eventName, function(eventArgs:Object):void {
for each (var eventData:Object in _eventsByTrigger[triggerKey]) {
var triggerParams:Object = eventData[TRIGGER_PARAMS];
if (!info.checker(eventArgs, triggerParams)) { continue; }
_callMethod(eventData);
}
});
}
private function _callMethod(eventData:Object):void {
var methodName:String = eventData[METHOD];
if (!methodName) {
throw new Error('[KrewEventPlayer] method name not found. (trigger: '
+ eventData[TRIGGER_KEY] + ')');
return;
}
var method:Function = _methods[methodName];
if (method == null) {
throw new Error('[KrewEventPlayer] method not registered: ' + methodName);
return;
}
method(eventData[PARAMS], function():void {
_callNextMethod(eventData);
});
}
private function _callNextMethod(parentEventData:Object):void {
if (!parentEventData.next) { return; }
for each (var nextEventData:Object in parentEventData.next) {
_callMethod(nextEventData);
}
}
}
}
class TriggerInfo {
public var eventName:String;
public var checker:Function;
public function TriggerInfo(eventName:String, checker:Function) {
this.eventName = eventName;
this.checker = checker;
}
}
|
Modify KrewScenarioPlayer
|
Modify KrewScenarioPlayer
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
9599391556da800b04996834a4d457b4119a367e
|
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.Group;
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 _data : CameraDataProvider;
private var _camera : AbstractCamera;
private var _ortho : Boolean;
public function get cameraData() : CameraDataProvider
{
return _data;
}
public function get orthographic() : Boolean
{
return _ortho;
}
public function set orthographic(value : Boolean) : void
{
_ortho = value;
}
public function CameraController()
{
super(AbstractCamera);
initialize();
}
private function initialize() : void
{
_data = new CameraDataProvider();
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.added.add(addedHandler);
_camera.removed.add(removedHandler);
}
private function targetRemovedHandler(controller : CameraController,
target : AbstractCamera) : void
{
_camera.added.remove(addedHandler);
_camera.removed.remove(removedHandler);
_camera = null;
}
private function addedHandler(camera : AbstractCamera, ancestor : Group) : void
{
var scene : Scene = camera.scene;
if (!scene)
return;
var sceneBindings : DataBindings = scene.bindings;
resetSceneCamera(scene);
if (camera.enabled)
sceneBindings.addProvider(_data);
camera.localToWorldTransformChanged.add(localToWorldChangedHandler);
camera.activated.add(cameraActivatedHandler);
camera.deactivated.add(cameraDeactivatedHandler);
_data.changed.add(cameraPropertyChangedHandler);
sceneBindings.addCallback('viewportWidth', viewportSizeChanged);
sceneBindings.addCallback('viewportHeight', viewportSizeChanged);
updateProjection();
localToWorldChangedHandler(camera, camera.getLocalToWorldTransform());
}
private function removedHandler(camera : AbstractCamera, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return;
var sceneBindings : DataBindings = scene.bindings;
resetSceneCamera(scene);
if (camera.enabled)
sceneBindings.removeProvider(_data);
camera.localToWorldTransformChanged.remove(localToWorldChangedHandler);
camera.activated.remove(cameraActivatedHandler);
camera.deactivated.remove(cameraDeactivatedHandler);
_data.changed.remove(cameraPropertyChangedHandler);
sceneBindings.removeCallback('viewportWidth', viewportSizeChanged);
sceneBindings.removeCallback('viewportHeight', viewportSizeChanged);
}
private function localToWorldChangedHandler(camera : AbstractCamera,
localToWorld : Matrix4x4) : void
{
var cameraData : CameraDataProvider = _data;
var worldToView : Matrix4x4 = cameraData.worldToView;
var worldToScreen : Matrix4x4 = cameraData.worldToScreen;
localToWorld.deltaTransformVector(Vector4.Z_AXIS, cameraData.direction);
localToWorld.transformVector(Vector4.ZERO, cameraData.position);
worldToView.lock();
worldToScreen.lock();
worldToView
.copyFrom(localToWorld)
.invert()
worldToScreen
.copyFrom(worldToView)
.append(cameraData.projection)
cameraData.frustum.updateFromMatrix(worldToScreen);
worldToView.unlock();
worldToScreen.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 = _data;
var viewportWidth : Number = sceneBindings.getProperty('viewportWidth');
var viewportHeight : Number = sceneBindings.getProperty('viewportHeight');
var ratio : Number = viewportWidth / viewportHeight;
var projection : Matrix4x4 = cameraData.projection;
var worldToScreen : Matrix4x4 = cameraData.worldToScreen;
projection.lock();
worldToScreen.lock();
if (_ortho)
{
var cameraZoom : Number = cameraData.zoom;
projection.ortho(
viewportWidth / cameraZoom,
viewportHeight / cameraZoom,
cameraData.zNear,
cameraData.zFar
);
}
else
projection.perspectiveFoV(
cameraData.fieldOfView,
ratio,
cameraData.zNear,
cameraData.zFar
);
worldToScreen.copyFrom(_camera.getWorldToLocalTransform()).append(projection);
cameraData.frustum.updateFromMatrix(worldToScreen);
projection.unlock();
worldToScreen.unlock();
}
}
private function cameraActivatedHandler(camera : AbstractCamera) : void
{
var scene : Scene = camera.root as Scene;
resetSceneCamera(scene);
scene.bindings.addProvider(_data);
}
private function cameraDeactivatedHandler(camera : AbstractCamera) : void
{
var scene : Scene = camera.root as Scene;
resetSceneCamera(scene);
scene.bindings.removeProvider(_data);
}
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.Group;
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 _data : CameraDataProvider;
private var _camera : AbstractCamera;
private var _ortho : Boolean;
public function get cameraData() : CameraDataProvider
{
return _data;
}
public function get orthographic() : Boolean
{
return _ortho;
}
public function set orthographic(value : Boolean) : void
{
_ortho = value;
}
public function CameraController()
{
super(AbstractCamera);
initialize();
}
private function initialize() : void
{
_data = new CameraDataProvider();
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.added.add(addedHandler);
_camera.removed.add(removedHandler);
}
private function targetRemovedHandler(controller : CameraController,
target : AbstractCamera) : void
{
_camera.added.remove(addedHandler);
_camera.removed.remove(removedHandler);
_camera = null;
}
private function addedHandler(camera : AbstractCamera, ancestor : Group) : void
{
var scene : Scene = camera.scene;
if (!scene)
return;
var sceneBindings : DataBindings = scene.bindings;
resetSceneCamera(scene);
if (camera.enabled)
sceneBindings.addProvider(_data);
camera.localToWorldTransformChanged.add(localToWorldChangedHandler);
camera.activated.add(cameraActivatedHandler);
camera.deactivated.add(cameraDeactivatedHandler);
_data.changed.add(cameraPropertyChangedHandler);
sceneBindings.addCallback('viewportWidth', viewportSizeChanged);
sceneBindings.addCallback('viewportHeight', viewportSizeChanged);
updateProjection();
localToWorldChangedHandler(camera, camera.getLocalToWorldTransform());
}
private function removedHandler(camera : AbstractCamera, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return;
var sceneBindings : DataBindings = scene.bindings;
resetSceneCamera(scene);
if (camera.enabled)
sceneBindings.removeProvider(_data);
camera.localToWorldTransformChanged.remove(localToWorldChangedHandler);
camera.activated.remove(cameraActivatedHandler);
camera.deactivated.remove(cameraDeactivatedHandler);
_data.changed.remove(cameraPropertyChangedHandler);
sceneBindings.removeCallback('viewportWidth', viewportSizeChanged);
sceneBindings.removeCallback('viewportHeight', viewportSizeChanged);
}
private function localToWorldChangedHandler(camera : AbstractCamera,
localToWorld : Matrix4x4) : void
{
var cameraData : CameraDataProvider = _data;
var worldToView : Matrix4x4 = cameraData.worldToView;
var worldToScreen : Matrix4x4 = cameraData.worldToScreen;
localToWorld.deltaTransformVector(Vector4.Z_AXIS, cameraData.direction);
localToWorld.transformVector(Vector4.ZERO, cameraData.position);
worldToView.lock();
worldToScreen.lock();
worldToView
.copyFrom(localToWorld)
.invert();
worldToScreen
.copyFrom(worldToView)
.append(cameraData.projection)
cameraData.frustum.updateFromMatrix(worldToScreen);
worldToView.unlock();
worldToScreen.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 = _data;
var viewportWidth : Number = sceneBindings.getProperty('viewportWidth');
var viewportHeight : Number = sceneBindings.getProperty('viewportHeight');
var ratio : Number = viewportWidth / viewportHeight;
var projection : Matrix4x4 = cameraData.projection;
var worldToScreen : Matrix4x4 = cameraData.worldToScreen;
projection.lock();
worldToScreen.lock();
if (_ortho)
{
var cameraZoom : Number = cameraData.zoom;
projection.ortho(
viewportWidth / cameraZoom,
viewportHeight / cameraZoom,
cameraData.zNear,
cameraData.zFar
);
}
else
projection.perspectiveFoV(
cameraData.fieldOfView,
ratio,
cameraData.zNear,
cameraData.zFar
);
worldToScreen.copyFrom(cameraData.worldToView).append(projection);
cameraData.frustum.updateFromMatrix(worldToScreen);
projection.unlock();
worldToScreen.unlock();
}
}
private function cameraActivatedHandler(camera : AbstractCamera) : void
{
var scene : Scene = camera.root as Scene;
resetSceneCamera(scene);
scene.bindings.addProvider(_data);
}
private function cameraDeactivatedHandler(camera : AbstractCamera) : void
{
var scene : Scene = camera.root as Scene;
resetSceneCamera(scene);
scene.bindings.removeProvider(_data);
}
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 wrong update of worldToScreen matrix when the viewport is resized
|
fix wrong update of worldToScreen matrix when the viewport is resized
|
ActionScript
|
mit
|
aerys/minko-as3
|
a9c72e390a284f6da7a324b741a3e9deab1ce371
|
src/flails/resource/Resources.as
|
src/flails/resource/Resources.as
|
package flails.resource {
import mx.core.IMXMLObject;
import flash.utils.Dictionary;
public class Resources implements IMXMLObject {
[DefaultProperty("resources")]
private static var _resources:Dictionary = new Dictionary();
public static function getResource(name:String):Resource {
return _resources[name] as Resource;
}
public function set resources(rs:Array):void {
for each (var r:Resource in rs) {
_resources[r.name] = r;
}
}
public function initialized(parent:Object, id:String):void {
}
}
}
|
package flails.resource {
import mx.core.IMXMLObject;
import flash.utils.Dictionary;
[DefaultProperty("resources")]
public class Resources implements IMXMLObject {
private static var _resources:Dictionary = new Dictionary();
public static function getResource(name:String):Resource {
return _resources[name] as Resource;
}
public function set resources(rs:Array):void {
for each (var r:Resource in rs) {
_resources[r.name] = r;
}
}
public function initialized(parent:Object, id:String):void {
}
}
}
|
Correct DefaultPropery placement.
|
Correct DefaultPropery placement.
|
ActionScript
|
mit
|
lancecarlson/flails,lancecarlson/flails
|
eed030c985547ac4f04149782d665b2a0902b1f4
|
examples/web/app/classes/server/FMSClient.as
|
examples/web/app/classes/server/FMSClient.as
|
package server {
import flash.events.EventDispatcher;
dynamic public class FMSClient extends EventDispatcher {
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);
}
}
}
|
package server {
import flash.events.EventDispatcher;
dynamic public class FMSClient extends EventDispatcher {
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);
}
public function dispose():void {
trace('FMSClient.diposed');
}
}
}
|
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
|
24fa8920770c81bf07e32beb18c65defa36e451b
|
lib/FlashFallback/com/visual/VisualVideo.as
|
lib/FlashFallback/com/visual/VisualVideo.as
|
package com.visual {
/* Flash widgets */
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.events.Event;
/* OSMF widgets */
import org.osmf.media.MediaPlayerSprite;
import org.osmf.media.MediaPlayer;
import org.osmf.media.URLResource;
import org.osmf.elements.VideoElement;
import org.osmf.media.MediaElement;
import org.osmf.utils.OSMFSettings;
import org.osmf.events.LoadEvent;
import org.osmf.events.MediaElementEvent;
import org.osmf.layout.LayoutMetadata;
import org.osmf.layout.ScaleMode;
import org.osmf.traits.DisplayObjectTrait;
import org.osmf.traits.MediaTraitType;
public class VisualVideo extends Sprite {
// Create the container classes to displays media.
OSMFSettings.enableStageVideo = false;
private var image:VisualImage = new VisualImage();
private var videoContainer:MediaPlayerSprite = null;
private var video:MediaPlayer = null;
private var layout:LayoutMetadata = new LayoutMetadata();
private var loadFired:Boolean = false;
private var videoEnded:Boolean = false;
private var queuePlay:Boolean = false;
private var attachedEvents:Boolean = false;
public var pseudoStreamingOffset:Number = 0;
// Logging
private function trace(s:String):void {
try {
ExternalInterface.call("console.log", "FlashFallback", s);
}catch(e:Error){}
}
// Callback for events
public var callback:Function = function():void{};
// Constructor method
public function VisualVideo() {}
private var inited:Boolean = false;
private function init():void {
if(inited) return;
// Alignment
layout.scaleMode = ScaleMode.LETTERBOX;
layout.verticalAlign = 'middle';
layout.horizontalAlign = 'center';
// Add video stage
videoContainer = new MediaPlayerSprite();
this.addChild(videoContainer);
// Size
this.stage.addEventListener(Event.RESIZE, matchVideoSize);
matchVideoSize();
inited = true;
}
// PROPERTIES
// Property: Source
private var _source:String = null;
public function set source(s:String):void {
init();
_source=s;
//this really should be reset here, but we need to be able to overwrite with a property// this.pseudoStreamingOffset = 0;
this.loadFired = false;
this.videoEnded = false;
var isPlaying:Boolean = (video && video.playing);
var pseudoSource:String = '';
if(this.pseudoStreamingOffset==0) {
pseudoSource = _source;
} else {
pseudoSource = _source + (new RegExp("\\?").test(_source) ? '&' : '?') + 'start=' + this.pseudoStreamingOffset;
}
_duration = 0;
// Load the stream and attach to playback
var resource:URLResource = new URLResource(pseudoSource);
video = videoContainer.mediaPlayer;
video.autoPlay = isPlaying||queuePlay;
video.bufferTime = (isLive ? 0.1 : 1);
queuePlay = false;
video.autoRewind = false;
videoContainer.resource = new URLResource(pseudoSource);
videoContainer.media.addMetadata(LayoutMetadata.LAYOUT_NAMESPACE, layout);
// Smoothing with OSMF isn't supposed to be easy. We'll try two different things...
// 1st case
if (videoContainer.media is VideoElement) (videoContainer.media as VideoElement).smoothing = true;
// 2nd case
videoContainer.media.addEventListener(MediaElementEvent.TRAIT_ADD, function(event:MediaElementEvent):void {
if(event.type == MediaElementEvent.TRAIT_ADD && event.traitType == MediaTraitType.DISPLAY_OBJECT) {
var displayObject:Object = (videoContainer.media.getTrait(MediaTraitType.DISPLAY_OBJECT) as DisplayObjectTrait).displayObject;
displayObject.smoothing = true;
}
});
matchVideoSize();
if(!this.attachedEvents) {
this.video.addEventListener('durationChange', function():void{_duration=video.duration;});
this.video.addEventListener('bytesLoadedChange', function():void{callback('progress');});
this.video.addEventListener('complete', function():void{
videoEnded = true;
callback('ended');
});
this.video.addEventListener('volumeChange', function():void{callback('volumechange');});
this.video.addEventListener('currentTimeChange', function():void{callback('timeupdate');});
this.video.addEventListener('canPlayChange', function():void{
if(video.canPlay) {
callback('canplay');
if(queuePlay) {
playing = true;
queuePlay = false;
}
}
});
this.video.addEventListener('mediaPlayerStateChange', function():void{
if( !loadFired && (video.state=='playing'||video.state=='buffering'||video.state=='loading'||video.state=='ready')) {
callback('loadeddata');
callback('loadedmetadata');
loadFired = true;
}
if( video.state=='buffering'||video.state=='playbackError'||video.state=='loading' ) {
callback('stalled');
} else if( video.state=='playing' ) {
callback('play');
callback('playing');
} else if( video.state=='paused'||video.state=='ready' ) {
callback('pause');
}
});
this.attachedEvents = true;
}
}
public function get source():String {
return _source;
}
// Property: Poster
private var _poster:String = null;
public function set poster(p:String):void {
init();
if(_poster==p) return;
this.addChildAt(image,0);
image.source = p;
_poster=p;
}
public function get poster():String {
return _poster;
}
// Property: Playing
public function set playing(p:Boolean):void {
if(!this.video) return;
try {
if(p) {
if(this.videoEnded) this.currentTime = 0;
this.video.play();
callback('play');
} else {
this.video.pause();
}
}catch(e:Error){
queuePlay = p;
}
}
public function get playing():Boolean {
return this.video && this.video.playing;
}
// Property: Seeking
public function get seeking():Boolean {
return this.video && this.video.seeking;
}
// Property: Stalled
public function get stalled():Boolean {
return (this.video && (this.video.state=='buffering' || this.video.state=='loading' || this.video.state=='playbackError'));
}
// Property: Ended
public function get ended():Boolean {
return this.videoEnded;
}
// Property: Current time
public function set currentTime(ct:Number):void {
if(!this.video) return;
if(ct<0||ct>duration) return;
if(isLive) return;
if(ct<this.pseudoStreamingOffset || ct>this.bufferTime) {
_duration = duration - ct; // Guesstimate the duration of the new clip before changing the offset
this.pseudoStreamingOffset = ct;
trace('Pseudo streaming from ' + this.pseudoStreamingOffset);
source = source; // switch source with new pseudo stream time
} else {
try {
this.video.seek(ct-this.pseudoStreamingOffset);
}catch(e:Error){}
}
}
public function get currentTime():Number {
return (this.video ? this.pseudoStreamingOffset + this.video.currentTime : 0);
}
// Property: Duration
private var _duration:Number = 0;
public function get duration():Number {
if(isLive) {
return currentTime;
} else {
return (this.video ? this.pseudoStreamingOffset+_duration : 0);
}
}
// Property: Buffer time
public function get bufferTime():Number {
if(!this.video) return 0;
if(isLive) {
return currentTime;
} else {
var bytesLoaded:int = (this.video ? this.video.bytesLoaded : 0);
var bytesTotal:int = (this.video ? this.video.bytesTotal : 0);
if(this.duration<=0 || bytesLoaded<=0 || bytesTotal<=0) {
return 0;
} else {
return this.pseudoStreamingOffset+((bytesLoaded/bytesTotal)*_duration);
}
}
}
// Property: Volume
public function set volume(v:Number):void {
if(!this.video) return;
this.video.volume = v;
}
public function get volume():Number {
if(!this.video) return 1;
return this.video.volume;
}
// Property: isLive
public function get isLive():Boolean {
return( /^rtmp:\/\//.test(_source.toLowerCase()) || /\.f4m$/.test(_source.toLowerCase()) );
}
private function matchVideoSize(e:Event=null):void {
try {
videoContainer.height = this.stage.stageHeight;
videoContainer.width = this.stage.stageWidth;
layout.height = this.stage.stageHeight;
layout.width = this.stage.stageWidth;
}catch(e:Error){}
}
}
}
|
package com.visual {
/* Flash widgets */
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.events.Event;
/* OSMF widgets */
import org.osmf.media.MediaPlayerSprite;
import org.osmf.media.MediaPlayer;
import org.osmf.media.URLResource;
import org.osmf.elements.VideoElement;
import org.osmf.media.MediaElement;
import org.osmf.utils.OSMFSettings;
import org.osmf.events.LoadEvent;
import org.osmf.events.MediaElementEvent;
import org.osmf.layout.LayoutMetadata;
import org.osmf.layout.ScaleMode;
import org.osmf.traits.DisplayObjectTrait;
import org.osmf.traits.MediaTraitType;
public class VisualVideo extends Sprite {
// Create the container classes to displays media.
OSMFSettings.enableStageVideo = false;
private var image:VisualImage = new VisualImage();
private var videoContainer:MediaPlayerSprite = null;
private var video:MediaPlayer = null;
private var layout:LayoutMetadata = new LayoutMetadata();
private var loadFired:Boolean = false;
private var videoEnded:Boolean = false;
private var queuePlay:Boolean = false;
private var attachedEvents:Boolean = false;
public var pseudoStreamingOffset:Number = 0;
// Logging
private function trace(s:String):void {
try {
ExternalInterface.call("console.log", "FlashFallback", s);
}catch(e:Error){}
}
// Callback for events
public var callback:Function = function():void{};
// Constructor method
public function VisualVideo() {}
private var inited:Boolean = false;
private function init():void {
if(inited) return;
// Alignment
layout.scaleMode = ScaleMode.LETTERBOX;
layout.verticalAlign = 'middle';
layout.horizontalAlign = 'center';
// Add video stage
videoContainer = new MediaPlayerSprite();
this.addChild(videoContainer);
// Size
this.stage.addEventListener(Event.RESIZE, matchVideoSize);
matchVideoSize();
inited = true;
}
// PROPERTIES
// Property: Source
private var _source:String = null;
public function set source(s:String):void {
init();
_source=s;
//this really should be reset here, but we need to be able to overwrite with a property// this.pseudoStreamingOffset = 0;
this.loadFired = false;
this.videoEnded = false;
var isPlaying:Boolean = (video && video.playing);
var pseudoSource:String = '';
if(this.pseudoStreamingOffset==0) {
pseudoSource = _source;
} else {
pseudoSource = _source + (new RegExp("\\?").test(_source) ? '&' : '?') + 'start=' + this.pseudoStreamingOffset;
}
_duration = 0;
// Load the stream and attach to playback
var resource:URLResource = new URLResource(pseudoSource);
video = videoContainer.mediaPlayer;
video.autoPlay = isPlaying||queuePlay;
video.bufferTime = (isLive ? 0.1 : 1);
queuePlay = false;
video.autoRewind = false;
videoContainer.resource = new URLResource(pseudoSource);
videoContainer.media.addMetadata(LayoutMetadata.LAYOUT_NAMESPACE, layout);
// Smoothing with OSMF isn't supposed to be easy. We'll try two different things...
// 1st case
if (videoContainer.media is VideoElement) (videoContainer.media as VideoElement).smoothing = true;
// 2nd case
videoContainer.media.addEventListener(MediaElementEvent.TRAIT_ADD, function(event:MediaElementEvent):void {
if(event.type == MediaElementEvent.TRAIT_ADD && event.traitType == MediaTraitType.DISPLAY_OBJECT) {
var displayObject:Object = (videoContainer.media.getTrait(MediaTraitType.DISPLAY_OBJECT) as DisplayObjectTrait).displayObject;
displayObject.smoothing = true;
}
});
matchVideoSize();
if(!this.attachedEvents) {
this.video.addEventListener('durationChange', function():void{_duration=video.duration;});
this.video.addEventListener('bytesLoadedChange', function():void{callback('progress');});
this.video.addEventListener('complete', function():void{
videoEnded = true;
callback('ended');
});
this.video.addEventListener('volumeChange', function():void{callback('volumechange');});
this.video.addEventListener('currentTimeChange', function():void{callback('timeupdate');});
this.video.addEventListener('canPlayChange', function():void{
if(video.canPlay) {
callback('canplay');
if(queuePlay) {
playing = true;
queuePlay = false;
}
}
});
this.video.addEventListener('mediaPlayerStateChange', function():void{
if( !loadFired && (video.state=='playing'||video.state=='buffering'||video.state=='loading'||video.state=='ready')) {
callback('loadeddata');
callback('loadedmetadata');
loadFired = true;
}
if( video.state=='buffering'||video.state=='playbackError'||video.state=='loading' ) {
callback('stalled');
} else if( video.state=='playing' ) {
callback('play');
callback('playing');
image.visible = false;
} else if( video.state=='paused'||video.state=='ready' ) {
callback('pause');
}
});
this.attachedEvents = true;
}
}
public function get source():String {
return _source;
}
// Property: Poster
private var _poster:String = null;
public function set poster(p:String):void {
init();
if(_poster==p) return;
this.addChildAt(image,0);
image.source = p;
_poster=p;
}
public function get poster():String {
return _poster;
}
// Property: Playing
public function set playing(p:Boolean):void {
if(!this.video) return;
try {
if(p) {
if(this.videoEnded) this.currentTime = 0;
this.video.play();
callback('play');
} else {
this.video.pause();
}
}catch(e:Error){
queuePlay = p;
}
}
public function get playing():Boolean {
return this.video && this.video.playing;
}
// Property: Seeking
public function get seeking():Boolean {
return this.video && this.video.seeking;
}
// Property: Stalled
public function get stalled():Boolean {
return (this.video && (this.video.state=='buffering' || this.video.state=='loading' || this.video.state=='playbackError'));
}
// Property: Ended
public function get ended():Boolean {
return this.videoEnded;
}
// Property: Current time
public function set currentTime(ct:Number):void {
if(!this.video) return;
if(ct<0||ct>duration) return;
if(isLive) return;
if(ct<this.pseudoStreamingOffset || ct>this.bufferTime) {
_duration = duration - ct; // Guesstimate the duration of the new clip before changing the offset
this.pseudoStreamingOffset = ct;
trace('Pseudo streaming from ' + this.pseudoStreamingOffset);
source = source; // switch source with new pseudo stream time
} else {
try {
this.video.seek(ct-this.pseudoStreamingOffset);
}catch(e:Error){}
}
}
public function get currentTime():Number {
return (this.video ? this.pseudoStreamingOffset + this.video.currentTime : 0);
}
// Property: Duration
private var _duration:Number = 0;
public function get duration():Number {
if(isLive) {
return currentTime;
} else {
return (this.video ? this.pseudoStreamingOffset+_duration : 0);
}
}
// Property: Buffer time
public function get bufferTime():Number {
if(!this.video) return 0;
if(isLive) {
return currentTime;
} else {
var bytesLoaded:int = (this.video ? this.video.bytesLoaded : 0);
var bytesTotal:int = (this.video ? this.video.bytesTotal : 0);
if(this.duration<=0 || bytesLoaded<=0 || bytesTotal<=0) {
return 0;
} else {
return this.pseudoStreamingOffset+((bytesLoaded/bytesTotal)*_duration);
}
}
}
// Property: Volume
public function set volume(v:Number):void {
if(!this.video) return;
this.video.volume = v;
}
public function get volume():Number {
if(!this.video) return 1;
return this.video.volume;
}
// Property: isLive
public function get isLive():Boolean {
return( /^rtmp:\/\//.test(_source.toLowerCase()) || /\.f4m$/.test(_source.toLowerCase()) );
}
private function matchVideoSize(e:Event=null):void {
try {
videoContainer.height = this.stage.stageHeight;
videoContainer.width = this.stage.stageWidth;
layout.height = this.stage.stageHeight;
layout.width = this.stage.stageWidth;
}catch(e:Error){}
}
}
}
|
Hide thumbnail image when is playing
|
Hide thumbnail image when is playing
|
ActionScript
|
mit
|
23/eingebaut,23/eingebaut,23/eingebaut
|
0f4d55bed5e68604f4dcc42305136227aa075e3c
|
flexclient/dag/Components/Association.as
|
flexclient/dag/Components/Association.as
|
package Components
{
[Bindable]
public class Association
{
public var associatedNode:String;
public var associatedLink:String;
public var operatorIndex:int;
public function Association(associatedNode:String,associatedLink:String,operatorIndex:int)
{
this.associatedLink = associatedLink;
this.associatedNode = associatedNode;
this.operatorIndex = operatorIndex;
}
}
}
|
package Components
{
[Bindable]
public class Association
{
public var associatedNode:String;
public var associatedLink:String;
public var operatorIndex:int;
public var order:int=0;
public function Association(associatedNode:String,associatedLink:String,operatorIndex:int,order:int)
{
this.associatedLink = associatedLink;
this.associatedNode = associatedNode;
this.operatorIndex = operatorIndex;
this.order=order;
}
}
}
|
Order vairable added todecide order of association
|
Order vairable added todecide order of association
SVN-Revision: 9306
|
ActionScript
|
bsd-3-clause
|
asamgir/openspecimen,asamgir/openspecimen,krishagni/openspecimen,krishagni/openspecimen,asamgir/openspecimen,krishagni/openspecimen
|
fac7d8e3416f65e79b956a2d719dede5ebffdeb6
|
runtime/src/main/as/flump/display/Movie.as
|
runtime/src/main/as/flump/display/Movie.as
|
//
// Flump - Copyright 2013 Flump Authors
package flump.display {
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import flump.mold.LayerMold;
import flump.mold.MovieMold;
import react.Signal;
import starling.animation.IAnimatable;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
import starling.utils.MatrixUtil;
/**
* A movie created from flump-exported data. It has children corresponding to the layers in the
* movie in Flash, in the same order and with the same names. It fills in those children
* initially with the image or movie of the symbol on that exported layer. After the initial
* population, it only applies the keyframe-based transformations to the child at the index
* corresponding to the layer. This means it's safe to swap in other DisplayObjects at those
* positions to have them animated in place of the initial child.
*
* <p>A Movie will not animate unless it's added to a Juggler (or its advanceTime() function
* is otherwise called). When the movie is added to a juggler, it advances its playhead with the
* frame ticks if isPlaying is true. It will automatically remove itself from its juggler when
* removed from the stage.</p>
*
* @see Library and LibraryLoader to create instances of Movie.
*/
public class Movie extends Sprite
implements IAnimatable
{
/** A label fired by all movies when entering their first frame. */
public static const FIRST_FRAME :String = "flump.movie.FIRST_FRAME";
/** A label fired by all movies when entering their last frame. */
public static const LAST_FRAME :String = "flump.movie.LAST_FRAME";
/** Fires the label string whenever it's passed in playing. */
public const labelPassed :Signal = new Signal(String);
/** @private */
public function Movie (src :MovieMold, frameRate :Number, library :Library) {
this.name = src.id;
_labels = src.labels;
_frameRate = frameRate;
if (src.flipbook) {
_layers = new Vector.<Layer>(1, true);
_layers[0] = createLayer(this, src.layers[0], library, /*flipbook=*/true);
_numFrames = src.layers[0].frames;
} else {
_layers = new Vector.<Layer>(src.layers.length, true);
for (var ii :int = 0; ii < _layers.length; ii++) {
_layers[ii] = createLayer(this, src.layers[ii], library, /*flipbook=*/false);
_numFrames = Math.max(src.layers[ii].frames, _numFrames);
}
}
_duration = _numFrames / _frameRate;
updateFrame(0, 0);
// When we're removed from the stage, remove ourselves from any juggler animating us.
addEventListener(Event.REMOVED_FROM_STAGE, function (..._) :void {
dispatchEventWith(Event.REMOVE_FROM_JUGGLER);
});
}
/** @return the frame being displayed. */
public function get frame () :int { return _frame; }
/** @return the number of frames in the movie. */
public function get numFrames () :int { return _numFrames; }
/** @return true if the movie is currently playing. */
public function get isPlaying () :Boolean { return _state == PLAYING; }
/** @return true if the movie contains the given label. */
public function hasLabel (label :String) :Boolean {
return getFrameForLabel(label) >= 0;
}
/** @return the frame index for the given label, or -1 if the label doesn't exist. */
public function getFrameForLabel (label :String) :int {
for (var ii :int = 0; ii < _labels.length; ii++) {
if (_labels[ii] != null && _labels[ii].indexOf(label) != -1) return ii;
}
return -1;
}
/** Plays the movie from its current frame. The movie will loop forever. */
public function loop () :Movie {
_state = PLAYING;
_stopFrame = NO_FRAME;
return this;
}
/** Plays the movie from its current frame, stopping when it reaches its last frame. */
public function playOnce () :Movie { return playTo(LAST_FRAME); }
/**
* Moves to the given String label or int frame. Doesn't alter playing status or stop frame.
* If there are labels at the given position, they're fired as part of the goto, even if the
* current frame is equal to the destination. Labels between the current frame and the
* destination frame are not fired.
*
* @param position the int frame or String label to goto.
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie
*/
public function goTo (position :Object) :Movie {
const frame :int = extractFrame(position);
updateFrame(frame, 0);
return this;
}
/**
* Plays the movie from its current frame. The movie will stop when it reaches the given label
* or frame.
*
* @param position to int frame or String label to stop at
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie.
*/
public function playTo (position :Object) :Movie {
// won't play if we're already at the stop position
return stopAt(position).play();
}
/**
* Sets the stop frame for this Movie.
*
* @param position the int frame or String label to stop at.
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie.
*/
public function stopAt (position :Object) :Movie {
_stopFrame = extractFrame(position);
return this;
}
/**
* Sets the movie playing. It will automatically stop at its stopFrame, if one is set,
* otherwise it will loop forever.
*
* @return this movie for chaining
*/
public function play () :Movie {
// set playing to true unless movie is at the stop frame
_state = (_frame != _stopFrame ? PLAYING : STOPPED);
return this;
}
/** Stops playback if it's currently active. Doesn't alter the current frame or stop frame. */
public function stop () :Movie {
_state = STOPPED;
return this;
}
/** Stops playback of this movie, but not its children */
public function playChildrenOnly () :Movie {
_state = PLAYING_CHILDREN_ONLY;
return this;
}
/** Advances the playhead by the give number of seconds. From IAnimatable. */
public function advanceTime (dt :Number) :void {
if (dt < 0) throw new Error("Invalid time [dt=" + dt + "]");
if (_skipAdvanceTime) { _skipAdvanceTime = false; return; }
if (_state == STOPPED) return;
if (_state == PLAYING && _numFrames > 1) {
_playTime += dt;
var actualPlaytime :Number = _playTime;
if (_playTime >= _duration) _playTime %= _duration;
// If _playTime is very close to _duration, rounding error can cause us to
// land on lastFrame + 1. Protect against that.
var newFrame :int = int(_playTime * _frameRate);
if (newFrame < 0) newFrame = 0;
if (newFrame >= _numFrames) newFrame = _numFrames - 1;
// If the update crosses or goes to the stopFrame:
// go to the stopFrame, stop the movie, clear the stopFrame
if (_stopFrame != NO_FRAME) {
// how many frames remain to the stopframe?
var framesRemaining :int =
(_frame <= _stopFrame ? _stopFrame - _frame : _numFrames - _frame + _stopFrame);
var framesElapsed :int = int(actualPlaytime * _frameRate) - _frame;
if (framesElapsed >= framesRemaining) {
_state = STOPPED;
newFrame = _stopFrame;
}
}
updateFrame(newFrame, dt);
}
for each (var layer :Layer in _layers) {
layer.advanceTime(dt);
}
}
/**
* @public
*
* Modified from starling.display.DisplayObjectContainer
*/
public override function getBounds (targetSpace :DisplayObject, resultRect :Rectangle=null) :Rectangle {
if (resultRect == null) {
resultRect = new Rectangle();
} else {
resultRect.setEmpty();
}
// get bounds from layer contents
for each (var layer :Layer in _layers) {
layer.expandBounds(targetSpace, resultRect);
}
// if no contents exist, simply include this movie's position in the bounds
if (resultRect.isEmpty()) {
getTransformationMatrix(targetSpace, IDENTITY_MATRIX);
MatrixUtil.transformCoords(IDENTITY_MATRIX, 0.0, 0.0, _s_helperPoint);
resultRect.setTo(_s_helperPoint.x, _s_helperPoint.y, 0, 0);
}
return resultRect;
}
/**
* @private
*
* Called when the Movie has been newly added to a layer.
*/
internal function addedToLayer () :void {
goTo(0);
_skipAdvanceTime = true;
}
/** @private */
protected function extractFrame (position :Object) :int {
if (position is int) return int(position);
if (!(position is String)) throw new Error("Movie position must be an int frame or String label");
const label :String = String(position);
var frame :int = getFrameForLabel(label);
if (frame < 0) {
throw new Error("No such label '" + label + "'");
}
return frame;
}
/**
* @private
*
* @param dt the timeline's elapsed time since the last update. This should be 0
* for updates that are the result of a "goTo" call.
*/
protected function updateFrame (newFrame :int, dt :Number) :void {
if (newFrame < 0 || newFrame >= _numFrames) {
throw new Error("Invalid frame [frame=" + newFrame,
" validRange=0-" + (_numFrames - 1) + "]");
}
if (_isUpdatingFrame) {
_pendingFrame = newFrame;
return;
} else {
_pendingFrame = NO_FRAME;
_isUpdatingFrame = true;
}
const isGoTo :Boolean = (dt <= 0);
const wrapped :Boolean = (dt >= _duration) || (newFrame < _frame);
if (newFrame != _frame) {
for each (var layer :Layer in _layers) {
layer.drawFrame(newFrame);
}
}
if (isGoTo) _playTime = newFrame / _frameRate;
// Update the frame before firing frame label signals, so if firing changes the frame,
// it sticks.
const oldFrame :int = _frame;
_frame = newFrame;
// determine which labels to fire signals for
var startFrame :int;
var frameCount :int;
if (isGoTo) {
startFrame = newFrame;
frameCount = 1;
} else {
startFrame = (oldFrame + 1 < _numFrames ? oldFrame + 1 : 0);
frameCount = (_frame - oldFrame);
if (wrapped) frameCount += _numFrames;
}
// Fire signals. Stop if pendingFrame is updated, which indicates that the client
// has called goTo()
var frameIdx :int = startFrame;
for (var ii :int = 0; ii < frameCount; ++ii) {
if (_pendingFrame != NO_FRAME) break;
if (_labels[frameIdx] != null) {
for each (var label :String in _labels[frameIdx]) {
labelPassed.emit(label);
if (_pendingFrame != NO_FRAME) break;
}
}
// avoid modulo division by updating frameIdx each time through the loop
if (++frameIdx == _numFrames) {
frameIdx = 0;
}
}
_isUpdatingFrame = false;
// If we were interrupted by a goTo(), update to that frame now.
if (_pendingFrame != NO_FRAME) {
newFrame = _pendingFrame;
updateFrame(newFrame, 0);
}
}
protected function createLayer (movie :Movie, src :LayerMold, library :Library, flipbook :Boolean) :Layer {
return new Layer(movie, src, library, flipbook);
}
/** @private */
protected var _isUpdatingFrame :Boolean;
/** @private */
protected var _pendingFrame :int = NO_FRAME;
/** @private */
protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME;
/** @private */
protected var _state :int = PLAYING;
/** @private */
protected var _playTime :Number, _duration :Number;
/** @private */
protected var _layers :Vector.<Layer>;
/** @private */
protected var _numFrames :int;
/** @private */
protected var _frameRate :Number;
/** @private */
protected var _labels :Vector.<Vector.<String>>;
/** @private */
private var _skipAdvanceTime :Boolean = false;
/** @private */
internal var _playerData :MoviePlayerNode;
/** @private */
private static var _s_helperPoint :Point = new Point();
private static const IDENTITY_MATRIX :Matrix = new Matrix();
private static const NO_FRAME :int = -1;
private static const STOPPED :int = 0;
private static const PLAYING_CHILDREN_ONLY :int = 1;
private static const PLAYING :int = 2;
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.display {
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import flump.mold.LayerMold;
import flump.mold.MovieMold;
import react.Signal;
import starling.animation.IAnimatable;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
import starling.utils.MatrixUtil;
/**
* A movie created from flump-exported data. It has children corresponding to the layers in the
* movie in Flash, in the same order and with the same names. It fills in those children
* initially with the image or movie of the symbol on that exported layer. After the initial
* population, it only applies the keyframe-based transformations to the child at the index
* corresponding to the layer. This means it's safe to swap in other DisplayObjects at those
* positions to have them animated in place of the initial child.
*
* <p>A Movie will not animate unless it's added to a Juggler (or its advanceTime() function
* is otherwise called). When the movie is added to a juggler, it advances its playhead with the
* frame ticks if isPlaying is true. It will automatically remove itself from its juggler when
* removed from the stage.</p>
*
* @see Library and LibraryLoader to create instances of Movie.
*/
public class Movie extends Sprite
implements IAnimatable
{
/** A label fired by all movies when entering their first frame. */
public static const FIRST_FRAME :String = "flump.movie.FIRST_FRAME";
/** A label fired by all movies when entering their last frame. */
public static const LAST_FRAME :String = "flump.movie.LAST_FRAME";
/** Fires the label string whenever it's passed in playing. */
public const labelPassed :Signal = new Signal(String);
/** @private */
public function Movie (src :MovieMold, frameRate :Number, library :Library) {
this.name = src.id;
_labels = src.labels;
_frameRate = frameRate;
if (src.flipbook) {
_layers = new Vector.<Layer>(1, true);
_layers[0] = createLayer(this, src.layers[0], library, /*flipbook=*/true);
_numFrames = src.layers[0].frames;
} else {
_layers = new Vector.<Layer>(src.layers.length, true);
for (var ii :int = 0; ii < _layers.length; ii++) {
_layers[ii] = createLayer(this, src.layers[ii], library, /*flipbook=*/false);
_numFrames = Math.max(src.layers[ii].frames, _numFrames);
}
}
_duration = _numFrames / _frameRate;
updateFrame(0, 0);
// When we're removed from the stage, remove ourselves from any juggler animating us.
addEventListener(Event.REMOVED_FROM_STAGE, function (..._) :void {
dispatchEventWith(Event.REMOVE_FROM_JUGGLER);
});
}
/** @return the frame being displayed. */
public function get frame () :int { return _frame; }
/** @return the number of frames in the movie. */
public function get numFrames () :int { return _numFrames; }
/** @return true if the movie is currently playing. */
public function get isPlaying () :Boolean { return _state == PLAYING; }
/** @return true if the movie contains the given label. */
public function hasLabel (label :String) :Boolean {
return getFrameForLabel(label) >= 0;
}
/** @return the frame index for the given label, or -1 if the label doesn't exist. */
public function getFrameForLabel (label :String) :int {
for (var ii :int = 0; ii < _labels.length; ii++) {
if (_labels[ii] != null && _labels[ii].indexOf(label) != -1) return ii;
}
return -1;
}
/** Plays the movie from its current frame. The movie will loop forever. */
public function loop () :Movie {
_state = PLAYING;
_stopFrame = NO_FRAME;
return this;
}
/** Plays the movie from its current frame, stopping when it reaches its last frame. */
public function playOnce () :Movie { return playTo(LAST_FRAME); }
/**
* Moves to the given String label or int frame. Doesn't alter playing status or stop frame.
* If there are labels at the given position, they're fired as part of the goto, even if the
* current frame is equal to the destination. Labels between the current frame and the
* destination frame are not fired.
*
* @param position the int frame or String label to goto.
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie
*/
public function goTo (position :Object) :Movie {
const frame :int = extractFrame(position);
updateFrame(frame, 0);
return this;
}
/**
* Plays the movie from its current frame. The movie will stop when it reaches the given label
* or frame.
*
* @param position to int frame or String label to stop at
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie.
*/
public function playTo (position :Object) :Movie {
// won't play if we're already at the stop position
return stopAt(position).play();
}
/**
* Sets the stop frame for this Movie.
*
* @param position the int frame or String label to stop at.
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie.
*/
public function stopAt (position :Object) :Movie {
_stopFrame = extractFrame(position);
return this;
}
/**
* Sets the movie playing. It will automatically stop at its stopFrame, if one is set,
* otherwise it will loop forever.
*
* @return this movie for chaining
*/
public function play () :Movie {
// set playing to true unless movie is at the stop frame
_state = (_frame != _stopFrame ? PLAYING : STOPPED);
return this;
}
/** Stops playback if it's currently active. Doesn't alter the current frame or stop frame. */
public function stop () :Movie {
_state = STOPPED;
return this;
}
/** Stops playback of this movie, but not its children */
public function playChildrenOnly () :Movie {
_state = PLAYING_CHILDREN_ONLY;
return this;
}
/** Advances the playhead by the give number of seconds. From IAnimatable. */
public function advanceTime (dt :Number) :void {
if (dt < 0) {
throw new Error("Invalid time [dt=" + dt + "]");
}
if (_skipAdvanceTime) {
_skipAdvanceTime = false;
return;
}
if (_state == STOPPED) {
return;
}
if (_state == PLAYING && _numFrames > 1) {
_playTime += dt;
var actualPlaytime :Number = _playTime;
if (_playTime >= _duration) {
_playTime %= _duration;
}
// If _playTime is very close to _duration, rounding error can cause us to
// land on lastFrame + 1. Protect against that.
var newFrame :int = int(_playTime * _frameRate);
if (newFrame < 0) {
newFrame = 0;
} else if (newFrame >= _numFrames) {
newFrame = _numFrames - 1;
}
// If the update crosses or goes to the stopFrame:
// go to the stopFrame, stop the movie, clear the stopFrame
if (_stopFrame != NO_FRAME) {
// how many frames remain to the stopframe?
var framesRemaining :int =
(_frame <= _stopFrame ? _stopFrame - _frame : _numFrames - _frame + _stopFrame);
var framesElapsed :int = int(actualPlaytime * _frameRate) - _frame;
if (framesElapsed >= framesRemaining) {
_state = STOPPED;
newFrame = _stopFrame;
}
}
updateFrame(newFrame, dt);
}
for each (var layer :Layer in _layers) {
layer.advanceTime(dt);
}
}
/**
* @public
*
* Modified from starling.display.DisplayObjectContainer
*/
public override function getBounds (targetSpace :DisplayObject, resultRect :Rectangle=null) :Rectangle {
if (resultRect == null) {
resultRect = new Rectangle();
} else {
resultRect.setEmpty();
}
// get bounds from layer contents
for each (var layer :Layer in _layers) {
layer.expandBounds(targetSpace, resultRect);
}
// if no contents exist, simply include this movie's position in the bounds
if (resultRect.isEmpty()) {
getTransformationMatrix(targetSpace, IDENTITY_MATRIX);
MatrixUtil.transformCoords(IDENTITY_MATRIX, 0.0, 0.0, HELPER_POINT);
resultRect.setTo(HELPER_POINT.x, HELPER_POINT.y, 0, 0);
}
return resultRect;
}
/**
* @private
*
* Called when the Movie has been newly added to a layer.
*/
internal function addedToLayer () :void {
goTo(0);
_skipAdvanceTime = true;
}
/** @private */
protected function extractFrame (position :Object) :int {
if (position is int) return int(position);
if (!(position is String)) throw new Error("Movie position must be an int frame or String label");
const label :String = String(position);
var frame :int = getFrameForLabel(label);
if (frame < 0) {
throw new Error("No such label '" + label + "'");
}
return frame;
}
/**
* @private
*
* @param dt the timeline's elapsed time since the last update. This should be 0
* for updates that are the result of a "goTo" call.
*/
protected function updateFrame (newFrame :int, dt :Number) :void {
if (newFrame < 0 || newFrame >= _numFrames) {
throw new Error("Invalid frame [frame=" + newFrame + ", validRange=0-" + (_numFrames - 1) + "]");
}
if (_isUpdatingFrame) {
_pendingFrame = newFrame;
return;
}
_pendingFrame = NO_FRAME;
_isUpdatingFrame = true;
const isGoTo :Boolean = (dt <= 0);
const wrapped :Boolean = (dt >= _duration) || (newFrame < _frame);
if (newFrame != _frame) {
for each (var layer :Layer in _layers) {
layer.drawFrame(newFrame);
}
}
if (isGoTo) {
_playTime = newFrame / _frameRate;
}
// Update the frame before firing frame label signals, so if firing changes the frame,
// it sticks.
const oldFrame :int = _frame;
_frame = newFrame;
// determine which labels to fire signals for
var startFrame :int;
var frameCount :int;
if (isGoTo) {
startFrame = newFrame;
frameCount = 1;
} else {
startFrame = (oldFrame + 1 < _numFrames ? oldFrame + 1 : 0);
frameCount = (_frame - oldFrame);
if (wrapped) {
frameCount += _numFrames;
}
}
// Fire signals. Stop if pendingFrame is updated, which indicates that the client
// has called goTo()
var frameIdx :int = startFrame;
for (var ii :int = 0; ii < frameCount; ++ii) {
if (_pendingFrame != NO_FRAME) break;
if (_labels[frameIdx] != null) {
for each (var label :String in _labels[frameIdx]) {
labelPassed.emit(label);
if (_pendingFrame != NO_FRAME) break;
}
}
// avoid modulo division by updating frameIdx each time through the loop
if (++frameIdx == _numFrames) {
frameIdx = 0;
}
}
_isUpdatingFrame = false;
// If we were interrupted by a goTo(), update to that frame now.
if (_pendingFrame != NO_FRAME) {
newFrame = _pendingFrame;
updateFrame(newFrame, 0);
}
}
protected function createLayer (movie :Movie, src :LayerMold, library :Library, flipbook :Boolean) :Layer {
return new Layer(movie, src, library, flipbook);
}
/** @private */
protected var _isUpdatingFrame :Boolean;
/** @private */
protected var _pendingFrame :int = NO_FRAME;
/** @private */
protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME;
/** @private */
protected var _state :int = PLAYING;
/** @private */
protected var _playTime :Number = 0;
/** @private */
protected var _duration :Number;
/** @private */
protected var _layers :Vector.<Layer>;
/** @private */
protected var _numFrames :int;
/** @private */
protected var _frameRate :Number;
/** @private */
protected var _labels :Vector.<Vector.<String>>;
/** @private */
private var _skipAdvanceTime :Boolean = false;
/** @private */
internal var _playerData :MoviePlayerNode;
private static const HELPER_POINT :Point = new Point();
private static const IDENTITY_MATRIX :Matrix = new Matrix();
private static const NO_FRAME :int = -1;
private static const STOPPED :int = 0;
private static const PLAYING_CHILDREN_ONLY :int = 1;
private static const PLAYING :int = 2;
}
}
|
Fix a string concatenation and some minor cleanup
|
Fix a string concatenation and some minor cleanup
|
ActionScript
|
mit
|
mathieuanthoine/flump,tconkling/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump
|
95802c2da9f7625cf39a06e52944837d54f5f8c7
|
src/com/esri/builder/controllers/RemoveCustomWidgetController.as
|
src/com/esri/builder/controllers/RemoveCustomWidgetController.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.processes.CleanUpProcess;
import com.esri.builder.controllers.supportClasses.processes.ProcessArbiter;
import com.esri.builder.controllers.supportClasses.processes.ProcessArbiterEvent;
import com.esri.builder.controllers.supportClasses.WellKnownDirectories;
import com.esri.builder.eventbus.AppEvent;
import com.esri.builder.model.WidgetType;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.views.BuilderAlert;
import flash.filesystem.File;
import mx.resources.ResourceManager;
public class RemoveCustomWidgetController
{
private var removeWidgetArbiter:ProcessArbiter;
private var widgetTypeToRemove:WidgetType;
public function RemoveCustomWidgetController()
{
AppEvent.addListener(AppEvent.REMOVE_CUSTOM_WIDGET, removeCustomWidgetHandler);
}
private function removeCustomWidgetHandler(importCustomWidget:AppEvent):void
{
widgetTypeToRemove = importCustomWidget.data as WidgetType;
removeWidget(widgetTypeToRemove);
}
private function removeWidget(widgetType:WidgetType):void
{
removeWidgetArbiter = new ProcessArbiter();
removeWidgetArbiter.addEventListener(ProcessArbiterEvent.COMPLETE, importArbiter_completeHandler);
removeWidgetArbiter.addEventListener(ProcessArbiterEvent.FAILURE, importArbiter_failureHandler);
var customWidgetModule:File = WellKnownDirectories.getInstance().customModules.resolvePath(widgetTypeToRemove.name + "Module.swf");
var customWidgetConfig:File = WellKnownDirectories.getInstance().customModules.resolvePath(widgetTypeToRemove.name + "Module.xml");
var customWidgetFolder:File = WellKnownDirectories.getInstance().customFlexViewer.resolvePath("widgets/" + widgetType.name);
removeWidgetArbiter.addProcess(new CleanUpProcess(customWidgetModule));
removeWidgetArbiter.addProcess(new CleanUpProcess(customWidgetConfig));
removeWidgetArbiter.addProcess(new CleanUpProcess(customWidgetFolder));
removeWidgetArbiter.executeProcs();
}
protected function importArbiter_completeHandler(event:ProcessArbiterEvent):void
{
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.COMPLETE, importArbiter_completeHandler);
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.FAILURE, importArbiter_failureHandler);
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.removeWidgetType(widgetTypeToRemove);
AppEvent.dispatch(AppEvent.REMOVE_CUSTOM_WIDGET_SUCCESS);
}
protected function importArbiter_failureHandler(event:ProcessArbiterEvent):void
{
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.COMPLETE, importArbiter_completeHandler);
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.FAILURE, importArbiter_failureHandler);
var removeCustomWidgetFailureMessage:String = ResourceManager.getInstance().getString("BuilderStrings",
"removeCustomWidgetProcess.failure",
[ event.message ]);
var removeCustomWidgetFailureTitle:String = ResourceManager.getInstance().getString("BuilderStrings",
"widgetManager.removeCustomWidget");
BuilderAlert.show(removeCustomWidgetFailureMessage, removeCustomWidgetFailureTitle);
AppEvent.dispatch(AppEvent.REMOVE_CUSTOM_WIDGET_FAILURE);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// 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.controllers.supportClasses.processes.CleanUpProcess;
import com.esri.builder.controllers.supportClasses.processes.ProcessArbiter;
import com.esri.builder.controllers.supportClasses.processes.ProcessArbiterEvent;
import com.esri.builder.eventbus.AppEvent;
import com.esri.builder.model.WidgetType;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.views.BuilderAlert;
import flash.filesystem.File;
import mx.resources.ResourceManager;
public class RemoveCustomWidgetController
{
private var removeWidgetArbiter:ProcessArbiter;
private var widgetTypeToRemove:WidgetType;
public function RemoveCustomWidgetController()
{
AppEvent.addListener(AppEvent.REMOVE_CUSTOM_WIDGET, removeCustomWidgetHandler);
}
private function removeCustomWidgetHandler(importCustomWidget:AppEvent):void
{
widgetTypeToRemove = importCustomWidget.data as WidgetType;
removeWidget(widgetTypeToRemove);
}
private function removeWidget(widgetType:WidgetType):void
{
removeWidgetArbiter = new ProcessArbiter();
removeWidgetArbiter.addEventListener(ProcessArbiterEvent.COMPLETE, importArbiter_completeHandler);
removeWidgetArbiter.addEventListener(ProcessArbiterEvent.FAILURE, importArbiter_failureHandler);
var customWidgetModule:File = WellKnownDirectories.getInstance().customModules.resolvePath(widgetTypeToRemove.name + "Module.swf");
var customWidgetConfig:File = WellKnownDirectories.getInstance().customModules.resolvePath(widgetTypeToRemove.name + "Module.xml");
var customWidgetFolder:File = WellKnownDirectories.getInstance().customFlexViewer.resolvePath("widgets/" + widgetType.name);
removeWidgetArbiter.addProcess(new CleanUpProcess(customWidgetModule));
removeWidgetArbiter.addProcess(new CleanUpProcess(customWidgetConfig));
removeWidgetArbiter.addProcess(new CleanUpProcess(customWidgetFolder));
removeWidgetArbiter.executeProcs();
}
protected function importArbiter_completeHandler(event:ProcessArbiterEvent):void
{
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.COMPLETE, importArbiter_completeHandler);
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.FAILURE, importArbiter_failureHandler);
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.removeWidgetType(widgetTypeToRemove);
AppEvent.dispatch(AppEvent.REMOVE_CUSTOM_WIDGET_SUCCESS);
}
protected function importArbiter_failureHandler(event:ProcessArbiterEvent):void
{
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.COMPLETE, importArbiter_completeHandler);
removeWidgetArbiter.removeEventListener(ProcessArbiterEvent.FAILURE, importArbiter_failureHandler);
var removeCustomWidgetFailureMessage:String = ResourceManager.getInstance().getString("BuilderStrings",
"removeCustomWidgetProcess.failure",
[ event.message ]);
var removeCustomWidgetFailureTitle:String = ResourceManager.getInstance().getString("BuilderStrings",
"widgetManager.removeCustomWidget");
BuilderAlert.show(removeCustomWidgetFailureMessage, removeCustomWidgetFailureTitle);
AppEvent.dispatch(AppEvent.REMOVE_CUSTOM_WIDGET_FAILURE);
}
}
}
|
Apply formatting.
|
Apply formatting.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
c90910110c9ca56213fb53b700ce42ae6efbdc7a
|
as3/com/netease/protobuf/stringToByteArray.as
|
as3/com/netease/protobuf/stringToByteArray.as
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
//
// Author: Yang Bo ([email protected])
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.utils.ByteArray
public function stringToByteArray(s:String):ByteArray {
const ba:ByteArray = new ByteArray
for (var i:uint = 0; i < s.length; ++i) {
ba.writeByte(s.charCodeAt(i))
}
return ba
}
}
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
//
// Author: Yang Bo ([email protected])
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.utils.ByteArray
public function stringToByteArray(s:String):ByteArray {
const ba:ByteArray = new ByteArray
ba.length = s.length
for (var i:uint = 0; i < s.length; ++i) {
ba[i] = s.charCodeAt(i)
}
return ba
}
}
|
初始化ByteArray时position为0
|
初始化ByteArray时position为0
|
ActionScript
|
bsd-2-clause
|
tconkling/protoc-gen-as3
|
ef2ff7fe40fd7aea803348e57edcc984f64b582f
|
examples/web/app/classes/server/FMSBridge.as
|
examples/web/app/classes/server/FMSBridge.as
|
package server {
import flash.events.EventDispatcher;
import flash.events.NetStatusEvent;
import flash.events.Event;
import flash.net.Responder;
public final class FMSBridge extends EventDispatcher {
public var connection:FMSConnection;
public var client:FMSClient;
public function FMSBridge(rtmpAddress:String = null, ...rest) {
connection = new FMSConnection();
connection.client = client = new FMSClient();
rtmpAddress && connect.apply(this, [rtmpAddress].concat(rest));
}
public function connect(rtmpAddress:String, ...rest):void {
connection.connect.apply(this, [rtmpAddress].concat(rest));
}
public function dispose():void {
connection.dispose();
}
public function close():void {
connection.close();
}
public function registerUser(token:String, email:String, player:uint):void {
connection.call('registerUser', null, token, email, player);
}
public function signinUser(token:String):void {
connection.call('signinUser', null, token);
}
public function changePlayer(player:uint):void {
connection.call('changePlayer', null, player);
}
public function startGame():void {
connection.call('startGame', null);
}
public function updateScore(score:uint):void {
connection.call('updateScore', null, score);
}
}
}
|
package server {
import flash.events.EventDispatcher;
import flash.events.NetStatusEvent;
import flash.events.Event;
import flash.net.Responder;
public final class FMSBridge extends EventDispatcher {
public var connection:FMSConnection;
public var client:FMSClient;
public function FMSBridge(rtmpAddress:String = null, ...rest) {
connection = new FMSConnection();
connection.client = client = new FMSClient();
rtmpAddress && connect.apply(this, [rtmpAddress].concat(rest));
}
public function connect(rtmpAddress:String, ...rest):void {
connection.connect.apply(this, [rtmpAddress].concat(rest));
}
public function dispose():void {
connection.dispose();
client.dispose();
}
public function close():void {
connection.close();
}
public function registerUser(token:String, email:String, player:uint):void {
connection.call('registerUser', null, token, email, player);
}
public function signinUser(token:String):void {
connection.call('signinUser', null, token);
}
public function changePlayer(player:uint):void {
connection.call('changePlayer', null, player);
}
public function startGame():void {
connection.call('startGame', null);
}
public function updateScore(score:uint):void {
connection.call('updateScore', null, score);
}
}
}
|
Update FMSBridge.as
|
Update FMSBridge.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
|
8a5e8d3f7eaab91633fb7188bf0233202a4290b3
|
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 _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;
//------------------------------------------------------------
public function KrewAsync(asyncDef:*) {
if (asyncDef is Function) {
_initWithFunction(asyncDef);
return;
}
if (asyncDef is KrewAsync) {
_initWithKrewAsync(asyncDef);
}
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 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.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;
_errorHandler = asyncDef.errorHandler;
_finallyHandler = asyncDef.finallyHandler;
_serialTasks = asyncDef.serialTasks;
_parallelTasks = asyncDef.parallelTasks;
}
//------------------------------------------------------------
// task runner
//------------------------------------------------------------
private function _kickNextSerialTask():void {
if (_serialTaskIndex >= _serialTasks.length) {
done();
return;
}
var nextTask:KrewAsync = _serialTasks[_serialTaskIndex];
++_serialTaskIndex;
nextTask.go(function(async:KrewAsync):void {
if (async.state == KrewAsync.RESOLVED) {
_kickNextSerialTask();
} else {
_onReject();
}
});
}
private function _onReject():void {
if (_errorHandler != null) {
_errorHandler();
}
_finalize();
}
private function _finalize():void {
if (_finallyHandler != null) {
_finallyHandler();
}
_onComplete(this);
}
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) {
done();
}
} else {
_onReject();
}
});
}
}
}
}
|
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 _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;
//------------------------------------------------------------
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 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.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;
_errorHandler = asyncDef.errorHandler;
_finallyHandler = asyncDef.finallyHandler;
_serialTasks = asyncDef.serialTasks;
_parallelTasks = asyncDef.parallelTasks;
}
//------------------------------------------------------------
// task runner
//------------------------------------------------------------
private function _kickNextSerialTask():void {
if (_serialTaskIndex >= _serialTasks.length) {
done();
return;
}
var nextTask:KrewAsync = _serialTasks[_serialTaskIndex];
++_serialTaskIndex;
nextTask.go(function(async:KrewAsync):void {
if (async.state == KrewAsync.RESOLVED) {
_kickNextSerialTask();
} else {
_onReject();
}
});
}
private function _onReject():void {
if (_errorHandler != null) {
_errorHandler();
}
_finalize();
}
private function _finalize():void {
if (_finallyHandler != null) {
_finallyHandler();
}
_onComplete(this);
}
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) {
done();
}
} else {
_onReject();
}
});
}
}
}
}
|
Modify KrewAsync a little
|
Modify KrewAsync a little
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
5670dd814078ad9f113e6bea0af57e0d45faa35d
|
src/org/openPyro/containers/HDividedBox.as
|
src/org/openPyro/containers/HDividedBox.as
|
package org.openPyro.containers
{
import flash.display.DisplayObject;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.getQualifiedClassName;
import org.openPyro.core.ClassFactory;
import org.openPyro.core.MeasurableControl;
import org.openPyro.core.UIControl;
import org.openPyro.layout.HLayout;
import org.openPyro.layout.ILayout;
import org.openPyro.managers.events.DragEvent;
import org.openPyro.painters.GradientFillPainter;
/**
*
*/
public class HDividedBox extends DividedBox
{
/**
* Constructor
*/
public function HDividedBox(){
super();
_styleName = "HDividedBox";
}
override public function initialize():void{
super.layout = new HLayout();
super.initialize()
}
override protected function get defaultDividerFactory():ClassFactory{
var df:ClassFactory = new ClassFactory(UIControl);
df.properties = {percentHeight:100, width:6, backgroundPainter:new GradientFillPainter([0x999999, 0x666666])}
return df;
}
protected var leftUIC:MeasurableControl
protected var rightUIC:MeasurableControl
/**
* @inheritDoc
*/
override protected function getDividerDragRect():Rectangle{
var point:Point = new Point(0,0);
point = this.localToGlobal(point);
return new Rectangle(point.x,point.y,this.width, 0)
}
override protected function onDividerDragDrop(event:DragEvent):void{
/*
If the divider moves left, delta is -ve, otherwise +ve
*/
var delta:Number = event.mouseXDelta
for(var i:int=0; i<dividerPane.numChildren; i++){
var child:DisplayObject = dividerPane.getChildAt(i)
if(child == event.dragInitiator){
leftUIC = MeasurableControl(contentPane.getChildAt(i));
rightUIC = MeasurableControl(contentPane.getChildAt(i+1));
break;
}
}
/*
Disable mouseEvents so that rollovers etc are
not triggered if the mouse rolls over them
*/
leftUIC.cancelMouseEvents();
rightUIC.cancelMouseEvents();
var unallocatedWidth:Number = (this.width - this.explicitlyAllocatedWidth);
var newUnallocatedWidth:Number = unallocatedWidth;
if(isNaN(leftUIC.explicitWidth) && isNaN(rightUIC.explicitWidth)){
/*
* The change in dimensions can be compensated by recalculating the
* two percents.
*/
var newLeftW:Number = leftUIC.width + delta;
var newRightW:Number = rightUIC.width - delta;
leftUIC.percentUnusedWidth = newLeftW*100/unallocatedWidth;
rightUIC.percentUnusedWidth = newRightW*100/unallocatedWidth
}
else if(!isNaN(leftUIC.explicitWidth) && !isNaN(rightUIC.explicitWidth)){
/*
* The dimension changes can be safely calculated
*/
leftUIC.width+=delta
rightUIC.width-=delta;
}
else if(!isNaN(leftUIC.explicitWidth)) {
/*
* Left child is explicitly sized , right is percent sized
*/
leftUIC.width+=delta;
newUnallocatedWidth = unallocatedWidth-delta;
for(var j:int=0; j<contentPane.numChildren; j++){
var currChildL:MeasurableControl = contentPane.getChildAt(j) as MeasurableControl;
if(dividers.indexOf(currChildL) != -1) continue;
if(currChildL == leftUIC) continue;
if(currChildL == rightUIC){
var newW:Number = currChildL.width-delta;
rightUIC.percentUnusedWidth = newW*100/newUnallocatedWidth
}
else if(!isNaN(currChildL.percentUnusedWidth)){
currChildL.percentUnusedWidth = currChildL.percentUnusedWidth*unallocatedWidth/newUnallocatedWidth;
}
}
}
else{
/*
* Right child is explicitly sized , left is percent sized
*/
rightUIC.width-=delta;
newUnallocatedWidth = unallocatedWidth+delta;
for(var k:int=0; k<contentPane.numChildren; k++){
var currChild:MeasurableControl = contentPane.getChildAt(k) as MeasurableControl;
if(dividers.indexOf(currChild) != -1) continue;
if(currChild == rightUIC) continue;
if(currChild == leftUIC){
var newLW:Number = currChild.width+delta;
leftUIC.percentUnusedWidth = newLW*100/newUnallocatedWidth
}
else if(!isNaN(currChild.percentUnusedWidth)){
currChild.percentUnusedWidth = currChild.percentUnusedWidth*unallocatedWidth/newUnallocatedWidth;
}
}
}
leftUIC.enableMouseEvents()
rightUIC.enableMouseEvents();
}
/**
* @inheritDoc
*/
override public function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
super.updateDisplayList(unscaledWidth, unscaledHeight);
if(this.contentPane.numChildren < 2) return;
for(var i:uint=1; i<this.contentPane.numChildren; i++){
var child:DisplayObject = this.contentPane.getChildAt(i);
dividerPane.getChildAt(i-1).x = child.x;
}
}
override public function set layout(l:ILayout):void{
throw new Error(getQualifiedClassName(this)+" cannot have layouts applied to it")
}
}
}
|
package org.openPyro.containers
{
import flash.display.DisplayObject;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.getQualifiedClassName;
import org.openPyro.core.ClassFactory;
import org.openPyro.core.MeasurableControl;
import org.openPyro.core.UIControl;
import org.openPyro.layout.HLayout;
import org.openPyro.layout.ILayout;
import org.openPyro.managers.events.DragEvent;
import org.openPyro.painters.GradientFillPainter;
/**
*
*/
public class HDividedBox extends DividedBox
{
/**
* Constructor
*/
public function HDividedBox(){
super();
_styleName = "HDividedBox";
}
override public function initialize():void{
super.layout = new HLayout();
super.initialize()
}
override protected function get defaultDividerFactory():ClassFactory{
var df:ClassFactory = new ClassFactory(UIControl);
df.properties = {percentHeight:100, width:6, backgroundPainter:new GradientFillPainter([0x999999, 0x666666])}
return df;
}
protected var leftUIC:MeasurableControl
protected var rightUIC:MeasurableControl
/**
* @inheritDoc
*/
override protected function getDividerDragRect():Rectangle{
var point:Point = new Point(0,0);
point = this.localToGlobal(point);
return new Rectangle(point.x,point.y,this.width, 0)
}
override protected function onDividerDragDrop(event:DragEvent):void{
/*
If the divider moves left, delta is -ve, otherwise +ve
*/
var delta:Number = event.mouseXDelta
for(var i:int=0; i<dividerPane.numChildren; i++){
var child:DisplayObject = dividerPane.getChildAt(i)
if(child == event.dragInitiator){
leftUIC = MeasurableControl(contentPane.getChildAt(i));
rightUIC = MeasurableControl(contentPane.getChildAt(i+1));
break;
}
}
/*
Disable mouseEvents so that rollovers etc are
not triggered if the mouse rolls over them
*/
leftUIC.cancelMouseEvents();
rightUIC.cancelMouseEvents();
var unallocatedWidth:Number = (this.width - this.explicitlyAllocatedWidth);
var newUnallocatedWidth:Number = unallocatedWidth;
if(isNaN(leftUIC.explicitWidth) && isNaN(rightUIC.explicitWidth)){
/*
* The change in dimensions can be compensated by recalculating the
* two percents.
*/
var newLeftW:Number = leftUIC.width + delta;
var newRightW:Number = rightUIC.width - delta;
leftUIC.percentUnusedWidth = newLeftW*100/unallocatedWidth;
rightUIC.percentUnusedWidth = newRightW*100/unallocatedWidth
}
else if(!isNaN(leftUIC.explicitWidth) && !isNaN(rightUIC.explicitWidth)){
/*
* The dimension changes can be safely calculated
*/
leftUIC.width+=delta
rightUIC.width-=delta;
}
else if(!isNaN(leftUIC.explicitWidth)) {
/*
* Left child is explicitly sized , right is percent sized
*/
leftUIC.width+=delta;
newUnallocatedWidth = unallocatedWidth-delta;
for(var j:int=0; j<contentPane.numChildren; j++){
var currChildL:MeasurableControl = contentPane.getChildAt(j) as MeasurableControl;
if(dividers.indexOf(currChildL) != -1) continue;
if(currChildL == leftUIC) continue;
if(currChildL == rightUIC){
var newW:Number = currChildL.width-delta;
rightUIC.percentUnusedWidth = newW*100/newUnallocatedWidth
}
else if(!isNaN(currChildL.percentUnusedWidth)){
currChildL.percentUnusedWidth = currChildL.percentUnusedWidth*unallocatedWidth/newUnallocatedWidth;
}
}
}
else{
/*
* Right child is explicitly sized , left is percent sized
*/
rightUIC.width-=delta;
newUnallocatedWidth = unallocatedWidth+delta;
for(var k:int=0; k<contentPane.numChildren; k++){
var currChild:MeasurableControl = contentPane.getChildAt(k) as MeasurableControl;
if(dividers.indexOf(currChild) != -1) continue;
if(currChild == rightUIC) continue;
if(currChild == leftUIC){
var newLW:Number = currChild.width+delta;
leftUIC.percentUnusedWidth = newLW*100/newUnallocatedWidth
}
else if(!isNaN(currChild.percentUnusedWidth)){
currChild.percentUnusedWidth = currChild.percentUnusedWidth*unallocatedWidth/newUnallocatedWidth;
}
}
}
leftUIC.enableMouseEvents()
rightUIC.enableMouseEvents();
forceUpdateDisplayList = true;
}
/**
* @inheritDoc
*/
override public function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
super.updateDisplayList(unscaledWidth, unscaledHeight);
if(this.contentPane.numChildren < 2) return;
for(var i:uint=1; i<this.contentPane.numChildren; i++){
var child:DisplayObject = this.contentPane.getChildAt(i);
dividerPane.getChildAt(i-1).x = child.x;
}
}
override public function set layout(l:ILayout):void{
throw new Error(getQualifiedClassName(this)+" cannot have layouts applied to it")
}
}
}
|
Fix to forceUpdateList on HDividedBox
|
Fix to forceUpdateList on HDividedBox
|
ActionScript
|
mit
|
arpit/openpyro
|
2652c2f0b9fc2fbc1dd6571211358addd6da9d6c
|
src/avm2/tests/regress/correctness/pass/order.as
|
src/avm2/tests/regress/correctness/pass/order.as
|
package {
class A {
var x = 1;
var y = 2;
var z = 3;
}
(function () {
trace("--- Test 1 ---");
var o : A = new A();
var r0 = o.x;
o.x = 2;
var r1 = o.x;
o.x = 3;
var r2 = o.x;
o.x = 4;
var r3 = o.x;
o.x = 5;
var r4 = o.x;
o.x = 6;
var r5 = o.x;
o.x = 7;
var r6 = o.x;
o.x = 8;
var r7 = o.x;
o.x = 9;
var r8 = o.x;
trace(r0);
trace(r1);
trace(r2);
trace(r3);
trace(r4);
trace(r5);
trace(r6);
trace(r7);
trace(r8);
})();
}
|
package {
class A {
var x = 1;
var y = 2;
var z = 3;
}
(function () {
trace("--- Test 1 ---");
var o : A = new A();
var r0 = o.x;
o.x = 2;
var r1 = o.x;
o.x = 3;
var r2 = o.x;
o.x = 4;
var r3 = o.x;
o.x = 5;
var r4 = o.x;
o.x = 6;
var r5 = o.x;
o.x = 7;
var r6 = o.x;
o.x = 8;
var r7 = o.x;
o.x = 9;
var r8 = o.x;
trace(r0);
trace(r1);
trace(r2);
trace(r3);
trace(r4);
trace(r5);
trace(r6);
trace(r7);
trace(r8);
})();
(function () {
trace("--- Test 2 ---");
var o : A = new A();
trace(o.x);
o.x = 2;
trace(o.x + o.x);
o.x = 3;
trace(o.x + o.x + o.x);
o.x = 4;
trace(o.x + o.x + o.x + o.x);
o.x = 5;
trace(o.x + o.x + o.x + o.x + o.x);
o.x = 6;
trace(o.x + o.x + o.x + o.x + o.x + o.x);
o.x = 7;
trace(o.x + o.x + o.x + o.x + o.x + o.x + o.x);
o.x = 8;
trace(o.x + o.x + o.x + o.x + o.x + o.x + o.x + o.x);
o.x = 9;
trace(o.x + o.x + o.x + o.x + o.x + o.x + o.x + o.x + o.x);
})();
}
|
Add test case.
|
Add test case.
|
ActionScript
|
apache-2.0
|
yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway
|
d43f6e332c184b12d90afef9d737f696e1b26244
|
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.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
private const CIRRUS_URL:String = "rtmfp://tor-facilitator.bamsoftware.com";
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "tor-facilitator.bamsoftware.com",
port: 9002
};
/* Local Tor client to use in case of RTMFP connection. */
private const LOCAL_TOR_CLIENT_ADDR:Object = {
host: "127.0.0.1",
port: 9002
};
private const MAX_NUM_PROXY_PAIRS:uint = 1;
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Bytes per second. Set to undefined to disable limit.
public const RATE_LIMIT:Number = undefined;
// Seconds.
private const RATE_LIMIT_HISTORY:Number = 5.0;
/* TextField for debug output. */
private var output_text:TextField;
/* UI shown when debug is off. */
private var badge:Badge;
/* Number of proxy pairs currently connected (up to
MAX_NUM_PROXY_PAIRS). */
private var num_proxy_pairs:int = 0;
private var fac_addr:Object;
public var rate_limit:RateLimit;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
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;
badge = new Badge();
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY);
else
rate_limit = new RateUnlimit();
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"] || this.loaderInfo.parameters["client"])
addChild(output_text);
else
addChild(badge);
fac_addr = get_param_addr("facilitator", DEFAULT_FACILITATOR_ADDR);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
if (this.loaderInfo.parameters["client"])
client_main();
else
proxy_main();
}
/* Get an address structure from the given movie parameter, or the given
default. Returns null on error. */
private function get_param_addr(param:String, default_addr:Object):Object
{
var spec:String, addr:Object;
spec = this.loaderInfo.parameters[param];
if (spec)
return parse_addr_spec(spec);
else
return default_addr;
}
/* The main logic begins here, after start-up issues are taken care of. */
private function proxy_main():void
{
var fac_url:String;
var loader:URLLoader;
if (num_proxy_pairs >= MAX_NUM_PROXY_PAIRS) {
setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL);
return;
}
loader = new URLLoader();
/* Get the x-www-form-urlencoded values. */
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, fac_complete);
loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
fac_url = "http://" + encodeURIComponent(fac_addr.host)
+ ":" + encodeURIComponent(fac_addr.port) + "/";
puts("Facilitator: connecting to " + fac_url + ".");
loader.load(new URLRequest(fac_url));
}
private function fac_complete(e:Event):void
{
var loader:URLLoader;
var client_spec:String;
var relay_spec:String;
var proxy_pair:Object;
setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL);
loader = e.target as URLLoader;
client_spec = loader.data.client;
if (client_spec == "") {
puts("No clients.");
return;
} else if (!client_spec) {
puts("Error: missing \"client\" in response.");
return;
}
relay_spec = loader.data.relay;
if (!relay_spec) {
puts("Error: missing \"relay\" in response.");
return;
}
puts("Facilitator: got client:\"" + client_spec + "\" "
+ "relay:\"" + relay_spec + "\".");
try {
proxy_pair = make_proxy_pair(client_spec, relay_spec);
} catch (e:ArgumentError) {
puts("Error: " + e);
return;
}
proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void {
proxy_pair.log("Complete.");
num_proxy_pairs--;
badge.proxy_end();
});
proxy_pair.connect();
num_proxy_pairs++;
badge.proxy_begin();
}
private function client_main():void
{
var rs:RTMFPSocket;
rs = new RTMFPSocket(CIRRUS_URL);
rs.addEventListener(Event.COMPLETE, function (e:Event):void {
puts("Got RTMFP id " + rs.id);
register(rs);
});
rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, client_accept);
rs.listen();
}
private function client_accept(e:Event):void {
var rs:RTMFPSocket;
var s_t:Socket;
var proxy_pair:ProxyPair;
rs = e.target as RTMFPSocket;
s_t = new Socket();
puts("Got RTMFP connection from " + rs.peer_id);
proxy_pair = new ProxyPair(this, rs, function ():void {
/* Do nothing; already connected. */
}, s_t, function ():void {
s_t.connect(LOCAL_TOR_CLIENT_ADDR.host, LOCAL_TOR_CLIENT_ADDR.port);
});
proxy_pair.connect();
}
private function register(rs:RTMFPSocket):void {
var fac_url:String;
var loader:URLLoader;
var request:URLRequest;
var variables:URLVariables;
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, function (e:Event):void {
puts("Facilitator: registered.");
});
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
rs.close();
});
loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
rs.close();
});
fac_url = "http://" + encodeURIComponent(fac_addr.host)
+ ":" + encodeURIComponent(fac_addr.port) + "/";
request = new URLRequest(fac_url);
request.method = URLRequestMethod.POST;
request.data = new URLVariables;
request.data["client"] = rs.id;
puts("Facilitator: connecting to " + fac_url + ".");
loader.load(request);
}
private function make_proxy_pair(client_spec:String, relay_spec:String):ProxyPair
{
var proxy_pair:ProxyPair;
var addr_c:Object;
var addr_r:Object;
var s_c:*;
var s_r:Socket;
addr_r = swfcat.parse_addr_spec(relay_spec);
if (!addr_r)
throw new ArgumentError("Relay spec must be in the form \"host:port\".");
addr_c = swfcat.parse_addr_spec(client_spec);
if (addr_c) {
s_c = new Socket();
s_r = new Socket();
proxy_pair = new ProxyPair(this, s_c, function ():void {
s_c.connect(addr_c.host, addr_c.port);
}, s_r, function ():void {
s_r.connect(addr_r.host, addr_r.port);
});
proxy_pair.set_name("<" + addr_c.host + ":" + addr_c.port + ","
+ addr_r.host + ":" + addr_r.port + ">");
return proxy_pair;
}
if (client_spec.match(/^[0-9A-Fa-f]{64}$/)) {
s_c = new RTMFPSocket(CIRRUS_URL);
s_r = new Socket();
proxy_pair = new ProxyPair(this, s_c, function ():void {
s_c.connect(client_spec);
}, s_r, function ():void {
s_r.connect(addr_r.host, addr_r.port);
});
proxy_pair.set_name("<" + client_spec.substr(0, 4) + "...,"
+ addr_r.host + ":" + addr_r.port + ">");
return proxy_pair;
}
throw new ArgumentError("Can't parse client spec \"" + client_spec + "\".");
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.text.TextFormat;
import flash.text.TextField;
import flash.utils.getTimer;
class Badge extends flash.display.Sprite
{
/* Number of proxy pairs currently connected. */
private var num_proxy_pairs:int = 0;
/* Number of proxy pairs ever connected. */
private var total_proxy_pairs:int = 0;
[Embed(source="badge.png")]
private var BadgeImage:Class;
private var tot_client_count_tf:TextField;
private var tot_client_count_fmt:TextFormat;
private var cur_client_count_tf:TextField;
private var cur_client_count_fmt:TextFormat;
public function Badge()
{
/* Setup client counter for badge. */
tot_client_count_fmt = new TextFormat();
tot_client_count_fmt.color = 0xFFFFFF;
tot_client_count_fmt.align = "center";
tot_client_count_fmt.font = "courier-new";
tot_client_count_fmt.bold = true;
tot_client_count_fmt.size = 10;
tot_client_count_tf = new TextField();
tot_client_count_tf.width = 20;
tot_client_count_tf.height = 17;
tot_client_count_tf.background = false;
tot_client_count_tf.defaultTextFormat = tot_client_count_fmt;
tot_client_count_tf.x=47;
tot_client_count_tf.y=0;
cur_client_count_fmt = new TextFormat();
cur_client_count_fmt.color = 0xFFFFFF;
cur_client_count_fmt.align = "center";
cur_client_count_fmt.font = "courier-new";
cur_client_count_fmt.bold = true;
cur_client_count_fmt.size = 10;
cur_client_count_tf = new TextField();
cur_client_count_tf.width = 20;
cur_client_count_tf.height = 17;
cur_client_count_tf.background = false;
cur_client_count_tf.defaultTextFormat = cur_client_count_fmt;
cur_client_count_tf.x=47;
cur_client_count_tf.y=6;
addChild(new BadgeImage());
addChild(tot_client_count_tf);
addChild(cur_client_count_tf);
/* Update the client counter on badge. */
update_client_count();
}
public function proxy_begin():void
{
num_proxy_pairs++;
total_proxy_pairs++;
update_client_count();
}
public function proxy_end():void
{
num_proxy_pairs--;
update_client_count();
}
private function update_client_count():void
{
/* Update total client count. */
if (String(total_proxy_pairs).length == 1)
tot_client_count_tf.text = "0" + String(total_proxy_pairs);
else
tot_client_count_tf.text = String(total_proxy_pairs);
/* Update current client count. */
cur_client_count_tf.text = "";
for(var i:Number = 0; i < num_proxy_pairs; i++)
cur_client_count_tf.appendText(".");
}
}
class RateLimit
{
public function RateLimit()
{
}
public function update(n:Number):Boolean
{
return true;
}
public function when():Number
{
return 0.0;
}
public function is_limited():Boolean
{
return false;
}
}
class RateUnlimit extends RateLimit
{
public function RateUnlimit()
{
}
public override function update(n:Number):Boolean
{
return true;
}
public override function when():Number
{
return 0.0;
}
public override function is_limited():Boolean
{
return false;
}
}
class BucketRateLimit extends RateLimit
{
private var amount:Number;
private var capacity:Number;
private var time:Number;
private var last_update:uint;
public function BucketRateLimit(capacity:Number, time:Number)
{
this.amount = 0.0;
/* capacity / time is the rate we are aiming for. */
this.capacity = capacity;
this.time = time;
this.last_update = getTimer();
}
private function age():void
{
var now:uint;
var delta:Number;
now = getTimer();
delta = (now - last_update) / 1000.0;
last_update = now;
amount -= delta * capacity / time;
if (amount < 0.0)
amount = 0.0;
}
public override function update(n:Number):Boolean
{
age();
amount += n;
return amount <= capacity;
}
public override function when():Number
{
age();
return (amount - capacity) / (capacity / time);
}
public override function is_limited():Boolean
{
age();
return amount > capacity;
}
}
|
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.net.Socket;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
private const RTMFP_URL:String = "rtmfp://tor-facilitator.bamsoftware.com";
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "tor-facilitator.bamsoftware.com",
port: 9002
};
/* Local Tor client to use in case of RTMFP connection. */
private const LOCAL_TOR_CLIENT_ADDR:Object = {
host: "127.0.0.1",
port: 9002
};
private const MAX_NUM_PROXY_PAIRS:uint = 1;
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Bytes per second. Set to undefined to disable limit.
public const RATE_LIMIT:Number = undefined;
// Seconds.
private const RATE_LIMIT_HISTORY:Number = 5.0;
/* TextField for debug output. */
private var output_text:TextField;
/* UI shown when debug is off. */
private var badge:Badge;
/* Number of proxy pairs currently connected (up to
MAX_NUM_PROXY_PAIRS). */
private var num_proxy_pairs:int = 0;
private var fac_addr:Object;
public var rate_limit:RateLimit;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
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;
badge = new Badge();
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY);
else
rate_limit = new RateUnlimit();
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"] || this.loaderInfo.parameters["client"])
addChild(output_text);
else
addChild(badge);
fac_addr = get_param_addr("facilitator", DEFAULT_FACILITATOR_ADDR);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
if (this.loaderInfo.parameters["client"])
client_main();
else
proxy_main();
}
/* Get an address structure from the given movie parameter, or the given
default. Returns null on error. */
private function get_param_addr(param:String, default_addr:Object):Object
{
var spec:String, addr:Object;
spec = this.loaderInfo.parameters[param];
if (spec)
return parse_addr_spec(spec);
else
return default_addr;
}
/* The main logic begins here, after start-up issues are taken care of. */
private function proxy_main():void
{
var fac_url:String;
var loader:URLLoader;
if (num_proxy_pairs >= MAX_NUM_PROXY_PAIRS) {
setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL);
return;
}
loader = new URLLoader();
/* Get the x-www-form-urlencoded values. */
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, fac_complete);
loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
fac_url = "http://" + encodeURIComponent(fac_addr.host)
+ ":" + encodeURIComponent(fac_addr.port) + "/";
puts("Facilitator: connecting to " + fac_url + ".");
loader.load(new URLRequest(fac_url));
}
private function fac_complete(e:Event):void
{
var loader:URLLoader;
var client_spec:String;
var relay_spec:String;
var proxy_pair:Object;
setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL);
loader = e.target as URLLoader;
client_spec = loader.data.client;
if (client_spec == "") {
puts("No clients.");
return;
} else if (!client_spec) {
puts("Error: missing \"client\" in response.");
return;
}
relay_spec = loader.data.relay;
if (!relay_spec) {
puts("Error: missing \"relay\" in response.");
return;
}
puts("Facilitator: got client:\"" + client_spec + "\" "
+ "relay:\"" + relay_spec + "\".");
try {
proxy_pair = make_proxy_pair(client_spec, relay_spec);
} catch (e:ArgumentError) {
puts("Error: " + e);
return;
}
proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void {
proxy_pair.log("Complete.");
num_proxy_pairs--;
badge.proxy_end();
});
proxy_pair.connect();
num_proxy_pairs++;
badge.proxy_begin();
}
private function client_main():void
{
var rs:RTMFPSocket;
rs = new RTMFPSocket(RTMFP_URL);
rs.addEventListener(Event.COMPLETE, function (e:Event):void {
puts("Got RTMFP id " + rs.id);
register(rs);
});
rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, client_accept);
rs.listen();
}
private function client_accept(e:Event):void {
var rs:RTMFPSocket;
var s_t:Socket;
var proxy_pair:ProxyPair;
rs = e.target as RTMFPSocket;
s_t = new Socket();
puts("Got RTMFP connection from " + rs.peer_id);
proxy_pair = new ProxyPair(this, rs, function ():void {
/* Do nothing; already connected. */
}, s_t, function ():void {
s_t.connect(LOCAL_TOR_CLIENT_ADDR.host, LOCAL_TOR_CLIENT_ADDR.port);
});
proxy_pair.connect();
}
private function register(rs:RTMFPSocket):void {
var fac_url:String;
var loader:URLLoader;
var request:URLRequest;
var variables:URLVariables;
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, function (e:Event):void {
puts("Facilitator: registered.");
});
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
rs.close();
});
loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
rs.close();
});
fac_url = "http://" + encodeURIComponent(fac_addr.host)
+ ":" + encodeURIComponent(fac_addr.port) + "/";
request = new URLRequest(fac_url);
request.method = URLRequestMethod.POST;
request.data = new URLVariables;
request.data["client"] = rs.id;
puts("Facilitator: connecting to " + fac_url + ".");
loader.load(request);
}
private function make_proxy_pair(client_spec:String, relay_spec:String):ProxyPair
{
var proxy_pair:ProxyPair;
var addr_c:Object;
var addr_r:Object;
var s_c:*;
var s_r:Socket;
addr_r = swfcat.parse_addr_spec(relay_spec);
if (!addr_r)
throw new ArgumentError("Relay spec must be in the form \"host:port\".");
addr_c = swfcat.parse_addr_spec(client_spec);
if (addr_c) {
s_c = new Socket();
s_r = new Socket();
proxy_pair = new ProxyPair(this, s_c, function ():void {
s_c.connect(addr_c.host, addr_c.port);
}, s_r, function ():void {
s_r.connect(addr_r.host, addr_r.port);
});
proxy_pair.set_name("<" + addr_c.host + ":" + addr_c.port + ","
+ addr_r.host + ":" + addr_r.port + ">");
return proxy_pair;
}
if (client_spec.match(/^[0-9A-Fa-f]{64}$/)) {
s_c = new RTMFPSocket(RTMFP_URL);
s_r = new Socket();
proxy_pair = new ProxyPair(this, s_c, function ():void {
s_c.connect(client_spec);
}, s_r, function ():void {
s_r.connect(addr_r.host, addr_r.port);
});
proxy_pair.set_name("<" + client_spec.substr(0, 4) + "...,"
+ addr_r.host + ":" + addr_r.port + ">");
return proxy_pair;
}
throw new ArgumentError("Can't parse client spec \"" + client_spec + "\".");
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.text.TextFormat;
import flash.text.TextField;
import flash.utils.getTimer;
class Badge extends flash.display.Sprite
{
/* Number of proxy pairs currently connected. */
private var num_proxy_pairs:int = 0;
/* Number of proxy pairs ever connected. */
private var total_proxy_pairs:int = 0;
[Embed(source="badge.png")]
private var BadgeImage:Class;
private var tot_client_count_tf:TextField;
private var tot_client_count_fmt:TextFormat;
private var cur_client_count_tf:TextField;
private var cur_client_count_fmt:TextFormat;
public function Badge()
{
/* Setup client counter for badge. */
tot_client_count_fmt = new TextFormat();
tot_client_count_fmt.color = 0xFFFFFF;
tot_client_count_fmt.align = "center";
tot_client_count_fmt.font = "courier-new";
tot_client_count_fmt.bold = true;
tot_client_count_fmt.size = 10;
tot_client_count_tf = new TextField();
tot_client_count_tf.width = 20;
tot_client_count_tf.height = 17;
tot_client_count_tf.background = false;
tot_client_count_tf.defaultTextFormat = tot_client_count_fmt;
tot_client_count_tf.x=47;
tot_client_count_tf.y=0;
cur_client_count_fmt = new TextFormat();
cur_client_count_fmt.color = 0xFFFFFF;
cur_client_count_fmt.align = "center";
cur_client_count_fmt.font = "courier-new";
cur_client_count_fmt.bold = true;
cur_client_count_fmt.size = 10;
cur_client_count_tf = new TextField();
cur_client_count_tf.width = 20;
cur_client_count_tf.height = 17;
cur_client_count_tf.background = false;
cur_client_count_tf.defaultTextFormat = cur_client_count_fmt;
cur_client_count_tf.x=47;
cur_client_count_tf.y=6;
addChild(new BadgeImage());
addChild(tot_client_count_tf);
addChild(cur_client_count_tf);
/* Update the client counter on badge. */
update_client_count();
}
public function proxy_begin():void
{
num_proxy_pairs++;
total_proxy_pairs++;
update_client_count();
}
public function proxy_end():void
{
num_proxy_pairs--;
update_client_count();
}
private function update_client_count():void
{
/* Update total client count. */
if (String(total_proxy_pairs).length == 1)
tot_client_count_tf.text = "0" + String(total_proxy_pairs);
else
tot_client_count_tf.text = String(total_proxy_pairs);
/* Update current client count. */
cur_client_count_tf.text = "";
for(var i:Number = 0; i < num_proxy_pairs; i++)
cur_client_count_tf.appendText(".");
}
}
class RateLimit
{
public function RateLimit()
{
}
public function update(n:Number):Boolean
{
return true;
}
public function when():Number
{
return 0.0;
}
public function is_limited():Boolean
{
return false;
}
}
class RateUnlimit extends RateLimit
{
public function RateUnlimit()
{
}
public override function update(n:Number):Boolean
{
return true;
}
public override function when():Number
{
return 0.0;
}
public override function is_limited():Boolean
{
return false;
}
}
class BucketRateLimit extends RateLimit
{
private var amount:Number;
private var capacity:Number;
private var time:Number;
private var last_update:uint;
public function BucketRateLimit(capacity:Number, time:Number)
{
this.amount = 0.0;
/* capacity / time is the rate we are aiming for. */
this.capacity = capacity;
this.time = time;
this.last_update = getTimer();
}
private function age():void
{
var now:uint;
var delta:Number;
now = getTimer();
delta = (now - last_update) / 1000.0;
last_update = now;
amount -= delta * capacity / time;
if (amount < 0.0)
amount = 0.0;
}
public override function update(n:Number):Boolean
{
age();
amount += n;
return amount <= capacity;
}
public override function when():Number
{
age();
return (amount - capacity) / (capacity / time);
}
public override function is_limited():Boolean
{
age();
return amount > capacity;
}
}
|
Rename CIRRUS_URL to RTMFP_URL.
|
Rename CIRRUS_URL to RTMFP_URL.
|
ActionScript
|
mit
|
glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy
|
7d7452d604dda4f5fbd94c63eedb78140cde017b
|
WeaveData/src/weave/data/CSVParser.as
|
WeaveData/src/weave/data/CSVParser.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.data
{
import flash.utils.ByteArray;
import flash.utils.getTimer;
import mx.utils.ObjectUtil;
import mx.utils.StringUtil;
import weave.api.WeaveAPI;
import weave.api.core.ILinkableObject;
import weave.api.data.ICSVParser;
import weave.api.getCallbackCollection;
import weave.utils.AsyncSort;
/**
* This is an all-static class containing functions to parse and generate valid CSV files.
* Ported from AutoIt Script to Flex. Original author: adufilie
*
* @author skolman
* @author adufilie
*/
public class CSVParser implements ICSVParser, ILinkableObject
{
private static const CR:String = '\r';
private static const LF:String = '\n';
private static const CRLF:String = '\r\n';
/**
* @param delimiter
* @param quote
* @param asyncMode If this is set to true, parseCSV() will work asynchronously and trigger callbacks when it finishes.
* Note that if asyncMode is enabled, you can only parse one CSV string at a time.
*/
public function CSVParser(asyncMode:Boolean = false, delimiter:String = ',', quote:String = '"')
{
this.asyncMode = asyncMode;
if (delimiter && delimiter.length == 1)
this.delimiter = delimiter;
if (quote && quote.length == 1)
this.quote = quote;
}
// modes set in constructor
private var asyncMode:Boolean;
private var delimiter:String = ',';
private var quote:String = '"';
// async state
private var csvData:String;
private var csvDataArray:Array;
private var parseTokens:Boolean;
private var i:int;
private var row:int;
private var col:int;
private var escaped:Boolean;
/**
* @return The resulting two-dimensional Array from the last call to parseCSV().
*/
public function get parseResult():Array
{
return csvDataArray;
}
/**
* @inheritDoc
*/
public function parseCSV(csvData:String, parseTokens:Boolean = true):Array
{
// initialization
this.csvData = csvData;
this.csvDataArray = [];
this.parseTokens = parseTokens;
this.i = 0;
this.row = 0;
this.col = 0;
this.escaped = false;
if (asyncMode)
{
WeaveAPI.StageUtils.startTask(this, parseIterate, WeaveAPI.TASK_PRIORITY_3_PARSING, parseDone);
}
else
{
parseIterate(int.MAX_VALUE);
parseDone();
}
return csvDataArray;
}
private function parseIterate(stopTime:int):Number
{
// run initialization code on first iteration
if (i == 0)
{
if (!csvData) // null or empty string?
return 1; // done
// start off first row with an empty string token
csvDataArray[row] = [''];
}
while (getTimer() < stopTime)
{
if (i >= csvData.length)
return 1; // done
var currentChar:String = csvData.charAt(i);
var twoChar:String = currentChar + csvData.charAt(i+1);
if (escaped)
{
if (twoChar == quote+quote) //escaped quote
{
csvDataArray[row][col] += (parseTokens?currentChar:twoChar);//append quote(s) to current token
i += 1; //skip second quote mark
}
else if (currentChar == quote) //end of escaped text
{
escaped = false;
if (!parseTokens)
{
csvDataArray[row][col] += currentChar;//append quote to current token
}
}
else
{
csvDataArray[row][col] += currentChar;//append quotes to current token
}
}
else
{
if (twoChar == delimiter+quote)
{
escaped = true;
col += 1;
csvDataArray[row][col] = (parseTokens?'':quote);
i += 1; //skip quote mark
}
else if (currentChar == quote && csvDataArray[row][col] == '') //start new token
{
escaped = true;
if (!parseTokens)
csvDataArray[row][col] += currentChar;
}
else if (currentChar == delimiter) //start new token
{
col += 1;
csvDataArray[row][col] = '';
}
else if (twoChar == CRLF) //then start new row
{
i += 1; //skip line feed
row += 1;
col = 0;
csvDataArray[row] = [''];
}
else if (currentChar == CR) //then start new row
{
row += 1;
col = 0;
csvDataArray[row] = [''];
}
else if (currentChar == LF) //then start new row
{
row += 1;
col = 0;
csvDataArray[row] = [''];
}
else //append single character to current token
csvDataArray[row][col] += currentChar;
}
i++;
}
return i / csvData.length;
}
private function parseDone():void
{
// if there is more than one row and last row is empty,
// remove last row assuming it is there because of a newline at the end of the file.
for (var iRow:int = csvDataArray.length; iRow--;)
{
var dataLine:Array = csvDataArray[iRow];
if (dataLine.length == 1 && dataLine[0] == '')
csvDataArray.splice(iRow, 1);
}
if (asyncMode)
getCallbackCollection(this).triggerCallbacks();
}
/**
* @inheritDoc
*/
public function createCSV(rows:Array):String
{
var firstRow:Boolean = true;
var out:ByteArray = new ByteArray();
for each (var row:Array in rows)
{
if (firstRow)
firstRow = false;
else
out.writeUTFBytes(LF);
var firstItem:Boolean = true;
for each (var item:String in row)
{
if (firstItem)
firstItem = false;
else
out.writeUTFBytes(delimiter);
out.writeUTFBytes(createCSVToken(item));
}
}
out.position = 0;
return out.readUTFBytes(out.length);
}
/**
* @inheritDoc
*/
public function parseCSVRow(csvData:String, parseTokens:Boolean = true):Array
{
if (csvData == null)
return null;
var rows:Array = parseCSV(csvData, parseTokens);
if (rows.length == 0)
return rows;
if (rows.length == 1)
return rows[0];
// flatten
return [].concat.apply(null, rows);
}
/**
* @inheritDoc
*/
public function createCSVRow(row:Array):String
{
return createCSV([row]);
}
/**
* @inheritDoc
*/
public function parseCSVToken(token:String):String
{
var parsedToken:String = '';
var tokenLength:int = token.length;
if (token.charAt(0) == quote)
{
var escaped:Boolean = true;
for (var i:int = 1; i <= tokenLength; i++)
{
var currentChar:String = token.charAt(i);
var twoChar:String = currentChar + token.charAt(i+1);
if (twoChar == quote+quote) //append escaped quote
{
i += 1;
parsedToken += quote;
}
else if (currentChar == quote && escaped)
{
escaped = false;
}
else
{
parsedToken += currentChar;
}
}
}
else
{
parsedToken = token;
}
return parsedToken;
}
/**
* @inheritDoc
*/
public function createCSVToken(str:String):String
{
if (str == null)
str = '';
// determine if quotes are necessary
if ( str.length > 0
&& str.indexOf(quote) < 0
&& str.indexOf(delimiter) < 0
&& str.indexOf(LF) < 0
&& str.indexOf(CR) < 0
&& str == StringUtil.trim(str) )
{
return str;
}
var token:String = quote;
for (var i:int = 0; i <= str.length; i++)
{
var currentChar:String = str.charAt(i);
if (currentChar == quote)
token += quote + quote;
else
token += currentChar;
}
return token + quote;
}
/**
* @inheritDoc
*/
public function convertRowsToRecords(rows:Array, headerDepth:int = 1):Array
{
if (rows.length < headerDepth)
throw new Error("headerDepth is greater than the number of rows");
assertHeaderDepth(headerDepth);
var records:Array = new Array(rows.length - headerDepth);
for (var r:int = headerDepth; r < rows.length; r++)
{
var record:Object = {};
var row:Array = rows[r];
for (var c:int = 0; c < row.length; c++)
{
var output:Object = record;
var cell:Object = row[c];
for (var h:int = 0; h < headerDepth; h++)
{
var colName:String = rows[h][c];
if (h < headerDepth - 1)
{
if (!output[colName])
output[colName] = {};
output = output[colName];
}
else
output[colName] = cell;
}
}
records[r - headerDepth] = record;
}
return records;
}
/**
* @inheritDoc
*/
public function getRecordFieldNames(records:Array, includeNullFields:Boolean = false, headerDepth:int = 1):Array
{
assertHeaderDepth(headerDepth);
var nestedFieldNames:Object = {};
for each (var record:Object in records)
_outputNestedFieldNames(record, includeNullFields, nestedFieldNames, headerDepth);
var fields:Array = [];
_collapseNestedFieldNames(nestedFieldNames, fields);
return fields;
}
private function _outputNestedFieldNames(record:Object, includeNullFields:Boolean, output:Object, depth:int):void
{
for (var field:String in record)
{
if (includeNullFields || record[field] != null)
{
if (depth == 1)
{
output[field] = false;
}
else
{
if (!output[field])
output[field] = {};
_outputNestedFieldNames(record[field], includeNullFields, output[field], depth - 1);
}
}
}
}
private function _collapseNestedFieldNames(nestedFieldNames:Object, output:Array, prefix:Array = null):void
{
for (var field:String in nestedFieldNames)
{
if (nestedFieldNames[field]) // either an Object or false
{
_collapseNestedFieldNames(nestedFieldNames[field], output, prefix ? prefix.concat(field) : [field]);
}
else // false means reached full nesting depth
{
if (prefix) // is depth > 1?
output.push(prefix.concat(field)); // output the list of nested field names
else
output.push(field); // no array when max depth is 1
}
}
}
/**
* @inheritDoc
*/
public function convertRecordsToRows(records:Array, columnOrder:Array = null, allowBlankColumns:Boolean = false, headerDepth:int = 1):Array
{
assertHeaderDepth(headerDepth);
var fields:Array = columnOrder;
if (fields == null)
{
fields = getRecordFieldNames(records, allowBlankColumns, headerDepth);
AsyncSort.sortImmediately(fields);
}
var r:int;
var c:int;
var cell:Object;
var row:Array;
var rows:Array = new Array(records.length + headerDepth);
// construct multiple header rows from field name chains
for (r = 0; r < headerDepth; r++)
{
row = new Array(fields.length);
for (c = 0; c < fields.length; c++)
{
if (headerDepth > 1)
row[c] = fields[c][r] || ''; // fields are Arrays
else
row[c] = fields[c] || ''; // fields are Strings
}
rows[r] = row;
}
for (r = 0; r < records.length; r++)
{
var record:Object = records[r];
row = new Array(fields.length);
for (c = 0; c < fields.length; c++)
{
if (headerDepth == 1)
{
// fields is an Array of Strings
cell = record[fields[c]];
}
else
{
// fields is an Array of Arrays
cell = record;
for each (var field:String in fields[c])
if (cell)
cell = cell[field];
}
row[c] = cell != null ? String(cell) : '';
}
rows[headerDepth + r] = row;
}
return rows;
}
private static function assertHeaderDepth(headerDepth:int):void
{
if (headerDepth < 1)
throw new Error("headerDepth must be > 0");
}
//test();
private static var _tested:Boolean = false;
private static function test():void
{
if (_tested)
return;
_tested = true;
var _:Object = {};
_.parser = WeaveAPI.CSVParser;
_.csv=[
"internal,internal,public,public,public,private,private,test",
"id,type,title,keyType,dataType,connection,sqlQuery,empty",
"2,1,state name,fips,string,resd,\"select fips,name from myschema.state_data\",",
"3,1,population,fips,number,resd,\"select fips,pop from myschema.state_data\",",
"1,0,state data table"
].join('\n');
_.table = _.parser.parseCSV(_.csv);
_.records = _.parser.convertRowsToRecords(_.table, 2);
_.rows = _.parser.convertRecordsToRows(_.records, null, false, 2);
_.fields = _.parser.getRecordFieldNames(_.records, false, 2);
_.fieldOrder = _.parser.parseCSV('internal,id\ninternal,type\npublic,title\npublic,keyType\npublic,dataType\nprivate,connection\nprivate,sqlQuery');
_.rows2 = _.parser.convertRecordsToRows(_.records, _.fieldOrder, false, 2);
weaveTrace(ObjectUtil.toString(_));
}
}
}
|
/*
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.data
{
import flash.utils.getTimer;
import mx.utils.ObjectUtil;
import mx.utils.StringUtil;
import weave.api.WeaveAPI;
import weave.api.core.ILinkableObject;
import weave.api.data.ICSVParser;
import weave.api.getCallbackCollection;
import weave.utils.AsyncSort;
/**
* This is an all-static class containing functions to parse and generate valid CSV files.
* Ported from AutoIt Script to Flex. Original author: adufilie
*
* @author skolman
* @author adufilie
*/
public class CSVParser implements ICSVParser, ILinkableObject
{
private static const CR:String = '\r';
private static const LF:String = '\n';
private static const CRLF:String = '\r\n';
/**
* @param delimiter
* @param quote
* @param asyncMode If this is set to true, parseCSV() will work asynchronously and trigger callbacks when it finishes.
* Note that if asyncMode is enabled, you can only parse one CSV string at a time.
*/
public function CSVParser(asyncMode:Boolean = false, delimiter:String = ',', quote:String = '"')
{
this.asyncMode = asyncMode;
if (delimiter && delimiter.length == 1)
this.delimiter = delimiter;
if (quote && quote.length == 1)
this.quote = quote;
}
// modes set in constructor
private var asyncMode:Boolean;
private var delimiter:String = ',';
private var quote:String = '"';
// async state
private var csvData:String;
private var csvDataArray:Array;
private var parseTokens:Boolean;
private var i:int;
private var row:int;
private var col:int;
private var escaped:Boolean;
/**
* @return The resulting two-dimensional Array from the last call to parseCSV().
*/
public function get parseResult():Array
{
return csvDataArray;
}
/**
* @inheritDoc
*/
public function parseCSV(csvData:String, parseTokens:Boolean = true):Array
{
// initialization
this.csvData = csvData;
this.csvDataArray = [];
this.parseTokens = parseTokens;
this.i = 0;
this.row = 0;
this.col = 0;
this.escaped = false;
if (asyncMode)
{
WeaveAPI.StageUtils.startTask(this, parseIterate, WeaveAPI.TASK_PRIORITY_3_PARSING, parseDone);
}
else
{
parseIterate(int.MAX_VALUE);
parseDone();
}
return csvDataArray;
}
private function parseIterate(stopTime:int):Number
{
// run initialization code on first iteration
if (i == 0)
{
if (!csvData) // null or empty string?
return 1; // done
// start off first row with an empty string token
csvDataArray[row] = [''];
}
while (getTimer() < stopTime)
{
if (i >= csvData.length)
return 1; // done
var currentChar:String = csvData.charAt(i);
var twoChar:String = currentChar + csvData.charAt(i+1);
if (escaped)
{
if (twoChar == quote+quote) //escaped quote
{
csvDataArray[row][col] += (parseTokens?currentChar:twoChar);//append quote(s) to current token
i += 1; //skip second quote mark
}
else if (currentChar == quote) //end of escaped text
{
escaped = false;
if (!parseTokens)
{
csvDataArray[row][col] += currentChar;//append quote to current token
}
}
else
{
csvDataArray[row][col] += currentChar;//append quotes to current token
}
}
else
{
if (twoChar == delimiter+quote)
{
escaped = true;
col += 1;
csvDataArray[row][col] = (parseTokens?'':quote);
i += 1; //skip quote mark
}
else if (currentChar == quote && csvDataArray[row][col] == '') //start new token
{
escaped = true;
if (!parseTokens)
csvDataArray[row][col] += currentChar;
}
else if (currentChar == delimiter) //start new token
{
col += 1;
csvDataArray[row][col] = '';
}
else if (twoChar == CRLF) //then start new row
{
i += 1; //skip line feed
row += 1;
col = 0;
csvDataArray[row] = [''];
}
else if (currentChar == CR) //then start new row
{
row += 1;
col = 0;
csvDataArray[row] = [''];
}
else if (currentChar == LF) //then start new row
{
row += 1;
col = 0;
csvDataArray[row] = [''];
}
else //append single character to current token
csvDataArray[row][col] += currentChar;
}
i++;
}
return i / csvData.length;
}
private function parseDone():void
{
// if there is more than one row and last row is empty,
// remove last row assuming it is there because of a newline at the end of the file.
for (var iRow:int = csvDataArray.length; iRow--;)
{
var dataLine:Array = csvDataArray[iRow];
if (dataLine.length == 1 && dataLine[0] == '')
csvDataArray.splice(iRow, 1);
}
if (asyncMode)
getCallbackCollection(this).triggerCallbacks();
}
/**
* @inheritDoc
*/
public function createCSV(rows:Array):String
{
var lines:Array = new Array(rows.length);
for (var i:int = rows.length; i--;)
{
var tokens:Array = new Array(rows[i].length);
for (var j:int = tokens.length; j--;)
tokens[j] = createCSVToken(rows[i][j]);
lines[i] = tokens.join(delimiter);
}
var csvData:String = lines.join(LF);
return csvData;
}
/**
* @inheritDoc
*/
public function parseCSVRow(csvData:String, parseTokens:Boolean = true):Array
{
if (csvData == null)
return null;
var rows:Array = parseCSV(csvData, parseTokens);
if (rows.length == 0)
return rows;
if (rows.length == 1)
return rows[0];
// flatten
return [].concat.apply(null, rows);
}
/**
* @inheritDoc
*/
public function createCSVRow(row:Array):String
{
return createCSV([row]);
}
/**
* @inheritDoc
*/
public function parseCSVToken(token:String):String
{
var parsedToken:String = '';
var tokenLength:int = token.length;
if (token.charAt(0) == quote)
{
var escaped:Boolean = true;
for (var i:int = 1; i <= tokenLength; i++)
{
var currentChar:String = token.charAt(i);
var twoChar:String = currentChar + token.charAt(i+1);
if (twoChar == quote+quote) //append escaped quote
{
i += 1;
parsedToken += quote;
}
else if (currentChar == quote && escaped)
{
escaped = false;
}
else
{
parsedToken += currentChar;
}
}
}
else
{
parsedToken = token;
}
return parsedToken;
}
/**
* @inheritDoc
*/
public function createCSVToken(str:String):String
{
if (str == null)
str = '';
// determine if quotes are necessary
if ( str.length > 0
&& str.indexOf(quote) < 0
&& str.indexOf(delimiter) < 0
&& str.indexOf(LF) < 0
&& str.indexOf(CR) < 0
&& str == StringUtil.trim(str) )
{
return str;
}
var token:String = quote;
for (var i:int = 0; i <= str.length; i++)
{
var currentChar:String = str.charAt(i);
if (currentChar == quote)
token += quote + quote;
else
token += currentChar;
}
return token + quote;
}
/**
* @inheritDoc
*/
public function convertRowsToRecords(rows:Array, headerDepth:int = 1):Array
{
if (rows.length < headerDepth)
throw new Error("headerDepth is greater than the number of rows");
assertHeaderDepth(headerDepth);
var records:Array = new Array(rows.length - headerDepth);
for (var r:int = headerDepth; r < rows.length; r++)
{
var record:Object = {};
var row:Array = rows[r];
for (var c:int = 0; c < row.length; c++)
{
var output:Object = record;
var cell:Object = row[c];
for (var h:int = 0; h < headerDepth; h++)
{
var colName:String = rows[h][c];
if (h < headerDepth - 1)
{
if (!output[colName])
output[colName] = {};
output = output[colName];
}
else
output[colName] = cell;
}
}
records[r - headerDepth] = record;
}
return records;
}
/**
* @inheritDoc
*/
public function getRecordFieldNames(records:Array, includeNullFields:Boolean = false, headerDepth:int = 1):Array
{
assertHeaderDepth(headerDepth);
var nestedFieldNames:Object = {};
for each (var record:Object in records)
_outputNestedFieldNames(record, includeNullFields, nestedFieldNames, headerDepth);
var fields:Array = [];
_collapseNestedFieldNames(nestedFieldNames, fields);
return fields;
}
private function _outputNestedFieldNames(record:Object, includeNullFields:Boolean, output:Object, depth:int):void
{
for (var field:String in record)
{
if (includeNullFields || record[field] != null)
{
if (depth == 1)
{
output[field] = false;
}
else
{
if (!output[field])
output[field] = {};
_outputNestedFieldNames(record[field], includeNullFields, output[field], depth - 1);
}
}
}
}
private function _collapseNestedFieldNames(nestedFieldNames:Object, output:Array, prefix:Array = null):void
{
for (var field:String in nestedFieldNames)
{
if (nestedFieldNames[field]) // either an Object or false
{
_collapseNestedFieldNames(nestedFieldNames[field], output, prefix ? prefix.concat(field) : [field]);
}
else // false means reached full nesting depth
{
if (prefix) // is depth > 1?
output.push(prefix.concat(field)); // output the list of nested field names
else
output.push(field); // no array when max depth is 1
}
}
}
/**
* @inheritDoc
*/
public function convertRecordsToRows(records:Array, columnOrder:Array = null, allowBlankColumns:Boolean = false, headerDepth:int = 1):Array
{
assertHeaderDepth(headerDepth);
var fields:Array = columnOrder;
if (fields == null)
{
fields = getRecordFieldNames(records, allowBlankColumns, headerDepth);
AsyncSort.sortImmediately(fields);
}
var r:int;
var c:int;
var cell:Object;
var row:Array;
var rows:Array = new Array(records.length + headerDepth);
// construct multiple header rows from field name chains
for (r = 0; r < headerDepth; r++)
{
row = new Array(fields.length);
for (c = 0; c < fields.length; c++)
{
if (headerDepth > 1)
row[c] = fields[c][r] || ''; // fields are Arrays
else
row[c] = fields[c] || ''; // fields are Strings
}
rows[r] = row;
}
for (r = 0; r < records.length; r++)
{
var record:Object = records[r];
row = new Array(fields.length);
for (c = 0; c < fields.length; c++)
{
if (headerDepth == 1)
{
// fields is an Array of Strings
cell = record[fields[c]];
}
else
{
// fields is an Array of Arrays
cell = record;
for each (var field:String in fields[c])
if (cell)
cell = cell[field];
}
row[c] = cell != null ? String(cell) : '';
}
rows[headerDepth + r] = row;
}
return rows;
}
private static function assertHeaderDepth(headerDepth:int):void
{
if (headerDepth < 1)
throw new Error("headerDepth must be > 0");
}
//test();
private static var _tested:Boolean = false;
private static function test():void
{
if (_tested)
return;
_tested = true;
var _:Object = {};
_.parser = WeaveAPI.CSVParser;
_.csv=[
"internal,internal,public,public,public,private,private,test",
"id,type,title,keyType,dataType,connection,sqlQuery,empty",
"2,1,state name,fips,string,resd,\"select fips,name from myschema.state_data\",",
"3,1,population,fips,number,resd,\"select fips,pop from myschema.state_data\",",
"1,0,state data table"
].join('\n');
_.table = _.parser.parseCSV(_.csv);
_.records = _.parser.convertRowsToRecords(_.table, 2);
_.rows = _.parser.convertRecordsToRows(_.records, null, false, 2);
_.fields = _.parser.getRecordFieldNames(_.records, false, 2);
_.fieldOrder = _.parser.parseCSV('internal,id\ninternal,type\npublic,title\npublic,keyType\npublic,dataType\nprivate,connection\nprivate,sqlQuery');
_.rows2 = _.parser.convertRecordsToRows(_.records, _.fieldOrder, false, 2);
weaveTrace(ObjectUtil.toString(_));
}
}
}
|
Revert "Now using ByteArray in CSVParser.createCSV() for 2x speedup."
|
Revert "Now using ByteArray in CSVParser.createCSV() for 2x speedup."
This reverts commit 721aaba8b1b70953a764dabf3dc743372a206d84.
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
21bf7822410aff226883c2f720428c282661a6cf
|
as3/com/netease/protobuf/messageToString.as
|
as3/com/netease/protobuf/messageToString.as
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved.
//
// [email protected]
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.utils.*;
public function messageToString(message:Object):String {
var s:String = getQualifiedClassName(message) + "(\n"
const descriptor:XML = describeType(message)
for each(var getter:String in descriptor.accessor.(@access != "writeonly").@name) {
if (getter.search(/^has(.)(.*)$/) != -1) {
continue
}
s += fieldToString(message, descriptor, getter)
}
for each(var field:String in descriptor.variable.@name) {
s += fieldToString(message, descriptor, field)
}
for (var k:* in message) {
s += k + "=" + message[k] + ";\n"
}
s += ")"
return s
}
}
function fieldToString(message:Object, descriptor:XML, name:String):String {
var hasField:String = "has" + name.charAt(0).toUpperCase() + name.substr(1)
if (descriptor.accessor.(@name == hasField).length() != 0 && !message[hasField]) {
return ""
}
var field:* = message[name]
if (field.constructor == Array && field.length == 0) {
return ""
}
return name + "=" + message[name] + ";\n"
}
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved.
//
// [email protected]
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.utils.*;
public function messageToString(message:Object):String {
var s:String = getQualifiedClassName(message) + "(\n"
const descriptor:XML = describeType(message)
for each(var getter:String in descriptor.accessor.(@access != "writeonly").@name) {
if (getter.search(/^has(.)(.*)$/) != -1) {
continue
}
s += fieldToString(message, descriptor, getter)
}
for each(var field:String in descriptor.variable.@name) {
s += fieldToString(message, descriptor, field)
}
for (var k:* in message) {
s += k + "=" + message[k] + ";\n"
}
s += ")"
return s
}
}
function fieldToString(message:Object, descriptor:XML, name:String):String {
var hasField:String = "has" + name.charAt(0).toUpperCase() + name.substr(1)
if (descriptor.accessor.(@name == hasField).length() != 0 && !message[hasField]) {
return ""
}
var field:* = message[name]
if (field != null && field.constructor == Array && field.length == 0) {
return ""
}
return name + "=" + field + ";\n"
}
|
修复当某一项为 null 时,toString 出错的 bug
|
修复当某一项为 null 时,toString 出错的 bug
|
ActionScript
|
bsd-2-clause
|
tconkling/protoc-gen-as3
|
a9b986d4884810f259e1f7b7579f0f4207fef811
|
flash/src/lambmei/starling/display/HandleSheet.as
|
flash/src/lambmei/starling/display/HandleSheet.as
|
package lambmei.starling.display
{
import flash.display.MovieClip;
import flash.geom.Point;
import starling.display.Button;
import starling.display.DisplayObject;
import starling.display.DisplayObjectContainer;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.events.TouchPhase;
import starling.textures.Texture;
public class HandleSheet extends Sprite
{
/** 點擊 將物件移動到前方 **/
protected var _touchBringToFront:Boolean
public function get touchBringToFront():Boolean { return _touchBringToFront;}
public function set touchBringToFront(value:Boolean):void{ _touchBringToFront = value; }
/** 是否選擇 **/
protected var _selected:Boolean
public function get selected():Boolean { return _selected;}
public function set selected(value:Boolean):void
{
if(value!=_selected){
_selected = value;
_selectedGroup.visible = _selected
}
}
/** 是否有使用 控制按鈕 Read Only **/
protected var _useCtrlButton:Boolean
public function get useCtrlButton():Boolean
{
return _useCtrlButton;
}
// public function set useCtrlButton(value:Boolean):void
// {
// _useCtrlButton = value;
// }
//Const Vars
protected static const CTRL_BUTTON_NAME:String = "HandlectrlBtn"
public static const ALIGN_CENTER:String = "center"
public static const ALIGN_LT:String = "LT"
//UI
protected var _contents:DisplayObject
protected var _ctrlButton:DisplayObject
protected var _selectedGroup:Sprite
public function HandleSheet(contents:DisplayObject=null)
{
addEventListener(TouchEvent.TOUCH, onTouch);
useHandCursor = true;
_touchBringToFront = true
if (contents)
{
var _w:Number = contents.width
var _h:Number = contents.height
var _halfW:Number = _w/2
var _halfH:Number= _h/2
//將物件置中
contents.x = int(_halfW * -1);
contents.y = int(_halfH * -1);
addChild(contents);
_contents = contents
}
//init SelectGroup
_selectedGroup = new Sprite()
this.addChild(this._selectedGroup);
_selectedGroup.visible = _selected
}
public function setCtrlButtonInitByTexture(upTexture:Texture , downTexture:Texture = null ):void
{
_useCtrlButton = true
if ( upTexture !=null)
{
_ctrlButton = new Button(upTexture,CTRL_BUTTON_NAME,downTexture);
setCtrlButtonInitByObject(_ctrlButton )
}else{
throw new ArgumentError("Texture is Null!")
}
}
/** 設定控制按鈕 by 物件 可以是 image sprite button **/
public function setCtrlButtonInitByObject( obj:DisplayObject ):void
{
_useCtrlButton = true
if (_contents)
{
_ctrlButton = obj
var _w:Number = _contents.width
var _h:Number = _contents.height
var _halfW:Number = _w/2
var _halfH:Number= _h/2
//放置右上角
_ctrlButton.x = int(_halfW)
_ctrlButton.y = - int(_halfH)
//置中對齊
_ctrlButton.x -= int(_ctrlButton.width/2)
_ctrlButton.y -= int(_ctrlButton.height/2)
_selectedGroup.addChild(_ctrlButton)
}
}
protected function onTouch(event:TouchEvent):void
{
var touches:Vector.<Touch> = event.getTouches(this, TouchPhase.MOVED);
var touch:Touch
touch = event.getTouch(this, TouchPhase.BEGAN);
onTouchBegan(touch)
//一隻手指
if (touches.length == 1)
{
//檢查是否是Ctrl
if(isTouchCtrlButton(event.target) )
{
resizeAndRotationByCtrlButton(touches)
}
else
{
//一隻手指平移
var delta:Point = touches[0].getMovement(parent);
x += delta.x;
y += delta.y;
}
}
else if (touches.length == 2)
{
//兩隻手指
resizeAndRotationByTwoFingers(touches)
}
touch = event.getTouch(this, TouchPhase.ENDED);
onTouchEnd(touch)
}
/**當touch開始**/
protected function onTouchBegan(touch:Touch):void
{
//touch 開始要做的事情
if(touch){
if(_touchBringToFront){
parent.addChild(this);
}
selected = true
}
}
/**當touch結束**/
protected function onTouchEnd(touch:Touch):void
{
}
/**檢查是否touch 控制按鈕**/
protected function isTouchCtrlButton(target:*):Boolean
{
var _do :DisplayObject
var _doc :DisplayObjectContainer
if(_ctrlButton is DisplayObjectContainer){
_doc = _ctrlButton as DisplayObjectContainer
return _doc.contains(target)
}
else if(_ctrlButton is DisplayObject)
{
_do = _ctrlButton as DisplayObject
return _do == target
}
return false
}
/** 單隻手指使用控制按鈕 放大縮小旋轉 **/
protected function resizeAndRotationByCtrlButton(touches:Vector.<Touch>):void
{
var touchA:Touch = touches[0];
var touchB:Touch = touchA.clone(); //模擬B點
var n = touchA.getLocation(this);
//鏡射A點坐標
touchB.globalX = n.x * 1
touchB.globalY = n.y * -1
var currentPosA:Point = touchA.getLocation(this);
var previousPosA:Point = touchA.getPreviousLocation(this);
//鏡射A點
var currentPosB:Point = currentPosA.clone();
currentPosB.x *=-1;
currentPosB.y *=-1;
//鏡射A點
var previousPosB:Point = previousPosA.clone();
previousPosB.x *=-1;
previousPosB.y *=-1;
var currentVector:Point = currentPosA.subtract(currentPosB);
var previousVector:Point = previousPosA.subtract(previousPosB);
var currentAngle:Number = Math.atan2(currentVector.y, currentVector.x);
var previousAngle:Number = Math.atan2(previousVector.y, previousVector.x);
var deltaAngle:Number = currentAngle - previousAngle;
// rotate
rotation += deltaAngle;
// scale
var sizeDiff:Number = currentVector.length / previousVector.length;
scaleX *= sizeDiff;
scaleY *= sizeDiff;
//_ctrlButton 保持原比例
if(_ctrlButton){
_ctrlButton.scaleX /= sizeDiff
_ctrlButton.scaleY /= sizeDiff
}
}
/** 使用兩隻手指 使用放大縮小旋轉 保留官方功能 **/
protected function resizeAndRotationByTwoFingers(touches:Vector.<Touch>):void
{
//保留官方原本兩隻手指操作的功能
// two fingers touching -> rotate and scale
var touchA:Touch = touches[0];
var touchB:Touch = touches[1];
var currentPosA:Point = touchA.getLocation(parent);
var previousPosA:Point = touchA.getPreviousLocation(parent);
var currentPosB:Point = touchB.getLocation(parent);
var previousPosB:Point = touchB.getPreviousLocation(parent);
var currentVector:Point = currentPosA.subtract(currentPosB);
var previousVector:Point = previousPosA.subtract(previousPosB);
var currentAngle:Number = Math.atan2(currentVector.y, currentVector.x);
var previousAngle:Number = Math.atan2(previousVector.y, previousVector.x);
var deltaAngle:Number = currentAngle - previousAngle;
// update pivot point based on previous center
var previousLocalA:Point = touchA.getPreviousLocation(this);
var previousLocalB:Point = touchB.getPreviousLocation(this);
trace(previousLocalA , previousLocalB)
pivotX = (previousLocalA.x + previousLocalB.x) * 0.5;
pivotY = (previousLocalA.y + previousLocalB.y) * 0.5;
// update location based on the current center
x = (currentPosA.x + currentPosB.x) * 0.5;
y = (currentPosA.y + currentPosB.y) * 0.5;
// rotate
rotation += deltaAngle;
// scale
var sizeDiff:Number = currentVector.length / previousVector.length;
scaleX *= sizeDiff;
scaleY *= sizeDiff;
}
public override function dispose():void
{
removeEventListener(TouchEvent.TOUCH, onTouch);
if(_contents){
_contents.dispose()
}
super.dispose();
}
}
}
import lambmei.starling.display.HandleSheet;
|
package lambmei.starling.display
{
import flash.display.MovieClip;
import flash.geom.Point;
import flash.system.System;
import starling.display.Button;
import starling.display.DisplayObject;
import starling.display.DisplayObjectContainer;
import starling.display.Shape;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.events.TouchPhase;
import starling.textures.Texture;
import starling.utils.Line;
public class HandleSheet extends Sprite
{
/** 點擊 將物件移動到前方 **/
protected var _touchBringToFront:Boolean
public function get touchBringToFront():Boolean { return _touchBringToFront;}
public function set touchBringToFront(value:Boolean):void{ _touchBringToFront = value; }
/** 是否選擇 **/
protected var _selected:Boolean
public function get selected():Boolean { return _selected;}
public function set selected(value:Boolean):void
{
if(value!=_selected){
_selected = value;
_selectedGroup.visible = _selected
}
}
/** 是否有使用 控制按鈕 Read Only **/
protected var _useCtrlButton:Boolean
public function get useCtrlButton():Boolean
{
return _useCtrlButton;
}
// public function set useCtrlButton(value:Boolean):void
// {
// _useCtrlButton = value;
// }
//Const Vars
protected static const CTRL_BUTTON_NAME:String = "HandlectrlBtn"
public static const ALIGN_CENTER:String = "center"
public static const ALIGN_LT:String = "LT"
//UI
protected var _contents:DisplayObject
protected var _ctrlButton:DisplayObject
protected var _selectedGroup:Sprite
protected var _shape:Shape
public function HandleSheet(contents:DisplayObject=null)
{
addEventListener(TouchEvent.TOUCH, onTouch);
useHandCursor = true;
_touchBringToFront = true
if (contents)
{
var _w:Number = contents.width
var _h:Number = contents.height
var _halfW:Number = _w/2
var _halfH:Number= _h/2
//將物件置中
contents.x = int(_halfW * -1);
contents.y = int(_halfH * -1);
addChild(contents);
_contents = contents
}
//init SelectGroup
initSelectedGroup()
}
/** 初始化選擇的群組**/
protected function initSelectedGroup():void
{
_selectedGroup = new Sprite()
this.addChild(this._selectedGroup);
_shape = new Shape()
updateLine()
_selectedGroup.addChild(_shape)
_selectedGroup.visible = _selected
}
/**重新計算**/
protected function render(scale=1):void
{
updateLine(scale)
}
/**更新框線**/
protected function updateLine(scale=1):void
{
if(_contents && _shape){
_shape.graphics.lineStyle(10,0xFFffFF);
_shape.graphics.clear();
System.gc();
var _w:Number = _contents.width
var _h:Number = _contents.height
var _halfW:Number = _w/2
var _halfH:Number= _h/2
_shape.graphics.lineStyle(2 * scale,0xFFFFFF);
//_shape.graphics.drawRoundRect( -_halfW, -_halfH, _w, _h, 10 );
_shape.graphics.drawRect(-_halfW, -_halfH, _w, _h);
//trace("scale",scale)
}
}
public function setCtrlButtonInitByTexture(upTexture:Texture , downTexture:Texture = null ):void
{
_useCtrlButton = true
if ( upTexture !=null)
{
_ctrlButton = new Button(upTexture,"",downTexture);
setCtrlButtonInitByObject(_ctrlButton )
}else{
throw new ArgumentError("Texture is Null!")
}
}
/** 設定控制按鈕 by 物件 可以是 image sprite button **/
public function setCtrlButtonInitByObject( obj:DisplayObject ):void
{
_useCtrlButton = true
if (_contents)
{
_ctrlButton = obj
var _w:Number = _contents.width
var _h:Number = _contents.height
var _halfW:Number = _w/2
var _halfH:Number= _h/2
//放置右上角
_ctrlButton.x = int(_halfW)
_ctrlButton.y = - int(_halfH)
//置中對齊
_ctrlButton.x -= int(_ctrlButton.width/2)
_ctrlButton.y -= int(_ctrlButton.height/2)
_selectedGroup.addChild(_ctrlButton)
}
}
protected function onTouch(event:TouchEvent):void
{
var touches:Vector.<Touch> = event.getTouches(this, TouchPhase.MOVED);
var touch:Touch
touch = event.getTouch(this, TouchPhase.BEGAN);
onTouchBegan(touch)
//一隻手指
if (touches.length == 1)
{
//檢查是否是Ctrl
if(isTouchCtrlButton(event.target) )
{
resizeAndRotationByCtrlButton(touches)
}
else
{
//一隻手指平移
var delta:Point = touches[0].getMovement(parent);
x += delta.x;
y += delta.y;
}
}
else if (touches.length == 2)
{
//兩隻手指
resizeAndRotationByTwoFingers(touches)
}
touch = event.getTouch(this, TouchPhase.ENDED);
onTouchEnd(touch)
}
/**當touch開始**/
protected function onTouchBegan(touch:Touch):void
{
//touch 開始要做的事情
if(touch){
if(_touchBringToFront){
parent.addChild(this);
}
selected = true
}
}
/**當touch結束**/
protected function onTouchEnd(touch:Touch):void
{
}
/**檢查是否touch 控制按鈕**/
protected function isTouchCtrlButton(target:*):Boolean
{
var _do :DisplayObject
var _doc :DisplayObjectContainer
if(_ctrlButton is DisplayObjectContainer){
_doc = _ctrlButton as DisplayObjectContainer
return _doc.contains(target)
}
else if(_ctrlButton is DisplayObject)
{
_do = _ctrlButton as DisplayObject
return _do == target
}
return false
}
/** 單隻手指使用控制按鈕 放大縮小旋轉 **/
protected function resizeAndRotationByCtrlButton(touches:Vector.<Touch>):void
{
var touchA:Touch = touches[0];
var touchB:Touch = touchA.clone(); //模擬B點
var n:Point = touchA.getLocation(this);
//鏡射A點坐標
touchB.globalX = n.x * 1
touchB.globalY = n.y * -1
var currentPosA:Point = touchA.getLocation(this);
var previousPosA:Point = touchA.getPreviousLocation(this);
//鏡射A點
var currentPosB:Point = currentPosA.clone();
currentPosB.x *=-1;
currentPosB.y *=-1;
//鏡射A點
var previousPosB:Point = previousPosA.clone();
previousPosB.x *=-1;
previousPosB.y *=-1;
var currentVector:Point = currentPosA.subtract(currentPosB);
var previousVector:Point = previousPosA.subtract(previousPosB);
var currentAngle:Number = Math.atan2(currentVector.y, currentVector.x);
var previousAngle:Number = Math.atan2(previousVector.y, previousVector.x);
var deltaAngle:Number = currentAngle - previousAngle;
// rotate
rotation += deltaAngle;
// scale
var sizeDiff:Number = currentVector.length / previousVector.length;
scaleX *= sizeDiff;
scaleY *= sizeDiff;
//_ctrlButton 保持原比例
if(_ctrlButton){
_ctrlButton.scaleX /= sizeDiff
_ctrlButton.scaleY /= sizeDiff
}
render(_ctrlButton.scaleX)
}
/** 使用兩隻手指 使用放大縮小旋轉 保留官方功能 **/
protected function resizeAndRotationByTwoFingers(touches:Vector.<Touch>):void
{
//保留官方原本兩隻手指操作的功能
// two fingers touching -> rotate and scale
var touchA:Touch = touches[0];
var touchB:Touch = touches[1];
var currentPosA:Point = touchA.getLocation(parent);
var previousPosA:Point = touchA.getPreviousLocation(parent);
var currentPosB:Point = touchB.getLocation(parent);
var previousPosB:Point = touchB.getPreviousLocation(parent);
var currentVector:Point = currentPosA.subtract(currentPosB);
var previousVector:Point = previousPosA.subtract(previousPosB);
var currentAngle:Number = Math.atan2(currentVector.y, currentVector.x);
var previousAngle:Number = Math.atan2(previousVector.y, previousVector.x);
var deltaAngle:Number = currentAngle - previousAngle;
// update pivot point based on previous center
var previousLocalA:Point = touchA.getPreviousLocation(this);
var previousLocalB:Point = touchB.getPreviousLocation(this);
trace(previousLocalA , previousLocalB)
pivotX = (previousLocalA.x + previousLocalB.x) * 0.5;
pivotY = (previousLocalA.y + previousLocalB.y) * 0.5;
// update location based on the current center
x = (currentPosA.x + currentPosB.x) * 0.5;
y = (currentPosA.y + currentPosB.y) * 0.5;
// rotate
rotation += deltaAngle;
// scale
var sizeDiff:Number = currentVector.length / previousVector.length;
scaleX *= sizeDiff;
scaleY *= sizeDiff;
render(_ctrlButton.scaleX)
}
public override function dispose():void
{
removeEventListener(TouchEvent.TOUCH, onTouch);
if(_contents){
_contents.dispose()
}
super.dispose();
}
}
}
|
add 外框線
|
add 外框線
|
ActionScript
|
mit
|
lamb-mei/HandleSheet
|
308fee1f437ecf0b8812dce4f4cddfa06ff40954
|
src/model/ImportDataProxy.as
|
src/model/ImportDataProxy.as
|
package model
{
import dragonBones.Armature;
import dragonBones.Bone;
import dragonBones.animation.WorldClock;
import dragonBones.events.AnimationEvent;
import dragonBones.factorys.BaseFactory;
import dragonBones.objects.BoneData;
import dragonBones.objects.SkeletonData;
import dragonBones.objects.XMLDataParser;
import dragonBones.textures.NativeTextureAtlas;
import dragonBones.utils.ConstValues;
import dragonBones.utils.dragonBones_internal;
import flash.errors.IllegalOperationError;
import flash.utils.ByteArray;
import message.MessageDispatcher;
import mx.collections.XMLListCollection;
import utils.GlobalConstValues;
import utils.TextureUtil;
import utils.movePivotToSkeleton;
use namespace dragonBones_internal;
[Bindable]
/**
* Manage imported data
*/
public class ImportDataProxy
{
private static var _instance:ImportDataProxy
public static function getInstance():ImportDataProxy
{
if(!_instance)
{
_instance = new ImportDataProxy();
}
return _instance;
}
public static function getElementByName(xmlList:XMLList, name:String = null, returnFirst:Boolean = false):XML
{
if(xmlList)
{
if(name)
{
return XMLDataParser.getElementsByAttribute(xmlList, ConstValues.A_NAME, name)[0];
}
if(returnFirst)
{
return xmlList[0];
}
}
return null;
}
public var armaturesMC:XMLListCollection;
public var isTextureChanged:Boolean;
public var isExportedSource:Boolean;
private var _armaturesXMLList:XMLList;
private var _animationsXMLList:XMLList;
private var _baseFactory:BaseFactory;
public function get skeletonName():String
{
return _skeletonXML?_skeletonXML.attribute(ConstValues.A_NAME):"";
}
public function get frameRate():int
{
return int(_skeletonXML.attribute(ConstValues.A_FRAME_RATE));
}
private var _skeletonXML:XML;
public function get skeletonXML():XML
{
return _skeletonXML;
}
private var _textureAtlasXML:XML;
public function get textureAtlasXML():XML
{
return _textureAtlasXML;
}
private var _armatureDataProxy:ArmatureDataProxy;
public function get armatureDataProxy():ArmatureDataProxy
{
return _armatureDataProxy;
}
private var _animationDataProxy:AnimationDataProxy;
public function get animationDataProxy():AnimationDataProxy
{
return _animationDataProxy;
}
private var _skeletonData:SkeletonData;
public function get skeletonData():SkeletonData
{
return _skeletonData;
}
private function set skeletonData(value:SkeletonData)
{
_skeletonData = value;
}
private var _textureAtlas:NativeTextureAtlas;
public function get textureAtlas():NativeTextureAtlas
{
return _textureAtlas;
}
public var textureBytes:ByteArray;
private var _armature:Armature;
public function get armature():Armature
{
return _armature;
}
public function ImportDataProxy()
{
if (_instance)
{
throw new IllegalOperationError("Singleton already constructed!");
}
armaturesMC = new XMLListCollection();
_armatureDataProxy = new ArmatureDataProxy();
_animationDataProxy = new AnimationDataProxy();
_baseFactory = new BaseFactory();
}
public function setData(skeletonXML:XML, textureAtlasXML:XML, textureData:Object, textureBytes:ByteArray, isExportedSource:Boolean):void
{
disposeArmature();
if(_skeletonData)
{
_baseFactory.removeSkeletonData(_skeletonData.name);
_skeletonData.dispose();
}
if(_textureAtlas)
{
_baseFactory.removeTextureAtlas(_textureAtlas.name);
_textureAtlas.dispose();
}
isTextureChanged = false;
_skeletonXML = skeletonXML;
_textureAtlasXML = textureAtlasXML;
this.textureBytes = textureBytes;
this.isExportedSource = isExportedSource;
movePivotToSkeleton(_skeletonXML, _textureAtlasXML);
_armaturesXMLList = _skeletonXML.elements(ConstValues.ARMATURES).elements(ConstValues.ARMATURE);
_animationsXMLList = _skeletonXML.elements(ConstValues.ANIMATIONS).elements(ConstValues.ANIMATION);
armaturesMC.source = _armaturesXMLList;
skeletonData = XMLDataParser.parseSkeletonData(skeletonXML);
_textureAtlas = new NativeTextureAtlas(textureData, textureAtlasXML)
_textureAtlas.movieClipToBitmapData();
_baseFactory.addSkeletonData(_skeletonData);
_baseFactory.addTextureAtlas(_textureAtlas);
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_IMPORT_DATA, skeletonName);
armatureDataProxy.setData(getArmatureXMLByName());
}
public function changeRenderArmature(armatureName:String):void
{
disposeArmature();
_armature = _baseFactory.buildArmature(armatureName);
_armature.addEventListener(dragonBones.events.AnimationEvent.MOVEMENT_CHANGE, armatureEventHandler);
_armature.addEventListener(dragonBones.events.AnimationEvent.START, armatureEventHandler);
_armature.addEventListener(dragonBones.events.AnimationEvent.COMPLETE, armatureEventHandler);
WorldClock.clock.add(_armature);
}
public function render():void
{
WorldClock.update();
}
public function updateTextures():void
{
if(isExportedSource || !skeletonName)
{
return;
}
TextureUtil.packTextures(SettingDataProxy.getInstance().textureMaxWidth, SettingDataProxy.getInstance().texturePadding, textureAtlasXML);
JSFLProxy.getInstance().packTextures(textureAtlasXML);
isTextureChanged = true;
}
public function getArmatureXMLByName(name:String = null):XML
{
return getElementByName(_armaturesXMLList, name, true);
}
public function getAnimationXMLByName(name:String = null):XML
{
return getElementByName(_animationsXMLList, name, true);
}
public function updateArmatureBoneOrigin(boneName:String):void
{
var armatureName:String = armatureDataProxy.armatureName;
updateOrigin(_armature, armatureName, boneName);
}
private function armatureEventHandler(e:AnimationEvent):void
{
switch(e.type)
{
case dragonBones.events.AnimationEvent.MOVEMENT_CHANGE:
MessageDispatcher.dispatchEvent(MessageDispatcher.MOVEMENT_CHANGE, e.movementID);
break;
case dragonBones.events.AnimationEvent.START:
MessageDispatcher.dispatchEvent(MessageDispatcher.MOVEMENT_START, e.movementID);
break;
case dragonBones.events.AnimationEvent.COMPLETE:
MessageDispatcher.dispatchEvent(MessageDispatcher.MOVEMENT_COMPLETE, e.movementID);
break;
}
}
private function updateOrigin(armature:Armature, armatureName:String, boneName:String):void
{
if(armature)
{
if(armature.name == armatureName)
{
var boneData:BoneData = _skeletonData.getArmatureData(armatureName).getBoneData(boneName);
var bone:Bone = armature.getBone(boneName);
bone._origin.copy(boneData);
armature.addBone(bone, boneData.parent);
}
for each(bone in armature._boneDepthList)
{
updateOrigin(bone.childArmature, armatureName, boneName);
}
}
}
private function disposeArmature():void
{
if(_armature)
{
WorldClock.clock.remove(_armature);
_armature.removeEventListener(dragonBones.events.AnimationEvent.MOVEMENT_CHANGE, armatureEventHandler);
_armature.removeEventListener(dragonBones.events.AnimationEvent.START, armatureEventHandler);
_armature.removeEventListener(dragonBones.events.AnimationEvent.COMPLETE, armatureEventHandler);
_armature.dispose();
}
_armature = null;
}
}
}
|
package model
{
import dragonBones.Armature;
import dragonBones.Bone;
import dragonBones.animation.WorldClock;
import dragonBones.events.AnimationEvent;
import dragonBones.factorys.BaseFactory;
import dragonBones.objects.BoneData;
import dragonBones.objects.SkeletonData;
import dragonBones.objects.XMLDataParser;
import dragonBones.textures.NativeTextureAtlas;
import dragonBones.utils.ConstValues;
import dragonBones.utils.dragonBones_internal;
import flash.errors.IllegalOperationError;
import flash.utils.ByteArray;
import message.MessageDispatcher;
import mx.collections.XMLListCollection;
import utils.GlobalConstValues;
import utils.TextureUtil;
import utils.movePivotToSkeleton;
use namespace dragonBones_internal;
[Bindable]
/**
* Manage imported data
*/
public class ImportDataProxy
{
private static var _instance:ImportDataProxy
public static function getInstance():ImportDataProxy
{
if(!_instance)
{
_instance = new ImportDataProxy();
}
return _instance;
}
public static function getElementByName(xmlList:XMLList, name:String = null, returnFirst:Boolean = false):XML
{
if(xmlList)
{
if(name)
{
return XMLDataParser.getElementsByAttribute(xmlList, ConstValues.A_NAME, name)[0];
}
if(returnFirst)
{
return xmlList[0];
}
}
return null;
}
public var armaturesMC:XMLListCollection;
public var isTextureChanged:Boolean;
public var isExportedSource:Boolean;
private var _armaturesXMLList:XMLList;
private var _animationsXMLList:XMLList;
private var _baseFactory:BaseFactory;
public function get skeletonName():String
{
return _skeletonXML?_skeletonXML.attribute(ConstValues.A_NAME):"";
}
public function get frameRate():int
{
return int(_skeletonXML.attribute(ConstValues.A_FRAME_RATE));
}
private var _skeletonXML:XML;
public function get skeletonXML():XML
{
return _skeletonXML;
}
private var _textureAtlasXML:XML;
public function get textureAtlasXML():XML
{
return _textureAtlasXML;
}
private var _armatureDataProxy:ArmatureDataProxy;
public function get armatureDataProxy():ArmatureDataProxy
{
return _armatureDataProxy;
}
private var _animationDataProxy:AnimationDataProxy;
public function get animationDataProxy():AnimationDataProxy
{
return _animationDataProxy;
}
private var _skeletonData:SkeletonData;
public function get skeletonData():SkeletonData
{
return _skeletonData;
}
private function set skeletonData(value:SkeletonData):void
{
_skeletonData = value;
}
private var _textureAtlas:NativeTextureAtlas;
public function get textureAtlas():NativeTextureAtlas
{
return _textureAtlas;
}
public var textureBytes:ByteArray;
private var _armature:Armature;
public function get armature():Armature
{
return _armature;
}
public function ImportDataProxy()
{
if (_instance)
{
throw new IllegalOperationError("Singleton already constructed!");
}
armaturesMC = new XMLListCollection();
_armatureDataProxy = new ArmatureDataProxy();
_animationDataProxy = new AnimationDataProxy();
_baseFactory = new BaseFactory();
}
public function setData(skeletonXML:XML, textureAtlasXML:XML, textureData:Object, textureBytes:ByteArray, isExportedSource:Boolean):void
{
disposeArmature();
if(_skeletonData)
{
_baseFactory.removeSkeletonData(_skeletonData.name);
_skeletonData.dispose();
}
if(_textureAtlas)
{
_baseFactory.removeTextureAtlas(_textureAtlas.name);
_textureAtlas.dispose();
}
isTextureChanged = false;
_skeletonXML = skeletonXML;
_textureAtlasXML = textureAtlasXML;
this.textureBytes = textureBytes;
this.isExportedSource = isExportedSource;
movePivotToSkeleton(_skeletonXML, _textureAtlasXML);
_armaturesXMLList = _skeletonXML.elements(ConstValues.ARMATURES).elements(ConstValues.ARMATURE);
_animationsXMLList = _skeletonXML.elements(ConstValues.ANIMATIONS).elements(ConstValues.ANIMATION);
armaturesMC.source = _armaturesXMLList;
skeletonData = XMLDataParser.parseSkeletonData(skeletonXML);
_textureAtlas = new NativeTextureAtlas(textureData, textureAtlasXML)
_textureAtlas.movieClipToBitmapData();
_baseFactory.addSkeletonData(_skeletonData);
_baseFactory.addTextureAtlas(_textureAtlas);
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_IMPORT_DATA, skeletonName);
armatureDataProxy.setData(getArmatureXMLByName());
}
public function changeRenderArmature(armatureName:String):void
{
disposeArmature();
_armature = _baseFactory.buildArmature(armatureName);
_armature.addEventListener(dragonBones.events.AnimationEvent.MOVEMENT_CHANGE, armatureEventHandler);
_armature.addEventListener(dragonBones.events.AnimationEvent.START, armatureEventHandler);
_armature.addEventListener(dragonBones.events.AnimationEvent.COMPLETE, armatureEventHandler);
WorldClock.clock.add(_armature);
}
public function render():void
{
WorldClock.update();
}
public function updateTextures():void
{
if(isExportedSource || !skeletonName)
{
return;
}
TextureUtil.packTextures(SettingDataProxy.getInstance().textureMaxWidth, SettingDataProxy.getInstance().texturePadding, textureAtlasXML);
JSFLProxy.getInstance().packTextures(textureAtlasXML);
isTextureChanged = true;
}
public function getArmatureXMLByName(name:String = null):XML
{
return getElementByName(_armaturesXMLList, name, true);
}
public function getAnimationXMLByName(name:String = null):XML
{
return getElementByName(_animationsXMLList, name, true);
}
public function updateArmatureBoneOrigin(boneName:String):void
{
var armatureName:String = armatureDataProxy.armatureName;
updateOrigin(_armature, armatureName, boneName);
}
private function armatureEventHandler(e:AnimationEvent):void
{
switch(e.type)
{
case dragonBones.events.AnimationEvent.MOVEMENT_CHANGE:
MessageDispatcher.dispatchEvent(MessageDispatcher.MOVEMENT_CHANGE, e.movementID);
break;
case dragonBones.events.AnimationEvent.START:
MessageDispatcher.dispatchEvent(MessageDispatcher.MOVEMENT_START, e.movementID);
break;
case dragonBones.events.AnimationEvent.COMPLETE:
MessageDispatcher.dispatchEvent(MessageDispatcher.MOVEMENT_COMPLETE, e.movementID);
break;
}
}
private function updateOrigin(armature:Armature, armatureName:String, boneName:String):void
{
if(armature)
{
if(armature.name == armatureName)
{
var boneData:BoneData = _skeletonData.getArmatureData(armatureName).getBoneData(boneName);
var bone:Bone = armature.getBone(boneName);
bone._origin.copy(boneData);
armature.addBone(bone, boneData.parent);
}
for each(bone in armature._boneDepthList)
{
updateOrigin(bone.childArmature, armatureName, boneName);
}
}
}
private function disposeArmature():void
{
if(_armature)
{
WorldClock.clock.remove(_armature);
_armature.removeEventListener(dragonBones.events.AnimationEvent.MOVEMENT_CHANGE, armatureEventHandler);
_armature.removeEventListener(dragonBones.events.AnimationEvent.START, armatureEventHandler);
_armature.removeEventListener(dragonBones.events.AnimationEvent.COMPLETE, armatureEventHandler);
_armature.dispose();
}
_armature = null;
}
}
}
|
declare function return value type
|
declare function return value type
|
ActionScript
|
mit
|
DragonBones/DesignPanel
|
56ddb2310c1ac988a54735050d65f3fe89aa1203
|
src/org/mangui/chromeless/ChromelessPlayer.as
|
src/org/mangui/chromeless/ChromelessPlayer.as
|
package org.mangui.chromeless {
import flash.net.URLStream;
import org.mangui.HLS.parsing.Level;
import org.mangui.HLS.*;
import org.mangui.HLS.utils.*;
import flash.display.*;
import flash.events.*;
import flash.external.ExternalInterface;
import flash.geom.Rectangle;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.media.StageVideo;
import flash.media.StageVideoAvailability;
import flash.utils.setTimeout;
public class ChromelessPlayer extends Sprite {
/** reference to the framework. **/
private var _hls : HLS;
/** Sheet to place on top of the video. **/
private var _sheet : Sprite;
/** Reference to the stage video element. **/
private var _stageVideo : StageVideo = null;
/** Reference to the video element. **/
private var _video : Video = null;
/** Video size **/
private var _videoWidth : Number = 0;
private var _videoHeight : Number = 0;
/** current media position */
private var _media_position : Number;
/** Initialization. **/
public function ChromelessPlayer() : void {
// Set stage properties
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState);
stage.addEventListener(Event.RESIZE, _onStageResize);
// Draw sheet for catching clicks
_sheet = new Sprite();
_sheet.graphics.beginFill(0x000000, 0);
_sheet.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
_sheet.addEventListener(MouseEvent.CLICK, _clickHandler);
_sheet.buttonMode = true;
addChild(_sheet);
// Connect getters to JS.
ExternalInterface.addCallback("getLevel", _getLevel);
ExternalInterface.addCallback("getLevels", _getLevels);
ExternalInterface.addCallback("getMetrics", _getMetrics);
ExternalInterface.addCallback("getPosition", _getPosition);
ExternalInterface.addCallback("getState", _getState);
ExternalInterface.addCallback("getType", _getType);
ExternalInterface.addCallback("getmaxBufferLength", _getmaxBufferLength);
ExternalInterface.addCallback("getminBufferLength", _getminBufferLength);
ExternalInterface.addCallback("getbufferLength", _getbufferLength);
ExternalInterface.addCallback("getLogDebug", _getLogDebug);
ExternalInterface.addCallback("getLogDebug2", _getLogDebug2);
ExternalInterface.addCallback("getflushLiveURLCache", _getflushLiveURLCache);
ExternalInterface.addCallback("getstartFromLowestLevel", _getstartFromLowestLevel);
ExternalInterface.addCallback("getseekFromLowestLevel", _getseekFromLowestLevel);
ExternalInterface.addCallback("getJSURLStream", _getJSURLStream);
ExternalInterface.addCallback("getPlayerVersion", _getPlayerVersion);
ExternalInterface.addCallback("getAudioTrackList", _getAudioTrackList);
ExternalInterface.addCallback("getAudioTrackId", _getAudioTrackId);
// Connect calls to JS.
ExternalInterface.addCallback("playerLoad", _load);
ExternalInterface.addCallback("playerPlay", _play);
ExternalInterface.addCallback("playerPause", _pause);
ExternalInterface.addCallback("playerResume", _resume);
ExternalInterface.addCallback("playerSeek", _seek);
ExternalInterface.addCallback("playerStop", _stop);
ExternalInterface.addCallback("playerVolume", _volume);
ExternalInterface.addCallback("playerSetLevel", _setLevel);
ExternalInterface.addCallback("playerSetmaxBufferLength", _setmaxBufferLength);
ExternalInterface.addCallback("playerSetminBufferLength", _setminBufferLength);
ExternalInterface.addCallback("playerSetflushLiveURLCache", _setflushLiveURLCache);
ExternalInterface.addCallback("playerSetstartFromLowestLevel", _setstartFromLowestLevel);
ExternalInterface.addCallback("playerSetseekFromLowestLevel", _setseekFromLowestLevel);
ExternalInterface.addCallback("playerSetLogDebug", _setLogDebug);
ExternalInterface.addCallback("playerSetLogDebug2", _setLogDebug2);
ExternalInterface.addCallback("playerSetAudioTrack", _setAudioTrack);
ExternalInterface.addCallback("playerSetJSURLStream", _setJSURLStream);
setTimeout(_pingJavascript, 50);
};
/** Notify javascript the framework is ready. **/
private function _pingJavascript() : void {
ExternalInterface.call("onHLSReady", ExternalInterface.objectID);
};
/** Forward events from the framework. **/
private function _completeHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onComplete");
}
};
private function _errorHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onError", event.message);
}
};
private function _fragmentHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onFragment", event.metrics.bandwidth, event.metrics.level, stage.stageWidth);
}
};
private function _manifestHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onManifest", event.levels[0].duration);
}
};
private function _mediaTimeHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
_media_position = event.mediatime.position;
ExternalInterface.call("onPosition", event.mediatime.position, event.mediatime.duration, event.mediatime.live_sliding);
}
var videoWidth : Number = _video ? _video.videoWidth : _stageVideo.videoWidth;
var videoHeight : Number = _video ? _video.videoHeight : _stageVideo.videoHeight;
if (videoWidth && videoHeight) {
var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight;
if (changed) {
_videoHeight = videoHeight;
_videoWidth = videoWidth;
_resize();
if (ExternalInterface.available) {
ExternalInterface.call("onVideoSize", _videoWidth, _videoHeight);
}
}
}
};
private function _stateHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onState", event.state);
}
};
private function _switchHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onSwitch", event.level);
}
};
private function _audioTracksListChange(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onAudioTracksListChange", _getAudioTrackList());
}
}
private function _audioTrackChange(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onAudioTrackChange", event.audioTrack);
}
}
/** Javascript getters. **/
private function _getLevel() : Number {
return _hls.level;
};
private function _getLevels() : Vector.<Level> {
return _hls.levels;
};
private function _getMetrics() : Object {
return _hls.metrics;
};
private function _getPosition() : Number {
return _hls.position;
};
private function _getState() : String {
return _hls.state;
};
private function _getType() : String {
return _hls.type;
};
private function _getbufferLength() : Number {
return _hls.bufferLength;
};
private function _getmaxBufferLength() : Number {
return _hls.maxBufferLength;
};
private function _getminBufferLength() : Number {
return _hls.minBufferLength;
};
private function _getflushLiveURLCache() : Boolean {
return _hls.flushLiveURLCache;
};
private function _getstartFromLowestLevel() : Boolean {
return _hls.startFromLowestLevel;
};
private function _getseekFromLowestLevel() : Boolean {
return _hls.seekFromLowestLevel;
};
private function _getLogDebug() : Boolean {
return Log.LOG_DEBUG_ENABLED;
};
private function _getLogDebug2() : Boolean {
return Log.LOG_DEBUG2_ENABLED;
};
private function _getJSURLStream() : Boolean {
return (_hls.URLstream is JSURLStream);
};
private function _getPlayerVersion() : Number {
return 2;
};
private function _getAudioTrackList() : Array {
var list : Array = [];
var vec : Vector.<HLSAudioTrack> = _hls.audioTracks;
for (var i : Object in vec) {
list.push(vec[i]);
}
return list;
};
private function _getAudioTrackId() : Number {
return _hls.audioTrack;
};
/** Javascript calls. **/
private function _load(url : String) : void {
_hls.load(url);
};
private function _play() : void {
_hls.stream.play();
};
private function _pause() : void {
_hls.stream.pause();
};
private function _resume() : void {
_hls.stream.resume();
};
private function _seek(position : Number) : void {
_hls.stream.seek(position);
};
private function _stop() : void {
_hls.stream.close();
};
private function _volume(percent : Number) : void {
_hls.stream.soundTransform = new SoundTransform(percent / 100);
};
private function _setLevel(level : Number) : void {
_hls.level = level;
if (!isNaN(_media_position)) {
_hls.stream.seek(_media_position);
}
};
private function _setmaxBufferLength(new_len : Number) : void {
_hls.maxBufferLength = new_len;
};
private function _setminBufferLength(new_len : Number) : void {
_hls.minBufferLength = new_len;
};
private function _setflushLiveURLCache(flushLiveURLCache : Boolean) : void {
_hls.flushLiveURLCache = flushLiveURLCache;
};
private function _setstartFromLowestLevel(startFromLowestLevel : Boolean) : void {
_hls.startFromLowestLevel = startFromLowestLevel;
};
private function _setseekFromLowestLevel(seekFromLowestLevel : Boolean) : void {
_hls.seekFromLowestLevel = seekFromLowestLevel;
};
private function _setLogDebug(debug : Boolean) : void {
Log.LOG_DEBUG_ENABLED = debug;
};
private function _setLogDebug2(debug2 : Boolean) : void {
Log.LOG_DEBUG2_ENABLED = debug2;
};
private function _setJSURLStream(jsURLstream : Boolean) : void {
if (jsURLstream) {
_hls.URLstream = JSURLStream as Class;
} else {
_hls.URLstream = URLStream as Class;
}
};
private function _setAudioTrack(val : Number) : void {
if (val == _hls.audioTrack) return;
_hls.audioTrack = val;
if (!isNaN(_media_position)) {
_hls.stream.seek(_media_position);
}
};
/** Mouse click handler. **/
private function _clickHandler(event : MouseEvent) : void {
if (stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE || stage.displayState == StageDisplayState.FULL_SCREEN) {
stage.displayState = StageDisplayState.NORMAL;
} else {
stage.displayState = StageDisplayState.FULL_SCREEN;
}
};
/** StageVideo detector. **/
private function _onStageVideoState(event : StageVideoAvailabilityEvent) : void {
var available : Boolean = (event.availability == StageVideoAvailability.AVAILABLE);
_hls = new HLS();
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler);
_hls.addEventListener(HLSEvent.ERROR, _errorHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler);
_hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler);
_hls.addEventListener(HLSEvent.STATE, _stateHandler);
_hls.addEventListener(HLSEvent.QUALITY_SWITCH, _switchHandler);
_hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTracksListChange);
_hls.addEventListener(HLSEvent.AUDIO_TRACK_CHANGE, _audioTrackChange);
if (available && stage.stageVideos.length > 0) {
_stageVideo = stage.stageVideos[0];
_stageVideo.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
_stageVideo.attachNetStream(_hls.stream);
} else {
_video = new Video(stage.stageWidth, stage.stageHeight);
addChild(_video);
_video.smoothing = true;
_video.attachNetStream(_hls.stream);
}
stage.removeEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState);
};
private function _onStageResize(event : Event) : void {
stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
_sheet.width = stage.stageWidth;
_sheet.height = stage.stageHeight;
_resize();
};
private function _resize() : void {
var rect : Rectangle;
rect = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, stage.stageWidth, stage.stageHeight);
// resize video
if (_video) {
_video.width = rect.width;
_video.height = rect.height;
_video.x = rect.x;
_video.y = rect.y;
} else if (_stageVideo) {
_stageVideo.viewPort = rect;
}
}
}
}
|
package org.mangui.chromeless {
import flash.net.URLStream;
import org.mangui.HLS.parsing.Level;
import org.mangui.HLS.*;
import org.mangui.HLS.utils.*;
import flash.display.*;
import flash.events.*;
import flash.external.ExternalInterface;
import flash.geom.Rectangle;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.media.StageVideo;
import flash.media.StageVideoAvailability;
import flash.utils.setTimeout;
public class ChromelessPlayer extends Sprite {
/** reference to the framework. **/
private var _hls : HLS;
/** Sheet to place on top of the video. **/
private var _sheet : Sprite;
/** Reference to the stage video element. **/
private var _stageVideo : StageVideo = null;
/** Reference to the video element. **/
private var _video : Video = null;
/** Video size **/
private var _videoWidth : Number = 0;
private var _videoHeight : Number = 0;
/** current media position */
private var _media_position : Number;
private var _duration : Number;
/** Initialization. **/
public function ChromelessPlayer() : void {
// Set stage properties
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState);
stage.addEventListener(Event.RESIZE, _onStageResize);
// Draw sheet for catching clicks
_sheet = new Sprite();
_sheet.graphics.beginFill(0x000000, 0);
_sheet.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
_sheet.addEventListener(MouseEvent.CLICK, _clickHandler);
_sheet.buttonMode = true;
addChild(_sheet);
// Connect getters to JS.
ExternalInterface.addCallback("getLevel", _getLevel);
ExternalInterface.addCallback("getLevels", _getLevels);
ExternalInterface.addCallback("getMetrics", _getMetrics);
ExternalInterface.addCallback("getDuration", _getDuration);
ExternalInterface.addCallback("getPosition", _getPosition);
ExternalInterface.addCallback("getState", _getState);
ExternalInterface.addCallback("getType", _getType);
ExternalInterface.addCallback("getmaxBufferLength", _getmaxBufferLength);
ExternalInterface.addCallback("getminBufferLength", _getminBufferLength);
ExternalInterface.addCallback("getbufferLength", _getbufferLength);
ExternalInterface.addCallback("getLogDebug", _getLogDebug);
ExternalInterface.addCallback("getLogDebug2", _getLogDebug2);
ExternalInterface.addCallback("getflushLiveURLCache", _getflushLiveURLCache);
ExternalInterface.addCallback("getstartFromLowestLevel", _getstartFromLowestLevel);
ExternalInterface.addCallback("getseekFromLowestLevel", _getseekFromLowestLevel);
ExternalInterface.addCallback("getJSURLStream", _getJSURLStream);
ExternalInterface.addCallback("getPlayerVersion", _getPlayerVersion);
ExternalInterface.addCallback("getAudioTrackList", _getAudioTrackList);
ExternalInterface.addCallback("getAudioTrackId", _getAudioTrackId);
// Connect calls to JS.
ExternalInterface.addCallback("playerLoad", _load);
ExternalInterface.addCallback("playerPlay", _play);
ExternalInterface.addCallback("playerPause", _pause);
ExternalInterface.addCallback("playerResume", _resume);
ExternalInterface.addCallback("playerSeek", _seek);
ExternalInterface.addCallback("playerStop", _stop);
ExternalInterface.addCallback("playerVolume", _volume);
ExternalInterface.addCallback("playerSetLevel", _setLevel);
ExternalInterface.addCallback("playerSetmaxBufferLength", _setmaxBufferLength);
ExternalInterface.addCallback("playerSetminBufferLength", _setminBufferLength);
ExternalInterface.addCallback("playerSetflushLiveURLCache", _setflushLiveURLCache);
ExternalInterface.addCallback("playerSetstartFromLowestLevel", _setstartFromLowestLevel);
ExternalInterface.addCallback("playerSetseekFromLowestLevel", _setseekFromLowestLevel);
ExternalInterface.addCallback("playerSetLogDebug", _setLogDebug);
ExternalInterface.addCallback("playerSetLogDebug2", _setLogDebug2);
ExternalInterface.addCallback("playerSetAudioTrack", _setAudioTrack);
ExternalInterface.addCallback("playerSetJSURLStream", _setJSURLStream);
setTimeout(_pingJavascript, 50);
};
/** Notify javascript the framework is ready. **/
private function _pingJavascript() : void {
ExternalInterface.call("onHLSReady", ExternalInterface.objectID);
};
/** Forward events from the framework. **/
private function _completeHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onComplete");
}
};
private function _errorHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onError", event.message);
}
};
private function _fragmentHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onFragment", event.metrics.bandwidth, event.metrics.level, stage.stageWidth);
}
};
private function _manifestHandler(event : HLSEvent) : void {
_duration = event.levels[0].duration;
if (ExternalInterface.available) {
ExternalInterface.call("onManifest", event.levels[0].duration);
}
};
private function _mediaTimeHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
_media_position = event.mediatime.position;
ExternalInterface.call("onPosition", event.mediatime.position, event.mediatime.duration, event.mediatime.live_sliding);
}
var videoWidth : Number = _video ? _video.videoWidth : _stageVideo.videoWidth;
var videoHeight : Number = _video ? _video.videoHeight : _stageVideo.videoHeight;
if (videoWidth && videoHeight) {
var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight;
if (changed) {
_videoHeight = videoHeight;
_videoWidth = videoWidth;
_resize();
if (ExternalInterface.available) {
ExternalInterface.call("onVideoSize", _videoWidth, _videoHeight);
}
}
}
};
private function _stateHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onState", event.state);
}
};
private function _switchHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onSwitch", event.level);
}
};
private function _audioTracksListChange(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onAudioTracksListChange", _getAudioTrackList());
}
}
private function _audioTrackChange(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onAudioTrackChange", event.audioTrack);
}
}
/** Javascript getters. **/
private function _getLevel() : Number {
return _hls.level;
};
private function _getLevels() : Vector.<Level> {
return _hls.levels;
};
private function _getMetrics() : Object {
return _hls.metrics;
};
private function _getDuration() : Number {
return _duration;
};
private function _getPosition() : Number {
return _hls.position;
};
private function _getState() : String {
return _hls.state;
};
private function _getType() : String {
return _hls.type;
};
private function _getbufferLength() : Number {
return _hls.bufferLength;
};
private function _getmaxBufferLength() : Number {
return _hls.maxBufferLength;
};
private function _getminBufferLength() : Number {
return _hls.minBufferLength;
};
private function _getflushLiveURLCache() : Boolean {
return _hls.flushLiveURLCache;
};
private function _getstartFromLowestLevel() : Boolean {
return _hls.startFromLowestLevel;
};
private function _getseekFromLowestLevel() : Boolean {
return _hls.seekFromLowestLevel;
};
private function _getLogDebug() : Boolean {
return Log.LOG_DEBUG_ENABLED;
};
private function _getLogDebug2() : Boolean {
return Log.LOG_DEBUG2_ENABLED;
};
private function _getJSURLStream() : Boolean {
return (_hls.URLstream is JSURLStream);
};
private function _getPlayerVersion() : Number {
return 2;
};
private function _getAudioTrackList() : Array {
var list : Array = [];
var vec : Vector.<HLSAudioTrack> = _hls.audioTracks;
for (var i : Object in vec) {
list.push(vec[i]);
}
return list;
};
private function _getAudioTrackId() : Number {
return _hls.audioTrack;
};
/** Javascript calls. **/
private function _load(url : String) : void {
_hls.load(url);
};
private function _play() : void {
_hls.stream.play();
};
private function _pause() : void {
_hls.stream.pause();
};
private function _resume() : void {
_hls.stream.resume();
};
private function _seek(position : Number) : void {
_hls.stream.seek(position);
};
private function _stop() : void {
_hls.stream.close();
};
private function _volume(percent : Number) : void {
_hls.stream.soundTransform = new SoundTransform(percent / 100);
};
private function _setLevel(level : Number) : void {
_hls.level = level;
if (!isNaN(_media_position)) {
_hls.stream.seek(_media_position);
}
};
private function _setmaxBufferLength(new_len : Number) : void {
_hls.maxBufferLength = new_len;
};
private function _setminBufferLength(new_len : Number) : void {
_hls.minBufferLength = new_len;
};
private function _setflushLiveURLCache(flushLiveURLCache : Boolean) : void {
_hls.flushLiveURLCache = flushLiveURLCache;
};
private function _setstartFromLowestLevel(startFromLowestLevel : Boolean) : void {
_hls.startFromLowestLevel = startFromLowestLevel;
};
private function _setseekFromLowestLevel(seekFromLowestLevel : Boolean) : void {
_hls.seekFromLowestLevel = seekFromLowestLevel;
};
private function _setLogDebug(debug : Boolean) : void {
Log.LOG_DEBUG_ENABLED = debug;
};
private function _setLogDebug2(debug2 : Boolean) : void {
Log.LOG_DEBUG2_ENABLED = debug2;
};
private function _setJSURLStream(jsURLstream : Boolean) : void {
if (jsURLstream) {
_hls.URLstream = JSURLStream as Class;
} else {
_hls.URLstream = URLStream as Class;
}
};
private function _setAudioTrack(val : Number) : void {
if (val == _hls.audioTrack) return;
_hls.audioTrack = val;
if (!isNaN(_media_position)) {
_hls.stream.seek(_media_position);
}
};
/** Mouse click handler. **/
private function _clickHandler(event : MouseEvent) : void {
if (stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE || stage.displayState == StageDisplayState.FULL_SCREEN) {
stage.displayState = StageDisplayState.NORMAL;
} else {
stage.displayState = StageDisplayState.FULL_SCREEN;
}
};
/** StageVideo detector. **/
private function _onStageVideoState(event : StageVideoAvailabilityEvent) : void {
var available : Boolean = (event.availability == StageVideoAvailability.AVAILABLE);
_hls = new HLS();
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler);
_hls.addEventListener(HLSEvent.ERROR, _errorHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler);
_hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler);
_hls.addEventListener(HLSEvent.STATE, _stateHandler);
_hls.addEventListener(HLSEvent.QUALITY_SWITCH, _switchHandler);
_hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTracksListChange);
_hls.addEventListener(HLSEvent.AUDIO_TRACK_CHANGE, _audioTrackChange);
if (available && stage.stageVideos.length > 0) {
_stageVideo = stage.stageVideos[0];
_stageVideo.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
_stageVideo.attachNetStream(_hls.stream);
} else {
_video = new Video(stage.stageWidth, stage.stageHeight);
addChild(_video);
_video.smoothing = true;
_video.attachNetStream(_hls.stream);
}
stage.removeEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState);
};
private function _onStageResize(event : Event) : void {
stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
_sheet.width = stage.stageWidth;
_sheet.height = stage.stageHeight;
_resize();
};
private function _resize() : void {
var rect : Rectangle;
rect = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, stage.stageWidth, stage.stageHeight);
// resize video
if (_video) {
_video.width = rect.width;
_video.height = rect.height;
_video.x = rect.x;
_video.y = rect.y;
} else if (_stageVideo) {
_stageVideo.viewPort = rect;
}
}
}
}
|
add getDuration() function to ChromelessPlayer
|
add getDuration() function to ChromelessPlayer
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
dc2cbcf8f779e013f7698c0e860dfb6872d790e4
|
src/as/com/threerings/flex/CursorManager.as
|
src/as/com/threerings/flex/CursorManager.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.InteractiveObject;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.ui.Mouse;
import mx.core.Application;
import mx.managers.SystemManager;
import mx.styles.CSSStyleDeclaration;
import mx.styles.StyleManager;
import com.threerings.util.HashMap;
/**
* A better CursorManager.
*/
public class CursorManager
{
public static const SYSTEM_CURSOR :int = 0;
public static const BUSY_CURSOR :int = 1;
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
/**
* Makes the cursor visible.
* Cursor visibility is not reference-counted.
* A single call to the <code>showCursor()</code> method
* always shows the cursor regardless of how many calls
* to the <code>hideCursor()</code> method were made.
*/
public static function showCursor () :void
{
if (_currentCursorId == SYSTEM_CURSOR) {
Mouse.show();
} else {
_cursorHolder.visible = true;
}
}
/**
* Makes the cursor invisible.
* Cursor visibility is not reference-counted.
* A single call to the <code>hideCursor()</code> method
* always hides the cursor regardless of how many calls
* to the <code>showCursor()</code> method were made.
*/
public static function hideCursor () :void
{
_cursorHolder.visible = false;
Mouse.hide();
}
public static function getCurrentCursorId () :int
{
return _currentCursorId;
}
/**
* Creates a new cursor.
*
* @param cursorClass Class of the cursor to display.
*
* @param xOffset Number that specifies the x offset
* of the cursor, in pixels, relative to the mouse pointer.
* The default value is 0.
*
* @param yOffset Number that specifies the y offset
* of the cursor, in pixels, relative to the mouse pointer.
* The default value is 0.
*
* @return The ID of the cursor.
*/
public static function addCursor (
cursorClass :Class, xOffset :int = 0, yOffset :int = 0) :int
{
var cursorId :int = _nextCursorId++;
var rec :CursorRecord = new CursorRecord(cursorClass);
rec.x = xOffset;
rec.y = yOffset;
_cursors.put(cursorId, rec);
return cursorId;
}
/**
* Set the current cursor.
*/
public static function setCursor (id :int) :void
{
if (id == _currentCursorId) {
return;
}
if (!_initialized) {
// oh, let's set it up
_systemManager = Application.application.systemManager;
// set up the busy cursor
var cursorManagerStyleDeclaration :CSSStyleDeclaration =
StyleManager.getStyleDeclaration("CursorManager");
var busyCursorClass :Class =
cursorManagerStyleDeclaration.getStyle("busyCursor");
_busyCursor = new CursorRecord(busyCursorClass);
// The first time a cursor is requested of the CursorManager,
// create a Sprite to hold the cursor symbol
_cursorHolder = new Sprite();
_cursorHolder.mouseEnabled = false;
_systemManager.cursorChildren.addChild(_cursorHolder);
_initialized = true;
}
// figure out what the new cursor will be like
var rec :CursorRecord;
if (id == BUSY_CURSOR) {
rec = _busyCursor;
} else if (id != SYSTEM_CURSOR) {
rec = (_cursors.get(id) as CursorRecord);
if (rec == null) {
// a bogus id was specified
// TODO: throw an error?
return;
}
}
if (rec != null && (rec.cursor is Class)) {
// go ahead and instantiate the class
try {
var disp :DisplayObject = new (rec.cursor as Class);
rec.cursor = disp;
if (disp is InteractiveObject) {
(disp as InteractiveObject).mouseEnabled = false;
}
} catch (err :Error) {
// this cursor is not usable, bail
return;
}
}
// always remove any custom cursors from the hierarchy
if (_cursorHolder.numChildren > 0) {
_cursorHolder.removeChildAt(0);
}
if (id != SYSTEM_CURSOR) {
Mouse.hide();
var currentCursor :DisplayObject = (rec.cursor as DisplayObject);
_cursorHolder.addChild(currentCursor);
_cursorHolder.x = _systemManager.mouseX + rec.x;
_cursorHolder.y = _systemManager.mouseY + rec.y;
_currentXOffset = rec.x;
_currentYOffset = rec.y;
_systemManager.stage.addEventListener(
MouseEvent.MOUSE_MOVE, mouseMoveHandler);
} else {
_currentXOffset = 0;
_currentYOffset = 0;
_systemManager.stage.removeEventListener(
MouseEvent.MOUSE_MOVE, mouseMoveHandler);
Mouse.show();
}
_currentCursorId = id;
}
/**
* Removes a cursor from the cursor list.
* If the cursor being removed is the currently displayed cursor,
* the CursorManager displays the next cursor in the list, if one exists.
* If the list becomes empty, the CursorManager displays
* the default system cursor.
*
* @param cursorID ID of cursor to remove.
*/
public static function removeCursor (id :int) :void
{
var rec :CursorRecord = (_cursors.remove(id) as CursorRecord);
if (rec != null && id == _currentCursorId) {
setCursor(SYSTEM_CURSOR);
}
}
/**
* Removes all of the cursors from the cursor list
* and restores the system cursor.
*/
public static function removeAllCursors () :void
{
_cursors.clear();
if (_currentCursorId != BUSY_CURSOR) {
setCursor(SYSTEM_CURSOR);
}
}
//--------------------------------------------------------------------------
//
// Class event handlers
//
//--------------------------------------------------------------------------
/**
* @private
*/
private static function mouseMoveHandler (event :MouseEvent) :void
{
_cursorHolder.x = _systemManager.mouseX + _currentXOffset;
_cursorHolder.y = _systemManager.mouseY + _currentYOffset;
var target :Object = event.target;
// Do target test.
if (!_overTextField &&
target is TextField && target.type == TextFieldType.INPUT) {
_overTextField = true;
_showSystemCursor = true;
} else if (_overTextField &&
!(target is TextField && target.type == TextFieldType.INPUT)) {
_overTextField = false;
_showCustomCursor = true;
}
// Handle switching between system and custom cursor.
if (_showSystemCursor) {
_showSystemCursor = false;
_cursorHolder.visible = false;
Mouse.show();
}
if (_showCustomCursor) {
_showCustomCursor = false;
_cursorHolder.visible = true;
Mouse.hide();
}
}
/** A mapping of all assigned cursor ids. */
private static const _cursors :HashMap = new HashMap();
private static var _currentCursorId :int = 0; // SYSTEM_CURSOR
private static var _nextCursorId :int = 2; // skip BUSY
private static var _initialized :Boolean = false;
private static var _cursorHolder :Sprite;
private static var _currentXOffset :int = 0;
private static var _currentYOffset :int = 0;
/** A record for the busy cursor (where it can't be removed). */
private static var _busyCursor :CursorRecord;
private static var _overTextField :Boolean = false;
private static var _overLink :Boolean = false;
private static var _showSystemCursor :Boolean = false;
private static var _showCustomCursor :Boolean = false;
private static var _systemManager :SystemManager = null;
}
}
/**
*/
class CursorRecord extends Object
{
public function CursorRecord (clazz :Class)
{
cursor = clazz;
}
/** The class, or instantiated cursor. */
public var cursor :Object
/** The x/y offset for the hotspot. */
public var x :Number;
public var y :Number;
}
|
//
// $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.InteractiveObject;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.ui.Mouse;
import mx.core.Application;
import mx.managers.SystemManager;
import mx.styles.CSSStyleDeclaration;
import mx.styles.StyleManager;
import com.threerings.util.Map;
import com.threerings.util.Maps;
/**
* A better CursorManager.
*/
public class CursorManager
{
public static const SYSTEM_CURSOR :int = 0;
public static const BUSY_CURSOR :int = 1;
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
/**
* Makes the cursor visible.
* Cursor visibility is not reference-counted.
* A single call to the <code>showCursor()</code> method
* always shows the cursor regardless of how many calls
* to the <code>hideCursor()</code> method were made.
*/
public static function showCursor () :void
{
if (_currentCursorId == SYSTEM_CURSOR) {
Mouse.show();
} else {
_cursorHolder.visible = true;
}
}
/**
* Makes the cursor invisible.
* Cursor visibility is not reference-counted.
* A single call to the <code>hideCursor()</code> method
* always hides the cursor regardless of how many calls
* to the <code>showCursor()</code> method were made.
*/
public static function hideCursor () :void
{
_cursorHolder.visible = false;
Mouse.hide();
}
public static function getCurrentCursorId () :int
{
return _currentCursorId;
}
/**
* Creates a new cursor.
*
* @param cursorClass Class of the cursor to display.
*
* @param xOffset Number that specifies the x offset
* of the cursor, in pixels, relative to the mouse pointer.
* The default value is 0.
*
* @param yOffset Number that specifies the y offset
* of the cursor, in pixels, relative to the mouse pointer.
* The default value is 0.
*
* @return The ID of the cursor.
*/
public static function addCursor (
cursorClass :Class, xOffset :int = 0, yOffset :int = 0) :int
{
var cursorId :int = _nextCursorId++;
var rec :CursorRecord = new CursorRecord(cursorClass);
rec.x = xOffset;
rec.y = yOffset;
_cursors.put(cursorId, rec);
return cursorId;
}
/**
* Set the current cursor.
*/
public static function setCursor (id :int) :void
{
if (id == _currentCursorId) {
return;
}
if (!_initialized) {
// oh, let's set it up
_systemManager = Application.application.systemManager;
// set up the busy cursor
var cursorManagerStyleDeclaration :CSSStyleDeclaration =
StyleManager.getStyleDeclaration("CursorManager");
var busyCursorClass :Class =
cursorManagerStyleDeclaration.getStyle("busyCursor");
_busyCursor = new CursorRecord(busyCursorClass);
// The first time a cursor is requested of the CursorManager,
// create a Sprite to hold the cursor symbol
_cursorHolder = new Sprite();
_cursorHolder.mouseEnabled = false;
_systemManager.cursorChildren.addChild(_cursorHolder);
_initialized = true;
}
// figure out what the new cursor will be like
var rec :CursorRecord;
if (id == BUSY_CURSOR) {
rec = _busyCursor;
} else if (id != SYSTEM_CURSOR) {
rec = (_cursors.get(id) as CursorRecord);
if (rec == null) {
// a bogus id was specified
// TODO: throw an error?
return;
}
}
if (rec != null && (rec.cursor is Class)) {
// go ahead and instantiate the class
try {
var disp :DisplayObject = new (rec.cursor as Class);
rec.cursor = disp;
if (disp is InteractiveObject) {
(disp as InteractiveObject).mouseEnabled = false;
}
} catch (err :Error) {
// this cursor is not usable, bail
return;
}
}
// always remove any custom cursors from the hierarchy
if (_cursorHolder.numChildren > 0) {
_cursorHolder.removeChildAt(0);
}
if (id != SYSTEM_CURSOR) {
Mouse.hide();
var currentCursor :DisplayObject = (rec.cursor as DisplayObject);
_cursorHolder.addChild(currentCursor);
_cursorHolder.x = _systemManager.mouseX + rec.x;
_cursorHolder.y = _systemManager.mouseY + rec.y;
_currentXOffset = rec.x;
_currentYOffset = rec.y;
_systemManager.stage.addEventListener(
MouseEvent.MOUSE_MOVE, mouseMoveHandler);
} else {
_currentXOffset = 0;
_currentYOffset = 0;
_systemManager.stage.removeEventListener(
MouseEvent.MOUSE_MOVE, mouseMoveHandler);
Mouse.show();
}
_currentCursorId = id;
}
/**
* Removes a cursor from the cursor list.
* If the cursor being removed is the currently displayed cursor,
* the CursorManager displays the next cursor in the list, if one exists.
* If the list becomes empty, the CursorManager displays
* the default system cursor.
*
* @param cursorID ID of cursor to remove.
*/
public static function removeCursor (id :int) :void
{
var rec :CursorRecord = (_cursors.remove(id) as CursorRecord);
if (rec != null && id == _currentCursorId) {
setCursor(SYSTEM_CURSOR);
}
}
/**
* Removes all of the cursors from the cursor list
* and restores the system cursor.
*/
public static function removeAllCursors () :void
{
_cursors.clear();
if (_currentCursorId != BUSY_CURSOR) {
setCursor(SYSTEM_CURSOR);
}
}
//--------------------------------------------------------------------------
//
// Class event handlers
//
//--------------------------------------------------------------------------
/**
* @private
*/
private static function mouseMoveHandler (event :MouseEvent) :void
{
_cursorHolder.x = _systemManager.mouseX + _currentXOffset;
_cursorHolder.y = _systemManager.mouseY + _currentYOffset;
var target :Object = event.target;
// Do target test.
if (!_overTextField &&
target is TextField && target.type == TextFieldType.INPUT) {
_overTextField = true;
_showSystemCursor = true;
} else if (_overTextField &&
!(target is TextField && target.type == TextFieldType.INPUT)) {
_overTextField = false;
_showCustomCursor = true;
}
// Handle switching between system and custom cursor.
if (_showSystemCursor) {
_showSystemCursor = false;
_cursorHolder.visible = false;
Mouse.show();
}
if (_showCustomCursor) {
_showCustomCursor = false;
_cursorHolder.visible = true;
Mouse.hide();
}
}
/** A mapping of all assigned cursor ids. */
private static const _cursors :Map = Maps.newMapOf(int);
private static var _currentCursorId :int = 0; // SYSTEM_CURSOR
private static var _nextCursorId :int = 2; // skip BUSY
private static var _initialized :Boolean = false;
private static var _cursorHolder :Sprite;
private static var _currentXOffset :int = 0;
private static var _currentYOffset :int = 0;
/** A record for the busy cursor (where it can't be removed). */
private static var _busyCursor :CursorRecord;
private static var _overTextField :Boolean = false;
private static var _overLink :Boolean = false;
private static var _showSystemCursor :Boolean = false;
private static var _showCustomCursor :Boolean = false;
private static var _systemManager :SystemManager = null;
}
}
/**
*/
class CursorRecord extends Object
{
public function CursorRecord (clazz :Class)
{
cursor = clazz;
}
/** The class, or instantiated cursor. */
public var cursor :Object
/** The x/y offset for the hotspot. */
public var x :Number;
public var y :Number;
}
|
Use new Maps factory. Does anyone care about this crappy class?
|
Use new Maps factory.
Does anyone care about this crappy class?
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@852 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
8d725549435e3dffcbe66a4f97b283ed7fb8ab13
|
src/org/mangui/osmf/plugins/HLSSeekTrait.as
|
src/org/mangui/osmf/plugins/HLSSeekTrait.as
|
package org.mangui.osmf.plugins {
import org.osmf.traits.SeekTrait;
import org.osmf.traits.TimeTrait;
import org.mangui.HLS.HLS;
import org.mangui.HLS.HLSStates;
import org.mangui.HLS.HLSEvent;
import org.mangui.HLS.utils.*;
public class HLSSeekTrait extends SeekTrait {
private var _hls : HLS;
public function HLSSeekTrait(hls : HLS, timeTrait : TimeTrait) {
super(timeTrait);
_hls = hls;
_hls.addEventListener(HLSEvent.STATE, _stateChangedHandler);
}
/**
* @private
* Communicates a <code>seeking</code> change to the media through the NetStream.
* @param newSeeking New <code>seeking</code> value.
* @param time Time to seek to, in seconds.
*/
override protected function seekingChangeStart(newSeeking : Boolean, time : Number) : void {
if (newSeeking) {
_hls.stream.seek(time);
}
super.seekingChangeStart(newSeeking, time);
}
/** state changed handler **/
private function _stateChangedHandler(event : HLSEvent) : void {
if (seeking && (event.state != HLSStates.PAUSED_BUFFERING && event.state != HLSStates.PLAYING_BUFFERING)) {
Log.debug("HLSSeekTrait:setSeeking(false);");
setSeeking(false, timeTrait.currentTime);
}
}
}
}
|
package org.mangui.osmf.plugins {
import org.osmf.traits.SeekTrait;
import org.osmf.traits.TimeTrait;
import org.mangui.HLS.HLS;
import org.mangui.HLS.HLSStates;
import org.mangui.HLS.HLSEvent;
import org.mangui.HLS.utils.*;
public class HLSSeekTrait extends SeekTrait {
private var _hls : HLS;
public function HLSSeekTrait(hls : HLS, timeTrait : TimeTrait) {
super(timeTrait);
_hls = hls;
_hls.addEventListener(HLSEvent.STATE, _stateChangedHandler);
}
/**
* @private
* Communicates a <code>seeking</code> change to the media through the NetStream.
* @param newSeeking New <code>seeking</code> value.
* @param time Time to seek to, in seconds.
*/
override protected function seekingChangeStart(newSeeking : Boolean, time : Number) : void {
if (newSeeking) {
Log.info("HLSSeekTrait:seekingChangeStart(newSeeking/time):(" + newSeeking + "/" + time + ")");
_hls.stream.seek(time);
}
super.seekingChangeStart(newSeeking, time);
}
/** state changed handler **/
private function _stateChangedHandler(event : HLSEvent) : void {
if (seeking && (event.state != HLSStates.PAUSED_BUFFERING && event.state != HLSStates.PLAYING_BUFFERING)) {
Log.debug("HLSSeekTrait:setSeeking(false);");
setSeeking(false, timeTrait.currentTime);
}
}
}
}
|
add logs
|
add logs
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
5230cd695aca000a21c51a148333efc1b83d77bf
|
tests/org/osflash/signals/AllTestsRunner.as
|
tests/org/osflash/signals/AllTestsRunner.as
|
package org.osflash.signals {
import asunit4.ui.MinimalRunnerUI;
import org.osflash.signals.AllTests;
public class AllTestsRunner extends MinimalRunnerUI
{
public function AllTestsRunner()
{
run(org.osflash.signals.AllTests);
}
}
}
|
package org.osflash.signals {
import asunit4.ui.MinimalRunnerUI;
import org.osflash.signals.AllTests;
[SWF(width='1000', height='800', backgroundColor='#333333', frameRate='31')]
public class AllTestsRunner extends MinimalRunnerUI
{
public function AllTestsRunner()
{
run(org.osflash.signals.AllTests);
}
}
}
|
Put [SWF] tag in test runner app.
|
Put [SWF] tag in test runner app.
|
ActionScript
|
mit
|
ifuller1/Signals
|
11d3ec5931937f268a0c2b5db10ed299a1d63a23
|
sdk-remote/src/tests/liburbi-check.as
|
sdk-remote/src/tests/liburbi-check.as
|
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*-
AS_INIT()dnl
URBI_PREPARE()
set -e
case $VERBOSE in
x) set -x;;
esac
# Avoid zombies and preserve debugging information.
cleanup ()
{
exit_status=$?
# In case we were caught by set -e, kill the children.
children_kill
children_harvest
children_report
children_sta=$(children_status remote)
# Don't clean before calling children_status...
test x$VERBOSE != x || children_clean
case $exit_status:$children_sta in
0:0) ;;
0:*) # Maybe a children exited for SKIP etc.
exit $children_sta;;
*:*) # If liburbi-check failed, there is a big problem.
error SOFTWARE "liburbi-check itself failed with $exit_status";;
esac
# rst_expect sets exit=false if it saw a failure.
$exit
}
for signal in 1 2 13 15; do
trap 'error $((128 + $signal)) \
"received signal $signal ($(kill -l $signal))"' $signal
done
trap cleanup 0
# Overriden to include the test name.
stderr ()
{
echo >&2 "$(basename $0): $me: $@"
echo >&2
}
# Sleep some time, but taking into account the fact that
# instrumentation slows down a lot.
my_sleep ()
{
if $INSTRUMENT; then
sleep $(($1 * 5))
else
sleep $1
fi
}
## -------------- ##
## Main program. ##
## -------------- ##
exec 3>&2
: ${abs_builddir='@abs_builddir@'}
check_dir abs_builddir liburbi-check
: ${abs_top_builddir='@abs_top_builddir@'}
check_dir abs_top_builddir config.status
: ${abs_top_srcdir='@abs_top_srcdir@'}
check_dir abs_top_srcdir configure.ac
# Make it absolute.
chk=$(absolute "$1")
if test ! -f "$chk.cc"; then
fatal "no such file: $chk.cc"
fi
period=32
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x
medir=$(basename $(dirname "$chk"))
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x/andexp-pipeexp
me=$medir/$(basename "$chk" ".cc")
# ./../../../tests/2.x/andexp-pipeexp.chk -> andexp-pipeexp
meraw=$(basename $me) # MERAW!
srcdir=$(absolute $srcdir)
export srcdir
# Move to a private dir.
rm -rf $me.dir
mkdir -p $me.dir
cd $me.dir
# Help debugging
set | rst_pre "$me variables"
# $URBI_SERVER.
#
# If this SDK-Remote is part of the Kernel package, then we should not
# use an installed urbi-console, but rather the one which is part of
# this package.
if test -d $abs_top_srcdir/../../src/kernel; then
stderr "This SDK-Remote is part of a kernel package" \
" ($abs_top_srcdir/../../src/kernel exists)."
URBI_SERVER=$abs_top_builddir/../src/urbi-console
export URBI_PATH=$abs_top_srcdir/../share
else
stderr "This SDK-Remote is standalone."
fi
# Leaves trailing files, so run it in subdir.
find_urbi_server
# Compute expected output.
sed -n -e 's@//= @@p' $chk.cc >output.exp
touch error.exp
echo 0 >status.exp
# Start it.
valgrind=$(instrument "server.val")
cmd="$valgrind $URBI_SERVER --port 0 -w server.port --period $period"
echo "$cmd" >server.cmd
$cmd >server.out 2>server.err &
children_register server
my_sleep 2
# Start the test.
valgrind=$(instrument "remote.val")
cmd="$valgrind ../../tests localhost $(cat server.port) $meraw"
echo "$cmd" >remote.cmd
$cmd >remote.out.raw 2>remote.err &
children_register remote
# Let some time to run the tests.
children_wait 10
# Ignore the "client errors".
sed -e '/^E client error/d' remote.out.raw >remote.out.eff
# Compare expected output with actual output.
rst_expect output remote.out
rst_pre "Error output" remote.err
# Display Valgrind report.
rst_pre "Valgrind" remote.val
# Exit with success: liburbi-check made its job. But now clean (on
# trap 0) will check $exit to see if there is a failure in the tests
# and adjust the exit status accordingly.
exit 0
|
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*-
URBI_INIT
# Avoid zombies and preserve debugging information.
cleanup ()
{
exit_status=$?
# In case we were caught by set -e, kill the children.
children_kill
children_harvest
children_report
children_sta=$(children_status remote)
# Don't clean before calling children_status...
test x$VERBOSE != x || children_clean
case $exit_status:$children_sta in
0:0) ;;
0:*) # Maybe a children exited for SKIP etc.
exit $children_sta;;
*:*) # If liburbi-check failed, there is a big problem.
error SOFTWARE "liburbi-check itself failed with $exit_status";;
esac
# rst_expect sets exit=false if it saw a failure.
$exit
}
for signal in 1 2 13 15; do
trap 'error $((128 + $signal)) \
"received signal $signal ($(kill -l $signal))"' $signal
done
trap cleanup 0
# Overriden to include the test name.
stderr ()
{
echo >&2 "$(basename $0): $me: $@"
echo >&2
}
# Sleep some time, but taking into account the fact that
# instrumentation slows down a lot.
my_sleep ()
{
if $INSTRUMENT; then
sleep $(($1 * 5))
else
sleep $1
fi
}
## -------------- ##
## Main program. ##
## -------------- ##
exec 3>&2
check_dir abs_builddir liburbi-check
check_dir abs_top_builddir config.status
check_dir abs_top_srcdir configure.ac
# Make it absolute.
chk=$(absolute "$1")
if test ! -f "$chk.cc"; then
fatal "no such file: $chk.cc"
fi
period=32
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x
medir=$(basename $(dirname "$chk"))
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x/andexp-pipeexp
me=$medir/$(basename "$chk" ".cc")
# ./../../../tests/2.x/andexp-pipeexp.chk -> andexp-pipeexp
meraw=$(basename $me) # MERAW!
srcdir=$(absolute $srcdir)
export srcdir
# Move to a private dir.
rm -rf $me.dir
mkdir -p $me.dir
cd $me.dir
# Help debugging
set | rst_pre "$me variables"
# $URBI_SERVER.
#
# If this SDK-Remote is part of the Kernel package, then we should not
# use an installed urbi-console, but rather the one which is part of
# this package.
if test -d $abs_top_srcdir/../../src/kernel; then
stderr "This SDK-Remote is part of a kernel package" \
" ($abs_top_srcdir/../../src/kernel exists)."
export PATH=$abs_top_builddir/../tests/bin:$PATH
else
stderr "This SDK-Remote is standalone."
fi
# Leaves trailing files, so run it in subdir.
find_urbi_server
# Compute expected output.
sed -n -e 's,//= ,,p' $chk.cc >output.exp
touch error.exp
echo 0 >status.exp
# Start it.
valgrind=$(instrument "server.val")
cmd="$valgrind $URBI_SERVER --port 0 -w server.port --period $period"
echo "$cmd" >server.cmd
$cmd >server.out 2>server.err &
children_register server
my_sleep 2
# Start the test.
valgrind=$(instrument "remote.val")
cmd="$valgrind ../../tests localhost $(cat server.port) $meraw"
echo "$cmd" >remote.cmd
$cmd >remote.out.raw 2>remote.err &
children_register remote
# Let some time to run the tests.
children_wait 10
# Ignore the "client errors".
sed -e '/^E client error/d' remote.out.raw >remote.out.eff
# Compare expected output with actual output.
rst_expect output remote.out
rst_pre "Error output" remote.err
# Display Valgrind report.
rst_pre "Valgrind" remote.val
# Exit with success: liburbi-check made its job. But now clean (on
# trap 0) will check $exit to see if there is a failure in the tests
# and adjust the exit status accordingly.
exit 0
|
Update to use the urbi-console wrapper.
|
Update to use the urbi-console wrapper.
* src/tests/liburbi-check.as: Use URBI_INIT.
Remove factored code.
Style changes.
No longer define URBI_SERVER and URBI_PATH to force the use of the
shipped one (instead of the installed version in case of a
standalone SDK Remote). Rather, define the PATH to use the
urbi-console wrapper from the kernel if present.
|
ActionScript
|
bsd-3-clause
|
aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi
|
0c387cd1ec22c7a640cca8135e946b4c68881f9e
|
src/modules/supportClasses/FieldSettings.as
|
src/modules/supportClasses/FieldSettings.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 modules.supportClasses
{
[Bindable]
public class FieldSettings
{
public var name:String;
public var alias:String;
public var tooltip:String;
public function fromXML(configXML:XML):void
{
name = configXML.@name[0];
alias = configXML.@alias[0];
tooltip = configXML.@tooltip[0];
}
public function toXML():XML
{
var configXML:XML = <field name={name}/>
if (alias)
{
configXML.@alias = alias;
}
if (tooltip)
{
configXML.@tooltip = tooltip;
}
return configXML;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// 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 modules.supportClasses
{
[Bindable]
public class FieldSettings
{
public var name:String;
public var alias:String;
public var tooltip:String;
public var dateFormat:String;
public var useUTC:Boolean;
public var required:Boolean;
public function fromXML(configXML:XML):void
{
name = configXML.@name[0];
alias = configXML.@alias[0];
tooltip = configXML.@tooltip[0];
dateFormat = configXML.@dateformat[0];
useUTC = configXML.@useutc[0] == "true";
required = configXML.@required[0] == "true";
}
public function toXML():XML
{
var configXML:XML = <field name={name} required={required} useutc={useUTC}/>
if (alias)
{
configXML.@alias = alias;
}
if (tooltip)
{
configXML.@tooltip = tooltip;
}
if (dateFormat)
{
configXML.@dateformat = dateFormat;
}
return configXML;
}
}
}
|
Update FieldSettings to store supported properties.
|
Update FieldSettings to store supported properties.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
99e723a5aeabae69151f2b5e275420b4542a2281
|
actionscript/src/com/freshplanet/ane/AirInAppPurchase/InAppPurchase.as
|
actionscript/src/com/freshplanet/ane/AirInAppPurchase/InAppPurchase.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.AirInAppPurchase {
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
/**
*
*/
public class InAppPurchase extends EventDispatcher {
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
/**
* If <code>true</code>, logs will be displayed at the ActionScript level.
*/
public static var logEnabled:Boolean = false;
/**
*
*/
public static function get isSupported():Boolean {
return _isIOS() || _isAndroid();
}
/**
*
*/
public static function get instance():InAppPurchase {
return _instance ? _instance : new InAppPurchase();
}
/**
* INIT_SUCCESSFUL
* INIT_ERROR
* @param googlePlayKey
* @param debug
*/
public function init(googlePlayKey:String, debug:Boolean = false):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.INIT_ERROR, "InAppPurchase not supported");
else
_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");
else
_context.call("makePurchase", productId);
}
/**
* PURCHASE_SUCCESSFUL
* PURCHASE_ERROR
* @param productId
*/
public function makeSubscription(productId:String):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported");
else
_context.call("makeSubscription", productId);
}
/**
* CONSUME_SUCCESSFUL
* CONSUME_ERROR
* @param productId
* @param receipt
* @param developerPayload used on Android
*/
public function removePurchaseFromQueue(productId:String, receipt:String, developerPayload:String = null):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.CONSUME_ERROR, "InAppPurchase not supported");
else {
_context.call("removePurchaseFromQueue", productId, receipt, developerPayload ? developerPayload : "");
if (_isIOS()) {
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) {
_log("ERROR", "couldn't parse purchase: " + jsonPurchase);
}
return false;
};
_iosPendingPurchases = _iosPendingPurchases.filter(filterPurchase);
}
}
}
/**
* PRODUCT_INFO_RECEIVED
* PRODUCT_INFO_ERROR
* @param productsIds
* @param subscriptionIds
*/
public function getProductsInfo(productsIds:Array, subscriptionIds:Array):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.PRODUCT_INFO_ERROR, "InAppPurchase not supported");
else {
productsIds ||= [];
subscriptionIds ||= [];
_context.call("getProductsInfo", productsIds, subscriptionIds);
}
}
/**
* RESTORE_INFO_RECEIVED
* RESTORE_INFO_ERROR
*/
public function restoreTransactions(restoreIOSHistory:Boolean=false):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.RESTORE_INFO_ERROR, "InAppPurchase not supported");
else if (_isAndroid() || restoreIOSHistory)
_context.call("restoreTransaction");
else if (_isIOS()) {
var jsonPurchases:String = "[" + _iosPendingPurchases.join(",") + "]";
var jsonData:String = "{ \"purchases\": " + jsonPurchases + "}";
_dispatchEvent(InAppPurchaseEvent.RESTORE_INFO_RECEIVED, jsonData);
}
}
public function clearTransactions():void
{
_iosPendingPurchases = new Vector.<Object>();
if (!isSupported || _isAndroid()) {
_dispatchEvent(InAppPurchaseEvent.CLEAR_TRANSACTIONS_ERROR, "clear transactions not supported");
} else if (_isIOS()) {
_context.call("clearTransactions");
}
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.ane.AirInAppPurchase";
private static var _instance:InAppPurchase = null;
private var _context:ExtensionContext = null;
private var _iosPendingPurchases:Vector.<Object> = new Vector.<Object>();
/**
* "private" singleton constructor
*/
public function InAppPurchase() {
super();
if (_instance)
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
_instance = this;
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
_log("ERROR", "Extension context is null. Please check if extension.xml is setup correctly.");
else
_context.addEventListener(StatusEvent.STATUS, _onStatus);
}
/**
*
* @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 {
if (event.code == InAppPurchaseEvent.PURCHASE_SUCCESSFUL && _isIOS())
_iosPendingPurchases.push(event.level);
_dispatchEvent(event.code, event.level);
}
/**
*
* @param strings
*/
private function _log(...strings):void {
if (logEnabled) {
strings.unshift(EXTENSION_ID);
trace.apply(null, strings);
}
}
/**
*
* @return
*/
private static function _isIOS():Boolean {
return Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0;
}
/**
*
* @return
*/
private static function _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.AirInAppPurchase {
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
/**
*
*/
public class InAppPurchase extends EventDispatcher {
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
/**
* If <code>true</code>, logs will be displayed at the ActionScript level.
*/
public static var logEnabled:Boolean = false;
/**
*
*/
public static function get isSupported():Boolean {
return _isIOS() || _isAndroid();
}
/**
*
*/
public static function get instance():InAppPurchase {
return _instance ? _instance : new InAppPurchase();
}
/**
* INIT_SUCCESSFUL
* INIT_ERROR
* @param googlePlayKey
* @param debug
*/
public function init(googlePlayKey:String, debug:Boolean = false):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.INIT_ERROR, "InAppPurchase not supported");
else
_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");
else
_context.call("makePurchase", productId);
}
/**
* PURCHASE_SUCCESSFUL
* PURCHASE_ERROR
* @param productId
*/
public function makeSubscription(productId:String):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported");
else
_context.call("makeSubscription", productId);
}
/**
* CONSUME_SUCCESSFUL
* CONSUME_ERROR
* @param productId
* @param receipt
* @param developerPayload used on Android
*/
public function removePurchaseFromQueue(productId:String, receipt:String, developerPayload:String = null):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.CONSUME_ERROR, "InAppPurchase not supported");
else {
_context.call("removePurchaseFromQueue", productId, receipt, developerPayload ? developerPayload : "");
if (_isIOS()) {
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) {
_log("ERROR", "couldn't parse purchase: " + jsonPurchase);
}
return false;
};
_iosPendingPurchases = _iosPendingPurchases.filter(filterPurchase);
}
}
}
/**
* PRODUCT_INFO_RECEIVED
* PRODUCT_INFO_ERROR
* @param productsIds
* @param subscriptionIds
*/
public function getProductsInfo(productsIds:Array, subscriptionIds:Array):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.PRODUCT_INFO_ERROR, "InAppPurchase not supported");
else {
productsIds ||= [];
subscriptionIds ||= [];
_context.call("getProductsInfo", productsIds, subscriptionIds);
}
}
/**
* RESTORE_INFO_RECEIVED
* RESTORE_INFO_ERROR
*/
public function restoreTransactions(restoreIOSHistory:Boolean=false):void {
if (!isSupported)
_dispatchEvent(InAppPurchaseEvent.RESTORE_INFO_ERROR, "InAppPurchase not supported");
else if (_isAndroid() || restoreIOSHistory)
_context.call("restoreTransaction");
else if (_isIOS()) {
var jsonPurchases:String = "[" + _iosPendingPurchases.join(",") + "]";
var jsonData:String = "{ \"purchases\": " + jsonPurchases + "}";
_dispatchEvent(InAppPurchaseEvent.RESåTORE_INFO_RECEIVED, jsonData);
}
}
public function clearTransactions():void
{
_iosPendingPurchases = new Vector.<Object>();
if (!isSupported || _isAndroid()) {
_dispatchEvent("CLEAR_TRANSACTIONS_ERROR", "clear transactions not supported");
} else if (_isIOS()) {
_context.call("clearTransactions");
}
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.ane.AirInAppPurchase";
private static var _instance:InAppPurchase = null;
private var _context:ExtensionContext = null;
private var _iosPendingPurchases:Vector.<Object> = new Vector.<Object>();
/**
* "private" singleton constructor
*/
public function InAppPurchase() {
super();
if (_instance)
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
_instance = this;
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
_log("ERROR", "Extension context is null. Please check if extension.xml is setup correctly.");
else
_context.addEventListener(StatusEvent.STATUS, _onStatus);
}
/**
*
* @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 {
if (event.code == InAppPurchaseEvent.PURCHASE_SUCCESSFUL && _isIOS())
_iosPendingPurchases.push(event.level);
_dispatchEvent(event.code, event.level);
}
/**
*
* @param strings
*/
private function _log(...strings):void {
if (logEnabled) {
strings.unshift(EXTENSION_ID);
trace.apply(null, strings);
}
}
/**
*
* @return
*/
private static function _isIOS():Boolean {
return Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0;
}
/**
*
* @return
*/
private static function _isAndroid():Boolean {
return Capabilities.manufacturer.indexOf("Android") > -1;
}
}
}
|
fix typo & event name
|
fix typo & event name
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-In-App-Purchase,freshplanet/ANE-In-App-Purchase,freshplanet/ANE-In-App-Purchase
|
b99483faf7f43cb7f66f6b9509443bd0353ac7ff
|
src/aerys/minko/render/material/realistic/RealisticMaterial.as
|
src/aerys/minko/render/material/realistic/RealisticMaterial.as
|
package aerys.minko.render.material.realistic
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.environment.EnvironmentMappingProperties;
import aerys.minko.render.material.phong.PhongEffect;
import aerys.minko.render.material.phong.PhongMaterial;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.IDataProvider;
import flash.utils.Dictionary;
public class RealisticMaterial extends PhongMaterial
{
private static const DEFAULT_NAME : String = 'RealisticMaterial';
private static const DEFAULT_EFFECT : Effect = new PhongEffect(
new RealisticShader()
);
public function get environmentMap() : ITextureResource
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP) as ITextureResource;
}
public function set environmentMap(value : ITextureResource) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP, value);
}
public function get environmentMapFiltering() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING);
}
public function set environmentMapFiltering(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, value);
}
public function get environmentMapMipMapping() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING);
}
public function set environmentMapMipMapping(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, value);
}
public function get environmentMapWrapping() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING);
}
public function set environmentMapWrapping(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, value);
}
public function get environmentMapFormat() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT);
}
public function set environmentMapFormat(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, value);
}
public function get reflectivity() : Number
{
return getProperty(EnvironmentMappingProperties.REFLECTIVITY) as Number;
}
public function set reflectivity(value : Number) : void
{
setProperty(EnvironmentMappingProperties.REFLECTIVITY, value);
}
public function get environmentMappingType() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE) as uint;
}
public function set environmentMappingType(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE, value);
}
public function get environmentBlending() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING) as uint;
}
public function set environmentBlending(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, value);
}
public function RealisticMaterial(properties : Object = null,
effect : Effect = null,
name : String = DEFAULT_NAME)
{
super(properties, effect || DEFAULT_EFFECT, name);
}
override public function clone() : IDataProvider
{
return new RealisticMaterial(this, effect, name);
}
}
}
|
package aerys.minko.render.material.realistic
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.environment.EnvironmentMappingProperties;
import aerys.minko.render.material.phong.PhongEffect;
import aerys.minko.render.material.phong.PhongMaterial;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.type.binding.IDataProvider;
public class RealisticMaterial extends PhongMaterial
{
private static const DEFAULT_NAME : String = 'RealisticMaterial';
private static const DEFAULT_EFFECT : Effect = new PhongEffect(
new RealisticShader()
);
public function get environmentMap() : ITextureResource
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP) as ITextureResource;
}
public function set environmentMap(value : ITextureResource) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP, value);
}
public function get environmentMapFiltering() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING);
}
public function set environmentMapFiltering(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, value);
}
public function get environmentMapMipMapping() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING);
}
public function set environmentMapMipMapping(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, value);
}
public function get environmentMapWrapping() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING);
}
public function set environmentMapWrapping(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, value);
}
public function get environmentMapFormat() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT);
}
public function set environmentMapFormat(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, value);
}
public function get reflectivity() : Number
{
return getProperty(EnvironmentMappingProperties.REFLECTIVITY) as Number;
}
public function set reflectivity(value : Number) : void
{
setProperty(EnvironmentMappingProperties.REFLECTIVITY, value);
}
public function get environmentMappingType() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE) as uint;
}
public function set environmentMappingType(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE, value);
}
public function get environmentBlending() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING) as uint;
}
public function set environmentBlending(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, value);
}
public function RealisticMaterial(properties : Object = null,
effect : Effect = null,
name : String = DEFAULT_NAME)
{
super(properties, effect || DEFAULT_EFFECT, name);
}
override public function clone() : IDataProvider
{
return new RealisticMaterial(this, effect, name);
}
}
}
|
remove useless imports
|
remove useless imports
|
ActionScript
|
mit
|
aerys/minko-as3
|
8c08172ad98578ba8705dbda0b804890e50aa531
|
WEB-INF/lps/lfc/kernel/swf9/LzMouseKernel.as
|
WEB-INF/lps/lfc/kernel/swf9/LzMouseKernel.as
|
/**
* LzMouseKernel.as
*
* @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
*/
// Receives mouse events from the runtime
class LzMouseKernel {
#passthrough (toplevel:true) {
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.ui.*;
import flash.utils.getDefinitionByName;
}#
//////////////////
// MOUSE EVENTS //
//////////////////
// sends mouse events to the callback
static function handleMouseEvent (view:*, eventname:String) :void {
if (__callback) __scope[__callback](eventname, view);
//Debug.write('LzMouseKernel event', eventname);
}
static var __callback:String = null;
static var __scope:* = null;
static var __lastMouseDown:LzSprite = null;
static var __mouseLeft:Boolean = false;
static var __listeneradded:Boolean = false;
/**
* Shows or hides the hand cursor for all clickable views.
*/
static var showhandcursor:Boolean = true;
static function setCallback (scope:*, funcname:String) :void {
__scope = scope;
__callback = funcname;
if (__listeneradded == false) {
/* TODO [hqm 2008-01] Do we want to do anything with other
* events, like click?
stage.addEventListener(MouseEvent.CLICK, reportClick);
*/
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mouseHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_UP, __mouseHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_DOWN, __mouseHandler);
// handled by lz.embed.mousewheel for Windows LFCApplication.stage.addEventListener(MouseEvent.MOUSE_WHEEL, __mouseWheelHandler);
LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, __mouseLeaveHandler);
__listeneradded = true;
}
}
// Handles global mouse events
static function __mouseHandler (event:MouseEvent) :void {
var eventname:String = 'on' + event.type.toLowerCase();
if (eventname == 'onmouseup' && __lastMouseDown != null) {
// call mouseup on the sprite that got the last mouse down
__lastMouseDown.__globalmouseup(event);
__lastMouseDown = null;
} else {
if (__mouseLeft) {
__mouseLeft = false;
// Mouse reentered the app.
if (event.buttonDown) __mouseUpOutsideHandler();
// TODO [hqm 2009-04] LPP-7957 -- this works
// around Firefox bug; if you are making a text
// selection, and then drag the mouse outside of
// the app while the left button is down, and then
// release it. When you bring the mouse back into
// the app, the selection is stuck dragging
// because Flash plugin never gets the mouse up.
LFCApplication.stage.focus = null;
// generate a 'onmouseenter' event
handleMouseEvent(null, 'onmouseenter');
}
handleMouseEvent(null, eventname);
}
}
// sends mouseup and calls __globalmouseup when the mouse goes up outside the app - see LPP-7724
static function __mouseUpOutsideHandler () :void {
if (__lastMouseDown != null) {
var ev:MouseEvent = new MouseEvent('mouseup');
__lastMouseDown.__globalmouseup(ev);
__lastMouseDown = null;
}
}
// handles MOUSE_LEAVE event
static function __mouseLeaveHandler (event:Event = null) :void {
__mouseLeft = true;
handleMouseEvent(null, 'onmouseleave');
}
static function __mouseWheelHandler (event:MouseEvent) :void {
lz.Keys.__mousewheelEvent(event.delta);
}
//////////////////
// MOUSE CURSOR //
//////////////////
/**
* Shows or hides the hand cursor for all clickable views.
* @param Boolean show: true shows the hand cursor for buttons, false hides it
*/
static function showHandCursor (show:Boolean) :void {
showhandcursor = show;
LzSprite.rootSprite.setGlobalHandCursor(show);
}
static var __amLocked:Boolean = false;
static var useBuiltinCursor:Boolean = false;
static var cursorSprite:Sprite = null;
static var cursorOffsetX:int = 0;
static var cursorOffsetY:int = 0;
static var globalCursorResource:String = null;
static var lastCursorResource:String = null;
#passthrough {
private static var __MouseCursor:Object = null;
private static function get MouseCursor () :Object {
if (__MouseCursor == null) {
__MouseCursor = getDefinitionByName('flash.ui.MouseCursor');
}
return __MouseCursor;
}
private static var __builtinCursors:Object = null;
static function get builtinCursors () :Object {
if (__builtinCursors == null) {
var cursors:Object = {};
if ($swf10) {
cursors[MouseCursor.ARROW] = true;
cursors[MouseCursor.AUTO] = true;
cursors[MouseCursor.BUTTON] = true;
cursors[MouseCursor.HAND] = true;
cursors[MouseCursor.IBEAM] = true;
}
__builtinCursors = cursors;
}
return __builtinCursors;
}
static function get hasGlobalCursor () :Boolean {
var gcursor:String = globalCursorResource;
if ($swf10) {
return ! (gcursor == null || (gcursor == MouseCursor.AUTO && useBuiltinCursor));
} else {
return ! (gcursor == null);
}
}
}#
/**
* Sets the cursor to a resource
* @param String what: The resource to use as the cursor.
*/
static function setCursorGlobal (what:String) :void {
globalCursorResource = what;
setCursorLocal(what);
}
static function setCursorLocal (what:String) :void {
if ( __amLocked ) { return; }
if (what == null) {
// null is invalid, maybe call restoreCursor()?
return;
} else if (lastCursorResource != what) {
var resourceSprite:DisplayObject = getCursorResource(what);
if (resourceSprite != null) {
if (cursorSprite.numChildren > 0) {
cursorSprite.removeChildAt(0);
}
cursorSprite.addChild( resourceSprite );
useBuiltinCursor = false;
} else if (builtinCursors[what] != null) {
useBuiltinCursor = true;
} else {
// invalid cursor?
return;
}
lastCursorResource = what;
}
if (useBuiltinCursor) {
if ($swf10) { Mouse['cursor'] = what; }
cursorSprite.stopDrag();
cursorSprite.visible = false;
LFCApplication.stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
LFCApplication.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
Mouse.show();
} else {
// you can only hide the Mouse when Mouse.cursor is AUTO
if ($swf10) { Mouse['cursor'] = MouseCursor.AUTO; }
Mouse.hide();
cursorSprite.x = LFCApplication.stage.mouseX + cursorOffsetX;
cursorSprite.y = LFCApplication.stage.mouseY + cursorOffsetY;
LFCApplication.setChildIndex(cursorSprite, LFCApplication._sprite.numChildren-1);
// respond to mouse move events
cursorSprite.startDrag();
LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
cursorSprite.visible = true;
}
}
/**
* Triggered when cursor leaves screen or context-menu is opened, in both
* cases we must display the system cursor
*/
private static function mouseLeaveHandler (event:Event) :void {
cursorSprite.visible = false;
Mouse.show();
// use capture-phase because most sprites call stopPropagation() for mouse-events
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_OVER, mouseEnterHandler, true);
}
/**
* Triggered when cursor enters screen or context-menu is closed
*/
private static function mouseEnterHandler (event:Event) :void {
cursorSprite.visible = true;
Mouse.hide();
LFCApplication.stage.removeEventListener(MouseEvent.MOUSE_OVER, mouseEnterHandler, true);
}
/**
* Hide custom cursor over selectable TextFields otherwise both the ibeam-cursor
* and the custom cursor are displayed
*/
private static function mouseMoveHandler (event:MouseEvent) :void {
var target:Object = event.target;
if (target is TextField && target.selectable) {
cursorSprite.visible = false;
Mouse.show();
} else {
Mouse.hide();
cursorSprite.visible = true;
}
}
private static function getCursorResource (resource:String) :DisplayObject {
var resinfo:Object = LzResourceLibrary[resource];
var assetclass:Class;
if (resinfo == null) {
return null;
}
// single frame resources get an entry in LzResourceLibrary which has
// 'assetclass' pointing to the resource Class object.
if (resinfo.assetclass is Class) {
assetclass = resinfo.assetclass;
} else {
// Multiframe resources have an array of Class objects in frames[]
var frames:Array = resinfo.frames;
assetclass = frames[0];
}
var asset:DisplayObject = new assetclass();
asset.scaleX = 1.0;
asset.scaleY = 1.0;
if (resinfo['offsetx'] != null) { cursorOffsetX = resinfo['offsetx']; }
if (resinfo['offsety'] != null) { cursorOffsetY = resinfo['offsety']; }
return asset;
}
/**
* This function restores the default cursor if there is no locked cursor on
* the screen.
*
* @access private
*/
static function restoreCursor () :void {
if ( __amLocked ) { return; }
cursorSprite.stopDrag();
cursorSprite.visible = false;
LFCApplication.stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
LFCApplication.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
globalCursorResource = null;
if ($swf10) { Mouse['cursor'] = MouseCursor.AUTO; }
Mouse.show();
}
/** Called by LzSprite to restore cursor to global value.
*/
static function restoreCursorLocal () :void {
if ( __amLocked ) { return; }
if (globalCursorResource == null) {
// Restore to system default pointer
restoreCursor();
} else {
// Restore to the last value set by setCursorGlobal
setCursorLocal(globalCursorResource);
}
}
/**
* Prevents the cursor from being changed until unlock is called.
*
*/
static function lock () :void {
__amLocked = true;
}
/**
* Restores the default cursor.
*
*/
static function unlock () :void {
__amLocked = false;
restoreCursor();
}
static function initCursor () :void {
cursorSprite = new Sprite();
cursorSprite.mouseChildren = false;
cursorSprite.mouseEnabled = false;
cursorSprite.visible = false;
// Add the cursor DisplayObject to the root sprite
LFCApplication.addChild(cursorSprite);
cursorSprite.x = -10000;
cursorSprite.y = -10000;
}
}
|
/**
* LzMouseKernel.as
*
* @copyright Copyright 2001-2010 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
*/
// Receives mouse events from the runtime
class LzMouseKernel {
#passthrough (toplevel:true) {
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.ui.*;
import flash.utils.getDefinitionByName;
}#
//////////////////
// MOUSE EVENTS //
//////////////////
// sends mouse events to the callback
static function handleMouseEvent (view:*, eventname:String) :void {
if (__callback) __scope[__callback](eventname, view);
//Debug.write('LzMouseKernel event', eventname);
}
static var __callback:String = null;
static var __scope:* = null;
static var __lastMouseDown:LzSprite = null;
static var __mouseLeft:Boolean = false;
static var __listeneradded:Boolean = false;
/**
* Shows or hides the hand cursor for all clickable views.
*/
static var showhandcursor:Boolean = true;
static function setCallback (scope:*, funcname:String) :void {
__scope = scope;
__callback = funcname;
if (__listeneradded == false) {
/* TODO [hqm 2008-01] Do we want to do anything with other
* events, like click?
stage.addEventListener(MouseEvent.CLICK, reportClick);
*/
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mouseHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_UP, __mouseHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_DOWN, __mouseHandler);
// handled by lz.embed.mousewheel for Windows LFCApplication.stage.addEventListener(MouseEvent.MOUSE_WHEEL, __mouseWheelHandler);
LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, __mouseLeaveHandler);
__listeneradded = true;
}
}
// Handles global mouse events
static function __mouseHandler (event:MouseEvent) :void {
var eventname:String = 'on' + event.type.toLowerCase();
if (eventname == 'onmouseup' && __lastMouseDown != null) {
// call mouseup on the sprite that got the last mouse down
__lastMouseDown.__globalmouseup(event);
__lastMouseDown = null;
} else {
if (__mouseLeft) {
__mouseLeft = false;
// Mouse reentered the app.
if (event.buttonDown) __mouseUpOutsideHandler();
if (lz.embed.browser.isFirefox && lz.embed.browser.OS == 'mac' && lz.embed.browser.version < 3.5) {
// TODO [hqm 2009-04] LPP-7957 -- this works
// around Firefox bug; if you are making a text
// selection, and then drag the mouse outside of
// the app while the left button is down, and then
// release it. When you bring the mouse back into
// the app, the selection is stuck dragging
// because Flash plugin never gets the mouse up.
LFCApplication.stage.focus = null;
}
// generate a 'onmouseenter' event
handleMouseEvent(null, 'onmouseenter');
}
handleMouseEvent(null, eventname);
}
}
// sends mouseup and calls __globalmouseup when the mouse goes up outside the app - see LPP-7724
static function __mouseUpOutsideHandler () :void {
if (__lastMouseDown != null) {
var ev:MouseEvent = new MouseEvent('mouseup');
__lastMouseDown.__globalmouseup(ev);
__lastMouseDown = null;
}
}
// handles MOUSE_LEAVE event
static function __mouseLeaveHandler (event:Event = null) :void {
__mouseLeft = true;
handleMouseEvent(null, 'onmouseleave');
}
static function __mouseWheelHandler (event:MouseEvent) :void {
lz.Keys.__mousewheelEvent(event.delta);
}
//////////////////
// MOUSE CURSOR //
//////////////////
/**
* Shows or hides the hand cursor for all clickable views.
* @param Boolean show: true shows the hand cursor for buttons, false hides it
*/
static function showHandCursor (show:Boolean) :void {
showhandcursor = show;
LzSprite.rootSprite.setGlobalHandCursor(show);
}
static var __amLocked:Boolean = false;
static var useBuiltinCursor:Boolean = false;
static var cursorSprite:Sprite = null;
static var cursorOffsetX:int = 0;
static var cursorOffsetY:int = 0;
static var globalCursorResource:String = null;
static var lastCursorResource:String = null;
#passthrough {
private static var __MouseCursor:Object = null;
private static function get MouseCursor () :Object {
if (__MouseCursor == null) {
__MouseCursor = getDefinitionByName('flash.ui.MouseCursor');
}
return __MouseCursor;
}
private static var __builtinCursors:Object = null;
static function get builtinCursors () :Object {
if (__builtinCursors == null) {
var cursors:Object = {};
if ($swf10) {
cursors[MouseCursor.ARROW] = true;
cursors[MouseCursor.AUTO] = true;
cursors[MouseCursor.BUTTON] = true;
cursors[MouseCursor.HAND] = true;
cursors[MouseCursor.IBEAM] = true;
}
__builtinCursors = cursors;
}
return __builtinCursors;
}
static function get hasGlobalCursor () :Boolean {
var gcursor:String = globalCursorResource;
if ($swf10) {
return ! (gcursor == null || (gcursor == MouseCursor.AUTO && useBuiltinCursor));
} else {
return ! (gcursor == null);
}
}
}#
/**
* Sets the cursor to a resource
* @param String what: The resource to use as the cursor.
*/
static function setCursorGlobal (what:String) :void {
globalCursorResource = what;
setCursorLocal(what);
}
static function setCursorLocal (what:String) :void {
if ( __amLocked ) { return; }
if (what == null) {
// null is invalid, maybe call restoreCursor()?
return;
} else if (lastCursorResource != what) {
var resourceSprite:DisplayObject = getCursorResource(what);
if (resourceSprite != null) {
if (cursorSprite.numChildren > 0) {
cursorSprite.removeChildAt(0);
}
cursorSprite.addChild( resourceSprite );
useBuiltinCursor = false;
} else if (builtinCursors[what] != null) {
useBuiltinCursor = true;
} else {
// invalid cursor?
return;
}
lastCursorResource = what;
}
if (useBuiltinCursor) {
if ($swf10) { Mouse['cursor'] = what; }
cursorSprite.stopDrag();
cursorSprite.visible = false;
LFCApplication.stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
LFCApplication.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
Mouse.show();
} else {
// you can only hide the Mouse when Mouse.cursor is AUTO
if ($swf10) { Mouse['cursor'] = MouseCursor.AUTO; }
Mouse.hide();
cursorSprite.x = LFCApplication.stage.mouseX + cursorOffsetX;
cursorSprite.y = LFCApplication.stage.mouseY + cursorOffsetY;
LFCApplication.setChildIndex(cursorSprite, LFCApplication._sprite.numChildren-1);
// respond to mouse move events
cursorSprite.startDrag();
LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
cursorSprite.visible = true;
}
}
/**
* Triggered when cursor leaves screen or context-menu is opened, in both
* cases we must display the system cursor
*/
private static function mouseLeaveHandler (event:Event) :void {
cursorSprite.visible = false;
Mouse.show();
// use capture-phase because most sprites call stopPropagation() for mouse-events
LFCApplication.stage.addEventListener(MouseEvent.MOUSE_OVER, mouseEnterHandler, true);
}
/**
* Triggered when cursor enters screen or context-menu is closed
*/
private static function mouseEnterHandler (event:Event) :void {
cursorSprite.visible = true;
Mouse.hide();
LFCApplication.stage.removeEventListener(MouseEvent.MOUSE_OVER, mouseEnterHandler, true);
}
/**
* Hide custom cursor over selectable TextFields otherwise both the ibeam-cursor
* and the custom cursor are displayed
*/
private static function mouseMoveHandler (event:MouseEvent) :void {
var target:Object = event.target;
if (target is TextField && target.selectable) {
cursorSprite.visible = false;
Mouse.show();
} else {
Mouse.hide();
cursorSprite.visible = true;
}
}
private static function getCursorResource (resource:String) :DisplayObject {
var resinfo:Object = LzResourceLibrary[resource];
var assetclass:Class;
if (resinfo == null) {
return null;
}
// single frame resources get an entry in LzResourceLibrary which has
// 'assetclass' pointing to the resource Class object.
if (resinfo.assetclass is Class) {
assetclass = resinfo.assetclass;
} else {
// Multiframe resources have an array of Class objects in frames[]
var frames:Array = resinfo.frames;
assetclass = frames[0];
}
var asset:DisplayObject = new assetclass();
asset.scaleX = 1.0;
asset.scaleY = 1.0;
if (resinfo['offsetx'] != null) { cursorOffsetX = resinfo['offsetx']; }
if (resinfo['offsety'] != null) { cursorOffsetY = resinfo['offsety']; }
return asset;
}
/**
* This function restores the default cursor if there is no locked cursor on
* the screen.
*
* @access private
*/
static function restoreCursor () :void {
if ( __amLocked ) { return; }
cursorSprite.stopDrag();
cursorSprite.visible = false;
LFCApplication.stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
LFCApplication.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
globalCursorResource = null;
if ($swf10) { Mouse['cursor'] = MouseCursor.AUTO; }
Mouse.show();
}
/** Called by LzSprite to restore cursor to global value.
*/
static function restoreCursorLocal () :void {
if ( __amLocked ) { return; }
if (globalCursorResource == null) {
// Restore to system default pointer
restoreCursor();
} else {
// Restore to the last value set by setCursorGlobal
setCursorLocal(globalCursorResource);
}
}
/**
* Prevents the cursor from being changed until unlock is called.
*
*/
static function lock () :void {
__amLocked = true;
}
/**
* Restores the default cursor.
*
*/
static function unlock () :void {
__amLocked = false;
restoreCursor();
}
static function initCursor () :void {
cursorSprite = new Sprite();
cursorSprite.mouseChildren = false;
cursorSprite.mouseEnabled = false;
cursorSprite.visible = false;
// Add the cursor DisplayObject to the root sprite
LFCApplication.addChild(cursorSprite);
cursorSprite.x = -10000;
cursorSprite.y = -10000;
}
}
|
Change 20100222-maxcarlson-o by maxcarlson@bank on 2010-02-22 19:35:00 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20100222-maxcarlson-o by maxcarlson@bank on 2010-02-22 19:35:00 PST
in /Users/maxcarlson/openlaszlo/trunk-clean
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: Conditionalize textfield focus workaround from LPP-7957
Bugs Fixed: LPP-8783 - Text field loses focus when mousing out of canvas and then mousing back in (SWF9)
Technical Reviewer: ptw
QA Reviewer: [email protected]
Details: Conditionalize workaround to only happen for FF < 3.5 on OS X.
Tests: See LPP-8783.
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@15797 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
f1448d0d30bec8d20df5a3fc0d224a1b7a161e53
|
src/battlecode/client/viewer/render/DrawState.as
|
src/battlecode/client/viewer/render/DrawState.as
|
package battlecode.client.viewer.render {
import battlecode.client.viewer.render.DrawRobot;
import battlecode.client.viewer.render.DrawRobot;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.ResearchType;
import battlecode.common.RobotType;
import battlecode.common.Team;
import battlecode.serial.RoundDelta;
import battlecode.serial.RoundStats;
import battlecode.world.GameMap;
import battlecode.world.signals.*;
public class DrawState extends DefaultSignalHandler {
// state
private var mines:Array; // Team[][]
private var neutralEncampments:Object;
private var encampments:Object;
private var groundRobots:Object;
private var hqA:DrawRobot;
private var hqB:DrawRobot;
// stats
private var aPoints:Number;
private var bPoints:Number;
private var aFlux:Number;
private var bFlux:Number;
private var aGatheredPoints:Number;
private var bGatheredPoints:Number;
private var roundNum:uint;
private var progressA:Array;
private var progressB:Array;
// immutables
private var map:GameMap;
private var origin:MapLocation;
public function DrawState(map:GameMap) {
neutralEncampments = new Object();
encampments = new Object();
groundRobots = new Object();
mines = new Array();
for (var i:int = 0; i < map.getWidth(); i++) {
mines[i] = new Array();
for (var j:int = 0; j < map.getHeight(); j++) {
mines[i][j] = null;
}
}
aPoints = 0;
bPoints = 0;
aFlux = 0;
bFlux = 0;
aGatheredPoints = 0;
bGatheredPoints = 0;
roundNum = 1;
progressA = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
progressB = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
this.map = map;
this.origin = map.getOrigin();
}
///////////////////////////////////////////////////////
///////////////// PROPERTY GETTERS ////////////////////
///////////////////////////////////////////////////////
public function getMines():Array {
return mines;
}
public function getNeutralEncampments():Object {
return neutralEncampments;
}
public function getEncampments():Object {
return encampments
}
public function getGroundRobots():Object {
return groundRobots;
}
public function getHQ(team:String):DrawRobot {
return team == Team.A ? hqA : hqB;
}
public function getPoints(team:String):uint {
return (team == Team.A) ? aPoints : bPoints;
}
public function getFlux(team:String):uint {
return (team == Team.A) ? aFlux : bFlux;
}
public function getResearchProgress(team:String):Array {
return team == Team.A ? progressA : progressB;
}
///////////////////////////////////////////////////////
/////////////////// CORE FUNCTIONS ////////////////////
///////////////////////////////////////////////////////
private function copyStateFrom(state:DrawState):void {
var a:*;
mines = new Array();
for (var i:int = 0; i < map.getWidth(); i++) {
mines[i] = new Array();
for (var j:int = 0; j < map.getHeight(); j++) {
mines[i][j] = state.mines[i][j];
}
}
neutralEncampments = new Object();
for (a in state.neutralEncampments) {
neutralEncampments[a] = state.neutralEncampments[a].clone();
}
encampments = new Object();
for (a in state.encampments) {
encampments[a] = state.encampments[a].clone();
}
groundRobots = new Object();
for (a in state.groundRobots) {
groundRobots[a] = state.groundRobots[a].clone();
}
hqA = state.hqA ? state.hqA.clone() as DrawRobot : null;
hqB = state.hqB ? state.hqB.clone() as DrawRobot : null;
progressA = state.progressA.concat();
progressB = state.progressB.concat();
roundNum = state.roundNum;
}
public function clone():DrawState {
var state:DrawState = new DrawState(map);
state.copyStateFrom(this);
return state;
}
public function applyDelta(delta:RoundDelta):void {
updateRound();
for each (var signal:Signal in delta.getSignals()) {
applySignal(signal);
}
processEndOfRound();
}
public function applySignal(signal:Signal):void {
if (signal != null) signal.accept(this);
}
public function applyStats(stats:RoundStats):void {
aPoints = stats.getPoints(Team.A);
bPoints = stats.getPoints(Team.B);
aGatheredPoints = stats.getGatheredPoints(Team.A);
bGatheredPoints = stats.getGatheredPoints(Team.B);
}
public function updateRound():void {
var a:*, i:uint, j:uint;
var o:DrawRobot;
for (a in groundRobots) {
o = groundRobots[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete groundRobots[a];
}
}
for (a in encampments) {
o = encampments[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete encampments[a];
}
}
if (hqA) {
hqA.updateRound();
if (!hqA.isAlive()) {
if (hqA.parent) {
hqA.parent.removeChild(hqA);
}
hqA = null;
}
}
if (hqB) {
hqB.updateRound();
if (!hqB.isAlive()) {
if (hqB.parent) {
hqB.parent.removeChild(hqB);
}
hqB = null;
}
}
}
private function processEndOfRound():void {
roundNum++;
}
///////////////////////////////////////////////////////
////////////// PRIVATE HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function getRobot(id:uint):DrawRobot {
if (groundRobots[id]) return groundRobots[id] as DrawRobot;
if (encampments[id]) return encampments[id] as DrawRobot;
return null;
}
private function removeRobot(id:uint):void {
if (groundRobots[id]) delete groundRobots[id];
if (encampments[id]) delete encampments[id];
}
private function translateCoordinates(loc:MapLocation):MapLocation {
return new MapLocation(loc.getX() - origin.getX(), loc.getY() - origin.getY());
}
///////////////////////////////////////////////////////
/////////////////// SIGNAL HANDLERS ///////////////////
///////////////////////////////////////////////////////
override public function visitBroadcastSignal(s:BroadcastSignal):* {
getRobot(s.getRobotID()).broadcast();
}
override public function visitCaptureSignal(s:CaptureSignal):* {
var o:DrawRobot = neutralEncampments[s.getLocation()];
if (o) {
if (o.parent) {
o.parent.removeChild(o);
}
delete neutralEncampments[s.getLocation()]; // TODO dont delete just hide
}
var robot:DrawRobot = getRobot(s.getParentID());
robot.capture();
}
override public function visitDeathSignal(s:DeathSignal):* {
var robot:DrawRobot = getRobot(s.getRobotID());
robot.destroyUnit();
if (robot.getType() == RobotType.HQ) {
var hq:DrawRobot = robot.getTeam() == Team.A ? hqA : hqB;
hq.destroyUnit();
}
}
override public function visitEnergonChangeSignal(s:EnergonChangeSignal):* {
var robotIDs:Array = s.getRobotIDs();
var energon:Array = s.getEnergon();
for (var i:uint; i < robotIDs.length; i++) {
var robot:DrawRobot = getRobot(robotIDs[i]);
robot.setEnergon(energon[i]);
if (robot.getType() == RobotType.HQ) {
var hq:DrawRobot = robot.getTeam() == Team.A ? hqA : hqB;
hq.setEnergon(energon[i]);
}
}
}
override public function visitFluxChangeSignal(s:FluxChangeSignal):* {
aFlux = s.getFlux(Team.A);
bFlux = s.getFlux(Team.B);
}
override public function visitIndicatorStringSignal(s:IndicatorStringSignal):* {
getRobot(s.getRobotID()).setIndicatorString(s.getIndicatorString(), s.getIndex());
}
override public function visitMineSignal(s:MineSignal):* {
var loc:MapLocation = translateCoordinates(s.getLocation());
if (s.isBirth()) {
mines[loc.getX()][loc.getY()] = s.getTeam();
} else {
mines[loc.getX()][loc.getY()] = null;
}
}
override public function visitMineLayerSignal(s:MineLayerSignal):* {
var robot:DrawRobot = getRobot(s.getRobotID());
if (s.isLaying()) {
robot.layMine();
} else {
// TODO mining stopping - not enough info on the signal?
var researchProgress:Array = robot.getTeam() == Team.A ? progressA : progressB;
var hasUpgrade:Boolean = researchProgress[ResearchType.getField(ResearchType.PIXAXE)] == 1.0;
robot.diffuseMine(hasUpgrade);
}
}
override public function visitMovementSignal(s:MovementSignal):* {
getRobot(s.getRobotID()).moveToLocation(s.getTargetLoc());
}
override public function visitNodeBirthSignal(s:NodeBirthSignal):* {
var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
encampment.setLocation(s.getLocation());
neutralEncampments[s.getLocation()] = encampment;
}
override public function visitResearchChangeSignal(s:ResearchChangeSignal):* {
progressA = s.getProgress(Team.A);
progressB = s.getProgress(Team.B);
}
override public function visitSpawnSignal(s:SpawnSignal):* {
var robot:DrawRobot = new DrawRobot(s.getRobotID(), s.getRobotType(), s.getTeam());
robot.setLocation(s.getLocation());
groundRobots[s.getRobotID()] = robot;
if (s.getRobotType() == RobotType.HQ) {
if (s.getTeam() == Team.A) hqA = robot.clone() as DrawRobot;
if (s.getTeam() == Team.B) hqB = robot.clone() as DrawRobot;
}
}
}
}
|
package battlecode.client.viewer.render {
import battlecode.common.MapLocation;
import battlecode.common.ResearchType;
import battlecode.common.RobotType;
import battlecode.common.Team;
import battlecode.serial.RoundDelta;
import battlecode.serial.RoundStats;
import battlecode.world.GameMap;
import battlecode.world.signals.*;
public class DrawState extends DefaultSignalHandler {
// state
private var mines:Array; // Team[][]
private var neutralEncampments:Object;
private var encampments:Object;
private var groundRobots:Object;
private var hqA:DrawRobot;
private var hqB:DrawRobot;
// stats
private var aPoints:Number;
private var bPoints:Number;
private var aFlux:Number;
private var bFlux:Number;
private var aGatheredPoints:Number;
private var bGatheredPoints:Number;
private var roundNum:uint;
private var progressA:Array;
private var progressB:Array;
// immutables
private var map:GameMap;
private var origin:MapLocation;
public function DrawState(map:GameMap) {
neutralEncampments = new Object();
encampments = new Object();
groundRobots = new Object();
mines = new Array();
for (var i:int = 0; i < map.getWidth(); i++) {
mines[i] = new Array();
for (var j:int = 0; j < map.getHeight(); j++) {
mines[i][j] = null;
}
}
aPoints = 0;
bPoints = 0;
aFlux = 0;
bFlux = 0;
aGatheredPoints = 0;
bGatheredPoints = 0;
roundNum = 1;
progressA = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
progressB = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
this.map = map;
this.origin = map.getOrigin();
}
///////////////////////////////////////////////////////
///////////////// PROPERTY GETTERS ////////////////////
///////////////////////////////////////////////////////
public function getMines():Array {
return mines;
}
public function getNeutralEncampments():Object {
return neutralEncampments;
}
public function getEncampments():Object {
return encampments
}
public function getGroundRobots():Object {
return groundRobots;
}
public function getHQ(team:String):DrawRobot {
return team == Team.A ? hqA : hqB;
}
public function getPoints(team:String):uint {
return (team == Team.A) ? aPoints : bPoints;
}
public function getFlux(team:String):uint {
return (team == Team.A) ? aFlux : bFlux;
}
public function getResearchProgress(team:String):Array {
return team == Team.A ? progressA : progressB;
}
///////////////////////////////////////////////////////
/////////////////// CORE FUNCTIONS ////////////////////
///////////////////////////////////////////////////////
private function copyStateFrom(state:DrawState):void {
var a:*;
mines = new Array();
for (var i:int = 0; i < map.getWidth(); i++) {
mines[i] = new Array();
for (var j:int = 0; j < map.getHeight(); j++) {
mines[i][j] = state.mines[i][j];
}
}
neutralEncampments = new Object();
for (a in state.neutralEncampments) {
neutralEncampments[a] = state.neutralEncampments[a].clone();
}
encampments = new Object();
for (a in state.encampments) {
encampments[a] = state.encampments[a].clone();
}
groundRobots = new Object();
for (a in state.groundRobots) {
groundRobots[a] = state.groundRobots[a].clone();
}
hqA = state.hqA ? state.hqA.clone() as DrawRobot : null;
hqB = state.hqB ? state.hqB.clone() as DrawRobot : null;
progressA = state.progressA.concat();
progressB = state.progressB.concat();
roundNum = state.roundNum;
}
public function clone():DrawState {
var state:DrawState = new DrawState(map);
state.copyStateFrom(this);
return state;
}
public function applyDelta(delta:RoundDelta):void {
updateRound();
for each (var signal:Signal in delta.getSignals()) {
applySignal(signal);
}
processEndOfRound();
}
public function applySignal(signal:Signal):void {
if (signal != null) signal.accept(this);
}
public function applyStats(stats:RoundStats):void {
aPoints = stats.getPoints(Team.A);
bPoints = stats.getPoints(Team.B);
aGatheredPoints = stats.getGatheredPoints(Team.A);
bGatheredPoints = stats.getGatheredPoints(Team.B);
}
public function updateRound():void {
var a:*, i:uint, j:uint;
var o:DrawRobot;
for (a in groundRobots) {
o = groundRobots[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete groundRobots[a];
}
}
for (a in encampments) {
o = encampments[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete encampments[a];
}
}
if (hqA) {
hqA.updateRound();
if (!hqA.isAlive()) {
if (hqA.parent) {
hqA.parent.removeChild(hqA);
}
hqA = null;
}
}
if (hqB) {
hqB.updateRound();
if (!hqB.isAlive()) {
if (hqB.parent) {
hqB.parent.removeChild(hqB);
}
hqB = null;
}
}
}
private function processEndOfRound():void {
roundNum++;
}
///////////////////////////////////////////////////////
////////////// PRIVATE HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function getRobot(id:uint):DrawRobot {
if (groundRobots[id]) return groundRobots[id] as DrawRobot;
if (encampments[id]) return encampments[id] as DrawRobot;
return null;
}
private function removeRobot(id:uint):void {
if (groundRobots[id]) delete groundRobots[id];
if (encampments[id]) delete encampments[id];
}
private function translateCoordinates(loc:MapLocation):MapLocation {
return new MapLocation(loc.getX() - origin.getX(), loc.getY() - origin.getY());
}
///////////////////////////////////////////////////////
/////////////////// SIGNAL HANDLERS ///////////////////
///////////////////////////////////////////////////////
override public function visitBroadcastSignal(s:BroadcastSignal):* {
getRobot(s.getRobotID()).broadcast();
}
override public function visitCaptureSignal(s:CaptureSignal):* {
var o:DrawRobot = neutralEncampments[s.getLocation()];
if (o) {
if (o.parent) {
o.parent.removeChild(o);
}
delete neutralEncampments[s.getLocation()];
}
var robot:DrawRobot = getRobot(s.getParentID());
robot.capture();
}
override public function visitDeathSignal(s:DeathSignal):* {
var robot:DrawRobot = getRobot(s.getRobotID());
robot.destroyUnit();
if (robot.getType() == RobotType.HQ) {
var hq:DrawRobot = robot.getTeam() == Team.A ? hqA : hqB;
hq.destroyUnit();
}
if (RobotType.isEncampment(robot.getType())) {
var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
encampment.setLocation(robot.getLocation());
neutralEncampments[robot.getLocation()] = encampment;
}
}
override public function visitEnergonChangeSignal(s:EnergonChangeSignal):* {
var robotIDs:Array = s.getRobotIDs();
var energon:Array = s.getEnergon();
for (var i:uint; i < robotIDs.length; i++) {
var robot:DrawRobot = getRobot(robotIDs[i]);
robot.setEnergon(energon[i]);
if (robot.getType() == RobotType.HQ) {
var hq:DrawRobot = robot.getTeam() == Team.A ? hqA : hqB;
hq.setEnergon(energon[i]);
}
}
}
override public function visitFluxChangeSignal(s:FluxChangeSignal):* {
aFlux = s.getFlux(Team.A);
bFlux = s.getFlux(Team.B);
}
override public function visitIndicatorStringSignal(s:IndicatorStringSignal):* {
getRobot(s.getRobotID()).setIndicatorString(s.getIndicatorString(), s.getIndex());
}
override public function visitMineSignal(s:MineSignal):* {
var loc:MapLocation = translateCoordinates(s.getLocation());
if (s.isBirth()) {
mines[loc.getX()][loc.getY()] = s.getTeam();
} else {
mines[loc.getX()][loc.getY()] = null;
}
}
override public function visitMineLayerSignal(s:MineLayerSignal):* {
var robot:DrawRobot = getRobot(s.getRobotID());
if (s.isLaying()) {
robot.layMine();
} else {
// TODO mining stopping - not enough info on the signal?
var researchProgress:Array = robot.getTeam() == Team.A ? progressA : progressB;
var hasUpgrade:Boolean = researchProgress[ResearchType.getField(ResearchType.PIXAXE)] == 1.0;
robot.diffuseMine(hasUpgrade);
}
}
override public function visitMovementSignal(s:MovementSignal):* {
getRobot(s.getRobotID()).moveToLocation(s.getTargetLoc());
}
override public function visitNodeBirthSignal(s:NodeBirthSignal):* {
var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
encampment.setLocation(s.getLocation());
neutralEncampments[s.getLocation()] = encampment;
}
override public function visitResearchChangeSignal(s:ResearchChangeSignal):* {
progressA = s.getProgress(Team.A);
progressB = s.getProgress(Team.B);
}
override public function visitSpawnSignal(s:SpawnSignal):* {
var robot:DrawRobot = new DrawRobot(s.getRobotID(), s.getRobotType(), s.getTeam());
robot.setLocation(s.getLocation());
groundRobots[s.getRobotID()] = robot;
if (s.getRobotType() == RobotType.HQ) {
if (s.getTeam() == Team.A) hqA = robot.clone() as DrawRobot;
if (s.getTeam() == Team.B) hqB = robot.clone() as DrawRobot;
}
}
}
}
|
replace neutral encampments after captured encampment has been destroyed
|
replace neutral encampments after captured encampment has been destroyed
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.